test.cc 455 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870
  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. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) {
  74. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  75. return;
  76. #else
  77. throw std::runtime_error("File not found: " + path);
  78. #endif
  79. }
  80. fs.seekg(0, std::ios_base::end);
  81. auto size = fs.tellg();
  82. fs.seekg(0);
  83. out.resize(static_cast<size_t>(size));
  84. fs.read(&out[0], static_cast<std::streamsize>(size));
  85. }
  86. void performance_test(const char *host) {
  87. Server svr;
  88. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  89. res.set_content("Benchmark Response", "text/plain");
  90. });
  91. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  92. auto se = detail::scope_exit([&] {
  93. svr.stop();
  94. listen_thread.join();
  95. ASSERT_FALSE(svr.is_running());
  96. });
  97. svr.wait_until_ready();
  98. Client cli(host, PORT);
  99. // Warm-up request to establish connection and resolve DNS
  100. auto warmup_res = cli.Get("/benchmark");
  101. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  102. // Run multiple trials and collect timings
  103. const int num_trials = 20;
  104. std::vector<int64_t> timings;
  105. timings.reserve(num_trials);
  106. for (int i = 0; i < num_trials; i++) {
  107. auto start = std::chrono::high_resolution_clock::now();
  108. auto res = cli.Get("/benchmark");
  109. auto end = std::chrono::high_resolution_clock::now();
  110. auto elapsed =
  111. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  112. .count();
  113. // Assertions after timing measurement to avoid overhead
  114. ASSERT_TRUE(res);
  115. EXPECT_EQ(StatusCode::OK_200, res->status);
  116. timings.push_back(elapsed);
  117. }
  118. // Calculate 25th percentile (lower quartile)
  119. std::sort(timings.begin(), timings.end());
  120. auto p25 = timings[num_trials / 4];
  121. // Format timings for output
  122. std::ostringstream timings_str;
  123. timings_str << "[";
  124. for (size_t i = 0; i < timings.size(); i++) {
  125. if (i > 0) timings_str << ", ";
  126. timings_str << timings[i];
  127. }
  128. timings_str << "]";
  129. // Localhost HTTP GET should be fast even in CI environments
  130. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  131. << "ms (Issue #1777). Timings: " << timings_str.str();
  132. }
  133. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  134. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  135. class UnixSocketTest : public ::testing::Test {
  136. protected:
  137. void TearDown() override { std::remove(pathname_.c_str()); }
  138. void client_GET(const std::string &addr) {
  139. httplib::Client cli{addr};
  140. cli.set_address_family(AF_UNIX);
  141. ASSERT_TRUE(cli.is_valid());
  142. const auto &result = cli.Get(pattern_);
  143. ASSERT_TRUE(result) << "error: " << result.error();
  144. const auto &resp = result.value();
  145. EXPECT_EQ(resp.status, StatusCode::OK_200);
  146. EXPECT_EQ(resp.body, content_);
  147. }
  148. const std::string pathname_{"./httplib-server.sock"};
  149. const std::string pattern_{"/hi"};
  150. const std::string content_{"Hello World!"};
  151. };
  152. TEST_F(UnixSocketTest, pathname) {
  153. httplib::Server svr;
  154. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. client_GET(pathname_);
  168. }
  169. #if defined(__linux__) || \
  170. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  171. TEST_F(UnixSocketTest, PeerPid) {
  172. httplib::Server svr;
  173. std::string remote_port_val;
  174. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  175. res.set_content(content_, "text/plain");
  176. remote_port_val = std::to_string(req.remote_port);
  177. });
  178. std::thread t{[&] {
  179. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  180. }};
  181. auto se = detail::scope_exit([&] {
  182. svr.stop();
  183. t.join();
  184. ASSERT_FALSE(svr.is_running());
  185. });
  186. svr.wait_until_ready();
  187. ASSERT_TRUE(svr.is_running());
  188. client_GET(pathname_);
  189. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  190. }
  191. #endif
  192. #ifdef __linux__
  193. TEST_F(UnixSocketTest, abstract) {
  194. constexpr char svr_path[]{"\x00httplib-server.sock"};
  195. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  196. httplib::Server svr;
  197. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  198. res.set_content(content_, "text/plain");
  199. });
  200. std::thread t{[&] {
  201. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  202. }};
  203. auto se = detail::scope_exit([&] {
  204. svr.stop();
  205. t.join();
  206. ASSERT_FALSE(svr.is_running());
  207. });
  208. svr.wait_until_ready();
  209. ASSERT_TRUE(svr.is_running());
  210. client_GET(abstract_addr);
  211. }
  212. #endif
  213. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  214. httplib::Server svr;
  215. std::string received_host_header;
  216. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  217. // Capture the Host header sent by the client
  218. auto host_iter = req.headers.find("Host");
  219. if (host_iter != req.headers.end()) {
  220. received_host_header = host_iter->second;
  221. }
  222. res.set_content(content_, "text/plain");
  223. });
  224. std::thread t{[&] {
  225. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  226. }};
  227. auto se = detail::scope_exit([&] {
  228. svr.stop();
  229. t.join();
  230. ASSERT_FALSE(svr.is_running());
  231. });
  232. svr.wait_until_ready();
  233. ASSERT_TRUE(svr.is_running());
  234. // Test that Host header is automatically set to "localhost" for Unix socket
  235. // connections
  236. httplib::Client cli{pathname_};
  237. cli.set_address_family(AF_UNIX);
  238. ASSERT_TRUE(cli.is_valid());
  239. const auto &result = cli.Get(pattern_);
  240. ASSERT_TRUE(result) << "error: " << result.error();
  241. const auto &resp = result.value();
  242. EXPECT_EQ(resp.status, StatusCode::OK_200);
  243. EXPECT_EQ(resp.body, content_);
  244. // Verify that Host header was automatically set to "localhost"
  245. EXPECT_EQ(received_host_header, "localhost");
  246. }
  247. #ifndef _WIN32
  248. TEST(SocketStream, wait_writable_UNIX) {
  249. int fds[2];
  250. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  251. const auto asSocketStream = [&](socket_t fd,
  252. std::function<bool(Stream &)> func) {
  253. return detail::process_client_socket(
  254. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  255. };
  256. asSocketStream(fds[0], [&](Stream &s0) {
  257. EXPECT_EQ(s0.socket(), fds[0]);
  258. EXPECT_TRUE(s0.wait_writable());
  259. EXPECT_EQ(0, close(fds[1]));
  260. EXPECT_FALSE(s0.wait_writable());
  261. return true;
  262. });
  263. EXPECT_EQ(0, close(fds[0]));
  264. }
  265. TEST(SocketStream, wait_writable_INET) {
  266. sockaddr_in addr;
  267. memset(&addr, 0, sizeof(addr));
  268. addr.sin_family = AF_INET;
  269. addr.sin_port = htons(PORT + 1);
  270. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  271. int disconnected_svr_sock = -1;
  272. std::thread svr{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, listen(s, 1));
  277. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  281. std::thread cli{[&] {
  282. const int s = socket(AF_INET, SOCK_STREAM, 0);
  283. ASSERT_LE(0, s);
  284. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  285. ASSERT_EQ(0, close(s));
  286. }};
  287. cli.join();
  288. svr.join();
  289. ASSERT_NE(disconnected_svr_sock, -1);
  290. const auto asSocketStream = [&](socket_t fd,
  291. std::function<bool(Stream &)> func) {
  292. return detail::process_client_socket(
  293. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  294. };
  295. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  296. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  297. EXPECT_FALSE(ss.wait_writable());
  298. return true;
  299. });
  300. ASSERT_EQ(0, close(disconnected_svr_sock));
  301. }
  302. #endif // #ifndef _WIN32
  303. TEST(ClientTest, MoveConstructible) {
  304. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  305. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  306. }
  307. TEST(ClientTest, MoveAssignable) {
  308. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  309. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  310. }
  311. #ifdef _WIN32
  312. TEST(StartupTest, WSAStartup) {
  313. WSADATA wsaData;
  314. int ret = WSAStartup(0x0002, &wsaData);
  315. ASSERT_EQ(0, ret);
  316. }
  317. #endif
  318. TEST(DecodePathTest, PercentCharacter) {
  319. EXPECT_EQ(
  320. decode_path_component(
  321. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  322. U8("descrip=Gastos áéíóúñÑ 6"));
  323. }
  324. TEST(DecodePathTest, PercentCharacterNUL) {
  325. string expected;
  326. expected.push_back('x');
  327. expected.push_back('\0');
  328. expected.push_back('x');
  329. EXPECT_EQ(decode_path_component("x%00x"), expected);
  330. }
  331. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  332. string unescapedCharacters = "-_.!~*'()";
  333. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  334. }
  335. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  336. string reservedCharacters = ";,/?:@&=+$";
  337. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  338. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  339. }
  340. TEST(ClientQueryOrder, PreserveOrder) {
  341. // This test reproduces Issue #2259: client may reorder query parameters
  342. // when sending a GET request. The expected behavior is that the client
  343. // preserves the original query string order when the caller supplied it
  344. // as part of the path.
  345. Server svr;
  346. svr.Get("/", [&](const Request &req, Response &res) {
  347. // Echo back the raw target so the test can assert ordering
  348. res.set_content(req.target, "text/plain");
  349. });
  350. std::thread t{[&] { svr.listen(HOST, PORT); }};
  351. auto se = detail::scope_exit([&] {
  352. svr.stop();
  353. t.join();
  354. ASSERT_FALSE(svr.is_running());
  355. });
  356. svr.wait_until_ready();
  357. Client cli(HOST, PORT);
  358. ASSERT_TRUE(cli.is_valid());
  359. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  360. auto res = cli.Get(original);
  361. ASSERT_TRUE(res);
  362. // Expect the echoed target to exactly match the original path (order
  363. // preserved)
  364. EXPECT_EQ(res->body, original);
  365. }
  366. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  367. string chineseCharacters = U8("中国語");
  368. string russianCharacters = U8("дом");
  369. string brazilianCharacters = U8("óculos");
  370. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  371. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  372. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  373. "%D0%B4%D0%BE%D0%BC");
  374. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  375. }
  376. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  377. string unescapedCharacters = "-_.!~*'()";
  378. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  379. }
  380. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  381. string reservedCharacters = ";,/?:@&=+$";
  382. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  383. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  384. }
  385. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  386. string chineseCharacters = U8("中国語");
  387. string russianCharacters = U8("дом");
  388. string brazilianCharacters = U8("óculos");
  389. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  390. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  391. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  392. "%D0%B4%D0%BE%D0%BC");
  393. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  394. }
  395. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  396. // Issue #2082 use case: encoding path component with ampersand
  397. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  398. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  399. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  400. }
  401. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  402. string unescapedCharacters = "-_.!~*'()";
  403. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  404. }
  405. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  406. string reservedCharacters = ";,/?:@&=+$#";
  407. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  408. }
  409. TEST(EncodeUriTest, TestUTF8Characters) {
  410. string chineseCharacters = U8("中国語");
  411. string russianCharacters = U8("дом");
  412. string brazilianCharacters = U8("óculos");
  413. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  414. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  415. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  416. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  417. }
  418. TEST(EncodeUriTest, TestCompleteUri) {
  419. string uri =
  420. "https://example.com/path/to/resource?query=value&param=test#fragment";
  421. EXPECT_EQ(
  422. httplib::encode_uri(uri),
  423. "https://example.com/path/to/resource?query=value&param=test#fragment");
  424. }
  425. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  426. string uri =
  427. "https://example.com/path with spaces/file name.html?q=hello world";
  428. EXPECT_EQ(httplib::encode_uri(uri),
  429. "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world");
  431. }
  432. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  433. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  434. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  435. }
  436. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  437. string unescapedCharacters = "-_.!~*'()";
  438. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  439. }
  440. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  441. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  442. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  443. string encodedBrazilian = "%C3%B3culos";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  445. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  446. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  447. }
  448. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  449. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  451. "Piri Tommy Villiers - on & on");
  452. }
  453. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  454. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  455. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  456. }
  457. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  458. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  459. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  460. }
  461. TEST(DecodeUriTest, TestUTF8Characters) {
  462. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  463. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  464. string encodedBrazilian = "%C3%B3culos";
  465. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  466. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  467. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  468. }
  469. TEST(DecodeUriTest, TestCompleteUri) {
  470. string encodedUri = "https://example.com/path%20with%20spaces/"
  471. "file%20name.html?q=hello%20world";
  472. EXPECT_EQ(
  473. httplib::decode_uri(encodedUri),
  474. "https://example.com/path with spaces/file name.html?q=hello world");
  475. }
  476. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  477. string original =
  478. "https://example.com/path with spaces/file name.html?q=hello world";
  479. string encoded = httplib::encode_uri(original);
  480. string decoded = httplib::decode_uri(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  484. string original = "Piri Tommy Villiers - on & on";
  485. string encoded = httplib::encode_uri_component(original);
  486. string decoded = httplib::decode_uri_component(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(TrimTests, TrimStringTests) {
  490. EXPECT_EQ("abc", detail::trim_copy("abc"));
  491. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  492. EXPECT_TRUE(detail::trim_copy("").empty());
  493. }
  494. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  495. // Simple case without quality values
  496. std::vector<std::string> result1;
  497. EXPECT_TRUE(detail::parse_accept_header(
  498. "text/html,application/json,text/plain", result1));
  499. EXPECT_EQ(result1.size(), 3U);
  500. EXPECT_EQ(result1[0], "text/html");
  501. EXPECT_EQ(result1[1], "application/json");
  502. EXPECT_EQ(result1[2], "text/plain");
  503. // With quality values
  504. std::vector<std::string> result2;
  505. EXPECT_TRUE(detail::parse_accept_header(
  506. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  507. EXPECT_EQ(result2.size(), 3U);
  508. EXPECT_EQ(result2[0], "application/json"); // highest q value
  509. EXPECT_EQ(result2[1], "text/html");
  510. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  511. }
  512. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  513. // Mixed with and without quality values
  514. std::vector<std::string> result;
  515. EXPECT_TRUE(detail::parse_accept_header(
  516. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  517. EXPECT_EQ(result.size(), 3U);
  518. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  519. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  520. EXPECT_EQ(result[2], "application/json"); // q=0.5
  521. }
  522. TEST(ParseAcceptHeaderTest, EdgeCases) {
  523. // Empty header
  524. std::vector<std::string> empty_result;
  525. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  526. EXPECT_TRUE(empty_result.empty());
  527. // Single type
  528. std::vector<std::string> single_result;
  529. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  530. EXPECT_EQ(single_result.size(), 1U);
  531. EXPECT_EQ(single_result[0], "application/json");
  532. // Wildcard types
  533. std::vector<std::string> wildcard_result;
  534. EXPECT_TRUE(detail::parse_accept_header(
  535. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  536. EXPECT_EQ(wildcard_result.size(), 3U);
  537. EXPECT_EQ(wildcard_result[0], "application/json");
  538. EXPECT_EQ(wildcard_result[1], "text/*");
  539. EXPECT_EQ(wildcard_result[2], "*/*");
  540. }
  541. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  542. // Common browser Accept header
  543. std::vector<std::string> browser_result;
  544. EXPECT_TRUE(
  545. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  546. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  547. browser_result));
  548. EXPECT_EQ(browser_result.size(), 6U);
  549. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  550. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  551. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  552. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  553. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  554. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  555. // API client header
  556. std::vector<std::string> api_result;
  557. EXPECT_TRUE(detail::parse_accept_header(
  558. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  559. api_result));
  560. EXPECT_EQ(api_result.size(), 3U);
  561. EXPECT_EQ(api_result[0], "application/json");
  562. EXPECT_EQ(api_result[1], "application/xml");
  563. EXPECT_EQ(api_result[2], "text/plain");
  564. }
  565. TEST(ParseAcceptHeaderTest, SpecialCases) {
  566. // Quality value with 3 decimal places
  567. std::vector<std::string> decimal_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  570. EXPECT_EQ(decimal_result.size(), 2U);
  571. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  572. EXPECT_EQ(decimal_result[1], "text/html");
  573. // Zero quality (should still be included but with lowest priority)
  574. std::vector<std::string> zero_q_result;
  575. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  576. zero_q_result));
  577. EXPECT_EQ(zero_q_result.size(), 2U);
  578. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  579. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  580. // No spaces around commas
  581. std::vector<std::string> no_space_result;
  582. EXPECT_TRUE(detail::parse_accept_header(
  583. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  584. no_space_result));
  585. EXPECT_EQ(no_space_result.size(), 3U);
  586. EXPECT_EQ(no_space_result[0], "text/html");
  587. EXPECT_EQ(no_space_result[1], "application/json");
  588. EXPECT_EQ(no_space_result[2], "text/plain");
  589. }
  590. TEST(ParseAcceptHeaderTest, InvalidCases) {
  591. std::vector<std::string> result;
  592. // Invalid quality value (> 1.0)
  593. EXPECT_FALSE(
  594. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  595. // Invalid quality value (< 0.0)
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  598. // Invalid quality value (not a number)
  599. EXPECT_FALSE(detail::parse_accept_header(
  600. "text/html;q=invalid,application/json", result));
  601. // Empty quality value
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=,application/json", result));
  604. // Invalid media type format (no slash and not wildcard)
  605. EXPECT_FALSE(
  606. detail::parse_accept_header("invalidtype,application/json", result));
  607. // Empty media type
  608. result.clear();
  609. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  610. // Only commas
  611. result.clear();
  612. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  613. // Valid cases should still work
  614. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "*/*");
  617. EXPECT_TRUE(detail::parse_accept_header("*", result));
  618. EXPECT_EQ(result.size(), 1U);
  619. EXPECT_EQ(result[0], "*");
  620. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "text/*");
  623. }
  624. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  625. Server svr;
  626. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  627. EXPECT_EQ(req.accept_content_types.size(), 3U);
  628. EXPECT_EQ(req.accept_content_types[0], "application/json");
  629. EXPECT_EQ(req.accept_content_types[1], "text/html");
  630. EXPECT_EQ(req.accept_content_types[2], "*/*");
  631. res.set_content("ok", "text/plain");
  632. });
  633. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  634. EXPECT_TRUE(false);
  635. res.set_content("bad request", "text/plain");
  636. });
  637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  638. auto se = detail::scope_exit([&] {
  639. svr.stop();
  640. listen_thread.join();
  641. ASSERT_FALSE(svr.is_running());
  642. });
  643. svr.wait_until_ready();
  644. Client cli("localhost", PORT);
  645. {
  646. auto res =
  647. cli.Get("/accept_ok",
  648. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::OK_200, res->status);
  651. }
  652. {
  653. auto res = cli.Get("/accept_bad_request",
  654. {{"Accept", "text/html;q=abc,application/json"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  657. }
  658. }
  659. TEST(DivideTest, DivideStringTests) {
  660. auto divide = [](const std::string &str, char d) {
  661. std::string lhs;
  662. std::string rhs;
  663. detail::divide(str, d,
  664. [&](const char *lhs_data, std::size_t lhs_size,
  665. const char *rhs_data, std::size_t rhs_size) {
  666. lhs.assign(lhs_data, lhs_size);
  667. rhs.assign(rhs_data, rhs_size);
  668. });
  669. return std::make_pair(std::move(lhs), std::move(rhs));
  670. };
  671. {
  672. const auto res = divide("", '=');
  673. EXPECT_EQ(res.first, "");
  674. EXPECT_EQ(res.second, "");
  675. }
  676. {
  677. const auto res = divide("=", '=');
  678. EXPECT_EQ(res.first, "");
  679. EXPECT_EQ(res.second, "");
  680. }
  681. {
  682. const auto res = divide(" ", '=');
  683. EXPECT_EQ(res.first, " ");
  684. EXPECT_EQ(res.second, "");
  685. }
  686. {
  687. const auto res = divide("a", '=');
  688. EXPECT_EQ(res.first, "a");
  689. EXPECT_EQ(res.second, "");
  690. }
  691. {
  692. const auto res = divide("a=", '=');
  693. EXPECT_EQ(res.first, "a");
  694. EXPECT_EQ(res.second, "");
  695. }
  696. {
  697. const auto res = divide("=b", '=');
  698. EXPECT_EQ(res.first, "");
  699. EXPECT_EQ(res.second, "b");
  700. }
  701. {
  702. const auto res = divide("a=b", '=');
  703. EXPECT_EQ(res.first, "a");
  704. EXPECT_EQ(res.second, "b");
  705. }
  706. {
  707. const auto res = divide("a=b=", '=');
  708. EXPECT_EQ(res.first, "a");
  709. EXPECT_EQ(res.second, "b=");
  710. }
  711. {
  712. const auto res = divide("a=b=c", '=');
  713. EXPECT_EQ(res.first, "a");
  714. EXPECT_EQ(res.second, "b=c");
  715. }
  716. }
  717. TEST(SplitTest, ParseQueryString) {
  718. string s = "key1=val1&key2=val2&key3=val3";
  719. Params dic;
  720. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  721. [&](const char *b, const char *e) {
  722. string key, val;
  723. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  724. if (key.empty()) {
  725. key.assign(b2, e2);
  726. } else {
  727. val.assign(b2, e2);
  728. }
  729. });
  730. dic.emplace(key, val);
  731. });
  732. EXPECT_EQ("val1", dic.find("key1")->second);
  733. EXPECT_EQ("val2", dic.find("key2")->second);
  734. EXPECT_EQ("val3", dic.find("key3")->second);
  735. }
  736. TEST(SplitTest, ParseInvalidQueryTests) {
  737. {
  738. string s = " ";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. {
  744. string s = " = =";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. }
  750. TEST(ParseQueryTest, ParseQueryString) {
  751. {
  752. std::string s = "key1=val1&key2=val2&key3=val3";
  753. Params dic;
  754. detail::parse_query_text(s, dic);
  755. EXPECT_EQ("val1", dic.find("key1")->second);
  756. EXPECT_EQ("val2", dic.find("key2")->second);
  757. EXPECT_EQ("val3", dic.find("key3")->second);
  758. }
  759. {
  760. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  761. Params dic;
  762. detail::parse_query_text(s, dic);
  763. EXPECT_EQ("", dic.find("key1")->second);
  764. EXPECT_EQ("val1", dic.find("key2")->second);
  765. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  766. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  767. }
  768. }
  769. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  770. Params dic;
  771. EXPECT_EQ(detail::params_to_query_str(dic), "");
  772. dic.emplace("key1", "val1");
  773. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  774. dic.emplace("key2", "val2");
  775. dic.emplace("key3", "val3");
  776. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  777. }
  778. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  779. string content_type = "multipart/form-data; boundary=something";
  780. string boundary;
  781. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  782. EXPECT_TRUE(ret);
  783. EXPECT_EQ(boundary, "something");
  784. }
  785. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  786. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  787. string boundary;
  788. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  789. EXPECT_TRUE(ret);
  790. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  791. }
  792. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  793. string content_type =
  794. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  795. string boundary;
  796. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  797. EXPECT_TRUE(ret);
  798. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  799. }
  800. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  801. string content_type =
  802. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  803. string boundary;
  804. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  805. EXPECT_TRUE(ret);
  806. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  807. }
  808. TEST(GetHeaderValueTest, DefaultValue) {
  809. Headers headers = {{"Dummy", "Dummy"}};
  810. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  811. EXPECT_STREQ("text/plain", val);
  812. }
  813. TEST(GetHeaderValueTest, DefaultValueInt) {
  814. Headers headers = {{"Dummy", "Dummy"}};
  815. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  816. EXPECT_EQ(100ull, val);
  817. }
  818. TEST(GetHeaderValueTest, RegularValue) {
  819. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  820. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  821. EXPECT_STREQ("text/html", val);
  822. }
  823. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  824. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  826. EXPECT_STREQ("text/html", val);
  827. }
  828. TEST(GetHeaderValueTest, SetContent) {
  829. Response res;
  830. res.set_content("html", "text/html");
  831. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  832. res.set_content("text", "text/plain");
  833. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  834. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  835. }
  836. TEST(GetHeaderValueTest, RegularValueInt) {
  837. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  839. EXPECT_EQ(100ull, val);
  840. }
  841. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  842. Headers headers = {{"Content-Length", "x"}};
  843. auto is_invalid_value = false;
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  845. is_invalid_value);
  846. EXPECT_EQ(0ull, val);
  847. EXPECT_TRUE(is_invalid_value);
  848. }
  849. TEST(GetHeaderValueTest, Range) {
  850. {
  851. Headers headers = {make_range_header({{1, -1}})};
  852. auto val = detail::get_header_value(headers, "Range", 0, 0);
  853. EXPECT_STREQ("bytes=1-", val);
  854. }
  855. {
  856. Headers headers = {make_range_header({{-1, 1}})};
  857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  858. EXPECT_STREQ("bytes=-1", val);
  859. }
  860. {
  861. Headers headers = {make_range_header({{1, 10}})};
  862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  863. EXPECT_STREQ("bytes=1-10", val);
  864. }
  865. {
  866. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  868. EXPECT_STREQ("bytes=1-10, 100-", val);
  869. }
  870. {
  871. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  873. EXPECT_STREQ("bytes=1-10, 100-200", val);
  874. }
  875. {
  876. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  878. EXPECT_STREQ("bytes=0-0, -1", val);
  879. }
  880. }
  881. TEST(ParseHeaderValueTest, Range) {
  882. {
  883. Ranges ranges;
  884. auto ret = detail::parse_range_header("bytes=1-", ranges);
  885. EXPECT_TRUE(ret);
  886. EXPECT_EQ(1u, ranges.size());
  887. EXPECT_EQ(1u, ranges[0].first);
  888. EXPECT_EQ(-1, ranges[0].second);
  889. }
  890. {
  891. Ranges ranges;
  892. auto ret = detail::parse_range_header("bytes=-1", ranges);
  893. EXPECT_TRUE(ret);
  894. EXPECT_EQ(1u, ranges.size());
  895. EXPECT_EQ(-1, ranges[0].first);
  896. EXPECT_EQ(1u, ranges[0].second);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(1u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. }
  906. {
  907. Ranges ranges;
  908. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  909. EXPECT_FALSE(ret);
  910. }
  911. {
  912. Ranges ranges;
  913. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  914. EXPECT_TRUE(ret);
  915. EXPECT_EQ(2u, ranges.size());
  916. EXPECT_EQ(1u, ranges[0].first);
  917. EXPECT_EQ(10u, ranges[0].second);
  918. EXPECT_EQ(100u, ranges[1].first);
  919. EXPECT_EQ(-1, ranges[1].second);
  920. }
  921. {
  922. Ranges ranges;
  923. auto ret =
  924. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  925. EXPECT_TRUE(ret);
  926. EXPECT_EQ(3u, ranges.size());
  927. EXPECT_EQ(1u, ranges[0].first);
  928. EXPECT_EQ(10u, ranges[0].second);
  929. EXPECT_EQ(100u, ranges[1].first);
  930. EXPECT_EQ(200u, ranges[1].second);
  931. EXPECT_EQ(300u, ranges[2].first);
  932. EXPECT_EQ(400u, ranges[2].second);
  933. }
  934. {
  935. Ranges ranges;
  936. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  949. EXPECT_TRUE(ranges.empty());
  950. }
  951. }
  952. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  953. Request req;
  954. req.set_header("Accept-Encoding", "gzip");
  955. Response res;
  956. res.set_header("Content-Type", "text/plain");
  957. auto ret = detail::encoding_type(req, res);
  958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #else
  961. EXPECT_TRUE(ret == detail::EncodingType::None);
  962. #endif
  963. }
  964. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  965. Request req;
  966. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  967. Response res;
  968. res.set_header("Content-Type", "text/plain");
  969. auto ret = detail::encoding_type(req, res);
  970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  971. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  972. #elif CPPHTTPLIB_ZLIB_SUPPORT
  973. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  974. #elif CPPHTTPLIB_ZSTD_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  976. #else
  977. EXPECT_TRUE(ret == detail::EncodingType::None);
  978. #endif
  979. }
  980. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  981. Request req;
  982. req.set_header("Accept-Encoding",
  983. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  984. Response res;
  985. res.set_header("Content-Type", "text/plain");
  986. auto ret = detail::encoding_type(req, res);
  987. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  988. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  989. #elif CPPHTTPLIB_ZLIB_SUPPORT
  990. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  991. #elif CPPHTTPLIB_ZSTD_SUPPORT
  992. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  993. #else
  994. EXPECT_TRUE(ret == detail::EncodingType::None);
  995. #endif
  996. }
  997. TEST(BufferStreamTest, read) {
  998. detail::BufferStream strm1;
  999. Stream &strm = strm1;
  1000. EXPECT_EQ(5, strm.write("hello"));
  1001. char buf[512];
  1002. EXPECT_EQ(2, strm.read(buf, 2));
  1003. EXPECT_EQ('h', buf[0]);
  1004. EXPECT_EQ('e', buf[1]);
  1005. EXPECT_EQ(2, strm.read(buf, 2));
  1006. EXPECT_EQ('l', buf[0]);
  1007. EXPECT_EQ('l', buf[1]);
  1008. EXPECT_EQ(1, strm.read(buf, 1));
  1009. EXPECT_EQ('o', buf[0]);
  1010. EXPECT_EQ(0, strm.read(buf, 1));
  1011. }
  1012. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1013. auto host = "www.httpwatch.com";
  1014. auto ip = hosted_at(host);
  1015. EXPECT_EQ("23.96.13.243", ip);
  1016. std::vector<std::string> addrs;
  1017. hosted_at(host, addrs);
  1018. EXPECT_EQ(1u, addrs.size());
  1019. }
  1020. #if 0 // It depends on each test environment...
  1021. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1022. auto host = "www.youtube.com";
  1023. std::vector<std::string> addrs;
  1024. hosted_at(host, addrs);
  1025. EXPECT_EQ(20u, addrs.size());
  1026. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1027. EXPECT_TRUE(it != addrs.end());
  1028. }
  1029. #endif
  1030. class ChunkedEncodingTest : public ::testing::Test {
  1031. protected:
  1032. ChunkedEncodingTest()
  1033. : cli_(HOST, PORT)
  1034. #ifdef CPPHTTPLIB_SSL_ENABLED
  1035. ,
  1036. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1037. #endif
  1038. {
  1039. cli_.set_connection_timeout(2);
  1040. #ifdef CPPHTTPLIB_SSL_ENABLED
  1041. cli_.enable_server_certificate_verification(false);
  1042. #endif
  1043. }
  1044. virtual void SetUp() {
  1045. read_file("./image.jpg", image_data_);
  1046. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1047. res.set_content("Hello World!", "text/plain");
  1048. });
  1049. svr_.Get(
  1050. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1051. res.set_chunked_content_provider(
  1052. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1053. size_t remaining = image_data_.size() - offset;
  1054. if (remaining == 0) {
  1055. sink.done();
  1056. } else {
  1057. constexpr size_t CHUNK_SIZE = 1024;
  1058. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1059. sink.write(&image_data_[offset], send_size);
  1060. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1061. }
  1062. return true;
  1063. });
  1064. });
  1065. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1066. svr_.wait_until_ready();
  1067. }
  1068. virtual void TearDown() {
  1069. svr_.stop();
  1070. if (!request_threads_.empty()) {
  1071. std::this_thread::sleep_for(std::chrono::seconds(1));
  1072. for (auto &t : request_threads_) {
  1073. t.join();
  1074. }
  1075. }
  1076. t_.join();
  1077. }
  1078. #ifdef CPPHTTPLIB_SSL_ENABLED
  1079. SSLClient cli_;
  1080. SSLServer svr_;
  1081. #else
  1082. Client cli_;
  1083. Server svr_;
  1084. #endif
  1085. thread t_;
  1086. std::vector<thread> request_threads_;
  1087. std::string image_data_;
  1088. };
  1089. TEST_F(ChunkedEncodingTest, NormalGet) {
  1090. auto res = cli_.Get("/chunked");
  1091. ASSERT_TRUE(res);
  1092. std::string out;
  1093. read_file("./image.jpg", out);
  1094. EXPECT_EQ(StatusCode::OK_200, res->status);
  1095. EXPECT_EQ(out, res->body);
  1096. }
  1097. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1098. std::string body;
  1099. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1100. body.append(data, data_length);
  1101. return true;
  1102. });
  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, body);
  1108. }
  1109. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1110. std::string body;
  1111. auto res = cli_.Get(
  1112. "/chunked",
  1113. [&](const Response &response) {
  1114. EXPECT_EQ(StatusCode::OK_200, response.status);
  1115. return true;
  1116. },
  1117. [&](const char *data, size_t data_length) {
  1118. body.append(data, data_length);
  1119. return true;
  1120. });
  1121. ASSERT_TRUE(res);
  1122. std::string out;
  1123. read_file("./image.jpg", out);
  1124. EXPECT_EQ(StatusCode::OK_200, res->status);
  1125. EXPECT_EQ(out, body);
  1126. }
  1127. TEST(RangeTest, FromHTTPBin_Online) {
  1128. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1129. auto host = "httpcan.org";
  1130. auto path = std::string{"/range/32"};
  1131. #else
  1132. auto host = "nghttp2.org";
  1133. auto path = std::string{"/httpbin/range/32"};
  1134. #endif
  1135. #ifdef CPPHTTPLIB_SSL_ENABLED
  1136. auto port = 443;
  1137. SSLClient cli(host, port);
  1138. #else
  1139. auto port = 80;
  1140. Client cli(host, port);
  1141. #endif
  1142. cli.set_connection_timeout(5);
  1143. {
  1144. auto res = cli.Get(path);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{1, -1}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{1, 10}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("bcdefghijk", res->body);
  1161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 31}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. Headers headers = {make_range_header({{0, -1}})};
  1172. auto res = cli.Get(path, headers);
  1173. ASSERT_TRUE(res);
  1174. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. }
  1177. {
  1178. Headers headers = {make_range_header({{0, 32}})};
  1179. auto res = cli.Get(path, headers);
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1182. }
  1183. }
  1184. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1185. auto host = "unresolvableaddress.local";
  1186. auto path = std::string{"/"};
  1187. #ifdef CPPHTTPLIB_SSL_ENABLED
  1188. auto port = 443;
  1189. SSLClient cli(host, port);
  1190. #else
  1191. auto port = 80;
  1192. Client cli(host, port);
  1193. #endif
  1194. cli.set_connection_timeout(1);
  1195. {
  1196. auto res = cli.Get(path);
  1197. ASSERT_FALSE(res);
  1198. }
  1199. std::this_thread::sleep_for(std::chrono::seconds(8));
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost) {
  1202. auto host = "-abcde.com";
  1203. #ifdef CPPHTTPLIB_SSL_ENABLED
  1204. auto port = 443;
  1205. SSLClient cli(host, port);
  1206. #else
  1207. auto port = 80;
  1208. Client cli(host, port);
  1209. #endif
  1210. cli.set_connection_timeout(std::chrono::seconds(2));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Connection, res.error());
  1214. }
  1215. TEST(ConnectionErrorTest, InvalidHost2) {
  1216. auto host = "httpcan.org/";
  1217. #ifdef CPPHTTPLIB_SSL_ENABLED
  1218. SSLClient cli(host);
  1219. #else
  1220. Client cli(host);
  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, InvalidHostCheckResultErrorToString) {
  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. stringstream s;
  1238. s << "error code: " << res.error();
  1239. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1240. }
  1241. TEST(ConnectionErrorTest, InvalidPort) {
  1242. auto host = "localhost";
  1243. auto port = 44380;
  1244. #ifdef CPPHTTPLIB_SSL_ENABLED
  1245. SSLClient cli(host, port);
  1246. #else
  1247. Client cli(host, port);
  1248. #endif
  1249. cli.set_connection_timeout(std::chrono::seconds(2));
  1250. auto res = cli.Get("/");
  1251. ASSERT_TRUE(!res);
  1252. EXPECT_TRUE(Error::Connection == res.error() ||
  1253. Error::ConnectionTimeout == res.error());
  1254. }
  1255. TEST(ConnectionErrorTest, Timeout_Online) {
  1256. auto host = "google.com";
  1257. #ifdef CPPHTTPLIB_SSL_ENABLED
  1258. auto port = 44380;
  1259. SSLClient cli(host, port);
  1260. #else
  1261. auto port = 8080;
  1262. Client cli(host, port);
  1263. #endif
  1264. cli.set_connection_timeout(std::chrono::seconds(2));
  1265. // only probe one address type so that the error reason
  1266. // correlates to the timed-out IPv4, not the unsupported
  1267. // IPv6 connection attempt
  1268. cli.set_address_family(AF_INET);
  1269. auto res = cli.Get("/");
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1272. }
  1273. TEST(CancelTest, NoCancel_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpcan.org";
  1276. auto path = std::string{"/range/32"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/32"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_SSL_ENABLED
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1290. ASSERT_TRUE(res);
  1291. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1292. EXPECT_EQ(StatusCode::OK_200, res->status);
  1293. }
  1294. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1295. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1296. auto host = "httpcan.org";
  1297. auto path = std::string{"/range/32"};
  1298. #else
  1299. auto host = "nghttp2.org";
  1300. auto path = std::string{"/httpbin/range/32"};
  1301. #endif
  1302. #ifdef CPPHTTPLIB_SSL_ENABLED
  1303. auto port = 443;
  1304. SSLClient cli(host, port);
  1305. #else
  1306. auto port = 80;
  1307. Client cli(host, port);
  1308. #endif
  1309. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1310. cli.set_connection_timeout(std::chrono::seconds(5));
  1311. ASSERT_TRUE(!res);
  1312. EXPECT_EQ(Error::Canceled, res.error());
  1313. }
  1314. TEST(CancelTest, WithCancelLargePayload_Online) {
  1315. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1316. auto host = "httpcan.org";
  1317. auto path = std::string{"/range/65536"};
  1318. #else
  1319. auto host = "nghttp2.org";
  1320. auto path = std::string{"/httpbin/range/65536"};
  1321. #endif
  1322. #ifdef CPPHTTPLIB_SSL_ENABLED
  1323. auto port = 443;
  1324. SSLClient cli(host, port);
  1325. #else
  1326. auto port = 80;
  1327. Client cli(host, port);
  1328. #endif
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. uint32_t count = 0;
  1331. auto res =
  1332. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, NoCancelPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content("Hello World!", "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return true; });
  1353. ASSERT_TRUE(res);
  1354. EXPECT_EQ("Hello World!", res->body);
  1355. EXPECT_EQ(StatusCode::OK_200, res->status);
  1356. }
  1357. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1358. Server svr;
  1359. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1360. res.set_content("Hello World!", "text/plain");
  1361. });
  1362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1363. auto se = detail::scope_exit([&] {
  1364. svr.stop();
  1365. thread.join();
  1366. ASSERT_FALSE(svr.is_running());
  1367. });
  1368. svr.wait_until_ready();
  1369. Client cli(HOST, PORT);
  1370. cli.set_connection_timeout(std::chrono::seconds(5));
  1371. auto res =
  1372. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1373. "application/json", [](uint64_t, uint64_t) { return false; });
  1374. ASSERT_TRUE(!res);
  1375. EXPECT_EQ(Error::Canceled, res.error());
  1376. }
  1377. TEST(CancelTest, WithCancelLargePayloadPost) {
  1378. Server svr;
  1379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content(LARGE_DATA, "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, NoCancelPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content("Hello World!", "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return true; });
  1414. ASSERT_TRUE(res);
  1415. EXPECT_EQ("Hello World!", res->body);
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1419. Server svr;
  1420. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1421. res.set_content("Hello World!", "text/plain");
  1422. });
  1423. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1424. auto se = detail::scope_exit([&] {
  1425. svr.stop();
  1426. thread.join();
  1427. ASSERT_FALSE(svr.is_running());
  1428. });
  1429. svr.wait_until_ready();
  1430. Client cli(HOST, PORT);
  1431. cli.set_connection_timeout(std::chrono::seconds(5));
  1432. auto res =
  1433. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1434. "application/json", [](uint64_t, uint64_t) { return false; });
  1435. ASSERT_TRUE(!res);
  1436. EXPECT_EQ(Error::Canceled, res.error());
  1437. }
  1438. TEST(CancelTest, WithCancelLargePayloadPut) {
  1439. Server svr;
  1440. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content(LARGE_DATA, "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1480. Server svr;
  1481. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1500. Server svr;
  1501. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content(LARGE_DATA, "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, NoCancelDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content("Hello World!", "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return true; });
  1536. ASSERT_TRUE(res);
  1537. EXPECT_EQ("Hello World!", res->body);
  1538. EXPECT_EQ(StatusCode::OK_200, res->status);
  1539. }
  1540. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1541. Server svr;
  1542. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1543. res.set_content("Hello World!", "text/plain");
  1544. });
  1545. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1546. auto se = detail::scope_exit([&] {
  1547. svr.stop();
  1548. thread.join();
  1549. ASSERT_FALSE(svr.is_running());
  1550. });
  1551. svr.wait_until_ready();
  1552. Client cli(HOST, PORT);
  1553. cli.set_connection_timeout(std::chrono::seconds(5));
  1554. auto res =
  1555. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1556. "application/json", [](uint64_t, uint64_t) { return false; });
  1557. ASSERT_TRUE(!res);
  1558. EXPECT_EQ(Error::Canceled, res.error());
  1559. }
  1560. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1561. Server svr;
  1562. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1563. res.set_content(LARGE_DATA, "text/plain");
  1564. });
  1565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1566. auto se = detail::scope_exit([&] {
  1567. svr.stop();
  1568. thread.join();
  1569. ASSERT_FALSE(svr.is_running());
  1570. });
  1571. svr.wait_until_ready();
  1572. Client cli(HOST, PORT);
  1573. cli.set_connection_timeout(std::chrono::seconds(5));
  1574. auto res =
  1575. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1576. "application/json", [](uint64_t, uint64_t) { return false; });
  1577. ASSERT_TRUE(!res);
  1578. EXPECT_EQ(Error::Canceled, res.error());
  1579. }
  1580. static std::string remove_whitespace(const std::string &input) {
  1581. std::string output;
  1582. output.reserve(input.size());
  1583. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1584. [](unsigned char c) { return !std::isspace(c); });
  1585. return output;
  1586. }
  1587. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1588. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1589. auto host = "httpcan.org";
  1590. auto path = std::string{"/basic-auth/hello/world"};
  1591. #else
  1592. auto host = "nghttp2.org";
  1593. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1594. #endif
  1595. #ifdef CPPHTTPLIB_SSL_ENABLED
  1596. auto port = 443;
  1597. SSLClient cli(host, port);
  1598. #else
  1599. auto port = 80;
  1600. Client cli(host, port);
  1601. #endif
  1602. {
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1606. }
  1607. {
  1608. auto res =
  1609. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1610. ASSERT_TRUE(res);
  1611. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1612. remove_whitespace(res->body));
  1613. EXPECT_EQ(StatusCode::OK_200, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("hello", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1620. remove_whitespace(res->body));
  1621. EXPECT_EQ(StatusCode::OK_200, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("hello", "bad");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. {
  1630. cli.set_basic_auth("bad", "world");
  1631. auto res = cli.Get(path);
  1632. ASSERT_TRUE(res);
  1633. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1634. }
  1635. }
  1636. #ifdef CPPHTTPLIB_SSL_ENABLED
  1637. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1638. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1639. auto host = "httpcan.org";
  1640. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1641. auto paths = std::vector<std::string>{
  1642. "/digest-auth/auth/hello/world/MD5",
  1643. "/digest-auth/auth/hello/world/SHA-256",
  1644. "/digest-auth/auth/hello/world/SHA-512",
  1645. };
  1646. #else
  1647. auto host = "nghttp2.org";
  1648. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1649. auto paths = std::vector<std::string>{
  1650. "/httpbin/digest-auth/auth/hello/world/MD5",
  1651. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1652. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1653. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1654. };
  1655. #endif
  1656. auto port = 443;
  1657. SSLClient cli(host, port);
  1658. {
  1659. auto res = cli.Get(unauth_path);
  1660. ASSERT_TRUE(res);
  1661. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1662. }
  1663. {
  1664. cli.set_digest_auth("hello", "world");
  1665. for (const auto &path : paths) {
  1666. auto res = cli.Get(path.c_str());
  1667. ASSERT_TRUE(res);
  1668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1669. std::string algo(path.substr(path.rfind('/') + 1));
  1670. EXPECT_EQ(
  1671. remove_whitespace("{\"algorithm\":\"" + algo +
  1672. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1673. remove_whitespace(res->body));
  1674. #else
  1675. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1676. remove_whitespace(res->body));
  1677. #endif
  1678. EXPECT_EQ(StatusCode::OK_200, res->status);
  1679. }
  1680. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1681. cli.set_digest_auth("hello", "bad");
  1682. for (const auto &path : paths) {
  1683. auto res = cli.Get(path.c_str());
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1686. }
  1687. #endif
  1688. }
  1689. }
  1690. #endif
  1691. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1692. auto host = "google.com";
  1693. auto another_host = "example.com";
  1694. auto wrong_ip = "0.0.0.0";
  1695. #ifdef CPPHTTPLIB_SSL_ENABLED
  1696. SSLClient cli(host);
  1697. #else
  1698. Client cli(host);
  1699. #endif
  1700. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1701. auto res = cli.Get("/");
  1702. ASSERT_TRUE(res);
  1703. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1704. }
  1705. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1706. auto host = "google.com";
  1707. auto wrong_ip = "0.0.0.0";
  1708. #ifdef CPPHTTPLIB_SSL_ENABLED
  1709. SSLClient cli(host);
  1710. #else
  1711. Client cli(host);
  1712. #endif
  1713. cli.set_hostname_addr_map({{host, wrong_ip}});
  1714. auto res = cli.Get("/");
  1715. ASSERT_TRUE(!res);
  1716. EXPECT_EQ(Error::Connection, res.error());
  1717. }
  1718. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1719. auto host = "nghttp2.org";
  1720. #ifdef CPPHTTPLIB_SSL_ENABLED
  1721. SSLClient cli(host);
  1722. #else
  1723. Client cli(host);
  1724. #endif
  1725. cli.set_follow_location(true);
  1726. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(StatusCode::OK_200, res->status);
  1729. }
  1730. TEST(RedirectTest, Redirect_Online) {
  1731. auto host = "nghttp2.org";
  1732. #ifdef CPPHTTPLIB_SSL_ENABLED
  1733. SSLClient cli(host);
  1734. #else
  1735. Client cli(host);
  1736. #endif
  1737. cli.set_follow_location(true);
  1738. auto res = cli.Get("/httpbin/redirect/3");
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(StatusCode::OK_200, res->status);
  1741. }
  1742. TEST(RelativeRedirectTest, Redirect_Online) {
  1743. auto host = "nghttp2.org";
  1744. #ifdef CPPHTTPLIB_SSL_ENABLED
  1745. SSLClient cli(host);
  1746. #else
  1747. Client cli(host);
  1748. #endif
  1749. cli.set_follow_location(true);
  1750. auto res = cli.Get("/httpbin/relative-redirect/3");
  1751. ASSERT_TRUE(res);
  1752. EXPECT_EQ(StatusCode::OK_200, res->status);
  1753. }
  1754. TEST(TooManyRedirectTest, Redirect_Online) {
  1755. auto host = "nghttp2.org";
  1756. #ifdef CPPHTTPLIB_SSL_ENABLED
  1757. SSLClient cli(host);
  1758. #else
  1759. Client cli(host);
  1760. #endif
  1761. cli.set_follow_location(true);
  1762. auto res = cli.Get("/httpbin/redirect/21");
  1763. ASSERT_TRUE(!res);
  1764. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1765. }
  1766. #ifdef CPPHTTPLIB_SSL_ENABLED
  1767. TEST(YahooRedirectTest, Redirect_Online) {
  1768. Client cli("yahoo.com");
  1769. auto res = cli.Get("/");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1772. cli.set_follow_location(true);
  1773. res = cli.Get("/");
  1774. ASSERT_TRUE(res);
  1775. EXPECT_EQ(StatusCode::OK_200, res->status);
  1776. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1777. }
  1778. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1779. #define REDIR_HOST "httpbingo.org"
  1780. #define REDIR_PATH "/redirect-to"
  1781. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1782. SSLClient cli(REDIR_HOST);
  1783. cli.set_follow_location(true);
  1784. auto res =
  1785. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(StatusCode::OK_200, res->status);
  1788. }
  1789. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1790. SSLClient cli(REDIR_HOST);
  1791. cli.set_follow_location(true);
  1792. Params params;
  1793. params.emplace("url", "http://example.com");
  1794. params.emplace("status_code", "302");
  1795. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1796. ASSERT_TRUE(res);
  1797. EXPECT_EQ(StatusCode::OK_200, res->status);
  1798. }
  1799. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1800. SSLClient cli(REDIR_HOST);
  1801. cli.set_follow_location(true);
  1802. Params params;
  1803. params.emplace("url", "http://example.com");
  1804. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1805. ASSERT_TRUE(res);
  1806. EXPECT_EQ(StatusCode::OK_200, res->status);
  1807. }
  1808. TEST(UrlWithSpace, Redirect_Online) {
  1809. SSLClient cli("edge.forgecdn.net");
  1810. cli.set_follow_location(true);
  1811. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1812. ASSERT_TRUE(res);
  1813. EXPECT_EQ(StatusCode::OK_200, res->status);
  1814. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1815. }
  1816. #endif
  1817. #if !defined(_WIN32) && !defined(_WIN64)
  1818. TEST(ReceiveSignals, Signal) {
  1819. auto setupSignalHandlers = []() {
  1820. struct sigaction act;
  1821. sigemptyset(&act.sa_mask);
  1822. act.sa_flags = SA_SIGINFO;
  1823. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1824. switch (sig) {
  1825. case SIGINT:
  1826. default: break;
  1827. }
  1828. };
  1829. ::sigaction(SIGINT, &act, nullptr);
  1830. };
  1831. Server svr;
  1832. int port = 0;
  1833. auto thread = std::thread([&]() {
  1834. setupSignalHandlers();
  1835. port = svr.bind_to_any_port(HOST);
  1836. svr.listen_after_bind();
  1837. });
  1838. auto se = detail::scope_exit([&] {
  1839. svr.stop();
  1840. thread.join();
  1841. ASSERT_FALSE(svr.is_running());
  1842. });
  1843. svr.wait_until_ready();
  1844. ASSERT_TRUE(svr.is_running());
  1845. pthread_kill(thread.native_handle(), SIGINT);
  1846. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1847. ASSERT_TRUE(svr.is_running());
  1848. }
  1849. #endif
  1850. TEST(RedirectToDifferentPort, Redirect) {
  1851. Server svr1;
  1852. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1853. res.set_content("Hello World!", "text/plain");
  1854. });
  1855. int svr1_port = 0;
  1856. auto thread1 = std::thread([&]() {
  1857. svr1_port = svr1.bind_to_any_port(HOST);
  1858. svr1.listen_after_bind();
  1859. });
  1860. Server svr2;
  1861. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1862. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1863. });
  1864. int svr2_port = 0;
  1865. auto thread2 = std::thread([&]() {
  1866. svr2_port = svr2.bind_to_any_port(HOST);
  1867. svr2.listen_after_bind();
  1868. });
  1869. auto se = detail::scope_exit([&] {
  1870. svr2.stop();
  1871. thread2.join();
  1872. svr1.stop();
  1873. thread1.join();
  1874. ASSERT_FALSE(svr2.is_running());
  1875. ASSERT_FALSE(svr1.is_running());
  1876. });
  1877. svr1.wait_until_ready();
  1878. svr2.wait_until_ready();
  1879. Client cli("localhost", svr2_port);
  1880. cli.set_follow_location(true);
  1881. auto res = cli.Get("/2");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(StatusCode::OK_200, res->status);
  1884. EXPECT_EQ("Hello World!", res->body);
  1885. }
  1886. TEST(RedirectFromPageWithContent, Redirect) {
  1887. Server svr;
  1888. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1889. res.set_content("___", "text/plain");
  1890. res.set_redirect("/2");
  1891. });
  1892. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1893. res.set_content("Hello World!", "text/plain");
  1894. });
  1895. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1896. auto se = detail::scope_exit([&] {
  1897. svr.stop();
  1898. th.join();
  1899. ASSERT_FALSE(svr.is_running());
  1900. });
  1901. svr.wait_until_ready();
  1902. {
  1903. Client cli("localhost", PORT);
  1904. cli.set_follow_location(true);
  1905. std::string body;
  1906. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1907. body.append(data, data_length);
  1908. return true;
  1909. });
  1910. ASSERT_TRUE(res);
  1911. EXPECT_EQ(StatusCode::OK_200, res->status);
  1912. EXPECT_EQ("Hello World!", body);
  1913. }
  1914. {
  1915. Client cli("localhost", PORT);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::Found_302, res->status);
  1923. EXPECT_EQ("___", body);
  1924. }
  1925. }
  1926. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1927. Server svr;
  1928. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1929. res.set_content("___", "text/plain");
  1930. // res.set_redirect("/2");
  1931. res.set_redirect("http://[::1]:1234/2");
  1932. });
  1933. svr.Get("/2", [&](const Request &req, Response &res) {
  1934. auto host_header = req.headers.find("Host");
  1935. ASSERT_TRUE(host_header != req.headers.end());
  1936. EXPECT_EQ("[::1]:1234", host_header->second);
  1937. res.set_content("Hello World!", "text/plain");
  1938. });
  1939. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1940. auto se = detail::scope_exit([&] {
  1941. svr.stop();
  1942. th.join();
  1943. ASSERT_FALSE(svr.is_running());
  1944. });
  1945. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1946. // actually starts anything, so the condition !svr.is_running() will
  1947. // always remain true, and the loop never stops.
  1948. // This basically counts how many milliseconds have passed since the
  1949. // call to svr.listen(), and if after 5 seconds nothing started yet
  1950. // aborts the test.
  1951. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1952. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1953. ASSERT_LT(milliseconds, 5000U);
  1954. }
  1955. {
  1956. Client cli("http://[::1]:1234");
  1957. cli.set_follow_location(true);
  1958. std::string body;
  1959. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1960. body.append(data, data_length);
  1961. return true;
  1962. });
  1963. ASSERT_TRUE(res);
  1964. EXPECT_EQ(StatusCode::OK_200, res->status);
  1965. EXPECT_EQ("Hello World!", body);
  1966. }
  1967. {
  1968. Client cli("http://[::1]:1234");
  1969. std::string body;
  1970. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1971. body.append(data, data_length);
  1972. return true;
  1973. });
  1974. ASSERT_TRUE(res);
  1975. EXPECT_EQ(StatusCode::Found_302, res->status);
  1976. EXPECT_EQ("___", body);
  1977. }
  1978. }
  1979. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1980. Server svr;
  1981. svr.Get("/foo", [](const Request &req, Response &res) {
  1982. auto a = req.params.find("a");
  1983. if (a != req.params.end()) {
  1984. res.set_content((*a).second, "text/plain");
  1985. res.status = StatusCode::OK_200;
  1986. } else {
  1987. res.status = StatusCode::BadRequest_400;
  1988. }
  1989. });
  1990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. {
  1998. Client cli(HOST, PORT);
  1999. cli.set_path_encode(false);
  2000. auto res = cli.Get("/foo?a=explicitly+encoded");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(StatusCode::OK_200, res->status);
  2003. // This expects it back with a space, as the `+` won't have been
  2004. // url-encoded, and server-side the params get decoded turning `+`
  2005. // into spaces.
  2006. EXPECT_EQ("explicitly encoded", res->body);
  2007. }
  2008. }
  2009. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2010. Server svr;
  2011. svr.Get("/", [](const Request &req, Response &) {
  2012. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2013. });
  2014. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2015. auto se = detail::scope_exit([&] {
  2016. svr.stop();
  2017. thread.join();
  2018. ASSERT_FALSE(svr.is_running());
  2019. });
  2020. svr.wait_until_ready();
  2021. {
  2022. Client cli(HOST, PORT);
  2023. cli.set_path_encode(false);
  2024. auto res = cli.Get("/?something=%0A");
  2025. ASSERT_TRUE(res);
  2026. EXPECT_EQ(StatusCode::OK_200, res->status);
  2027. }
  2028. }
  2029. TEST(BindServerTest, DISABLED_BindDualStack) {
  2030. Server svr;
  2031. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2032. res.set_content("Hello World!", "text/plain");
  2033. });
  2034. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2035. auto se = detail::scope_exit([&] {
  2036. svr.stop();
  2037. thread.join();
  2038. ASSERT_FALSE(svr.is_running());
  2039. });
  2040. svr.wait_until_ready();
  2041. {
  2042. Client cli("127.0.0.1", PORT);
  2043. auto res = cli.Get("/1");
  2044. ASSERT_TRUE(res);
  2045. EXPECT_EQ(StatusCode::OK_200, res->status);
  2046. EXPECT_EQ("Hello World!", res->body);
  2047. }
  2048. {
  2049. Client cli("::1", PORT);
  2050. auto res = cli.Get("/1");
  2051. ASSERT_TRUE(res);
  2052. EXPECT_EQ(StatusCode::OK_200, res->status);
  2053. EXPECT_EQ("Hello World!", res->body);
  2054. }
  2055. }
  2056. TEST(BindServerTest, BindAndListenSeparately) {
  2057. Server svr;
  2058. int port = svr.bind_to_any_port("0.0.0.0");
  2059. ASSERT_TRUE(svr.is_valid());
  2060. ASSERT_TRUE(port > 0);
  2061. svr.stop();
  2062. }
  2063. #ifdef CPPHTTPLIB_SSL_ENABLED
  2064. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2066. CLIENT_CA_CERT_DIR);
  2067. int port = svr.bind_to_any_port("0.0.0.0");
  2068. ASSERT_TRUE(svr.is_valid());
  2069. ASSERT_TRUE(port > 0);
  2070. svr.stop();
  2071. }
  2072. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2073. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2074. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2075. int port = svr.bind_to_any_port("0.0.0.0");
  2076. ASSERT_TRUE(svr.is_valid());
  2077. ASSERT_TRUE(port > 0);
  2078. svr.stop();
  2079. }
  2080. TEST(BindServerTest, UpdateCertsPem) {
  2081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2082. int port = svr.bind_to_any_port("0.0.0.0");
  2083. ASSERT_TRUE(svr.is_valid());
  2084. ASSERT_TRUE(port > 0);
  2085. // Read PEM files
  2086. std::string cert_pem, key_pem, ca_pem;
  2087. read_file(SERVER_CERT_FILE, cert_pem);
  2088. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2089. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2090. // Update server certificates using PEM API
  2091. ASSERT_TRUE(
  2092. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2093. ASSERT_TRUE(svr.is_valid());
  2094. svr.stop();
  2095. }
  2096. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2097. // Start server with client CA (enables client auth)
  2098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2099. ASSERT_TRUE(svr.is_valid());
  2100. bool handler_called = false;
  2101. svr.Get("/test", [&](const Request &req, Response &res) {
  2102. handler_called = true;
  2103. // Verify client certificate is present
  2104. auto cert = req.peer_cert();
  2105. EXPECT_TRUE(static_cast<bool>(cert));
  2106. res.set_content("ok", "text/plain");
  2107. });
  2108. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. t.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. // Read PEM files
  2116. std::string cert_pem, key_pem, ca_pem;
  2117. read_file(SERVER_CERT_FILE, cert_pem);
  2118. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2119. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2120. // Update server certificates and client CA using PEM API while server running
  2121. ASSERT_TRUE(
  2122. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2123. // Connect with client certificate
  2124. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2125. cli.enable_server_certificate_verification(false);
  2126. cli.set_connection_timeout(30);
  2127. auto res = cli.Get("/test");
  2128. ASSERT_TRUE(res);
  2129. ASSERT_EQ(StatusCode::OK_200, res->status);
  2130. ASSERT_TRUE(handler_called);
  2131. EXPECT_EQ("ok", res->body);
  2132. }
  2133. #endif
  2134. TEST(ErrorHandlerTest, ContentLength) {
  2135. Server svr;
  2136. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2137. res.status = StatusCode::OK_200;
  2138. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2139. "text/html"); // <= Content-Length still 13
  2140. });
  2141. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2142. res.set_content("Hello World!\n", "text/plain");
  2143. res.status = 524;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. {
  2153. Client cli(HOST, PORT);
  2154. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::OK_200, res->status);
  2157. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2158. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2159. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2160. }
  2161. }
  2162. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2163. TEST(ExceptionTest, WithoutExceptionHandler) {
  2164. Server svr;
  2165. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2166. throw std::runtime_error("exception...");
  2167. });
  2168. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2169. throw std::runtime_error("exception\r\n...");
  2170. });
  2171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2172. auto se = detail::scope_exit([&] {
  2173. svr.stop();
  2174. listen_thread.join();
  2175. ASSERT_FALSE(svr.is_running());
  2176. });
  2177. svr.wait_until_ready();
  2178. Client cli("localhost", PORT);
  2179. {
  2180. auto res = cli.Get("/exception");
  2181. ASSERT_TRUE(res);
  2182. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2183. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2184. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2185. }
  2186. {
  2187. auto res = cli.Get("/unknown");
  2188. ASSERT_TRUE(res);
  2189. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2190. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2191. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2192. }
  2193. }
  2194. TEST(ExceptionTest, WithExceptionHandler) {
  2195. Server svr;
  2196. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2197. std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. EXPECT_EQ("abc", std::string(e.what()));
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2206. "text/html"); // <= Content-Length still 13 at this point
  2207. });
  2208. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2209. res.set_content("Hello World!\n", "text/plain");
  2210. throw std::runtime_error("abc");
  2211. });
  2212. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2213. auto se = detail::scope_exit([&] {
  2214. svr.stop();
  2215. thread.join();
  2216. ASSERT_FALSE(svr.is_running());
  2217. });
  2218. svr.wait_until_ready();
  2219. for (size_t i = 0; i < 10; i++) {
  2220. Client cli(HOST, PORT);
  2221. for (size_t j = 0; j < 100; j++) {
  2222. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2225. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2226. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2227. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2228. }
  2229. cli.set_keep_alive(true);
  2230. for (size_t j = 0; j < 100; j++) {
  2231. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2234. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2236. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2237. }
  2238. }
  2239. }
  2240. TEST(ExceptionTest, AndErrorHandler) {
  2241. Server svr;
  2242. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2243. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2244. });
  2245. svr.set_exception_handler(
  2246. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2247. EXPECT_FALSE(ep == nullptr);
  2248. try {
  2249. std::rethrow_exception(ep);
  2250. } catch (std::exception &e) {
  2251. res.set_content(e.what(), "text/html");
  2252. } catch (...) {}
  2253. res.status = StatusCode::InternalServerError_500;
  2254. });
  2255. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2256. throw std::runtime_error("EXCEPTION");
  2257. });
  2258. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2259. res.set_content("ERROR", "text/html");
  2260. res.status = StatusCode::InternalServerError_500;
  2261. });
  2262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2263. auto se = detail::scope_exit([&] {
  2264. svr.stop();
  2265. thread.join();
  2266. ASSERT_FALSE(svr.is_running());
  2267. });
  2268. svr.wait_until_ready();
  2269. Client cli(HOST, PORT);
  2270. {
  2271. auto res = cli.Get("/exception");
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2274. EXPECT_EQ("EXCEPTION", res->body);
  2275. }
  2276. {
  2277. auto res = cli.Get("/error");
  2278. ASSERT_TRUE(res);
  2279. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2280. EXPECT_EQ("ERROR", res->body);
  2281. }
  2282. {
  2283. auto res = cli.Get("/invalid");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2286. EXPECT_EQ("NOT_FOUND", res->body);
  2287. }
  2288. }
  2289. #endif
  2290. TEST(NoContentTest, ContentLength) {
  2291. Server svr;
  2292. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2293. res.status = StatusCode::NoContent_204;
  2294. });
  2295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. {
  2303. Client cli(HOST, PORT);
  2304. auto res = cli.Get("/hi");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2307. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2308. }
  2309. }
  2310. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2313. ASSERT_TRUE(svr.is_valid());
  2314. #else
  2315. Server svr;
  2316. #endif
  2317. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2318. if (req.path == "/routing_handler") {
  2319. res.set_header("PRE_ROUTING", "on");
  2320. res.set_content("Routing Handler", "text/plain");
  2321. return httplib::Server::HandlerResponse::Handled;
  2322. }
  2323. return httplib::Server::HandlerResponse::Unhandled;
  2324. });
  2325. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2326. res.set_content("Error", "text/html");
  2327. });
  2328. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2329. if (req.path == "/routing_handler") {
  2330. res.set_header("POST_ROUTING", "on");
  2331. }
  2332. });
  2333. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2334. res.set_content("Hello World!\n", "text/plain");
  2335. });
  2336. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2337. auto se = detail::scope_exit([&] {
  2338. svr.stop();
  2339. thread.join();
  2340. ASSERT_FALSE(svr.is_running());
  2341. });
  2342. svr.wait_until_ready();
  2343. {
  2344. #ifdef CPPHTTPLIB_SSL_ENABLED
  2345. SSLClient cli(HOST, PORT);
  2346. cli.enable_server_certificate_verification(false);
  2347. #else
  2348. Client cli(HOST, PORT);
  2349. #endif
  2350. auto res = cli.Get("/routing_handler");
  2351. ASSERT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. EXPECT_EQ("Routing Handler", res->body);
  2354. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2355. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2356. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2357. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2358. }
  2359. {
  2360. #ifdef CPPHTTPLIB_SSL_ENABLED
  2361. SSLClient cli(HOST, PORT);
  2362. cli.enable_server_certificate_verification(false);
  2363. #else
  2364. Client cli(HOST, PORT);
  2365. #endif
  2366. auto res = cli.Get("/hi");
  2367. ASSERT_TRUE(res);
  2368. EXPECT_EQ(StatusCode::OK_200, res->status);
  2369. EXPECT_EQ("Hello World!\n", res->body);
  2370. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2371. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2372. }
  2373. {
  2374. #ifdef CPPHTTPLIB_SSL_ENABLED
  2375. SSLClient cli(HOST, PORT);
  2376. cli.enable_server_certificate_verification(false);
  2377. #else
  2378. Client cli(HOST, PORT);
  2379. #endif
  2380. auto res = cli.Get("/aaa");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2383. EXPECT_EQ("Error", res->body);
  2384. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2385. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2386. }
  2387. }
  2388. TEST(RequestHandlerTest, PreRequestHandler) {
  2389. auto route_path = "/user/:user";
  2390. Server svr;
  2391. svr.Get("/hi", [](const Request &, Response &res) {
  2392. res.set_content("hi", "text/plain");
  2393. });
  2394. svr.Get(route_path, [](const Request &req, Response &res) {
  2395. res.set_content(req.path_params.at("user"), "text/plain");
  2396. });
  2397. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2398. if (req.matched_route == route_path) {
  2399. auto user = req.path_params.at("user");
  2400. if (user != "john") {
  2401. res.status = StatusCode::Forbidden_403;
  2402. res.set_content("error", "text/html");
  2403. return Server::HandlerResponse::Handled;
  2404. }
  2405. }
  2406. return Server::HandlerResponse::Unhandled;
  2407. });
  2408. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2409. auto se = detail::scope_exit([&] {
  2410. svr.stop();
  2411. thread.join();
  2412. ASSERT_FALSE(svr.is_running());
  2413. });
  2414. svr.wait_until_ready();
  2415. Client cli(HOST, PORT);
  2416. {
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. EXPECT_EQ("hi", res->body);
  2421. }
  2422. {
  2423. auto res = cli.Get("/user/john");
  2424. ASSERT_TRUE(res);
  2425. EXPECT_EQ(StatusCode::OK_200, res->status);
  2426. EXPECT_EQ("john", res->body);
  2427. }
  2428. {
  2429. auto res = cli.Get("/user/invalid-user");
  2430. ASSERT_TRUE(res);
  2431. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2432. EXPECT_EQ("error", res->body);
  2433. }
  2434. }
  2435. TEST(InvalidFormatTest, StatusCode) {
  2436. Server svr;
  2437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2438. res.set_content("Hello World!\n", "text/plain");
  2439. res.status = 9999; // Status should be a three-digit code...
  2440. });
  2441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2442. auto se = detail::scope_exit([&] {
  2443. svr.stop();
  2444. thread.join();
  2445. ASSERT_FALSE(svr.is_running());
  2446. });
  2447. svr.wait_until_ready();
  2448. {
  2449. Client cli(HOST, PORT);
  2450. auto res = cli.Get("/hi");
  2451. ASSERT_FALSE(res);
  2452. }
  2453. }
  2454. TEST(URLFragmentTest, WithFragment) {
  2455. Server svr;
  2456. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2457. EXPECT_TRUE(req.target == "/hi");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. {
  2467. Client cli(HOST, PORT);
  2468. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2469. EXPECT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. res = cli.Get("/hi%23key1=val1=key2=val2");
  2472. EXPECT_TRUE(res);
  2473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2474. }
  2475. }
  2476. TEST(HeaderWriter, SetHeaderWriter) {
  2477. Server svr;
  2478. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2479. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2480. return detail::write_headers(strm, hdrs);
  2481. });
  2482. svr.Get("/hi", [](const Request &req, Response &res) {
  2483. auto it = req.headers.find("CustomClientHeader");
  2484. EXPECT_TRUE(it != req.headers.end());
  2485. EXPECT_EQ(it->second, "CustomClientValue");
  2486. res.set_content("Hello World!\n", "text/plain");
  2487. });
  2488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2489. auto se = detail::scope_exit([&] {
  2490. svr.stop();
  2491. thread.join();
  2492. ASSERT_FALSE(svr.is_running());
  2493. });
  2494. svr.wait_until_ready();
  2495. {
  2496. Client cli(HOST, PORT);
  2497. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2498. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2499. return detail::write_headers(strm, hdrs);
  2500. });
  2501. auto res = cli.Get("/hi");
  2502. EXPECT_TRUE(res);
  2503. EXPECT_EQ(StatusCode::OK_200, res->status);
  2504. auto it = res->headers.find("CustomServerHeader");
  2505. EXPECT_TRUE(it != res->headers.end());
  2506. EXPECT_EQ(it->second, "CustomServerValue");
  2507. }
  2508. }
  2509. class ServerTest : public ::testing::Test {
  2510. protected:
  2511. ServerTest()
  2512. : cli_(HOST, PORT)
  2513. #ifdef CPPHTTPLIB_SSL_ENABLED
  2514. ,
  2515. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2516. #endif
  2517. {
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. cli_.enable_server_certificate_verification(false);
  2520. #endif
  2521. }
  2522. virtual void SetUp() {
  2523. svr_.set_mount_point("/", "./www");
  2524. svr_.set_mount_point("/mount", "./www2");
  2525. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2526. svr_.Get("/hi",
  2527. [&](const Request & /*req*/, Response &res) {
  2528. res.set_content("Hello World!", "text/plain");
  2529. })
  2530. .Get("/file_content",
  2531. [&](const Request & /*req*/, Response &res) {
  2532. res.set_file_content("./www/dir/test.html");
  2533. })
  2534. .Get("/file_content_with_content_type",
  2535. [&](const Request & /*req*/, Response &res) {
  2536. res.set_file_content("./www/file", "text/plain");
  2537. })
  2538. .Get("/invalid_file_content",
  2539. [&](const Request & /*req*/, Response &res) {
  2540. res.set_file_content("./www/dir/invalid_file_path");
  2541. })
  2542. .Get("/http_response_splitting",
  2543. [&](const Request & /*req*/, Response &res) {
  2544. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2545. EXPECT_EQ(0U, res.headers.size());
  2546. EXPECT_FALSE(res.has_header("a"));
  2547. res.set_header("a", "1\nSet-Cookie: a=1");
  2548. EXPECT_EQ(0U, res.headers.size());
  2549. EXPECT_FALSE(res.has_header("a"));
  2550. res.set_header("a", "1\rSet-Cookie: a=1");
  2551. EXPECT_EQ(0U, res.headers.size());
  2552. EXPECT_FALSE(res.has_header("a"));
  2553. res.set_header("a\r\nb", "0");
  2554. EXPECT_EQ(0U, res.headers.size());
  2555. EXPECT_FALSE(res.has_header("a"));
  2556. res.set_header("a\rb", "0");
  2557. EXPECT_EQ(0U, res.headers.size());
  2558. EXPECT_FALSE(res.has_header("a"));
  2559. res.set_header("a\nb", "0");
  2560. EXPECT_EQ(0U, res.headers.size());
  2561. EXPECT_FALSE(res.has_header("a"));
  2562. res.set_redirect("1\r\nSet-Cookie: a=1");
  2563. EXPECT_EQ(0U, res.headers.size());
  2564. EXPECT_FALSE(res.has_header("Location"));
  2565. })
  2566. .Get("/slow",
  2567. [&](const Request & /*req*/, Response &res) {
  2568. std::this_thread::sleep_for(std::chrono::seconds(2));
  2569. res.set_content("slow", "text/plain");
  2570. })
  2571. #if 0
  2572. .Post("/slowpost",
  2573. [&](const Request & /*req*/, Response &res) {
  2574. std::this_thread::sleep_for(std::chrono::seconds(2));
  2575. res.set_content("slow", "text/plain");
  2576. })
  2577. #endif
  2578. .Get("/remote_addr",
  2579. [&](const Request &req, Response &res) {
  2580. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2581. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2582. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2583. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2584. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2585. #endif
  2586. res.set_content(req.remote_addr, "text/plain");
  2587. })
  2588. .Get("/local_addr",
  2589. [&](const Request &req, Response &res) {
  2590. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2591. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2593. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2594. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2595. #endif
  2596. auto local_addr = req.local_addr;
  2597. auto local_port = std::to_string(req.local_port);
  2598. res.set_content(local_addr.append(":").append(local_port),
  2599. "text/plain");
  2600. })
  2601. .Get("/endwith%",
  2602. [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. })
  2605. .Get("/a\\+\\+b",
  2606. [&](const Request &req, Response &res) {
  2607. ASSERT_TRUE(req.has_param("a +b"));
  2608. auto val = req.get_param_value("a +b");
  2609. res.set_content(val, "text/plain");
  2610. })
  2611. .Get("/", [&](const Request & /*req*/,
  2612. Response &res) { res.set_redirect("/hi"); })
  2613. .Post("/1",
  2614. [](const Request & /*req*/, Response &res) {
  2615. res.set_redirect("/2", StatusCode::SeeOther_303);
  2616. })
  2617. .Get("/2",
  2618. [](const Request & /*req*/, Response &res) {
  2619. res.set_content("redirected.", "text/plain");
  2620. res.status = StatusCode::OK_200;
  2621. })
  2622. .Post("/person",
  2623. [&](const Request &req, Response &res) {
  2624. if (req.has_param("name") && req.has_param("note")) {
  2625. persons_[req.get_param_value("name")] =
  2626. req.get_param_value("note");
  2627. } else {
  2628. res.status = StatusCode::BadRequest_400;
  2629. }
  2630. })
  2631. .Put("/person",
  2632. [&](const Request &req, Response &res) {
  2633. if (req.has_param("name") && req.has_param("note")) {
  2634. persons_[req.get_param_value("name")] =
  2635. req.get_param_value("note");
  2636. } else {
  2637. res.status = StatusCode::BadRequest_400;
  2638. }
  2639. })
  2640. .Get("/person/(.*)",
  2641. [&](const Request &req, Response &res) {
  2642. string name = req.matches[1];
  2643. if (persons_.find(name) != persons_.end()) {
  2644. auto note = persons_[name];
  2645. res.set_content(note, "text/plain");
  2646. } else {
  2647. res.status = StatusCode::NotFound_404;
  2648. }
  2649. })
  2650. .Delete("/person",
  2651. [&](const Request &req, Response &res) {
  2652. if (req.has_param("name")) {
  2653. string name = req.get_param_value("name");
  2654. if (persons_.find(name) != persons_.end()) {
  2655. persons_.erase(name);
  2656. res.set_content("DELETED", "text/plain");
  2657. } else {
  2658. res.status = StatusCode::NotFound_404;
  2659. }
  2660. } else {
  2661. res.status = StatusCode::BadRequest_400;
  2662. }
  2663. })
  2664. .Post("/x-www-form-urlencoded-json",
  2665. [&](const Request &req, Response &res) {
  2666. auto json = req.get_param_value("json");
  2667. ASSERT_EQ(JSON_DATA, json);
  2668. res.set_content(json, "appliation/json");
  2669. res.status = StatusCode::OK_200;
  2670. })
  2671. .Get("/streamed-chunked",
  2672. [&](const Request & /*req*/, Response &res) {
  2673. res.set_chunked_content_provider(
  2674. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2675. sink.os << "123";
  2676. sink.os << "456";
  2677. sink.os << "789";
  2678. sink.done();
  2679. return true;
  2680. });
  2681. })
  2682. .Get("/streamed-chunked-with-prohibited-trailer",
  2683. [&](const Request & /*req*/, Response &res) {
  2684. auto i = new int(0);
  2685. // Declare both a prohibited trailer (Content-Length) and an
  2686. // allowed one
  2687. res.set_header("Trailer", "Content-Length, X-Allowed");
  2688. res.set_chunked_content_provider(
  2689. "text/plain",
  2690. [i](size_t /*offset*/, DataSink &sink) {
  2691. switch (*i) {
  2692. case 0: sink.os << "123"; break;
  2693. case 1: sink.os << "456"; break;
  2694. case 2: sink.os << "789"; break;
  2695. case 3: {
  2696. sink.done_with_trailer(
  2697. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2698. } break;
  2699. }
  2700. (*i)++;
  2701. return true;
  2702. },
  2703. [i](bool success) {
  2704. EXPECT_TRUE(success);
  2705. delete i;
  2706. });
  2707. })
  2708. .Get("/streamed-chunked2",
  2709. [&](const Request & /*req*/, Response &res) {
  2710. auto i = new int(0);
  2711. res.set_chunked_content_provider(
  2712. "text/plain",
  2713. [i](size_t /*offset*/, DataSink &sink) {
  2714. switch (*i) {
  2715. case 0: sink.os << "123"; break;
  2716. case 1: sink.os << "456"; break;
  2717. case 2: sink.os << "789"; break;
  2718. case 3: sink.done(); break;
  2719. }
  2720. (*i)++;
  2721. return true;
  2722. },
  2723. [i](bool success) {
  2724. EXPECT_TRUE(success);
  2725. delete i;
  2726. });
  2727. })
  2728. .Get("/streamed-chunked-with-trailer",
  2729. [&](const Request & /*req*/, Response &res) {
  2730. auto i = new int(0);
  2731. res.set_header("Trailer", "Dummy1, Dummy2");
  2732. res.set_chunked_content_provider(
  2733. "text/plain",
  2734. [i](size_t /*offset*/, DataSink &sink) {
  2735. switch (*i) {
  2736. case 0: sink.os << "123"; break;
  2737. case 1: sink.os << "456"; break;
  2738. case 2: sink.os << "789"; break;
  2739. case 3: {
  2740. sink.done_with_trailer(
  2741. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2742. } break;
  2743. }
  2744. (*i)++;
  2745. return true;
  2746. },
  2747. [i](bool success) {
  2748. EXPECT_TRUE(success);
  2749. delete i;
  2750. });
  2751. })
  2752. .Get("/streamed",
  2753. [&](const Request & /*req*/, Response &res) {
  2754. res.set_content_provider(
  2755. 6, "text/plain",
  2756. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2757. sink.os << (offset < 3 ? "a" : "b");
  2758. return true;
  2759. });
  2760. })
  2761. .Get("/streamed-with-range",
  2762. [&](const Request &req, Response &res) {
  2763. auto data = new std::string("abcdefg");
  2764. res.set_content_provider(
  2765. data->size(), "text/plain",
  2766. [data](size_t offset, size_t length, DataSink &sink) {
  2767. size_t DATA_CHUNK_SIZE = 4;
  2768. const auto &d = *data;
  2769. auto out_len =
  2770. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2771. auto ret =
  2772. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2773. EXPECT_TRUE(ret);
  2774. return true;
  2775. },
  2776. [data, &req](bool success) {
  2777. EXPECT_EQ(success, !req.has_param("error"));
  2778. delete data;
  2779. });
  2780. })
  2781. .Get("/streamed-cancel",
  2782. [&](const Request & /*req*/, Response &res) {
  2783. res.set_content_provider(
  2784. size_t(-1), "text/plain",
  2785. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2786. sink.os << "data_chunk";
  2787. return true;
  2788. });
  2789. })
  2790. .Get("/regex-with-delimiter",
  2791. [&](const Request &req, Response & /*res*/) {
  2792. ASSERT_TRUE(req.has_param("key"));
  2793. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2794. })
  2795. .Get("/with-range",
  2796. [&](const Request & /*req*/, Response &res) {
  2797. res.set_content("abcdefg", "text/plain");
  2798. })
  2799. .Get("/test-start-time",
  2800. [&](const Request &req, Response & /*res*/) {
  2801. EXPECT_NE(req.start_time_,
  2802. std::chrono::steady_clock::time_point::min());
  2803. })
  2804. .Get("/with-range-customized-response",
  2805. [&](const Request & /*req*/, Response &res) {
  2806. res.status = StatusCode::BadRequest_400;
  2807. res.set_content(JSON_DATA, "application/json");
  2808. })
  2809. .Post("/chunked",
  2810. [&](const Request &req, Response & /*res*/) {
  2811. EXPECT_EQ(req.body, "dechunked post body");
  2812. })
  2813. .Post("/large-chunked",
  2814. [&](const Request &req, Response & /*res*/) {
  2815. std::string expected(6 * 30 * 1024u, 'a');
  2816. EXPECT_EQ(req.body, expected);
  2817. })
  2818. .Post("/multipart",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2821. req.form.get_field_count("text2") +
  2822. req.form.get_field_count("file3") +
  2823. req.form.get_field_count("file4"));
  2824. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2825. req.form.get_file_count("file2"));
  2826. ASSERT_TRUE(!req.form.has_file("???"));
  2827. ASSERT_TRUE(!req.form.has_field("???"));
  2828. ASSERT_TRUE(req.body.empty());
  2829. {
  2830. const auto &text = req.form.get_field("text1");
  2831. EXPECT_EQ("text default", text);
  2832. }
  2833. {
  2834. const auto &text = req.form.get_field("text2");
  2835. EXPECT_EQ("aωb", text);
  2836. }
  2837. {
  2838. const auto &file = req.form.get_file("file1");
  2839. EXPECT_EQ("hello.txt", file.filename);
  2840. EXPECT_EQ("text/plain", file.content_type);
  2841. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2842. }
  2843. {
  2844. const auto &file = req.form.get_file("file2");
  2845. EXPECT_EQ("world.json", file.filename);
  2846. EXPECT_EQ("application/json", file.content_type);
  2847. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2848. }
  2849. {
  2850. const auto &text = req.form.get_field("file3");
  2851. EXPECT_EQ(0u, text.size());
  2852. }
  2853. {
  2854. const auto &text = req.form.get_field("file4");
  2855. EXPECT_EQ(0u, text.size());
  2856. }
  2857. })
  2858. .Post("/multipart/multi_file_values",
  2859. [&](const Request &req, Response & /*res*/) {
  2860. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2861. req.form.get_field_count("multi_text1"));
  2862. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2863. ASSERT_TRUE(!req.form.has_file("???"));
  2864. ASSERT_TRUE(!req.form.has_field("???"));
  2865. ASSERT_TRUE(req.body.empty());
  2866. {
  2867. const auto &text = req.form.get_field("text");
  2868. EXPECT_EQ("default text", text);
  2869. }
  2870. {
  2871. const auto &text1_values = req.form.get_fields("multi_text1");
  2872. EXPECT_EQ(2u, text1_values.size());
  2873. EXPECT_EQ("aaaaa", text1_values[0]);
  2874. EXPECT_EQ("bbbbb", text1_values[1]);
  2875. }
  2876. {
  2877. const auto &file1_values = req.form.get_files("multi_file1");
  2878. EXPECT_EQ(2u, file1_values.size());
  2879. auto file1 = file1_values[0];
  2880. EXPECT_EQ(file1.filename, "hello.txt");
  2881. EXPECT_EQ(file1.content_type, "text/plain");
  2882. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2883. auto file2 = file1_values[1];
  2884. EXPECT_EQ(file2.filename, "world.json");
  2885. EXPECT_EQ(file2.content_type, "application/json");
  2886. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2887. }
  2888. })
  2889. .Post("/empty",
  2890. [&](const Request &req, Response &res) {
  2891. EXPECT_EQ(req.body, "");
  2892. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2893. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2894. res.set_content("empty", "text/plain");
  2895. })
  2896. .Post("/empty-no-content-type",
  2897. [&](const Request &req, Response &res) {
  2898. EXPECT_EQ(req.body, "");
  2899. EXPECT_FALSE(req.has_header("Content-Type"));
  2900. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2901. res.set_content("empty-no-content-type", "text/plain");
  2902. })
  2903. .Post("/path-only",
  2904. [&](const Request &req, Response &res) {
  2905. EXPECT_EQ(req.body, "");
  2906. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2907. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2908. res.set_content("path-only", "text/plain");
  2909. })
  2910. .Post("/path-headers-only",
  2911. [&](const Request &req, Response &res) {
  2912. EXPECT_EQ(req.body, "");
  2913. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2915. EXPECT_EQ("world", req.get_header_value("hello"));
  2916. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2917. res.set_content("path-headers-only", "text/plain");
  2918. })
  2919. .Post("/post-large",
  2920. [&](const Request &req, Response &res) {
  2921. EXPECT_EQ(req.body, LARGE_DATA);
  2922. res.set_content(req.body, "text/plain");
  2923. })
  2924. .Post("/post-loopback",
  2925. [&](const Request &, Response &res,
  2926. ContentReader const &content_reader) {
  2927. std::string body;
  2928. content_reader([&](const char *data, size_t data_length) {
  2929. body.append(data, data_length);
  2930. return true;
  2931. });
  2932. res.set_content(body, "text/plain");
  2933. })
  2934. .Put("/put-loopback",
  2935. [&](const Request &, Response &res,
  2936. ContentReader const &content_reader) {
  2937. std::string body;
  2938. content_reader([&](const char *data, size_t data_length) {
  2939. body.append(data, data_length);
  2940. return true;
  2941. });
  2942. res.set_content(body, "text/plain");
  2943. })
  2944. .Patch("/patch-loopback",
  2945. [&](const Request &, Response &res,
  2946. ContentReader const &content_reader) {
  2947. std::string body;
  2948. content_reader([&](const char *data, size_t data_length) {
  2949. body.append(data, data_length);
  2950. return true;
  2951. });
  2952. res.set_content(body, "text/plain");
  2953. })
  2954. .Put("/empty-no-content-type",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "");
  2957. EXPECT_FALSE(req.has_header("Content-Type"));
  2958. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2959. res.set_content("empty-no-content-type", "text/plain");
  2960. })
  2961. .Put("/put",
  2962. [&](const Request &req, Response &res) {
  2963. EXPECT_EQ(req.body, "PUT");
  2964. res.set_content(req.body, "text/plain");
  2965. })
  2966. .Put("/put-large",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(req.body, LARGE_DATA);
  2969. res.set_content(req.body, "text/plain");
  2970. })
  2971. .Patch("/patch",
  2972. [&](const Request &req, Response &res) {
  2973. EXPECT_EQ(req.body, "PATCH");
  2974. res.set_content(req.body, "text/plain");
  2975. })
  2976. .Delete("/delete",
  2977. [&](const Request & /*req*/, Response &res) {
  2978. res.set_content("DELETE", "text/plain");
  2979. })
  2980. .Delete("/delete-body",
  2981. [&](const Request &req, Response &res) {
  2982. EXPECT_EQ(req.body, "content");
  2983. res.set_content(req.body, "text/plain");
  2984. })
  2985. .Options(R"(\*)",
  2986. [&](const Request & /*req*/, Response &res) {
  2987. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2988. })
  2989. .Get("/request-target",
  2990. [&](const Request &req, Response & /*res*/) {
  2991. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2992. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2993. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2994. })
  2995. .Get("/long-query-value",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2998. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2999. })
  3000. .Get("/too-long-query-value",
  3001. [&](const Request &req, Response & /*res*/) {
  3002. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3003. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3004. })
  3005. .Get("/array-param",
  3006. [&](const Request &req, Response & /*res*/) {
  3007. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3008. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3009. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3010. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3011. })
  3012. .Post("/validate-no-multiple-headers",
  3013. [&](const Request &req, Response & /*res*/) {
  3014. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3015. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3016. })
  3017. .Post("/content_receiver",
  3018. [&](const Request &req, Response &res,
  3019. const ContentReader &content_reader) {
  3020. if (req.is_multipart_form_data()) {
  3021. std::vector<FormData> items;
  3022. content_reader(
  3023. [&](const FormData &file) {
  3024. items.push_back(file);
  3025. return true;
  3026. },
  3027. [&](const char *data, size_t data_length) {
  3028. items.back().content.append(data, data_length);
  3029. return true;
  3030. });
  3031. EXPECT_EQ(5u, items.size());
  3032. {
  3033. const auto &file = get_file_value(items, "text1");
  3034. EXPECT_TRUE(file.filename.empty());
  3035. EXPECT_EQ("text default", file.content);
  3036. }
  3037. {
  3038. const auto &file = get_file_value(items, "text2");
  3039. EXPECT_TRUE(file.filename.empty());
  3040. EXPECT_EQ("aωb", file.content);
  3041. }
  3042. {
  3043. const auto &file = get_file_value(items, "file1");
  3044. EXPECT_EQ("hello.txt", file.filename);
  3045. EXPECT_EQ("text/plain", file.content_type);
  3046. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3047. }
  3048. {
  3049. const auto &file = get_file_value(items, "file2");
  3050. EXPECT_EQ("world.json", file.filename);
  3051. EXPECT_EQ("application/json", file.content_type);
  3052. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3053. }
  3054. {
  3055. const auto &file = get_file_value(items, "file3");
  3056. EXPECT_TRUE(file.filename.empty());
  3057. EXPECT_EQ("application/octet-stream", file.content_type);
  3058. EXPECT_EQ(0u, file.content.size());
  3059. }
  3060. } else {
  3061. std::string body;
  3062. content_reader([&](const char *data, size_t data_length) {
  3063. EXPECT_EQ(7U, data_length);
  3064. body.append(data, data_length);
  3065. return true;
  3066. });
  3067. EXPECT_EQ(body, "content");
  3068. res.set_content(body, "text/plain");
  3069. }
  3070. })
  3071. .Put("/content_receiver",
  3072. [&](const Request & /*req*/, Response &res,
  3073. const ContentReader &content_reader) {
  3074. std::string body;
  3075. content_reader([&](const char *data, size_t data_length) {
  3076. body.append(data, data_length);
  3077. return true;
  3078. });
  3079. EXPECT_EQ(body, "content");
  3080. res.set_content(body, "text/plain");
  3081. })
  3082. .Patch("/content_receiver",
  3083. [&](const Request & /*req*/, Response &res,
  3084. const ContentReader &content_reader) {
  3085. std::string body;
  3086. content_reader([&](const char *data, size_t data_length) {
  3087. body.append(data, data_length);
  3088. return true;
  3089. });
  3090. EXPECT_EQ(body, "content");
  3091. res.set_content(body, "text/plain");
  3092. })
  3093. .Post("/query-string-and-body",
  3094. [&](const Request &req, Response & /*res*/) {
  3095. ASSERT_TRUE(req.has_param("key"));
  3096. EXPECT_EQ(req.get_param_value("key"), "value");
  3097. EXPECT_EQ(req.body, "content");
  3098. })
  3099. .Get("/last-request",
  3100. [&](const Request &req, Response & /*res*/) {
  3101. EXPECT_EQ("close", req.get_header_value("Connection"));
  3102. })
  3103. .Get(R"(/redirect/(\d+))",
  3104. [&](const Request &req, Response &res) {
  3105. auto num = std::stoi(req.matches[1]) + 1;
  3106. std::string url = "/redirect/" + std::to_string(num);
  3107. res.set_redirect(url);
  3108. })
  3109. .Post("/binary",
  3110. [&](const Request &req, Response &res) {
  3111. EXPECT_EQ(4U, req.body.size());
  3112. EXPECT_EQ("application/octet-stream",
  3113. req.get_header_value("Content-Type"));
  3114. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3115. res.set_content(req.body, "application/octet-stream");
  3116. })
  3117. .Put("/binary",
  3118. [&](const Request &req, Response &res) {
  3119. EXPECT_EQ(4U, req.body.size());
  3120. EXPECT_EQ("application/octet-stream",
  3121. req.get_header_value("Content-Type"));
  3122. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3123. res.set_content(req.body, "application/octet-stream");
  3124. })
  3125. .Patch("/binary",
  3126. [&](const Request &req, Response &res) {
  3127. EXPECT_EQ(4U, req.body.size());
  3128. EXPECT_EQ("application/octet-stream",
  3129. req.get_header_value("Content-Type"));
  3130. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3131. res.set_content(req.body, "application/octet-stream");
  3132. })
  3133. .Delete("/binary",
  3134. [&](const Request &req, Response &res) {
  3135. EXPECT_EQ(4U, req.body.size());
  3136. EXPECT_EQ("application/octet-stream",
  3137. req.get_header_value("Content-Type"));
  3138. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3139. res.set_content(req.body, "application/octet-stream");
  3140. })
  3141. .Get("/issue1772",
  3142. [&](const Request & /*req*/, Response &res) {
  3143. res.status = 401;
  3144. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3145. })
  3146. .Delete("/issue609",
  3147. [](const httplib::Request &, httplib::Response &res,
  3148. const httplib::ContentReader &) {
  3149. res.set_content("ok", "text/plain");
  3150. })
  3151. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3152. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3153. .Get("/compress",
  3154. [&](const Request & /*req*/, Response &res) {
  3155. res.set_content(
  3156. "12345678901234567890123456789012345678901234567890123456789"
  3157. "01234567890123456789012345678901234567890",
  3158. "text/plain");
  3159. })
  3160. .Get("/nocompress",
  3161. [&](const Request & /*req*/, Response &res) {
  3162. res.set_content(
  3163. "12345678901234567890123456789012345678901234567890123456789"
  3164. "01234567890123456789012345678901234567890",
  3165. "application/octet-stream");
  3166. })
  3167. .Post("/compress-multipart",
  3168. [&](const Request &req, Response & /*res*/) {
  3169. EXPECT_EQ(2u, req.form.fields.size());
  3170. ASSERT_TRUE(!req.form.has_field("???"));
  3171. {
  3172. const auto &text = req.form.get_field("key1");
  3173. EXPECT_EQ("test", text);
  3174. }
  3175. {
  3176. const auto &text = req.form.get_field("key2");
  3177. EXPECT_EQ("--abcdefg123", text);
  3178. }
  3179. })
  3180. #endif
  3181. ;
  3182. persons_["john"] = "programmer";
  3183. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3184. svr_.wait_until_ready();
  3185. }
  3186. virtual void TearDown() {
  3187. svr_.stop();
  3188. if (!request_threads_.empty()) {
  3189. std::this_thread::sleep_for(std::chrono::seconds(1));
  3190. for (auto &t : request_threads_) {
  3191. t.join();
  3192. }
  3193. }
  3194. t_.join();
  3195. }
  3196. map<string, string> persons_;
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli_;
  3199. SSLServer svr_;
  3200. #else
  3201. Client cli_;
  3202. Server svr_;
  3203. #endif
  3204. thread t_;
  3205. std::vector<thread> request_threads_;
  3206. };
  3207. TEST_F(ServerTest, GetMethod200) {
  3208. auto res = cli_.Get("/hi");
  3209. ASSERT_TRUE(res);
  3210. EXPECT_EQ("HTTP/1.1", res->version);
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("OK", res->reason);
  3213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3214. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3215. EXPECT_EQ("Hello World!", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetEmptyFile) {
  3218. auto res = cli_.Get("/empty_file");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetFileContent) {
  3226. auto res = cli_.Get("/file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3231. EXPECT_EQ("test.html", res->body);
  3232. }
  3233. TEST_F(ServerTest, GetFileContentWithRange) {
  3234. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3237. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3238. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3239. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3240. EXPECT_EQ("est", res->body);
  3241. }
  3242. TEST_F(ServerTest, GetFileContentWithContentType) {
  3243. auto res = cli_.Get("/file_content_with_content_type");
  3244. ASSERT_TRUE(res);
  3245. EXPECT_EQ(StatusCode::OK_200, res->status);
  3246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3247. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3248. EXPECT_EQ("file\n", res->body);
  3249. }
  3250. TEST_F(ServerTest, GetInvalidFileContent) {
  3251. auto res = cli_.Get("/invalid_file_content");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3256. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3257. ASSERT_TRUE(res);
  3258. EXPECT_EQ("HTTP/1.1", res->version);
  3259. EXPECT_EQ(StatusCode::OK_200, res->status);
  3260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3261. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. TEST_F(ServerTest, GetMethod302) {
  3265. auto res = cli_.Get("/");
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::Found_302, res->status);
  3268. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3269. }
  3270. TEST_F(ServerTest, GetMethod302Redirect) {
  3271. cli_.set_follow_location(true);
  3272. auto res = cli_.Get("/");
  3273. ASSERT_TRUE(res);
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. EXPECT_EQ("Hello World!", res->body);
  3276. EXPECT_EQ("/hi", res->location);
  3277. }
  3278. TEST_F(ServerTest, GetMethod404) {
  3279. auto res = cli_.Get("/invalid");
  3280. ASSERT_TRUE(res);
  3281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3282. }
  3283. TEST_F(ServerTest, HeadMethod200) {
  3284. auto res = cli_.Head("/hi");
  3285. ASSERT_TRUE(res);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3288. EXPECT_TRUE(res->body.empty());
  3289. }
  3290. TEST_F(ServerTest, HeadMethod200Static) {
  3291. auto res = cli_.Head("/mount/dir/index.html");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3295. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3296. EXPECT_TRUE(res->body.empty());
  3297. }
  3298. TEST_F(ServerTest, HeadMethod404) {
  3299. auto res = cli_.Head("/invalid");
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3302. EXPECT_TRUE(res->body.empty());
  3303. }
  3304. TEST_F(ServerTest, GetMethodPersonJohn) {
  3305. auto res = cli_.Get("/person/john");
  3306. ASSERT_TRUE(res);
  3307. EXPECT_EQ(StatusCode::OK_200, res->status);
  3308. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3309. EXPECT_EQ("programmer", res->body);
  3310. }
  3311. TEST_F(ServerTest, PostMethod1) {
  3312. auto res = cli_.Get("/person/john1");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3315. res = cli_.Post("/person", "name=john1&note=coder",
  3316. "application/x-www-form-urlencoded");
  3317. ASSERT_TRUE(res);
  3318. ASSERT_EQ(StatusCode::OK_200, res->status);
  3319. res = cli_.Get("/person/john1");
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::OK_200, res->status);
  3322. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. ASSERT_EQ("coder", res->body);
  3324. }
  3325. TEST_F(ServerTest, PostMethod2) {
  3326. auto res = cli_.Get("/person/john2");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3329. Params params;
  3330. params.emplace("name", "john2");
  3331. params.emplace("note", "coder");
  3332. res = cli_.Post("/person", params);
  3333. ASSERT_TRUE(res);
  3334. ASSERT_EQ(StatusCode::OK_200, res->status);
  3335. res = cli_.Get("/person/john2");
  3336. ASSERT_TRUE(res);
  3337. ASSERT_EQ(StatusCode::OK_200, res->status);
  3338. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3339. ASSERT_EQ("coder", res->body);
  3340. }
  3341. TEST_F(ServerTest, PutMethod3) {
  3342. auto res = cli_.Get("/person/john3");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3345. Params params;
  3346. params.emplace("name", "john3");
  3347. params.emplace("note", "coder");
  3348. res = cli_.Put("/person", params);
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. res = cli_.Get("/person/john3");
  3352. ASSERT_TRUE(res);
  3353. ASSERT_EQ(StatusCode::OK_200, res->status);
  3354. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3355. ASSERT_EQ("coder", res->body);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod1) {
  3358. auto res = cli_.Get("/person/john4");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john4");
  3363. params.emplace("note", "coder");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john4");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("coder", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john4");
  3374. res = cli_.Delete("/person", delete_params);
  3375. ASSERT_TRUE(res);
  3376. ASSERT_EQ(StatusCode::OK_200, res->status);
  3377. ASSERT_EQ("DELETED", res->body);
  3378. res = cli_.Get("/person/john4");
  3379. ASSERT_TRUE(res);
  3380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3381. }
  3382. TEST_F(ServerTest, DeleteMethod2) {
  3383. auto res = cli_.Get("/person/john5");
  3384. ASSERT_TRUE(res);
  3385. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3386. Params params;
  3387. params.emplace("name", "john5");
  3388. params.emplace("note", "developer");
  3389. res = cli_.Post("/person", params);
  3390. ASSERT_TRUE(res);
  3391. ASSERT_EQ(StatusCode::OK_200, res->status);
  3392. res = cli_.Get("/person/john5");
  3393. ASSERT_TRUE(res);
  3394. ASSERT_EQ(StatusCode::OK_200, res->status);
  3395. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3396. ASSERT_EQ("developer", res->body);
  3397. Params delete_params;
  3398. delete_params.emplace("name", "john5");
  3399. Headers headers;
  3400. headers.emplace("Custom-Header", "test-value");
  3401. res = cli_.Delete("/person", headers, delete_params);
  3402. ASSERT_TRUE(res);
  3403. ASSERT_EQ(StatusCode::OK_200, res->status);
  3404. ASSERT_EQ("DELETED", res->body);
  3405. res = cli_.Get("/person/john5");
  3406. ASSERT_TRUE(res);
  3407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3408. }
  3409. TEST_F(ServerTest, DeleteMethod3) {
  3410. auto res = cli_.Get("/person/john6");
  3411. ASSERT_TRUE(res);
  3412. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3413. Params params;
  3414. params.emplace("name", "john6");
  3415. params.emplace("note", "tester");
  3416. res = cli_.Post("/person", params);
  3417. ASSERT_TRUE(res);
  3418. ASSERT_EQ(StatusCode::OK_200, res->status);
  3419. res = cli_.Get("/person/john6");
  3420. ASSERT_TRUE(res);
  3421. ASSERT_EQ(StatusCode::OK_200, res->status);
  3422. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3423. ASSERT_EQ("tester", res->body);
  3424. Params delete_params;
  3425. delete_params.emplace("name", "john6");
  3426. Headers headers;
  3427. headers.emplace("Custom-Header", "test-value");
  3428. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. ASSERT_EQ("DELETED", res->body);
  3432. res = cli_.Get("/person/john6");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3435. }
  3436. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3437. Params params;
  3438. params.emplace("json", JSON_DATA);
  3439. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ(JSON_DATA, res->body);
  3443. }
  3444. TEST_F(ServerTest, PostEmptyContent) {
  3445. auto res = cli_.Post("/empty", "", "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. ASSERT_EQ("empty", res->body);
  3449. }
  3450. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3451. auto res = cli_.Post("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, PostPathOnly) {
  3457. auto res = cli_.Post("/path-only");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::OK_200, res->status);
  3460. ASSERT_EQ("path-only", res->body);
  3461. }
  3462. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3463. auto res = cli_.Post("/path-headers-only",
  3464. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3465. ASSERT_TRUE(res);
  3466. ASSERT_EQ(StatusCode::OK_200, res->status);
  3467. ASSERT_EQ("path-headers-only", res->body);
  3468. }
  3469. TEST_F(ServerTest, PostLarge) {
  3470. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3471. ASSERT_TRUE(res);
  3472. ASSERT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ(LARGE_DATA, res->body);
  3474. }
  3475. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3476. auto res = cli_.Put("/empty-no-content-type");
  3477. ASSERT_TRUE(res);
  3478. ASSERT_EQ(StatusCode::OK_200, res->status);
  3479. ASSERT_EQ("empty-no-content-type", res->body);
  3480. }
  3481. TEST_F(ServerTest, GetMethodDir) {
  3482. auto res = cli_.Get("/dir/");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::OK_200, res->status);
  3485. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3486. auto body = R"(<html>
  3487. <head>
  3488. </head>
  3489. <body>
  3490. <a href="/dir/test.html">Test</a>
  3491. <a href="/hi">hi</a>
  3492. </body>
  3493. </html>
  3494. )";
  3495. EXPECT_EQ(body, res->body);
  3496. }
  3497. TEST_F(ServerTest, GetMethodDirTest) {
  3498. auto res = cli_.Get("/dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::OK_200, res->status);
  3501. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3502. EXPECT_EQ("test.html", res->body);
  3503. }
  3504. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3505. auto res = cli_.Get("/dir/../dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3509. EXPECT_EQ("test.html", res->body);
  3510. }
  3511. TEST_F(ServerTest, GetMethodInvalidPath) {
  3512. auto res = cli_.Get("/dir/../test.html");
  3513. ASSERT_TRUE(res);
  3514. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3515. }
  3516. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3517. auto res = cli_.Get("/../www/dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3520. }
  3521. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3522. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3525. }
  3526. TEST_F(ServerTest, GetMethodDirMountTest) {
  3527. auto res = cli_.Get("/mount/dir/test.html");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("test.html", res->body);
  3532. }
  3533. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3534. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::OK_200, res->status);
  3537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("test.html", res->body);
  3539. }
  3540. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3541. auto res = cli_.Get("/mount/dir/../test.html");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3544. }
  3545. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3546. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3549. }
  3550. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3551. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3552. ASSERT_TRUE(res);
  3553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3554. }
  3555. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3556. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3559. }
  3560. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3561. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3564. }
  3565. TEST_F(ServerTest, PostMethod303) {
  3566. auto res = cli_.Post("/1", "body", "text/plain");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3569. EXPECT_EQ("/2", res->get_header_value("Location"));
  3570. }
  3571. TEST_F(ServerTest, PostMethod303Redirect) {
  3572. cli_.set_follow_location(true);
  3573. auto res = cli_.Post("/1", "body", "text/plain");
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("redirected.", res->body);
  3577. EXPECT_EQ("/2", res->location);
  3578. }
  3579. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3580. auto res = cli_.Get("/dir/test.abcde");
  3581. ASSERT_TRUE(res);
  3582. EXPECT_EQ(StatusCode::OK_200, res->status);
  3583. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3584. EXPECT_EQ("abcde", res->body);
  3585. }
  3586. TEST_F(ServerTest, StaticFileRange) {
  3587. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3590. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3591. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3592. EXPECT_EQ(true, res->has_header("Content-Range"));
  3593. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3594. EXPECT_EQ(std::string("cd"), res->body);
  3595. }
  3596. TEST_F(ServerTest, StaticFileRanges) {
  3597. auto res =
  3598. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3601. EXPECT_TRUE(
  3602. res->get_header_value("Content-Type")
  3603. .find(
  3604. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3605. 0);
  3606. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3607. }
  3608. TEST_F(ServerTest, StaticFileRangeHead) {
  3609. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3610. ASSERT_TRUE(res);
  3611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3612. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3613. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3614. EXPECT_EQ(true, res->has_header("Content-Range"));
  3615. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3616. }
  3617. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3618. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3619. ASSERT_TRUE(res);
  3620. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3621. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3622. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3623. EXPECT_EQ(true, res->has_header("Content-Range"));
  3624. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3625. res->get_header_value("Content-Range"));
  3626. EXPECT_EQ("LAST\n", res->body);
  3627. }
  3628. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3629. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3633. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3634. EXPECT_EQ(true, res->has_header("Content-Range"));
  3635. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3636. }
  3637. TEST_F(ServerTest, StaticFileBigFile) {
  3638. auto res = cli_.Get("/dir/1MB.txt");
  3639. ASSERT_TRUE(res);
  3640. EXPECT_EQ(StatusCode::OK_200, res->status);
  3641. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3642. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3643. }
  3644. TEST_F(ServerTest, InvalidBaseDirMount) {
  3645. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3646. }
  3647. TEST_F(ServerTest, Binary) {
  3648. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3649. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3650. "application/octet-stream");
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ(4U, res->body.size());
  3654. res = cli_.Put("/binary", binary.data(), binary.size(),
  3655. "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3660. "application/octet-stream");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ(4U, res->body.size());
  3664. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3665. "application/octet-stream");
  3666. ASSERT_TRUE(res);
  3667. ASSERT_EQ(StatusCode::OK_200, res->status);
  3668. ASSERT_EQ(4U, res->body.size());
  3669. }
  3670. TEST_F(ServerTest, BinaryString) {
  3671. auto binary = std::string("\x00\x01\x02\x03", 4);
  3672. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. ASSERT_EQ(4U, res->body.size());
  3676. res = cli_.Put("/binary", binary, "application/octet-stream");
  3677. ASSERT_TRUE(res);
  3678. ASSERT_EQ(StatusCode::OK_200, res->status);
  3679. ASSERT_EQ(4U, res->body.size());
  3680. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3681. ASSERT_TRUE(res);
  3682. ASSERT_EQ(StatusCode::OK_200, res->status);
  3683. ASSERT_EQ(4U, res->body.size());
  3684. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3685. ASSERT_TRUE(res);
  3686. ASSERT_EQ(StatusCode::OK_200, res->status);
  3687. ASSERT_EQ(4U, res->body.size());
  3688. }
  3689. TEST_F(ServerTest, EmptyRequest) {
  3690. auto res = cli_.Get("");
  3691. ASSERT_TRUE(!res);
  3692. EXPECT_EQ(Error::Connection, res.error());
  3693. }
  3694. TEST_F(ServerTest, LongRequest) {
  3695. std::string request;
  3696. for (size_t i = 0; i < 545; i++) {
  3697. request += "/TooLongRequest";
  3698. }
  3699. request += "OK";
  3700. auto res = cli_.Get(request.c_str());
  3701. ASSERT_TRUE(res);
  3702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3703. }
  3704. TEST_F(ServerTest, TooLongRequest) {
  3705. std::string request;
  3706. for (size_t i = 0; i < 546; i++) {
  3707. request += "/TooLongRequest";
  3708. }
  3709. request += "_NG";
  3710. auto start = std::chrono::high_resolution_clock::now();
  3711. cli_.set_keep_alive(true);
  3712. auto res = cli_.Get(request.c_str());
  3713. auto end = std::chrono::high_resolution_clock::now();
  3714. auto elapsed =
  3715. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3716. .count();
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3719. EXPECT_LE(elapsed, 100);
  3720. EXPECT_EQ("close", res->get_header_value("Connection"));
  3721. EXPECT_FALSE(cli_.is_socket_open());
  3722. }
  3723. TEST_F(ServerTest, AlmostTooLongRequest) {
  3724. // test for #2046 - URI length check shouldn't include other content on req
  3725. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3726. // leading /, space, HTTP/1.1)
  3727. std::string request =
  3728. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3729. auto res = cli_.Get(request.c_str());
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3732. }
  3733. TEST_F(ServerTest, LongHeader) {
  3734. Request req;
  3735. req.method = "GET";
  3736. req.path = "/hi";
  3737. std::string host_and_port;
  3738. host_and_port += HOST;
  3739. host_and_port += ":";
  3740. host_and_port += std::to_string(PORT);
  3741. req.headers.emplace("Host", host_and_port.c_str());
  3742. req.headers.emplace("Accept", "*/*");
  3743. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3744. req.headers.emplace(
  3745. "Header-Name",
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@");
  3775. auto res = std::make_shared<Response>();
  3776. auto error = Error::Success;
  3777. auto ret = cli_.send(req, *res, error);
  3778. ASSERT_TRUE(ret);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. }
  3781. TEST_F(ServerTest, LongQueryValue) {
  3782. auto start = std::chrono::high_resolution_clock::now();
  3783. cli_.set_keep_alive(true);
  3784. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3785. auto end = std::chrono::high_resolution_clock::now();
  3786. auto elapsed =
  3787. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3788. .count();
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3791. EXPECT_LE(elapsed, 100);
  3792. EXPECT_EQ("close", res->get_header_value("Connection"));
  3793. EXPECT_FALSE(cli_.is_socket_open());
  3794. }
  3795. TEST_F(ServerTest, TooLongQueryValue) {
  3796. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3797. ASSERT_FALSE(res);
  3798. EXPECT_EQ(Error::Read, res.error());
  3799. }
  3800. TEST_F(ServerTest, TooLongHeader) {
  3801. Request req;
  3802. req.method = "GET";
  3803. req.path = "/hi";
  3804. std::string host_and_port;
  3805. host_and_port += HOST;
  3806. host_and_port += ":";
  3807. host_and_port += std::to_string(PORT);
  3808. req.headers.emplace("Host", host_and_port.c_str());
  3809. req.headers.emplace("Accept", "*/*");
  3810. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3811. req.headers.emplace(
  3812. "Header-Name",
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3841. "@@@@@@@@@@@@@@@@@");
  3842. auto res = std::make_shared<Response>();
  3843. auto error = Error::Success;
  3844. auto ret = cli_.send(req, *res, error);
  3845. ASSERT_TRUE(ret);
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. }
  3848. TEST_F(ServerTest, HeaderCountAtLimit) {
  3849. // Test with headers just under the 100 limit
  3850. httplib::Headers headers;
  3851. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3852. // This should keep us just under the 100 header limit
  3853. for (int i = 0; i < 95; i++) {
  3854. std::string name = "X-Test-Header-" + std::to_string(i);
  3855. std::string value = "value" + std::to_string(i);
  3856. headers.emplace(name, value);
  3857. }
  3858. // This should work fine as we're under the limit
  3859. auto res = cli_.Get("/hi", headers);
  3860. EXPECT_TRUE(res);
  3861. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3862. }
  3863. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3864. // Test with many headers to exceed the 100 limit
  3865. httplib::Headers headers;
  3866. // Add 150 headers to definitely exceed the 100 limit
  3867. for (int i = 0; i < 150; i++) {
  3868. std::string name = "X-Test-Header-" + std::to_string(i);
  3869. std::string value = "value" + std::to_string(i);
  3870. headers.emplace(name, value);
  3871. }
  3872. // This should fail due to exceeding header count limit
  3873. cli_.set_keep_alive(true);
  3874. auto res = cli_.Get("/hi", headers);
  3875. // The request should either fail or return 400 Bad Request
  3876. if (res) {
  3877. // If we get a response, it should be 400 Bad Request
  3878. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3879. } else {
  3880. // Or the request should fail entirely
  3881. EXPECT_FALSE(res);
  3882. }
  3883. EXPECT_EQ("close", res->get_header_value("Connection"));
  3884. EXPECT_FALSE(cli_.is_socket_open());
  3885. }
  3886. TEST_F(ServerTest, PercentEncoding) {
  3887. auto res = cli_.Get("/e%6edwith%");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. }
  3891. TEST_F(ServerTest, PercentEncodingUnicode) {
  3892. auto res = cli_.Get("/e%u006edwith%");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. TEST_F(ServerTest, InvalidPercentEncoding) {
  3897. auto res = cli_.Get("/%endwith%");
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3900. }
  3901. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3902. auto res = cli_.Get("/%uendwith%");
  3903. ASSERT_TRUE(res);
  3904. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3905. }
  3906. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3907. auto res = cli_.Get("/hello?aaa=bbb%");
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3910. }
  3911. TEST_F(ServerTest, PlusSignEncoding) {
  3912. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. EXPECT_EQ("a +b", res->body);
  3916. }
  3917. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3918. // This test simulates a potential DoS attack using many headers
  3919. // to verify our security fix prevents memory exhaustion
  3920. httplib::Headers attack_headers;
  3921. // Attempt to add many headers like an attacker would (200 headers to far
  3922. // exceed limit)
  3923. for (int i = 0; i < 200; i++) {
  3924. std::string name = "X-Attack-Header-" + std::to_string(i);
  3925. std::string value = "attack_payload_" + std::to_string(i);
  3926. attack_headers.emplace(name, value);
  3927. }
  3928. // Try to POST with excessive headers
  3929. cli_.set_keep_alive(true);
  3930. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3931. // Should either fail or return 400 Bad Request due to security limit
  3932. if (res) {
  3933. // If we get a response, it should be 400 Bad Request
  3934. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3935. } else {
  3936. // Request failed, which is the expected behavior for DoS protection
  3937. EXPECT_FALSE(res);
  3938. }
  3939. EXPECT_EQ("close", res->get_header_value("Connection"));
  3940. EXPECT_FALSE(cli_.is_socket_open());
  3941. }
  3942. TEST_F(ServerTest, MultipartFormData) {
  3943. UploadFormDataItems items = {
  3944. {"text1", "text default", "", ""},
  3945. {"text2", "aωb", "", ""},
  3946. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3947. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3948. {"file3", "", "", "application/octet-stream"},
  3949. {"file4", "", "", " application/json tmp-string "}};
  3950. auto res = cli_.Post("/multipart", items);
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. }
  3954. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3955. UploadFormDataItems items = {
  3956. {"text", "default text", "", ""},
  3957. {"multi_text1", "aaaaa", "", ""},
  3958. {"multi_text1", "bbbbb", "", ""},
  3959. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3960. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3961. "application/json"},
  3962. };
  3963. auto res = cli_.Post("/multipart/multi_file_values", items);
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. }
  3967. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3968. auto res = cli_.Get("/hi");
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3972. EXPECT_EQ("Hello World!", res->body);
  3973. }
  3974. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3975. Request req;
  3976. req.method = "POST";
  3977. req.path = "/chunked";
  3978. std::string host_and_port;
  3979. host_and_port += HOST;
  3980. host_and_port += ":";
  3981. host_and_port += std::to_string(PORT);
  3982. req.headers.emplace("Host", host_and_port.c_str());
  3983. req.headers.emplace("Accept", "*/*");
  3984. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3985. req.headers.emplace("Content-Type", "text/plain");
  3986. req.headers.emplace("Content-Length", "0");
  3987. req.headers.emplace(
  3988. "Transfer-Encoding",
  3989. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3990. // Client does not chunk, so make a chunked body manually.
  3991. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3992. auto res = std::make_shared<Response>();
  3993. auto error = Error::Success;
  3994. auto ret = cli_.send(req, *res, error);
  3995. ASSERT_TRUE(ret);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. }
  3998. TEST_F(ServerTest, GetStreamed2) {
  3999. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("ab"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamed) {
  4008. auto res = cli_.Get("/streamed");
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::OK_200, res->status);
  4011. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(std::string("aaabbb"), res->body);
  4013. }
  4014. TEST_F(ServerTest, GetStreamedWithRange1) {
  4015. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4018. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4019. EXPECT_EQ(true, res->has_header("Content-Range"));
  4020. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4021. EXPECT_EQ(std::string("def"), res->body);
  4022. }
  4023. TEST_F(ServerTest, GetStreamedWithRange2) {
  4024. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4025. ASSERT_TRUE(res);
  4026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4027. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4028. EXPECT_EQ(true, res->has_header("Content-Range"));
  4029. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4030. EXPECT_EQ(std::string("bcdefg"), res->body);
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4033. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4034. ASSERT_TRUE(res);
  4035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4036. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4037. EXPECT_EQ(true, res->has_header("Content-Range"));
  4038. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4039. EXPECT_EQ(std::string("efg"), res->body);
  4040. }
  4041. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4042. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4043. ASSERT_TRUE(res);
  4044. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4045. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4046. EXPECT_EQ(false, res->has_header("Content-Range"));
  4047. EXPECT_EQ(0U, res->body.size());
  4048. }
  4049. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4050. auto res = cli_.Get("/streamed-with-range",
  4051. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4052. "92233720368547758079223372036854775807"}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4055. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(false, res->has_header("Content-Range"));
  4057. EXPECT_EQ(0U, res->body.size());
  4058. }
  4059. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4060. auto res = cli_.Get(
  4061. "/with-range",
  4062. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4063. {"Accept-Encoding", ""}});
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4066. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4067. EXPECT_EQ(true, res->has_header("Content-Range"));
  4068. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4069. EXPECT_EQ(std::string("abcdefg"), res->body);
  4070. }
  4071. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4072. auto res = cli_.Get("/with-range", {
  4073. {"Range", "bytes=0-"},
  4074. {"Accept-Encoding", ""},
  4075. });
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4079. EXPECT_EQ(true, res->has_header("Content-Range"));
  4080. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4081. EXPECT_EQ(std::string("abcdefg"), res->body);
  4082. }
  4083. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4084. auto res =
  4085. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4086. ASSERT_TRUE(res);
  4087. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4088. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4089. EXPECT_EQ(false, res->has_header("Content-Range"));
  4090. EXPECT_EQ(267U, res->body.size());
  4091. // Check that both range contents are present
  4092. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4093. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4094. // Check that Content-Range headers are present for both ranges
  4095. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4096. std::string::npos);
  4097. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4098. std::string::npos);
  4099. }
  4100. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4101. Ranges ranges;
  4102. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4103. ranges.emplace_back(0, -1);
  4104. }
  4105. auto res =
  4106. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4107. ASSERT_TRUE(res);
  4108. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4109. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4110. EXPECT_EQ(false, res->has_header("Content-Range"));
  4111. EXPECT_EQ(0U, res->body.size());
  4112. }
  4113. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4114. auto res =
  4115. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4116. ASSERT_TRUE(res);
  4117. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4118. EXPECT_EQ(5U, res->body.size());
  4119. // Check that overlapping ranges are coalesced into a single range
  4120. EXPECT_EQ("bcdef", res->body);
  4121. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4122. // Should be single range, not multipart
  4123. EXPECT_TRUE(res->has_header("Content-Range"));
  4124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4125. }
  4126. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4127. auto res =
  4128. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4131. EXPECT_EQ(268U, res->body.size());
  4132. // Check that both range contents are present
  4133. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4134. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4135. // Check that Content-Range headers are present for both ranges
  4136. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4137. std::string::npos);
  4138. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4139. std::string::npos);
  4140. }
  4141. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4142. auto res =
  4143. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4144. ASSERT_TRUE(res);
  4145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4146. EXPECT_EQ(269U, res->body.size());
  4147. // Check that both duplicate range contents are present
  4148. size_t first_abc = res->body.find("abc\r\n");
  4149. EXPECT_TRUE(first_abc != std::string::npos);
  4150. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4151. EXPECT_TRUE(second_abc != std::string::npos);
  4152. // Check that Content-Range headers are present for both ranges
  4153. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4154. EXPECT_TRUE(first_range != std::string::npos);
  4155. size_t second_range =
  4156. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4157. EXPECT_TRUE(second_range != std::string::npos);
  4158. }
  4159. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4160. auto res = cli_.Get("/streamed-with-range?error",
  4161. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4164. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4165. EXPECT_EQ(false, res->has_header("Content-Range"));
  4166. EXPECT_EQ(0U, res->body.size());
  4167. }
  4168. TEST_F(ServerTest, GetStreamedEndless) {
  4169. uint64_t offset = 0;
  4170. auto res = cli_.Get("/streamed-cancel",
  4171. [&](const char * /*data*/, uint64_t data_length) {
  4172. if (offset < 100) {
  4173. offset += data_length;
  4174. return true;
  4175. }
  4176. return false;
  4177. });
  4178. ASSERT_TRUE(!res);
  4179. EXPECT_EQ(Error::Canceled, res.error());
  4180. }
  4181. TEST_F(ServerTest, ClientStop) {
  4182. std::atomic_size_t count{4};
  4183. std::vector<std::thread> threads;
  4184. for (auto i = count.load(); i != 0; --i) {
  4185. threads.emplace_back([&]() {
  4186. auto res = cli_.Get("/streamed-cancel",
  4187. [&](const char *, uint64_t) { return true; });
  4188. --count;
  4189. ASSERT_TRUE(!res);
  4190. EXPECT_TRUE(res.error() == Error::Canceled ||
  4191. res.error() == Error::Read || res.error() == Error::Write);
  4192. });
  4193. }
  4194. std::this_thread::sleep_for(std::chrono::seconds(2));
  4195. while (count != 0) {
  4196. cli_.stop();
  4197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4198. }
  4199. for (auto &t : threads) {
  4200. t.join();
  4201. }
  4202. }
  4203. TEST_F(ServerTest, GetWithRange1) {
  4204. auto res = cli_.Get("/with-range", {
  4205. make_range_header({{3, 5}}),
  4206. {"Accept-Encoding", ""},
  4207. });
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4211. EXPECT_EQ(true, res->has_header("Content-Range"));
  4212. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4213. EXPECT_EQ(std::string("def"), res->body);
  4214. }
  4215. TEST_F(ServerTest, GetWithRange2) {
  4216. auto res = cli_.Get("/with-range", {
  4217. make_range_header({{1, -1}}),
  4218. {"Accept-Encoding", ""},
  4219. });
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4222. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4223. EXPECT_EQ(true, res->has_header("Content-Range"));
  4224. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4225. EXPECT_EQ(std::string("bcdefg"), res->body);
  4226. }
  4227. TEST_F(ServerTest, GetWithRange3) {
  4228. auto res = cli_.Get("/with-range", {
  4229. make_range_header({{0, 0}}),
  4230. {"Accept-Encoding", ""},
  4231. });
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("a"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetWithRange4) {
  4240. auto res = cli_.Get("/with-range", {
  4241. make_range_header({{-1, 2}}),
  4242. {"Accept-Encoding", ""},
  4243. });
  4244. ASSERT_TRUE(res);
  4245. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4246. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4247. EXPECT_EQ(true, res->has_header("Content-Range"));
  4248. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4249. EXPECT_EQ(std::string("fg"), res->body);
  4250. }
  4251. TEST_F(ServerTest, GetWithRange5) {
  4252. auto res = cli_.Get("/with-range", {
  4253. make_range_header({{0, 5}}),
  4254. {"Accept-Encoding", ""},
  4255. });
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4258. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4259. EXPECT_EQ(true, res->has_header("Content-Range"));
  4260. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4261. EXPECT_EQ(std::string("abcdef"), res->body);
  4262. }
  4263. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4264. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4265. ASSERT_TRUE(res);
  4266. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4267. }
  4268. TEST_F(ServerTest, GetWithRangeMultipart) {
  4269. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4270. ASSERT_TRUE(res);
  4271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4272. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4273. EXPECT_EQ(false, res->has_header("Content-Range"));
  4274. EXPECT_EQ(267U, res->body.size());
  4275. }
  4276. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4277. auto res =
  4278. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4281. }
  4282. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4283. auto res = cli_.Get("/with-range-customized-response",
  4284. {{make_range_header({{1, 2}})}});
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4287. EXPECT_EQ(true, res->has_header("Content-Length"));
  4288. EXPECT_EQ(false, res->has_header("Content-Range"));
  4289. EXPECT_EQ(JSON_DATA, res->body);
  4290. }
  4291. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4292. auto res = cli_.Get("/with-range-customized-response",
  4293. {{make_range_header({{1, 2}, {4, 5}})}});
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4296. EXPECT_EQ(true, res->has_header("Content-Length"));
  4297. EXPECT_EQ(false, res->has_header("Content-Range"));
  4298. EXPECT_EQ(JSON_DATA, res->body);
  4299. }
  4300. TEST_F(ServerTest, Issue1772) {
  4301. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4304. }
  4305. TEST_F(ServerTest, Issue609) {
  4306. auto res = cli_.Delete("/issue609");
  4307. ASSERT_TRUE(res);
  4308. EXPECT_EQ(StatusCode::OK_200, res->status);
  4309. EXPECT_EQ(std::string("ok"), res->body);
  4310. }
  4311. TEST_F(ServerTest, GetStreamedChunked) {
  4312. auto res = cli_.Get("/streamed-chunked");
  4313. ASSERT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::OK_200, res->status);
  4315. EXPECT_EQ(std::string("123456789"), res->body);
  4316. }
  4317. TEST_F(ServerTest, GetStreamedChunked2) {
  4318. auto res = cli_.Get("/streamed-chunked2");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. EXPECT_EQ(std::string("123456789"), res->body);
  4322. }
  4323. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4324. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. EXPECT_EQ(std::string("123456789"), res->body);
  4328. EXPECT_TRUE(res->has_header("Trailer"));
  4329. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4330. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4331. // Trailers are now stored separately from headers (security fix)
  4332. EXPECT_EQ(2U, res->trailers.size());
  4333. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4334. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4335. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4336. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4337. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4338. // Verify trailers are NOT in headers (security verification)
  4339. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4340. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4341. }
  4342. TEST_F(ServerTest, LargeChunkedPost) {
  4343. Request req;
  4344. req.method = "POST";
  4345. req.path = "/large-chunked";
  4346. std::string host_and_port;
  4347. host_and_port += HOST;
  4348. host_and_port += ":";
  4349. host_and_port += std::to_string(PORT);
  4350. req.headers.emplace("Host", host_and_port.c_str());
  4351. req.headers.emplace("Accept", "*/*");
  4352. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4353. req.headers.emplace("Content-Type", "text/plain");
  4354. req.headers.emplace("Content-Length", "0");
  4355. req.headers.emplace("Transfer-Encoding", "chunked");
  4356. std::string long_string(30 * 1024u, 'a');
  4357. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4358. // Attempt to make a large enough post to exceed OS buffers, to test that
  4359. // the server handles short reads if the full chunk data isn't available.
  4360. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4361. auto res = std::make_shared<Response>();
  4362. auto error = Error::Success;
  4363. auto ret = cli_.send(req, *res, error);
  4364. ASSERT_TRUE(ret);
  4365. EXPECT_EQ(StatusCode::OK_200, res->status);
  4366. }
  4367. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4368. auto res = cli_.Get("/remote_addr");
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4372. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4373. }
  4374. TEST_F(ServerTest, GetMethodLocalAddr) {
  4375. auto res = cli_.Get("/local_addr");
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4379. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4380. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4381. }
  4382. TEST_F(ServerTest, HTTPResponseSplitting) {
  4383. auto res = cli_.Get("/http_response_splitting");
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::OK_200, res->status);
  4386. }
  4387. TEST_F(ServerTest, SlowRequest) {
  4388. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4389. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4390. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4391. }
  4392. #if 0
  4393. TEST_F(ServerTest, SlowPost) {
  4394. char buffer[64 * 1024];
  4395. memset(buffer, 0x42, sizeof(buffer));
  4396. auto res = cli_.Post(
  4397. "/slowpost", 64 * 1024 * 1024,
  4398. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4399. auto ret = sink.write(buffer, sizeof(buffer));
  4400. EXPECT_TRUE(ret);
  4401. return true;
  4402. },
  4403. "text/plain");
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. }
  4407. TEST_F(ServerTest, SlowPostFail) {
  4408. char buffer[64 * 1024];
  4409. memset(buffer, 0x42, sizeof(buffer));
  4410. cli_.set_write_timeout(std::chrono::seconds(0));
  4411. auto res = cli_.Post(
  4412. "/slowpost", 64 * 1024 * 1024,
  4413. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4414. sink.write(buffer, sizeof(buffer));
  4415. return true;
  4416. },
  4417. "text/plain");
  4418. ASSERT_TRUE(!res);
  4419. EXPECT_EQ(Error::Write, res.error());
  4420. }
  4421. #endif
  4422. TEST_F(ServerTest, Put) {
  4423. auto res = cli_.Put("/put", "PUT", "text/plain");
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::OK_200, res->status);
  4426. EXPECT_EQ("PUT", res->body);
  4427. }
  4428. TEST_F(ServerTest, PutWithContentProvider) {
  4429. auto res = cli_.Put(
  4430. "/put", 3,
  4431. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4432. sink.os << "PUT";
  4433. return true;
  4434. },
  4435. "text/plain");
  4436. ASSERT_TRUE(res);
  4437. EXPECT_EQ(StatusCode::OK_200, res->status);
  4438. EXPECT_EQ("PUT", res->body);
  4439. }
  4440. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4441. auto res = cli_.Post(
  4442. "/post", 42,
  4443. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4444. return false;
  4445. },
  4446. "text/plain");
  4447. ASSERT_TRUE(!res);
  4448. EXPECT_EQ(Error::Canceled, res.error());
  4449. }
  4450. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4451. auto res = cli_.Put(
  4452. "/put",
  4453. [](size_t /*offset*/, DataSink &sink) {
  4454. sink.os << "PUT";
  4455. sink.done();
  4456. return true;
  4457. },
  4458. "text/plain");
  4459. ASSERT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. EXPECT_EQ("PUT", res->body);
  4462. }
  4463. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4464. auto res = cli_.Post(
  4465. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4466. "text/plain");
  4467. ASSERT_TRUE(!res);
  4468. EXPECT_EQ(Error::Canceled, res.error());
  4469. }
  4470. TEST_F(ServerTest, PostLoopBack) {
  4471. std::string body;
  4472. auto res = cli_.Post(
  4473. "/post-loopback", 9,
  4474. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4475. EXPECT_EQ(9u, length);
  4476. sink.write("123", 3);
  4477. sink.write("456", 3);
  4478. sink.write("789", 3);
  4479. return true;
  4480. },
  4481. "text/plain",
  4482. [&body](const char *data, size_t data_length) {
  4483. body.append(data, data_length);
  4484. return true;
  4485. });
  4486. ASSERT_TRUE(res);
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("123456789", body);
  4489. }
  4490. TEST_F(ServerTest, PutLoopBack) {
  4491. std::string body;
  4492. auto res = cli_.Put(
  4493. "/put-loopback", 9,
  4494. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4495. EXPECT_EQ(9u, length);
  4496. sink.write("123", 3);
  4497. sink.write("456", 3);
  4498. sink.write("789", 3);
  4499. return true;
  4500. },
  4501. "text/plain",
  4502. [&body](const char *data, size_t data_length) {
  4503. body.append(data, data_length);
  4504. return true;
  4505. });
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("123456789", body);
  4509. }
  4510. TEST_F(ServerTest, PatchLoopBack) {
  4511. std::string body;
  4512. auto res = cli_.Patch(
  4513. "/patch-loopback", 9,
  4514. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4515. EXPECT_EQ(9u, length);
  4516. sink.write("123", 3);
  4517. sink.write("456", 3);
  4518. sink.write("789", 3);
  4519. return true;
  4520. },
  4521. "text/plain",
  4522. [&body](const char *data, size_t data_length) {
  4523. body.append(data, data_length);
  4524. return true;
  4525. });
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::OK_200, res->status);
  4528. EXPECT_EQ("123456789", body);
  4529. }
  4530. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4531. std::string body;
  4532. auto res = cli_.Post(
  4533. "/post-loopback",
  4534. [](size_t /*offset*/, DataSink &sink) {
  4535. sink.write("123", 3);
  4536. sink.write("456", 3);
  4537. sink.write("789", 3);
  4538. sink.done();
  4539. return true;
  4540. },
  4541. "text/plain",
  4542. [&body](const char *data, size_t data_length) {
  4543. body.append(data, data_length);
  4544. return true;
  4545. });
  4546. ASSERT_TRUE(res);
  4547. EXPECT_EQ(StatusCode::OK_200, res->status);
  4548. EXPECT_EQ("123456789", body);
  4549. }
  4550. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4551. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4552. cli_.set_compress(true);
  4553. auto res = cli_.Put(
  4554. "/put", 3,
  4555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4556. sink.os << "PUT";
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", 42,
  4568. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4569. return false;
  4570. },
  4571. "text/plain");
  4572. ASSERT_TRUE(!res);
  4573. EXPECT_EQ(Error::Canceled, res.error());
  4574. }
  4575. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4576. cli_.set_compress(true);
  4577. auto res = cli_.Put(
  4578. "/put",
  4579. [](size_t /*offset*/, DataSink &sink) {
  4580. sink.os << "PUT";
  4581. sink.done();
  4582. return true;
  4583. },
  4584. "text/plain");
  4585. ASSERT_TRUE(res);
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("PUT", res->body);
  4588. }
  4589. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4590. cli_.set_compress(true);
  4591. auto res = cli_.Post(
  4592. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4593. "text/plain");
  4594. ASSERT_TRUE(!res);
  4595. EXPECT_EQ(Error::Canceled, res.error());
  4596. }
  4597. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4598. cli_.set_compress(true);
  4599. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. EXPECT_EQ(LARGE_DATA, res->body);
  4603. }
  4604. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4605. #ifdef CPPHTTPLIB_SSL_ENABLED
  4606. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4607. Client cli(s.c_str());
  4608. cli.enable_server_certificate_verification(false);
  4609. #else
  4610. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4611. Client cli(s.c_str());
  4612. #endif
  4613. cli.set_compress(true);
  4614. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. EXPECT_EQ(LARGE_DATA, res->body);
  4618. // The compressed size should be less than a 10th of the original. May vary
  4619. // depending on the zlib library.
  4620. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4621. static_cast<uint64_t>(10 * 1024 * 1024));
  4622. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4623. }
  4624. TEST_F(ServerTest, PutContentWithDeflate) {
  4625. cli_.set_compress(false);
  4626. Headers headers;
  4627. headers.emplace("Content-Encoding", "deflate");
  4628. // PUT in deflate format:
  4629. auto res = cli_.Put("/put", headers,
  4630. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("PUT", res->body);
  4634. }
  4635. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4636. Headers headers;
  4637. headers.emplace("Accept-Encoding", "gzip, deflate");
  4638. auto res = cli_.Get("/streamed-chunked", headers);
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ(std::string("123456789"), res->body);
  4642. }
  4643. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4644. Headers headers;
  4645. headers.emplace("Accept-Encoding", "gzip, deflate");
  4646. auto res = cli_.Get("/streamed-chunked2", headers);
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ(std::string("123456789"), res->body);
  4650. }
  4651. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4652. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::OK_200, res->status);
  4655. }
  4656. TEST(GzipDecompressor, ChunkedDecompression) {
  4657. std::string data;
  4658. for (size_t i = 0; i < 32 * 1024; ++i) {
  4659. data.push_back(static_cast<char>('a' + i % 26));
  4660. }
  4661. std::string compressed_data;
  4662. {
  4663. httplib::detail::gzip_compressor compressor;
  4664. bool result = compressor.compress(
  4665. data.data(), data.size(),
  4666. /*last=*/true,
  4667. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4668. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4669. compressed_data_size);
  4670. return true;
  4671. });
  4672. ASSERT_TRUE(result);
  4673. }
  4674. std::string decompressed_data;
  4675. {
  4676. httplib::detail::gzip_decompressor decompressor;
  4677. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4678. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4679. size_t chunk_size = 130;
  4680. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4681. chunk_begin += chunk_size) {
  4682. size_t current_chunk_size =
  4683. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4684. bool result = decompressor.decompress(
  4685. compressed_data.data() + chunk_begin, current_chunk_size,
  4686. [&](const char *decompressed_data_chunk,
  4687. size_t decompressed_data_chunk_size) {
  4688. decompressed_data.insert(decompressed_data.size(),
  4689. decompressed_data_chunk,
  4690. decompressed_data_chunk_size);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(result);
  4694. }
  4695. }
  4696. ASSERT_EQ(data, decompressed_data);
  4697. }
  4698. TEST(GzipDecompressor, DeflateDecompression) {
  4699. std::string original_text = "Raw deflate without gzip";
  4700. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4701. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4702. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4703. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4704. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4705. std::string decompressed_data;
  4706. {
  4707. httplib::detail::gzip_decompressor decompressor;
  4708. bool result = decompressor.decompress(
  4709. compressed_data.data(), compressed_data.size(),
  4710. [&](const char *decompressed_data_chunk,
  4711. size_t decompressed_data_chunk_size) {
  4712. decompressed_data.insert(decompressed_data.size(),
  4713. decompressed_data_chunk,
  4714. decompressed_data_chunk_size);
  4715. return true;
  4716. });
  4717. ASSERT_TRUE(result);
  4718. }
  4719. ASSERT_EQ(original_text, decompressed_data);
  4720. }
  4721. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4722. std::string original_text = "Raw deflate without gzip";
  4723. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4724. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4725. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4726. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4727. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4728. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4729. std::string decompressed_data;
  4730. {
  4731. httplib::detail::gzip_decompressor decompressor;
  4732. bool result = decompressor.decompress(
  4733. compressed_data.data(), compressed_data.size(),
  4734. [&](const char *decompressed_data_chunk,
  4735. size_t decompressed_data_chunk_size) {
  4736. decompressed_data.insert(decompressed_data.size(),
  4737. decompressed_data_chunk,
  4738. decompressed_data_chunk_size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. }
  4743. ASSERT_EQ(original_text, decompressed_data);
  4744. }
  4745. #ifdef _WIN32
  4746. TEST(GzipDecompressor, LargeRandomData) {
  4747. // prepare large random data that is difficult to be compressed and is
  4748. // expected to have large size even when compressed
  4749. std::random_device seed_gen;
  4750. std::mt19937 random(seed_gen());
  4751. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4752. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4753. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4754. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4755. // compress data over 4GiB
  4756. std::string compressed_data;
  4757. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4758. httplib::detail::gzip_compressor compressor;
  4759. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4760. data.size() * sizeof(std::uint32_t), true,
  4761. [&](const char *data, size_t size) {
  4762. compressed_data.insert(
  4763. compressed_data.size(), data, size);
  4764. return true;
  4765. });
  4766. ASSERT_TRUE(result);
  4767. // FIXME: compressed data size is expected to be greater than 4GiB,
  4768. // but there is no guarantee
  4769. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4770. // decompress data over 4GiB
  4771. std::string decompressed_data;
  4772. decompressed_data.reserve(data_size);
  4773. httplib::detail::gzip_decompressor decompressor;
  4774. result = decompressor.decompress(
  4775. compressed_data.data(), compressed_data.size(),
  4776. [&](const char *data, size_t size) {
  4777. decompressed_data.insert(decompressed_data.size(), data, size);
  4778. return true;
  4779. });
  4780. ASSERT_TRUE(result);
  4781. // compare
  4782. ASSERT_EQ(data_size, decompressed_data.size());
  4783. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4784. 0);
  4785. }
  4786. #endif
  4787. #endif
  4788. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4789. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4790. Headers headers;
  4791. headers.emplace("Accept-Encoding", "br");
  4792. auto res = cli_.Get("/streamed-chunked", headers);
  4793. ASSERT_TRUE(res);
  4794. EXPECT_EQ(StatusCode::OK_200, res->status);
  4795. EXPECT_EQ(std::string("123456789"), res->body);
  4796. }
  4797. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4798. Headers headers;
  4799. headers.emplace("Accept-Encoding", "br");
  4800. auto res = cli_.Get("/streamed-chunked2", headers);
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ(std::string("123456789"), res->body);
  4804. }
  4805. #endif
  4806. TEST_F(ServerTest, Patch) {
  4807. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. EXPECT_EQ("PATCH", res->body);
  4811. }
  4812. TEST_F(ServerTest, Delete) {
  4813. auto res = cli_.Delete("/delete");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ("DELETE", res->body);
  4817. }
  4818. TEST_F(ServerTest, DeleteContentReceiver) {
  4819. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. EXPECT_EQ("content", res->body);
  4823. }
  4824. TEST_F(ServerTest, Options) {
  4825. auto res = cli_.Options("*");
  4826. ASSERT_TRUE(res);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4829. EXPECT_TRUE(res->body.empty());
  4830. }
  4831. TEST_F(ServerTest, URL) {
  4832. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4833. ASSERT_TRUE(res);
  4834. EXPECT_EQ(StatusCode::OK_200, res->status);
  4835. }
  4836. TEST_F(ServerTest, ArrayParam) {
  4837. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, NoMultipleHeaders) {
  4842. Headers headers = {{"Content-Length", "5"}};
  4843. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4844. "text/plain");
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. }
  4848. TEST_F(ServerTest, PostContentReceiver) {
  4849. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4850. ASSERT_TRUE(res);
  4851. ASSERT_EQ(StatusCode::OK_200, res->status);
  4852. ASSERT_EQ("content", res->body);
  4853. }
  4854. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4855. UploadFormDataItems items = {
  4856. {"text1", "text default", "", ""},
  4857. {"text2", "aωb", "", ""},
  4858. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4859. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4860. {"file3", "", "", "application/octet-stream"},
  4861. };
  4862. auto res = cli_.Post("/content_receiver", items);
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. }
  4866. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4867. UploadFormDataItems items = {
  4868. {"text1", "text default", "", ""},
  4869. {"text2", "aωb", "", ""},
  4870. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4871. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4872. {"file3", "", "", "application/octet-stream"},
  4873. };
  4874. auto boundary = std::string("+++++");
  4875. std::string body;
  4876. for (const auto &item : items) {
  4877. body += "--" + boundary + "\r\n";
  4878. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4879. if (!item.filename.empty()) {
  4880. body += "; filename=\"" + item.filename + "\"";
  4881. }
  4882. body += "\r\n";
  4883. if (!item.content_type.empty()) {
  4884. body += "Content-Type: " + item.content_type + "\r\n";
  4885. }
  4886. body += "\r\n";
  4887. body += item.content + "\r\n";
  4888. }
  4889. body += "--" + boundary + "--\r\n";
  4890. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4891. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. }
  4895. TEST_F(ServerTest, PostContentReceiverGzip) {
  4896. cli_.set_compress(true);
  4897. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4898. ASSERT_TRUE(res);
  4899. ASSERT_EQ(StatusCode::OK_200, res->status);
  4900. ASSERT_EQ("content", res->body);
  4901. }
  4902. TEST_F(ServerTest, PutContentReceiver) {
  4903. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4904. ASSERT_TRUE(res);
  4905. ASSERT_EQ(StatusCode::OK_200, res->status);
  4906. ASSERT_EQ("content", res->body);
  4907. }
  4908. TEST_F(ServerTest, PatchContentReceiver) {
  4909. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4910. ASSERT_TRUE(res);
  4911. ASSERT_EQ(StatusCode::OK_200, res->status);
  4912. ASSERT_EQ("content", res->body);
  4913. }
  4914. template <typename ClientType>
  4915. void TestWithHeadersAndContentReceiver(
  4916. ClientType &cli,
  4917. std::function<Result(ClientType &, const std::string &, const Headers &,
  4918. const std::string &, const std::string &,
  4919. ContentReceiver, DownloadProgress)>
  4920. request_func) {
  4921. Headers headers;
  4922. headers.emplace("X-Custom-Header", "test-value");
  4923. std::string received_body;
  4924. auto res = request_func(
  4925. cli, "/content_receiver", headers, "content", "application/json",
  4926. [&](const char *data, size_t data_length) {
  4927. received_body.append(data, data_length);
  4928. return true;
  4929. },
  4930. nullptr);
  4931. ASSERT_TRUE(res);
  4932. EXPECT_EQ(StatusCode::OK_200, res->status);
  4933. EXPECT_EQ("content", received_body);
  4934. }
  4935. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4936. #ifdef CPPHTTPLIB_SSL_ENABLED
  4937. using ClientT = SSLClient;
  4938. #else
  4939. using ClientT = Client;
  4940. #endif
  4941. TestWithHeadersAndContentReceiver<ClientT>(
  4942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4943. const std::string &body, const std::string &content_type,
  4944. ContentReceiver receiver, DownloadProgress progress) {
  4945. return cli.Post(path, headers, body, content_type, receiver, progress);
  4946. });
  4947. }
  4948. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4949. #ifdef CPPHTTPLIB_SSL_ENABLED
  4950. using ClientT = SSLClient;
  4951. #else
  4952. using ClientT = Client;
  4953. #endif
  4954. TestWithHeadersAndContentReceiver<ClientT>(
  4955. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4956. const std::string &body, const std::string &content_type,
  4957. ContentReceiver receiver, DownloadProgress progress) {
  4958. return cli.Put(path, headers, body, content_type, receiver, progress);
  4959. });
  4960. }
  4961. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4962. #ifdef CPPHTTPLIB_SSL_ENABLED
  4963. using ClientT = SSLClient;
  4964. #else
  4965. using ClientT = Client;
  4966. #endif
  4967. TestWithHeadersAndContentReceiver<ClientT>(
  4968. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4969. const std::string &body, const std::string &content_type,
  4970. ContentReceiver receiver, DownloadProgress progress) {
  4971. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4972. });
  4973. }
  4974. template <typename ClientType>
  4975. void TestWithHeadersAndContentReceiverWithProgress(
  4976. ClientType &cli,
  4977. std::function<Result(ClientType &, const std::string &, const Headers &,
  4978. const std::string &, const std::string &,
  4979. ContentReceiver, DownloadProgress)>
  4980. request_func) {
  4981. Headers headers;
  4982. headers.emplace("X-Test-Header", "progress-test");
  4983. std::string received_body;
  4984. auto progress_called = false;
  4985. auto res = request_func(
  4986. cli, "/content_receiver", headers, "content", "text/plain",
  4987. [&](const char *data, size_t data_length) {
  4988. received_body.append(data, data_length);
  4989. return true;
  4990. },
  4991. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4992. progress_called = true;
  4993. return true;
  4994. });
  4995. ASSERT_TRUE(res);
  4996. EXPECT_EQ(StatusCode::OK_200, res->status);
  4997. EXPECT_EQ("content", received_body);
  4998. EXPECT_TRUE(progress_called);
  4999. }
  5000. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5001. #ifdef CPPHTTPLIB_SSL_ENABLED
  5002. using ClientT = SSLClient;
  5003. #else
  5004. using ClientT = Client;
  5005. #endif
  5006. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5008. const std::string &body, const std::string &content_type,
  5009. ContentReceiver receiver, DownloadProgress progress) {
  5010. return cli.Post(path, headers, body, content_type, receiver, progress);
  5011. });
  5012. }
  5013. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5014. #ifdef CPPHTTPLIB_SSL_ENABLED
  5015. using ClientT = SSLClient;
  5016. #else
  5017. using ClientT = Client;
  5018. #endif
  5019. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5021. const std::string &body, const std::string &content_type,
  5022. ContentReceiver receiver, DownloadProgress progress) {
  5023. return cli.Put(path, headers, body, content_type, receiver, progress);
  5024. });
  5025. }
  5026. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5027. #ifdef CPPHTTPLIB_SSL_ENABLED
  5028. using ClientT = SSLClient;
  5029. #else
  5030. using ClientT = Client;
  5031. #endif
  5032. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5034. const std::string &body, const std::string &content_type,
  5035. ContentReceiver receiver, DownloadProgress progress) {
  5036. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5037. });
  5038. }
  5039. template <typename ClientType>
  5040. void TestWithHeadersAndContentReceiverError(
  5041. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5042. const Headers &, const std::string &,
  5043. const std::string &, ContentReceiver)>
  5044. request_func) {
  5045. Headers headers;
  5046. headers.emplace("X-Error-Test", "true");
  5047. std::string received_body;
  5048. auto receiver_failed = false;
  5049. auto res =
  5050. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5051. [&](const char *data, size_t data_length) {
  5052. received_body.append(data, data_length);
  5053. receiver_failed = true;
  5054. return false;
  5055. });
  5056. ASSERT_FALSE(res);
  5057. EXPECT_TRUE(receiver_failed);
  5058. }
  5059. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5060. #ifdef CPPHTTPLIB_SSL_ENABLED
  5061. using ClientT = SSLClient;
  5062. #else
  5063. using ClientT = Client;
  5064. #endif
  5065. TestWithHeadersAndContentReceiverError<ClientT>(
  5066. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5067. const std::string &body, const std::string &content_type,
  5068. ContentReceiver receiver) {
  5069. return cli.Post(path, headers, body, content_type, receiver);
  5070. });
  5071. }
  5072. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5073. #ifdef CPPHTTPLIB_SSL_ENABLED
  5074. using ClientT = SSLClient;
  5075. #else
  5076. using ClientT = Client;
  5077. #endif
  5078. TestWithHeadersAndContentReceiverError<ClientT>(
  5079. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5080. const std::string &body, const std::string &content_type,
  5081. ContentReceiver receiver) {
  5082. return cli.Put(path, headers, body, content_type, receiver);
  5083. });
  5084. }
  5085. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5086. #ifdef CPPHTTPLIB_SSL_ENABLED
  5087. using ClientT = SSLClient;
  5088. #else
  5089. using ClientT = Client;
  5090. #endif
  5091. TestWithHeadersAndContentReceiverError<ClientT>(
  5092. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5093. const std::string &body, const std::string &content_type,
  5094. ContentReceiver receiver) {
  5095. return cli.Patch(path, headers, body, content_type, receiver);
  5096. });
  5097. }
  5098. TEST_F(ServerTest, PostQueryStringAndBody) {
  5099. auto res =
  5100. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5101. ASSERT_TRUE(res);
  5102. ASSERT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, HTTP2Magic) {
  5105. Request req;
  5106. req.method = "PRI";
  5107. req.path = "*";
  5108. req.body = "SM";
  5109. auto res = std::make_shared<Response>();
  5110. auto error = Error::Success;
  5111. auto ret = cli_.send(req, *res, error);
  5112. ASSERT_TRUE(ret);
  5113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5114. }
  5115. TEST_F(ServerTest, KeepAlive) {
  5116. auto res = cli_.Get("/hi");
  5117. ASSERT_TRUE(res);
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5120. EXPECT_EQ("Hello World!", res->body);
  5121. res = cli_.Get("/hi");
  5122. ASSERT_TRUE(res);
  5123. EXPECT_EQ(StatusCode::OK_200, res->status);
  5124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5125. EXPECT_EQ("Hello World!", res->body);
  5126. res = cli_.Get("/hi");
  5127. ASSERT_TRUE(res);
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5130. EXPECT_EQ("Hello World!", res->body);
  5131. res = cli_.Get("/not-exist");
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5134. res = cli_.Post("/empty", "", "text/plain");
  5135. ASSERT_TRUE(res);
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5138. EXPECT_EQ("empty", res->body);
  5139. EXPECT_EQ("close", res->get_header_value("Connection"));
  5140. res = cli_.Post(
  5141. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5142. "text/plain");
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ(StatusCode::OK_200, res->status);
  5145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5146. EXPECT_EQ("empty", res->body);
  5147. cli_.set_keep_alive(false);
  5148. res = cli_.Get("/last-request");
  5149. ASSERT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. EXPECT_EQ("close", res->get_header_value("Connection"));
  5152. }
  5153. TEST_F(ServerTest, TooManyRedirect) {
  5154. cli_.set_follow_location(true);
  5155. auto res = cli_.Get("/redirect/0");
  5156. ASSERT_TRUE(!res);
  5157. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5158. }
  5159. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5160. Request req;
  5161. req.method = "FOOBAR";
  5162. req.path = "/hi";
  5163. cli_.set_keep_alive(true);
  5164. auto res = cli_.send(req);
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5167. EXPECT_EQ("close", res->get_header_value("Connection"));
  5168. EXPECT_FALSE(cli_.is_socket_open());
  5169. }
  5170. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5171. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5172. TEST_F(ServerTest, Gzip) {
  5173. Headers headers;
  5174. headers.emplace("Accept-Encoding", "gzip, deflate");
  5175. auto res = cli_.Get("/compress", headers);
  5176. ASSERT_TRUE(res);
  5177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5180. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5181. "7890123456789012345678901234567890",
  5182. res->body);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. }
  5185. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5186. Headers headers;
  5187. headers.emplace("Accept-Encoding", "");
  5188. auto res = cli_.Get("/compress", headers);
  5189. ASSERT_TRUE(res);
  5190. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5192. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5193. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5194. "7890123456789012345678901234567890",
  5195. res->body);
  5196. EXPECT_EQ(StatusCode::OK_200, res->status);
  5197. }
  5198. TEST_F(ServerTest, GzipWithContentReceiver) {
  5199. Headers headers;
  5200. headers.emplace("Accept-Encoding", "gzip, deflate");
  5201. std::string body;
  5202. auto res = cli_.Get("/compress", headers,
  5203. [&](const char *data, uint64_t data_length) {
  5204. EXPECT_EQ(100U, data_length);
  5205. body.append(data, data_length);
  5206. return true;
  5207. });
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5211. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5212. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5213. "7890123456789012345678901234567890",
  5214. body);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. }
  5217. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5218. Headers headers;
  5219. headers.emplace("Accept-Encoding", "gzip, deflate");
  5220. cli_.set_decompress(false);
  5221. auto res = cli_.Get("/compress", headers);
  5222. ASSERT_TRUE(res);
  5223. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5226. EXPECT_EQ(33U, res->body.size());
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. }
  5229. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5230. Headers headers;
  5231. headers.emplace("Accept-Encoding", "");
  5232. std::string body;
  5233. auto res = cli_.Get("/compress", headers,
  5234. [&](const char *data, uint64_t data_length) {
  5235. EXPECT_EQ(100U, data_length);
  5236. body.append(data, data_length);
  5237. return true;
  5238. });
  5239. ASSERT_TRUE(res);
  5240. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5242. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5243. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5244. "7890123456789012345678901234567890",
  5245. body);
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. }
  5248. TEST_F(ServerTest, NoGzip) {
  5249. Headers headers;
  5250. headers.emplace("Accept-Encoding", "gzip, deflate");
  5251. auto res = cli_.Get("/nocompress", headers);
  5252. ASSERT_TRUE(res);
  5253. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5254. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5255. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5256. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5257. "7890123456789012345678901234567890",
  5258. res->body);
  5259. EXPECT_EQ(StatusCode::OK_200, res->status);
  5260. }
  5261. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5262. Headers headers;
  5263. headers.emplace("Accept-Encoding", "gzip, deflate");
  5264. std::string body;
  5265. auto res = cli_.Get("/nocompress", headers,
  5266. [&](const char *data, uint64_t data_length) {
  5267. EXPECT_EQ(100U, data_length);
  5268. body.append(data, data_length);
  5269. return true;
  5270. });
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5273. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. TEST_F(ServerTest, MultipartFormDataGzip) {
  5281. UploadFormDataItems items = {
  5282. {"key1", "test", "", ""},
  5283. {"key2", "--abcdefg123", "", ""},
  5284. };
  5285. cli_.set_compress(true);
  5286. auto res = cli_.Post("/compress-multipart", items);
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. }
  5290. #endif
  5291. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5292. TEST_F(ServerTest, Brotli) {
  5293. Headers headers;
  5294. headers.emplace("Accept-Encoding", "br");
  5295. auto res = cli_.Get("/compress", headers);
  5296. ASSERT_TRUE(res);
  5297. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5298. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5299. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5300. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5301. "7890123456789012345678901234567890",
  5302. res->body);
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. }
  5305. #endif
  5306. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5307. TEST_F(ServerTest, Zstd) {
  5308. Headers headers;
  5309. headers.emplace("Accept-Encoding", "zstd");
  5310. auto res = cli_.Get("/compress", headers);
  5311. ASSERT_TRUE(res);
  5312. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5313. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5314. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5315. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5316. "7890123456789012345678901234567890",
  5317. res->body);
  5318. EXPECT_EQ(StatusCode::OK_200, res->status);
  5319. }
  5320. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "");
  5323. auto res = cli_.Get("/compress", headers);
  5324. ASSERT_TRUE(res);
  5325. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5327. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5328. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5329. "7890123456789012345678901234567890",
  5330. res->body);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. }
  5333. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5334. Headers headers;
  5335. headers.emplace("Accept-Encoding", "zstd");
  5336. std::string body;
  5337. auto res = cli_.Get("/compress", headers,
  5338. [&](const char *data, uint64_t data_length) {
  5339. EXPECT_EQ(100U, data_length);
  5340. body.append(data, data_length);
  5341. return true;
  5342. });
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5353. Headers headers;
  5354. headers.emplace("Accept-Encoding", "zstd");
  5355. cli_.set_decompress(false);
  5356. auto res = cli_.Get("/compress", headers);
  5357. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5358. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5359. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5360. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5361. ASSERT_TRUE(res);
  5362. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5363. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5364. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. ASSERT_EQ(26U, res->body.size());
  5367. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5368. 0);
  5369. }
  5370. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5371. Headers headers;
  5372. headers.emplace("Accept-Encoding", "");
  5373. std::string body;
  5374. auto res = cli_.Get("/compress", headers,
  5375. [&](const char *data, uint64_t data_length) {
  5376. EXPECT_EQ(100U, data_length);
  5377. body.append(data, data_length);
  5378. return true;
  5379. });
  5380. ASSERT_TRUE(res);
  5381. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5382. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5384. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5385. "7890123456789012345678901234567890",
  5386. body);
  5387. EXPECT_EQ(StatusCode::OK_200, res->status);
  5388. }
  5389. TEST_F(ServerTest, NoZstd) {
  5390. Headers headers;
  5391. headers.emplace("Accept-Encoding", "zstd");
  5392. auto res = cli_.Get("/nocompress", headers);
  5393. ASSERT_TRUE(res);
  5394. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5395. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5396. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5398. "7890123456789012345678901234567890",
  5399. res->body);
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. }
  5402. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5403. Headers headers;
  5404. headers.emplace("Accept-Encoding", "zstd");
  5405. std::string body;
  5406. auto res = cli_.Get("/nocompress", headers,
  5407. [&](const char *data, uint64_t data_length) {
  5408. EXPECT_EQ(100U, data_length);
  5409. body.append(data, data_length);
  5410. return true;
  5411. });
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5414. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5417. "7890123456789012345678901234567890",
  5418. body);
  5419. EXPECT_EQ(StatusCode::OK_200, res->status);
  5420. }
  5421. // TODO: How to enable zstd ??
  5422. TEST_F(ServerTest, MultipartFormDataZstd) {
  5423. UploadFormDataItems items = {
  5424. {"key1", "test", "", ""},
  5425. {"key2", "--abcdefg123", "", ""},
  5426. };
  5427. Headers headers;
  5428. headers.emplace("Accept-Encoding", "zstd");
  5429. cli_.set_compress(true);
  5430. auto res = cli_.Post("/compress-multipart", headers, items);
  5431. ASSERT_TRUE(res);
  5432. EXPECT_EQ(StatusCode::OK_200, res->status);
  5433. }
  5434. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5435. Headers headers;
  5436. headers.emplace("Accept-Encoding", "zstd");
  5437. cli_.set_compress(true);
  5438. auto res = cli_.Put(
  5439. "/put", headers, 3,
  5440. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5441. sink.os << "PUT";
  5442. return true;
  5443. },
  5444. "text/plain");
  5445. ASSERT_TRUE(res);
  5446. EXPECT_EQ(StatusCode::OK_200, res->status);
  5447. EXPECT_EQ("PUT", res->body);
  5448. }
  5449. // Pre-compression logging tests
  5450. TEST_F(ServerTest, PreCompressionLogging) {
  5451. // Test data for compression (matches the actual /compress endpoint content)
  5452. const std::string test_content =
  5453. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5454. "3456789012345678901234567890";
  5455. // Variables to capture logging data
  5456. std::string pre_compression_body;
  5457. std::string pre_compression_content_type;
  5458. std::string pre_compression_content_encoding;
  5459. std::string post_compression_body;
  5460. std::string post_compression_content_type;
  5461. std::string post_compression_content_encoding;
  5462. // Set up pre-compression logger
  5463. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5464. const Response &res) {
  5465. pre_compression_body = res.body;
  5466. pre_compression_content_type = res.get_header_value("Content-Type");
  5467. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5468. });
  5469. // Set up post-compression logger
  5470. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5471. post_compression_body = res.body;
  5472. post_compression_content_type = res.get_header_value("Content-Type");
  5473. post_compression_content_encoding =
  5474. res.get_header_value("Content-Encoding");
  5475. });
  5476. // Test with gzip compression
  5477. Headers headers;
  5478. headers.emplace("Accept-Encoding", "gzip");
  5479. auto res = cli_.Get("/compress", headers);
  5480. // Verify response was compressed
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5484. // Verify pre-compression logger captured uncompressed content
  5485. EXPECT_EQ(test_content, pre_compression_body);
  5486. EXPECT_EQ("text/plain", pre_compression_content_type);
  5487. EXPECT_TRUE(pre_compression_content_encoding
  5488. .empty()); // No encoding header before compression
  5489. // Verify post-compression logger captured compressed content
  5490. EXPECT_NE(test_content,
  5491. post_compression_body); // Should be different after compression
  5492. EXPECT_EQ("text/plain", post_compression_content_type);
  5493. EXPECT_EQ("gzip", post_compression_content_encoding);
  5494. // Verify compressed content is smaller
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. Headers headers;
  5511. headers.emplace("Accept-Encoding", "br");
  5512. auto res = cli_.Get("/compress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5516. // Verify pre-compression content is uncompressed
  5517. EXPECT_EQ(test_content, pre_compression_body);
  5518. // Verify post-compression content is compressed
  5519. EXPECT_NE(test_content, post_compression_body);
  5520. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5521. }
  5522. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5523. const std::string test_content =
  5524. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5525. "3456789012345678901234567890";
  5526. std::string pre_compression_body;
  5527. std::string post_compression_body;
  5528. svr_.set_pre_compression_logger(
  5529. [&](const Request & /*req*/, const Response &res) {
  5530. pre_compression_body = res.body;
  5531. });
  5532. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5533. post_compression_body = res.body;
  5534. });
  5535. // Request without compression (use /nocompress endpoint)
  5536. Headers headers;
  5537. auto res = cli_.Get("/nocompress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5541. // Pre-compression logger should not be called when no compression is applied
  5542. EXPECT_TRUE(
  5543. pre_compression_body.empty()); // Pre-compression logger not called
  5544. EXPECT_EQ(
  5545. test_content,
  5546. post_compression_body); // Post-compression logger captures final content
  5547. }
  5548. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5549. const std::string test_content =
  5550. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5551. "3456789012345678901234567890";
  5552. std::string pre_compression_body;
  5553. bool pre_logger_called = false;
  5554. // Set only pre-compression logger
  5555. svr_.set_pre_compression_logger(
  5556. [&](const Request & /*req*/, const Response &res) {
  5557. pre_compression_body = res.body;
  5558. pre_logger_called = true;
  5559. });
  5560. Headers headers;
  5561. headers.emplace("Accept-Encoding", "gzip");
  5562. auto res = cli_.Get("/compress", headers);
  5563. ASSERT_TRUE(res);
  5564. EXPECT_EQ(StatusCode::OK_200, res->status);
  5565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5566. // Verify pre-compression logger was called
  5567. EXPECT_TRUE(pre_logger_called);
  5568. EXPECT_EQ(test_content, pre_compression_body);
  5569. }
  5570. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5571. {
  5572. // Test with Expect: 100-continue header - success case
  5573. // Server returns 100 Continue, client sends body, server returns 200 OK
  5574. Request req;
  5575. req.method = "POST";
  5576. req.path = "/post-large";
  5577. req.set_header("Expect", "100-continue");
  5578. req.body = LARGE_DATA;
  5579. Response res;
  5580. auto error = Error::Success;
  5581. cli_.set_keep_alive(true);
  5582. auto ret = cli_.send(req, res, error);
  5583. EXPECT_TRUE(ret);
  5584. EXPECT_EQ(StatusCode::OK_200, res.status);
  5585. EXPECT_EQ(LARGE_DATA, res.body);
  5586. }
  5587. {
  5588. // Test with Expect: 100-continue header - error case
  5589. // Client should not send the body when server returns an error
  5590. Request req;
  5591. req.method = "POST";
  5592. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5593. req.set_header("Expect", "100-continue");
  5594. req.body = LARGE_DATA;
  5595. Response res;
  5596. auto error = Error::Success;
  5597. auto start = std::chrono::high_resolution_clock::now();
  5598. cli_.set_keep_alive(true);
  5599. auto ret = cli_.send(req, res, error);
  5600. auto end = std::chrono::high_resolution_clock::now();
  5601. auto elapsed =
  5602. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5603. .count();
  5604. // With Expect: 100-continue, request completes successfully but with error
  5605. EXPECT_TRUE(ret);
  5606. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5607. EXPECT_EQ("close", res.get_header_value("Connection"));
  5608. EXPECT_FALSE(cli_.is_socket_open());
  5609. EXPECT_LE(elapsed, 200);
  5610. }
  5611. {
  5612. // Send an extra GET request to ensure error recovery without hanging
  5613. Request req;
  5614. req.method = "GET";
  5615. req.path = "/hi";
  5616. auto start = std::chrono::high_resolution_clock::now();
  5617. auto res = cli_.send(req);
  5618. auto end = std::chrono::high_resolution_clock::now();
  5619. auto elapsed =
  5620. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5621. .count();
  5622. ASSERT_TRUE(res);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. EXPECT_EQ("Hello World!", res->body);
  5625. EXPECT_LE(elapsed, 500);
  5626. }
  5627. }
  5628. TEST(ZstdDecompressor, ChunkedDecompression) {
  5629. std::string data;
  5630. for (size_t i = 0; i < 32 * 1024; ++i) {
  5631. data.push_back(static_cast<char>('a' + i % 26));
  5632. }
  5633. std::string compressed_data;
  5634. {
  5635. httplib::detail::zstd_compressor compressor;
  5636. bool result = compressor.compress(
  5637. data.data(), data.size(),
  5638. /*last=*/true,
  5639. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5640. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5641. compressed_data_size);
  5642. return true;
  5643. });
  5644. ASSERT_TRUE(result);
  5645. }
  5646. std::string decompressed_data;
  5647. {
  5648. httplib::detail::zstd_decompressor decompressor;
  5649. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5650. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5651. size_t chunk_size = 130;
  5652. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5653. chunk_begin += chunk_size) {
  5654. size_t current_chunk_size =
  5655. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5656. bool result = decompressor.decompress(
  5657. compressed_data.data() + chunk_begin, current_chunk_size,
  5658. [&](const char *decompressed_data_chunk,
  5659. size_t decompressed_data_chunk_size) {
  5660. decompressed_data.insert(decompressed_data.size(),
  5661. decompressed_data_chunk,
  5662. decompressed_data_chunk_size);
  5663. return true;
  5664. });
  5665. ASSERT_TRUE(result);
  5666. }
  5667. }
  5668. ASSERT_EQ(data, decompressed_data);
  5669. }
  5670. TEST(ZstdDecompressor, Decompress) {
  5671. std::string original_text = "Compressed with ZSTD";
  5672. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5673. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5674. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5675. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5676. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5677. std::string decompressed_data;
  5678. {
  5679. httplib::detail::zstd_decompressor decompressor;
  5680. bool result = decompressor.decompress(
  5681. compressed_data.data(), compressed_data.size(),
  5682. [&](const char *decompressed_data_chunk,
  5683. size_t decompressed_data_chunk_size) {
  5684. decompressed_data.insert(decompressed_data.size(),
  5685. decompressed_data_chunk,
  5686. decompressed_data_chunk_size);
  5687. return true;
  5688. });
  5689. ASSERT_TRUE(result);
  5690. }
  5691. ASSERT_EQ(original_text, decompressed_data);
  5692. }
  5693. #endif
  5694. // Sends a raw request to a server listening at HOST:PORT.
  5695. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5696. std::string *resp = nullptr) {
  5697. auto error = Error::Success;
  5698. auto client_sock = detail::create_client_socket(
  5699. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5700. /*connection_timeout_sec=*/5, 0,
  5701. /*read_timeout_sec=*/5, 0,
  5702. /*write_timeout_sec=*/5, 0, std::string(), error);
  5703. if (client_sock == INVALID_SOCKET) { return false; }
  5704. auto ret = detail::process_client_socket(
  5705. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5706. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5707. if (req.size() !=
  5708. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5709. return false;
  5710. }
  5711. char buf[512];
  5712. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5713. while (line_reader.getline()) {
  5714. if (resp) { *resp += line_reader.ptr(); }
  5715. }
  5716. return true;
  5717. });
  5718. detail::close_socket(client_sock);
  5719. return ret;
  5720. }
  5721. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5722. Server svr;
  5723. std::string header_value;
  5724. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5725. header_value = req.get_header_value("foo");
  5726. res.set_content("ok", "text/plain");
  5727. });
  5728. thread t = thread([&] { svr.listen(HOST, PORT); });
  5729. auto se = detail::scope_exit([&] {
  5730. svr.stop();
  5731. t.join();
  5732. ASSERT_FALSE(svr.is_running());
  5733. });
  5734. svr.wait_until_ready();
  5735. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5736. // like characters are not treated the same - use vertical tab and escape.
  5737. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5738. "foo: \t \v bar \x1B\t \r\n"
  5739. "Connection: close\r\n"
  5740. "\r\n";
  5741. std::string res;
  5742. ASSERT_TRUE(send_request(5, req, &res));
  5743. EXPECT_EQ(header_value, "");
  5744. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5745. }
  5746. // Sends a raw request and verifies that there isn't a crash or exception.
  5747. static void test_raw_request(const std::string &req,
  5748. std::string *out = nullptr) {
  5749. Server svr;
  5750. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5751. res.set_content("ok", "text/plain");
  5752. });
  5753. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5754. res.set_content("ok", "text/plain");
  5755. });
  5756. svr.Get("/header_field_value_check",
  5757. [&](const Request & /*req*/, Response &res) {
  5758. res.set_content("ok", "text/plain");
  5759. });
  5760. // Server read timeout must be longer than the client read timeout for the
  5761. // bug to reproduce, probably to force the server to process a request
  5762. // without a trailing blank line.
  5763. const time_t client_read_timeout_sec = 1;
  5764. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5765. bool listen_thread_ok = false;
  5766. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5767. auto se = detail::scope_exit([&] {
  5768. svr.stop();
  5769. t.join();
  5770. ASSERT_FALSE(svr.is_running());
  5771. EXPECT_TRUE(listen_thread_ok);
  5772. });
  5773. svr.wait_until_ready();
  5774. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5775. }
  5776. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5777. // A certain header line causes an exception if the header property is parsed
  5778. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5779. test_raw_request(
  5780. "GET /hi HTTP/1.1\r\n"
  5781. " : "
  5782. " "
  5783. " ");
  5784. }
  5785. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5786. // A certain header line causes an exception if the header property *name* is
  5787. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5788. // greedy matcher and requires backtracking when there are a lot of ":"
  5789. // characters.
  5790. // This occurs with libc++ but not libstdc++.
  5791. test_raw_request(
  5792. "GET /hi HTTP/1.1\r\n"
  5793. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5794. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5795. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5796. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5797. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5798. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5799. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5800. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5801. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5802. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5803. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5804. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5805. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5806. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5807. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5808. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5809. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5810. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5811. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5812. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5813. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5814. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5815. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5816. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5817. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5818. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5819. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5820. "&&&%%%");
  5821. }
  5822. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5823. // Make sure this doesn't crash the server.
  5824. // In a previous version of the header line regex, the "\r" rendered the line
  5825. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5826. // a new position where the leading white space ended and the field value
  5827. // began.
  5828. // The crash occurs with libc++ but not libstdc++.
  5829. test_raw_request("GET /hi HTTP/1.1\r\n"
  5830. "a:" +
  5831. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5832. "\r\n"
  5833. "\r\n");
  5834. }
  5835. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5836. std::string out;
  5837. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5838. "Content-Type: text/plain\r\n"
  5839. "Transfer-Encoding: chunked\r\n"
  5840. "\r\n"
  5841. "nothex\r\n",
  5842. &out);
  5843. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5844. }
  5845. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5846. std::string out;
  5847. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5848. "Content-Type: text/plain\r\n"
  5849. "Transfer-Encoding: chunked\r\n"
  5850. "\r\n"
  5851. "3\r\n"
  5852. "xyz\r\n"
  5853. "NaN\r\n",
  5854. &out);
  5855. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5856. }
  5857. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5858. std::string out;
  5859. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5860. "Content-Type: text/plain\r\n"
  5861. "Transfer-Encoding: chunked\r\n"
  5862. "\r\n"
  5863. // Length is too large for 64 bits.
  5864. "1ffffffffffffffff\r\n"
  5865. "xyz\r\n",
  5866. &out);
  5867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5868. }
  5869. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5870. test_raw_request("GET /hi HTTP/1.1\r\n"
  5871. "Content-Type: text/plain\r\n\r");
  5872. }
  5873. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5874. std::string out;
  5875. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5876. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5877. }
  5878. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5879. Server svr;
  5880. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5881. EXPECT_TRUE(!req.remote_addr.empty());
  5882. });
  5883. thread t = thread([&] { svr.listen(HOST, PORT); });
  5884. auto se = detail::scope_exit([&] {
  5885. svr.stop();
  5886. t.join();
  5887. ASSERT_FALSE(svr.is_running());
  5888. });
  5889. svr.wait_until_ready();
  5890. // Send an invalid request line to trigger Bad Request
  5891. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5892. std::string out;
  5893. ASSERT_TRUE(send_request(5, bad_req, &out));
  5894. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5895. }
  5896. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5897. std::string out;
  5898. std::string request(
  5899. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5900. test_raw_request(request, &out);
  5901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5902. }
  5903. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5904. std::string out;
  5905. std::string request(
  5906. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5907. test_raw_request(request, &out);
  5908. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5909. }
  5910. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5911. std::string out;
  5912. std::string request(
  5913. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5914. test_raw_request(request, &out);
  5915. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5916. }
  5917. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5918. std::string out;
  5919. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5920. "Test: \r\n\r\n",
  5921. &out);
  5922. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5923. }
  5924. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5925. Server svr;
  5926. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5927. res.set_header("Cache-Control", "no-cache");
  5928. res.set_chunked_content_provider(
  5929. "text/event-stream", [](size_t offset, DataSink &sink) {
  5930. std::string s = "data:";
  5931. s += std::to_string(offset);
  5932. s += "\n\n";
  5933. auto ret = sink.write(s.data(), s.size());
  5934. EXPECT_TRUE(ret);
  5935. std::this_thread::sleep_for(std::chrono::seconds(1));
  5936. return true;
  5937. });
  5938. });
  5939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5940. svr.wait_until_ready();
  5941. Client client(HOST, PORT);
  5942. const Headers headers = {{"Accept", "text/event-stream"}};
  5943. auto get_thread = std::thread([&client, &headers]() {
  5944. auto res = client.Get(
  5945. "/events", headers,
  5946. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5947. });
  5948. auto se = detail::scope_exit([&] {
  5949. svr.stop();
  5950. get_thread.join();
  5951. listen_thread.join();
  5952. ASSERT_FALSE(svr.is_running());
  5953. });
  5954. // Give GET time to get a few messages.
  5955. std::this_thread::sleep_for(std::chrono::seconds(2));
  5956. }
  5957. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5958. httplib::Server svr;
  5959. svr.Post("/hi",
  5960. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5961. res.status = StatusCode::OK_200;
  5962. });
  5963. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5964. svr.wait_until_ready();
  5965. Client cli(HOST, PORT);
  5966. auto res = cli.Post("/hi", "data", "text/plain");
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. svr.stop();
  5970. thread.join();
  5971. ASSERT_FALSE(svr.is_running());
  5972. res = cli.Post("/hi", "data", "text/plain");
  5973. ASSERT_FALSE(res);
  5974. }
  5975. TEST(ServerStopTest, ListenFailure) {
  5976. Server svr;
  5977. auto t = thread([&]() {
  5978. auto ret = svr.listen("????", PORT);
  5979. EXPECT_FALSE(ret);
  5980. });
  5981. svr.wait_until_ready();
  5982. svr.stop();
  5983. t.join();
  5984. }
  5985. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5986. TEST(ServerStopTest, Decommision) {
  5987. Server svr;
  5988. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5989. for (int i = 0; i < 4; i++) {
  5990. auto is_even = !(i % 2);
  5991. std::thread t{[&] {
  5992. try {
  5993. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5994. if (is_even) {
  5995. throw std::runtime_error("Some thing that happens to go wrong.");
  5996. }
  5997. svr.listen(HOST, PORT);
  5998. } catch (...) { svr.decommission(); }
  5999. }};
  6000. svr.wait_until_ready();
  6001. // Server is up
  6002. {
  6003. Client cli(HOST, PORT);
  6004. auto res = cli.Get("/hi");
  6005. if (is_even) {
  6006. EXPECT_FALSE(res);
  6007. } else {
  6008. EXPECT_TRUE(res);
  6009. EXPECT_EQ("hi...", res->body);
  6010. }
  6011. }
  6012. svr.stop();
  6013. t.join();
  6014. // Server is down...
  6015. {
  6016. Client cli(HOST, PORT);
  6017. auto res = cli.Get("/hi");
  6018. EXPECT_FALSE(res);
  6019. }
  6020. }
  6021. }
  6022. #endif
  6023. // Helper function for string body upload progress tests
  6024. template <typename SetupHandler, typename ClientCall>
  6025. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6026. ClientCall &&client_call,
  6027. const string &body) {
  6028. Server svr;
  6029. setup_handler(svr);
  6030. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6031. auto se = detail::scope_exit([&] {
  6032. svr.stop();
  6033. t.join();
  6034. });
  6035. svr.wait_until_ready();
  6036. Client cli(HOST, PORT);
  6037. vector<uint64_t> progress_values;
  6038. bool progress_called = false;
  6039. auto res =
  6040. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6041. progress_values.push_back(current);
  6042. progress_called = true;
  6043. return true;
  6044. });
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(200, res->status);
  6047. EXPECT_TRUE(progress_called);
  6048. }
  6049. TEST(UploadProgressTest, PostStringBodyBasic) {
  6050. TestStringBodyUploadProgress(
  6051. [](Server &svr) {
  6052. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6053. res.set_content("received", "text/plain");
  6054. });
  6055. },
  6056. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6057. return cli.Post("/test", body, "text/plain", progress_callback);
  6058. },
  6059. "test data for upload progress");
  6060. }
  6061. TEST(UploadProgressTest, PutStringBodyBasic) {
  6062. TestStringBodyUploadProgress(
  6063. [](Server &svr) {
  6064. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6065. res.set_content("put received", "text/plain");
  6066. });
  6067. },
  6068. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6069. return cli.Put("/test", body, "text/plain", progress_callback);
  6070. },
  6071. "put test data for upload progress");
  6072. }
  6073. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6074. TestStringBodyUploadProgress(
  6075. [](Server &svr) {
  6076. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6077. res.set_content("patch received", "text/plain");
  6078. });
  6079. },
  6080. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6081. return cli.Patch("/test", body, "text/plain", progress_callback);
  6082. },
  6083. "patch test data for upload progress");
  6084. }
  6085. // Helper function for content provider upload progress tests
  6086. template <typename SetupHandler, typename ClientCall>
  6087. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6088. ClientCall &&client_call) {
  6089. Server svr;
  6090. setup_handler(svr);
  6091. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6092. auto se = detail::scope_exit([&] {
  6093. svr.stop();
  6094. t.join();
  6095. });
  6096. svr.wait_until_ready();
  6097. Client cli(HOST, PORT);
  6098. vector<uint64_t> progress_values;
  6099. auto res =
  6100. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6101. progress_values.push_back(current);
  6102. return true;
  6103. });
  6104. ASSERT_TRUE(res);
  6105. EXPECT_EQ(200, res->status);
  6106. EXPECT_FALSE(progress_values.empty());
  6107. }
  6108. TEST(UploadProgressTest, PostContentProviderProgress) {
  6109. TestContentProviderUploadProgress(
  6110. [](Server &svr) {
  6111. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6112. res.set_content("provider received", "text/plain");
  6113. });
  6114. },
  6115. [](Client &cli, UploadProgress progress_callback) {
  6116. return cli.Post(
  6117. "/test", 10,
  6118. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6119. sink.os << "test data";
  6120. return true;
  6121. },
  6122. "text/plain", progress_callback);
  6123. });
  6124. }
  6125. // Helper function for multipart upload progress tests
  6126. template <typename SetupHandler, typename ClientCall>
  6127. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6128. ClientCall &&client_call,
  6129. const string &endpoint) {
  6130. Server svr;
  6131. setup_handler(svr);
  6132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6133. auto se = detail::scope_exit([&] {
  6134. svr.stop();
  6135. t.join();
  6136. });
  6137. svr.wait_until_ready();
  6138. Client cli(HOST, PORT);
  6139. vector<uint64_t> progress_values;
  6140. UploadFormDataItems items = {
  6141. {"field1", "value1", "", ""},
  6142. {"field2", "longer value for progress tracking test", "", ""},
  6143. {"file1", "file content data for upload progress", "test.txt",
  6144. "text/plain"}};
  6145. auto res = client_call(cli, endpoint, items,
  6146. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6147. progress_values.push_back(current);
  6148. return true;
  6149. });
  6150. ASSERT_TRUE(res);
  6151. EXPECT_EQ(200, res->status);
  6152. EXPECT_FALSE(progress_values.empty());
  6153. }
  6154. TEST(UploadProgressTest, PostMultipartProgress) {
  6155. TestMultipartUploadProgress(
  6156. [](Server &svr) {
  6157. svr.Post("/multipart", [](const Request &req, Response &res) {
  6158. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6159. res.set_content("multipart received", "text/plain");
  6160. });
  6161. },
  6162. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6163. UploadProgress progress_callback) {
  6164. return cli.Post(endpoint, items, progress_callback);
  6165. },
  6166. "/multipart");
  6167. }
  6168. // Helper function for basic download progress tests
  6169. template <typename SetupHandler, typename ClientCall>
  6170. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6171. ClientCall &&client_call, const string &endpoint,
  6172. size_t expected_content_size) {
  6173. Server svr;
  6174. setup_handler(svr);
  6175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6176. auto se = detail::scope_exit([&] {
  6177. svr.stop();
  6178. t.join();
  6179. });
  6180. svr.wait_until_ready();
  6181. Client cli(HOST, PORT);
  6182. vector<uint64_t> progress_values;
  6183. auto res = client_call(cli, endpoint,
  6184. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6185. progress_values.push_back(current);
  6186. return true;
  6187. });
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(200, res->status);
  6190. EXPECT_FALSE(progress_values.empty());
  6191. EXPECT_EQ(expected_content_size, res->body.size());
  6192. }
  6193. TEST(DownloadProgressTest, GetBasic) {
  6194. TestBasicDownloadProgress(
  6195. [](Server &svr) {
  6196. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6197. string content(1000, 'D');
  6198. res.set_content(content, "text/plain");
  6199. });
  6200. },
  6201. [](Client &cli, const string &endpoint,
  6202. DownloadProgress progress_callback) {
  6203. return cli.Get(endpoint, progress_callback);
  6204. },
  6205. "/download", 1000u);
  6206. }
  6207. // Helper function for content receiver download progress tests
  6208. template <typename SetupHandler, typename ClientCall>
  6209. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6210. ClientCall &&client_call,
  6211. const string &endpoint,
  6212. size_t expected_content_size) {
  6213. Server svr;
  6214. setup_handler(svr);
  6215. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6216. auto se = detail::scope_exit([&] {
  6217. svr.stop();
  6218. t.join();
  6219. });
  6220. svr.wait_until_ready();
  6221. Client cli(HOST, PORT);
  6222. vector<uint64_t> progress_values;
  6223. string received_body;
  6224. auto res = client_call(
  6225. cli, endpoint,
  6226. [&](const char *data, size_t data_length) -> bool {
  6227. received_body.append(data, data_length);
  6228. return true;
  6229. },
  6230. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6231. progress_values.push_back(current);
  6232. return true;
  6233. });
  6234. ASSERT_TRUE(res);
  6235. EXPECT_EQ(200, res->status);
  6236. EXPECT_FALSE(progress_values.empty());
  6237. EXPECT_EQ(expected_content_size, received_body.size());
  6238. EXPECT_TRUE(res->body.empty());
  6239. }
  6240. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6241. TestContentReceiverDownloadProgress(
  6242. [](Server &svr) {
  6243. svr.Get("/download-receiver",
  6244. [](const Request & /*req*/, Response &res) {
  6245. string content(2000, 'R');
  6246. res.set_content(content, "text/plain");
  6247. });
  6248. },
  6249. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6250. DownloadProgress progress_callback) {
  6251. return cli.Get(endpoint, content_receiver, progress_callback);
  6252. },
  6253. "/download-receiver", 2000u);
  6254. }
  6255. TEST(StreamingTest, NoContentLengthStreaming) {
  6256. Server svr;
  6257. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6258. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6259. if (offset < 6) {
  6260. sink.os << (offset < 3 ? "a" : "b");
  6261. } else {
  6262. sink.done();
  6263. }
  6264. return true;
  6265. });
  6266. });
  6267. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6268. auto listen_se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. listen_thread.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. });
  6273. svr.wait_until_ready();
  6274. Client client(HOST, PORT);
  6275. auto get_thread = std::thread([&client]() {
  6276. std::string s;
  6277. auto res =
  6278. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6279. s += std::string(data, len);
  6280. return true;
  6281. });
  6282. ASSERT_TRUE(res);
  6283. EXPECT_EQ(StatusCode::OK_200, res->status);
  6284. EXPECT_EQ("aaabbb", s);
  6285. });
  6286. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6287. // Give GET time to get a few messages.
  6288. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6289. }
  6290. TEST(MountTest, Unmount) {
  6291. Server svr;
  6292. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6293. auto se = detail::scope_exit([&] {
  6294. svr.stop();
  6295. listen_thread.join();
  6296. ASSERT_FALSE(svr.is_running());
  6297. });
  6298. svr.wait_until_ready();
  6299. Client cli("localhost", PORT);
  6300. svr.set_mount_point("/mount2", "./www2");
  6301. auto res = cli.Get("/");
  6302. ASSERT_TRUE(res);
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. res = cli.Get("/mount2/dir/test.html");
  6305. ASSERT_TRUE(res);
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. svr.set_mount_point("/", "./www");
  6308. res = cli.Get("/dir/");
  6309. ASSERT_TRUE(res);
  6310. EXPECT_EQ(StatusCode::OK_200, res->status);
  6311. svr.remove_mount_point("/");
  6312. res = cli.Get("/dir/");
  6313. ASSERT_TRUE(res);
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. svr.remove_mount_point("/mount2");
  6316. res = cli.Get("/mount2/dir/test.html");
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6319. }
  6320. TEST(MountTest, Redicect) {
  6321. Server svr;
  6322. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6323. auto se = detail::scope_exit([&] {
  6324. svr.stop();
  6325. listen_thread.join();
  6326. ASSERT_FALSE(svr.is_running());
  6327. });
  6328. svr.set_mount_point("/", "./www");
  6329. svr.wait_until_ready();
  6330. Client cli("localhost", PORT);
  6331. auto res = cli.Get("/dir/");
  6332. ASSERT_TRUE(res);
  6333. EXPECT_EQ(StatusCode::OK_200, res->status);
  6334. res = cli.Get("/dir");
  6335. ASSERT_TRUE(res);
  6336. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6337. res = cli.Get("/file");
  6338. ASSERT_TRUE(res);
  6339. EXPECT_EQ(StatusCode::OK_200, res->status);
  6340. res = cli.Get("/file/");
  6341. ASSERT_TRUE(res);
  6342. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6343. cli.set_follow_location(true);
  6344. res = cli.Get("/dir");
  6345. ASSERT_TRUE(res);
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. }
  6348. TEST(MountTest, MultibytesPathName) {
  6349. Server svr;
  6350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. listen_thread.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.set_mount_point("/", "./www");
  6357. svr.wait_until_ready();
  6358. Client cli("localhost", PORT);
  6359. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6360. ASSERT_TRUE(res);
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6363. }
  6364. TEST(KeepAliveTest, ReadTimeout) {
  6365. Server svr;
  6366. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6367. std::this_thread::sleep_for(std::chrono::seconds(2));
  6368. res.set_content("a", "text/plain");
  6369. });
  6370. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6371. res.set_content("b", "text/plain");
  6372. });
  6373. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6374. auto se = detail::scope_exit([&] {
  6375. svr.stop();
  6376. listen_thread.join();
  6377. ASSERT_FALSE(svr.is_running());
  6378. });
  6379. svr.wait_until_ready();
  6380. Client cli("localhost", PORT);
  6381. cli.set_keep_alive(true);
  6382. cli.set_read_timeout(std::chrono::seconds(1));
  6383. auto resa = cli.Get("/a");
  6384. ASSERT_FALSE(resa);
  6385. EXPECT_EQ(Error::Read, resa.error());
  6386. auto resb = cli.Get("/b");
  6387. ASSERT_TRUE(resb);
  6388. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6389. EXPECT_EQ("b", resb->body);
  6390. }
  6391. TEST(KeepAliveTest, MaxCount) {
  6392. size_t keep_alive_max_count = 3;
  6393. Server svr;
  6394. svr.set_keep_alive_max_count(keep_alive_max_count);
  6395. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6396. res.set_content("Hello World!", "text/plain");
  6397. });
  6398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6399. auto se = detail::scope_exit([&] {
  6400. svr.stop();
  6401. listen_thread.join();
  6402. ASSERT_FALSE(svr.is_running());
  6403. });
  6404. svr.wait_until_ready();
  6405. Client cli(HOST, PORT);
  6406. cli.set_keep_alive(true);
  6407. for (size_t i = 0; i < 5; i++) {
  6408. auto result = cli.Get("/hi");
  6409. ASSERT_TRUE(result);
  6410. EXPECT_EQ(StatusCode::OK_200, result->status);
  6411. if (i == keep_alive_max_count - 1) {
  6412. EXPECT_EQ("close", result->get_header_value("Connection"));
  6413. } else {
  6414. EXPECT_FALSE(result->has_header("Connection"));
  6415. }
  6416. }
  6417. }
  6418. TEST(KeepAliveTest, Issue1041) {
  6419. Server svr;
  6420. svr.set_keep_alive_timeout(3);
  6421. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6422. res.set_content("Hello World!", "text/plain");
  6423. });
  6424. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6425. auto se = detail::scope_exit([&] {
  6426. svr.stop();
  6427. listen_thread.join();
  6428. ASSERT_FALSE(svr.is_running());
  6429. });
  6430. svr.wait_until_ready();
  6431. Client cli(HOST, PORT);
  6432. cli.set_keep_alive(true);
  6433. auto result = cli.Get("/hi");
  6434. ASSERT_TRUE(result);
  6435. EXPECT_EQ(StatusCode::OK_200, result->status);
  6436. std::this_thread::sleep_for(std::chrono::seconds(5));
  6437. result = cli.Get("/hi");
  6438. ASSERT_TRUE(result);
  6439. EXPECT_EQ(StatusCode::OK_200, result->status);
  6440. }
  6441. TEST(KeepAliveTest, Issue1959) {
  6442. Server svr;
  6443. svr.set_keep_alive_timeout(5);
  6444. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6445. res.set_content("a", "text/plain");
  6446. });
  6447. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6448. auto se = detail::scope_exit([&] {
  6449. if (!svr.is_running()) return;
  6450. svr.stop();
  6451. listen_thread.join();
  6452. ASSERT_FALSE(svr.is_running());
  6453. });
  6454. svr.wait_until_ready();
  6455. Client cli("localhost", PORT);
  6456. cli.set_keep_alive(true);
  6457. using namespace std::chrono;
  6458. auto start = steady_clock::now();
  6459. cli.Get("/a");
  6460. svr.stop();
  6461. listen_thread.join();
  6462. auto end = steady_clock::now();
  6463. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6464. EXPECT_LT(elapsed, 5000);
  6465. }
  6466. #ifdef CPPHTTPLIB_SSL_ENABLED
  6467. TEST(KeepAliveTest, SSLClientReconnection) {
  6468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6469. ASSERT_TRUE(svr.is_valid());
  6470. svr.set_keep_alive_timeout(1);
  6471. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6472. res.set_content("Hello World!", "text/plain");
  6473. });
  6474. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6475. auto se = detail::scope_exit([&] {
  6476. svr.stop();
  6477. listen_thread.join();
  6478. ASSERT_FALSE(svr.is_running());
  6479. });
  6480. svr.wait_until_ready();
  6481. SSLClient cli(HOST, PORT);
  6482. cli.enable_server_certificate_verification(false);
  6483. cli.set_keep_alive(true);
  6484. auto result = cli.Get("/hi");
  6485. ASSERT_TRUE(result);
  6486. EXPECT_EQ(StatusCode::OK_200, result->status);
  6487. result = cli.Get("/hi");
  6488. ASSERT_TRUE(result);
  6489. EXPECT_EQ(StatusCode::OK_200, result->status);
  6490. std::this_thread::sleep_for(std::chrono::seconds(2));
  6491. // Recoonect
  6492. result = cli.Get("/hi");
  6493. ASSERT_TRUE(result);
  6494. EXPECT_EQ(StatusCode::OK_200, result->status);
  6495. result = cli.Get("/hi");
  6496. ASSERT_TRUE(result);
  6497. EXPECT_EQ(StatusCode::OK_200, result->status);
  6498. }
  6499. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6501. ASSERT_TRUE(svr.is_valid());
  6502. svr.set_keep_alive_timeout(1);
  6503. std::string content = "reconnect";
  6504. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6505. res.set_content("Hello World!", "text/plain");
  6506. });
  6507. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6508. auto se = detail::scope_exit([&] {
  6509. svr.stop();
  6510. listen_thread.join();
  6511. ASSERT_FALSE(svr.is_running());
  6512. });
  6513. svr.wait_until_ready();
  6514. SSLClient cli(HOST, PORT);
  6515. cli.enable_server_certificate_verification(false);
  6516. cli.set_keep_alive(true);
  6517. auto result = cli.Post(
  6518. "/hi", content.size(),
  6519. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6520. sink.write(content.c_str(), content.size());
  6521. return true;
  6522. },
  6523. "text/plain");
  6524. ASSERT_TRUE(result);
  6525. EXPECT_EQ(200, result->status);
  6526. std::this_thread::sleep_for(std::chrono::seconds(2));
  6527. // Recoonect
  6528. result = cli.Post(
  6529. "/hi", content.size(),
  6530. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6531. sink.write(content.c_str(), content.size());
  6532. return true;
  6533. },
  6534. "text/plain");
  6535. ASSERT_TRUE(result);
  6536. EXPECT_EQ(200, result->status);
  6537. result = cli.Post(
  6538. "/hi", content.size(),
  6539. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6540. sink.write(content.c_str(), content.size());
  6541. return true;
  6542. },
  6543. "text/plain");
  6544. ASSERT_TRUE(result);
  6545. EXPECT_EQ(200, result->status);
  6546. }
  6547. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6548. using namespace httplib::tls;
  6549. {
  6550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6551. ASSERT_TRUE(svr.is_valid());
  6552. svr.Get("/sni", [&](const Request &req, Response &res) {
  6553. std::string expected = req.sni();
  6554. EXPECT_EQ(expected, req.get_param_value("expected"));
  6555. res.set_content("ok", "text/plain");
  6556. });
  6557. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6558. auto se = detail::scope_exit([&] {
  6559. svr.stop();
  6560. listen_thread.join();
  6561. ASSERT_FALSE(svr.is_running());
  6562. });
  6563. svr.wait_until_ready();
  6564. {
  6565. SSLClient cli("localhost", PORT);
  6566. cli.enable_server_certificate_verification(false);
  6567. auto res = cli.Get("/sni?expected=localhost");
  6568. ASSERT_TRUE(res);
  6569. }
  6570. {
  6571. SSLClient cli("::1", PORT);
  6572. cli.enable_server_certificate_verification(false);
  6573. auto res = cli.Get("/sni?expected=");
  6574. // NOTE: This may fail if the server is listening on IPv4 only
  6575. // (e.g., when localhost resolves to 127.0.0.1 only)
  6576. if (res) {
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. } else {
  6579. EXPECT_EQ(Error::Connection, res.error());
  6580. }
  6581. }
  6582. }
  6583. }
  6584. #endif
  6585. TEST(ClientProblemDetectionTest, ContentProvider) {
  6586. Server svr;
  6587. size_t content_length = 1024 * 1024;
  6588. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6589. res.set_content_provider(
  6590. content_length, "text/plain",
  6591. [&](size_t offset, size_t length, DataSink &sink) {
  6592. auto out_len = std::min(length, static_cast<size_t>(1024));
  6593. std::string out(out_len, '@');
  6594. sink.write(out.data(), out_len);
  6595. return offset < 4096;
  6596. },
  6597. [](bool success) { ASSERT_FALSE(success); });
  6598. });
  6599. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6600. res.set_content_provider(
  6601. 0, "text/plain",
  6602. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6603. EXPECT_TRUE(false);
  6604. return true;
  6605. },
  6606. [](bool success) { ASSERT_FALSE(success); });
  6607. });
  6608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6609. auto se = detail::scope_exit([&] {
  6610. svr.stop();
  6611. listen_thread.join();
  6612. ASSERT_FALSE(svr.is_running());
  6613. });
  6614. svr.wait_until_ready();
  6615. Client cli("localhost", PORT);
  6616. {
  6617. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6618. size_t /*data_length*/) { return false; });
  6619. ASSERT_FALSE(res);
  6620. }
  6621. {
  6622. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6623. size_t /*data_length*/) { return false; });
  6624. ASSERT_TRUE(res);
  6625. }
  6626. }
  6627. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6628. Server svr;
  6629. svr.set_error_handler([](Request const &, Response &res) -> void {
  6630. res.set_chunked_content_provider(
  6631. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6632. sink.os << "hello";
  6633. sink.os << "world";
  6634. sink.done();
  6635. return true;
  6636. });
  6637. });
  6638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6639. auto se = detail::scope_exit([&] {
  6640. svr.stop();
  6641. listen_thread.join();
  6642. ASSERT_FALSE(svr.is_running());
  6643. });
  6644. svr.wait_until_ready();
  6645. Client cli("localhost", PORT);
  6646. auto res = cli.Get("/");
  6647. ASSERT_TRUE(res);
  6648. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6649. EXPECT_EQ("helloworld", res->body);
  6650. }
  6651. TEST(LongPollingTest, ClientCloseDetection) {
  6652. Server svr;
  6653. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6654. res.set_chunked_content_provider(
  6655. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6656. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6657. sink.os << "hello";
  6658. auto count = 10;
  6659. while (count > 0 && sink.is_writable()) {
  6660. this_thread::sleep_for(chrono::milliseconds(10));
  6661. count--;
  6662. }
  6663. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6664. return true;
  6665. });
  6666. });
  6667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6668. auto se = detail::scope_exit([&] {
  6669. svr.stop();
  6670. listen_thread.join();
  6671. ASSERT_FALSE(svr.is_running());
  6672. });
  6673. svr.wait_until_ready();
  6674. Client cli("localhost", PORT);
  6675. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6676. EXPECT_EQ("hello", string(data, data_length));
  6677. return false; // close the socket immediately.
  6678. });
  6679. ASSERT_FALSE(res);
  6680. }
  6681. TEST(GetWithParametersTest, GetWithParameters) {
  6682. Server svr;
  6683. svr.Get("/", [&](const Request &req, Response &) {
  6684. EXPECT_EQ("world", req.get_param_value("hello"));
  6685. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6686. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6687. });
  6688. svr.Get("/params", [&](const Request &req, Response &) {
  6689. EXPECT_EQ("world", req.get_param_value("hello"));
  6690. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6691. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6692. });
  6693. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6694. EXPECT_EQ("resource-id", req.matches[1]);
  6695. EXPECT_EQ("foo", req.get_param_value("param1"));
  6696. EXPECT_EQ("bar", req.get_param_value("param2"));
  6697. });
  6698. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6699. EXPECT_EQ("user-id", req.path_params.at("id"));
  6700. EXPECT_EQ("foo", req.get_param_value("param1"));
  6701. EXPECT_EQ("bar", req.get_param_value("param2"));
  6702. });
  6703. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6704. auto se = detail::scope_exit([&] {
  6705. svr.stop();
  6706. listen_thread.join();
  6707. ASSERT_FALSE(svr.is_running());
  6708. });
  6709. svr.wait_until_ready();
  6710. {
  6711. Client cli(HOST, PORT);
  6712. Params params;
  6713. params.emplace("hello", "world");
  6714. params.emplace("hello2", "world2");
  6715. params.emplace("hello3", "world3");
  6716. auto res = cli.Get("/", params, Headers{});
  6717. ASSERT_TRUE(res);
  6718. EXPECT_EQ(StatusCode::OK_200, res->status);
  6719. }
  6720. {
  6721. Client cli(HOST, PORT);
  6722. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6723. ASSERT_TRUE(res);
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. }
  6726. {
  6727. Client cli(HOST, PORT);
  6728. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6729. ASSERT_TRUE(res);
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. }
  6732. {
  6733. Client cli(HOST, PORT);
  6734. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6735. ASSERT_TRUE(res);
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. }
  6738. }
  6739. TEST(GetWithParametersTest, GetWithParameters2) {
  6740. Server svr;
  6741. svr.Get("/", [&](const Request &req, Response &res) {
  6742. auto text = req.get_param_value("hello");
  6743. res.set_content(text, "text/plain");
  6744. });
  6745. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6746. auto se = detail::scope_exit([&] {
  6747. svr.stop();
  6748. listen_thread.join();
  6749. ASSERT_FALSE(svr.is_running());
  6750. });
  6751. svr.wait_until_ready();
  6752. Client cli("localhost", PORT);
  6753. Params params;
  6754. params.emplace("hello", "world");
  6755. std::string body;
  6756. auto res = cli.Get("/", params, Headers{},
  6757. [&](const char *data, size_t data_length) {
  6758. body.append(data, data_length);
  6759. return true;
  6760. });
  6761. ASSERT_TRUE(res);
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ("world", body);
  6764. }
  6765. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6766. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6767. auto host = "httpcan.org";
  6768. auto path = std::string{"/range/32"};
  6769. #else
  6770. auto host = "nghttp2.org";
  6771. auto path = std::string{"/httpbin/range/32"};
  6772. #endif
  6773. #ifdef CPPHTTPLIB_SSL_ENABLED
  6774. SSLClient cli(host);
  6775. #else
  6776. Client cli(host);
  6777. #endif
  6778. cli.set_default_headers({make_range_header({{1, 10}})});
  6779. cli.set_connection_timeout(5);
  6780. {
  6781. auto res = cli.Get(path);
  6782. ASSERT_TRUE(res);
  6783. EXPECT_EQ("bcdefghijk", res->body);
  6784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6785. }
  6786. {
  6787. auto res = cli.Get(path);
  6788. ASSERT_TRUE(res);
  6789. EXPECT_EQ("bcdefghijk", res->body);
  6790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6791. }
  6792. }
  6793. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6794. Server svr;
  6795. svr.set_default_headers({{"Hello", "World"}});
  6796. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6797. res.set_content("ok", "text/plain");
  6798. });
  6799. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6800. auto se = detail::scope_exit([&] {
  6801. svr.stop();
  6802. listen_thread.join();
  6803. ASSERT_FALSE(svr.is_running());
  6804. });
  6805. svr.wait_until_ready();
  6806. Client cli("localhost", PORT);
  6807. auto res = cli.Get("/");
  6808. ASSERT_TRUE(res);
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. EXPECT_EQ("ok", res->body);
  6811. EXPECT_EQ("World", res->get_header_value("Hello"));
  6812. }
  6813. #ifdef CPPHTTPLIB_SSL_ENABLED
  6814. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6816. ASSERT_TRUE(svr.is_valid());
  6817. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6818. std::this_thread::sleep_for(std::chrono::seconds(2));
  6819. res.set_content("a", "text/plain");
  6820. });
  6821. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6822. res.set_content("b", "text/plain");
  6823. });
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.wait_until_ready();
  6831. SSLClient cli("localhost", PORT);
  6832. cli.enable_server_certificate_verification(false);
  6833. cli.set_keep_alive(true);
  6834. cli.set_read_timeout(std::chrono::seconds(1));
  6835. auto resa = cli.Get("/a");
  6836. ASSERT_TRUE(!resa);
  6837. EXPECT_EQ(Error::Read, resa.error());
  6838. auto resb = cli.Get("/b");
  6839. ASSERT_TRUE(resb);
  6840. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6841. EXPECT_EQ("b", resb->body);
  6842. }
  6843. #endif
  6844. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6845. protected:
  6846. ServerTestWithAI_PASSIVE()
  6847. : cli_(HOST, PORT)
  6848. #ifdef CPPHTTPLIB_SSL_ENABLED
  6849. ,
  6850. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6851. #endif
  6852. {
  6853. #ifdef CPPHTTPLIB_SSL_ENABLED
  6854. cli_.enable_server_certificate_verification(false);
  6855. #endif
  6856. }
  6857. virtual void SetUp() {
  6858. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6859. res.set_content("Hello World!", "text/plain");
  6860. });
  6861. t_ = thread(
  6862. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6863. svr_.wait_until_ready();
  6864. }
  6865. virtual void TearDown() {
  6866. svr_.stop();
  6867. t_.join();
  6868. }
  6869. #ifdef CPPHTTPLIB_SSL_ENABLED
  6870. SSLClient cli_;
  6871. SSLServer svr_;
  6872. #else
  6873. Client cli_;
  6874. Server svr_;
  6875. #endif
  6876. thread t_;
  6877. };
  6878. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6879. auto res = cli_.Get("/hi");
  6880. ASSERT_TRUE(res);
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6883. EXPECT_EQ("Hello World!", res->body);
  6884. }
  6885. class ServerUpDownTest : public ::testing::Test {
  6886. protected:
  6887. ServerUpDownTest() : cli_(HOST, PORT) {}
  6888. virtual void SetUp() {
  6889. t_ = thread([&]() {
  6890. svr_.bind_to_any_port(HOST);
  6891. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6892. ASSERT_TRUE(svr_.listen_after_bind());
  6893. });
  6894. svr_.wait_until_ready();
  6895. }
  6896. virtual void TearDown() {
  6897. svr_.stop();
  6898. t_.join();
  6899. }
  6900. Client cli_;
  6901. Server svr_;
  6902. thread t_;
  6903. };
  6904. TEST_F(ServerUpDownTest, QuickStartStop) {
  6905. // Should not crash, especially when run with
  6906. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6907. }
  6908. class PayloadMaxLengthTest : public ::testing::Test {
  6909. protected:
  6910. PayloadMaxLengthTest()
  6911. : cli_(HOST, PORT)
  6912. #ifdef CPPHTTPLIB_SSL_ENABLED
  6913. ,
  6914. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6915. #endif
  6916. {
  6917. #ifdef CPPHTTPLIB_SSL_ENABLED
  6918. cli_.enable_server_certificate_verification(false);
  6919. #endif
  6920. }
  6921. virtual void SetUp() {
  6922. svr_.set_payload_max_length(8);
  6923. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6924. res.set_content("test", "text/plain");
  6925. });
  6926. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6927. svr_.wait_until_ready();
  6928. }
  6929. virtual void TearDown() {
  6930. svr_.stop();
  6931. t_.join();
  6932. }
  6933. #ifdef CPPHTTPLIB_SSL_ENABLED
  6934. SSLClient cli_;
  6935. SSLServer svr_;
  6936. #else
  6937. Client cli_;
  6938. Server svr_;
  6939. #endif
  6940. thread t_;
  6941. };
  6942. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6943. auto res = cli_.Post("/test", "123456789", "text/plain");
  6944. ASSERT_TRUE(res);
  6945. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6946. res = cli_.Post("/test", "12345678", "text/plain");
  6947. ASSERT_TRUE(res);
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6951. // Test chunked encoding with payload exceeding the 8-byte limit
  6952. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6953. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6954. ASSERT_TRUE(res);
  6955. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6956. }
  6957. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6958. // Test chunked encoding with payload within the 8-byte limit
  6959. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6960. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6961. ASSERT_TRUE(res);
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. }
  6964. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6965. // Test using send_request to send chunked data exceeding payload limit
  6966. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6967. "Host: " +
  6968. std::string(HOST) + ":" + std::to_string(PORT) +
  6969. "\r\n"
  6970. "Transfer-Encoding: chunked\r\n"
  6971. "Connection: close\r\n"
  6972. "\r\n"
  6973. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6974. "0123456789\r\n"
  6975. "0\r\n" // End chunk
  6976. "\r\n";
  6977. std::string response;
  6978. bool result = send_request(1, chunked_request, &response);
  6979. if (!result) {
  6980. // If send_request fails, it might be because the server closed the
  6981. // connection due to payload limit enforcement, which is acceptable
  6982. SUCCEED()
  6983. << "Server rejected oversized chunked request (connection closed)";
  6984. } else {
  6985. // If we got a response, check if it's an error response or connection was
  6986. // closed early Short response length indicates connection was closed due to
  6987. // payload limit
  6988. if (response.length() <= 10) {
  6989. SUCCEED() << "Server closed connection for oversized chunked request";
  6990. } else {
  6991. // Check for error status codes
  6992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6993. response.find("Payload Too Large") != std::string::npos ||
  6994. response.find("400") != std::string::npos);
  6995. }
  6996. }
  6997. }
  6998. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6999. // Test request without Content-Length header exceeding payload limit
  7000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7001. "Host: " +
  7002. std::string(HOST) + ":" +
  7003. std::to_string(PORT) +
  7004. "\r\n"
  7005. "Connection: close\r\n"
  7006. "\r\n";
  7007. // Add payload exceeding the 8-byte limit
  7008. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7009. request_without_content_length += large_payload;
  7010. std::string response;
  7011. bool result = send_request(1, request_without_content_length, &response);
  7012. if (!result) {
  7013. // If send_request fails, server likely closed connection due to payload
  7014. // limit
  7015. SUCCEED() << "Server rejected oversized request without Content-Length "
  7016. "(connection closed)";
  7017. } else {
  7018. // Check if server responded with error or closed connection early
  7019. if (response.length() <= 10) {
  7020. SUCCEED() << "Server closed connection for oversized request without "
  7021. "Content-Length";
  7022. } else {
  7023. // Check for error status codes
  7024. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7025. response.find("Payload Too Large") != std::string::npos ||
  7026. response.find("400") != std::string::npos);
  7027. }
  7028. }
  7029. }
  7030. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7031. // Test request without Content-Length header within payload limit
  7032. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7033. "Host: " +
  7034. std::string(HOST) + ":" +
  7035. std::to_string(PORT) +
  7036. "\r\n"
  7037. "Connection: close\r\n"
  7038. "\r\n";
  7039. // Add payload within the 8-byte limit
  7040. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7041. request_without_content_length += small_payload;
  7042. std::string response;
  7043. bool result = send_request(1, request_without_content_length, &response);
  7044. // For requests without Content-Length, the server may have different behavior
  7045. // The key is that it should not reject due to payload limit for small
  7046. // payloads
  7047. if (result) {
  7048. // Check for any HTTP response (success or error, but not connection closed)
  7049. if (response.length() > 10) {
  7050. SUCCEED()
  7051. << "Server processed request without Content-Length within limit";
  7052. } else {
  7053. // Short response might indicate connection closed, which is acceptable
  7054. SUCCEED() << "Server closed connection for request without "
  7055. "Content-Length (acceptable behavior)";
  7056. }
  7057. } else {
  7058. // Connection failure might be due to protocol requirements
  7059. SUCCEED() << "Connection issue with request without Content-Length "
  7060. "(environment-specific)";
  7061. }
  7062. }
  7063. class LargePayloadMaxLengthTest : public ::testing::Test {
  7064. protected:
  7065. LargePayloadMaxLengthTest()
  7066. : cli_(HOST, PORT)
  7067. #ifdef CPPHTTPLIB_SSL_ENABLED
  7068. ,
  7069. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7070. #endif
  7071. {
  7072. #ifdef CPPHTTPLIB_SSL_ENABLED
  7073. cli_.enable_server_certificate_verification(false);
  7074. #endif
  7075. }
  7076. virtual void SetUp() {
  7077. // Set 10MB payload limit
  7078. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7079. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7080. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7081. res.set_content("Large payload test", "text/plain");
  7082. });
  7083. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7084. svr_.wait_until_ready();
  7085. }
  7086. virtual void TearDown() {
  7087. svr_.stop();
  7088. t_.join();
  7089. }
  7090. #ifdef CPPHTTPLIB_SSL_ENABLED
  7091. SSLClient cli_;
  7092. SSLServer svr_;
  7093. #else
  7094. Client cli_;
  7095. Server svr_;
  7096. #endif
  7097. thread t_;
  7098. };
  7099. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7100. // Test chunked encoding with payload within 10MB limit
  7101. std::string medium_payload(5 * 1024 * 1024,
  7102. 'A'); // 5MB payload, within 10MB limit
  7103. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7104. ASSERT_TRUE(res);
  7105. EXPECT_EQ(StatusCode::OK_200, res->status);
  7106. }
  7107. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7108. // Test chunked encoding with payload exceeding 10MB limit
  7109. std::string large_payload(12 * 1024 * 1024,
  7110. 'B'); // 12MB payload, exceeds 10MB limit
  7111. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7112. ASSERT_TRUE(res);
  7113. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7114. }
  7115. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7116. // Test request without Content-Length header within 10MB limit
  7117. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7118. "Host: " +
  7119. std::string(HOST) + ":" +
  7120. std::to_string(PORT) +
  7121. "\r\n"
  7122. "Connection: close\r\n"
  7123. "\r\n";
  7124. // Add 1MB payload (within 10MB limit)
  7125. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7126. request_without_content_length += medium_payload;
  7127. std::string response;
  7128. bool result = send_request(5, request_without_content_length, &response);
  7129. if (result) {
  7130. // Should get a proper HTTP response for payloads within limit
  7131. if (response.length() > 10) {
  7132. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7133. "10MB limit";
  7134. } else {
  7135. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7136. "Content-Length)";
  7137. }
  7138. } else {
  7139. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7140. }
  7141. }
  7142. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7143. // Test request without Content-Length header exceeding 10MB limit
  7144. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7145. "Host: " +
  7146. std::string(HOST) + ":" +
  7147. std::to_string(PORT) +
  7148. "\r\n"
  7149. "Connection: close\r\n"
  7150. "\r\n";
  7151. // Add 12MB payload (exceeds 10MB limit)
  7152. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7153. request_without_content_length += large_payload;
  7154. std::string response;
  7155. bool result = send_request(10, request_without_content_length, &response);
  7156. if (!result) {
  7157. // Server should close connection due to payload limit
  7158. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7159. "(connection closed)";
  7160. } else {
  7161. // Check for error response
  7162. if (response.length() <= 10) {
  7163. SUCCEED()
  7164. << "Server closed connection for 12MB request exceeding 10MB limit";
  7165. } else {
  7166. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7167. response.find("Payload Too Large") != std::string::npos ||
  7168. response.find("400") != std::string::npos);
  7169. }
  7170. }
  7171. }
  7172. TEST(HostAndPortPropertiesTest, NoSSL) {
  7173. httplib::Client cli("www.google.com", 1234);
  7174. ASSERT_EQ("www.google.com", cli.host());
  7175. ASSERT_EQ(1234, cli.port());
  7176. }
  7177. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7178. httplib::Client cli("www.google.com:1234");
  7179. ASSERT_EQ("www.google.com", cli.host());
  7180. ASSERT_EQ(1234, cli.port());
  7181. }
  7182. #ifdef CPPHTTPLIB_SSL_ENABLED
  7183. TEST(HostAndPortPropertiesTest, SSL) {
  7184. httplib::SSLClient cli("www.google.com");
  7185. ASSERT_EQ("www.google.com", cli.host());
  7186. ASSERT_EQ(443, cli.port());
  7187. }
  7188. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7189. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7190. std::string cert;
  7191. read_file(CA_CERT_FILE, cert);
  7192. httplib::SSLClient httplib_client("www.google.com");
  7193. // Load CA store first time
  7194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7195. // Load CA store second time (update)
  7196. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7197. // Verify client is still valid and can make connections
  7198. httplib_client.enable_server_certificate_verification(true);
  7199. auto res = httplib_client.Get("/");
  7200. ASSERT_TRUE(res);
  7201. // Google may return 200 or 301 depending on various factors
  7202. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7203. res->status == StatusCode::MovedPermanently_301);
  7204. }
  7205. TEST(SSLClientTest, ServerNameIndication_Online) {
  7206. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7207. auto host = "httpcan.org";
  7208. auto path = std::string{"/get"};
  7209. #else
  7210. auto host = "nghttp2.org";
  7211. auto path = std::string{"/httpbin/get"};
  7212. #endif
  7213. SSLClient cli(host, 443);
  7214. auto res = cli.Get(path);
  7215. ASSERT_TRUE(res);
  7216. ASSERT_EQ(StatusCode::OK_200, res->status);
  7217. }
  7218. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7219. // Use a site that will cause SSL verification failure due to self-signed cert
  7220. SSLClient cli("self-signed.badssl.com", 443);
  7221. cli.enable_server_certificate_verification(true);
  7222. auto res = cli.Get("/");
  7223. ASSERT_TRUE(!res);
  7224. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7225. // Verify backend error is captured for SSLServerVerification
  7226. // This occurs when certificate verification fails
  7227. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7228. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7229. EXPECT_NE(0UL, res.ssl_backend_error());
  7230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7231. // For OpenSSL, ssl_error is 0 for verification errors
  7232. EXPECT_EQ(0, res.ssl_error());
  7233. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7234. res.ssl_backend_error());
  7235. #endif
  7236. }
  7237. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7238. // Use a site where hostname doesn't match the certificate
  7239. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7240. SSLClient cli("wrong.host.badssl.com", 443);
  7241. cli.enable_server_certificate_verification(true);
  7242. cli.enable_server_hostname_verification(true);
  7243. auto res = cli.Get("/");
  7244. ASSERT_TRUE(!res);
  7245. // The error type depends on when hostname verification occurs:
  7246. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7247. // - Mbed TLS: SSLServerVerification (during handshake)
  7248. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7249. res.error() == Error::SSLServerVerification);
  7250. // Verify backend error is captured for hostname verification failure
  7251. EXPECT_NE(0UL, res.ssl_backend_error());
  7252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7253. // For OpenSSL, ssl_error is 0 for verification errors
  7254. EXPECT_EQ(0, res.ssl_error());
  7255. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7256. res.ssl_backend_error());
  7257. #endif
  7258. }
  7259. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7260. Client cli("https://google.com");
  7261. auto res = cli.Get("/");
  7262. ASSERT_TRUE(res);
  7263. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7264. }
  7265. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7266. SSLClient cli("google.com");
  7267. cli.set_ca_cert_path(CA_CERT_FILE);
  7268. auto res = cli.Get("/");
  7269. ASSERT_TRUE(res);
  7270. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7271. }
  7272. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7273. SSLClient cli("google.com");
  7274. cli.enable_server_certificate_verification(true);
  7275. cli.set_ca_cert_path("hello");
  7276. auto res = cli.Get("/");
  7277. ASSERT_TRUE(!res);
  7278. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7279. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7280. // should be set
  7281. EXPECT_EQ(0, res.ssl_error());
  7282. // Verify backend error is captured for SSLLoadingCerts
  7283. // This error occurs when loading CA certificates fails
  7284. EXPECT_NE(0UL, res.ssl_backend_error());
  7285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7286. // OpenSSL specific error codes:
  7287. // > openssl errstr 0x80000002
  7288. // error:80000002:system library::No such file or directory
  7289. // > openssl errstr 0xA000126
  7290. // error:0A000126:SSL routines::unexpected eof while reading
  7291. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  7292. res.ssl_backend_error() == 0xA000126);
  7293. #endif
  7294. }
  7295. TEST(SSLClientTest, ServerCertificateVerification4) {
  7296. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7297. ASSERT_TRUE(svr.is_valid());
  7298. svr.Get("/test", [&](const Request &, Response &res) {
  7299. res.set_content("test", "text/plain");
  7300. svr.stop();
  7301. ASSERT_TRUE(true);
  7302. });
  7303. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7304. auto se = detail::scope_exit([&] {
  7305. t.join();
  7306. ASSERT_FALSE(svr.is_running());
  7307. });
  7308. svr.wait_until_ready();
  7309. SSLClient cli("127.0.0.1", PORT);
  7310. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7311. cli.enable_server_certificate_verification(true);
  7312. cli.set_connection_timeout(30);
  7313. auto res = cli.Get("/test");
  7314. ASSERT_TRUE(res);
  7315. ASSERT_EQ(StatusCode::OK_200, res->status);
  7316. }
  7317. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7318. std::string cert;
  7319. read_file(CA_CERT_FILE, cert);
  7320. SSLClient cli("google.com");
  7321. cli.load_ca_cert_store(cert.data(), cert.size());
  7322. const auto res = cli.Get("/");
  7323. ASSERT_TRUE(res);
  7324. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7325. }
  7326. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7327. // clang-format off
  7328. static constexpr char cert[] =
  7329. "GlobalSign Root CA\n"
  7330. "==================\n"
  7331. "-----BEGIN CERTIFICATE-----\n"
  7332. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7333. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7334. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7335. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7336. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7337. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7338. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7339. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7340. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7341. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7342. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7343. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7344. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7345. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7346. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7347. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7348. "-----END CERTIFICATE-----\n";
  7349. // clang-format on
  7350. SSLClient cli("google.com");
  7351. cli.load_ca_cert_store(cert, sizeof(cert));
  7352. const auto res = cli.Get("/");
  7353. ASSERT_TRUE(res);
  7354. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7355. }
  7356. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7357. SSLClient cli("www.youtube.com");
  7358. cli.set_ca_cert_path(CA_CERT_FILE);
  7359. cli.enable_server_certificate_verification(true);
  7360. cli.set_follow_location(true);
  7361. auto res = cli.Get("/");
  7362. ASSERT_TRUE(res);
  7363. ASSERT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  7366. SSLClient cli("wWw.YouTube.Com");
  7367. cli.set_ca_cert_path(CA_CERT_FILE);
  7368. cli.enable_server_certificate_verification(true);
  7369. cli.enable_server_hostname_verification(true);
  7370. cli.set_follow_location(true);
  7371. auto res = cli.Get("/");
  7372. ASSERT_TRUE(res);
  7373. ASSERT_EQ(StatusCode::OK_200, res->status);
  7374. }
  7375. TEST(SSLClientTest, HostNameMatchCase_Online) {
  7376. SSLClient cli("gOoGlE.COm");
  7377. cli.enable_server_certificate_verification(true);
  7378. cli.enable_server_hostname_verification(true);
  7379. cli.set_follow_location(true);
  7380. auto res = cli.Get("/");
  7381. ASSERT_TRUE(res);
  7382. ASSERT_EQ(StatusCode::OK_200, res->status);
  7383. }
  7384. TEST(SSLClientTest, Issue2004_Online) {
  7385. Client client("https://google.com");
  7386. client.set_follow_location(true);
  7387. auto res = client.Get("/");
  7388. ASSERT_TRUE(res);
  7389. ASSERT_EQ(StatusCode::OK_200, res->status);
  7390. auto body = res->body;
  7391. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7392. }
  7393. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7394. // Create SSLClient with invalid cert/key to make is_valid() return false
  7395. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7396. "nonexistent_key.pem");
  7397. // is_valid() should be false due to cert loading failure
  7398. ASSERT_FALSE(cli.is_valid());
  7399. auto res = cli.Get("/");
  7400. ASSERT_FALSE(res);
  7401. EXPECT_EQ(Error::SSLConnection, res.error());
  7402. }
  7403. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7404. // Test for Issue #2251: SSL error not properly reported when client cert
  7405. // and key paths are swapped or mismatched
  7406. // This simulates the scenario where user accidentally swaps the cert and key
  7407. // files
  7408. // Using client cert file as private key and vice versa (completely wrong)
  7409. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7410. // Should fail validation due to cert/key mismatch
  7411. ASSERT_FALSE(cli.is_valid());
  7412. // Attempt to make a request should fail with proper error
  7413. auto res = cli.Get("/");
  7414. ASSERT_FALSE(res);
  7415. EXPECT_EQ(Error::SSLConnection, res.error());
  7416. // SSL error should be recorded in the Result object (this is the key fix for
  7417. // Issue #2251)
  7418. auto backend_error = res.ssl_backend_error();
  7419. EXPECT_NE(0u, backend_error);
  7420. }
  7421. // Tests cert/key mismatch detection at the TLS context level
  7422. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7423. // Test that using mismatched cert/key causes connection failure.
  7424. // We verify this at the SSLClient level rather than through internal
  7425. // TLS API functions.
  7426. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  7427. cli.enable_server_certificate_verification(false);
  7428. cli.set_connection_timeout(2);
  7429. // The mismatch should cause a connection or handshake error
  7430. auto res = cli.Get("/test");
  7431. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  7432. // Either way, the request should fail
  7433. EXPECT_FALSE(res);
  7434. }
  7435. #endif
  7436. #if 0
  7437. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7438. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7439. ASSERT_TRUE(cli != nullptr);
  7440. cli->set_address_family(AF_INET6);
  7441. cli->set_interface("en0");
  7442. auto res = cli->Get("/get");
  7443. ASSERT_TRUE(res);
  7444. ASSERT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. #endif
  7447. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  7448. #ifdef CPPHTTPLIB_SSL_ENABLED
  7449. void ClientCertPresent(
  7450. const std::string &client_cert_file,
  7451. const std::string &client_private_key_file,
  7452. const std::string &client_encrypted_private_key_pass = std::string()) {
  7453. using namespace httplib::tls;
  7454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7455. CLIENT_CA_CERT_DIR);
  7456. ASSERT_TRUE(svr.is_valid());
  7457. svr.Get("/test", [&](const Request &req, Response &res) {
  7458. res.set_content("test", "text/plain");
  7459. auto cert = req.peer_cert();
  7460. ASSERT_TRUE(static_cast<bool>(cert));
  7461. std::string common_name = cert.subject_cn();
  7462. EXPECT_EQ("Common Name", common_name);
  7463. });
  7464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. t.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7472. client_encrypted_private_key_pass);
  7473. cli.enable_server_certificate_verification(false);
  7474. cli.set_connection_timeout(30);
  7475. auto res = cli.Get("/test");
  7476. ASSERT_TRUE(res);
  7477. ASSERT_EQ(StatusCode::OK_200, res->status);
  7478. }
  7479. TEST(SSLClientServerTest, ClientCertPresent) {
  7480. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7481. }
  7482. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7483. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7484. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7485. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7486. }
  7487. // PEM memory-based constructor tests (works with all TLS backends)
  7488. void PemMemoryClientCertPresent(
  7489. const std::string &client_cert_file,
  7490. const std::string &client_private_key_file,
  7491. const std::string &client_encrypted_private_key_pass = std::string()) {
  7492. // Read PEM files into memory
  7493. std::string server_cert_pem, server_key_pem;
  7494. std::string client_ca_pem;
  7495. std::string client_cert_pem, client_key_pem;
  7496. read_file(SERVER_CERT_FILE, server_cert_pem);
  7497. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7498. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7499. read_file(client_cert_file, client_cert_pem);
  7500. read_file(client_private_key_file, client_key_pem);
  7501. // Create server with PEM memory
  7502. SSLServer::PemMemory server_pem = {
  7503. server_cert_pem.c_str(),
  7504. server_cert_pem.size(),
  7505. server_key_pem.c_str(),
  7506. server_key_pem.size(),
  7507. client_ca_pem.c_str(),
  7508. client_ca_pem.size(),
  7509. nullptr // no password for server key
  7510. };
  7511. SSLServer svr(server_pem);
  7512. ASSERT_TRUE(svr.is_valid());
  7513. svr.Get("/test", [&](const Request &, Response &res) {
  7514. res.set_content("test", "text/plain");
  7515. });
  7516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7517. auto se = detail::scope_exit([&] {
  7518. svr.stop();
  7519. t.join();
  7520. ASSERT_FALSE(svr.is_running());
  7521. });
  7522. svr.wait_until_ready();
  7523. // Create client with PEM memory
  7524. const char *password = client_encrypted_private_key_pass.empty()
  7525. ? nullptr
  7526. : client_encrypted_private_key_pass.c_str();
  7527. SSLClient::PemMemory client_pem = {
  7528. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7529. client_key_pem.size(), password};
  7530. SSLClient cli(HOST, PORT, client_pem);
  7531. cli.enable_server_certificate_verification(false);
  7532. cli.set_connection_timeout(30);
  7533. auto res = cli.Get("/test");
  7534. ASSERT_TRUE(res);
  7535. ASSERT_EQ(StatusCode::OK_200, res->status);
  7536. }
  7537. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7538. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7539. }
  7540. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7541. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7542. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7543. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7544. }
  7545. TEST(SSLClientServerTest, ClientCertMissing) {
  7546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7547. CLIENT_CA_CERT_DIR);
  7548. ASSERT_TRUE(svr.is_valid());
  7549. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7551. auto se = detail::scope_exit([&] {
  7552. svr.stop();
  7553. t.join();
  7554. ASSERT_FALSE(svr.is_running());
  7555. });
  7556. svr.wait_until_ready();
  7557. SSLClient cli(HOST, PORT);
  7558. cli.set_connection_timeout(30);
  7559. auto res = cli.Get("/test");
  7560. ASSERT_TRUE(!res);
  7561. // When client cert is missing and server requires it, connection fails
  7562. // Error type depends on backend implementation
  7563. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7564. res.error() == Error::SSLConnection);
  7565. // Verify backend error is captured
  7566. // Note: This test may have different error codes depending on the exact
  7567. // verification failure
  7568. EXPECT_NE(0UL, res.ssl_backend_error());
  7569. }
  7570. TEST(SSLClientServerTest, TrustDirOptional) {
  7571. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7572. ASSERT_TRUE(svr.is_valid());
  7573. svr.Get("/test", [&](const Request &, Response &res) {
  7574. res.set_content("test", "text/plain");
  7575. });
  7576. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7577. auto se = detail::scope_exit([&] {
  7578. svr.stop();
  7579. t.join();
  7580. ASSERT_FALSE(svr.is_running());
  7581. });
  7582. svr.wait_until_ready();
  7583. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7584. cli.enable_server_certificate_verification(false);
  7585. cli.set_connection_timeout(30);
  7586. auto res = cli.Get("/test");
  7587. ASSERT_TRUE(res);
  7588. ASSERT_EQ(StatusCode::OK_200, res->status);
  7589. }
  7590. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7591. class NoListenSSLServer : public SSLServer {
  7592. public:
  7593. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7594. const char *client_ca_cert_file_path,
  7595. const char *client_ca_cert_dir_path = nullptr)
  7596. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7597. client_ca_cert_dir_path),
  7598. stop_(false) {}
  7599. std::atomic_bool stop_;
  7600. private:
  7601. bool process_and_close_socket(socket_t /*sock*/) override {
  7602. // Don't create SSL context
  7603. while (!stop_.load()) {
  7604. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7605. }
  7606. return true;
  7607. }
  7608. };
  7609. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7610. CLIENT_CA_CERT_FILE);
  7611. ASSERT_TRUE(svr.is_valid());
  7612. svr.Get("/test", [&](const Request &, Response &res) {
  7613. res.set_content("test", "text/plain");
  7614. });
  7615. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7616. auto se = detail::scope_exit([&] {
  7617. svr.stop_ = true;
  7618. svr.stop();
  7619. t.join();
  7620. ASSERT_FALSE(svr.is_running());
  7621. });
  7622. svr.wait_until_ready();
  7623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7624. cli.enable_server_certificate_verification(false);
  7625. cli.set_connection_timeout(1);
  7626. auto res = cli.Get("/test");
  7627. ASSERT_TRUE(!res);
  7628. EXPECT_EQ(Error::SSLConnection, res.error());
  7629. // Timeout results in WantRead error code (maps to backend-specific value)
  7630. EXPECT_NE(0, res.ssl_error());
  7631. }
  7632. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7633. // Test SSLServer with client certificate verification using the standard
  7634. // constructor (ContextSetupCallback is tested by backend-specific tests)
  7635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7636. CLIENT_CA_CERT_DIR);
  7637. ASSERT_TRUE(svr.is_valid());
  7638. svr.Get("/test", [&](const Request &req, Response &res) {
  7639. res.set_content("test", "text/plain");
  7640. auto cert = req.peer_cert();
  7641. ASSERT_TRUE(static_cast<bool>(cert));
  7642. auto common_name = cert.subject_cn();
  7643. EXPECT_EQ("Common Name", common_name);
  7644. });
  7645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7646. auto se = detail::scope_exit([&] {
  7647. svr.stop();
  7648. t.join();
  7649. ASSERT_FALSE(svr.is_running());
  7650. });
  7651. svr.wait_until_ready();
  7652. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7653. cli.enable_server_certificate_verification(false);
  7654. cli.set_connection_timeout(30);
  7655. auto res = cli.Get("/test");
  7656. ASSERT_TRUE(res);
  7657. ASSERT_EQ(StatusCode::OK_200, res->status);
  7658. }
  7659. // Test verify_hostname for both OpenSSL and MbedTLS backends
  7660. // Verifies that wildcard matching and exact matching work consistently
  7661. TEST(SSLClientServerTest, TlsVerifyHostname) {
  7662. using namespace httplib::tls;
  7663. // We need a running server to test against
  7664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7665. ASSERT_TRUE(svr.is_valid());
  7666. svr.Get("/test", [](const Request &, Response &res) {
  7667. res.set_content("ok", "text/plain");
  7668. });
  7669. thread t([&]() { svr.listen(HOST, PORT); });
  7670. auto se = detail::scope_exit([&] {
  7671. svr.stop();
  7672. t.join();
  7673. });
  7674. svr.wait_until_ready();
  7675. bool verify_callback_called = false;
  7676. bool verify_result_wrong = false;
  7677. SSLClient cli(HOST, PORT);
  7678. cli.enable_server_certificate_verification(true);
  7679. cli.set_ca_cert_path(CA_CERT_FILE);
  7680. cli.set_connection_timeout(5);
  7681. // Note: Test certificate has CN="Common Name", not "localhost"
  7682. bool verify_result_cn = false;
  7683. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7684. verify_callback_called = true;
  7685. if (!ctx.cert) return false;
  7686. // Test 1: "Common Name" should match (our test server cert CN)
  7687. verify_result_cn = ctx.check_hostname("Common Name");
  7688. // Test 2: wrong hostname should not match
  7689. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  7690. return true; // Accept for the purpose of this test
  7691. });
  7692. auto res = cli.Get("/test");
  7693. // The request may succeed or fail depending on cert configuration
  7694. // but the callback should have been called
  7695. ASSERT_TRUE(verify_callback_called)
  7696. << "Verify callback should have been called";
  7697. // CN="Common Name" should match our test certificate
  7698. EXPECT_TRUE(verify_result_cn)
  7699. << "verify_hostname should match 'Common Name' (certificate CN)";
  7700. // Wrong hostname should not match
  7701. EXPECT_FALSE(verify_result_wrong)
  7702. << "verify_hostname should not match 'wronghost.example.com'";
  7703. }
  7704. #endif
  7705. // mbedTLS-specific callback constructor test
  7706. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  7707. #ifdef CPPHTTPLIB_SSL_ENABLED
  7708. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7710. ASSERT_TRUE(svr.is_valid());
  7711. // Set up a handler to verify client certificate is present
  7712. bool client_cert_verified = false;
  7713. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7714. // Verify that client certificate was provided
  7715. client_cert_verified = true;
  7716. res.set_content("success", "text/plain");
  7717. });
  7718. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7719. auto se = detail::scope_exit([&] {
  7720. svr.stop();
  7721. t.join();
  7722. ASSERT_FALSE(svr.is_running());
  7723. });
  7724. svr.wait_until_ready();
  7725. // Client with certificate
  7726. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7727. cli.enable_server_certificate_verification(false);
  7728. cli.set_connection_timeout(30);
  7729. auto res = cli.Get("/test");
  7730. ASSERT_TRUE(res);
  7731. ASSERT_EQ(StatusCode::OK_200, res->status);
  7732. ASSERT_TRUE(client_cert_verified);
  7733. EXPECT_EQ("success", res->body);
  7734. }
  7735. #endif
  7736. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  7737. // backends
  7738. #ifdef CPPHTTPLIB_SSL_ENABLED
  7739. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7740. using namespace httplib::tls;
  7741. // Test that when client CA cert file is provided,
  7742. // the server properly requests and validates client certificates
  7743. // Create a server with client authentication
  7744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7745. ASSERT_TRUE(svr.is_valid());
  7746. bool handler_called = false;
  7747. svr.Get("/test", [&](const Request &req, Response &res) {
  7748. handler_called = true;
  7749. // Verify that a client certificate was provided
  7750. auto cert = req.peer_cert();
  7751. ASSERT_TRUE(static_cast<bool>(cert));
  7752. // Get the issuer name
  7753. std::string issuer_str = cert.issuer_name();
  7754. ASSERT_FALSE(issuer_str.empty());
  7755. // The client certificate should be issued by our test CA
  7756. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7757. res.set_content("authenticated", "text/plain");
  7758. });
  7759. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7760. auto se = detail::scope_exit([&] {
  7761. svr.stop();
  7762. t.join();
  7763. ASSERT_FALSE(svr.is_running());
  7764. });
  7765. svr.wait_until_ready();
  7766. // Connect with a client certificate issued by the CA
  7767. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7768. cli.enable_server_certificate_verification(false);
  7769. cli.set_connection_timeout(30);
  7770. auto res = cli.Get("/test");
  7771. ASSERT_TRUE(res);
  7772. ASSERT_EQ(StatusCode::OK_200, res->status);
  7773. ASSERT_TRUE(handler_called);
  7774. EXPECT_EQ("authenticated", res->body);
  7775. }
  7776. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  7777. using namespace httplib::tls;
  7778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7779. ASSERT_TRUE(svr.is_valid());
  7780. svr.Get("/test", [](const Request &, Response &res) {
  7781. res.set_content("ok", "text/plain");
  7782. });
  7783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7784. auto se = detail::scope_exit([&] {
  7785. svr.stop();
  7786. t.join();
  7787. });
  7788. svr.wait_until_ready();
  7789. SSLClient cli(HOST, PORT);
  7790. cli.enable_server_certificate_verification(false);
  7791. cli.set_connection_timeout(30);
  7792. bool cert_checked = false;
  7793. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7794. if (ctx.cert) {
  7795. auto sans = ctx.sans();
  7796. // Test certificate may or may not have SANs - just verify the API
  7797. // works If SANs exist, verify the types are valid
  7798. for (const auto &san : sans) {
  7799. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  7800. san.type == SanType::EMAIL || san.type == SanType::URI ||
  7801. san.type == SanType::OTHER);
  7802. EXPECT_FALSE(san.value.empty());
  7803. }
  7804. cert_checked = true;
  7805. }
  7806. return true;
  7807. });
  7808. auto res = cli.Get("/test");
  7809. ASSERT_TRUE(res);
  7810. EXPECT_TRUE(cert_checked);
  7811. }
  7812. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  7813. using namespace httplib::tls;
  7814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7815. ASSERT_TRUE(svr.is_valid());
  7816. svr.Get("/test", [](const Request &, Response &res) {
  7817. res.set_content("ok", "text/plain");
  7818. });
  7819. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7820. auto se = detail::scope_exit([&] {
  7821. svr.stop();
  7822. t.join();
  7823. });
  7824. svr.wait_until_ready();
  7825. SSLClient cli(HOST, PORT);
  7826. cli.enable_server_certificate_verification(false);
  7827. cli.set_connection_timeout(30);
  7828. bool validity_checked = false;
  7829. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7830. if (ctx.cert) {
  7831. time_t not_before = 0, not_after = 0;
  7832. bool result = ctx.validity(not_before, not_after);
  7833. EXPECT_TRUE(result);
  7834. // Verify that not_before < now < not_after for a valid cert
  7835. time_t now = time(nullptr);
  7836. EXPECT_LT(not_before, now);
  7837. EXPECT_GT(not_after, now);
  7838. validity_checked = true;
  7839. }
  7840. return true;
  7841. });
  7842. auto res = cli.Get("/test");
  7843. ASSERT_TRUE(res);
  7844. EXPECT_TRUE(validity_checked);
  7845. }
  7846. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  7847. using namespace httplib::tls;
  7848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7849. ASSERT_TRUE(svr.is_valid());
  7850. svr.Get("/test", [](const Request &, Response &res) {
  7851. res.set_content("ok", "text/plain");
  7852. });
  7853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7854. auto se = detail::scope_exit([&] {
  7855. svr.stop();
  7856. t.join();
  7857. });
  7858. svr.wait_until_ready();
  7859. SSLClient cli(HOST, PORT);
  7860. cli.enable_server_certificate_verification(false);
  7861. cli.set_connection_timeout(30);
  7862. bool serial_checked = false;
  7863. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7864. if (ctx.cert) {
  7865. std::string serial = ctx.serial();
  7866. EXPECT_FALSE(serial.empty());
  7867. // Serial should be a hex string
  7868. for (char c : serial) {
  7869. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  7870. (c >= 'a' && c <= 'f'));
  7871. }
  7872. serial_checked = true;
  7873. }
  7874. return true;
  7875. });
  7876. auto res = cli.Get("/test");
  7877. ASSERT_TRUE(res);
  7878. EXPECT_TRUE(serial_checked);
  7879. }
  7880. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7881. // Test 1: Valid CA file - no error should be recorded
  7882. {
  7883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7884. CLIENT_CA_CERT_FILE);
  7885. ASSERT_TRUE(svr.is_valid());
  7886. // With valid setup, last_ssl_error should be 0
  7887. EXPECT_EQ(0, svr.ssl_last_error());
  7888. }
  7889. // Test 2: Invalid CA file content
  7890. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7891. {
  7892. // Create a temporary file with completely invalid content
  7893. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7894. {
  7895. std::ofstream ofs(temp_invalid_ca);
  7896. ofs << "This is not a certificate file at all\n";
  7897. ofs << "Just plain text content\n";
  7898. }
  7899. // Create server with invalid CA file
  7900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7901. // Clean up temporary file
  7902. std::remove(temp_invalid_ca);
  7903. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7904. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7905. // Note: SSL_CTX_load_verify_locations typically fails first,
  7906. // but our error handling code path is still exercised
  7907. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7908. }
  7909. }
  7910. TEST(VerifyCallbackTest, VerifyContextFields) {
  7911. using namespace httplib::tls;
  7912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7913. ASSERT_TRUE(svr.is_valid());
  7914. svr.Get("/test", [](const Request &, Response &res) {
  7915. res.set_content("ok", "text/plain");
  7916. });
  7917. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7918. auto se = detail::scope_exit([&] {
  7919. svr.stop();
  7920. t.join();
  7921. });
  7922. svr.wait_until_ready();
  7923. SSLClient cli(HOST, PORT);
  7924. cli.enable_server_certificate_verification(false);
  7925. cli.set_connection_timeout(30);
  7926. int callback_count = 0;
  7927. bool saw_leaf_cert = false;
  7928. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  7929. if (ctx.cert) {
  7930. callback_count++;
  7931. // We should see at least one certificate (the leaf)
  7932. std::string cn = ctx.subject_cn();
  7933. if (!cn.empty()) { saw_leaf_cert = true; }
  7934. // Verify context fields are populated
  7935. EXPECT_NE(ctx.session, nullptr);
  7936. EXPECT_GE(ctx.depth, 0);
  7937. }
  7938. return true;
  7939. });
  7940. auto res = cli.Get("/test");
  7941. ASSERT_TRUE(res);
  7942. EXPECT_GT(callback_count, 0);
  7943. EXPECT_TRUE(saw_leaf_cert);
  7944. }
  7945. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  7946. using httplib::tls::TlsError;
  7947. // Test that verify_error_to_string returns empty for success
  7948. std::string success_str = TlsError::verify_error_to_string(0);
  7949. EXPECT_TRUE(success_str.empty());
  7950. // Test that verify_error_to_string returns non-empty for error codes
  7951. // Using a common error code (certificate expired)
  7952. std::string error_str =
  7953. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  7954. EXPECT_FALSE(error_str.empty());
  7955. }
  7956. TEST(SessionVerifierTest, CertificateAccepted) {
  7957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7958. ASSERT_TRUE(svr.is_valid());
  7959. svr.Get("/test", [](const Request &, Response &res) {
  7960. res.set_content("ok", "text/plain");
  7961. });
  7962. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7963. auto se = detail::scope_exit([&] {
  7964. svr.stop();
  7965. t.join();
  7966. });
  7967. svr.wait_until_ready();
  7968. SSLClient cli(HOST, PORT);
  7969. cli.enable_server_certificate_verification(false);
  7970. cli.set_connection_timeout(30);
  7971. bool callback_called = false;
  7972. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  7973. EXPECT_NE(session, nullptr);
  7974. callback_called = true;
  7975. return SSLVerifierResponse::CertificateAccepted;
  7976. });
  7977. auto res = cli.Get("/test");
  7978. ASSERT_TRUE(res);
  7979. EXPECT_EQ(200, res->status);
  7980. EXPECT_TRUE(callback_called);
  7981. }
  7982. TEST(SessionVerifierTest, CertificateRejected) {
  7983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7984. ASSERT_TRUE(svr.is_valid());
  7985. svr.Get("/test", [](const Request &, Response &res) {
  7986. res.set_content("ok", "text/plain");
  7987. });
  7988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7989. auto se = detail::scope_exit([&] {
  7990. svr.stop();
  7991. t.join();
  7992. });
  7993. svr.wait_until_ready();
  7994. SSLClient cli(HOST, PORT);
  7995. cli.enable_server_certificate_verification(false);
  7996. cli.set_connection_timeout(30);
  7997. bool callback_called = false;
  7998. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  7999. EXPECT_NE(session, nullptr);
  8000. callback_called = true;
  8001. return SSLVerifierResponse::CertificateRejected;
  8002. });
  8003. auto res = cli.Get("/test");
  8004. EXPECT_FALSE(res);
  8005. EXPECT_TRUE(callback_called);
  8006. }
  8007. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8009. ASSERT_TRUE(svr.is_valid());
  8010. svr.Get("/test", [](const Request &, Response &res) {
  8011. res.set_content("ok", "text/plain");
  8012. });
  8013. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8014. auto se = detail::scope_exit([&] {
  8015. svr.stop();
  8016. t.join();
  8017. });
  8018. svr.wait_until_ready();
  8019. // NoDecisionMade with verification disabled should succeed (no default check)
  8020. SSLClient cli(HOST, PORT);
  8021. cli.enable_server_certificate_verification(false);
  8022. cli.set_connection_timeout(30);
  8023. bool callback_called = false;
  8024. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8025. EXPECT_NE(session, nullptr);
  8026. callback_called = true;
  8027. return SSLVerifierResponse::NoDecisionMade;
  8028. });
  8029. auto res = cli.Get("/test");
  8030. ASSERT_TRUE(res);
  8031. EXPECT_EQ(200, res->status);
  8032. EXPECT_TRUE(callback_called);
  8033. }
  8034. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8036. ASSERT_TRUE(svr.is_valid());
  8037. svr.Get("/test", [](const Request &, Response &res) {
  8038. res.set_content("ok", "text/plain");
  8039. });
  8040. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8041. auto se = detail::scope_exit([&] {
  8042. svr.stop();
  8043. t.join();
  8044. });
  8045. svr.wait_until_ready();
  8046. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8047. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8048. // so we only check that the request fails, not whether the callback was
  8049. // called.
  8050. SSLClient cli(HOST, PORT);
  8051. cli.enable_server_certificate_verification(true);
  8052. cli.set_connection_timeout(30);
  8053. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8054. EXPECT_NE(session, nullptr);
  8055. return SSLVerifierResponse::NoDecisionMade;
  8056. });
  8057. auto res = cli.Get("/test");
  8058. EXPECT_FALSE(res);
  8059. }
  8060. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8061. // Test SSL server using PemMemory constructor with client CA certificates
  8062. // Read PEM files
  8063. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8064. read_file(SERVER_CERT_FILE, server_cert_pem);
  8065. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8066. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8067. // Create SSLServer with PemMemory constructor including client CA
  8068. SSLServer::PemMemory server_pem = {
  8069. server_cert_pem.c_str(),
  8070. server_cert_pem.size(),
  8071. server_key_pem.c_str(),
  8072. server_key_pem.size(),
  8073. client_ca_pem.c_str(),
  8074. client_ca_pem.size(),
  8075. nullptr // no password for server key
  8076. };
  8077. SSLServer svr(server_pem);
  8078. ASSERT_TRUE(svr.is_valid());
  8079. // No SSL error should be recorded for valid setup
  8080. EXPECT_EQ(0, svr.ssl_last_error());
  8081. // Set up server endpoints
  8082. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8083. res.set_content("ok", "text/plain");
  8084. });
  8085. // Start server in a thread
  8086. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8087. svr.wait_until_ready();
  8088. // Connect with client certificate (using constructor with paths)
  8089. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8090. cli.enable_server_certificate_verification(false);
  8091. auto res = cli.Get("/test-pem-ca");
  8092. ASSERT_TRUE(res);
  8093. EXPECT_EQ(200, res->status);
  8094. EXPECT_EQ("ok", res->body);
  8095. svr.stop();
  8096. server_thread.join();
  8097. }
  8098. #endif
  8099. #ifdef _WIN32
  8100. TEST(CleanupTest, WSACleanup) {
  8101. int ret = WSACleanup();
  8102. ASSERT_EQ(0, ret);
  8103. }
  8104. #endif
  8105. #ifndef CPPHTTPLIB_SSL_ENABLED
  8106. TEST(NoSSLSupport, SimpleInterface) {
  8107. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8108. }
  8109. #endif
  8110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8111. TEST(InvalidScheme, SimpleInterface) {
  8112. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8113. }
  8114. #endif
  8115. TEST(NoScheme, SimpleInterface) {
  8116. Client cli("yahoo.com:80");
  8117. ASSERT_TRUE(cli.is_valid());
  8118. }
  8119. TEST(SendAPI, SimpleInterface_Online) {
  8120. Client cli("http://yahoo.com");
  8121. Request req;
  8122. req.method = "GET";
  8123. req.path = "/";
  8124. auto res = cli.send(req);
  8125. ASSERT_TRUE(res);
  8126. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8127. }
  8128. TEST(SendAPI, WithParamsInRequest) {
  8129. Server svr;
  8130. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8131. EXPECT_TRUE(req.has_param("test"));
  8132. EXPECT_EQ("test_value", req.get_param_value("test"));
  8133. });
  8134. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8135. auto se = detail::scope_exit([&] {
  8136. svr.stop();
  8137. t.join();
  8138. ASSERT_FALSE(svr.is_running());
  8139. });
  8140. svr.wait_until_ready();
  8141. Client cli(HOST, PORT);
  8142. {
  8143. Request req;
  8144. req.method = "GET";
  8145. req.path = "/";
  8146. req.params.emplace("test", "test_value");
  8147. auto res = cli.send(req);
  8148. ASSERT_TRUE(res);
  8149. }
  8150. {
  8151. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8152. ASSERT_TRUE(res);
  8153. }
  8154. }
  8155. TEST(ClientImplMethods, GetSocketTest) {
  8156. httplib::Server svr;
  8157. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8158. res.status = StatusCode::OK_200;
  8159. });
  8160. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8161. auto se = detail::scope_exit([&] {
  8162. svr.stop();
  8163. thread.join();
  8164. ASSERT_FALSE(svr.is_running());
  8165. });
  8166. svr.wait_until_ready();
  8167. {
  8168. httplib::Client cli("http://127.0.0.1:3333");
  8169. cli.set_keep_alive(true);
  8170. // Use the behavior of cpp-httplib of opening the connection
  8171. // only when the first request happens. If that changes,
  8172. // this test would be obsolete.
  8173. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8174. // This also implicitly tests the server. But other tests would fail much
  8175. // earlier than this one to be considered.
  8176. auto res = cli.Get("/");
  8177. ASSERT_TRUE(res);
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8180. }
  8181. }
  8182. // Disabled due to out-of-memory problem on GitHub Actions
  8183. #ifdef _WIN64
  8184. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8185. // allocate content size larger than 2GB in memory
  8186. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8187. char *content = (char *)malloc(content_size);
  8188. ASSERT_TRUE(content);
  8189. Server svr;
  8190. svr.Get("/foo",
  8191. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8192. res.set_content(content, content_size, "application/octet-stream");
  8193. });
  8194. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8195. auto se = detail::scope_exit([&] {
  8196. svr.stop();
  8197. listen_thread.join();
  8198. if (content) free(content);
  8199. ASSERT_FALSE(svr.is_running());
  8200. });
  8201. svr.wait_until_ready();
  8202. Client cli(HOST, PORT);
  8203. auto res = cli.Get("/foo");
  8204. ASSERT_TRUE(res);
  8205. EXPECT_EQ(StatusCode::OK_200, res->status);
  8206. EXPECT_EQ(content_size, res->body.length());
  8207. }
  8208. #endif
  8209. #ifdef CPPHTTPLIB_SSL_ENABLED
  8210. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8211. Client cli("http://yahoo.com");
  8212. auto res = cli.Get("/");
  8213. ASSERT_TRUE(res);
  8214. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8215. cli.set_follow_location(true);
  8216. res = cli.Get("/");
  8217. ASSERT_TRUE(res);
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8220. }
  8221. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8222. Client cli("https://yahoo.com");
  8223. auto res = cli.Get("/");
  8224. ASSERT_TRUE(res);
  8225. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8226. cli.set_follow_location(true);
  8227. res = cli.Get("/");
  8228. ASSERT_TRUE(res);
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8231. }
  8232. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8233. Client cli("https://yahoo.com");
  8234. auto res = cli.Get("/");
  8235. ASSERT_TRUE(res);
  8236. ASSERT_FALSE(!res);
  8237. ASSERT_TRUE(res);
  8238. ASSERT_FALSE(res == nullptr);
  8239. ASSERT_TRUE(res != nullptr);
  8240. EXPECT_EQ(Error::Success, res.error());
  8241. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8242. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8243. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8244. cli.set_follow_location(true);
  8245. res = cli.Get("/");
  8246. ASSERT_TRUE(res);
  8247. EXPECT_EQ(Error::Success, res.error());
  8248. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8249. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8250. EXPECT_EQ(StatusCode::OK_200, res->status);
  8251. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8252. }
  8253. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8254. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8255. Client cli("https://cdnjs.cloudflare.com");
  8256. auto res =
  8257. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8258. ASSERT_TRUE(res);
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_EQ(287630U, res->body.size());
  8261. EXPECT_EQ("application/javascript; charset=utf-8",
  8262. res->get_header_value("Content-Type"));
  8263. }
  8264. #endif
  8265. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8266. #undef REDIR_HOST // Silence compiler warning
  8267. #define REDIR_HOST "https://httpbingo.org"
  8268. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8269. Client cli(REDIR_HOST);
  8270. cli.set_follow_location(true);
  8271. auto res =
  8272. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8273. ASSERT_TRUE(res);
  8274. EXPECT_EQ(StatusCode::OK_200, res->status);
  8275. }
  8276. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8277. Client cli(REDIR_HOST);
  8278. cli.set_follow_location(true);
  8279. Params params;
  8280. params.emplace("url", "http://example.com");
  8281. params.emplace("status_code", "302");
  8282. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8283. ASSERT_TRUE(res);
  8284. EXPECT_EQ(StatusCode::OK_200, res->status);
  8285. }
  8286. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8287. Client cli(REDIR_HOST);
  8288. cli.set_follow_location(true);
  8289. Params params;
  8290. params.emplace("url", "http://example.com");
  8291. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8292. ASSERT_TRUE(res);
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. }
  8295. TEST(HttpToHttpsRedirectTest, CertFile) {
  8296. Server svr;
  8297. ASSERT_TRUE(svr.is_valid());
  8298. svr.Get("/index", [&](const Request &, Response &res) {
  8299. res.set_redirect("https://127.0.0.1:1235/index");
  8300. svr.stop();
  8301. });
  8302. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8303. ASSERT_TRUE(ssl_svr.is_valid());
  8304. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8305. res.set_content("test", "text/plain");
  8306. ssl_svr.stop();
  8307. });
  8308. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8309. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8310. auto se = detail::scope_exit([&] {
  8311. t2.join();
  8312. t.join();
  8313. ASSERT_FALSE(svr.is_running());
  8314. });
  8315. svr.wait_until_ready();
  8316. ssl_svr.wait_until_ready();
  8317. Client cli("127.0.0.1", PORT);
  8318. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8319. cli.enable_server_certificate_verification(true);
  8320. cli.set_follow_location(true);
  8321. cli.set_connection_timeout(30);
  8322. auto res = cli.Get("/index");
  8323. ASSERT_TRUE(res);
  8324. ASSERT_EQ(StatusCode::OK_200, res->status);
  8325. }
  8326. TEST(SSLClientRedirectTest, CertFile) {
  8327. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8328. ASSERT_TRUE(ssl_svr1.is_valid());
  8329. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8330. res.set_redirect("https://127.0.0.1:1235/index");
  8331. ssl_svr1.stop();
  8332. });
  8333. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. ASSERT_TRUE(ssl_svr2.is_valid());
  8335. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8336. res.set_content("test", "text/plain");
  8337. ssl_svr2.stop();
  8338. });
  8339. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8340. thread t2 =
  8341. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8342. auto se = detail::scope_exit([&] {
  8343. t2.join();
  8344. t.join();
  8345. ASSERT_FALSE(ssl_svr1.is_running());
  8346. });
  8347. ssl_svr1.wait_until_ready();
  8348. ssl_svr2.wait_until_ready();
  8349. SSLClient cli("127.0.0.1", PORT);
  8350. std::string cert;
  8351. read_file(SERVER_CERT2_FILE, cert);
  8352. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8353. cli.enable_server_certificate_verification(true);
  8354. cli.set_follow_location(true);
  8355. cli.set_connection_timeout(30);
  8356. auto res = cli.Get("/index");
  8357. ASSERT_TRUE(res);
  8358. ASSERT_EQ(StatusCode::OK_200, res->status);
  8359. }
  8360. #endif
  8361. // Test that set_ca_cert_store() skips system certs (consistent with
  8362. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8363. // should be trusted - system certs should NOT be loaded.
  8364. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8365. // Load a specific cert that is NOT a system CA cert
  8366. std::string cert;
  8367. read_file(SERVER_CERT2_FILE, cert);
  8368. SSLClient cli("google.com");
  8369. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8370. cli.enable_server_certificate_verification(true);
  8371. // This should FAIL because:
  8372. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8373. // 2. System certs should NOT be loaded when custom store is set
  8374. // If system certs WERE loaded, this would succeed
  8375. auto res = cli.Get("/");
  8376. ASSERT_FALSE(res);
  8377. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8378. }
  8379. TEST(MultipartFormDataTest, LargeData) {
  8380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8381. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8382. const ContentReader &content_reader) {
  8383. if (req.is_multipart_form_data()) {
  8384. std::vector<FormData> items;
  8385. content_reader(
  8386. [&](const FormData &file) {
  8387. items.push_back(file);
  8388. return true;
  8389. },
  8390. [&](const char *data, size_t data_length) {
  8391. items.back().content.append(data, data_length);
  8392. return true;
  8393. });
  8394. EXPECT_TRUE(std::string(items[0].name) == "document");
  8395. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8396. EXPECT_TRUE(items[0].filename == "2MB_data");
  8397. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8398. EXPECT_TRUE(items[1].name == "hello");
  8399. EXPECT_TRUE(items[1].content == "world");
  8400. EXPECT_TRUE(items[1].filename == "");
  8401. EXPECT_TRUE(items[1].content_type == "");
  8402. } else {
  8403. std::string body;
  8404. content_reader([&](const char *data, size_t data_length) {
  8405. body.append(data, data_length);
  8406. return true;
  8407. });
  8408. }
  8409. });
  8410. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8411. auto se = detail::scope_exit([&] {
  8412. svr.stop();
  8413. t.join();
  8414. ASSERT_FALSE(svr.is_running());
  8415. });
  8416. svr.wait_until_ready();
  8417. {
  8418. std::string data(1024 * 1024 * 2, '.');
  8419. std::stringstream buffer;
  8420. buffer << data;
  8421. Client cli("https://localhost:8080");
  8422. cli.enable_server_certificate_verification(false);
  8423. UploadFormDataItems items{
  8424. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8425. {"hello", "world", "", ""},
  8426. };
  8427. auto res = cli.Post("/post", items);
  8428. ASSERT_TRUE(res);
  8429. ASSERT_EQ(StatusCode::OK_200, res->status);
  8430. }
  8431. }
  8432. TEST(MultipartFormDataTest, DataProviderItems) {
  8433. std::random_device seed_gen;
  8434. std::mt19937 random(seed_gen());
  8435. std::string rand1;
  8436. rand1.resize(1000);
  8437. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8438. std::string rand2;
  8439. rand2.resize(3000);
  8440. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8442. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8443. const ContentReader &content_reader) {
  8444. ASSERT_FALSE(req.is_multipart_form_data());
  8445. std::string body;
  8446. content_reader([&](const char *data, size_t data_length) {
  8447. body.append(data, data_length);
  8448. return true;
  8449. });
  8450. EXPECT_EQ(body, "");
  8451. });
  8452. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8453. const ContentReader &content_reader) {
  8454. ASSERT_TRUE(req.is_multipart_form_data());
  8455. std::vector<FormData> items;
  8456. content_reader(
  8457. [&](const FormData &file) {
  8458. items.push_back(file);
  8459. return true;
  8460. },
  8461. [&](const char *data, size_t data_length) {
  8462. items.back().content.append(data, data_length);
  8463. return true;
  8464. });
  8465. ASSERT_TRUE(items.size() == 2);
  8466. EXPECT_EQ(std::string(items[0].name), "name1");
  8467. EXPECT_EQ(items[0].content, "Testing123");
  8468. EXPECT_EQ(items[0].filename, "filename1");
  8469. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8470. EXPECT_EQ(items[1].name, "name2");
  8471. EXPECT_EQ(items[1].content, "Testing456");
  8472. EXPECT_EQ(items[1].filename, "");
  8473. EXPECT_EQ(items[1].content_type, "");
  8474. });
  8475. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8476. const ContentReader &content_reader) {
  8477. ASSERT_TRUE(req.is_multipart_form_data());
  8478. std::vector<FormData> items;
  8479. content_reader(
  8480. [&](const FormData &file) {
  8481. items.push_back(file);
  8482. return true;
  8483. },
  8484. [&](const char *data, size_t data_length) {
  8485. items.back().content.append(data, data_length);
  8486. return true;
  8487. });
  8488. ASSERT_TRUE(items.size() == 2);
  8489. EXPECT_EQ(items[0].name, "name3");
  8490. EXPECT_EQ(items[0].content, rand1);
  8491. EXPECT_EQ(items[0].filename, "filename3");
  8492. EXPECT_EQ(items[0].content_type, "");
  8493. EXPECT_EQ(items[1].name, "name4");
  8494. EXPECT_EQ(items[1].content, rand2);
  8495. EXPECT_EQ(items[1].filename, "filename4");
  8496. EXPECT_EQ(items[1].content_type, "");
  8497. });
  8498. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8499. const ContentReader &content_reader) {
  8500. ASSERT_TRUE(req.is_multipart_form_data());
  8501. std::vector<FormData> items;
  8502. content_reader(
  8503. [&](const FormData &file) {
  8504. items.push_back(file);
  8505. return true;
  8506. },
  8507. [&](const char *data, size_t data_length) {
  8508. items.back().content.append(data, data_length);
  8509. return true;
  8510. });
  8511. ASSERT_TRUE(items.size() == 4);
  8512. EXPECT_EQ(std::string(items[0].name), "name1");
  8513. EXPECT_EQ(items[0].content, "Testing123");
  8514. EXPECT_EQ(items[0].filename, "filename1");
  8515. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8516. EXPECT_EQ(items[1].name, "name2");
  8517. EXPECT_EQ(items[1].content, "Testing456");
  8518. EXPECT_EQ(items[1].filename, "");
  8519. EXPECT_EQ(items[1].content_type, "");
  8520. EXPECT_EQ(items[2].name, "name3");
  8521. EXPECT_EQ(items[2].content, rand1);
  8522. EXPECT_EQ(items[2].filename, "filename3");
  8523. EXPECT_EQ(items[2].content_type, "");
  8524. EXPECT_EQ(items[3].name, "name4");
  8525. EXPECT_EQ(items[3].content, rand2);
  8526. EXPECT_EQ(items[3].filename, "filename4");
  8527. EXPECT_EQ(items[3].content_type, "");
  8528. });
  8529. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8530. auto se = detail::scope_exit([&] {
  8531. svr.stop();
  8532. t.join();
  8533. ASSERT_FALSE(svr.is_running());
  8534. });
  8535. svr.wait_until_ready();
  8536. {
  8537. Client cli("https://localhost:8080");
  8538. cli.enable_server_certificate_verification(false);
  8539. UploadFormDataItems items{
  8540. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8541. {"name2", "Testing456", "", ""}, // not a file
  8542. };
  8543. {
  8544. auto res = cli.Post("/post-none", {}, {}, {});
  8545. ASSERT_TRUE(res);
  8546. ASSERT_EQ(StatusCode::OK_200, res->status);
  8547. }
  8548. FormDataProviderItems providers;
  8549. {
  8550. auto res =
  8551. cli.Post("/post-items", {}, items, providers); // empty providers
  8552. ASSERT_TRUE(res);
  8553. ASSERT_EQ(StatusCode::OK_200, res->status);
  8554. }
  8555. providers.push_back({"name3",
  8556. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8557. // test the offset is given correctly at each step
  8558. if (!offset)
  8559. sink.os.write(rand1.data(), 30);
  8560. else if (offset == 30)
  8561. sink.os.write(rand1.data() + 30, 300);
  8562. else if (offset == 330)
  8563. sink.os.write(rand1.data() + 330, 670);
  8564. else if (offset == rand1.size())
  8565. sink.done();
  8566. return true;
  8567. },
  8568. "filename3",
  8569. {}});
  8570. providers.push_back({"name4",
  8571. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8572. // test the offset is given correctly at each step
  8573. if (!offset)
  8574. sink.os.write(rand2.data(), 2000);
  8575. else if (offset == 2000)
  8576. sink.os.write(rand2.data() + 2000, 1);
  8577. else if (offset == 2001)
  8578. sink.os.write(rand2.data() + 2001, 999);
  8579. else if (offset == rand2.size())
  8580. sink.done();
  8581. return true;
  8582. },
  8583. "filename4",
  8584. {}});
  8585. {
  8586. auto res = cli.Post("/post-providers", {}, {}, providers);
  8587. ASSERT_TRUE(res);
  8588. ASSERT_EQ(StatusCode::OK_200, res->status);
  8589. }
  8590. {
  8591. auto res = cli.Post("/post-both", {}, items, providers);
  8592. ASSERT_TRUE(res);
  8593. ASSERT_EQ(StatusCode::OK_200, res->status);
  8594. }
  8595. }
  8596. }
  8597. TEST(MultipartFormDataTest, BadHeader) {
  8598. Server svr;
  8599. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8600. res.set_content("ok", "text/plain");
  8601. });
  8602. thread t = thread([&] { svr.listen(HOST, PORT); });
  8603. auto se = detail::scope_exit([&] {
  8604. svr.stop();
  8605. t.join();
  8606. ASSERT_FALSE(svr.is_running());
  8607. });
  8608. svr.wait_until_ready();
  8609. const std::string body =
  8610. "This is the preamble. It is to be ignored, though it\r\n"
  8611. "is a handy place for composition agents to include an\r\n"
  8612. "explanatory note to non-MIME conformant readers.\r\n"
  8613. "\r\n"
  8614. "\r\n"
  8615. "--simple boundary\r\n"
  8616. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8617. ": BAD...\r\n"
  8618. "\r\n"
  8619. "value1\r\n"
  8620. "--simple boundary\r\n"
  8621. "Content-Disposition: form-data; name=\"field2\"; "
  8622. "filename=\"example.txt\"\r\n"
  8623. "\r\n"
  8624. "value2\r\n"
  8625. "--simple boundary--\r\n"
  8626. "This is the epilogue. It is also to be ignored.\r\n";
  8627. std::string content_type =
  8628. R"(multipart/form-data; boundary="simple boundary")";
  8629. Client cli(HOST, PORT);
  8630. auto res = cli.Post("/post", body, content_type.c_str());
  8631. ASSERT_TRUE(res);
  8632. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8633. }
  8634. TEST(MultipartFormDataTest, WithPreamble) {
  8635. Server svr;
  8636. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8637. res.set_content("ok", "text/plain");
  8638. });
  8639. thread t = thread([&] { svr.listen(HOST, PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. t.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. });
  8645. svr.wait_until_ready();
  8646. const std::string body =
  8647. "This is the preamble. It is to be ignored, though it\r\n"
  8648. "is a handy place for composition agents to include an\r\n"
  8649. "explanatory note to non-MIME conformant readers.\r\n"
  8650. "\r\n"
  8651. "\r\n"
  8652. "--simple boundary\r\n"
  8653. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8654. "\r\n"
  8655. "value1\r\n"
  8656. "--simple boundary\r\n"
  8657. "Content-Disposition: form-data; name=\"field2\"; "
  8658. "filename=\"example.txt\"\r\n"
  8659. "\r\n"
  8660. "value2\r\n"
  8661. "--simple boundary--\r\n"
  8662. "This is the epilogue. It is also to be ignored.\r\n";
  8663. std::string content_type =
  8664. R"(multipart/form-data; boundary="simple boundary")";
  8665. Client cli(HOST, PORT);
  8666. auto res = cli.Post("/post", body, content_type.c_str());
  8667. ASSERT_TRUE(res);
  8668. EXPECT_EQ(StatusCode::OK_200, res->status);
  8669. }
  8670. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8672. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8673. const ContentReader &content_reader) {
  8674. if (req.is_multipart_form_data()) {
  8675. std::vector<FormData> items;
  8676. content_reader(
  8677. [&](const FormData &file) {
  8678. items.push_back(file);
  8679. return true;
  8680. },
  8681. [&](const char *data, size_t data_length) {
  8682. items.back().content.append(data, data_length);
  8683. return true;
  8684. });
  8685. EXPECT_TRUE(std::string(items[0].name) == "document");
  8686. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8687. EXPECT_TRUE(items[0].filename == "2MB_data");
  8688. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8689. EXPECT_TRUE(items[1].name == "hello");
  8690. EXPECT_TRUE(items[1].content == "world");
  8691. EXPECT_TRUE(items[1].filename == "");
  8692. EXPECT_TRUE(items[1].content_type == "");
  8693. } else {
  8694. std::string body;
  8695. content_reader([&](const char *data, size_t data_length) {
  8696. body.append(data, data_length);
  8697. return true;
  8698. });
  8699. }
  8700. });
  8701. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8702. auto se = detail::scope_exit([&] {
  8703. svr.stop();
  8704. t.join();
  8705. ASSERT_FALSE(svr.is_running());
  8706. });
  8707. svr.wait_until_ready();
  8708. {
  8709. std::string data(1024 * 1024 * 2, '.');
  8710. std::stringstream buffer;
  8711. buffer << data;
  8712. Client cli("https://localhost:8080");
  8713. cli.enable_server_certificate_verification(false);
  8714. UploadFormDataItems items{
  8715. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8716. {"hello", "world", "", ""},
  8717. };
  8718. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8719. ASSERT_TRUE(res);
  8720. ASSERT_EQ(StatusCode::OK_200, res->status);
  8721. }
  8722. }
  8723. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8724. std::string data(1024 * 1024 * 2, '&');
  8725. std::stringstream buffer;
  8726. buffer << data;
  8727. Client cli("https://localhost:8080");
  8728. UploadFormDataItems items{
  8729. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8730. {"hello", "world", "", ""},
  8731. };
  8732. for (const char &c : " \t\r\n") {
  8733. auto res =
  8734. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8735. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8736. ASSERT_FALSE(res);
  8737. }
  8738. }
  8739. TEST(MultipartFormDataTest, PutFormData) {
  8740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8741. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8742. const ContentReader &content_reader) {
  8743. if (req.is_multipart_form_data()) {
  8744. std::vector<FormData> items;
  8745. content_reader(
  8746. [&](const FormData &file) {
  8747. items.push_back(file);
  8748. return true;
  8749. },
  8750. [&](const char *data, size_t data_length) {
  8751. items.back().content.append(data, data_length);
  8752. return true;
  8753. });
  8754. EXPECT_TRUE(std::string(items[0].name) == "document");
  8755. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8756. EXPECT_TRUE(items[0].filename == "2MB_data");
  8757. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8758. EXPECT_TRUE(items[1].name == "hello");
  8759. EXPECT_TRUE(items[1].content == "world");
  8760. EXPECT_TRUE(items[1].filename == "");
  8761. EXPECT_TRUE(items[1].content_type == "");
  8762. } else {
  8763. std::string body;
  8764. content_reader([&](const char *data, size_t data_length) {
  8765. body.append(data, data_length);
  8766. return true;
  8767. });
  8768. }
  8769. });
  8770. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8771. auto se = detail::scope_exit([&] {
  8772. svr.stop();
  8773. t.join();
  8774. ASSERT_FALSE(svr.is_running());
  8775. });
  8776. svr.wait_until_ready();
  8777. {
  8778. std::string data(1024 * 1024 * 2, '&');
  8779. std::stringstream buffer;
  8780. buffer << data;
  8781. Client cli("https://localhost:8080");
  8782. cli.enable_server_certificate_verification(false);
  8783. UploadFormDataItems items{
  8784. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8785. {"hello", "world", "", ""},
  8786. };
  8787. auto res = cli.Put("/put", items);
  8788. ASSERT_TRUE(res);
  8789. ASSERT_EQ(StatusCode::OK_200, res->status);
  8790. }
  8791. }
  8792. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8794. svr.Put("/put_customboundary",
  8795. [&](const Request &req, const Response & /*res*/,
  8796. const ContentReader &content_reader) {
  8797. if (req.is_multipart_form_data()) {
  8798. std::vector<FormData> items;
  8799. content_reader(
  8800. [&](const FormData &file) {
  8801. items.push_back(file);
  8802. return true;
  8803. },
  8804. [&](const char *data, size_t data_length) {
  8805. items.back().content.append(data, data_length);
  8806. return true;
  8807. });
  8808. EXPECT_TRUE(std::string(items[0].name) == "document");
  8809. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8810. EXPECT_TRUE(items[0].filename == "2MB_data");
  8811. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8812. EXPECT_TRUE(items[1].name == "hello");
  8813. EXPECT_TRUE(items[1].content == "world");
  8814. EXPECT_TRUE(items[1].filename == "");
  8815. EXPECT_TRUE(items[1].content_type == "");
  8816. } else {
  8817. std::string body;
  8818. content_reader([&](const char *data, size_t data_length) {
  8819. body.append(data, data_length);
  8820. return true;
  8821. });
  8822. }
  8823. });
  8824. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. t.join();
  8828. ASSERT_FALSE(svr.is_running());
  8829. });
  8830. svr.wait_until_ready();
  8831. {
  8832. std::string data(1024 * 1024 * 2, '&');
  8833. std::stringstream buffer;
  8834. buffer << data;
  8835. Client cli("https://localhost:8080");
  8836. cli.enable_server_certificate_verification(false);
  8837. UploadFormDataItems items{
  8838. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8839. {"hello", "world", "", ""},
  8840. };
  8841. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8842. ASSERT_TRUE(res);
  8843. ASSERT_EQ(StatusCode::OK_200, res->status);
  8844. }
  8845. }
  8846. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8847. std::string data(1024 * 1024 * 2, '&');
  8848. std::stringstream buffer;
  8849. buffer << data;
  8850. Client cli("https://localhost:8080");
  8851. cli.enable_server_certificate_verification(false);
  8852. UploadFormDataItems items{
  8853. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8854. {"hello", "world", "", ""},
  8855. };
  8856. for (const char &c : " \t\r\n") {
  8857. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8858. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8859. ASSERT_FALSE(res);
  8860. }
  8861. }
  8862. TEST(MultipartFormDataTest, AlternateFilename) {
  8863. auto handled = false;
  8864. Server svr;
  8865. svr.Post("/test", [&](const Request &req, Response &res) {
  8866. ASSERT_EQ(2u, req.form.files.size());
  8867. ASSERT_EQ(1u, req.form.fields.size());
  8868. // Test files
  8869. const auto &file1 = req.form.get_file("file1");
  8870. ASSERT_EQ("file1", file1.name);
  8871. ASSERT_EQ("A.txt", file1.filename);
  8872. ASSERT_EQ("text/plain", file1.content_type);
  8873. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8874. const auto &file2 = req.form.get_file("file2");
  8875. ASSERT_EQ("file2", file2.name);
  8876. ASSERT_EQ("a.html", file2.filename);
  8877. ASSERT_EQ("text/html", file2.content_type);
  8878. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8879. file2.content);
  8880. // Test text field
  8881. const auto &text = req.form.get_field("text");
  8882. ASSERT_EQ("text default", text);
  8883. res.set_content("ok", "text/plain");
  8884. handled = true;
  8885. });
  8886. thread t = thread([&] { svr.listen(HOST, PORT); });
  8887. auto se = detail::scope_exit([&] {
  8888. svr.stop();
  8889. t.join();
  8890. ASSERT_FALSE(svr.is_running());
  8891. ASSERT_TRUE(handled);
  8892. });
  8893. svr.wait_until_ready();
  8894. auto req = "POST /test HTTP/1.1\r\n"
  8895. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8896. "Content-Length: 399\r\n"
  8897. "\r\n"
  8898. "----------\r\n"
  8899. "Content-Disposition: form-data; name=\"text\"\r\n"
  8900. "\r\n"
  8901. "text default\r\n"
  8902. "----------\r\n"
  8903. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8904. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8905. "Content-Type: text/plain\r\n"
  8906. "\r\n"
  8907. "Content of a.txt.\r\n"
  8908. "\r\n"
  8909. "----------\r\n"
  8910. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8911. "\"a.html\"\r\n"
  8912. "Content-Type: text/html\r\n"
  8913. "\r\n"
  8914. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8915. "\r\n"
  8916. "------------\r\n";
  8917. ASSERT_TRUE(send_request(1, req));
  8918. }
  8919. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8920. auto handled = false;
  8921. Server svr;
  8922. svr.Post("/test", [&](const Request &req, Response &) {
  8923. ASSERT_EQ(2u, req.form.fields.size());
  8924. const auto &text1 = req.form.get_field("text1");
  8925. ASSERT_EQ("text1", text1);
  8926. const auto &text2 = req.form.get_field("text2");
  8927. ASSERT_EQ("text2", text2);
  8928. handled = true;
  8929. });
  8930. thread t = thread([&] { svr.listen(HOST, PORT); });
  8931. auto se = detail::scope_exit([&] {
  8932. svr.stop();
  8933. t.join();
  8934. ASSERT_FALSE(svr.is_running());
  8935. ASSERT_TRUE(handled);
  8936. });
  8937. svr.wait_until_ready();
  8938. auto req = "POST /test HTTP/1.1\r\n"
  8939. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8940. "Content-Length: 146\r\n"
  8941. "\r\n----------\r\n"
  8942. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8943. "\r\n"
  8944. "text1"
  8945. "\r\n----------\r\n"
  8946. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8947. "\r\n"
  8948. "text2"
  8949. "\r\n------------";
  8950. std::string response;
  8951. ASSERT_TRUE(send_request(1, req, &response));
  8952. ASSERT_EQ("200", response.substr(9, 3));
  8953. }
  8954. TEST(MultipartFormDataTest, ContentLength) {
  8955. auto handled = false;
  8956. Server svr;
  8957. svr.Post("/test", [&](const Request &req, Response &) {
  8958. ASSERT_EQ(2u, req.form.fields.size());
  8959. const auto &text1 = req.form.get_field("text1");
  8960. ASSERT_EQ("text1", text1);
  8961. const auto &text2 = req.form.get_field("text2");
  8962. ASSERT_EQ("text2", text2);
  8963. handled = true;
  8964. });
  8965. thread t = thread([&] { svr.listen(HOST, PORT); });
  8966. auto se = detail::scope_exit([&] {
  8967. svr.stop();
  8968. t.join();
  8969. ASSERT_FALSE(svr.is_running());
  8970. ASSERT_TRUE(handled);
  8971. });
  8972. svr.wait_until_ready();
  8973. auto req = "POST /test HTTP/1.1\r\n"
  8974. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8975. "Content-Length: 167\r\n"
  8976. "\r\n----------\r\n"
  8977. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8978. "Content-Length: 5\r\n"
  8979. "\r\n"
  8980. "text1"
  8981. "\r\n----------\r\n"
  8982. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8983. "\r\n"
  8984. "text2"
  8985. "\r\n------------\r\n";
  8986. std::string response;
  8987. ASSERT_TRUE(send_request(1, req, &response));
  8988. ASSERT_EQ("200", response.substr(9, 3));
  8989. }
  8990. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8991. auto handled = false;
  8992. Server svr;
  8993. svr.Post("/test", [&](const Request &req, Response &) {
  8994. ASSERT_EQ(2u, req.form.fields.size());
  8995. const auto &text1 = req.form.get_field("text1");
  8996. ASSERT_EQ("text1", text1);
  8997. // TODO: Add header access for text fields if needed
  8998. const auto &text2 = req.form.get_field("text2");
  8999. ASSERT_EQ("text2", text2);
  9000. // TODO: Header access for text fields needs to be implemented
  9001. // auto &headers = it->second.headers;
  9002. // ASSERT_EQ(3U, headers.size());
  9003. // auto custom_header = headers.find("x-whatever");
  9004. // ASSERT_TRUE(custom_header != headers.end());
  9005. // ASSERT_NE("customvalue", custom_header->second);
  9006. // ASSERT_EQ("CustomValue", custom_header->second);
  9007. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9008. handled = true;
  9009. });
  9010. thread t = thread([&] { svr.listen(HOST, PORT); });
  9011. auto se = detail::scope_exit([&] {
  9012. svr.stop();
  9013. t.join();
  9014. ASSERT_FALSE(svr.is_running());
  9015. ASSERT_TRUE(handled);
  9016. });
  9017. svr.wait_until_ready();
  9018. auto req = "POST /test HTTP/1.1\r\n"
  9019. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9020. "Content-Length: 232\r\n"
  9021. "\r\n----------\r\n"
  9022. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9023. "Content-Length: 5\r\n"
  9024. "X-Test: 1\r\n"
  9025. "\r\n"
  9026. "text1"
  9027. "\r\n----------\r\n"
  9028. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9029. "Content-Type: text/plain\r\n"
  9030. "X-Whatever: CustomValue\r\n"
  9031. "\r\n"
  9032. "text2"
  9033. "\r\n------------\r\n"
  9034. "That should be disregarded. Not even read";
  9035. std::string response;
  9036. ASSERT_TRUE(send_request(1, req, &response));
  9037. ASSERT_EQ("200", response.substr(9, 3));
  9038. }
  9039. TEST(MultipartFormDataTest, LargeHeader) {
  9040. auto handled = false;
  9041. Server svr;
  9042. svr.Post("/test", [&](const Request &req, Response &) {
  9043. ASSERT_EQ(1u, req.form.fields.size());
  9044. const auto &text = req.form.get_field("name1");
  9045. ASSERT_EQ("text1", text);
  9046. handled = true;
  9047. });
  9048. thread t = thread([&] { svr.listen(HOST, PORT); });
  9049. auto se = detail::scope_exit([&] {
  9050. svr.stop();
  9051. t.join();
  9052. ASSERT_FALSE(svr.is_running());
  9053. ASSERT_TRUE(handled);
  9054. });
  9055. svr.wait_until_ready();
  9056. auto boundary = std::string("cpp-httplib-multipart-data");
  9057. std::string content = "--" + boundary +
  9058. "\r\n"
  9059. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9060. "\r\n"
  9061. "text1\r\n"
  9062. "--" +
  9063. boundary + "--\r\n";
  9064. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9065. "Content-Type: multipart/form-data;boundary=" +
  9066. boundary +
  9067. "\r\n"
  9068. "Content-Length: " +
  9069. std::to_string(content.size()) +
  9070. "\r\n"
  9071. "Dummy-Header: ";
  9072. std::string header_suffix = "\r\n"
  9073. "\r\n";
  9074. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9075. size_t header_dummy_size =
  9076. read_buff_size -
  9077. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9078. auto header_dummy = std::string(header_dummy_size, '@');
  9079. auto req = header_prefix + header_dummy + header_suffix + content;
  9080. std::string response;
  9081. ASSERT_TRUE(send_request(1, req, &response));
  9082. ASSERT_EQ("200", response.substr(9, 3));
  9083. }
  9084. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9085. static constexpr unsigned int number_of_tasks{1000000};
  9086. std::atomic_uint count{0};
  9087. std::unique_ptr<TaskQueue> task_queue{
  9088. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9089. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9090. auto queued = task_queue->enqueue(
  9091. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9092. EXPECT_TRUE(queued);
  9093. }
  9094. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9095. task_queue->shutdown();
  9096. #else
  9097. EXPECT_NO_THROW(task_queue->shutdown());
  9098. #endif
  9099. EXPECT_EQ(number_of_tasks, count.load());
  9100. }
  9101. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9102. static constexpr unsigned int number_of_tasks{1000000};
  9103. static constexpr unsigned int qlimit{2};
  9104. unsigned int queued_count{0};
  9105. std::atomic_uint count{0};
  9106. std::unique_ptr<TaskQueue> task_queue{
  9107. new ThreadPool{/*num_threads=*/1, qlimit}};
  9108. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9109. if (task_queue->enqueue(
  9110. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9111. queued_count++;
  9112. }
  9113. }
  9114. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9115. task_queue->shutdown();
  9116. #else
  9117. EXPECT_NO_THROW(task_queue->shutdown());
  9118. #endif
  9119. EXPECT_EQ(queued_count, count.load());
  9120. EXPECT_TRUE(queued_count <= number_of_tasks);
  9121. EXPECT_TRUE(queued_count >= qlimit);
  9122. }
  9123. TEST(TaskQueueTest, MaxQueuedRequests) {
  9124. static constexpr unsigned int qlimit{3};
  9125. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9126. std::condition_variable sem_cv;
  9127. std::mutex sem_mtx;
  9128. int credits = 0;
  9129. bool queued;
  9130. /* Fill up the queue with tasks that will block until we give them credits to
  9131. * complete. */
  9132. for (unsigned int n = 0; n <= qlimit;) {
  9133. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9134. std::unique_lock<std::mutex> lock(sem_mtx);
  9135. while (credits <= 0) {
  9136. sem_cv.wait(lock);
  9137. }
  9138. /* Consume the credit and signal the test code if they are all gone. */
  9139. if (--credits == 0) { sem_cv.notify_one(); }
  9140. });
  9141. if (n < qlimit) {
  9142. /* The first qlimit enqueues must succeed. */
  9143. EXPECT_TRUE(queued);
  9144. } else {
  9145. /* The last one will succeed only when the worker thread
  9146. * starts and dequeues the first blocking task. Although
  9147. * not necessary for the correctness of this test, we sleep for
  9148. * a short while to avoid busy waiting. */
  9149. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9150. }
  9151. if (queued) { n++; }
  9152. }
  9153. /* Further enqueues must fail since the queue is full. */
  9154. for (auto i = 0; i < 4; i++) {
  9155. queued = task_queue->enqueue([] {});
  9156. EXPECT_FALSE(queued);
  9157. }
  9158. /* Give the credits to allow the previous tasks to complete. */
  9159. {
  9160. std::unique_lock<std::mutex> lock(sem_mtx);
  9161. credits += qlimit + 1;
  9162. }
  9163. sem_cv.notify_all();
  9164. /* Wait for all the credits to be consumed. */
  9165. {
  9166. std::unique_lock<std::mutex> lock(sem_mtx);
  9167. while (credits > 0) {
  9168. sem_cv.wait(lock);
  9169. }
  9170. }
  9171. /* Check that we are able again to enqueue at least qlimit tasks. */
  9172. for (unsigned int i = 0; i < qlimit; i++) {
  9173. queued = task_queue->enqueue([] {});
  9174. EXPECT_TRUE(queued);
  9175. }
  9176. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  9177. task_queue->shutdown();
  9178. #else
  9179. EXPECT_NO_THROW(task_queue->shutdown());
  9180. #endif
  9181. }
  9182. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9183. Server svr;
  9184. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9185. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9186. });
  9187. svr.Get("/hello", [](const Request &req, Response &res) {
  9188. res.set_content(req.get_param_value("key"), "text/plain");
  9189. });
  9190. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9191. auto se = detail::scope_exit([&] {
  9192. svr.stop();
  9193. thread.join();
  9194. ASSERT_FALSE(svr.is_running());
  9195. });
  9196. svr.wait_until_ready();
  9197. {
  9198. Client cli(HOST, PORT);
  9199. cli.set_follow_location(true);
  9200. auto res = cli.Get("/");
  9201. ASSERT_TRUE(res);
  9202. EXPECT_EQ(StatusCode::OK_200, res->status);
  9203. EXPECT_EQ("val&key2=val2", res->body);
  9204. }
  9205. }
  9206. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9207. Server svr;
  9208. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9209. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9210. });
  9211. svr.Get("/hello", [](const Request &req, Response &res) {
  9212. res.set_content(req.get_param_value("key"), "text/plain");
  9213. });
  9214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9215. auto se = detail::scope_exit([&] {
  9216. svr.stop();
  9217. thread.join();
  9218. ASSERT_FALSE(svr.is_running());
  9219. });
  9220. svr.wait_until_ready();
  9221. {
  9222. Client cli(HOST, PORT);
  9223. cli.set_follow_location(true);
  9224. auto res = cli.Get("/");
  9225. ASSERT_TRUE(res);
  9226. EXPECT_EQ(StatusCode::OK_200, res->status);
  9227. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9228. }
  9229. }
  9230. #ifdef CPPHTTPLIB_SSL_ENABLED
  9231. TEST(RedirectTest, Issue2185_Online) {
  9232. SSLClient client("github.com");
  9233. client.set_follow_location(true);
  9234. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9235. "Coollab-Windows.zip");
  9236. ASSERT_TRUE(res);
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ(9920427U, res->body.size());
  9239. }
  9240. #endif
  9241. TEST(VulnerabilityTest, CRLFInjection) {
  9242. Server svr;
  9243. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9244. res.set_content("Hello 1", "text/plain");
  9245. });
  9246. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9247. res.set_content("Hello 2", "text/plain");
  9248. });
  9249. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9250. res.set_content("Hello 3", "text/plain");
  9251. });
  9252. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9253. res.set_content("Hello 4", "text/plain");
  9254. });
  9255. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9256. for (const auto &x : req.headers) {
  9257. auto key = x.first;
  9258. EXPECT_STRNE("evil", key.c_str());
  9259. }
  9260. });
  9261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9262. auto se = detail::scope_exit([&] {
  9263. svr.stop();
  9264. thread.join();
  9265. ASSERT_FALSE(svr.is_running());
  9266. });
  9267. svr.wait_until_ready();
  9268. {
  9269. Client cli(HOST, PORT);
  9270. cli.Post("/test1", "A=B",
  9271. "application/x-www-form-urlencoded\r\nevil: hello1");
  9272. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9273. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9274. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9275. }
  9276. }
  9277. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9278. auto server_thread = std::thread([] {
  9279. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9280. default_socket_options(srv);
  9281. sockaddr_in addr{};
  9282. addr.sin_family = AF_INET;
  9283. addr.sin_port = htons(PORT + 1);
  9284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9285. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9286. ::listen(srv, 1);
  9287. sockaddr_in cli_addr{};
  9288. socklen_t cli_len = sizeof(cli_addr);
  9289. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9290. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9291. std::string buf_all;
  9292. char buf[2048];
  9293. ssize_t n;
  9294. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9295. buf_all.append(buf, static_cast<size_t>(n));
  9296. size_t pos;
  9297. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9298. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9299. auto e = request_block.find("\r\n");
  9300. if (e != std::string::npos) {
  9301. auto request_line = request_block.substr(0, e);
  9302. std::string msg =
  9303. "CRLF injection detected in request line: '" + request_line + "'";
  9304. EXPECT_FALSE(true) << msg;
  9305. }
  9306. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9307. ::send(cli,
  9308. #ifdef _WIN32
  9309. static_cast<const char *>(resp.c_str()),
  9310. static_cast<int>(resp.size()),
  9311. #else
  9312. resp.c_str(), resp.size(),
  9313. #endif
  9314. 0);
  9315. buf_all.erase(0, pos + 4);
  9316. }
  9317. }
  9318. detail::close_socket(cli);
  9319. detail::close_socket(srv);
  9320. });
  9321. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9322. auto cli = Client("127.0.0.1", PORT + 1);
  9323. auto headers = Headers{
  9324. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9325. {"Connection", "keep-alive"}};
  9326. auto res = cli.Get("/hi", headers);
  9327. EXPECT_FALSE(res);
  9328. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9329. server_thread.join();
  9330. }
  9331. TEST(PathParamsTest, StaticMatch) {
  9332. const auto pattern = "/users/all";
  9333. detail::PathParamsMatcher matcher(pattern);
  9334. Request request;
  9335. request.path = "/users/all";
  9336. ASSERT_TRUE(matcher.match(request));
  9337. std::unordered_map<std::string, std::string> expected_params = {};
  9338. EXPECT_EQ(request.path_params, expected_params);
  9339. }
  9340. TEST(PathParamsTest, StaticMismatch) {
  9341. const auto pattern = "/users/all";
  9342. detail::PathParamsMatcher matcher(pattern);
  9343. Request request;
  9344. request.path = "/users/1";
  9345. ASSERT_FALSE(matcher.match(request));
  9346. }
  9347. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9348. const auto pattern = "/users/:id/subscriptions";
  9349. detail::PathParamsMatcher matcher(pattern);
  9350. Request request;
  9351. request.path = "/users/42/subscriptions";
  9352. ASSERT_TRUE(matcher.match(request));
  9353. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9354. EXPECT_EQ(request.path_params, expected_params);
  9355. }
  9356. TEST(PathParamsTest, SingleParamInTheEnd) {
  9357. const auto pattern = "/users/:id";
  9358. detail::PathParamsMatcher matcher(pattern);
  9359. Request request;
  9360. request.path = "/users/24";
  9361. ASSERT_TRUE(matcher.match(request));
  9362. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9363. EXPECT_EQ(request.path_params, expected_params);
  9364. }
  9365. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9366. const auto pattern = "/users/:id/";
  9367. detail::PathParamsMatcher matcher(pattern);
  9368. Request request;
  9369. request.path = "/users/42/";
  9370. ASSERT_TRUE(matcher.match(request));
  9371. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9372. EXPECT_EQ(request.path_params, expected_params);
  9373. }
  9374. TEST(PathParamsTest, EmptyParam) {
  9375. const auto pattern = "/users/:id/";
  9376. detail::PathParamsMatcher matcher(pattern);
  9377. Request request;
  9378. request.path = "/users//";
  9379. ASSERT_TRUE(matcher.match(request));
  9380. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9381. EXPECT_EQ(request.path_params, expected_params);
  9382. }
  9383. TEST(PathParamsTest, FragmentMismatch) {
  9384. const auto pattern = "/users/:id/";
  9385. detail::PathParamsMatcher matcher(pattern);
  9386. Request request;
  9387. request.path = "/admins/24/";
  9388. ASSERT_FALSE(matcher.match(request));
  9389. }
  9390. TEST(PathParamsTest, ExtraFragments) {
  9391. const auto pattern = "/users/:id";
  9392. detail::PathParamsMatcher matcher(pattern);
  9393. Request request;
  9394. request.path = "/users/42/subscriptions";
  9395. ASSERT_FALSE(matcher.match(request));
  9396. }
  9397. TEST(PathParamsTest, MissingTrailingParam) {
  9398. const auto pattern = "/users/:id";
  9399. detail::PathParamsMatcher matcher(pattern);
  9400. Request request;
  9401. request.path = "/users";
  9402. ASSERT_FALSE(matcher.match(request));
  9403. }
  9404. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9405. const auto pattern = "/users/:id/subscriptions";
  9406. detail::PathParamsMatcher matcher(pattern);
  9407. Request request;
  9408. request.path = "/users/subscriptions";
  9409. ASSERT_FALSE(matcher.match(request));
  9410. }
  9411. TEST(PathParamsTest, MultipleParams) {
  9412. const auto pattern = "/users/:userid/subscriptions/:subid";
  9413. detail::PathParamsMatcher matcher(pattern);
  9414. Request request;
  9415. request.path = "/users/42/subscriptions/2";
  9416. ASSERT_TRUE(matcher.match(request));
  9417. std::unordered_map<std::string, std::string> expected_params = {
  9418. {"userid", "42"}, {"subid", "2"}};
  9419. EXPECT_EQ(request.path_params, expected_params);
  9420. }
  9421. TEST(PathParamsTest, SequenceOfParams) {
  9422. const auto pattern = "/values/:x/:y/:z";
  9423. detail::PathParamsMatcher matcher(pattern);
  9424. Request request;
  9425. request.path = "/values/1/2/3";
  9426. ASSERT_TRUE(matcher.match(request));
  9427. std::unordered_map<std::string, std::string> expected_params = {
  9428. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9429. EXPECT_EQ(request.path_params, expected_params);
  9430. }
  9431. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9432. const auto pattern = "/prefix:suffix";
  9433. detail::PathParamsMatcher matcher(pattern);
  9434. Request request;
  9435. request.path = "/prefix:suffix";
  9436. ASSERT_TRUE(matcher.match(request));
  9437. const std::unordered_map<std::string, std::string> expected_params = {};
  9438. EXPECT_EQ(request.path_params, expected_params);
  9439. }
  9440. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9441. // If ipv6 regex working, regex match codepath is taken.
  9442. // else port will default to 80 in Client impl
  9443. int clientImplMagicPort = 80;
  9444. int port = 4321;
  9445. // above ports must be different to avoid false negative
  9446. EXPECT_NE(clientImplMagicPort, port);
  9447. std::string ipV6TestURL = "http://[ff06::c3]";
  9448. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9449. CLIENT_PRIVATE_KEY_FILE);
  9450. EXPECT_EQ(cli.port(), port);
  9451. }
  9452. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9453. auto file_path = "./www/dir/index.html";
  9454. auto dir_path = "./www/dir";
  9455. detail::FileStat stat_file(file_path);
  9456. EXPECT_TRUE(stat_file.is_file());
  9457. EXPECT_FALSE(stat_file.is_dir());
  9458. detail::FileStat stat_dir(dir_path);
  9459. EXPECT_FALSE(stat_dir.is_file());
  9460. EXPECT_TRUE(stat_dir.is_dir());
  9461. }
  9462. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9463. // IPv4 with default HTTP port (80)
  9464. EXPECT_EQ("example.com",
  9465. detail::make_host_and_port_string("example.com", 80, false));
  9466. // IPv4 with default HTTPS port (443)
  9467. EXPECT_EQ("example.com",
  9468. detail::make_host_and_port_string("example.com", 443, true));
  9469. // IPv4 with non-default HTTP port
  9470. EXPECT_EQ("example.com:8080",
  9471. detail::make_host_and_port_string("example.com", 8080, false));
  9472. // IPv4 with non-default HTTPS port
  9473. EXPECT_EQ("example.com:8443",
  9474. detail::make_host_and_port_string("example.com", 8443, true));
  9475. // IPv6 with default HTTP port (80)
  9476. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9477. // IPv6 with default HTTPS port (443)
  9478. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9479. // IPv6 with non-default HTTP port
  9480. EXPECT_EQ("[::1]:8080",
  9481. detail::make_host_and_port_string("::1", 8080, false));
  9482. // IPv6 with non-default HTTPS port
  9483. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9484. // IPv6 full address with default port
  9485. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9486. detail::make_host_and_port_string(
  9487. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9488. // IPv6 full address with non-default port
  9489. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9490. detail::make_host_and_port_string(
  9491. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9492. // IPv6 localhost with non-default port
  9493. EXPECT_EQ("[::1]:3000",
  9494. detail::make_host_and_port_string("::1", 3000, false));
  9495. // IPv6 with zone ID (link-local address) with default port
  9496. EXPECT_EQ("[fe80::1%eth0]",
  9497. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9498. // IPv6 with zone ID (link-local address) with non-default port
  9499. EXPECT_EQ("[fe80::1%eth0]:8080",
  9500. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9501. // Edge case: Port 443 with is_ssl=false (should add port)
  9502. EXPECT_EQ("example.com:443",
  9503. detail::make_host_and_port_string("example.com", 443, false));
  9504. // Edge case: Port 80 with is_ssl=true (should add port)
  9505. EXPECT_EQ("example.com:80",
  9506. detail::make_host_and_port_string("example.com", 80, true));
  9507. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9508. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9509. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9510. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9511. // Security fix: Already bracketed IPv6 should not get double brackets
  9512. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9513. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9514. EXPECT_EQ("[::1]:8080",
  9515. detail::make_host_and_port_string("[::1]", 8080, false));
  9516. EXPECT_EQ("[2001:db8::1]:8080",
  9517. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9518. EXPECT_EQ("[fe80::1%eth0]",
  9519. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9520. EXPECT_EQ("[fe80::1%eth0]:8080",
  9521. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9522. // Edge case: Empty host (should return as-is)
  9523. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9524. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9525. // This is a known limitation but shouldn't crash
  9526. EXPECT_EQ("[host:name]",
  9527. detail::make_host_and_port_string("host:name", 80, false));
  9528. // Port number edge cases (no validation, but should not crash)
  9529. EXPECT_EQ("example.com:0",
  9530. detail::make_host_and_port_string("example.com", 0, false));
  9531. EXPECT_EQ("example.com:-1",
  9532. detail::make_host_and_port_string("example.com", -1, false));
  9533. EXPECT_EQ("example.com:65535",
  9534. detail::make_host_and_port_string("example.com", 65535, false));
  9535. EXPECT_EQ("example.com:65536",
  9536. detail::make_host_and_port_string("example.com", 65536, false));
  9537. }
  9538. #ifdef CPPHTTPLIB_SSL_ENABLED
  9539. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9540. httplib::SSLClient cli("roblox.com", 443);
  9541. cli.set_follow_location(true);
  9542. auto res = cli.Get("/");
  9543. ASSERT_TRUE(res);
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. }
  9546. #endif
  9547. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9548. Server svr;
  9549. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9550. EXPECT_EQ(res.status, 400);
  9551. });
  9552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. thread.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. Client cli(HOST, PORT);
  9560. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9561. }
  9562. TEST(InvalidHeaderCharsTest, is_field_name) {
  9563. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9564. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9565. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9566. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9567. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9568. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9569. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9570. EXPECT_FALSE(detail::fields::is_field_name(""));
  9571. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9572. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9573. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9574. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9575. }
  9576. TEST(InvalidHeaderCharsTest, is_field_value) {
  9577. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9578. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9579. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9580. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9581. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9582. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9583. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9584. EXPECT_TRUE(detail::fields::is_field_value(""));
  9585. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9586. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9587. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9588. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9589. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9590. }
  9591. TEST(InvalidHeaderCharsTest, OnServer) {
  9592. Server svr;
  9593. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9594. std::string header = "Not Set";
  9595. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9596. res.set_header(header, "value");
  9597. res.set_content("Page Content Page Content", "text/plain");
  9598. });
  9599. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9600. std::string header = "Not Set";
  9601. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9602. res.set_header("X-Test", header);
  9603. res.set_content("Page Content Page Content", "text/plain");
  9604. });
  9605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9606. auto se = detail::scope_exit([&] {
  9607. svr.stop();
  9608. thread.join();
  9609. ASSERT_FALSE(svr.is_running());
  9610. });
  9611. svr.wait_until_ready();
  9612. Client cli(HOST, PORT);
  9613. {
  9614. auto res = cli.Get(
  9615. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9616. ASSERT_TRUE(res);
  9617. EXPECT_EQ("Page Content Page Content", res->body);
  9618. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9619. }
  9620. {
  9621. auto res = cli.Get(
  9622. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9623. ASSERT_TRUE(res);
  9624. EXPECT_EQ("Page Content Page Content", res->body);
  9625. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9626. }
  9627. }
  9628. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9629. auto handled = false;
  9630. Server svr;
  9631. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9632. thread t = thread([&] { svr.listen(HOST, PORT); });
  9633. auto se = detail::scope_exit([&] {
  9634. svr.stop();
  9635. t.join();
  9636. ASSERT_FALSE(svr.is_running());
  9637. ASSERT_FALSE(handled);
  9638. });
  9639. svr.wait_until_ready();
  9640. auto req = "POST /test HTTP/1.1\r\n"
  9641. "Content-Length: x\r\n"
  9642. "\r\n";
  9643. std::string response;
  9644. ASSERT_TRUE(send_request(1, req, &response));
  9645. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9646. response.substr(0, response.find("\r\n")));
  9647. }
  9648. #ifndef _WIN32
  9649. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9650. static constexpr char reject[] = "Unauthorized";
  9651. static constexpr char accept[] = "Upload accepted";
  9652. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9653. Server svr;
  9654. svr.set_expect_100_continue_handler(
  9655. [](const Request & /*req*/, Response &res) {
  9656. res.status = StatusCode::Unauthorized_401;
  9657. res.set_content(reject, "text/plain");
  9658. return res.status;
  9659. });
  9660. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9661. res.set_content(accept, "text/plain");
  9662. });
  9663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9664. auto se = detail::scope_exit([&] {
  9665. svr.stop();
  9666. thread.join();
  9667. ASSERT_FALSE(svr.is_running());
  9668. });
  9669. svr.wait_until_ready();
  9670. {
  9671. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9672. curl_easy_init(), &curl_easy_cleanup};
  9673. ASSERT_NE(curl, nullptr);
  9674. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9675. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9676. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9677. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9678. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9679. &curl_slist_free_all};
  9680. ASSERT_NE(list, nullptr);
  9681. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9682. struct read_data {
  9683. size_t read_size;
  9684. size_t total_size;
  9685. } data = {0, total_size};
  9686. using read_callback_t =
  9687. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9688. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9689. void *userdata) -> size_t {
  9690. read_data *data = (read_data *)userdata;
  9691. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9692. std::fill_n(ptr, size * nmemb, 'A');
  9693. data->read_size += size * nmemb;
  9694. return size * nmemb;
  9695. };
  9696. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9697. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9698. std::vector<char> buffer;
  9699. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9700. using write_callback_t =
  9701. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9702. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9703. void *userdata) -> size_t {
  9704. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9705. buffer->reserve(buffer->size() + size * nmemb + 1);
  9706. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9707. return size * nmemb;
  9708. };
  9709. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9710. {
  9711. const auto res = curl_easy_perform(curl.get());
  9712. ASSERT_EQ(res, CURLE_OK);
  9713. }
  9714. {
  9715. auto response_code = long{};
  9716. const auto res =
  9717. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9718. ASSERT_EQ(res, CURLE_OK);
  9719. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9720. }
  9721. {
  9722. auto dl = curl_off_t{};
  9723. const auto res =
  9724. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9725. ASSERT_EQ(res, CURLE_OK);
  9726. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9727. }
  9728. {
  9729. buffer.push_back('\0');
  9730. ASSERT_STRCASEEQ(buffer.data(), reject);
  9731. }
  9732. }
  9733. }
  9734. #endif
  9735. template <typename S, typename C>
  9736. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9737. svr.Get("/stream", [&](const Request &, Response &res) {
  9738. auto data = new std::string("01234567890123456789");
  9739. res.set_content_provider(
  9740. data->size(), "text/plain",
  9741. [&, data](size_t offset, size_t length, DataSink &sink) {
  9742. const size_t DATA_CHUNK_SIZE = 4;
  9743. const auto &d = *data;
  9744. std::this_thread::sleep_for(std::chrono::seconds(1));
  9745. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9746. return true;
  9747. },
  9748. [data](bool success) {
  9749. EXPECT_FALSE(success);
  9750. delete data;
  9751. });
  9752. });
  9753. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9754. auto i = new size_t(0);
  9755. res.set_content_provider(
  9756. "text/plain",
  9757. [i](size_t, DataSink &sink) {
  9758. if (*i < 5) {
  9759. std::this_thread::sleep_for(std::chrono::seconds(1));
  9760. sink.write("abcd", 4);
  9761. (*i)++;
  9762. } else {
  9763. sink.done();
  9764. }
  9765. return true;
  9766. },
  9767. [i](bool success) {
  9768. EXPECT_FALSE(success);
  9769. delete i;
  9770. });
  9771. });
  9772. svr.Get("/chunked", [&](const Request &, Response &res) {
  9773. auto i = new size_t(0);
  9774. res.set_chunked_content_provider(
  9775. "text/plain",
  9776. [i](size_t, DataSink &sink) {
  9777. if (*i < 5) {
  9778. std::this_thread::sleep_for(std::chrono::seconds(1));
  9779. sink.os << "abcd";
  9780. (*i)++;
  9781. } else {
  9782. sink.done();
  9783. }
  9784. return true;
  9785. },
  9786. [i](bool success) {
  9787. EXPECT_FALSE(success);
  9788. delete i;
  9789. });
  9790. });
  9791. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9792. auto se = detail::scope_exit([&] {
  9793. svr.stop();
  9794. listen_thread.join();
  9795. ASSERT_FALSE(svr.is_running());
  9796. });
  9797. svr.wait_until_ready();
  9798. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9799. {
  9800. auto start = std::chrono::steady_clock::now();
  9801. auto res = cli.Get("/stream");
  9802. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9803. std::chrono::steady_clock::now() - start)
  9804. .count();
  9805. ASSERT_FALSE(res);
  9806. EXPECT_EQ(Error::Read, res.error());
  9807. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9808. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9809. }
  9810. {
  9811. auto start = std::chrono::steady_clock::now();
  9812. auto res = cli.Get("/stream_without_length");
  9813. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9814. std::chrono::steady_clock::now() - start)
  9815. .count();
  9816. ASSERT_FALSE(res);
  9817. EXPECT_EQ(Error::Read, res.error());
  9818. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9819. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9820. }
  9821. {
  9822. auto start = std::chrono::steady_clock::now();
  9823. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9824. EXPECT_EQ("abcd", string(data, data_length));
  9825. return true;
  9826. });
  9827. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9828. std::chrono::steady_clock::now() - start)
  9829. .count();
  9830. ASSERT_FALSE(res);
  9831. EXPECT_EQ(Error::Read, res.error());
  9832. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9833. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9834. }
  9835. }
  9836. TEST(MaxTimeoutTest, ContentStream) {
  9837. time_t timeout = 2000;
  9838. time_t threshold = 200;
  9839. Server svr;
  9840. Client cli("localhost", PORT);
  9841. max_timeout_test(svr, cli, timeout, threshold);
  9842. }
  9843. #ifdef CPPHTTPLIB_SSL_ENABLED
  9844. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9845. time_t timeout = 2000;
  9846. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9848. SSLClient cli("localhost", PORT);
  9849. cli.enable_server_certificate_verification(false);
  9850. max_timeout_test(svr, cli, timeout, threshold);
  9851. }
  9852. #endif
  9853. class EventDispatcher {
  9854. public:
  9855. EventDispatcher() {}
  9856. bool wait_event(DataSink *sink) {
  9857. unique_lock<mutex> lk(m_);
  9858. int id = id_;
  9859. // Wait with timeout to prevent hanging if client disconnects
  9860. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9861. [&] { return cid_ == id; })) {
  9862. return false; // Timeout occurred
  9863. }
  9864. sink->write(message_.data(), message_.size());
  9865. return true;
  9866. }
  9867. void send_event(const string &message) {
  9868. lock_guard<mutex> lk(m_);
  9869. cid_ = id_++;
  9870. message_ = message;
  9871. cv_.notify_all();
  9872. }
  9873. private:
  9874. mutex m_;
  9875. condition_variable cv_;
  9876. atomic_int id_{0};
  9877. atomic_int cid_{-1};
  9878. string message_;
  9879. };
  9880. TEST(ClientInThreadTest, Issue2068) {
  9881. EventDispatcher ed;
  9882. Server svr;
  9883. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9884. res.set_chunked_content_provider("text/event-stream",
  9885. [&](size_t /*offset*/, DataSink &sink) {
  9886. return ed.wait_event(&sink);
  9887. });
  9888. });
  9889. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9890. svr.wait_until_ready();
  9891. thread event_thread([&] {
  9892. int id = 0;
  9893. while (svr.is_running()) {
  9894. this_thread::sleep_for(chrono::milliseconds(500));
  9895. std::stringstream ss;
  9896. ss << "data: " << id << "\n\n";
  9897. ed.send_event(ss.str());
  9898. id++;
  9899. }
  9900. });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. listen_thread.join();
  9904. event_thread.join();
  9905. ASSERT_FALSE(svr.is_running());
  9906. });
  9907. {
  9908. auto client = detail::make_unique<Client>(HOST, PORT);
  9909. client->set_read_timeout(std::chrono::minutes(10));
  9910. std::atomic<bool> stop{false};
  9911. std::thread t([&] {
  9912. client->Get("/event1",
  9913. [&](const char *, size_t) -> bool { return !stop; });
  9914. });
  9915. std::this_thread::sleep_for(std::chrono::seconds(2));
  9916. stop = true;
  9917. client->stop();
  9918. t.join();
  9919. // Reset client after thread has finished
  9920. client.reset();
  9921. }
  9922. }
  9923. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9924. Server svr;
  9925. svr.Get("/", [](const Request &req, Response &res) {
  9926. EXPECT_EQ(2U, req.trailers.size());
  9927. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9928. // Denied
  9929. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9930. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9931. // Accepted
  9932. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9933. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9934. EXPECT_TRUE(req.has_trailer("X-World"));
  9935. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9936. res.set_content("ok", "text/plain");
  9937. });
  9938. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9939. auto se = detail::scope_exit([&] {
  9940. svr.stop();
  9941. t.join();
  9942. ASSERT_FALSE(svr.is_running());
  9943. });
  9944. svr.wait_until_ready();
  9945. const std::string req = "GET / HTTP/1.1\r\n"
  9946. "Transfer-Encoding: chunked\r\n"
  9947. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9948. "\r\n"
  9949. "0\r\n"
  9950. "Content-Length: 10\r\n"
  9951. "Host: internal.local\r\n"
  9952. "Content-Type: malicious/content\r\n"
  9953. "Cookie: any\r\n"
  9954. "Set-Cookie: any\r\n"
  9955. "X-Forwarded-For: attacker.com\r\n"
  9956. "X-Real-Ip: 1.1.1.1\r\n"
  9957. "X-Hello: hello\r\n"
  9958. "X-World: world\r\n"
  9959. "\r\n";
  9960. std::string res;
  9961. ASSERT_TRUE(send_request(1, req, &res));
  9962. }
  9963. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9964. Server svr;
  9965. std::string observed_remote_addr;
  9966. std::string observed_xff;
  9967. svr.Get("/ip", [&](const Request &req, Response &res) {
  9968. observed_remote_addr = req.remote_addr;
  9969. observed_xff = req.get_header_value("X-Forwarded-For");
  9970. res.set_content("ok", "text/plain");
  9971. });
  9972. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9973. auto se = detail::scope_exit([&] {
  9974. svr.stop();
  9975. t.join();
  9976. ASSERT_FALSE(svr.is_running());
  9977. });
  9978. svr.wait_until_ready();
  9979. Client cli(HOST, PORT);
  9980. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9981. ASSERT_TRUE(res);
  9982. EXPECT_EQ(StatusCode::OK_200, res->status);
  9983. EXPECT_EQ(observed_xff, "203.0.113.66");
  9984. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9985. observed_remote_addr == "127.0.0.1");
  9986. }
  9987. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9988. Server svr;
  9989. svr.set_trusted_proxies({"203.0.113.66"});
  9990. std::string observed_remote_addr;
  9991. std::string observed_xff;
  9992. svr.Get("/ip", [&](const Request &req, Response &res) {
  9993. observed_remote_addr = req.remote_addr;
  9994. observed_xff = req.get_header_value("X-Forwarded-For");
  9995. res.set_content("ok", "text/plain");
  9996. });
  9997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9998. auto se = detail::scope_exit([&] {
  9999. svr.stop();
  10000. t.join();
  10001. ASSERT_FALSE(svr.is_running());
  10002. });
  10003. svr.wait_until_ready();
  10004. Client cli(HOST, PORT);
  10005. auto res = cli.Get("/ip");
  10006. ASSERT_TRUE(res);
  10007. EXPECT_EQ(StatusCode::OK_200, res->status);
  10008. EXPECT_EQ(observed_xff, "");
  10009. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10010. observed_remote_addr == "127.0.0.1");
  10011. }
  10012. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10013. Server svr;
  10014. svr.set_trusted_proxies({"203.0.113.66"});
  10015. std::string observed_remote_addr;
  10016. std::string observed_xff;
  10017. svr.Get("/ip", [&](const Request &req, Response &res) {
  10018. observed_remote_addr = req.remote_addr;
  10019. observed_xff = req.get_header_value("X-Forwarded-For");
  10020. res.set_content("ok", "text/plain");
  10021. });
  10022. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. });
  10028. svr.wait_until_ready();
  10029. Client cli(HOST, PORT);
  10030. auto res =
  10031. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10032. ASSERT_TRUE(res);
  10033. EXPECT_EQ(StatusCode::OK_200, res->status);
  10034. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10035. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10036. }
  10037. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10038. Server svr;
  10039. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10040. std::string observed_remote_addr;
  10041. std::string observed_xff;
  10042. svr.Get("/ip", [&](const Request &req, Response &res) {
  10043. observed_remote_addr = req.remote_addr;
  10044. observed_xff = req.get_header_value("X-Forwarded-For");
  10045. res.set_content("ok", "text/plain");
  10046. });
  10047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10048. auto se = detail::scope_exit([&] {
  10049. svr.stop();
  10050. t.join();
  10051. ASSERT_FALSE(svr.is_running());
  10052. });
  10053. svr.wait_until_ready();
  10054. Client cli(HOST, PORT);
  10055. auto res = cli.Get(
  10056. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10057. ASSERT_TRUE(res);
  10058. EXPECT_EQ(StatusCode::OK_200, res->status);
  10059. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10060. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10061. }
  10062. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10063. Server svr;
  10064. svr.set_trusted_proxies({"192.0.2.45"});
  10065. std::string observed_remote_addr;
  10066. std::string observed_xff;
  10067. svr.Get("/ip", [&](const Request &req, Response &res) {
  10068. observed_remote_addr = req.remote_addr;
  10069. observed_xff = req.get_header_value("X-Forwarded-For");
  10070. res.set_content("ok", "text/plain");
  10071. });
  10072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10073. auto se = detail::scope_exit([&] {
  10074. svr.stop();
  10075. t.join();
  10076. ASSERT_FALSE(svr.is_running());
  10077. });
  10078. svr.wait_until_ready();
  10079. Client cli(HOST, PORT);
  10080. auto res =
  10081. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10082. ASSERT_TRUE(res);
  10083. EXPECT_EQ(StatusCode::OK_200, res->status);
  10084. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10085. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10086. }
  10087. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10088. Server svr;
  10089. svr.set_trusted_proxies({"192.0.2.45"});
  10090. std::string observed_remote_addr;
  10091. std::string observed_xff;
  10092. svr.Get("/ip", [&](const Request &req, Response &res) {
  10093. observed_remote_addr = req.remote_addr;
  10094. observed_xff = req.get_header_value("X-Forwarded-For");
  10095. res.set_content("ok", "text/plain");
  10096. });
  10097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. t.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. Client cli(HOST, PORT);
  10105. auto res = cli.Get(
  10106. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10107. ASSERT_TRUE(res);
  10108. EXPECT_EQ(StatusCode::OK_200, res->status);
  10109. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10110. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10111. }
  10112. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10113. Server svr;
  10114. svr.set_trusted_proxies({"192.0.2.45"});
  10115. std::string observed_remote_addr;
  10116. std::string observed_xff;
  10117. svr.Get("/ip", [&](const Request &req, Response &res) {
  10118. observed_remote_addr = req.remote_addr;
  10119. observed_xff = req.get_header_value("X-Forwarded-For");
  10120. res.set_content("ok", "text/plain");
  10121. });
  10122. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. t.join();
  10126. ASSERT_FALSE(svr.is_running());
  10127. });
  10128. svr.wait_until_ready();
  10129. std::string raw_req =
  10130. "GET /ip HTTP/1.1\r\n"
  10131. "Host: localhost\r\n"
  10132. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10133. "Connection: close\r\n"
  10134. "\r\n";
  10135. std::string out;
  10136. ASSERT_TRUE(send_request(5, raw_req, &out));
  10137. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10138. // Header parser trims surrounding whitespace of the header value
  10139. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10140. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10141. }
  10142. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10143. Server svr;
  10144. svr.Post("/post", [&](const Request &req, Response &res) {
  10145. res.set_content(req.body, "text/plain");
  10146. });
  10147. svr.Put("/put", [&](const Request &req, Response &res) {
  10148. res.set_content(req.body, "text/plain");
  10149. });
  10150. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10151. res.set_content(req.body, "text/plain");
  10152. });
  10153. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10154. res.set_content(req.body, "text/plain");
  10155. });
  10156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. t.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. std::string resp;
  10164. // POST without Content-Length
  10165. ASSERT_TRUE(send_request(5,
  10166. "POST /post HTTP/1.1\r\n"
  10167. "Host: localhost\r\n"
  10168. "Connection: close\r\n"
  10169. "\r\n",
  10170. &resp));
  10171. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10172. // PUT without Content-Length
  10173. resp.clear();
  10174. ASSERT_TRUE(send_request(5,
  10175. "PUT /put HTTP/1.1\r\n"
  10176. "Host: localhost\r\n"
  10177. "Connection: close\r\n"
  10178. "\r\n",
  10179. &resp));
  10180. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10181. // PATCH without Content-Length
  10182. resp.clear();
  10183. ASSERT_TRUE(send_request(5,
  10184. "PATCH /patch HTTP/1.1\r\n"
  10185. "Host: localhost\r\n"
  10186. "Connection: close\r\n"
  10187. "\r\n",
  10188. &resp));
  10189. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10190. // DELETE without Content-Length
  10191. resp.clear();
  10192. ASSERT_TRUE(send_request(5,
  10193. "DELETE /delete HTTP/1.1\r\n"
  10194. "Host: localhost\r\n"
  10195. "Connection: close\r\n"
  10196. "\r\n",
  10197. &resp));
  10198. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10199. }
  10200. //==============================================================================
  10201. // open_stream() Tests
  10202. //==============================================================================
  10203. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10204. std::string result;
  10205. char buf[8192];
  10206. ssize_t n;
  10207. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10208. result.append(buf, static_cast<size_t>(n));
  10209. }
  10210. return result;
  10211. }
  10212. // Mock stream for unit tests
  10213. class MockStream : public Stream {
  10214. public:
  10215. std::string data;
  10216. size_t pos = 0;
  10217. ssize_t error_after = -1; // -1 = no error
  10218. explicit MockStream(const std::string &d, ssize_t err = -1)
  10219. : data(d), error_after(err) {}
  10220. bool is_readable() const override { return true; }
  10221. bool wait_readable() const override { return true; }
  10222. bool wait_writable() const override { return true; }
  10223. ssize_t read(char *ptr, size_t size) override {
  10224. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10225. if (pos >= data.size()) return 0;
  10226. size_t limit =
  10227. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10228. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10229. std::memcpy(ptr, data.data() + pos, to_read);
  10230. pos += to_read;
  10231. return static_cast<ssize_t>(to_read);
  10232. }
  10233. ssize_t write(const char *, size_t) override { return -1; }
  10234. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10235. ip = "127.0.0.1";
  10236. port = 0;
  10237. }
  10238. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10239. ip = "127.0.0.1";
  10240. port = 0;
  10241. }
  10242. socket_t socket() const override { return INVALID_SOCKET; }
  10243. time_t duration() const override { return 0; }
  10244. };
  10245. TEST(StreamHandleTest, Basic) {
  10246. ClientImpl::StreamHandle handle;
  10247. EXPECT_FALSE(handle.is_valid());
  10248. handle.response = detail::make_unique<Response>();
  10249. handle.error = Error::Connection;
  10250. EXPECT_FALSE(handle.is_valid());
  10251. handle.error = Error::Success;
  10252. EXPECT_TRUE(handle.is_valid());
  10253. }
  10254. TEST(BodyReaderTest, Basic) {
  10255. MockStream stream("Hello, World!");
  10256. detail::BodyReader reader;
  10257. reader.stream = &stream;
  10258. reader.content_length = 13;
  10259. char buf[32];
  10260. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10261. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10262. EXPECT_TRUE(reader.eof);
  10263. }
  10264. TEST(BodyReaderTest, NoStream) {
  10265. detail::BodyReader reader;
  10266. char buf[32];
  10267. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10268. EXPECT_EQ(Error::Connection, reader.last_error);
  10269. }
  10270. TEST(BodyReaderTest, Error) {
  10271. MockStream stream("Hello, World!", 5);
  10272. detail::BodyReader reader;
  10273. reader.stream = &stream;
  10274. reader.content_length = 13;
  10275. char buf[32];
  10276. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10277. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10278. EXPECT_EQ(Error::Read, reader.last_error);
  10279. }
  10280. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10281. // Mock-based StreamHandle tests relying on private internals are removed.
  10282. class OpenStreamTest : public ::testing::Test {
  10283. protected:
  10284. void SetUp() override {
  10285. svr_.Get("/hello", [](const Request &, Response &res) {
  10286. res.set_content("Hello World!", "text/plain");
  10287. });
  10288. svr_.Get("/large", [](const Request &, Response &res) {
  10289. res.set_content(std::string(10000, 'X'), "text/plain");
  10290. });
  10291. svr_.Get("/chunked", [](const Request &, Response &res) {
  10292. res.set_chunked_content_provider("text/plain",
  10293. [](size_t offset, DataSink &sink) {
  10294. if (offset < 15) {
  10295. sink.write("chunk", 5);
  10296. return true;
  10297. }
  10298. sink.done();
  10299. return true;
  10300. });
  10301. });
  10302. svr_.Get("/compressible", [](const Request &, Response &res) {
  10303. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10304. DataSink &sink) {
  10305. if (offset < 100 * 1024) {
  10306. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10307. sink.write(chunk.data(), chunk.size());
  10308. return true;
  10309. }
  10310. sink.done();
  10311. return true;
  10312. });
  10313. });
  10314. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10315. [](const Request & /*req*/, Response &res) {
  10316. auto i = new int(0);
  10317. res.set_header("Trailer", "Content-Length, X-Allowed");
  10318. res.set_chunked_content_provider(
  10319. "text/plain",
  10320. [i](size_t /*offset*/, DataSink &sink) {
  10321. switch (*i) {
  10322. case 0: sink.os << "123"; break;
  10323. case 1: sink.os << "456"; break;
  10324. case 2: sink.os << "789"; break;
  10325. case 3: {
  10326. sink.done_with_trailer(
  10327. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10328. } break;
  10329. }
  10330. (*i)++;
  10331. return true;
  10332. },
  10333. [i](bool success) {
  10334. EXPECT_TRUE(success);
  10335. delete i;
  10336. });
  10337. });
  10338. // Echo headers endpoint for header-related tests
  10339. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10340. std::string body;
  10341. for (const auto &h : req.headers) {
  10342. body.append(h.first);
  10343. body.push_back(':');
  10344. body.append(h.second);
  10345. body.push_back('\n');
  10346. }
  10347. res.set_content(body, "text/plain");
  10348. });
  10349. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10350. std::string body;
  10351. for (const auto &h : req.headers) {
  10352. body.append(h.first);
  10353. body.push_back(':');
  10354. body.append(h.second);
  10355. body.push_back('\n');
  10356. }
  10357. res.set_content(body, "text/plain");
  10358. });
  10359. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10360. svr_.wait_until_ready();
  10361. }
  10362. void TearDown() override {
  10363. svr_.stop();
  10364. if (thread_.joinable()) thread_.join();
  10365. }
  10366. Server svr_;
  10367. std::thread thread_;
  10368. };
  10369. TEST_F(OpenStreamTest, Basic) {
  10370. Client cli("127.0.0.1", 8787);
  10371. auto handle = cli.open_stream("GET", "/hello");
  10372. EXPECT_TRUE(handle.is_valid());
  10373. EXPECT_EQ("Hello World!", read_all(handle));
  10374. }
  10375. TEST_F(OpenStreamTest, SmallBuffer) {
  10376. Client cli("127.0.0.1", 8787);
  10377. auto handle = cli.open_stream("GET", "/hello");
  10378. std::string result;
  10379. char buf[4];
  10380. ssize_t n;
  10381. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10382. result.append(buf, static_cast<size_t>(n));
  10383. EXPECT_EQ("Hello World!", result);
  10384. }
  10385. TEST_F(OpenStreamTest, DefaultHeaders) {
  10386. Client cli("127.0.0.1", 8787);
  10387. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10388. {
  10389. auto handle = cli.open_stream("GET", "/echo-headers");
  10390. ASSERT_TRUE(handle.is_valid());
  10391. auto body = read_all(handle);
  10392. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10393. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10394. std::string::npos);
  10395. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10396. }
  10397. // open_stream POST with body and no explicit content_type should NOT add
  10398. // text/plain Content-Type (behavior differs from non-streaming path), but
  10399. // should include Content-Length
  10400. {
  10401. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10402. ASSERT_TRUE(handle.is_valid());
  10403. auto body = read_all(handle);
  10404. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10405. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10406. }
  10407. // open_stream POST with explicit Content-Type should preserve it
  10408. {
  10409. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10410. {{"Content-Type", "application/custom"}},
  10411. "{}", "application/custom");
  10412. ASSERT_TRUE(handle.is_valid());
  10413. auto body = read_all(handle);
  10414. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10415. }
  10416. // User-specified User-Agent must not be overwritten for stream API
  10417. {
  10418. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10419. {{"User-Agent", "MyAgent/1.2"}});
  10420. ASSERT_TRUE(handle.is_valid());
  10421. auto body = read_all(handle);
  10422. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10423. }
  10424. }
  10425. TEST_F(OpenStreamTest, Large) {
  10426. Client cli("127.0.0.1", 8787);
  10427. auto handle = cli.open_stream("GET", "/large");
  10428. EXPECT_EQ(10000u, read_all(handle).size());
  10429. }
  10430. TEST_F(OpenStreamTest, ConnectionError) {
  10431. Client cli("127.0.0.1", 9999);
  10432. auto handle = cli.open_stream("GET", "/hello");
  10433. EXPECT_FALSE(handle.is_valid());
  10434. }
  10435. TEST_F(OpenStreamTest, Chunked) {
  10436. Client cli("127.0.0.1", 8787);
  10437. auto handle = cli.open_stream("GET", "/chunked");
  10438. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10439. "Transfer-Encoding") == "chunked");
  10440. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10441. }
  10442. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10443. Client cli("127.0.0.1", 8787);
  10444. auto handle =
  10445. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10446. ASSERT_TRUE(handle.is_valid());
  10447. // Consume body to allow trailers to be received/parsed
  10448. auto body = read_all(handle);
  10449. // Explicitly parse trailers (ensure trailers are available for assertion)
  10450. handle.parse_trailers_if_needed();
  10451. EXPECT_EQ(std::string("123456789"), body);
  10452. // The response should include a Trailer header declaring both names
  10453. ASSERT_TRUE(handle.response);
  10454. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10455. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10456. handle.response->get_header_value("Trailer"));
  10457. // Prohibited trailer must not be present
  10458. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10459. // Allowed trailer should be present
  10460. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10461. EXPECT_EQ(std::string("yes"),
  10462. handle.response->get_trailer_value("X-Allowed"));
  10463. // Verify trailers are NOT present as regular headers
  10464. EXPECT_EQ(std::string(""),
  10465. handle.response->get_header_value("Content-Length"));
  10466. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10467. }
  10468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10469. TEST_F(OpenStreamTest, Gzip) {
  10470. Client cli("127.0.0.1", 8787);
  10471. auto handle = cli.open_stream("GET", "/compressible", {},
  10472. {{"Accept-Encoding", "gzip"}});
  10473. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10474. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10475. }
  10476. #endif
  10477. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10478. TEST_F(OpenStreamTest, Brotli) {
  10479. Client cli("127.0.0.1", 8787);
  10480. auto handle =
  10481. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10482. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10483. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10484. }
  10485. #endif
  10486. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10487. TEST_F(OpenStreamTest, Zstd) {
  10488. Client cli("127.0.0.1", 8787);
  10489. auto handle = cli.open_stream("GET", "/compressible", {},
  10490. {{"Accept-Encoding", "zstd"}});
  10491. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10492. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10493. }
  10494. #endif
  10495. #ifdef CPPHTTPLIB_SSL_ENABLED
  10496. class SSLOpenStreamTest : public ::testing::Test {
  10497. protected:
  10498. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10499. void SetUp() override {
  10500. svr_.Get("/hello", [](const Request &, Response &res) {
  10501. res.set_content("Hello SSL World!", "text/plain");
  10502. });
  10503. svr_.Get("/chunked", [](const Request &, Response &res) {
  10504. res.set_chunked_content_provider("text/plain",
  10505. [](size_t offset, DataSink &sink) {
  10506. if (offset < 15) {
  10507. sink.write("chunk", 5);
  10508. return true;
  10509. }
  10510. sink.done();
  10511. return true;
  10512. });
  10513. });
  10514. svr_.Post("/echo", [](const Request &req, Response &res) {
  10515. res.set_content(req.body, req.get_header_value("Content-Type"));
  10516. });
  10517. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10518. std::string body = req.body;
  10519. res.set_chunked_content_provider(
  10520. "text/plain", [body](size_t offset, DataSink &sink) {
  10521. if (offset < body.size()) {
  10522. sink.write(body.data() + offset, body.size() - offset);
  10523. }
  10524. sink.done();
  10525. return true;
  10526. });
  10527. });
  10528. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10529. svr_.wait_until_ready();
  10530. }
  10531. void TearDown() override {
  10532. svr_.stop();
  10533. if (thread_.joinable()) thread_.join();
  10534. }
  10535. SSLServer svr_;
  10536. std::thread thread_;
  10537. };
  10538. TEST_F(SSLOpenStreamTest, Basic) {
  10539. SSLClient cli("127.0.0.1", 8788);
  10540. cli.enable_server_certificate_verification(false);
  10541. auto handle = cli.open_stream("GET", "/hello");
  10542. ASSERT_TRUE(handle.is_valid());
  10543. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10544. }
  10545. TEST_F(SSLOpenStreamTest, Chunked) {
  10546. SSLClient cli("127.0.0.1", 8788);
  10547. cli.enable_server_certificate_verification(false);
  10548. auto handle = cli.open_stream("GET", "/chunked");
  10549. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10550. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10551. "Transfer-Encoding") == "chunked");
  10552. auto body = read_all(handle);
  10553. EXPECT_EQ("chunkchunkchunk", body);
  10554. }
  10555. TEST_F(SSLOpenStreamTest, Post) {
  10556. SSLClient cli("127.0.0.1", 8788);
  10557. cli.enable_server_certificate_verification(false);
  10558. auto handle =
  10559. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10560. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10561. EXPECT_EQ(200, handle.response->status);
  10562. auto body = read_all(handle);
  10563. EXPECT_EQ("Hello SSL POST", body);
  10564. }
  10565. TEST_F(SSLOpenStreamTest, PostChunked) {
  10566. SSLClient cli("127.0.0.1", 8788);
  10567. cli.enable_server_certificate_verification(false);
  10568. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10569. "Chunked SSL Data", "text/plain");
  10570. ASSERT_TRUE(handle.is_valid());
  10571. EXPECT_EQ(200, handle.response->status);
  10572. auto body = read_all(handle);
  10573. EXPECT_EQ("Chunked SSL Data", body);
  10574. }
  10575. #endif // CPPHTTPLIB_SSL_ENABLED
  10576. //==============================================================================
  10577. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10578. // results for various scenarios.
  10579. //==============================================================================
  10580. TEST(ParityTest, GetVsOpenStream) {
  10581. Server svr;
  10582. const std::string path = "/parity";
  10583. const std::string content = "Parity test content: hello world";
  10584. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10585. res.set_content(content, "text/plain");
  10586. });
  10587. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10588. auto se = detail::scope_exit([&] {
  10589. svr.stop();
  10590. t.join();
  10591. ASSERT_FALSE(svr.is_running());
  10592. });
  10593. svr.wait_until_ready();
  10594. Client cli(HOST, PORT);
  10595. // Non-stream path
  10596. auto r1 = cli.Get(path);
  10597. ASSERT_TRUE(r1);
  10598. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10599. // Stream path
  10600. auto h = cli.open_stream("GET", path);
  10601. ASSERT_TRUE(h.is_valid());
  10602. EXPECT_EQ(r1->body, read_all(h));
  10603. }
  10604. // Helper to compress data with provided compressor type T
  10605. template <typename Compressor>
  10606. static std::string compress_payload_for_parity(const std::string &in) {
  10607. std::string out;
  10608. Compressor compressor;
  10609. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10610. [&](const char *data, size_t n) {
  10611. out.append(data, n);
  10612. return true;
  10613. });
  10614. EXPECT_TRUE(ok);
  10615. return out;
  10616. }
  10617. // Helper function for compression parity tests
  10618. template <typename Compressor>
  10619. static void test_compression_parity(const std::string &original,
  10620. const std::string &path,
  10621. const std::string &encoding) {
  10622. const std::string compressed =
  10623. compress_payload_for_parity<Compressor>(original);
  10624. Server svr;
  10625. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10626. res.set_content(compressed, "application/octet-stream");
  10627. res.set_header("Content-Encoding", encoding);
  10628. });
  10629. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10630. auto se = detail::scope_exit([&] {
  10631. svr.stop();
  10632. t.join();
  10633. ASSERT_FALSE(svr.is_running());
  10634. });
  10635. svr.wait_until_ready();
  10636. Client cli(HOST, PORT);
  10637. // Non-streaming
  10638. {
  10639. auto res = cli.Get(path);
  10640. ASSERT_TRUE(res);
  10641. EXPECT_EQ(StatusCode::OK_200, res->status);
  10642. EXPECT_EQ(original, res->body);
  10643. }
  10644. // Streaming
  10645. {
  10646. auto h = cli.open_stream("GET", path);
  10647. ASSERT_TRUE(h.is_valid());
  10648. EXPECT_EQ(original, read_all(h));
  10649. }
  10650. }
  10651. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10652. TEST(ParityTest, Gzip) {
  10653. test_compression_parity<detail::gzip_compressor>(
  10654. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10655. }
  10656. #endif
  10657. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10658. TEST(ParityTest, Brotli) {
  10659. test_compression_parity<detail::brotli_compressor>(
  10660. "Hello, brotli parity test payload", "/parity-br", "br");
  10661. }
  10662. #endif
  10663. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10664. TEST(ParityTest, Zstd) {
  10665. test_compression_parity<detail::zstd_compressor>(
  10666. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10667. }
  10668. #endif
  10669. //==============================================================================
  10670. // New Stream API Tests
  10671. //==============================================================================
  10672. inline std::string read_body(httplib::stream::Result &result) {
  10673. std::string body;
  10674. while (result.next()) {
  10675. body.append(result.data(), result.size());
  10676. }
  10677. return body;
  10678. }
  10679. TEST(ClientConnectionTest, Basic) {
  10680. httplib::ClientConnection conn;
  10681. EXPECT_FALSE(conn.is_open());
  10682. conn.sock = 1;
  10683. EXPECT_TRUE(conn.is_open());
  10684. httplib::ClientConnection conn2(std::move(conn));
  10685. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10686. conn2.sock = INVALID_SOCKET;
  10687. }
  10688. // Unified test server for all stream::* tests
  10689. class StreamApiTest : public ::testing::Test {
  10690. protected:
  10691. void SetUp() override {
  10692. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10693. res.set_content("Hello World!", "text/plain");
  10694. });
  10695. svr_.Get("/echo-params",
  10696. [](const httplib::Request &req, httplib::Response &res) {
  10697. std::string r;
  10698. for (const auto &p : req.params) {
  10699. if (!r.empty()) r += "&";
  10700. r += p.first + "=" + p.second;
  10701. }
  10702. res.set_content(r, "text/plain");
  10703. });
  10704. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10705. res.set_content(req.body, req.get_header_value("Content-Type"));
  10706. });
  10707. svr_.Post("/echo-headers",
  10708. [](const httplib::Request &req, httplib::Response &res) {
  10709. std::string r;
  10710. for (const auto &h : req.headers)
  10711. r += h.first + ": " + h.second + "\n";
  10712. res.set_content(r, "text/plain");
  10713. });
  10714. svr_.Post("/echo-params",
  10715. [](const httplib::Request &req, httplib::Response &res) {
  10716. std::string r = "params:";
  10717. for (const auto &p : req.params)
  10718. r += p.first + "=" + p.second + ";";
  10719. res.set_content(r + " body:" + req.body, "text/plain");
  10720. });
  10721. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10722. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10723. });
  10724. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10725. res.set_content("PUT:" + req.body, "text/plain");
  10726. });
  10727. svr_.Patch("/echo",
  10728. [](const httplib::Request &req, httplib::Response &res) {
  10729. res.set_content("PATCH:" + req.body, "text/plain");
  10730. });
  10731. svr_.Delete(
  10732. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10733. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10734. "text/plain");
  10735. });
  10736. svr_.Get("/head-test",
  10737. [](const httplib::Request &, httplib::Response &res) {
  10738. res.set_content("body for HEAD", "text/plain");
  10739. });
  10740. svr_.Options("/options",
  10741. [](const httplib::Request &, httplib::Response &res) {
  10742. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10743. });
  10744. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10745. svr_.wait_until_ready();
  10746. }
  10747. void TearDown() override {
  10748. svr_.stop();
  10749. if (thread_.joinable()) thread_.join();
  10750. }
  10751. httplib::Server svr_;
  10752. std::thread thread_;
  10753. };
  10754. // stream::Get tests
  10755. TEST_F(StreamApiTest, GetBasic) {
  10756. httplib::Client cli(HOST, PORT);
  10757. auto result = httplib::stream::Get(cli, "/hello");
  10758. ASSERT_TRUE(result.is_valid());
  10759. EXPECT_EQ(200, result.status());
  10760. EXPECT_EQ("Hello World!", read_body(result));
  10761. }
  10762. TEST_F(StreamApiTest, GetWithParams) {
  10763. httplib::Client cli(HOST, PORT);
  10764. httplib::Params params{{"foo", "bar"}};
  10765. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10766. ASSERT_TRUE(result.is_valid());
  10767. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10768. }
  10769. TEST_F(StreamApiTest, GetConnectionError) {
  10770. httplib::Client cli(HOST, 9999);
  10771. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10772. }
  10773. TEST_F(StreamApiTest, Get404) {
  10774. httplib::Client cli(HOST, PORT);
  10775. auto result = httplib::stream::Get(cli, "/nonexistent");
  10776. EXPECT_TRUE(result.is_valid());
  10777. EXPECT_EQ(404, result.status());
  10778. }
  10779. // stream::Post tests
  10780. TEST_F(StreamApiTest, PostBasic) {
  10781. httplib::Client cli(HOST, PORT);
  10782. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10783. "application/json");
  10784. ASSERT_TRUE(result.is_valid());
  10785. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10786. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10787. }
  10788. TEST_F(StreamApiTest, PostWithHeaders) {
  10789. httplib::Client cli(HOST, PORT);
  10790. httplib::Headers headers{{"X-Custom", "value"}};
  10791. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10792. "text/plain");
  10793. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10794. }
  10795. TEST_F(StreamApiTest, PostWithParams) {
  10796. httplib::Client cli(HOST, PORT);
  10797. httplib::Params params{{"k", "v"}};
  10798. auto result =
  10799. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10800. auto body = read_body(result);
  10801. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10802. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10803. }
  10804. TEST_F(StreamApiTest, PostLarge) {
  10805. httplib::Client cli(HOST, PORT);
  10806. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10807. size_t total = 0;
  10808. while (result.next()) {
  10809. total += result.size();
  10810. }
  10811. EXPECT_EQ(100u * 1024u, total);
  10812. }
  10813. // stream::Put/Patch tests
  10814. TEST_F(StreamApiTest, PutAndPatch) {
  10815. httplib::Client cli(HOST, PORT);
  10816. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10817. EXPECT_EQ("PUT:test", read_body(put));
  10818. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10819. EXPECT_EQ("PATCH:test", read_body(patch));
  10820. }
  10821. // stream::Delete tests
  10822. TEST_F(StreamApiTest, Delete) {
  10823. httplib::Client cli(HOST, PORT);
  10824. auto del1 = httplib::stream::Delete(cli, "/resource");
  10825. EXPECT_EQ("Deleted", read_body(del1));
  10826. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10827. EXPECT_EQ("Deleted:data", read_body(del2));
  10828. }
  10829. // stream::Head/Options tests
  10830. TEST_F(StreamApiTest, HeadAndOptions) {
  10831. httplib::Client cli(HOST, PORT);
  10832. auto head = httplib::stream::Head(cli, "/head-test");
  10833. EXPECT_TRUE(head.is_valid());
  10834. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10835. auto opts = httplib::stream::Options(cli, "/options");
  10836. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10837. }
  10838. // SSL stream::* tests
  10839. #ifdef CPPHTTPLIB_SSL_ENABLED
  10840. class SSLStreamApiTest : public ::testing::Test {
  10841. protected:
  10842. void SetUp() override {
  10843. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10844. res.set_content("Hello SSL!", "text/plain");
  10845. });
  10846. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10847. res.set_content(req.body, "text/plain");
  10848. });
  10849. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10850. svr_.wait_until_ready();
  10851. }
  10852. void TearDown() override {
  10853. svr_.stop();
  10854. if (thread_.joinable()) thread_.join();
  10855. }
  10856. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10857. std::thread thread_;
  10858. };
  10859. TEST_F(SSLStreamApiTest, GetAndPost) {
  10860. httplib::SSLClient cli("127.0.0.1", 8803);
  10861. cli.enable_server_certificate_verification(false);
  10862. auto get = httplib::stream::Get(cli, "/hello");
  10863. EXPECT_EQ("Hello SSL!", read_body(get));
  10864. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10865. EXPECT_EQ("test", read_body(post));
  10866. }
  10867. #endif
  10868. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10869. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10870. // BodyReader
  10871. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10872. // Test that read timeout during streaming is detected
  10873. // Use a large content-length response where server delays mid-stream
  10874. Server svr;
  10875. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10876. // Send a large response with delay in the middle
  10877. res.set_content_provider(
  10878. 1000, // content_length
  10879. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10880. if (offset < 100) {
  10881. // Send first 100 bytes immediately
  10882. std::string data(100, 'A');
  10883. sink.write(data.c_str(), data.size());
  10884. return true;
  10885. }
  10886. // Then delay longer than client timeout
  10887. std::this_thread::sleep_for(std::chrono::seconds(3));
  10888. std::string data(900, 'B');
  10889. sink.write(data.c_str(), data.size());
  10890. return true;
  10891. });
  10892. });
  10893. auto port = 8091;
  10894. std::thread t([&]() { svr.listen("localhost", port); });
  10895. svr.wait_until_ready();
  10896. Client cli("localhost", port);
  10897. cli.set_read_timeout(1, 0); // 1 second timeout
  10898. auto handle = cli.open_stream("GET", "/slow-stream");
  10899. ASSERT_TRUE(handle.is_valid());
  10900. char buf[256];
  10901. ssize_t total = 0;
  10902. ssize_t n;
  10903. bool got_error = false;
  10904. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10905. total += n;
  10906. }
  10907. if (n < 0) {
  10908. got_error = true;
  10909. // Should be timeout or read error
  10910. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10911. handle.get_read_error() == Error::Read)
  10912. << "Actual error: " << to_string(handle.get_read_error());
  10913. }
  10914. // Either we got an error, or we got less data than expected
  10915. EXPECT_TRUE(got_error || total < 1000)
  10916. << "Expected timeout but got all " << total << " bytes";
  10917. svr.stop();
  10918. t.join();
  10919. }
  10920. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10921. // Test connection closed detection via BodyReader
  10922. Server svr;
  10923. std::atomic<bool> close_now{false};
  10924. svr.Get("/will-close", [&](const Request &, Response &res) {
  10925. res.set_content_provider(
  10926. 10000, // Large content_length that we won't fully send
  10927. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10928. if (offset < 100) {
  10929. std::string data(100, 'X');
  10930. sink.write(data.c_str(), data.size());
  10931. return true;
  10932. }
  10933. // Wait for signal then abort
  10934. while (!close_now) {
  10935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10936. }
  10937. return false; // Abort - server will close connection
  10938. });
  10939. });
  10940. auto port = 8092;
  10941. std::thread t([&]() { svr.listen("localhost", port); });
  10942. svr.wait_until_ready();
  10943. Client cli("localhost", port);
  10944. auto handle = cli.open_stream("GET", "/will-close");
  10945. ASSERT_TRUE(handle.is_valid());
  10946. char buf[256];
  10947. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10948. EXPECT_GT(n, 0) << "First read should succeed";
  10949. // Signal server to close
  10950. close_now = true;
  10951. // Keep reading until error or EOF
  10952. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10953. // Keep reading
  10954. }
  10955. // Should get an error since content_length wasn't satisfied
  10956. if (n < 0) {
  10957. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10958. handle.get_read_error() == Error::Read)
  10959. << "Actual error: " << to_string(handle.get_read_error());
  10960. }
  10961. svr.stop();
  10962. t.join();
  10963. }
  10964. #ifdef CPPHTTPLIB_SSL_ENABLED
  10965. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10966. // Test that read timeout during SSL streaming is detected
  10967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10968. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10969. res.set_content_provider(
  10970. 1000, "text/plain",
  10971. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10972. if (offset < 100) {
  10973. std::string data(100, 'A');
  10974. sink.write(data.c_str(), data.size());
  10975. return true;
  10976. }
  10977. std::this_thread::sleep_for(std::chrono::seconds(3));
  10978. std::string data(900, 'B');
  10979. sink.write(data.c_str(), data.size());
  10980. return true;
  10981. });
  10982. });
  10983. auto port = 8093;
  10984. std::thread t([&]() { svr.listen("localhost", port); });
  10985. svr.wait_until_ready();
  10986. SSLClient cli("localhost", port);
  10987. cli.enable_server_certificate_verification(false);
  10988. cli.set_read_timeout(1, 0); // 1 second timeout
  10989. auto handle = cli.open_stream("GET", "/slow-stream");
  10990. ASSERT_TRUE(handle.is_valid());
  10991. char buf[256];
  10992. ssize_t total = 0;
  10993. ssize_t n;
  10994. bool got_error = false;
  10995. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10996. total += n;
  10997. }
  10998. if (n < 0) {
  10999. got_error = true;
  11000. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11001. handle.get_read_error() == Error::Read)
  11002. << "Actual error: " << to_string(handle.get_read_error());
  11003. }
  11004. EXPECT_TRUE(got_error || total < 1000)
  11005. << "Expected timeout but got all " << total << " bytes";
  11006. svr.stop();
  11007. t.join();
  11008. }
  11009. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11010. // Test SSL connection closed detection
  11011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11012. std::atomic<bool> close_now{false};
  11013. svr.Get("/will-close", [&](const Request &, Response &res) {
  11014. res.set_content_provider(
  11015. 10000, "text/plain",
  11016. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11017. if (offset < 100) {
  11018. std::string data(100, 'X');
  11019. sink.write(data.c_str(), data.size());
  11020. return true;
  11021. }
  11022. while (!close_now) {
  11023. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11024. }
  11025. return false;
  11026. });
  11027. });
  11028. auto port = 8094;
  11029. std::thread t([&]() { svr.listen("localhost", port); });
  11030. svr.wait_until_ready();
  11031. SSLClient cli("localhost", port);
  11032. cli.enable_server_certificate_verification(false);
  11033. auto handle = cli.open_stream("GET", "/will-close");
  11034. ASSERT_TRUE(handle.is_valid());
  11035. char buf[256];
  11036. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11037. EXPECT_GT(n, 0);
  11038. // Signal server to close
  11039. close_now = true;
  11040. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11041. // Keep reading
  11042. }
  11043. if (n < 0) {
  11044. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11045. handle.get_read_error() == Error::Read)
  11046. << "Actual error: " << to_string(handle.get_read_error());
  11047. }
  11048. svr.stop();
  11049. t.join();
  11050. }
  11051. #endif
  11052. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11053. using namespace httplib;
  11054. // Create a test file
  11055. const char *fname = "etag_testfile.txt";
  11056. const char *content = "etag-content";
  11057. {
  11058. std::ofstream ofs(fname);
  11059. ofs << content;
  11060. ASSERT_TRUE(ofs.good());
  11061. }
  11062. Server svr;
  11063. svr.set_mount_point("/static", ".");
  11064. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11065. svr.wait_until_ready();
  11066. Client cli(HOST, PORT);
  11067. // First request: should get 200 with ETag header
  11068. auto res1 = cli.Get("/static/etag_testfile.txt");
  11069. ASSERT_TRUE(res1);
  11070. ASSERT_EQ(200, res1->status);
  11071. ASSERT_TRUE(res1->has_header("ETag"));
  11072. std::string etag = res1->get_header_value("ETag");
  11073. EXPECT_FALSE(etag.empty());
  11074. // Verify ETag format: W/"hex-hex"
  11075. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11076. EXPECT_EQ('W', etag[0]);
  11077. EXPECT_EQ('/', etag[1]);
  11078. EXPECT_EQ('"', etag[2]);
  11079. EXPECT_EQ('"', etag.back());
  11080. // Exact match: expect 304 Not Modified
  11081. Headers h2 = {{"If-None-Match", etag}};
  11082. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11083. ASSERT_TRUE(res2);
  11084. EXPECT_EQ(304, res2->status);
  11085. // Wildcard match: expect 304 Not Modified
  11086. Headers h3 = {{"If-None-Match", "*"}};
  11087. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11088. ASSERT_TRUE(res3);
  11089. EXPECT_EQ(304, res3->status);
  11090. // Non-matching ETag: expect 200
  11091. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11092. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11093. ASSERT_TRUE(res4);
  11094. EXPECT_EQ(200, res4->status);
  11095. // Multiple ETags with one matching: expect 304
  11096. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11097. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11098. ASSERT_TRUE(res5);
  11099. EXPECT_EQ(304, res5->status);
  11100. svr.stop();
  11101. t.join();
  11102. std::remove(fname);
  11103. }
  11104. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11105. using namespace httplib;
  11106. Server svr;
  11107. svr.set_mount_point("/static", ".");
  11108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11109. svr.wait_until_ready();
  11110. Client cli(HOST, PORT);
  11111. // Send If-None-Match: * to a non-existent file
  11112. Headers h = {{"If-None-Match", "*"}};
  11113. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11114. ASSERT_TRUE(res);
  11115. EXPECT_EQ(404, res->status);
  11116. svr.stop();
  11117. t.join();
  11118. }
  11119. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11120. using namespace httplib;
  11121. // Create a test file
  11122. const char *fname = "ims_testfile.txt";
  11123. const char *content = "if-modified-since-test";
  11124. {
  11125. std::ofstream ofs(fname);
  11126. ofs << content;
  11127. ASSERT_TRUE(ofs.good());
  11128. }
  11129. Server svr;
  11130. svr.set_mount_point("/static", ".");
  11131. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11132. svr.wait_until_ready();
  11133. Client cli(HOST, PORT);
  11134. // First request: should get 200 with Last-Modified header
  11135. auto res1 = cli.Get("/static/ims_testfile.txt");
  11136. ASSERT_TRUE(res1);
  11137. ASSERT_EQ(200, res1->status);
  11138. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11139. std::string last_modified = res1->get_header_value("Last-Modified");
  11140. EXPECT_FALSE(last_modified.empty());
  11141. // If-Modified-Since with same time: expect 304
  11142. Headers h2 = {{"If-Modified-Since", last_modified}};
  11143. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11144. ASSERT_TRUE(res2);
  11145. EXPECT_EQ(304, res2->status);
  11146. // If-Modified-Since with future time: expect 304
  11147. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11148. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11149. ASSERT_TRUE(res3);
  11150. EXPECT_EQ(304, res3->status);
  11151. // If-Modified-Since with past time: expect 200
  11152. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11153. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11154. ASSERT_TRUE(res4);
  11155. EXPECT_EQ(200, res4->status);
  11156. // If-None-Match takes precedence over If-Modified-Since
  11157. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11158. ASSERT_TRUE(res1->has_header("ETag"));
  11159. std::string etag = res1->get_header_value("ETag");
  11160. Headers h5 = {{"If-None-Match", etag},
  11161. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11162. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11163. ASSERT_TRUE(res5);
  11164. EXPECT_EQ(304, res5->status);
  11165. svr.stop();
  11166. t.join();
  11167. std::remove(fname);
  11168. }
  11169. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11170. using namespace httplib;
  11171. Server svr;
  11172. // Endpoint that returns compressible content
  11173. svr.Get("/compressible", [](const Request &, Response &res) {
  11174. // Return a large enough body to trigger compression
  11175. std::string body(1000, 'a');
  11176. res.set_content(body, "text/plain");
  11177. });
  11178. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11179. svr.wait_until_ready();
  11180. Client cli(HOST, PORT);
  11181. // Request with gzip support: should get Vary header when compressed
  11182. cli.set_compress(true);
  11183. auto res1 = cli.Get("/compressible");
  11184. ASSERT_TRUE(res1);
  11185. EXPECT_EQ(200, res1->status);
  11186. // If Content-Encoding is set, Vary should also be set
  11187. if (res1->has_header("Content-Encoding")) {
  11188. EXPECT_TRUE(res1->has_header("Vary"));
  11189. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11190. }
  11191. // Request without Accept-Encoding header: should not have compression
  11192. Headers h_no_compress;
  11193. auto res2 = cli.Get("/compressible", h_no_compress);
  11194. ASSERT_TRUE(res2);
  11195. EXPECT_EQ(200, res2->status);
  11196. // Verify Vary header is present when compression is applied
  11197. // (the exact behavior depends on server configuration)
  11198. svr.stop();
  11199. t.join();
  11200. }
  11201. TEST(ETagTest, IfRangeWithETag) {
  11202. using namespace httplib;
  11203. // Create a test file with known content
  11204. const char *fname = "if_range_testfile.txt";
  11205. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11206. {
  11207. std::ofstream ofs(fname);
  11208. ofs << content;
  11209. ASSERT_TRUE(ofs.good());
  11210. }
  11211. Server svr;
  11212. svr.set_mount_point("/static", ".");
  11213. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11214. svr.wait_until_ready();
  11215. Client cli(HOST, PORT);
  11216. // First request: get ETag
  11217. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11218. ASSERT_TRUE(res1);
  11219. ASSERT_EQ(200, res1->status);
  11220. ASSERT_TRUE(res1->has_header("ETag"));
  11221. std::string etag = res1->get_header_value("ETag");
  11222. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11223. // Since our server generates weak ETags (W/"..."), If-Range with our
  11224. // ETag should NOT result in partial content - it should return full content.
  11225. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11226. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11227. ASSERT_TRUE(res2);
  11228. // Weak ETag in If-Range -> full content (200), not partial (206)
  11229. EXPECT_EQ(200, res2->status);
  11230. EXPECT_EQ(content, res2->body);
  11231. EXPECT_FALSE(res2->has_header("Content-Range"));
  11232. // Range request with non-matching If-Range (ETag): should get 200 (full
  11233. // content)
  11234. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11235. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11236. ASSERT_TRUE(res3);
  11237. EXPECT_EQ(200, res3->status);
  11238. EXPECT_EQ(content, res3->body);
  11239. EXPECT_FALSE(res3->has_header("Content-Range"));
  11240. // Range request with strong ETag (hypothetical - our server doesn't generate
  11241. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11242. // should return full content)
  11243. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11244. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11245. ASSERT_TRUE(res4);
  11246. EXPECT_EQ(200, res4->status);
  11247. EXPECT_EQ(content, res4->body);
  11248. EXPECT_FALSE(res4->has_header("Content-Range"));
  11249. svr.stop();
  11250. t.join();
  11251. std::remove(fname);
  11252. }
  11253. TEST(ETagTest, IfRangeWithDate) {
  11254. using namespace httplib;
  11255. // Create a test file
  11256. const char *fname = "if_range_date_testfile.txt";
  11257. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11258. {
  11259. std::ofstream ofs(fname);
  11260. ofs << content;
  11261. ASSERT_TRUE(ofs.good());
  11262. }
  11263. Server svr;
  11264. svr.set_mount_point("/static", ".");
  11265. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11266. svr.wait_until_ready();
  11267. Client cli(HOST, PORT);
  11268. // First request: get Last-Modified
  11269. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11270. ASSERT_TRUE(res1);
  11271. ASSERT_EQ(200, res1->status);
  11272. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11273. std::string last_modified = res1->get_header_value("Last-Modified");
  11274. // Range request with matching If-Range (date): should get 206
  11275. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11276. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11277. ASSERT_TRUE(res2);
  11278. EXPECT_EQ(206, res2->status);
  11279. EXPECT_EQ("FGHIJ", res2->body);
  11280. // Range request with old If-Range date: should get 200 (full content)
  11281. Headers h3 = {{"Range", "bytes=5-9"},
  11282. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11283. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11284. ASSERT_TRUE(res3);
  11285. EXPECT_EQ(200, res3->status);
  11286. EXPECT_EQ(content, res3->body);
  11287. // Range request with future If-Range date: should get 206
  11288. Headers h4 = {{"Range", "bytes=0-4"},
  11289. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11290. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11291. ASSERT_TRUE(res4);
  11292. EXPECT_EQ(206, res4->status);
  11293. EXPECT_EQ("ABCDE", res4->body);
  11294. svr.stop();
  11295. t.join();
  11296. std::remove(fname);
  11297. }
  11298. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11299. using namespace httplib;
  11300. const char *fname = "etag_malformed.txt";
  11301. const char *content = "malformed-etag";
  11302. {
  11303. std::ofstream ofs(fname);
  11304. ofs << content;
  11305. ASSERT_TRUE(ofs.good());
  11306. }
  11307. Server svr;
  11308. svr.set_mount_point("/static", ".");
  11309. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11310. svr.wait_until_ready();
  11311. Client cli(HOST, PORT);
  11312. // baseline: should get 200 and an ETag
  11313. auto res1 = cli.Get("/static/etag_malformed.txt");
  11314. ASSERT_TRUE(res1);
  11315. ASSERT_EQ(200, res1->status);
  11316. ASSERT_TRUE(res1->has_header("ETag"));
  11317. // Malformed ETag value (missing quotes) should be treated as non-matching
  11318. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11319. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11320. ASSERT_TRUE(res_bad);
  11321. EXPECT_EQ(200, res_bad->status);
  11322. // Whitespace-only header value should be considered invalid / non-matching
  11323. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11324. "Host: localhost\r\n"
  11325. "If-None-Match: \r\n"
  11326. "Connection: close\r\n"
  11327. "\r\n";
  11328. std::string out;
  11329. ASSERT_TRUE(send_request(5, raw_req, &out));
  11330. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11331. svr.stop();
  11332. t.join();
  11333. std::remove(fname);
  11334. }
  11335. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11336. using namespace httplib;
  11337. const char *fname = "ims_invalid_format.txt";
  11338. const char *content = "ims-bad-format";
  11339. {
  11340. std::ofstream ofs(fname);
  11341. ofs << content;
  11342. ASSERT_TRUE(ofs.good());
  11343. }
  11344. Server svr;
  11345. svr.set_mount_point("/static", ".");
  11346. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11347. svr.wait_until_ready();
  11348. Client cli(HOST, PORT);
  11349. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11350. ASSERT_TRUE(res1);
  11351. ASSERT_EQ(200, res1->status);
  11352. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11353. // If-Modified-Since with invalid format should not result in 304
  11354. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11355. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11356. ASSERT_TRUE(res_bad);
  11357. EXPECT_EQ(200, res_bad->status);
  11358. // If-Range with invalid date format should be treated as mismatch -> full
  11359. // content (200)
  11360. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11361. {"If-Range", "invalid-date"}};
  11362. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11363. ASSERT_TRUE(res_ifrange);
  11364. EXPECT_EQ(200, res_ifrange->status);
  11365. svr.stop();
  11366. t.join();
  11367. std::remove(fname);
  11368. }
  11369. TEST(ETagTest, IfRangeWithMalformedETag) {
  11370. using namespace httplib;
  11371. const char *fname = "ifrange_malformed.txt";
  11372. const std::string content = "0123456789";
  11373. {
  11374. std::ofstream ofs(fname);
  11375. ofs << content;
  11376. ASSERT_TRUE(ofs.good());
  11377. }
  11378. Server svr;
  11379. svr.set_mount_point("/static", ".");
  11380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11381. svr.wait_until_ready();
  11382. Client cli(HOST, PORT);
  11383. // First request: get ETag
  11384. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11385. ASSERT_TRUE(res1);
  11386. ASSERT_EQ(200, res1->status);
  11387. ASSERT_TRUE(res1->has_header("ETag"));
  11388. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11389. // full content (200)
  11390. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11391. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11392. ASSERT_TRUE(res2);
  11393. EXPECT_EQ(200, res2->status);
  11394. EXPECT_EQ(content, res2->body);
  11395. svr.stop();
  11396. t.join();
  11397. std::remove(fname);
  11398. }
  11399. TEST(ETagTest, ExtremeLargeDateValues) {
  11400. using namespace httplib;
  11401. const char *fname = "ims_extreme_date.txt";
  11402. const char *content = "ims-extreme-date";
  11403. {
  11404. std::ofstream ofs(fname);
  11405. ofs << content;
  11406. ASSERT_TRUE(ofs.good());
  11407. }
  11408. Server svr;
  11409. svr.set_mount_point("/static", ".");
  11410. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11411. svr.wait_until_ready();
  11412. Client cli(HOST, PORT);
  11413. auto res1 = cli.Get(std::string("/static/") + fname);
  11414. ASSERT_TRUE(res1);
  11415. ASSERT_EQ(200, res1->status);
  11416. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11417. // Extremely large year that may overflow date parsing routines.
  11418. Headers h_large_date = {
  11419. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11420. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11421. ASSERT_TRUE(res_bad);
  11422. // Expect server to treat this as invalid/mismatch and return full content
  11423. EXPECT_EQ(200, res_bad->status);
  11424. // If-Range with extremely large date should be treated as mismatch -> full
  11425. // content (200)
  11426. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11427. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11428. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11429. ASSERT_TRUE(res_ifrange);
  11430. EXPECT_EQ(200, res_ifrange->status);
  11431. svr.stop();
  11432. t.join();
  11433. std::remove(fname);
  11434. }
  11435. TEST(ETagTest, NegativeFileModificationTime) {
  11436. using namespace httplib;
  11437. const char *fname = "ims_negative_mtime.txt";
  11438. const std::string content = "negative-mtime";
  11439. {
  11440. std::ofstream ofs(fname);
  11441. ofs << content;
  11442. ASSERT_TRUE(ofs.good());
  11443. }
  11444. // Try to set file mtime to a negative value. This may fail on some
  11445. // platforms/filesystems; if it fails, the test will still verify server
  11446. // behaves safely by performing a regular conditional request.
  11447. #if defined(__APPLE__) || defined(__linux__)
  11448. bool set_negative = false;
  11449. do {
  11450. struct timeval times[2];
  11451. // access time: now
  11452. times[0].tv_sec = time(nullptr);
  11453. times[0].tv_usec = 0;
  11454. // modification time: negative (e.g., -1)
  11455. times[1].tv_sec = -1;
  11456. times[1].tv_usec = 0;
  11457. if (utimes(fname, times) == 0) { set_negative = true; }
  11458. } while (0);
  11459. #else
  11460. bool set_negative = false;
  11461. #endif
  11462. Server svr;
  11463. svr.set_mount_point("/static", ".");
  11464. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11465. svr.wait_until_ready();
  11466. Client cli(HOST, PORT);
  11467. auto res1 = cli.Get(std::string("/static/") + fname);
  11468. ASSERT_TRUE(res1);
  11469. ASSERT_EQ(200, res1->status);
  11470. bool has_last_modified = res1->has_header("Last-Modified");
  11471. std::string last_modified;
  11472. if (has_last_modified) {
  11473. last_modified = res1->get_header_value("Last-Modified");
  11474. }
  11475. if (set_negative) {
  11476. // If we successfully set a negative mtime, ensure server returns a
  11477. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11478. // with an old date and ensure server handles it without crash.
  11479. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11480. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11481. ASSERT_TRUE(res2);
  11482. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11483. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11484. } else {
  11485. // Could not set negative mtime on this platform; fall back to verifying
  11486. // that normal invalid/malformed dates are treated safely (non-304).
  11487. Headers h_bad_date = {
  11488. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11489. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11490. ASSERT_TRUE(res_bad);
  11491. EXPECT_EQ(200, res_bad->status);
  11492. }
  11493. svr.stop();
  11494. t.join();
  11495. std::remove(fname);
  11496. }
  11497. //==============================================================================
  11498. // SSE Parsing Tests
  11499. //==============================================================================
  11500. class SSEParsingTest : public ::testing::Test {
  11501. protected:
  11502. // Test helper that mimics SSE parsing behavior
  11503. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11504. int &retry_ms) {
  11505. // Blank line signals end of event
  11506. if (line.empty() || line == "\r") { return true; }
  11507. // Lines starting with ':' are comments (ignored)
  11508. if (!line.empty() && line[0] == ':') { return false; }
  11509. // Find the colon separator
  11510. auto colon_pos = line.find(':');
  11511. if (colon_pos == std::string::npos) {
  11512. // Line with no colon is treated as field name with empty value
  11513. return false;
  11514. }
  11515. std::string field = line.substr(0, colon_pos);
  11516. std::string value;
  11517. // Value starts after colon, skip optional single space
  11518. if (colon_pos + 1 < line.size()) {
  11519. size_t value_start = colon_pos + 1;
  11520. if (line[value_start] == ' ') { value_start++; }
  11521. value = line.substr(value_start);
  11522. // Remove trailing \r if present
  11523. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11524. }
  11525. // Handle known fields
  11526. if (field == "event") {
  11527. msg.event = value;
  11528. } else if (field == "data") {
  11529. // Multiple data lines are concatenated with newlines
  11530. if (!msg.data.empty()) { msg.data += "\n"; }
  11531. msg.data += value;
  11532. } else if (field == "id") {
  11533. // Empty id is valid (clears the last event ID)
  11534. msg.id = value;
  11535. } else if (field == "retry") {
  11536. // Parse retry interval in milliseconds
  11537. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  11538. {
  11539. std::istringstream iss(value);
  11540. iss >> retry_ms;
  11541. }
  11542. #else
  11543. try {
  11544. retry_ms = std::stoi(value);
  11545. } catch (...) {
  11546. // Invalid retry value, ignore
  11547. }
  11548. #endif
  11549. }
  11550. // Unknown fields are ignored per SSE spec
  11551. return false;
  11552. }
  11553. };
  11554. // Test: Single-line data
  11555. TEST_F(SSEParsingTest, SingleLineData) {
  11556. sse::SSEMessage msg;
  11557. int retry_ms = 3000;
  11558. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11559. EXPECT_EQ(msg.data, "hello");
  11560. EXPECT_EQ(msg.event, "message");
  11561. // Blank line ends event
  11562. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11563. }
  11564. // Test: Multi-line data
  11565. TEST_F(SSEParsingTest, MultiLineData) {
  11566. sse::SSEMessage msg;
  11567. int retry_ms = 3000;
  11568. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11569. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11570. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11571. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11572. }
  11573. // Test: Custom event types
  11574. TEST_F(SSEParsingTest, CustomEventType) {
  11575. sse::SSEMessage msg;
  11576. int retry_ms = 3000;
  11577. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11578. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11579. EXPECT_EQ(msg.event, "update");
  11580. EXPECT_EQ(msg.data, "payload");
  11581. }
  11582. // Test: Event ID handling
  11583. TEST_F(SSEParsingTest, EventIdHandling) {
  11584. sse::SSEMessage msg;
  11585. int retry_ms = 3000;
  11586. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11587. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11588. EXPECT_EQ(msg.id, "12345");
  11589. }
  11590. // Test: Empty event ID (clears last event ID)
  11591. TEST_F(SSEParsingTest, EmptyEventId) {
  11592. sse::SSEMessage msg;
  11593. msg.id = "previous";
  11594. int retry_ms = 3000;
  11595. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11596. EXPECT_EQ(msg.id, "");
  11597. }
  11598. // Test: Retry field parsing
  11599. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11600. sse::SSEMessage msg;
  11601. int retry_ms = 3000;
  11602. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11603. EXPECT_EQ(retry_ms, 5000);
  11604. }
  11605. // Test: Invalid retry value
  11606. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11607. sse::SSEMessage msg;
  11608. int retry_ms = 3000;
  11609. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11610. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11611. }
  11612. // Test: Comments (lines starting with :)
  11613. TEST_F(SSEParsingTest, CommentsIgnored) {
  11614. sse::SSEMessage msg;
  11615. int retry_ms = 3000;
  11616. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11617. EXPECT_EQ(msg.data, "");
  11618. EXPECT_EQ(msg.event, "message");
  11619. }
  11620. // Test: Colon in value
  11621. TEST_F(SSEParsingTest, ColonInValue) {
  11622. sse::SSEMessage msg;
  11623. int retry_ms = 3000;
  11624. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11625. EXPECT_EQ(msg.data, "hello:world:test");
  11626. }
  11627. // Test: Line with no colon (field name only)
  11628. TEST_F(SSEParsingTest, FieldNameOnly) {
  11629. sse::SSEMessage msg;
  11630. int retry_ms = 3000;
  11631. // According to SSE spec, this is treated as field name with empty value
  11632. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11633. // Since we don't recognize "data" without colon, data should be empty
  11634. EXPECT_EQ(msg.data, "");
  11635. }
  11636. // Test: Trailing \r handling
  11637. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11638. sse::SSEMessage msg;
  11639. int retry_ms = 3000;
  11640. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11641. EXPECT_EQ(msg.data, "hello");
  11642. }
  11643. // Test: Unknown fields ignored
  11644. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11645. sse::SSEMessage msg;
  11646. int retry_ms = 3000;
  11647. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11648. EXPECT_EQ(msg.data, "");
  11649. EXPECT_EQ(msg.event, "message");
  11650. }
  11651. // Test: Space after colon is optional
  11652. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11653. sse::SSEMessage msg1, msg2;
  11654. int retry_ms = 3000;
  11655. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11656. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11657. EXPECT_EQ(msg1.data, "hello");
  11658. EXPECT_EQ(msg2.data, "hello");
  11659. }
  11660. // Test: SSEMessage clear
  11661. TEST_F(SSEParsingTest, MessageClear) {
  11662. sse::SSEMessage msg;
  11663. msg.event = "custom";
  11664. msg.data = "some data";
  11665. msg.id = "123";
  11666. msg.clear();
  11667. EXPECT_EQ(msg.event, "message");
  11668. EXPECT_EQ(msg.data, "");
  11669. EXPECT_EQ(msg.id, "");
  11670. }
  11671. // Test: Complete event parsing
  11672. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11673. sse::SSEMessage msg;
  11674. int retry_ms = 3000;
  11675. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11676. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11677. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11678. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11679. // Blank line ends event
  11680. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11681. EXPECT_EQ(msg.event, "notification");
  11682. EXPECT_EQ(msg.id, "evt-42");
  11683. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11684. EXPECT_EQ(retry_ms, 1000);
  11685. }
  11686. //==============================================================================
  11687. // Integration Tests with Server
  11688. //==============================================================================
  11689. class SSEIntegrationTest : public ::testing::Test {
  11690. protected:
  11691. void SetUp() override {
  11692. stop_server_.store(false);
  11693. events_.clear();
  11694. server_ = httplib::detail::make_unique<Server>();
  11695. setup_server();
  11696. start_server();
  11697. }
  11698. void TearDown() override {
  11699. stop_server_.store(true);
  11700. event_cv_.notify_all();
  11701. server_->stop();
  11702. if (server_thread_.joinable()) { server_thread_.join(); }
  11703. }
  11704. void setup_server() {
  11705. // Simple SSE endpoint
  11706. server_->Get("/events", [this](const Request &req, Response &res) {
  11707. auto last_id = req.get_header_value("Last-Event-ID");
  11708. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11709. res.set_chunked_content_provider(
  11710. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11711. std::unique_lock<std::mutex> lock(event_mutex_);
  11712. if (event_cv_.wait_for(
  11713. lock, std::chrono::milliseconds(200), [this] {
  11714. return !events_.empty() || stop_server_.load();
  11715. })) {
  11716. if (stop_server_.load()) { return false; }
  11717. if (!events_.empty()) {
  11718. std::string event = events_.front();
  11719. events_.erase(events_.begin());
  11720. sink.write(event.data(), event.size());
  11721. return true;
  11722. }
  11723. }
  11724. return !stop_server_.load();
  11725. });
  11726. });
  11727. // Endpoint that returns error
  11728. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11729. res.status = 500;
  11730. res.set_content("Internal Server Error", "text/plain");
  11731. });
  11732. // Endpoint for custom event types
  11733. server_->Get("/custom-events", [](const Request &, Response &res) {
  11734. res.set_chunked_content_provider(
  11735. "text/event-stream", [](size_t offset, DataSink &sink) {
  11736. if (offset == 0) {
  11737. std::string event = "event: update\ndata: updated\n\n"
  11738. "event: delete\ndata: deleted\n\n";
  11739. sink.write(event.data(), event.size());
  11740. }
  11741. return false; // End stream after sending
  11742. });
  11743. });
  11744. }
  11745. void start_server() {
  11746. port_ = server_->bind_to_any_port(HOST);
  11747. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11748. // Wait for server to start
  11749. while (!server_->is_running()) {
  11750. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11751. }
  11752. }
  11753. int get_port() const { return port_; }
  11754. void send_event(const std::string &event) {
  11755. std::lock_guard<std::mutex> lock(event_mutex_);
  11756. events_.push_back(event);
  11757. event_cv_.notify_all();
  11758. }
  11759. std::unique_ptr<Server> server_;
  11760. std::thread server_thread_;
  11761. std::mutex event_mutex_;
  11762. std::condition_variable event_cv_;
  11763. std::vector<std::string> events_;
  11764. std::atomic<bool> stop_server_{false};
  11765. std::string last_received_event_id_;
  11766. int port_ = 0;
  11767. };
  11768. // Test: Successful connection and on_open callback
  11769. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11770. // Add a simple endpoint that sends one event and closes
  11771. server_->Get("/simple-event", [](const Request &, Response &res) {
  11772. res.set_chunked_content_provider(
  11773. "text/event-stream", [](size_t offset, DataSink &sink) {
  11774. if (offset == 0) {
  11775. std::string event = "data: hello\n\n";
  11776. sink.write(event.data(), event.size());
  11777. }
  11778. return false; // Close stream after sending
  11779. });
  11780. });
  11781. Client client("localhost", get_port());
  11782. sse::SSEClient sse(client, "/simple-event");
  11783. std::atomic<bool> open_called{false};
  11784. std::atomic<bool> message_received{false};
  11785. sse.on_open([&open_called]() { open_called.store(true); });
  11786. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11787. if (msg.data == "hello") { message_received.store(true); }
  11788. });
  11789. sse.set_reconnect_interval(100);
  11790. sse.set_max_reconnect_attempts(1);
  11791. // Start async
  11792. sse.start_async();
  11793. // Wait for message to be processed
  11794. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11795. sse.stop();
  11796. EXPECT_TRUE(open_called.load());
  11797. EXPECT_TRUE(message_received.load());
  11798. }
  11799. // Test: on_message callback
  11800. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11801. // Endpoint that sends multiple events then closes
  11802. server_->Get("/multi-event", [](const Request &, Response &res) {
  11803. res.set_chunked_content_provider(
  11804. "text/event-stream", [](size_t offset, DataSink &sink) {
  11805. if (offset == 0) {
  11806. std::string events = "data: message1\n\ndata: message2\n\n";
  11807. sink.write(events.data(), events.size());
  11808. }
  11809. return false;
  11810. });
  11811. });
  11812. Client client("localhost", get_port());
  11813. sse::SSEClient sse(client, "/multi-event");
  11814. std::vector<std::string> received_messages;
  11815. std::mutex messages_mutex;
  11816. sse.on_message([&](const sse::SSEMessage &msg) {
  11817. std::lock_guard<std::mutex> lock(messages_mutex);
  11818. received_messages.push_back(msg.data);
  11819. });
  11820. sse.set_reconnect_interval(100);
  11821. sse.set_max_reconnect_attempts(1);
  11822. sse.start_async();
  11823. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11824. sse.stop();
  11825. std::lock_guard<std::mutex> lock(messages_mutex);
  11826. EXPECT_GE(received_messages.size(), 2u);
  11827. if (received_messages.size() >= 2) {
  11828. EXPECT_EQ(received_messages[0], "message1");
  11829. EXPECT_EQ(received_messages[1], "message2");
  11830. }
  11831. }
  11832. // Test: on_event for specific types
  11833. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11834. Client client("localhost", get_port());
  11835. sse::SSEClient sse(client, "/custom-events");
  11836. std::atomic<bool> update_received{false};
  11837. std::atomic<bool> delete_received{false};
  11838. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11839. if (msg.data == "updated") { update_received.store(true); }
  11840. });
  11841. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11842. if (msg.data == "deleted") { delete_received.store(true); }
  11843. });
  11844. sse.set_max_reconnect_attempts(1);
  11845. sse.start_async();
  11846. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11847. sse.stop();
  11848. EXPECT_TRUE(update_received.load());
  11849. EXPECT_TRUE(delete_received.load());
  11850. }
  11851. // Test: on_error callback on connection failure
  11852. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11853. // Connect to a non-existent port
  11854. Client client("localhost", 59999);
  11855. sse::SSEClient sse(client, "/events");
  11856. std::atomic<bool> error_called{false};
  11857. Error received_error = Error::Success;
  11858. sse.on_error([&](Error err) {
  11859. error_called.store(true);
  11860. received_error = err;
  11861. });
  11862. sse.set_reconnect_interval(50);
  11863. sse.set_max_reconnect_attempts(1);
  11864. sse.start_async();
  11865. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11866. sse.stop();
  11867. EXPECT_TRUE(error_called.load());
  11868. EXPECT_NE(received_error, Error::Success);
  11869. }
  11870. // Test: Last-Event-ID header sent on reconnect
  11871. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11872. // Endpoint that sends event with ID
  11873. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11874. res.set_chunked_content_provider(
  11875. "text/event-stream", [](size_t offset, DataSink &sink) {
  11876. if (offset == 0) {
  11877. std::string event = "id: evt-123\ndata: test\n\n";
  11878. sink.write(event.data(), event.size());
  11879. }
  11880. return false;
  11881. });
  11882. });
  11883. Client client("localhost", get_port());
  11884. sse::SSEClient sse(client, "/event-with-id");
  11885. std::atomic<bool> id_received{false};
  11886. sse.on_message([&](const sse::SSEMessage &msg) {
  11887. if (!msg.id.empty()) { id_received.store(true); }
  11888. });
  11889. sse.set_reconnect_interval(100);
  11890. sse.set_max_reconnect_attempts(1);
  11891. sse.start_async();
  11892. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11893. sse.stop();
  11894. EXPECT_TRUE(id_received.load());
  11895. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11896. }
  11897. // Test: Manual stop
  11898. TEST_F(SSEIntegrationTest, ManualStop) {
  11899. // Endpoint that sends one event and stays open briefly
  11900. std::atomic<bool> handler_running{true};
  11901. server_->Get("/stay-open", [&handler_running](const Request &,
  11902. Response &res) {
  11903. res.set_chunked_content_provider(
  11904. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11905. if (offset == 0) {
  11906. std::string event = "data: connected\n\n";
  11907. sink.write(event.data(), event.size());
  11908. }
  11909. // Keep connection open while handler_running is true
  11910. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11911. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11912. }
  11913. return false;
  11914. });
  11915. });
  11916. Client client("localhost", get_port());
  11917. sse::SSEClient sse(client, "/stay-open");
  11918. std::atomic<bool> connected{false};
  11919. sse.on_open([&connected]() { connected.store(true); });
  11920. sse.set_reconnect_interval(100);
  11921. sse.set_max_reconnect_attempts(1);
  11922. sse.start_async();
  11923. // Wait for connection to establish
  11924. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11925. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11926. }
  11927. EXPECT_TRUE(connected.load());
  11928. EXPECT_TRUE(sse.is_connected());
  11929. // Signal handler to stop
  11930. handler_running.store(false);
  11931. // Stop SSE client
  11932. sse.stop();
  11933. EXPECT_FALSE(sse.is_connected());
  11934. }
  11935. // Test: SSEClient with custom headers
  11936. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11937. // Setup a server endpoint that checks for custom header
  11938. std::atomic<bool> header_received{false};
  11939. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11940. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11941. header_received.store(true);
  11942. }
  11943. res.set_chunked_content_provider("text/event-stream",
  11944. [](size_t, DataSink &) { return false; });
  11945. });
  11946. Client client("localhost", get_port());
  11947. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11948. sse::SSEClient sse(client, "/header-check", headers);
  11949. sse.set_max_reconnect_attempts(1);
  11950. sse.start_async();
  11951. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11952. sse.stop();
  11953. EXPECT_TRUE(header_received.load());
  11954. }
  11955. // Test: Reconnect interval configuration
  11956. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11957. Client client("localhost", get_port());
  11958. sse::SSEClient sse(client, "/events");
  11959. auto &result = sse.set_reconnect_interval(500);
  11960. // Builder pattern should return reference to self
  11961. EXPECT_EQ(&result, &sse);
  11962. }
  11963. // Test: Max reconnect attempts
  11964. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11965. // Connect to non-existent port to force reconnects
  11966. Client client("localhost", 59998);
  11967. sse::SSEClient sse(client, "/events");
  11968. std::atomic<int> error_count{0};
  11969. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11970. sse.set_reconnect_interval(50);
  11971. sse.set_max_reconnect_attempts(2);
  11972. auto start = std::chrono::steady_clock::now();
  11973. sse.start(); // Blocking call
  11974. auto end = std::chrono::steady_clock::now();
  11975. // Should have stopped after 2 failed attempts
  11976. EXPECT_GE(error_count.load(), 2);
  11977. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11978. auto duration =
  11979. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11980. #ifdef _WIN32
  11981. // Windows is much slower for socket connection failures
  11982. EXPECT_LT(duration.count(), 7000);
  11983. #else
  11984. EXPECT_LT(duration.count(), 1000);
  11985. #endif
  11986. }
  11987. // Test: Multi-line data in integration
  11988. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11989. // Endpoint with multi-line data
  11990. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11991. res.set_chunked_content_provider(
  11992. "text/event-stream", [](size_t offset, DataSink &sink) {
  11993. if (offset == 0) {
  11994. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11995. sink.write(event.data(), event.size());
  11996. }
  11997. return false;
  11998. });
  11999. });
  12000. Client client("localhost", get_port());
  12001. sse::SSEClient sse(client, "/multiline-data");
  12002. std::string received_data;
  12003. std::mutex data_mutex;
  12004. sse.on_message([&](const sse::SSEMessage &msg) {
  12005. std::lock_guard<std::mutex> lock(data_mutex);
  12006. received_data = msg.data;
  12007. });
  12008. sse.set_reconnect_interval(100);
  12009. sse.set_max_reconnect_attempts(1);
  12010. sse.start_async();
  12011. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12012. sse.stop();
  12013. std::lock_guard<std::mutex> lock(data_mutex);
  12014. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12015. }
  12016. // Test: Auto-reconnect after server disconnection
  12017. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12018. std::atomic<int> connection_count{0};
  12019. std::atomic<int> message_count{0};
  12020. // Endpoint that sends one event and closes, forcing reconnect
  12021. server_->Get("/reconnect-test",
  12022. [&connection_count](const Request &, Response &res) {
  12023. connection_count.fetch_add(1);
  12024. res.set_chunked_content_provider(
  12025. "text/event-stream", [](size_t offset, DataSink &sink) {
  12026. if (offset == 0) {
  12027. std::string event = "data: hello\n\n";
  12028. sink.write(event.data(), event.size());
  12029. }
  12030. return false; // Close connection after sending
  12031. });
  12032. });
  12033. Client client("localhost", get_port());
  12034. sse::SSEClient sse(client, "/reconnect-test");
  12035. sse.on_message([&message_count](const sse::SSEMessage &) {
  12036. message_count.fetch_add(1);
  12037. });
  12038. sse.set_reconnect_interval(100);
  12039. sse.set_max_reconnect_attempts(3);
  12040. sse.start_async();
  12041. // Wait long enough for multiple reconnects
  12042. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12043. sse.stop();
  12044. // Should have connected multiple times (initial + reconnects)
  12045. EXPECT_GE(connection_count.load(), 2);
  12046. // Should have received messages from multiple connections
  12047. EXPECT_GE(message_count.load(), 2);
  12048. }
  12049. // Test: Last-Event-ID sent on reconnect
  12050. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12051. std::atomic<int> connection_count{0};
  12052. std::vector<std::string> received_last_event_ids;
  12053. std::mutex id_mutex;
  12054. // Endpoint that checks Last-Event-ID header and sends event with ID
  12055. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12056. int conn = connection_count.fetch_add(1);
  12057. // Capture the Last-Event-ID header from each connection
  12058. {
  12059. std::lock_guard<std::mutex> lock(id_mutex);
  12060. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12061. }
  12062. res.set_chunked_content_provider(
  12063. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12064. if (offset == 0) {
  12065. std::string event =
  12066. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12067. sink.write(event.data(), event.size());
  12068. }
  12069. return false;
  12070. });
  12071. });
  12072. Client client("localhost", get_port());
  12073. sse::SSEClient sse(client, "/reconnect-with-id");
  12074. sse.set_reconnect_interval(100);
  12075. sse.set_max_reconnect_attempts(3);
  12076. sse.start_async();
  12077. // Wait for at least 2 connections
  12078. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12079. sse.stop();
  12080. // Verify behavior
  12081. std::lock_guard<std::mutex> lock(id_mutex);
  12082. EXPECT_GE(received_last_event_ids.size(), 2u);
  12083. // First connection should have no Last-Event-ID
  12084. if (!received_last_event_ids.empty()) {
  12085. EXPECT_EQ(received_last_event_ids[0], "");
  12086. }
  12087. // Second connection should have Last-Event-ID from first connection
  12088. if (received_last_event_ids.size() >= 2) {
  12089. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12090. }
  12091. }
  12092. TEST(Issue2318Test, EmptyHostString) {
  12093. {
  12094. httplib::Client cli_empty("", PORT);
  12095. auto res = cli_empty.Get("/");
  12096. ASSERT_FALSE(res);
  12097. EXPECT_EQ(httplib::Error::Connection, res.error());
  12098. }
  12099. {
  12100. httplib::Client cli(" ", PORT);
  12101. auto res = cli.Get("/");
  12102. ASSERT_FALSE(res);
  12103. EXPECT_EQ(httplib::Error::Connection, res.error());
  12104. }
  12105. }
  12106. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12107. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12108. Server svr;
  12109. // Set a small payload limit (1KB)
  12110. svr.set_payload_max_length(1024);
  12111. svr.Post("/test", [&](const Request &req, Response &res) {
  12112. res.set_content("Body size: " + std::to_string(req.body.size()),
  12113. "text/plain");
  12114. });
  12115. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. listen_thread.join();
  12119. });
  12120. svr.wait_until_ready();
  12121. // Create data that compresses well but exceeds limit when decompressed
  12122. // 8KB of repeated null bytes compresses to a very small size
  12123. std::string original_data(8 * 1024, '\0');
  12124. // Compress the data using gzip
  12125. std::string compressed_data;
  12126. detail::gzip_compressor compressor;
  12127. compressor.compress(original_data.data(), original_data.size(), true,
  12128. [&](const char *data, size_t size) {
  12129. compressed_data.append(data, size);
  12130. return true;
  12131. });
  12132. // Verify compression worked (compressed should be much smaller)
  12133. ASSERT_LT(compressed_data.size(), original_data.size());
  12134. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12135. // Send compressed data with Content-Encoding: gzip
  12136. Client cli(HOST, PORT);
  12137. Headers headers = {{"Content-Encoding", "gzip"}};
  12138. auto res =
  12139. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12140. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12141. ASSERT_TRUE(res);
  12142. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12143. }
  12144. #endif
  12145. // ============================================================================
  12146. // OpenSSL-Specific Tests
  12147. // ============================================================================
  12148. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12149. X509 *readCertificate(const std::string &strFileName) {
  12150. std::ifstream inStream(strFileName);
  12151. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  12152. std::istreambuf_iterator<char>());
  12153. if (strCertPEM.empty()) return (nullptr);
  12154. BIO *pbCert = BIO_new(BIO_s_mem());
  12155. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  12156. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  12157. BIO_free(pbCert);
  12158. return (pCert);
  12159. }
  12160. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  12161. std::ifstream inStream(strFileName);
  12162. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  12163. std::istreambuf_iterator<char>());
  12164. if (strPrivateKeyPEM.empty()) return (nullptr);
  12165. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  12166. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  12167. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  12168. BIO_free(pbPrivKey);
  12169. return (pPrivateKey);
  12170. }
  12171. TEST(BindServerTest, UpdateCerts) {
  12172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12173. int port = svr.bind_to_any_port("0.0.0.0");
  12174. ASSERT_TRUE(svr.is_valid());
  12175. ASSERT_TRUE(port > 0);
  12176. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12177. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12178. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12179. ASSERT_TRUE(cert != nullptr);
  12180. ASSERT_TRUE(ca_cert != nullptr);
  12181. ASSERT_TRUE(key != nullptr);
  12182. X509_STORE *cert_store = X509_STORE_new();
  12183. X509_STORE_add_cert(cert_store, ca_cert);
  12184. // svr.update_certs(cert, key, cert_store); // deprecated
  12185. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12186. CLIENT_CA_CERT_FILE);
  12187. ASSERT_TRUE(svr.is_valid());
  12188. svr.stop();
  12189. X509_free(cert);
  12190. X509_free(ca_cert);
  12191. EVP_PKEY_free(key);
  12192. }
  12193. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  12194. // client CA list correctly for TLS handshake
  12195. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  12196. X509 *cert = readCertificate(SERVER_CERT_FILE);
  12197. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  12198. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  12199. ASSERT_TRUE(cert != nullptr);
  12200. ASSERT_TRUE(ca_cert != nullptr);
  12201. ASSERT_TRUE(key != nullptr);
  12202. X509_STORE *cert_store = X509_STORE_new();
  12203. X509_STORE_add_cert(cert_store, ca_cert);
  12204. // Use X509-based constructor (deprecated but should still work correctly)
  12205. #pragma GCC diagnostic push
  12206. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  12207. SSLServer svr(cert, key, cert_store);
  12208. #pragma GCC diagnostic pop
  12209. ASSERT_TRUE(svr.is_valid());
  12210. // Verify that client CA list is set in SSL_CTX
  12211. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12212. ASSERT_TRUE(ssl_ctx != nullptr);
  12213. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12214. ASSERT_TRUE(ca_list != nullptr);
  12215. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12216. X509_free(cert);
  12217. X509_free(ca_cert);
  12218. EVP_PKEY_free(key);
  12219. }
  12220. // Test that update_certs() updates client CA list correctly
  12221. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  12222. // Start with file-based constructor
  12223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12224. ASSERT_TRUE(svr.is_valid());
  12225. // Initially no client CA list should be set
  12226. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12227. ASSERT_TRUE(ssl_ctx != nullptr);
  12228. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  12229. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  12230. EXPECT_EQ(0, count_before);
  12231. // Now update with client CA (PEM string)
  12232. std::string cert_pem, key_pem, ca_pem;
  12233. read_file(SERVER_CERT_FILE, cert_pem);
  12234. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  12235. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  12236. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  12237. ASSERT_TRUE(svr.is_valid());
  12238. // Now client CA list should be set
  12239. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  12240. ASSERT_TRUE(ca_list_after != nullptr);
  12241. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  12242. }
  12243. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  12244. // Test that the file-path SSLServer constructor properly sets the client CA
  12245. // list that is sent to clients during the TLS handshake (CertificateRequest)
  12246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12247. ASSERT_TRUE(svr.is_valid());
  12248. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  12249. ASSERT_TRUE(ssl_ctx != nullptr);
  12250. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  12251. ASSERT_TRUE(ca_list != nullptr);
  12252. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  12253. }
  12254. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  12255. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  12256. // prepare large data
  12257. std::random_device seed_gen;
  12258. std::mt19937 random(seed_gen());
  12259. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  12260. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  12261. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  12262. // server
  12263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12264. ASSERT_TRUE(svr.is_valid());
  12265. svr.Post("/binary", [&](const Request &req, Response &res) {
  12266. EXPECT_EQ(large_size_byte, req.body.size());
  12267. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  12268. res.set_content(req.body, "application/octet-stream");
  12269. });
  12270. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12271. auto se = detail::scope_exit([&] {
  12272. svr.stop();
  12273. listen_thread.join();
  12274. ASSERT_FALSE(svr.is_running());
  12275. });
  12276. svr.wait_until_ready();
  12277. // client POST
  12278. SSLClient cli("localhost", PORT);
  12279. cli.enable_server_certificate_verification(false);
  12280. cli.set_read_timeout(std::chrono::seconds(100));
  12281. cli.set_write_timeout(std::chrono::seconds(100));
  12282. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  12283. large_size_byte, "application/octet-stream");
  12284. // compare
  12285. EXPECT_EQ(StatusCode::OK_200, res->status);
  12286. EXPECT_EQ(large_size_byte, res->body.size());
  12287. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  12288. }
  12289. #endif
  12290. // ============================================================================
  12291. // MbedTLS-Specific Tests
  12292. // ============================================================================
  12293. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  12294. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  12295. using namespace httplib::tls;
  12296. // Track if callback was invoked
  12297. bool callback_invoked = false;
  12298. // The callback receives void* ctx which is actually MbedTlsContext*
  12299. // We can access the mbedtls_ssl_config via the context
  12300. auto setup_callback = [&callback_invoked](void *ctx) {
  12301. callback_invoked = true;
  12302. // Cast to MbedTlsContext* to access the ssl config
  12303. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  12304. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  12305. // Use static variables to hold certificate data (simplified for test)
  12306. static mbedtls_x509_crt own_cert;
  12307. static mbedtls_pk_context own_key;
  12308. static mbedtls_x509_crt ca_chain;
  12309. static bool initialized = false;
  12310. if (!initialized) {
  12311. mbedtls_x509_crt_init(&own_cert);
  12312. mbedtls_pk_init(&own_key);
  12313. mbedtls_x509_crt_init(&ca_chain);
  12314. // Load server certificate
  12315. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  12316. return false;
  12317. }
  12318. // Load server private key
  12319. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  12320. #if MBEDTLS_VERSION_MAJOR >= 3
  12321. ,
  12322. mbedtls_ctr_drbg_random, nullptr
  12323. #endif
  12324. ) != 0) {
  12325. return false;
  12326. }
  12327. // Load CA chain for client verification
  12328. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  12329. return false;
  12330. }
  12331. initialized = true;
  12332. }
  12333. // Configure the SSL config
  12334. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  12335. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  12336. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  12337. // Set minimum TLS version using mbedTLS native API
  12338. #if MBEDTLS_VERSION_MAJOR >= 3
  12339. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  12340. #else
  12341. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  12342. MBEDTLS_SSL_MINOR_VERSION_3);
  12343. #endif
  12344. return true;
  12345. };
  12346. SSLServer svr(setup_callback);
  12347. ASSERT_TRUE(svr.is_valid());
  12348. ASSERT_TRUE(callback_invoked);
  12349. svr.Get("/test", [&](const Request &req, Response &res) {
  12350. res.set_content("test", "text/plain");
  12351. auto cert = req.peer_cert();
  12352. ASSERT_TRUE(static_cast<bool>(cert));
  12353. auto common_name = cert.subject_cn();
  12354. EXPECT_EQ("Common Name", common_name);
  12355. });
  12356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. t.join();
  12360. ASSERT_FALSE(svr.is_running());
  12361. });
  12362. svr.wait_until_ready();
  12363. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12364. cli.enable_server_certificate_verification(false);
  12365. cli.set_connection_timeout(30);
  12366. auto res = cli.Get("/test");
  12367. ASSERT_TRUE(res);
  12368. ASSERT_EQ(StatusCode::OK_200, res->status);
  12369. }
  12370. #endif