test.cc 437 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261
  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) throw std::runtime_error("File not found: " + path);
  74. fs.seekg(0, std::ios_base::end);
  75. auto size = fs.tellg();
  76. fs.seekg(0);
  77. out.resize(static_cast<size_t>(size));
  78. fs.read(&out[0], static_cast<std::streamsize>(size));
  79. }
  80. void performance_test(const char *host) {
  81. Server svr;
  82. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  83. res.set_content("Benchmark Response", "text/plain");
  84. });
  85. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  86. auto se = detail::scope_exit([&] {
  87. svr.stop();
  88. listen_thread.join();
  89. ASSERT_FALSE(svr.is_running());
  90. });
  91. svr.wait_until_ready();
  92. Client cli(host, PORT);
  93. // Warm-up request to establish connection and resolve DNS
  94. auto warmup_res = cli.Get("/benchmark");
  95. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  96. // Run multiple trials and collect timings
  97. const int num_trials = 20;
  98. std::vector<int64_t> timings;
  99. timings.reserve(num_trials);
  100. for (int i = 0; i < num_trials; i++) {
  101. auto start = std::chrono::high_resolution_clock::now();
  102. auto res = cli.Get("/benchmark");
  103. auto end = std::chrono::high_resolution_clock::now();
  104. auto elapsed =
  105. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  106. .count();
  107. // Assertions after timing measurement to avoid overhead
  108. ASSERT_TRUE(res);
  109. EXPECT_EQ(StatusCode::OK_200, res->status);
  110. timings.push_back(elapsed);
  111. }
  112. // Calculate 25th percentile (lower quartile)
  113. std::sort(timings.begin(), timings.end());
  114. auto p25 = timings[num_trials / 4];
  115. // Format timings for output
  116. std::ostringstream timings_str;
  117. timings_str << "[";
  118. for (size_t i = 0; i < timings.size(); i++) {
  119. if (i > 0) timings_str << ", ";
  120. timings_str << timings[i];
  121. }
  122. timings_str << "]";
  123. // Localhost HTTP GET should be fast even in CI environments
  124. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  125. << "ms (Issue #1777). Timings: " << timings_str.str();
  126. }
  127. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  128. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  129. class UnixSocketTest : public ::testing::Test {
  130. protected:
  131. void TearDown() override { std::remove(pathname_.c_str()); }
  132. void client_GET(const std::string &addr) {
  133. httplib::Client cli{addr};
  134. cli.set_address_family(AF_UNIX);
  135. ASSERT_TRUE(cli.is_valid());
  136. const auto &result = cli.Get(pattern_);
  137. ASSERT_TRUE(result) << "error: " << result.error();
  138. const auto &resp = result.value();
  139. EXPECT_EQ(resp.status, StatusCode::OK_200);
  140. EXPECT_EQ(resp.body, content_);
  141. }
  142. const std::string pathname_{"./httplib-server.sock"};
  143. const std::string pattern_{"/hi"};
  144. const std::string content_{"Hello World!"};
  145. };
  146. TEST_F(UnixSocketTest, pathname) {
  147. httplib::Server svr;
  148. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  149. res.set_content(content_, "text/plain");
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_EQ(0, close(fds[1]));
  254. EXPECT_FALSE(s0.wait_writable());
  255. return true;
  256. });
  257. EXPECT_EQ(0, close(fds[0]));
  258. }
  259. TEST(SocketStream, wait_writable_INET) {
  260. sockaddr_in addr;
  261. memset(&addr, 0, sizeof(addr));
  262. addr.sin_family = AF_INET;
  263. addr.sin_port = htons(PORT + 1);
  264. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  265. int disconnected_svr_sock = -1;
  266. std::thread svr{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. EXPECT_FALSE(ss.wait_writable());
  292. return true;
  293. });
  294. ASSERT_EQ(0, close(disconnected_svr_sock));
  295. }
  296. #endif // #ifndef _WIN32
  297. TEST(ClientTest, MoveConstructible) {
  298. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  299. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  300. }
  301. TEST(ClientTest, MoveAssignable) {
  302. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  303. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  304. }
  305. #ifdef _WIN32
  306. TEST(StartupTest, WSAStartup) {
  307. WSADATA wsaData;
  308. int ret = WSAStartup(0x0002, &wsaData);
  309. ASSERT_EQ(0, ret);
  310. }
  311. #endif
  312. TEST(DecodePathTest, PercentCharacter) {
  313. EXPECT_EQ(
  314. decode_path_component(
  315. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  316. U8("descrip=Gastos áéíóúñÑ 6"));
  317. }
  318. TEST(DecodePathTest, PercentCharacterNUL) {
  319. string expected;
  320. expected.push_back('x');
  321. expected.push_back('\0');
  322. expected.push_back('x');
  323. EXPECT_EQ(decode_path_component("x%00x"), expected);
  324. }
  325. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  326. string unescapedCharacters = "-_.!~*'()";
  327. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  328. }
  329. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  330. string reservedCharacters = ";,/?:@&=+$";
  331. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  332. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  333. }
  334. TEST(ClientQueryOrder, PreserveOrder) {
  335. // This test reproduces Issue #2259: client may reorder query parameters
  336. // when sending a GET request. The expected behavior is that the client
  337. // preserves the original query string order when the caller supplied it
  338. // as part of the path.
  339. Server svr;
  340. svr.Get("/", [&](const Request &req, Response &res) {
  341. // Echo back the raw target so the test can assert ordering
  342. res.set_content(req.target, "text/plain");
  343. });
  344. std::thread t{[&] { svr.listen(HOST, PORT); }};
  345. auto se = detail::scope_exit([&] {
  346. svr.stop();
  347. t.join();
  348. ASSERT_FALSE(svr.is_running());
  349. });
  350. svr.wait_until_ready();
  351. Client cli(HOST, PORT);
  352. ASSERT_TRUE(cli.is_valid());
  353. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  354. auto res = cli.Get(original);
  355. ASSERT_TRUE(res);
  356. // Expect the echoed target to exactly match the original path (order
  357. // preserved)
  358. EXPECT_EQ(res->body, original);
  359. }
  360. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  361. string chineseCharacters = U8("中国語");
  362. string russianCharacters = U8("дом");
  363. string brazilianCharacters = U8("óculos");
  364. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  365. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  366. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  367. "%D0%B4%D0%BE%D0%BC");
  368. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  369. }
  370. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  371. string unescapedCharacters = "-_.!~*'()";
  372. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  373. }
  374. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  375. string reservedCharacters = ";,/?:@&=+$";
  376. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  377. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  378. }
  379. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  380. string chineseCharacters = U8("中国語");
  381. string russianCharacters = U8("дом");
  382. string brazilianCharacters = U8("óculos");
  383. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  384. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  385. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  386. "%D0%B4%D0%BE%D0%BC");
  387. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  388. }
  389. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  390. // Issue #2082 use case: encoding path component with ampersand
  391. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  392. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  393. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  394. }
  395. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  400. string reservedCharacters = ";,/?:@&=+$#";
  401. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  402. }
  403. TEST(EncodeUriTest, TestUTF8Characters) {
  404. string chineseCharacters = U8("中国語");
  405. string russianCharacters = U8("дом");
  406. string brazilianCharacters = U8("óculos");
  407. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  408. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  409. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  410. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  411. }
  412. TEST(EncodeUriTest, TestCompleteUri) {
  413. string uri =
  414. "https://example.com/path/to/resource?query=value&param=test#fragment";
  415. EXPECT_EQ(
  416. httplib::encode_uri(uri),
  417. "https://example.com/path/to/resource?query=value&param=test#fragment");
  418. }
  419. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  420. string uri =
  421. "https://example.com/path with spaces/file name.html?q=hello world";
  422. EXPECT_EQ(httplib::encode_uri(uri),
  423. "https://example.com/path%20with%20spaces/"
  424. "file%20name.html?q=hello%20world");
  425. }
  426. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  427. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  428. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  429. }
  430. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  435. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  436. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  437. string encodedBrazilian = "%C3%B3culos";
  438. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  441. }
  442. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  443. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  445. "Piri Tommy Villiers - on & on");
  446. }
  447. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  449. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  450. }
  451. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  453. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  454. }
  455. TEST(DecodeUriTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriTest, TestCompleteUri) {
  464. string encodedUri = "https://example.com/path%20with%20spaces/"
  465. "file%20name.html?q=hello%20world";
  466. EXPECT_EQ(
  467. httplib::decode_uri(encodedUri),
  468. "https://example.com/path with spaces/file name.html?q=hello world");
  469. }
  470. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  471. string original =
  472. "https://example.com/path with spaces/file name.html?q=hello world";
  473. string encoded = httplib::encode_uri(original);
  474. string decoded = httplib::decode_uri(encoded);
  475. EXPECT_EQ(decoded, original);
  476. }
  477. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  478. string original = "Piri Tommy Villiers - on & on";
  479. string encoded = httplib::encode_uri_component(original);
  480. string decoded = httplib::decode_uri_component(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(TrimTests, TrimStringTests) {
  484. EXPECT_EQ("abc", detail::trim_copy("abc"));
  485. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  486. EXPECT_TRUE(detail::trim_copy("").empty());
  487. }
  488. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  489. // Simple case without quality values
  490. std::vector<std::string> result1;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html,application/json,text/plain", result1));
  493. EXPECT_EQ(result1.size(), 3U);
  494. EXPECT_EQ(result1[0], "text/html");
  495. EXPECT_EQ(result1[1], "application/json");
  496. EXPECT_EQ(result1[2], "text/plain");
  497. // With quality values
  498. std::vector<std::string> result2;
  499. EXPECT_TRUE(detail::parse_accept_header(
  500. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  501. EXPECT_EQ(result2.size(), 3U);
  502. EXPECT_EQ(result2[0], "application/json"); // highest q value
  503. EXPECT_EQ(result2[1], "text/html");
  504. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  505. }
  506. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  507. // Mixed with and without quality values
  508. std::vector<std::string> result;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  511. EXPECT_EQ(result.size(), 3U);
  512. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  513. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  514. EXPECT_EQ(result[2], "application/json"); // q=0.5
  515. }
  516. TEST(ParseAcceptHeaderTest, EdgeCases) {
  517. // Empty header
  518. std::vector<std::string> empty_result;
  519. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  520. EXPECT_TRUE(empty_result.empty());
  521. // Single type
  522. std::vector<std::string> single_result;
  523. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  524. EXPECT_EQ(single_result.size(), 1U);
  525. EXPECT_EQ(single_result[0], "application/json");
  526. // Wildcard types
  527. std::vector<std::string> wildcard_result;
  528. EXPECT_TRUE(detail::parse_accept_header(
  529. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  530. EXPECT_EQ(wildcard_result.size(), 3U);
  531. EXPECT_EQ(wildcard_result[0], "application/json");
  532. EXPECT_EQ(wildcard_result[1], "text/*");
  533. EXPECT_EQ(wildcard_result[2], "*/*");
  534. }
  535. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  536. // Common browser Accept header
  537. std::vector<std::string> browser_result;
  538. EXPECT_TRUE(
  539. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  540. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  541. browser_result));
  542. EXPECT_EQ(browser_result.size(), 6U);
  543. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  548. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  549. // API client header
  550. std::vector<std::string> api_result;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  553. api_result));
  554. EXPECT_EQ(api_result.size(), 3U);
  555. EXPECT_EQ(api_result[0], "application/json");
  556. EXPECT_EQ(api_result[1], "application/xml");
  557. EXPECT_EQ(api_result[2], "text/plain");
  558. }
  559. TEST(ParseAcceptHeaderTest, SpecialCases) {
  560. // Quality value with 3 decimal places
  561. std::vector<std::string> decimal_result;
  562. EXPECT_TRUE(detail::parse_accept_header(
  563. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  564. EXPECT_EQ(decimal_result.size(), 2U);
  565. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  566. EXPECT_EQ(decimal_result[1], "text/html");
  567. // Zero quality (should still be included but with lowest priority)
  568. std::vector<std::string> zero_q_result;
  569. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  570. zero_q_result));
  571. EXPECT_EQ(zero_q_result.size(), 2U);
  572. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  573. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  574. // No spaces around commas
  575. std::vector<std::string> no_space_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  578. no_space_result));
  579. EXPECT_EQ(no_space_result.size(), 3U);
  580. EXPECT_EQ(no_space_result[0], "text/html");
  581. EXPECT_EQ(no_space_result[1], "application/json");
  582. EXPECT_EQ(no_space_result[2], "text/plain");
  583. }
  584. TEST(ParseAcceptHeaderTest, InvalidCases) {
  585. std::vector<std::string> result;
  586. // Invalid quality value (> 1.0)
  587. EXPECT_FALSE(
  588. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  589. // Invalid quality value (< 0.0)
  590. EXPECT_FALSE(
  591. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  592. // Invalid quality value (not a number)
  593. EXPECT_FALSE(detail::parse_accept_header(
  594. "text/html;q=invalid,application/json", result));
  595. // Empty quality value
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=,application/json", result));
  598. // Invalid media type format (no slash and not wildcard)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("invalidtype,application/json", result));
  601. // Empty media type
  602. result.clear();
  603. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  604. // Only commas
  605. result.clear();
  606. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  607. // Valid cases should still work
  608. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  609. EXPECT_EQ(result.size(), 1U);
  610. EXPECT_EQ(result[0], "*/*");
  611. EXPECT_TRUE(detail::parse_accept_header("*", result));
  612. EXPECT_EQ(result.size(), 1U);
  613. EXPECT_EQ(result[0], "*");
  614. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "text/*");
  617. }
  618. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  619. Server svr;
  620. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  621. EXPECT_EQ(req.accept_content_types.size(), 3U);
  622. EXPECT_EQ(req.accept_content_types[0], "application/json");
  623. EXPECT_EQ(req.accept_content_types[1], "text/html");
  624. EXPECT_EQ(req.accept_content_types[2], "*/*");
  625. res.set_content("ok", "text/plain");
  626. });
  627. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  628. EXPECT_TRUE(false);
  629. res.set_content("bad request", "text/plain");
  630. });
  631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  632. auto se = detail::scope_exit([&] {
  633. svr.stop();
  634. listen_thread.join();
  635. ASSERT_FALSE(svr.is_running());
  636. });
  637. svr.wait_until_ready();
  638. Client cli("localhost", PORT);
  639. {
  640. auto res =
  641. cli.Get("/accept_ok",
  642. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  643. ASSERT_TRUE(res);
  644. EXPECT_EQ(StatusCode::OK_200, res->status);
  645. }
  646. {
  647. auto res = cli.Get("/accept_bad_request",
  648. {{"Accept", "text/html;q=abc,application/json"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  651. }
  652. }
  653. TEST(DivideTest, DivideStringTests) {
  654. auto divide = [](const std::string &str, char d) {
  655. std::string lhs;
  656. std::string rhs;
  657. detail::divide(str, d,
  658. [&](const char *lhs_data, std::size_t lhs_size,
  659. const char *rhs_data, std::size_t rhs_size) {
  660. lhs.assign(lhs_data, lhs_size);
  661. rhs.assign(rhs_data, rhs_size);
  662. });
  663. return std::make_pair(std::move(lhs), std::move(rhs));
  664. };
  665. {
  666. const auto res = divide("", '=');
  667. EXPECT_EQ(res.first, "");
  668. EXPECT_EQ(res.second, "");
  669. }
  670. {
  671. const auto res = divide("=", '=');
  672. EXPECT_EQ(res.first, "");
  673. EXPECT_EQ(res.second, "");
  674. }
  675. {
  676. const auto res = divide(" ", '=');
  677. EXPECT_EQ(res.first, " ");
  678. EXPECT_EQ(res.second, "");
  679. }
  680. {
  681. const auto res = divide("a", '=');
  682. EXPECT_EQ(res.first, "a");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("a=", '=');
  687. EXPECT_EQ(res.first, "a");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide("=b", '=');
  692. EXPECT_EQ(res.first, "");
  693. EXPECT_EQ(res.second, "b");
  694. }
  695. {
  696. const auto res = divide("a=b", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "b");
  699. }
  700. {
  701. const auto res = divide("a=b=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "b=");
  704. }
  705. {
  706. const auto res = divide("a=b=c", '=');
  707. EXPECT_EQ(res.first, "a");
  708. EXPECT_EQ(res.second, "b=c");
  709. }
  710. }
  711. TEST(SplitTest, ParseQueryString) {
  712. string s = "key1=val1&key2=val2&key3=val3";
  713. Params dic;
  714. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  715. [&](const char *b, const char *e) {
  716. string key, val;
  717. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  718. if (key.empty()) {
  719. key.assign(b2, e2);
  720. } else {
  721. val.assign(b2, e2);
  722. }
  723. });
  724. dic.emplace(key, val);
  725. });
  726. EXPECT_EQ("val1", dic.find("key1")->second);
  727. EXPECT_EQ("val2", dic.find("key2")->second);
  728. EXPECT_EQ("val3", dic.find("key3")->second);
  729. }
  730. TEST(SplitTest, ParseInvalidQueryTests) {
  731. {
  732. string s = " ";
  733. Params dict;
  734. detail::parse_query_text(s, dict);
  735. EXPECT_TRUE(dict.empty());
  736. }
  737. {
  738. string s = " = =";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. }
  744. TEST(ParseQueryTest, ParseQueryString) {
  745. {
  746. std::string s = "key1=val1&key2=val2&key3=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("val1", dic.find("key1")->second);
  750. EXPECT_EQ("val2", dic.find("key2")->second);
  751. EXPECT_EQ("val3", dic.find("key3")->second);
  752. }
  753. {
  754. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  755. Params dic;
  756. detail::parse_query_text(s, dic);
  757. EXPECT_EQ("", dic.find("key1")->second);
  758. EXPECT_EQ("val1", dic.find("key2")->second);
  759. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  760. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  761. }
  762. }
  763. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  764. Params dic;
  765. EXPECT_EQ(detail::params_to_query_str(dic), "");
  766. dic.emplace("key1", "val1");
  767. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  768. dic.emplace("key2", "val2");
  769. dic.emplace("key3", "val3");
  770. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  771. }
  772. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  773. string content_type = "multipart/form-data; boundary=something";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "something");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  780. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  795. string content_type =
  796. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  797. string boundary;
  798. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  801. }
  802. TEST(GetHeaderValueTest, DefaultValue) {
  803. Headers headers = {{"Dummy", "Dummy"}};
  804. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  805. EXPECT_STREQ("text/plain", val);
  806. }
  807. TEST(GetHeaderValueTest, DefaultValueInt) {
  808. Headers headers = {{"Dummy", "Dummy"}};
  809. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  810. EXPECT_EQ(100ull, val);
  811. }
  812. TEST(GetHeaderValueTest, RegularValue) {
  813. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  814. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  815. EXPECT_STREQ("text/html", val);
  816. }
  817. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  818. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  820. EXPECT_STREQ("text/html", val);
  821. }
  822. TEST(GetHeaderValueTest, SetContent) {
  823. Response res;
  824. res.set_content("html", "text/html");
  825. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  826. res.set_content("text", "text/plain");
  827. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  828. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  829. }
  830. TEST(GetHeaderValueTest, RegularValueInt) {
  831. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  833. EXPECT_EQ(100ull, val);
  834. }
  835. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  836. Headers headers = {{"Content-Length", "x"}};
  837. auto is_invalid_value = false;
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  839. is_invalid_value);
  840. EXPECT_EQ(0ull, val);
  841. EXPECT_TRUE(is_invalid_value);
  842. }
  843. TEST(GetHeaderValueTest, Range) {
  844. {
  845. Headers headers = {make_range_header({{1, -1}})};
  846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  847. EXPECT_STREQ("bytes=1-", val);
  848. }
  849. {
  850. Headers headers = {make_range_header({{-1, 1}})};
  851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  852. EXPECT_STREQ("bytes=-1", val);
  853. }
  854. {
  855. Headers headers = {make_range_header({{1, 10}})};
  856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  857. EXPECT_STREQ("bytes=1-10", val);
  858. }
  859. {
  860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-10, 100-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=0-0, -1", val);
  873. }
  874. }
  875. TEST(ParseHeaderValueTest, Range) {
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=1-", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(1u, ranges[0].first);
  882. EXPECT_EQ(-1, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=-1", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(-1, ranges[0].first);
  890. EXPECT_EQ(1u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  895. EXPECT_TRUE(ret);
  896. EXPECT_EQ(1u, ranges.size());
  897. EXPECT_EQ(1u, ranges[0].first);
  898. EXPECT_EQ(10u, ranges[0].second);
  899. }
  900. {
  901. Ranges ranges;
  902. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  903. EXPECT_FALSE(ret);
  904. }
  905. {
  906. Ranges ranges;
  907. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  908. EXPECT_TRUE(ret);
  909. EXPECT_EQ(2u, ranges.size());
  910. EXPECT_EQ(1u, ranges[0].first);
  911. EXPECT_EQ(10u, ranges[0].second);
  912. EXPECT_EQ(100u, ranges[1].first);
  913. EXPECT_EQ(-1, ranges[1].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret =
  918. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  919. EXPECT_TRUE(ret);
  920. EXPECT_EQ(3u, ranges.size());
  921. EXPECT_EQ(1u, ranges[0].first);
  922. EXPECT_EQ(10u, ranges[0].second);
  923. EXPECT_EQ(100u, ranges[1].first);
  924. EXPECT_EQ(200u, ranges[1].second);
  925. EXPECT_EQ(300u, ranges[2].first);
  926. EXPECT_EQ(400u, ranges[2].second);
  927. }
  928. {
  929. Ranges ranges;
  930. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,", 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=a-b", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  943. EXPECT_TRUE(ranges.empty());
  944. }
  945. }
  946. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  947. Request req;
  948. req.set_header("Accept-Encoding", "gzip");
  949. Response res;
  950. res.set_header("Content-Type", "text/plain");
  951. auto ret = detail::encoding_type(req, res);
  952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  966. #elif CPPHTTPLIB_ZLIB_SUPPORT
  967. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  968. #elif CPPHTTPLIB_ZSTD_SUPPORT
  969. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  970. #else
  971. EXPECT_TRUE(ret == detail::EncodingType::None);
  972. #endif
  973. }
  974. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  975. Request req;
  976. req.set_header("Accept-Encoding",
  977. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  978. Response res;
  979. res.set_header("Content-Type", "text/plain");
  980. auto ret = detail::encoding_type(req, res);
  981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  983. #elif CPPHTTPLIB_ZLIB_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  985. #elif CPPHTTPLIB_ZSTD_SUPPORT
  986. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  987. #else
  988. EXPECT_TRUE(ret == detail::EncodingType::None);
  989. #endif
  990. }
  991. TEST(BufferStreamTest, read) {
  992. detail::BufferStream strm1;
  993. Stream &strm = strm1;
  994. EXPECT_EQ(5, strm.write("hello"));
  995. char buf[512];
  996. EXPECT_EQ(2, strm.read(buf, 2));
  997. EXPECT_EQ('h', buf[0]);
  998. EXPECT_EQ('e', buf[1]);
  999. EXPECT_EQ(2, strm.read(buf, 2));
  1000. EXPECT_EQ('l', buf[0]);
  1001. EXPECT_EQ('l', buf[1]);
  1002. EXPECT_EQ(1, strm.read(buf, 1));
  1003. EXPECT_EQ('o', buf[0]);
  1004. EXPECT_EQ(0, strm.read(buf, 1));
  1005. }
  1006. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1007. auto host = "www.httpwatch.com";
  1008. auto ip = hosted_at(host);
  1009. EXPECT_EQ("23.96.13.243", ip);
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(1u, addrs.size());
  1013. }
  1014. #if 0 // It depends on each test environment...
  1015. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1016. auto host = "www.youtube.com";
  1017. std::vector<std::string> addrs;
  1018. hosted_at(host, addrs);
  1019. EXPECT_EQ(20u, addrs.size());
  1020. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1021. EXPECT_TRUE(it != addrs.end());
  1022. }
  1023. #endif
  1024. class ChunkedEncodingTest : public ::testing::Test {
  1025. protected:
  1026. ChunkedEncodingTest()
  1027. : cli_(HOST, PORT)
  1028. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1029. ,
  1030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1031. #endif
  1032. {
  1033. cli_.set_connection_timeout(2);
  1034. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1035. cli_.enable_server_certificate_verification(false);
  1036. #endif
  1037. }
  1038. virtual void SetUp() {
  1039. read_file("./image.jpg", image_data_);
  1040. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content("Hello World!", "text/plain");
  1042. });
  1043. svr_.Get(
  1044. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1045. res.set_chunked_content_provider(
  1046. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1047. size_t remaining = image_data_.size() - offset;
  1048. if (remaining == 0) {
  1049. sink.done();
  1050. } else {
  1051. constexpr size_t CHUNK_SIZE = 1024;
  1052. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1053. sink.write(&image_data_[offset], send_size);
  1054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1055. }
  1056. return true;
  1057. });
  1058. });
  1059. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1060. svr_.wait_until_ready();
  1061. }
  1062. virtual void TearDown() {
  1063. svr_.stop();
  1064. if (!request_threads_.empty()) {
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. for (auto &t : request_threads_) {
  1067. t.join();
  1068. }
  1069. }
  1070. t_.join();
  1071. }
  1072. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1073. SSLClient cli_;
  1074. SSLServer svr_;
  1075. #else
  1076. Client cli_;
  1077. Server svr_;
  1078. #endif
  1079. thread t_;
  1080. std::vector<thread> request_threads_;
  1081. std::string image_data_;
  1082. };
  1083. TEST_F(ChunkedEncodingTest, NormalGet) {
  1084. auto res = cli_.Get("/chunked");
  1085. ASSERT_TRUE(res);
  1086. std::string out;
  1087. read_file("./image.jpg", out);
  1088. EXPECT_EQ(StatusCode::OK_200, res->status);
  1089. EXPECT_EQ(out, res->body);
  1090. }
  1091. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1092. std::string body;
  1093. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1094. body.append(data, data_length);
  1095. return true;
  1096. });
  1097. ASSERT_TRUE(res);
  1098. std::string out;
  1099. read_file("./image.jpg", out);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. EXPECT_EQ(out, body);
  1102. }
  1103. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1104. std::string body;
  1105. auto res = cli_.Get(
  1106. "/chunked",
  1107. [&](const Response &response) {
  1108. EXPECT_EQ(StatusCode::OK_200, response.status);
  1109. return true;
  1110. },
  1111. [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST(RangeTest, FromHTTPBin_Online) {
  1122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1123. auto host = "httpcan.org";
  1124. auto path = std::string{"/range/32"};
  1125. #else
  1126. auto host = "nghttp2.org";
  1127. auto path = std::string{"/httpbin/range/32"};
  1128. #endif
  1129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1130. auto port = 443;
  1131. SSLClient cli(host, port);
  1132. #else
  1133. auto port = 80;
  1134. Client cli(host, port);
  1135. #endif
  1136. cli.set_connection_timeout(5);
  1137. {
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::OK_200, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, -1}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{1, 10}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("bcdefghijk", res->body);
  1155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, 31}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, -1}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. }
  1171. {
  1172. Headers headers = {make_range_header({{0, 32}})};
  1173. auto res = cli.Get(path, headers);
  1174. ASSERT_TRUE(res);
  1175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1176. }
  1177. }
  1178. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1179. auto host = "unresolvableaddress.local";
  1180. auto path = std::string{"/"};
  1181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(1);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_FALSE(res);
  1192. }
  1193. std::this_thread::sleep_for(std::chrono::seconds(8));
  1194. }
  1195. TEST(ConnectionErrorTest, InvalidHost) {
  1196. auto host = "-abcde.com";
  1197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1198. auto port = 443;
  1199. SSLClient cli(host, port);
  1200. #else
  1201. auto port = 80;
  1202. Client cli(host, port);
  1203. #endif
  1204. cli.set_connection_timeout(std::chrono::seconds(2));
  1205. auto res = cli.Get("/");
  1206. ASSERT_TRUE(!res);
  1207. EXPECT_EQ(Error::Connection, res.error());
  1208. }
  1209. TEST(ConnectionErrorTest, InvalidHost2) {
  1210. auto host = "httpcan.org/";
  1211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1212. SSLClient cli(host);
  1213. #else
  1214. Client cli(host);
  1215. #endif
  1216. cli.set_connection_timeout(std::chrono::seconds(2));
  1217. auto res = cli.Get("/");
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Connection, res.error());
  1220. }
  1221. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1222. auto host = "httpcan.org/";
  1223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1224. SSLClient cli(host);
  1225. #else
  1226. Client cli(host);
  1227. #endif
  1228. cli.set_connection_timeout(std::chrono::seconds(2));
  1229. auto res = cli.Get("/");
  1230. ASSERT_TRUE(!res);
  1231. stringstream s;
  1232. s << "error code: " << res.error();
  1233. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1234. }
  1235. TEST(ConnectionErrorTest, InvalidPort) {
  1236. auto host = "localhost";
  1237. auto port = 44380;
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host, port);
  1240. #else
  1241. Client cli(host, port);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. EXPECT_TRUE(Error::Connection == res.error() ||
  1247. Error::ConnectionTimeout == res.error());
  1248. }
  1249. TEST(ConnectionErrorTest, Timeout_Online) {
  1250. auto host = "google.com";
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. auto port = 44380;
  1253. SSLClient cli(host, port);
  1254. #else
  1255. auto port = 8080;
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. // only probe one address type so that the error reason
  1260. // correlates to the timed-out IPv4, not the unsupported
  1261. // IPv6 connection attempt
  1262. cli.set_address_family(AF_INET);
  1263. auto res = cli.Get("/");
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1266. }
  1267. TEST(CancelTest, NoCancel_Online) {
  1268. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1269. auto host = "httpcan.org";
  1270. auto path = std::string{"/range/32"};
  1271. #else
  1272. auto host = "nghttp2.org";
  1273. auto path = std::string{"/httpbin/range/32"};
  1274. #endif
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. auto port = 443;
  1277. SSLClient cli(host, port);
  1278. #else
  1279. auto port = 80;
  1280. Client cli(host, port);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(5));
  1283. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1284. ASSERT_TRUE(res);
  1285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1286. EXPECT_EQ(StatusCode::OK_200, res->status);
  1287. }
  1288. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1289. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1290. auto host = "httpcan.org";
  1291. auto path = std::string{"/range/32"};
  1292. #else
  1293. auto host = "nghttp2.org";
  1294. auto path = std::string{"/httpbin/range/32"};
  1295. #endif
  1296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1304. cli.set_connection_timeout(std::chrono::seconds(5));
  1305. ASSERT_TRUE(!res);
  1306. EXPECT_EQ(Error::Canceled, res.error());
  1307. }
  1308. TEST(CancelTest, WithCancelLargePayload_Online) {
  1309. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1310. auto host = "httpcan.org";
  1311. auto path = std::string{"/range/65536"};
  1312. #else
  1313. auto host = "nghttp2.org";
  1314. auto path = std::string{"/httpbin/range/65536"};
  1315. #endif
  1316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1317. auto port = 443;
  1318. SSLClient cli(host, port);
  1319. #else
  1320. auto port = 80;
  1321. Client cli(host, port);
  1322. #endif
  1323. cli.set_connection_timeout(std::chrono::seconds(5));
  1324. uint32_t count = 0;
  1325. auto res =
  1326. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1327. ASSERT_TRUE(!res);
  1328. EXPECT_EQ(Error::Canceled, res.error());
  1329. }
  1330. TEST(CancelTest, NoCancelPost) {
  1331. Server svr;
  1332. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1333. res.set_content("Hello World!", "text/plain");
  1334. });
  1335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1336. auto se = detail::scope_exit([&] {
  1337. svr.stop();
  1338. thread.join();
  1339. ASSERT_FALSE(svr.is_running());
  1340. });
  1341. svr.wait_until_ready();
  1342. Client cli(HOST, PORT);
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res =
  1345. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1346. "application/json", [](uint64_t, uint64_t) { return true; });
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("Hello World!", res->body);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1352. Server svr;
  1353. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1354. res.set_content("Hello World!", "text/plain");
  1355. });
  1356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1357. auto se = detail::scope_exit([&] {
  1358. svr.stop();
  1359. thread.join();
  1360. ASSERT_FALSE(svr.is_running());
  1361. });
  1362. svr.wait_until_ready();
  1363. Client cli(HOST, PORT);
  1364. cli.set_connection_timeout(std::chrono::seconds(5));
  1365. auto res =
  1366. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1367. "application/json", [](uint64_t, uint64_t) { return false; });
  1368. ASSERT_TRUE(!res);
  1369. EXPECT_EQ(Error::Canceled, res.error());
  1370. }
  1371. TEST(CancelTest, WithCancelLargePayloadPost) {
  1372. Server svr;
  1373. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1374. res.set_content(LARGE_DATA, "text/plain");
  1375. });
  1376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1377. auto se = detail::scope_exit([&] {
  1378. svr.stop();
  1379. thread.join();
  1380. ASSERT_FALSE(svr.is_running());
  1381. });
  1382. svr.wait_until_ready();
  1383. Client cli(HOST, PORT);
  1384. cli.set_connection_timeout(std::chrono::seconds(5));
  1385. auto res =
  1386. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1387. "application/json", [](uint64_t, uint64_t) { return false; });
  1388. ASSERT_TRUE(!res);
  1389. EXPECT_EQ(Error::Canceled, res.error());
  1390. }
  1391. TEST(CancelTest, NoCancelPut) {
  1392. Server svr;
  1393. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. });
  1396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. thread.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. Client cli(HOST, PORT);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return true; });
  1408. ASSERT_TRUE(res);
  1409. EXPECT_EQ("Hello World!", res->body);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. }
  1412. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1413. Server svr;
  1414. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1415. res.set_content("Hello World!", "text/plain");
  1416. });
  1417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1418. auto se = detail::scope_exit([&] {
  1419. svr.stop();
  1420. thread.join();
  1421. ASSERT_FALSE(svr.is_running());
  1422. });
  1423. svr.wait_until_ready();
  1424. Client cli(HOST, PORT);
  1425. cli.set_connection_timeout(std::chrono::seconds(5));
  1426. auto res =
  1427. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1428. "application/json", [](uint64_t, uint64_t) { return false; });
  1429. ASSERT_TRUE(!res);
  1430. EXPECT_EQ(Error::Canceled, res.error());
  1431. }
  1432. TEST(CancelTest, WithCancelLargePayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content(LARGE_DATA, "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, NoCancelPatch) {
  1453. Server svr;
  1454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("Hello World!", "text/plain");
  1456. });
  1457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1458. auto se = detail::scope_exit([&] {
  1459. svr.stop();
  1460. thread.join();
  1461. ASSERT_FALSE(svr.is_running());
  1462. });
  1463. svr.wait_until_ready();
  1464. Client cli(HOST, PORT);
  1465. cli.set_connection_timeout(std::chrono::seconds(5));
  1466. auto res =
  1467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1468. "application/json", [](uint64_t, uint64_t) { return true; });
  1469. ASSERT_TRUE(res);
  1470. EXPECT_EQ("Hello World!", res->body);
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1474. Server svr;
  1475. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1476. res.set_content("Hello World!", "text/plain");
  1477. });
  1478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. thread.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. Client cli(HOST, PORT);
  1486. cli.set_connection_timeout(std::chrono::seconds(5));
  1487. auto res =
  1488. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1489. "application/json", [](uint64_t, uint64_t) { return false; });
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_EQ(Error::Canceled, res.error());
  1492. }
  1493. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1494. Server svr;
  1495. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1496. res.set_content(LARGE_DATA, "text/plain");
  1497. });
  1498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1499. auto se = detail::scope_exit([&] {
  1500. svr.stop();
  1501. thread.join();
  1502. ASSERT_FALSE(svr.is_running());
  1503. });
  1504. svr.wait_until_ready();
  1505. Client cli(HOST, PORT);
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. auto res =
  1508. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1509. "application/json", [](uint64_t, uint64_t) { return false; });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelDelete) {
  1514. Server svr;
  1515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1555. Server svr;
  1556. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1557. res.set_content(LARGE_DATA, "text/plain");
  1558. });
  1559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. thread.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. Client cli(HOST, PORT);
  1567. cli.set_connection_timeout(std::chrono::seconds(5));
  1568. auto res =
  1569. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1570. "application/json", [](uint64_t, uint64_t) { return false; });
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Canceled, res.error());
  1573. }
  1574. static std::string remove_whitespace(const std::string &input) {
  1575. std::string output;
  1576. output.reserve(input.size());
  1577. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1578. [](unsigned char c) { return !std::isspace(c); });
  1579. return output;
  1580. }
  1581. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1582. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1583. auto host = "httpcan.org";
  1584. auto path = std::string{"/basic-auth/hello/world"};
  1585. #else
  1586. auto host = "nghttp2.org";
  1587. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1588. #endif
  1589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1590. auto port = 443;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 80;
  1594. Client cli(host, port);
  1595. #endif
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1600. }
  1601. {
  1602. auto res =
  1603. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "world");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1614. remove_whitespace(res->body));
  1615. EXPECT_EQ(StatusCode::OK_200, res->status);
  1616. }
  1617. {
  1618. cli.set_basic_auth("hello", "bad");
  1619. auto res = cli.Get(path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("bad", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. }
  1630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1631. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1632. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1633. auto host = "httpcan.org";
  1634. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/digest-auth/auth/hello/world/MD5",
  1637. "/digest-auth/auth/hello/world/SHA-256",
  1638. "/digest-auth/auth/hello/world/SHA-512",
  1639. };
  1640. #else
  1641. auto host = "nghttp2.org";
  1642. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1643. auto paths = std::vector<std::string>{
  1644. "/httpbin/digest-auth/auth/hello/world/MD5",
  1645. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1646. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1647. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1648. };
  1649. #endif
  1650. auto port = 443;
  1651. SSLClient cli(host, port);
  1652. {
  1653. auto res = cli.Get(unauth_path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. cli.set_digest_auth("hello", "world");
  1659. for (const auto &path : paths) {
  1660. auto res = cli.Get(path.c_str());
  1661. ASSERT_TRUE(res);
  1662. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1663. std::string algo(path.substr(path.rfind('/') + 1));
  1664. EXPECT_EQ(
  1665. remove_whitespace("{\"algorithm\":\"" + algo +
  1666. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1667. remove_whitespace(res->body));
  1668. #else
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. #endif
  1672. EXPECT_EQ(StatusCode::OK_200, res->status);
  1673. }
  1674. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1675. cli.set_digest_auth("hello", "bad");
  1676. for (const auto &path : paths) {
  1677. auto res = cli.Get(path.c_str());
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. #endif
  1682. }
  1683. }
  1684. #endif
  1685. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1686. auto host = "google.com";
  1687. auto another_host = "example.com";
  1688. auto wrong_ip = "0.0.0.0";
  1689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1690. SSLClient cli(host);
  1691. #else
  1692. Client cli(host);
  1693. #endif
  1694. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1695. auto res = cli.Get("/");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1698. }
  1699. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1700. auto host = "google.com";
  1701. auto wrong_ip = "0.0.0.0";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_hostname_addr_map({{host, wrong_ip}});
  1708. auto res = cli.Get("/");
  1709. ASSERT_TRUE(!res);
  1710. EXPECT_EQ(Error::Connection, res.error());
  1711. }
  1712. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(StatusCode::OK_200, res->status);
  1723. }
  1724. TEST(RedirectTest, Redirect_Online) {
  1725. auto host = "nghttp2.org";
  1726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_follow_location(true);
  1732. auto res = cli.Get("/httpbin/redirect/3");
  1733. ASSERT_TRUE(res);
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. TEST(RelativeRedirectTest, Redirect_Online) {
  1737. auto host = "nghttp2.org";
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_follow_location(true);
  1744. auto res = cli.Get("/httpbin/relative-redirect/3");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. }
  1748. TEST(TooManyRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/redirect/21");
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1759. }
  1760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1761. TEST(YahooRedirectTest, Redirect_Online) {
  1762. Client cli("yahoo.com");
  1763. auto res = cli.Get("/");
  1764. ASSERT_TRUE(res);
  1765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1766. cli.set_follow_location(true);
  1767. res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1771. }
  1772. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1773. #define REDIR_HOST "httpbingo.org"
  1774. #define REDIR_PATH "/redirect-to"
  1775. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. auto res =
  1779. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ(StatusCode::OK_200, res->status);
  1782. }
  1783. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1784. SSLClient cli(REDIR_HOST);
  1785. cli.set_follow_location(true);
  1786. Params params;
  1787. params.emplace("url", "http://example.com");
  1788. params.emplace("status_code", "302");
  1789. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::OK_200, res->status);
  1792. }
  1793. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1794. SSLClient cli(REDIR_HOST);
  1795. cli.set_follow_location(true);
  1796. Params params;
  1797. params.emplace("url", "http://example.com");
  1798. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. }
  1802. TEST(UrlWithSpace, Redirect_Online) {
  1803. SSLClient cli("edge.forgecdn.net");
  1804. cli.set_follow_location(true);
  1805. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1809. }
  1810. #endif
  1811. #if !defined(_WIN32) && !defined(_WIN64)
  1812. TEST(ReceiveSignals, Signal) {
  1813. auto setupSignalHandlers = []() {
  1814. struct sigaction act;
  1815. sigemptyset(&act.sa_mask);
  1816. act.sa_flags = SA_SIGINFO;
  1817. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1818. switch (sig) {
  1819. case SIGINT:
  1820. default: break;
  1821. }
  1822. };
  1823. ::sigaction(SIGINT, &act, nullptr);
  1824. };
  1825. Server svr;
  1826. int port = 0;
  1827. auto thread = std::thread([&]() {
  1828. setupSignalHandlers();
  1829. port = svr.bind_to_any_port(HOST);
  1830. svr.listen_after_bind();
  1831. });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. ASSERT_TRUE(svr.is_running());
  1839. pthread_kill(thread.native_handle(), SIGINT);
  1840. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1841. ASSERT_TRUE(svr.is_running());
  1842. }
  1843. #endif
  1844. TEST(RedirectToDifferentPort, Redirect) {
  1845. Server svr1;
  1846. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. int svr1_port = 0;
  1850. auto thread1 = std::thread([&]() {
  1851. svr1_port = svr1.bind_to_any_port(HOST);
  1852. svr1.listen_after_bind();
  1853. });
  1854. Server svr2;
  1855. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1856. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1857. });
  1858. int svr2_port = 0;
  1859. auto thread2 = std::thread([&]() {
  1860. svr2_port = svr2.bind_to_any_port(HOST);
  1861. svr2.listen_after_bind();
  1862. });
  1863. auto se = detail::scope_exit([&] {
  1864. svr2.stop();
  1865. thread2.join();
  1866. svr1.stop();
  1867. thread1.join();
  1868. ASSERT_FALSE(svr2.is_running());
  1869. ASSERT_FALSE(svr1.is_running());
  1870. });
  1871. svr1.wait_until_ready();
  1872. svr2.wait_until_ready();
  1873. Client cli("localhost", svr2_port);
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/2");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(StatusCode::OK_200, res->status);
  1878. EXPECT_EQ("Hello World!", res->body);
  1879. }
  1880. TEST(RedirectFromPageWithContent, Redirect) {
  1881. Server svr;
  1882. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("___", "text/plain");
  1884. res.set_redirect("/2");
  1885. });
  1886. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("Hello World!", "text/plain");
  1888. });
  1889. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1890. auto se = detail::scope_exit([&] {
  1891. svr.stop();
  1892. th.join();
  1893. ASSERT_FALSE(svr.is_running());
  1894. });
  1895. svr.wait_until_ready();
  1896. {
  1897. Client cli("localhost", PORT);
  1898. cli.set_follow_location(true);
  1899. std::string body;
  1900. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1901. body.append(data, data_length);
  1902. return true;
  1903. });
  1904. ASSERT_TRUE(res);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. EXPECT_EQ("Hello World!", body);
  1907. }
  1908. {
  1909. Client cli("localhost", PORT);
  1910. std::string body;
  1911. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1912. body.append(data, data_length);
  1913. return true;
  1914. });
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::Found_302, res->status);
  1917. EXPECT_EQ("___", body);
  1918. }
  1919. }
  1920. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1921. Server svr;
  1922. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1923. res.set_content("___", "text/plain");
  1924. // res.set_redirect("/2");
  1925. res.set_redirect("http://[::1]:1234/2");
  1926. });
  1927. svr.Get("/2", [&](const Request &req, Response &res) {
  1928. auto host_header = req.headers.find("Host");
  1929. ASSERT_TRUE(host_header != req.headers.end());
  1930. EXPECT_EQ("[::1]:1234", host_header->second);
  1931. res.set_content("Hello World!", "text/plain");
  1932. });
  1933. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. th.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1940. // actually starts anything, so the condition !svr.is_running() will
  1941. // always remain true, and the loop never stops.
  1942. // This basically counts how many milliseconds have passed since the
  1943. // call to svr.listen(), and if after 5 seconds nothing started yet
  1944. // aborts the test.
  1945. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1946. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1947. ASSERT_LT(milliseconds, 5000U);
  1948. }
  1949. {
  1950. Client cli("http://[::1]:1234");
  1951. cli.set_follow_location(true);
  1952. std::string body;
  1953. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1954. body.append(data, data_length);
  1955. return true;
  1956. });
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", body);
  1960. }
  1961. {
  1962. Client cli("http://[::1]:1234");
  1963. std::string body;
  1964. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1965. body.append(data, data_length);
  1966. return true;
  1967. });
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::Found_302, res->status);
  1970. EXPECT_EQ("___", body);
  1971. }
  1972. }
  1973. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1974. Server svr;
  1975. svr.Get("/foo", [](const Request &req, Response &res) {
  1976. auto a = req.params.find("a");
  1977. if (a != req.params.end()) {
  1978. res.set_content((*a).second, "text/plain");
  1979. res.status = StatusCode::OK_200;
  1980. } else {
  1981. res.status = StatusCode::BadRequest_400;
  1982. }
  1983. });
  1984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1985. auto se = detail::scope_exit([&] {
  1986. svr.stop();
  1987. thread.join();
  1988. ASSERT_FALSE(svr.is_running());
  1989. });
  1990. svr.wait_until_ready();
  1991. {
  1992. Client cli(HOST, PORT);
  1993. cli.set_path_encode(false);
  1994. auto res = cli.Get("/foo?a=explicitly+encoded");
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::OK_200, res->status);
  1997. // This expects it back with a space, as the `+` won't have been
  1998. // url-encoded, and server-side the params get decoded turning `+`
  1999. // into spaces.
  2000. EXPECT_EQ("explicitly encoded", res->body);
  2001. }
  2002. }
  2003. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2004. Server svr;
  2005. svr.Get("/", [](const Request &req, Response &) {
  2006. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2007. });
  2008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2009. auto se = detail::scope_exit([&] {
  2010. svr.stop();
  2011. thread.join();
  2012. ASSERT_FALSE(svr.is_running());
  2013. });
  2014. svr.wait_until_ready();
  2015. {
  2016. Client cli(HOST, PORT);
  2017. cli.set_path_encode(false);
  2018. auto res = cli.Get("/?something=%0A");
  2019. ASSERT_TRUE(res);
  2020. EXPECT_EQ(StatusCode::OK_200, res->status);
  2021. }
  2022. }
  2023. TEST(BindServerTest, DISABLED_BindDualStack) {
  2024. Server svr;
  2025. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. thread.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli("127.0.0.1", PORT);
  2037. auto res = cli.Get("/1");
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. EXPECT_EQ("Hello World!", res->body);
  2041. }
  2042. {
  2043. Client cli("::1", PORT);
  2044. auto res = cli.Get("/1");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. EXPECT_EQ("Hello World!", res->body);
  2048. }
  2049. }
  2050. TEST(BindServerTest, BindAndListenSeparately) {
  2051. Server svr;
  2052. int port = svr.bind_to_any_port("0.0.0.0");
  2053. ASSERT_TRUE(svr.is_valid());
  2054. ASSERT_TRUE(port > 0);
  2055. svr.stop();
  2056. }
  2057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2058. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2060. CLIENT_CA_CERT_DIR);
  2061. int port = svr.bind_to_any_port("0.0.0.0");
  2062. ASSERT_TRUE(svr.is_valid());
  2063. ASSERT_TRUE(port > 0);
  2064. svr.stop();
  2065. }
  2066. #endif
  2067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2068. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2069. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2070. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2071. int port = svr.bind_to_any_port("0.0.0.0");
  2072. ASSERT_TRUE(svr.is_valid());
  2073. ASSERT_TRUE(port > 0);
  2074. svr.stop();
  2075. }
  2076. #endif
  2077. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2078. X509 *readCertificate(const std::string &strFileName) {
  2079. std::ifstream inStream(strFileName);
  2080. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2081. std::istreambuf_iterator<char>());
  2082. if (strCertPEM.empty()) return (nullptr);
  2083. BIO *pbCert = BIO_new(BIO_s_mem());
  2084. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2085. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2086. BIO_free(pbCert);
  2087. return (pCert);
  2088. }
  2089. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2090. std::ifstream inStream(strFileName);
  2091. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2092. std::istreambuf_iterator<char>());
  2093. if (strPrivateKeyPEM.empty()) return (nullptr);
  2094. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2095. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2096. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2097. BIO_free(pbPrivKey);
  2098. return (pPrivateKey);
  2099. }
  2100. TEST(BindServerTest, UpdateCerts) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2106. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2107. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2108. ASSERT_TRUE(cert != nullptr);
  2109. ASSERT_TRUE(ca_cert != nullptr);
  2110. ASSERT_TRUE(key != nullptr);
  2111. X509_STORE *cert_store = X509_STORE_new();
  2112. X509_STORE_add_cert(cert_store, ca_cert);
  2113. svr.update_certs(cert, key, cert_store);
  2114. ASSERT_TRUE(svr.is_valid());
  2115. svr.stop();
  2116. X509_free(cert);
  2117. X509_free(ca_cert);
  2118. EVP_PKEY_free(key);
  2119. }
  2120. #endif
  2121. TEST(ErrorHandlerTest, ContentLength) {
  2122. Server svr;
  2123. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2124. res.status = StatusCode::OK_200;
  2125. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2126. "text/html"); // <= Content-Length still 13
  2127. });
  2128. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!\n", "text/plain");
  2130. res.status = 524;
  2131. });
  2132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2133. auto se = detail::scope_exit([&] {
  2134. svr.stop();
  2135. thread.join();
  2136. ASSERT_FALSE(svr.is_running());
  2137. });
  2138. svr.wait_until_ready();
  2139. {
  2140. Client cli(HOST, PORT);
  2141. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ(StatusCode::OK_200, res->status);
  2144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2145. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2147. }
  2148. }
  2149. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2150. TEST(ExceptionTest, WithoutExceptionHandler) {
  2151. Server svr;
  2152. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2153. throw std::runtime_error("exception...");
  2154. });
  2155. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2156. throw std::runtime_error("exception\r\n...");
  2157. });
  2158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2159. auto se = detail::scope_exit([&] {
  2160. svr.stop();
  2161. listen_thread.join();
  2162. ASSERT_FALSE(svr.is_running());
  2163. });
  2164. svr.wait_until_ready();
  2165. Client cli("localhost", PORT);
  2166. {
  2167. auto res = cli.Get("/exception");
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2170. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2171. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2172. }
  2173. {
  2174. auto res = cli.Get("/unknown");
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2177. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2178. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2179. }
  2180. }
  2181. TEST(ExceptionTest, WithExceptionHandler) {
  2182. Server svr;
  2183. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2184. std::exception_ptr ep) {
  2185. EXPECT_FALSE(ep == nullptr);
  2186. try {
  2187. std::rethrow_exception(ep);
  2188. } catch (std::exception &e) {
  2189. EXPECT_EQ("abc", std::string(e.what()));
  2190. } catch (...) {}
  2191. res.status = StatusCode::InternalServerError_500;
  2192. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2193. "text/html"); // <= Content-Length still 13 at this point
  2194. });
  2195. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2196. res.set_content("Hello World!\n", "text/plain");
  2197. throw std::runtime_error("abc");
  2198. });
  2199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2200. auto se = detail::scope_exit([&] {
  2201. svr.stop();
  2202. thread.join();
  2203. ASSERT_FALSE(svr.is_running());
  2204. });
  2205. svr.wait_until_ready();
  2206. for (size_t i = 0; i < 10; i++) {
  2207. Client cli(HOST, PORT);
  2208. for (size_t j = 0; j < 100; j++) {
  2209. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2213. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2214. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2215. }
  2216. cli.set_keep_alive(true);
  2217. for (size_t j = 0; j < 100; j++) {
  2218. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2219. ASSERT_TRUE(res);
  2220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2221. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2222. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2224. }
  2225. }
  2226. }
  2227. TEST(ExceptionTest, AndErrorHandler) {
  2228. Server svr;
  2229. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2230. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2231. });
  2232. svr.set_exception_handler(
  2233. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2234. EXPECT_FALSE(ep == nullptr);
  2235. try {
  2236. std::rethrow_exception(ep);
  2237. } catch (std::exception &e) {
  2238. res.set_content(e.what(), "text/html");
  2239. } catch (...) {}
  2240. res.status = StatusCode::InternalServerError_500;
  2241. });
  2242. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2243. throw std::runtime_error("EXCEPTION");
  2244. });
  2245. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2246. res.set_content("ERROR", "text/html");
  2247. res.status = StatusCode::InternalServerError_500;
  2248. });
  2249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. Client cli(HOST, PORT);
  2257. {
  2258. auto res = cli.Get("/exception");
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2261. EXPECT_EQ("EXCEPTION", res->body);
  2262. }
  2263. {
  2264. auto res = cli.Get("/error");
  2265. ASSERT_TRUE(res);
  2266. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2267. EXPECT_EQ("ERROR", res->body);
  2268. }
  2269. {
  2270. auto res = cli.Get("/invalid");
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2273. EXPECT_EQ("NOT_FOUND", res->body);
  2274. }
  2275. }
  2276. #endif
  2277. TEST(NoContentTest, ContentLength) {
  2278. Server svr;
  2279. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2280. res.status = StatusCode::NoContent_204;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. {
  2290. Client cli(HOST, PORT);
  2291. auto res = cli.Get("/hi");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2294. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2295. }
  2296. }
  2297. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2300. ASSERT_TRUE(svr.is_valid());
  2301. #else
  2302. Server svr;
  2303. #endif
  2304. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2305. if (req.path == "/routing_handler") {
  2306. res.set_header("PRE_ROUTING", "on");
  2307. res.set_content("Routing Handler", "text/plain");
  2308. return httplib::Server::HandlerResponse::Handled;
  2309. }
  2310. return httplib::Server::HandlerResponse::Unhandled;
  2311. });
  2312. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2313. res.set_content("Error", "text/html");
  2314. });
  2315. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2316. if (req.path == "/routing_handler") {
  2317. res.set_header("POST_ROUTING", "on");
  2318. }
  2319. });
  2320. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2321. res.set_content("Hello World!\n", "text/plain");
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2332. SSLClient cli(HOST, PORT);
  2333. cli.enable_server_certificate_verification(false);
  2334. #else
  2335. Client cli(HOST, PORT);
  2336. #endif
  2337. auto res = cli.Get("/routing_handler");
  2338. ASSERT_TRUE(res);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ("Routing Handler", res->body);
  2341. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2342. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2343. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2344. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2345. }
  2346. {
  2347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2348. SSLClient cli(HOST, PORT);
  2349. cli.enable_server_certificate_verification(false);
  2350. #else
  2351. Client cli(HOST, PORT);
  2352. #endif
  2353. auto res = cli.Get("/hi");
  2354. ASSERT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::OK_200, res->status);
  2356. EXPECT_EQ("Hello World!\n", res->body);
  2357. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2358. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2359. }
  2360. {
  2361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2362. SSLClient cli(HOST, PORT);
  2363. cli.enable_server_certificate_verification(false);
  2364. #else
  2365. Client cli(HOST, PORT);
  2366. #endif
  2367. auto res = cli.Get("/aaa");
  2368. ASSERT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2370. EXPECT_EQ("Error", res->body);
  2371. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2372. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2373. }
  2374. }
  2375. TEST(RequestHandlerTest, PreRequestHandler) {
  2376. auto route_path = "/user/:user";
  2377. Server svr;
  2378. svr.Get("/hi", [](const Request &, Response &res) {
  2379. res.set_content("hi", "text/plain");
  2380. });
  2381. svr.Get(route_path, [](const Request &req, Response &res) {
  2382. res.set_content(req.path_params.at("user"), "text/plain");
  2383. });
  2384. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2385. if (req.matched_route == route_path) {
  2386. auto user = req.path_params.at("user");
  2387. if (user != "john") {
  2388. res.status = StatusCode::Forbidden_403;
  2389. res.set_content("error", "text/html");
  2390. return Server::HandlerResponse::Handled;
  2391. }
  2392. }
  2393. return Server::HandlerResponse::Unhandled;
  2394. });
  2395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2396. auto se = detail::scope_exit([&] {
  2397. svr.stop();
  2398. thread.join();
  2399. ASSERT_FALSE(svr.is_running());
  2400. });
  2401. svr.wait_until_ready();
  2402. Client cli(HOST, PORT);
  2403. {
  2404. auto res = cli.Get("/hi");
  2405. ASSERT_TRUE(res);
  2406. EXPECT_EQ(StatusCode::OK_200, res->status);
  2407. EXPECT_EQ("hi", res->body);
  2408. }
  2409. {
  2410. auto res = cli.Get("/user/john");
  2411. ASSERT_TRUE(res);
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. EXPECT_EQ("john", res->body);
  2414. }
  2415. {
  2416. auto res = cli.Get("/user/invalid-user");
  2417. ASSERT_TRUE(res);
  2418. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2419. EXPECT_EQ("error", res->body);
  2420. }
  2421. }
  2422. TEST(InvalidFormatTest, StatusCode) {
  2423. Server svr;
  2424. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2425. res.set_content("Hello World!\n", "text/plain");
  2426. res.status = 9999; // Status should be a three-digit code...
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. {
  2436. Client cli(HOST, PORT);
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_FALSE(res);
  2439. }
  2440. }
  2441. TEST(URLFragmentTest, WithFragment) {
  2442. Server svr;
  2443. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2444. EXPECT_TRUE(req.target == "/hi");
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2456. EXPECT_TRUE(res);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. res = cli.Get("/hi%23key1=val1=key2=val2");
  2459. EXPECT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2461. }
  2462. }
  2463. TEST(HeaderWriter, SetHeaderWriter) {
  2464. Server svr;
  2465. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2466. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2467. return detail::write_headers(strm, hdrs);
  2468. });
  2469. svr.Get("/hi", [](const Request &req, Response &res) {
  2470. auto it = req.headers.find("CustomClientHeader");
  2471. EXPECT_TRUE(it != req.headers.end());
  2472. EXPECT_EQ(it->second, "CustomClientValue");
  2473. res.set_content("Hello World!\n", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. {
  2483. Client cli(HOST, PORT);
  2484. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2485. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2486. return detail::write_headers(strm, hdrs);
  2487. });
  2488. auto res = cli.Get("/hi");
  2489. EXPECT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. auto it = res->headers.find("CustomServerHeader");
  2492. EXPECT_TRUE(it != res->headers.end());
  2493. EXPECT_EQ(it->second, "CustomServerValue");
  2494. }
  2495. }
  2496. class ServerTest : public ::testing::Test {
  2497. protected:
  2498. ServerTest()
  2499. : cli_(HOST, PORT)
  2500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2501. ,
  2502. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2503. #endif
  2504. {
  2505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2506. cli_.enable_server_certificate_verification(false);
  2507. #endif
  2508. }
  2509. virtual void SetUp() {
  2510. svr_.set_mount_point("/", "./www");
  2511. svr_.set_mount_point("/mount", "./www2");
  2512. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2513. svr_.Get("/hi",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_content("Hello World!", "text/plain");
  2516. })
  2517. .Get("/file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/test.html");
  2520. })
  2521. .Get("/file_content_with_content_type",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_file_content("./www/file", "text/plain");
  2524. })
  2525. .Get("/invalid_file_content",
  2526. [&](const Request & /*req*/, Response &res) {
  2527. res.set_file_content("./www/dir/invalid_file_path");
  2528. })
  2529. .Get("/http_response_splitting",
  2530. [&](const Request & /*req*/, Response &res) {
  2531. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2532. EXPECT_EQ(0U, res.headers.size());
  2533. EXPECT_FALSE(res.has_header("a"));
  2534. res.set_header("a", "1\nSet-Cookie: a=1");
  2535. EXPECT_EQ(0U, res.headers.size());
  2536. EXPECT_FALSE(res.has_header("a"));
  2537. res.set_header("a", "1\rSet-Cookie: a=1");
  2538. EXPECT_EQ(0U, res.headers.size());
  2539. EXPECT_FALSE(res.has_header("a"));
  2540. res.set_header("a\r\nb", "0");
  2541. EXPECT_EQ(0U, res.headers.size());
  2542. EXPECT_FALSE(res.has_header("a"));
  2543. res.set_header("a\rb", "0");
  2544. EXPECT_EQ(0U, res.headers.size());
  2545. EXPECT_FALSE(res.has_header("a"));
  2546. res.set_header("a\nb", "0");
  2547. EXPECT_EQ(0U, res.headers.size());
  2548. EXPECT_FALSE(res.has_header("a"));
  2549. res.set_redirect("1\r\nSet-Cookie: a=1");
  2550. EXPECT_EQ(0U, res.headers.size());
  2551. EXPECT_FALSE(res.has_header("Location"));
  2552. })
  2553. .Get("/slow",
  2554. [&](const Request & /*req*/, Response &res) {
  2555. std::this_thread::sleep_for(std::chrono::seconds(2));
  2556. res.set_content("slow", "text/plain");
  2557. })
  2558. #if 0
  2559. .Post("/slowpost",
  2560. [&](const Request & /*req*/, Response &res) {
  2561. std::this_thread::sleep_for(std::chrono::seconds(2));
  2562. res.set_content("slow", "text/plain");
  2563. })
  2564. #endif
  2565. .Get("/remote_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2568. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2571. res.set_content(req.remote_addr, "text/plain");
  2572. })
  2573. .Get("/local_addr",
  2574. [&](const Request &req, Response &res) {
  2575. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2576. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2577. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2578. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2579. auto local_addr = req.local_addr;
  2580. auto local_port = std::to_string(req.local_port);
  2581. res.set_content(local_addr.append(":").append(local_port),
  2582. "text/plain");
  2583. })
  2584. .Get("/endwith%",
  2585. [&](const Request & /*req*/, Response &res) {
  2586. res.set_content("Hello World!", "text/plain");
  2587. })
  2588. .Get("/a\\+\\+b",
  2589. [&](const Request &req, Response &res) {
  2590. ASSERT_TRUE(req.has_param("a +b"));
  2591. auto val = req.get_param_value("a +b");
  2592. res.set_content(val, "text/plain");
  2593. })
  2594. .Get("/", [&](const Request & /*req*/,
  2595. Response &res) { res.set_redirect("/hi"); })
  2596. .Post("/1",
  2597. [](const Request & /*req*/, Response &res) {
  2598. res.set_redirect("/2", StatusCode::SeeOther_303);
  2599. })
  2600. .Get("/2",
  2601. [](const Request & /*req*/, Response &res) {
  2602. res.set_content("redirected.", "text/plain");
  2603. res.status = StatusCode::OK_200;
  2604. })
  2605. .Post("/person",
  2606. [&](const Request &req, Response &res) {
  2607. if (req.has_param("name") && req.has_param("note")) {
  2608. persons_[req.get_param_value("name")] =
  2609. req.get_param_value("note");
  2610. } else {
  2611. res.status = StatusCode::BadRequest_400;
  2612. }
  2613. })
  2614. .Put("/person",
  2615. [&](const Request &req, Response &res) {
  2616. if (req.has_param("name") && req.has_param("note")) {
  2617. persons_[req.get_param_value("name")] =
  2618. req.get_param_value("note");
  2619. } else {
  2620. res.status = StatusCode::BadRequest_400;
  2621. }
  2622. })
  2623. .Get("/person/(.*)",
  2624. [&](const Request &req, Response &res) {
  2625. string name = req.matches[1];
  2626. if (persons_.find(name) != persons_.end()) {
  2627. auto note = persons_[name];
  2628. res.set_content(note, "text/plain");
  2629. } else {
  2630. res.status = StatusCode::NotFound_404;
  2631. }
  2632. })
  2633. .Delete("/person",
  2634. [&](const Request &req, Response &res) {
  2635. if (req.has_param("name")) {
  2636. string name = req.get_param_value("name");
  2637. if (persons_.find(name) != persons_.end()) {
  2638. persons_.erase(name);
  2639. res.set_content("DELETED", "text/plain");
  2640. } else {
  2641. res.status = StatusCode::NotFound_404;
  2642. }
  2643. } else {
  2644. res.status = StatusCode::BadRequest_400;
  2645. }
  2646. })
  2647. .Post("/x-www-form-urlencoded-json",
  2648. [&](const Request &req, Response &res) {
  2649. auto json = req.get_param_value("json");
  2650. ASSERT_EQ(JSON_DATA, json);
  2651. res.set_content(json, "appliation/json");
  2652. res.status = StatusCode::OK_200;
  2653. })
  2654. .Get("/streamed-chunked",
  2655. [&](const Request & /*req*/, Response &res) {
  2656. res.set_chunked_content_provider(
  2657. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2658. sink.os << "123";
  2659. sink.os << "456";
  2660. sink.os << "789";
  2661. sink.done();
  2662. return true;
  2663. });
  2664. })
  2665. .Get("/streamed-chunked-with-prohibited-trailer",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. auto i = new int(0);
  2668. // Declare both a prohibited trailer (Content-Length) and an
  2669. // allowed one
  2670. res.set_header("Trailer", "Content-Length, X-Allowed");
  2671. res.set_chunked_content_provider(
  2672. "text/plain",
  2673. [i](size_t /*offset*/, DataSink &sink) {
  2674. switch (*i) {
  2675. case 0: sink.os << "123"; break;
  2676. case 1: sink.os << "456"; break;
  2677. case 2: sink.os << "789"; break;
  2678. case 3: {
  2679. sink.done_with_trailer(
  2680. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2681. } break;
  2682. }
  2683. (*i)++;
  2684. return true;
  2685. },
  2686. [i](bool success) {
  2687. EXPECT_TRUE(success);
  2688. delete i;
  2689. });
  2690. })
  2691. .Get("/streamed-chunked2",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. auto i = new int(0);
  2694. res.set_chunked_content_provider(
  2695. "text/plain",
  2696. [i](size_t /*offset*/, DataSink &sink) {
  2697. switch (*i) {
  2698. case 0: sink.os << "123"; break;
  2699. case 1: sink.os << "456"; break;
  2700. case 2: sink.os << "789"; break;
  2701. case 3: sink.done(); break;
  2702. }
  2703. (*i)++;
  2704. return true;
  2705. },
  2706. [i](bool success) {
  2707. EXPECT_TRUE(success);
  2708. delete i;
  2709. });
  2710. })
  2711. .Get("/streamed-chunked-with-trailer",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. auto i = new int(0);
  2714. res.set_header("Trailer", "Dummy1, Dummy2");
  2715. res.set_chunked_content_provider(
  2716. "text/plain",
  2717. [i](size_t /*offset*/, DataSink &sink) {
  2718. switch (*i) {
  2719. case 0: sink.os << "123"; break;
  2720. case 1: sink.os << "456"; break;
  2721. case 2: sink.os << "789"; break;
  2722. case 3: {
  2723. sink.done_with_trailer(
  2724. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2725. } break;
  2726. }
  2727. (*i)++;
  2728. return true;
  2729. },
  2730. [i](bool success) {
  2731. EXPECT_TRUE(success);
  2732. delete i;
  2733. });
  2734. })
  2735. .Get("/streamed",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_content_provider(
  2738. 6, "text/plain",
  2739. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2740. sink.os << (offset < 3 ? "a" : "b");
  2741. return true;
  2742. });
  2743. })
  2744. .Get("/streamed-with-range",
  2745. [&](const Request &req, Response &res) {
  2746. auto data = new std::string("abcdefg");
  2747. res.set_content_provider(
  2748. data->size(), "text/plain",
  2749. [data](size_t offset, size_t length, DataSink &sink) {
  2750. size_t DATA_CHUNK_SIZE = 4;
  2751. const auto &d = *data;
  2752. auto out_len =
  2753. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2754. auto ret =
  2755. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2756. EXPECT_TRUE(ret);
  2757. return true;
  2758. },
  2759. [data, &req](bool success) {
  2760. EXPECT_EQ(success, !req.has_param("error"));
  2761. delete data;
  2762. });
  2763. })
  2764. .Get("/streamed-cancel",
  2765. [&](const Request & /*req*/, Response &res) {
  2766. res.set_content_provider(
  2767. size_t(-1), "text/plain",
  2768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2769. sink.os << "data_chunk";
  2770. return true;
  2771. });
  2772. })
  2773. .Get("/regex-with-delimiter",
  2774. [&](const Request &req, Response & /*res*/) {
  2775. ASSERT_TRUE(req.has_param("key"));
  2776. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2777. })
  2778. .Get("/with-range",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("abcdefg", "text/plain");
  2781. })
  2782. .Get("/test-start-time",
  2783. [&](const Request &req, Response & /*res*/) {
  2784. EXPECT_NE(req.start_time_,
  2785. std::chrono::steady_clock::time_point::min());
  2786. })
  2787. .Get("/with-range-customized-response",
  2788. [&](const Request & /*req*/, Response &res) {
  2789. res.status = StatusCode::BadRequest_400;
  2790. res.set_content(JSON_DATA, "application/json");
  2791. })
  2792. .Post("/chunked",
  2793. [&](const Request &req, Response & /*res*/) {
  2794. EXPECT_EQ(req.body, "dechunked post body");
  2795. })
  2796. .Post("/large-chunked",
  2797. [&](const Request &req, Response & /*res*/) {
  2798. std::string expected(6 * 30 * 1024u, 'a');
  2799. EXPECT_EQ(req.body, expected);
  2800. })
  2801. .Post("/multipart",
  2802. [&](const Request &req, Response & /*res*/) {
  2803. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2804. req.form.get_field_count("text2") +
  2805. req.form.get_field_count("file3") +
  2806. req.form.get_field_count("file4"));
  2807. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2808. req.form.get_file_count("file2"));
  2809. ASSERT_TRUE(!req.form.has_file("???"));
  2810. ASSERT_TRUE(!req.form.has_field("???"));
  2811. ASSERT_TRUE(req.body.empty());
  2812. {
  2813. const auto &text = req.form.get_field("text1");
  2814. EXPECT_EQ("text default", text);
  2815. }
  2816. {
  2817. const auto &text = req.form.get_field("text2");
  2818. EXPECT_EQ("aωb", text);
  2819. }
  2820. {
  2821. const auto &file = req.form.get_file("file1");
  2822. EXPECT_EQ("hello.txt", file.filename);
  2823. EXPECT_EQ("text/plain", file.content_type);
  2824. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2825. }
  2826. {
  2827. const auto &file = req.form.get_file("file2");
  2828. EXPECT_EQ("world.json", file.filename);
  2829. EXPECT_EQ("application/json", file.content_type);
  2830. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2831. }
  2832. {
  2833. const auto &text = req.form.get_field("file3");
  2834. EXPECT_EQ(0u, text.size());
  2835. }
  2836. {
  2837. const auto &text = req.form.get_field("file4");
  2838. EXPECT_EQ(0u, text.size());
  2839. }
  2840. })
  2841. .Post("/multipart/multi_file_values",
  2842. [&](const Request &req, Response & /*res*/) {
  2843. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2844. req.form.get_field_count("multi_text1"));
  2845. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2846. ASSERT_TRUE(!req.form.has_file("???"));
  2847. ASSERT_TRUE(!req.form.has_field("???"));
  2848. ASSERT_TRUE(req.body.empty());
  2849. {
  2850. const auto &text = req.form.get_field("text");
  2851. EXPECT_EQ("default text", text);
  2852. }
  2853. {
  2854. const auto &text1_values = req.form.get_fields("multi_text1");
  2855. EXPECT_EQ(2u, text1_values.size());
  2856. EXPECT_EQ("aaaaa", text1_values[0]);
  2857. EXPECT_EQ("bbbbb", text1_values[1]);
  2858. }
  2859. {
  2860. const auto &file1_values = req.form.get_files("multi_file1");
  2861. EXPECT_EQ(2u, file1_values.size());
  2862. auto file1 = file1_values[0];
  2863. EXPECT_EQ(file1.filename, "hello.txt");
  2864. EXPECT_EQ(file1.content_type, "text/plain");
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2866. auto file2 = file1_values[1];
  2867. EXPECT_EQ(file2.filename, "world.json");
  2868. EXPECT_EQ(file2.content_type, "application/json");
  2869. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2870. }
  2871. })
  2872. .Post("/empty",
  2873. [&](const Request &req, Response &res) {
  2874. EXPECT_EQ(req.body, "");
  2875. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2877. res.set_content("empty", "text/plain");
  2878. })
  2879. .Post("/empty-no-content-type",
  2880. [&](const Request &req, Response &res) {
  2881. EXPECT_EQ(req.body, "");
  2882. EXPECT_FALSE(req.has_header("Content-Type"));
  2883. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2884. res.set_content("empty-no-content-type", "text/plain");
  2885. })
  2886. .Post("/path-only",
  2887. [&](const Request &req, Response &res) {
  2888. EXPECT_EQ(req.body, "");
  2889. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2890. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2891. res.set_content("path-only", "text/plain");
  2892. })
  2893. .Post("/path-headers-only",
  2894. [&](const Request &req, Response &res) {
  2895. EXPECT_EQ(req.body, "");
  2896. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2897. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2898. EXPECT_EQ("world", req.get_header_value("hello"));
  2899. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2900. res.set_content("path-headers-only", "text/plain");
  2901. })
  2902. .Post("/post-large",
  2903. [&](const Request &req, Response &res) {
  2904. EXPECT_EQ(req.body, LARGE_DATA);
  2905. res.set_content(req.body, "text/plain");
  2906. })
  2907. .Post("/post-loopback",
  2908. [&](const Request &, Response &res,
  2909. ContentReader const &content_reader) {
  2910. std::string body;
  2911. content_reader([&](const char *data, size_t data_length) {
  2912. body.append(data, data_length);
  2913. return true;
  2914. });
  2915. res.set_content(body, "text/plain");
  2916. })
  2917. .Put("/put-loopback",
  2918. [&](const Request &, Response &res,
  2919. ContentReader const &content_reader) {
  2920. std::string body;
  2921. content_reader([&](const char *data, size_t data_length) {
  2922. body.append(data, data_length);
  2923. return true;
  2924. });
  2925. res.set_content(body, "text/plain");
  2926. })
  2927. .Patch("/patch-loopback",
  2928. [&](const Request &, Response &res,
  2929. ContentReader const &content_reader) {
  2930. std::string body;
  2931. content_reader([&](const char *data, size_t data_length) {
  2932. body.append(data, data_length);
  2933. return true;
  2934. });
  2935. res.set_content(body, "text/plain");
  2936. })
  2937. .Put("/empty-no-content-type",
  2938. [&](const Request &req, Response &res) {
  2939. EXPECT_EQ(req.body, "");
  2940. EXPECT_FALSE(req.has_header("Content-Type"));
  2941. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2942. res.set_content("empty-no-content-type", "text/plain");
  2943. })
  2944. .Put("/put",
  2945. [&](const Request &req, Response &res) {
  2946. EXPECT_EQ(req.body, "PUT");
  2947. res.set_content(req.body, "text/plain");
  2948. })
  2949. .Put("/put-large",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(req.body, LARGE_DATA);
  2952. res.set_content(req.body, "text/plain");
  2953. })
  2954. .Patch("/patch",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "PATCH");
  2957. res.set_content(req.body, "text/plain");
  2958. })
  2959. .Delete("/delete",
  2960. [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("DELETE", "text/plain");
  2962. })
  2963. .Delete("/delete-body",
  2964. [&](const Request &req, Response &res) {
  2965. EXPECT_EQ(req.body, "content");
  2966. res.set_content(req.body, "text/plain");
  2967. })
  2968. .Options(R"(\*)",
  2969. [&](const Request & /*req*/, Response &res) {
  2970. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2971. })
  2972. .Get("/request-target",
  2973. [&](const Request &req, Response & /*res*/) {
  2974. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2975. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2976. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2977. })
  2978. .Get("/long-query-value",
  2979. [&](const Request &req, Response & /*res*/) {
  2980. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2981. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2982. })
  2983. .Get("/too-long-query-value",
  2984. [&](const Request &req, Response & /*res*/) {
  2985. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2986. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2987. })
  2988. .Get("/array-param",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2991. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2992. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2993. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2994. })
  2995. .Post("/validate-no-multiple-headers",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2998. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2999. })
  3000. .Post("/content_receiver",
  3001. [&](const Request &req, Response &res,
  3002. const ContentReader &content_reader) {
  3003. if (req.is_multipart_form_data()) {
  3004. std::vector<FormData> items;
  3005. content_reader(
  3006. [&](const FormData &file) {
  3007. items.push_back(file);
  3008. return true;
  3009. },
  3010. [&](const char *data, size_t data_length) {
  3011. items.back().content.append(data, data_length);
  3012. return true;
  3013. });
  3014. EXPECT_EQ(5u, items.size());
  3015. {
  3016. const auto &file = get_file_value(items, "text1");
  3017. EXPECT_TRUE(file.filename.empty());
  3018. EXPECT_EQ("text default", file.content);
  3019. }
  3020. {
  3021. const auto &file = get_file_value(items, "text2");
  3022. EXPECT_TRUE(file.filename.empty());
  3023. EXPECT_EQ("aωb", file.content);
  3024. }
  3025. {
  3026. const auto &file = get_file_value(items, "file1");
  3027. EXPECT_EQ("hello.txt", file.filename);
  3028. EXPECT_EQ("text/plain", file.content_type);
  3029. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3030. }
  3031. {
  3032. const auto &file = get_file_value(items, "file2");
  3033. EXPECT_EQ("world.json", file.filename);
  3034. EXPECT_EQ("application/json", file.content_type);
  3035. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3036. }
  3037. {
  3038. const auto &file = get_file_value(items, "file3");
  3039. EXPECT_TRUE(file.filename.empty());
  3040. EXPECT_EQ("application/octet-stream", file.content_type);
  3041. EXPECT_EQ(0u, file.content.size());
  3042. }
  3043. } else {
  3044. std::string body;
  3045. content_reader([&](const char *data, size_t data_length) {
  3046. EXPECT_EQ(7U, data_length);
  3047. body.append(data, data_length);
  3048. return true;
  3049. });
  3050. EXPECT_EQ(body, "content");
  3051. res.set_content(body, "text/plain");
  3052. }
  3053. })
  3054. .Put("/content_receiver",
  3055. [&](const Request & /*req*/, Response &res,
  3056. const ContentReader &content_reader) {
  3057. std::string body;
  3058. content_reader([&](const char *data, size_t data_length) {
  3059. body.append(data, data_length);
  3060. return true;
  3061. });
  3062. EXPECT_EQ(body, "content");
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Patch("/content_receiver",
  3066. [&](const Request & /*req*/, Response &res,
  3067. const ContentReader &content_reader) {
  3068. std::string body;
  3069. content_reader([&](const char *data, size_t data_length) {
  3070. body.append(data, data_length);
  3071. return true;
  3072. });
  3073. EXPECT_EQ(body, "content");
  3074. res.set_content(body, "text/plain");
  3075. })
  3076. .Post("/query-string-and-body",
  3077. [&](const Request &req, Response & /*res*/) {
  3078. ASSERT_TRUE(req.has_param("key"));
  3079. EXPECT_EQ(req.get_param_value("key"), "value");
  3080. EXPECT_EQ(req.body, "content");
  3081. })
  3082. .Get("/last-request",
  3083. [&](const Request &req, Response & /*res*/) {
  3084. EXPECT_EQ("close", req.get_header_value("Connection"));
  3085. })
  3086. .Get(R"(/redirect/(\d+))",
  3087. [&](const Request &req, Response &res) {
  3088. auto num = std::stoi(req.matches[1]) + 1;
  3089. std::string url = "/redirect/" + std::to_string(num);
  3090. res.set_redirect(url);
  3091. })
  3092. .Post("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Put("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Patch("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Delete("/binary",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(4U, req.body.size());
  3119. EXPECT_EQ("application/octet-stream",
  3120. req.get_header_value("Content-Type"));
  3121. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3122. res.set_content(req.body, "application/octet-stream");
  3123. })
  3124. .Get("/issue1772",
  3125. [&](const Request & /*req*/, Response &res) {
  3126. res.status = 401;
  3127. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3128. })
  3129. .Delete("/issue609",
  3130. [](const httplib::Request &, httplib::Response &res,
  3131. const httplib::ContentReader &) {
  3132. res.set_content("ok", "text/plain");
  3133. })
  3134. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3135. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3136. .Get("/compress",
  3137. [&](const Request & /*req*/, Response &res) {
  3138. res.set_content(
  3139. "12345678901234567890123456789012345678901234567890123456789"
  3140. "01234567890123456789012345678901234567890",
  3141. "text/plain");
  3142. })
  3143. .Get("/nocompress",
  3144. [&](const Request & /*req*/, Response &res) {
  3145. res.set_content(
  3146. "12345678901234567890123456789012345678901234567890123456789"
  3147. "01234567890123456789012345678901234567890",
  3148. "application/octet-stream");
  3149. })
  3150. .Post("/compress-multipart",
  3151. [&](const Request &req, Response & /*res*/) {
  3152. EXPECT_EQ(2u, req.form.fields.size());
  3153. ASSERT_TRUE(!req.form.has_field("???"));
  3154. {
  3155. const auto &text = req.form.get_field("key1");
  3156. EXPECT_EQ("test", text);
  3157. }
  3158. {
  3159. const auto &text = req.form.get_field("key2");
  3160. EXPECT_EQ("--abcdefg123", text);
  3161. }
  3162. })
  3163. #endif
  3164. ;
  3165. persons_["john"] = "programmer";
  3166. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3167. svr_.wait_until_ready();
  3168. }
  3169. virtual void TearDown() {
  3170. svr_.stop();
  3171. if (!request_threads_.empty()) {
  3172. std::this_thread::sleep_for(std::chrono::seconds(1));
  3173. for (auto &t : request_threads_) {
  3174. t.join();
  3175. }
  3176. }
  3177. t_.join();
  3178. }
  3179. map<string, string> persons_;
  3180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3181. SSLClient cli_;
  3182. SSLServer svr_;
  3183. #else
  3184. Client cli_;
  3185. Server svr_;
  3186. #endif
  3187. thread t_;
  3188. std::vector<thread> request_threads_;
  3189. };
  3190. TEST_F(ServerTest, GetMethod200) {
  3191. auto res = cli_.Get("/hi");
  3192. ASSERT_TRUE(res);
  3193. EXPECT_EQ("HTTP/1.1", res->version);
  3194. EXPECT_EQ(StatusCode::OK_200, res->status);
  3195. EXPECT_EQ("OK", res->reason);
  3196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3198. EXPECT_EQ("Hello World!", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetEmptyFile) {
  3201. auto res = cli_.Get("/empty_file");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContent) {
  3209. auto res = cli_.Get("/file_content");
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3214. EXPECT_EQ("test.html", res->body);
  3215. }
  3216. TEST_F(ServerTest, GetFileContentWithRange) {
  3217. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3222. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("est", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetFileContentWithContentType) {
  3226. auto res = cli_.Get("/file_content_with_content_type");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3231. EXPECT_EQ("file\n", res->body);
  3232. }
  3233. TEST_F(ServerTest, GetInvalidFileContent) {
  3234. auto res = cli_.Get("/invalid_file_content");
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3237. }
  3238. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3239. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3240. ASSERT_TRUE(res);
  3241. EXPECT_EQ("HTTP/1.1", res->version);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3245. EXPECT_EQ("Hello World!", res->body);
  3246. }
  3247. TEST_F(ServerTest, GetMethod302) {
  3248. auto res = cli_.Get("/");
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::Found_302, res->status);
  3251. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3252. }
  3253. TEST_F(ServerTest, GetMethod302Redirect) {
  3254. cli_.set_follow_location(true);
  3255. auto res = cli_.Get("/");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::OK_200, res->status);
  3258. EXPECT_EQ("Hello World!", res->body);
  3259. EXPECT_EQ("/hi", res->location);
  3260. }
  3261. TEST_F(ServerTest, GetMethod404) {
  3262. auto res = cli_.Get("/invalid");
  3263. ASSERT_TRUE(res);
  3264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3265. }
  3266. TEST_F(ServerTest, HeadMethod200) {
  3267. auto res = cli_.Head("/hi");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod200Static) {
  3274. auto res = cli_.Head("/mount/dir/index.html");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3278. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3279. EXPECT_TRUE(res->body.empty());
  3280. }
  3281. TEST_F(ServerTest, HeadMethod404) {
  3282. auto res = cli_.Head("/invalid");
  3283. ASSERT_TRUE(res);
  3284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3285. EXPECT_TRUE(res->body.empty());
  3286. }
  3287. TEST_F(ServerTest, GetMethodPersonJohn) {
  3288. auto res = cli_.Get("/person/john");
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. EXPECT_EQ("programmer", res->body);
  3293. }
  3294. TEST_F(ServerTest, PostMethod1) {
  3295. auto res = cli_.Get("/person/john1");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3298. res = cli_.Post("/person", "name=john1&note=coder",
  3299. "application/x-www-form-urlencoded");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::OK_200, res->status);
  3302. res = cli_.Get("/person/john1");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::OK_200, res->status);
  3305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3306. ASSERT_EQ("coder", res->body);
  3307. }
  3308. TEST_F(ServerTest, PostMethod2) {
  3309. auto res = cli_.Get("/person/john2");
  3310. ASSERT_TRUE(res);
  3311. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3312. Params params;
  3313. params.emplace("name", "john2");
  3314. params.emplace("note", "coder");
  3315. res = cli_.Post("/person", params);
  3316. ASSERT_TRUE(res);
  3317. ASSERT_EQ(StatusCode::OK_200, res->status);
  3318. res = cli_.Get("/person/john2");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3322. ASSERT_EQ("coder", res->body);
  3323. }
  3324. TEST_F(ServerTest, PutMethod3) {
  3325. auto res = cli_.Get("/person/john3");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3328. Params params;
  3329. params.emplace("name", "john3");
  3330. params.emplace("note", "coder");
  3331. res = cli_.Put("/person", params);
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. res = cli_.Get("/person/john3");
  3335. ASSERT_TRUE(res);
  3336. ASSERT_EQ(StatusCode::OK_200, res->status);
  3337. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3338. ASSERT_EQ("coder", res->body);
  3339. }
  3340. TEST_F(ServerTest, DeleteMethod1) {
  3341. auto res = cli_.Get("/person/john4");
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3344. Params params;
  3345. params.emplace("name", "john4");
  3346. params.emplace("note", "coder");
  3347. res = cli_.Post("/person", params);
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. res = cli_.Get("/person/john4");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3354. ASSERT_EQ("coder", res->body);
  3355. Params delete_params;
  3356. delete_params.emplace("name", "john4");
  3357. res = cli_.Delete("/person", delete_params);
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::OK_200, res->status);
  3360. ASSERT_EQ("DELETED", res->body);
  3361. res = cli_.Get("/person/john4");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3364. }
  3365. TEST_F(ServerTest, DeleteMethod2) {
  3366. auto res = cli_.Get("/person/john5");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3369. Params params;
  3370. params.emplace("name", "john5");
  3371. params.emplace("note", "developer");
  3372. res = cli_.Post("/person", params);
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. res = cli_.Get("/person/john5");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. ASSERT_EQ("developer", res->body);
  3380. Params delete_params;
  3381. delete_params.emplace("name", "john5");
  3382. Headers headers;
  3383. headers.emplace("Custom-Header", "test-value");
  3384. res = cli_.Delete("/person", headers, delete_params);
  3385. ASSERT_TRUE(res);
  3386. ASSERT_EQ(StatusCode::OK_200, res->status);
  3387. ASSERT_EQ("DELETED", res->body);
  3388. res = cli_.Get("/person/john5");
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3391. }
  3392. TEST_F(ServerTest, DeleteMethod3) {
  3393. auto res = cli_.Get("/person/john6");
  3394. ASSERT_TRUE(res);
  3395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3396. Params params;
  3397. params.emplace("name", "john6");
  3398. params.emplace("note", "tester");
  3399. res = cli_.Post("/person", params);
  3400. ASSERT_TRUE(res);
  3401. ASSERT_EQ(StatusCode::OK_200, res->status);
  3402. res = cli_.Get("/person/john6");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::OK_200, res->status);
  3405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. ASSERT_EQ("tester", res->body);
  3407. Params delete_params;
  3408. delete_params.emplace("name", "john6");
  3409. Headers headers;
  3410. headers.emplace("Custom-Header", "test-value");
  3411. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("DELETED", res->body);
  3415. res = cli_.Get("/person/john6");
  3416. ASSERT_TRUE(res);
  3417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3418. }
  3419. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3420. Params params;
  3421. params.emplace("json", JSON_DATA);
  3422. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3423. ASSERT_TRUE(res);
  3424. ASSERT_EQ(StatusCode::OK_200, res->status);
  3425. ASSERT_EQ(JSON_DATA, res->body);
  3426. }
  3427. TEST_F(ServerTest, PostEmptyContent) {
  3428. auto res = cli_.Post("/empty", "", "text/plain");
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. ASSERT_EQ("empty", res->body);
  3432. }
  3433. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3434. auto res = cli_.Post("/empty-no-content-type");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::OK_200, res->status);
  3437. ASSERT_EQ("empty-no-content-type", res->body);
  3438. }
  3439. TEST_F(ServerTest, PostPathOnly) {
  3440. auto res = cli_.Post("/path-only");
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. ASSERT_EQ("path-only", res->body);
  3444. }
  3445. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3446. auto res = cli_.Post("/path-headers-only",
  3447. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3448. ASSERT_TRUE(res);
  3449. ASSERT_EQ(StatusCode::OK_200, res->status);
  3450. ASSERT_EQ("path-headers-only", res->body);
  3451. }
  3452. TEST_F(ServerTest, PostLarge) {
  3453. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. EXPECT_EQ(LARGE_DATA, res->body);
  3457. }
  3458. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3459. auto res = cli_.Put("/empty-no-content-type");
  3460. ASSERT_TRUE(res);
  3461. ASSERT_EQ(StatusCode::OK_200, res->status);
  3462. ASSERT_EQ("empty-no-content-type", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetMethodDir) {
  3465. auto res = cli_.Get("/dir/");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3469. auto body = R"(<html>
  3470. <head>
  3471. </head>
  3472. <body>
  3473. <a href="/dir/test.html">Test</a>
  3474. <a href="/hi">hi</a>
  3475. </body>
  3476. </html>
  3477. )";
  3478. EXPECT_EQ(body, res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirTest) {
  3481. auto res = cli_.Get("/dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3488. auto res = cli_.Get("/dir/../dir/test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ("test.html", res->body);
  3493. }
  3494. TEST_F(ServerTest, GetMethodInvalidPath) {
  3495. auto res = cli_.Get("/dir/../test.html");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3498. }
  3499. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3500. auto res = cli_.Get("/../www/dir/test.html");
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3503. }
  3504. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3505. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3508. }
  3509. TEST_F(ServerTest, GetMethodDirMountTest) {
  3510. auto res = cli_.Get("/mount/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("test.html", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3517. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("test.html", res->body);
  3522. }
  3523. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3524. auto res = cli_.Get("/mount/dir/../test.html");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3527. }
  3528. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3529. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3532. }
  3533. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3534. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3539. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3542. }
  3543. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3544. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3545. ASSERT_TRUE(res);
  3546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3547. }
  3548. TEST_F(ServerTest, PostMethod303) {
  3549. auto res = cli_.Post("/1", "body", "text/plain");
  3550. ASSERT_TRUE(res);
  3551. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3552. EXPECT_EQ("/2", res->get_header_value("Location"));
  3553. }
  3554. TEST_F(ServerTest, PostMethod303Redirect) {
  3555. cli_.set_follow_location(true);
  3556. auto res = cli_.Post("/1", "body", "text/plain");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. EXPECT_EQ("redirected.", res->body);
  3560. EXPECT_EQ("/2", res->location);
  3561. }
  3562. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3563. auto res = cli_.Get("/dir/test.abcde");
  3564. ASSERT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::OK_200, res->status);
  3566. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3567. EXPECT_EQ("abcde", res->body);
  3568. }
  3569. TEST_F(ServerTest, StaticFileRange) {
  3570. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3573. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3574. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3575. EXPECT_EQ(true, res->has_header("Content-Range"));
  3576. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3577. EXPECT_EQ(std::string("cd"), res->body);
  3578. }
  3579. TEST_F(ServerTest, StaticFileRanges) {
  3580. auto res =
  3581. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3584. EXPECT_TRUE(
  3585. res->get_header_value("Content-Type")
  3586. .find(
  3587. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3588. 0);
  3589. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3590. }
  3591. TEST_F(ServerTest, StaticFileRangeHead) {
  3592. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3595. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3596. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3597. EXPECT_EQ(true, res->has_header("Content-Range"));
  3598. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3599. }
  3600. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3601. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3605. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3606. EXPECT_EQ(true, res->has_header("Content-Range"));
  3607. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3608. res->get_header_value("Content-Range"));
  3609. EXPECT_EQ("LAST\n", res->body);
  3610. }
  3611. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3612. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3615. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3616. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3617. EXPECT_EQ(true, res->has_header("Content-Range"));
  3618. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3619. }
  3620. TEST_F(ServerTest, StaticFileBigFile) {
  3621. auto res = cli_.Get("/dir/1MB.txt");
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::OK_200, res->status);
  3624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3625. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3626. }
  3627. TEST_F(ServerTest, InvalidBaseDirMount) {
  3628. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3629. }
  3630. TEST_F(ServerTest, Binary) {
  3631. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3632. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3633. "application/octet-stream");
  3634. ASSERT_TRUE(res);
  3635. ASSERT_EQ(StatusCode::OK_200, res->status);
  3636. ASSERT_EQ(4U, res->body.size());
  3637. res = cli_.Put("/binary", binary.data(), binary.size(),
  3638. "application/octet-stream");
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_EQ(4U, res->body.size());
  3642. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3643. "application/octet-stream");
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(4U, res->body.size());
  3647. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3648. "application/octet-stream");
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ(4U, res->body.size());
  3652. }
  3653. TEST_F(ServerTest, BinaryString) {
  3654. auto binary = std::string("\x00\x01\x02\x03", 4);
  3655. auto res = cli_.Post("/binary", binary, "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_.Put("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::OK_200, res->status);
  3666. ASSERT_EQ(4U, res->body.size());
  3667. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ(4U, res->body.size());
  3671. }
  3672. TEST_F(ServerTest, EmptyRequest) {
  3673. auto res = cli_.Get("");
  3674. ASSERT_TRUE(!res);
  3675. EXPECT_EQ(Error::Connection, res.error());
  3676. }
  3677. TEST_F(ServerTest, LongRequest) {
  3678. std::string request;
  3679. for (size_t i = 0; i < 545; i++) {
  3680. request += "/TooLongRequest";
  3681. }
  3682. request += "OK";
  3683. auto res = cli_.Get(request.c_str());
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3686. }
  3687. TEST_F(ServerTest, TooLongRequest) {
  3688. std::string request;
  3689. for (size_t i = 0; i < 546; i++) {
  3690. request += "/TooLongRequest";
  3691. }
  3692. request += "_NG";
  3693. auto start = std::chrono::high_resolution_clock::now();
  3694. cli_.set_keep_alive(true);
  3695. auto res = cli_.Get(request.c_str());
  3696. auto end = std::chrono::high_resolution_clock::now();
  3697. auto elapsed =
  3698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3699. .count();
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3702. EXPECT_LE(elapsed, 100);
  3703. EXPECT_EQ("close", res->get_header_value("Connection"));
  3704. EXPECT_FALSE(cli_.is_socket_open());
  3705. }
  3706. TEST_F(ServerTest, AlmostTooLongRequest) {
  3707. // test for #2046 - URI length check shouldn't include other content on req
  3708. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3709. // leading /, space, HTTP/1.1)
  3710. std::string request =
  3711. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3712. auto res = cli_.Get(request.c_str());
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3715. }
  3716. TEST_F(ServerTest, LongHeader) {
  3717. Request req;
  3718. req.method = "GET";
  3719. req.path = "/hi";
  3720. std::string host_and_port;
  3721. host_and_port += HOST;
  3722. host_and_port += ":";
  3723. host_and_port += std::to_string(PORT);
  3724. req.headers.emplace("Host", host_and_port.c_str());
  3725. req.headers.emplace("Accept", "*/*");
  3726. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3727. req.headers.emplace(
  3728. "Header-Name",
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@");
  3758. auto res = std::make_shared<Response>();
  3759. auto error = Error::Success;
  3760. auto ret = cli_.send(req, *res, error);
  3761. ASSERT_TRUE(ret);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. }
  3764. TEST_F(ServerTest, LongQueryValue) {
  3765. auto start = std::chrono::high_resolution_clock::now();
  3766. cli_.set_keep_alive(true);
  3767. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3768. auto end = std::chrono::high_resolution_clock::now();
  3769. auto elapsed =
  3770. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3771. .count();
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3774. EXPECT_LE(elapsed, 100);
  3775. EXPECT_EQ("close", res->get_header_value("Connection"));
  3776. EXPECT_FALSE(cli_.is_socket_open());
  3777. }
  3778. TEST_F(ServerTest, TooLongQueryValue) {
  3779. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3780. ASSERT_FALSE(res);
  3781. EXPECT_EQ(Error::Read, res.error());
  3782. }
  3783. TEST_F(ServerTest, TooLongHeader) {
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/hi";
  3787. std::string host_and_port;
  3788. host_and_port += HOST;
  3789. host_and_port += ":";
  3790. host_and_port += std::to_string(PORT);
  3791. req.headers.emplace("Host", host_and_port.c_str());
  3792. req.headers.emplace("Accept", "*/*");
  3793. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3794. req.headers.emplace(
  3795. "Header-Name",
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@");
  3825. auto res = std::make_shared<Response>();
  3826. auto error = Error::Success;
  3827. auto ret = cli_.send(req, *res, error);
  3828. ASSERT_TRUE(ret);
  3829. EXPECT_EQ(StatusCode::OK_200, res->status);
  3830. }
  3831. TEST_F(ServerTest, HeaderCountAtLimit) {
  3832. // Test with headers just under the 100 limit
  3833. httplib::Headers headers;
  3834. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3835. // This should keep us just under the 100 header limit
  3836. for (int i = 0; i < 95; i++) {
  3837. std::string name = "X-Test-Header-" + std::to_string(i);
  3838. std::string value = "value" + std::to_string(i);
  3839. headers.emplace(name, value);
  3840. }
  3841. // This should work fine as we're under the limit
  3842. auto res = cli_.Get("/hi", headers);
  3843. EXPECT_TRUE(res);
  3844. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3845. }
  3846. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3847. // Test with many headers to exceed the 100 limit
  3848. httplib::Headers headers;
  3849. // Add 150 headers to definitely exceed the 100 limit
  3850. for (int i = 0; i < 150; i++) {
  3851. std::string name = "X-Test-Header-" + std::to_string(i);
  3852. std::string value = "value" + std::to_string(i);
  3853. headers.emplace(name, value);
  3854. }
  3855. // This should fail due to exceeding header count limit
  3856. cli_.set_keep_alive(true);
  3857. auto res = cli_.Get("/hi", headers);
  3858. // The request should either fail or return 400 Bad Request
  3859. if (res) {
  3860. // If we get a response, it should be 400 Bad Request
  3861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3862. } else {
  3863. // Or the request should fail entirely
  3864. EXPECT_FALSE(res);
  3865. }
  3866. EXPECT_EQ("close", res->get_header_value("Connection"));
  3867. EXPECT_FALSE(cli_.is_socket_open());
  3868. }
  3869. TEST_F(ServerTest, PercentEncoding) {
  3870. auto res = cli_.Get("/e%6edwith%");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::OK_200, res->status);
  3873. }
  3874. TEST_F(ServerTest, PercentEncodingUnicode) {
  3875. auto res = cli_.Get("/e%u006edwith%");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. }
  3879. TEST_F(ServerTest, InvalidPercentEncoding) {
  3880. auto res = cli_.Get("/%endwith%");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3883. }
  3884. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3885. auto res = cli_.Get("/%uendwith%");
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3888. }
  3889. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3890. auto res = cli_.Get("/hello?aaa=bbb%");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3893. }
  3894. TEST_F(ServerTest, PlusSignEncoding) {
  3895. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. EXPECT_EQ("a +b", res->body);
  3899. }
  3900. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3901. // This test simulates a potential DoS attack using many headers
  3902. // to verify our security fix prevents memory exhaustion
  3903. httplib::Headers attack_headers;
  3904. // Attempt to add many headers like an attacker would (200 headers to far
  3905. // exceed limit)
  3906. for (int i = 0; i < 200; i++) {
  3907. std::string name = "X-Attack-Header-" + std::to_string(i);
  3908. std::string value = "attack_payload_" + std::to_string(i);
  3909. attack_headers.emplace(name, value);
  3910. }
  3911. // Try to POST with excessive headers
  3912. cli_.set_keep_alive(true);
  3913. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3914. // Should either fail or return 400 Bad Request due to security limit
  3915. if (res) {
  3916. // If we get a response, it should be 400 Bad Request
  3917. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3918. } else {
  3919. // Request failed, which is the expected behavior for DoS protection
  3920. EXPECT_FALSE(res);
  3921. }
  3922. EXPECT_EQ("close", res->get_header_value("Connection"));
  3923. EXPECT_FALSE(cli_.is_socket_open());
  3924. }
  3925. TEST_F(ServerTest, MultipartFormData) {
  3926. UploadFormDataItems items = {
  3927. {"text1", "text default", "", ""},
  3928. {"text2", "aωb", "", ""},
  3929. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3930. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3931. {"file3", "", "", "application/octet-stream"},
  3932. {"file4", "", "", " application/json tmp-string "}};
  3933. auto res = cli_.Post("/multipart", items);
  3934. ASSERT_TRUE(res);
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3938. UploadFormDataItems items = {
  3939. {"text", "default text", "", ""},
  3940. {"multi_text1", "aaaaa", "", ""},
  3941. {"multi_text1", "bbbbb", "", ""},
  3942. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3943. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3944. "application/json"},
  3945. };
  3946. auto res = cli_.Post("/multipart/multi_file_values", items);
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::OK_200, res->status);
  3949. }
  3950. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3951. auto res = cli_.Get("/hi");
  3952. ASSERT_TRUE(res);
  3953. EXPECT_EQ(StatusCode::OK_200, res->status);
  3954. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3958. Request req;
  3959. req.method = "POST";
  3960. req.path = "/chunked";
  3961. std::string host_and_port;
  3962. host_and_port += HOST;
  3963. host_and_port += ":";
  3964. host_and_port += std::to_string(PORT);
  3965. req.headers.emplace("Host", host_and_port.c_str());
  3966. req.headers.emplace("Accept", "*/*");
  3967. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3968. req.headers.emplace("Content-Type", "text/plain");
  3969. req.headers.emplace("Content-Length", "0");
  3970. req.headers.emplace(
  3971. "Transfer-Encoding",
  3972. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3973. // Client does not chunk, so make a chunked body manually.
  3974. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3975. auto res = std::make_shared<Response>();
  3976. auto error = Error::Success;
  3977. auto ret = cli_.send(req, *res, error);
  3978. ASSERT_TRUE(ret);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. }
  3981. TEST_F(ServerTest, GetStreamed2) {
  3982. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3985. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ(true, res->has_header("Content-Range"));
  3987. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3988. EXPECT_EQ(std::string("ab"), res->body);
  3989. }
  3990. TEST_F(ServerTest, GetStreamed) {
  3991. auto res = cli_.Get("/streamed");
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3995. EXPECT_EQ(std::string("aaabbb"), res->body);
  3996. }
  3997. TEST_F(ServerTest, GetStreamedWithRange1) {
  3998. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4001. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4002. EXPECT_EQ(true, res->has_header("Content-Range"));
  4003. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4004. EXPECT_EQ(std::string("def"), res->body);
  4005. }
  4006. TEST_F(ServerTest, GetStreamedWithRange2) {
  4007. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4010. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4011. EXPECT_EQ(true, res->has_header("Content-Range"));
  4012. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4013. EXPECT_EQ(std::string("bcdefg"), res->body);
  4014. }
  4015. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4016. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4019. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4020. EXPECT_EQ(true, res->has_header("Content-Range"));
  4021. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4022. EXPECT_EQ(std::string("efg"), res->body);
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4025. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4028. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4029. EXPECT_EQ(false, res->has_header("Content-Range"));
  4030. EXPECT_EQ(0U, res->body.size());
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4033. auto res = cli_.Get("/streamed-with-range",
  4034. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4035. "92233720368547758079223372036854775807"}});
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4038. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ(false, res->has_header("Content-Range"));
  4040. EXPECT_EQ(0U, res->body.size());
  4041. }
  4042. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4043. auto res = cli_.Get(
  4044. "/with-range",
  4045. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4046. {"Accept-Encoding", ""}});
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4049. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4050. EXPECT_EQ(true, res->has_header("Content-Range"));
  4051. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4052. EXPECT_EQ(std::string("abcdefg"), res->body);
  4053. }
  4054. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4055. auto res = cli_.Get("/with-range", {
  4056. {"Range", "bytes=0-"},
  4057. {"Accept-Encoding", ""},
  4058. });
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4061. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4062. EXPECT_EQ(true, res->has_header("Content-Range"));
  4063. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4064. EXPECT_EQ(std::string("abcdefg"), res->body);
  4065. }
  4066. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4067. auto res =
  4068. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4071. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4072. EXPECT_EQ(false, res->has_header("Content-Range"));
  4073. EXPECT_EQ(267U, res->body.size());
  4074. // Check that both range contents are present
  4075. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4076. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4077. // Check that Content-Range headers are present for both ranges
  4078. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4079. std::string::npos);
  4080. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4081. std::string::npos);
  4082. }
  4083. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4084. Ranges ranges;
  4085. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4086. ranges.emplace_back(0, -1);
  4087. }
  4088. auto res =
  4089. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4092. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ(false, res->has_header("Content-Range"));
  4094. EXPECT_EQ(0U, res->body.size());
  4095. }
  4096. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4097. auto res =
  4098. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ(5U, res->body.size());
  4102. // Check that overlapping ranges are coalesced into a single range
  4103. EXPECT_EQ("bcdef", res->body);
  4104. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4105. // Should be single range, not multipart
  4106. EXPECT_TRUE(res->has_header("Content-Range"));
  4107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4108. }
  4109. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4110. auto res =
  4111. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4114. EXPECT_EQ(268U, res->body.size());
  4115. // Check that both range contents are present
  4116. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4117. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4118. // Check that Content-Range headers are present for both ranges
  4119. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4120. std::string::npos);
  4121. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4122. std::string::npos);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4125. auto res =
  4126. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4129. EXPECT_EQ(269U, res->body.size());
  4130. // Check that both duplicate range contents are present
  4131. size_t first_abc = res->body.find("abc\r\n");
  4132. EXPECT_TRUE(first_abc != std::string::npos);
  4133. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4134. EXPECT_TRUE(second_abc != std::string::npos);
  4135. // Check that Content-Range headers are present for both ranges
  4136. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4137. EXPECT_TRUE(first_range != std::string::npos);
  4138. size_t second_range =
  4139. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4140. EXPECT_TRUE(second_range != std::string::npos);
  4141. }
  4142. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4143. auto res = cli_.Get("/streamed-with-range?error",
  4144. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4147. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4148. EXPECT_EQ(false, res->has_header("Content-Range"));
  4149. EXPECT_EQ(0U, res->body.size());
  4150. }
  4151. TEST_F(ServerTest, GetStreamedEndless) {
  4152. uint64_t offset = 0;
  4153. auto res = cli_.Get("/streamed-cancel",
  4154. [&](const char * /*data*/, uint64_t data_length) {
  4155. if (offset < 100) {
  4156. offset += data_length;
  4157. return true;
  4158. }
  4159. return false;
  4160. });
  4161. ASSERT_TRUE(!res);
  4162. EXPECT_EQ(Error::Canceled, res.error());
  4163. }
  4164. TEST_F(ServerTest, ClientStop) {
  4165. std::atomic_size_t count{4};
  4166. std::vector<std::thread> threads;
  4167. for (auto i = count.load(); i != 0; --i) {
  4168. threads.emplace_back([&]() {
  4169. auto res = cli_.Get("/streamed-cancel",
  4170. [&](const char *, uint64_t) { return true; });
  4171. --count;
  4172. ASSERT_TRUE(!res);
  4173. EXPECT_TRUE(res.error() == Error::Canceled ||
  4174. res.error() == Error::Read || res.error() == Error::Write);
  4175. });
  4176. }
  4177. std::this_thread::sleep_for(std::chrono::seconds(2));
  4178. while (count != 0) {
  4179. cli_.stop();
  4180. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4181. }
  4182. for (auto &t : threads) {
  4183. t.join();
  4184. }
  4185. }
  4186. TEST_F(ServerTest, GetWithRange1) {
  4187. auto res = cli_.Get("/with-range", {
  4188. make_range_header({{3, 5}}),
  4189. {"Accept-Encoding", ""},
  4190. });
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4196. EXPECT_EQ(std::string("def"), res->body);
  4197. }
  4198. TEST_F(ServerTest, GetWithRange2) {
  4199. auto res = cli_.Get("/with-range", {
  4200. make_range_header({{1, -1}}),
  4201. {"Accept-Encoding", ""},
  4202. });
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4205. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(true, res->has_header("Content-Range"));
  4207. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4208. EXPECT_EQ(std::string("bcdefg"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetWithRange3) {
  4211. auto res = cli_.Get("/with-range", {
  4212. make_range_header({{0, 0}}),
  4213. {"Accept-Encoding", ""},
  4214. });
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4217. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4218. EXPECT_EQ(true, res->has_header("Content-Range"));
  4219. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4220. EXPECT_EQ(std::string("a"), res->body);
  4221. }
  4222. TEST_F(ServerTest, GetWithRange4) {
  4223. auto res = cli_.Get("/with-range", {
  4224. make_range_header({{-1, 2}}),
  4225. {"Accept-Encoding", ""},
  4226. });
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4229. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(true, res->has_header("Content-Range"));
  4231. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4232. EXPECT_EQ(std::string("fg"), res->body);
  4233. }
  4234. TEST_F(ServerTest, GetWithRange5) {
  4235. auto res = cli_.Get("/with-range", {
  4236. make_range_header({{0, 5}}),
  4237. {"Accept-Encoding", ""},
  4238. });
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("abcdef"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4247. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipart) {
  4252. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4253. ASSERT_TRUE(res);
  4254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4256. EXPECT_EQ(false, res->has_header("Content-Range"));
  4257. EXPECT_EQ(267U, res->body.size());
  4258. }
  4259. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4260. auto res =
  4261. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4264. }
  4265. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4266. auto res = cli_.Get("/with-range-customized-response",
  4267. {{make_range_header({{1, 2}})}});
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ(true, res->has_header("Content-Length"));
  4271. EXPECT_EQ(false, res->has_header("Content-Range"));
  4272. EXPECT_EQ(JSON_DATA, res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4275. auto res = cli_.Get("/with-range-customized-response",
  4276. {{make_range_header({{1, 2}, {4, 5}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4279. EXPECT_EQ(true, res->has_header("Content-Length"));
  4280. EXPECT_EQ(false, res->has_header("Content-Range"));
  4281. EXPECT_EQ(JSON_DATA, res->body);
  4282. }
  4283. TEST_F(ServerTest, Issue1772) {
  4284. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4287. }
  4288. TEST_F(ServerTest, Issue609) {
  4289. auto res = cli_.Delete("/issue609");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ(std::string("ok"), res->body);
  4293. }
  4294. TEST_F(ServerTest, GetStreamedChunked) {
  4295. auto res = cli_.Get("/streamed-chunked");
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ(std::string("123456789"), res->body);
  4299. }
  4300. TEST_F(ServerTest, GetStreamedChunked2) {
  4301. auto res = cli_.Get("/streamed-chunked2");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ(std::string("123456789"), res->body);
  4305. }
  4306. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4307. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ(std::string("123456789"), res->body);
  4311. EXPECT_TRUE(res->has_header("Trailer"));
  4312. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4313. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4314. // Trailers are now stored separately from headers (security fix)
  4315. EXPECT_EQ(2U, res->trailers.size());
  4316. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4317. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4318. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4319. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4320. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4321. // Verify trailers are NOT in headers (security verification)
  4322. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4323. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4324. }
  4325. TEST_F(ServerTest, LargeChunkedPost) {
  4326. Request req;
  4327. req.method = "POST";
  4328. req.path = "/large-chunked";
  4329. std::string host_and_port;
  4330. host_and_port += HOST;
  4331. host_and_port += ":";
  4332. host_and_port += std::to_string(PORT);
  4333. req.headers.emplace("Host", host_and_port.c_str());
  4334. req.headers.emplace("Accept", "*/*");
  4335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4336. req.headers.emplace("Content-Type", "text/plain");
  4337. req.headers.emplace("Content-Length", "0");
  4338. req.headers.emplace("Transfer-Encoding", "chunked");
  4339. std::string long_string(30 * 1024u, 'a');
  4340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4341. // Attempt to make a large enough post to exceed OS buffers, to test that
  4342. // the server handles short reads if the full chunk data isn't available.
  4343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4344. auto res = std::make_shared<Response>();
  4345. auto error = Error::Success;
  4346. auto ret = cli_.send(req, *res, error);
  4347. ASSERT_TRUE(ret);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. }
  4350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4351. auto res = cli_.Get("/remote_addr");
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::OK_200, res->status);
  4354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4356. }
  4357. TEST_F(ServerTest, GetMethodLocalAddr) {
  4358. auto res = cli_.Get("/local_addr");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4362. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4363. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4364. }
  4365. TEST_F(ServerTest, HTTPResponseSplitting) {
  4366. auto res = cli_.Get("/http_response_splitting");
  4367. ASSERT_TRUE(res);
  4368. EXPECT_EQ(StatusCode::OK_200, res->status);
  4369. }
  4370. TEST_F(ServerTest, SlowRequest) {
  4371. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4372. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4373. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4374. }
  4375. #if 0
  4376. TEST_F(ServerTest, SlowPost) {
  4377. char buffer[64 * 1024];
  4378. memset(buffer, 0x42, sizeof(buffer));
  4379. auto res = cli_.Post(
  4380. "/slowpost", 64 * 1024 * 1024,
  4381. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4382. auto ret = sink.write(buffer, sizeof(buffer));
  4383. EXPECT_TRUE(ret);
  4384. return true;
  4385. },
  4386. "text/plain");
  4387. ASSERT_TRUE(res);
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. }
  4390. TEST_F(ServerTest, SlowPostFail) {
  4391. char buffer[64 * 1024];
  4392. memset(buffer, 0x42, sizeof(buffer));
  4393. cli_.set_write_timeout(std::chrono::seconds(0));
  4394. auto res = cli_.Post(
  4395. "/slowpost", 64 * 1024 * 1024,
  4396. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4397. sink.write(buffer, sizeof(buffer));
  4398. return true;
  4399. },
  4400. "text/plain");
  4401. ASSERT_TRUE(!res);
  4402. EXPECT_EQ(Error::Write, res.error());
  4403. }
  4404. #endif
  4405. TEST_F(ServerTest, Put) {
  4406. auto res = cli_.Put("/put", "PUT", "text/plain");
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("PUT", res->body);
  4410. }
  4411. TEST_F(ServerTest, PutWithContentProvider) {
  4412. auto res = cli_.Put(
  4413. "/put", 3,
  4414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4415. sink.os << "PUT";
  4416. return true;
  4417. },
  4418. "text/plain");
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. EXPECT_EQ("PUT", res->body);
  4422. }
  4423. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4424. auto res = cli_.Post(
  4425. "/post", 42,
  4426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4427. return false;
  4428. },
  4429. "text/plain");
  4430. ASSERT_TRUE(!res);
  4431. EXPECT_EQ(Error::Canceled, res.error());
  4432. }
  4433. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4434. auto res = cli_.Put(
  4435. "/put",
  4436. [](size_t /*offset*/, DataSink &sink) {
  4437. sink.os << "PUT";
  4438. sink.done();
  4439. return true;
  4440. },
  4441. "text/plain");
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::OK_200, res->status);
  4444. EXPECT_EQ("PUT", res->body);
  4445. }
  4446. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4447. auto res = cli_.Post(
  4448. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4449. "text/plain");
  4450. ASSERT_TRUE(!res);
  4451. EXPECT_EQ(Error::Canceled, res.error());
  4452. }
  4453. TEST_F(ServerTest, PostLoopBack) {
  4454. std::string body;
  4455. auto res = cli_.Post(
  4456. "/post-loopback", 9,
  4457. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4458. EXPECT_EQ(9u, length);
  4459. sink.write("123", 3);
  4460. sink.write("456", 3);
  4461. sink.write("789", 3);
  4462. return true;
  4463. },
  4464. "text/plain",
  4465. [&body](const char *data, size_t data_length) {
  4466. body.append(data, data_length);
  4467. return true;
  4468. });
  4469. ASSERT_TRUE(res);
  4470. EXPECT_EQ(StatusCode::OK_200, res->status);
  4471. EXPECT_EQ("123456789", body);
  4472. }
  4473. TEST_F(ServerTest, PutLoopBack) {
  4474. std::string body;
  4475. auto res = cli_.Put(
  4476. "/put-loopback", 9,
  4477. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4478. EXPECT_EQ(9u, length);
  4479. sink.write("123", 3);
  4480. sink.write("456", 3);
  4481. sink.write("789", 3);
  4482. return true;
  4483. },
  4484. "text/plain",
  4485. [&body](const char *data, size_t data_length) {
  4486. body.append(data, data_length);
  4487. return true;
  4488. });
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ("123456789", body);
  4492. }
  4493. TEST_F(ServerTest, PatchLoopBack) {
  4494. std::string body;
  4495. auto res = cli_.Patch(
  4496. "/patch-loopback", 9,
  4497. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4498. EXPECT_EQ(9u, length);
  4499. sink.write("123", 3);
  4500. sink.write("456", 3);
  4501. sink.write("789", 3);
  4502. return true;
  4503. },
  4504. "text/plain",
  4505. [&body](const char *data, size_t data_length) {
  4506. body.append(data, data_length);
  4507. return true;
  4508. });
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ("123456789", body);
  4512. }
  4513. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4514. std::string body;
  4515. auto res = cli_.Post(
  4516. "/post-loopback",
  4517. [](size_t /*offset*/, DataSink &sink) {
  4518. sink.write("123", 3);
  4519. sink.write("456", 3);
  4520. sink.write("789", 3);
  4521. sink.done();
  4522. return true;
  4523. },
  4524. "text/plain",
  4525. [&body](const char *data, size_t data_length) {
  4526. body.append(data, data_length);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("123456789", body);
  4532. }
  4533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4534. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4535. cli_.set_compress(true);
  4536. auto res = cli_.Put(
  4537. "/put", 3,
  4538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4539. sink.os << "PUT";
  4540. return true;
  4541. },
  4542. "text/plain");
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::OK_200, res->status);
  4545. EXPECT_EQ("PUT", res->body);
  4546. }
  4547. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4548. cli_.set_compress(true);
  4549. auto res = cli_.Post(
  4550. "/post", 42,
  4551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4552. return false;
  4553. },
  4554. "text/plain");
  4555. ASSERT_TRUE(!res);
  4556. EXPECT_EQ(Error::Canceled, res.error());
  4557. }
  4558. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4559. cli_.set_compress(true);
  4560. auto res = cli_.Put(
  4561. "/put",
  4562. [](size_t /*offset*/, DataSink &sink) {
  4563. sink.os << "PUT";
  4564. sink.done();
  4565. return true;
  4566. },
  4567. "text/plain");
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ("PUT", res->body);
  4571. }
  4572. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Post(
  4575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4581. cli_.set_compress(true);
  4582. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ(LARGE_DATA, res->body);
  4586. }
  4587. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4589. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4590. Client cli(s.c_str());
  4591. cli.enable_server_certificate_verification(false);
  4592. #else
  4593. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4594. Client cli(s.c_str());
  4595. #endif
  4596. cli.set_compress(true);
  4597. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ(LARGE_DATA, res->body);
  4601. // The compressed size should be less than a 10th of the original. May vary
  4602. // depending on the zlib library.
  4603. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4604. static_cast<uint64_t>(10 * 1024 * 1024));
  4605. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4606. }
  4607. TEST_F(ServerTest, PutContentWithDeflate) {
  4608. cli_.set_compress(false);
  4609. Headers headers;
  4610. headers.emplace("Content-Encoding", "deflate");
  4611. // PUT in deflate format:
  4612. auto res = cli_.Put("/put", headers,
  4613. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ("PUT", res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4627. Headers headers;
  4628. headers.emplace("Accept-Encoding", "gzip, deflate");
  4629. auto res = cli_.Get("/streamed-chunked2", headers);
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. EXPECT_EQ(std::string("123456789"), res->body);
  4633. }
  4634. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4635. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST(GzipDecompressor, ChunkedDecompression) {
  4640. std::string data;
  4641. for (size_t i = 0; i < 32 * 1024; ++i) {
  4642. data.push_back(static_cast<char>('a' + i % 26));
  4643. }
  4644. std::string compressed_data;
  4645. {
  4646. httplib::detail::gzip_compressor compressor;
  4647. bool result = compressor.compress(
  4648. data.data(), data.size(),
  4649. /*last=*/true,
  4650. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4651. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4652. compressed_data_size);
  4653. return true;
  4654. });
  4655. ASSERT_TRUE(result);
  4656. }
  4657. std::string decompressed_data;
  4658. {
  4659. httplib::detail::gzip_decompressor decompressor;
  4660. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4661. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4662. size_t chunk_size = 130;
  4663. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4664. chunk_begin += chunk_size) {
  4665. size_t current_chunk_size =
  4666. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4667. bool result = decompressor.decompress(
  4668. compressed_data.data() + chunk_begin, current_chunk_size,
  4669. [&](const char *decompressed_data_chunk,
  4670. size_t decompressed_data_chunk_size) {
  4671. decompressed_data.insert(decompressed_data.size(),
  4672. decompressed_data_chunk,
  4673. decompressed_data_chunk_size);
  4674. return true;
  4675. });
  4676. ASSERT_TRUE(result);
  4677. }
  4678. }
  4679. ASSERT_EQ(data, decompressed_data);
  4680. }
  4681. TEST(GzipDecompressor, DeflateDecompression) {
  4682. std::string original_text = "Raw deflate without gzip";
  4683. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4684. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4685. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4686. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4687. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4688. std::string decompressed_data;
  4689. {
  4690. httplib::detail::gzip_decompressor decompressor;
  4691. bool result = decompressor.decompress(
  4692. compressed_data.data(), compressed_data.size(),
  4693. [&](const char *decompressed_data_chunk,
  4694. size_t decompressed_data_chunk_size) {
  4695. decompressed_data.insert(decompressed_data.size(),
  4696. decompressed_data_chunk,
  4697. decompressed_data_chunk_size);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(result);
  4701. }
  4702. ASSERT_EQ(original_text, decompressed_data);
  4703. }
  4704. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4705. std::string original_text = "Raw deflate without gzip";
  4706. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4707. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4708. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4709. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4710. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4711. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4712. std::string decompressed_data;
  4713. {
  4714. httplib::detail::gzip_decompressor decompressor;
  4715. bool result = decompressor.decompress(
  4716. compressed_data.data(), compressed_data.size(),
  4717. [&](const char *decompressed_data_chunk,
  4718. size_t decompressed_data_chunk_size) {
  4719. decompressed_data.insert(decompressed_data.size(),
  4720. decompressed_data_chunk,
  4721. decompressed_data_chunk_size);
  4722. return true;
  4723. });
  4724. ASSERT_TRUE(result);
  4725. }
  4726. ASSERT_EQ(original_text, decompressed_data);
  4727. }
  4728. #ifdef _WIN32
  4729. TEST(GzipDecompressor, LargeRandomData) {
  4730. // prepare large random data that is difficult to be compressed and is
  4731. // expected to have large size even when compressed
  4732. std::random_device seed_gen;
  4733. std::mt19937 random(seed_gen());
  4734. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4735. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4736. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4737. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4738. // compress data over 4GiB
  4739. std::string compressed_data;
  4740. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4741. httplib::detail::gzip_compressor compressor;
  4742. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4743. data.size() * sizeof(std::uint32_t), true,
  4744. [&](const char *data, size_t size) {
  4745. compressed_data.insert(
  4746. compressed_data.size(), data, size);
  4747. return true;
  4748. });
  4749. ASSERT_TRUE(result);
  4750. // FIXME: compressed data size is expected to be greater than 4GiB,
  4751. // but there is no guarantee
  4752. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4753. // decompress data over 4GiB
  4754. std::string decompressed_data;
  4755. decompressed_data.reserve(data_size);
  4756. httplib::detail::gzip_decompressor decompressor;
  4757. result = decompressor.decompress(
  4758. compressed_data.data(), compressed_data.size(),
  4759. [&](const char *data, size_t size) {
  4760. decompressed_data.insert(decompressed_data.size(), data, size);
  4761. return true;
  4762. });
  4763. ASSERT_TRUE(result);
  4764. // compare
  4765. ASSERT_EQ(data_size, decompressed_data.size());
  4766. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4767. 0);
  4768. }
  4769. #endif
  4770. #endif
  4771. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4781. Headers headers;
  4782. headers.emplace("Accept-Encoding", "br");
  4783. auto res = cli_.Get("/streamed-chunked2", headers);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ(std::string("123456789"), res->body);
  4787. }
  4788. #endif
  4789. TEST_F(ServerTest, Patch) {
  4790. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PATCH", res->body);
  4794. }
  4795. TEST_F(ServerTest, Delete) {
  4796. auto res = cli_.Delete("/delete");
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. EXPECT_EQ("DELETE", res->body);
  4800. }
  4801. TEST_F(ServerTest, DeleteContentReceiver) {
  4802. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4803. ASSERT_TRUE(res);
  4804. EXPECT_EQ(StatusCode::OK_200, res->status);
  4805. EXPECT_EQ("content", res->body);
  4806. }
  4807. TEST_F(ServerTest, Options) {
  4808. auto res = cli_.Options("*");
  4809. ASSERT_TRUE(res);
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4812. EXPECT_TRUE(res->body.empty());
  4813. }
  4814. TEST_F(ServerTest, URL) {
  4815. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4816. ASSERT_TRUE(res);
  4817. EXPECT_EQ(StatusCode::OK_200, res->status);
  4818. }
  4819. TEST_F(ServerTest, ArrayParam) {
  4820. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, NoMultipleHeaders) {
  4825. Headers headers = {{"Content-Length", "5"}};
  4826. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4827. "text/plain");
  4828. ASSERT_TRUE(res);
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. }
  4831. TEST_F(ServerTest, PostContentReceiver) {
  4832. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4833. ASSERT_TRUE(res);
  4834. ASSERT_EQ(StatusCode::OK_200, res->status);
  4835. ASSERT_EQ("content", res->body);
  4836. }
  4837. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4838. UploadFormDataItems items = {
  4839. {"text1", "text default", "", ""},
  4840. {"text2", "aωb", "", ""},
  4841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4843. {"file3", "", "", "application/octet-stream"},
  4844. };
  4845. auto res = cli_.Post("/content_receiver", items);
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::OK_200, res->status);
  4848. }
  4849. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4850. UploadFormDataItems items = {
  4851. {"text1", "text default", "", ""},
  4852. {"text2", "aωb", "", ""},
  4853. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4854. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4855. {"file3", "", "", "application/octet-stream"},
  4856. };
  4857. auto boundary = std::string("+++++");
  4858. std::string body;
  4859. for (const auto &item : items) {
  4860. body += "--" + boundary + "\r\n";
  4861. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4862. if (!item.filename.empty()) {
  4863. body += "; filename=\"" + item.filename + "\"";
  4864. }
  4865. body += "\r\n";
  4866. if (!item.content_type.empty()) {
  4867. body += "Content-Type: " + item.content_type + "\r\n";
  4868. }
  4869. body += "\r\n";
  4870. body += item.content + "\r\n";
  4871. }
  4872. body += "--" + boundary + "--\r\n";
  4873. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4874. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. TEST_F(ServerTest, PostContentReceiverGzip) {
  4879. cli_.set_compress(true);
  4880. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. ASSERT_EQ(StatusCode::OK_200, res->status);
  4883. ASSERT_EQ("content", res->body);
  4884. }
  4885. TEST_F(ServerTest, PutContentReceiver) {
  4886. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4887. ASSERT_TRUE(res);
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. ASSERT_EQ("content", res->body);
  4890. }
  4891. TEST_F(ServerTest, PatchContentReceiver) {
  4892. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4893. ASSERT_TRUE(res);
  4894. ASSERT_EQ(StatusCode::OK_200, res->status);
  4895. ASSERT_EQ("content", res->body);
  4896. }
  4897. template <typename ClientType>
  4898. void TestWithHeadersAndContentReceiver(
  4899. ClientType &cli,
  4900. std::function<Result(ClientType &, const std::string &, const Headers &,
  4901. const std::string &, const std::string &,
  4902. ContentReceiver, DownloadProgress)>
  4903. request_func) {
  4904. Headers headers;
  4905. headers.emplace("X-Custom-Header", "test-value");
  4906. std::string received_body;
  4907. auto res = request_func(
  4908. cli, "/content_receiver", headers, "content", "application/json",
  4909. [&](const char *data, size_t data_length) {
  4910. received_body.append(data, data_length);
  4911. return true;
  4912. },
  4913. nullptr);
  4914. ASSERT_TRUE(res);
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("content", received_body);
  4917. }
  4918. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. using ClientT = SSLClient;
  4921. #else
  4922. using ClientT = Client;
  4923. #endif
  4924. TestWithHeadersAndContentReceiver<ClientT>(
  4925. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4926. const std::string &body, const std::string &content_type,
  4927. ContentReceiver receiver, DownloadProgress progress) {
  4928. return cli.Post(path, headers, body, content_type, receiver, progress);
  4929. });
  4930. }
  4931. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4933. using ClientT = SSLClient;
  4934. #else
  4935. using ClientT = Client;
  4936. #endif
  4937. TestWithHeadersAndContentReceiver<ClientT>(
  4938. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4939. const std::string &body, const std::string &content_type,
  4940. ContentReceiver receiver, DownloadProgress progress) {
  4941. return cli.Put(path, headers, body, content_type, receiver, progress);
  4942. });
  4943. }
  4944. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4946. using ClientT = SSLClient;
  4947. #else
  4948. using ClientT = Client;
  4949. #endif
  4950. TestWithHeadersAndContentReceiver<ClientT>(
  4951. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4952. const std::string &body, const std::string &content_type,
  4953. ContentReceiver receiver, DownloadProgress progress) {
  4954. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4955. });
  4956. }
  4957. template <typename ClientType>
  4958. void TestWithHeadersAndContentReceiverWithProgress(
  4959. ClientType &cli,
  4960. std::function<Result(ClientType &, const std::string &, const Headers &,
  4961. const std::string &, const std::string &,
  4962. ContentReceiver, DownloadProgress)>
  4963. request_func) {
  4964. Headers headers;
  4965. headers.emplace("X-Test-Header", "progress-test");
  4966. std::string received_body;
  4967. auto progress_called = false;
  4968. auto res = request_func(
  4969. cli, "/content_receiver", headers, "content", "text/plain",
  4970. [&](const char *data, size_t data_length) {
  4971. received_body.append(data, data_length);
  4972. return true;
  4973. },
  4974. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4975. progress_called = true;
  4976. return true;
  4977. });
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("content", received_body);
  4981. EXPECT_TRUE(progress_called);
  4982. }
  4983. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4985. using ClientT = SSLClient;
  4986. #else
  4987. using ClientT = Client;
  4988. #endif
  4989. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4990. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4991. const std::string &body, const std::string &content_type,
  4992. ContentReceiver receiver, DownloadProgress progress) {
  4993. return cli.Post(path, headers, body, content_type, receiver, progress);
  4994. });
  4995. }
  4996. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4998. using ClientT = SSLClient;
  4999. #else
  5000. using ClientT = Client;
  5001. #endif
  5002. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5003. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5004. const std::string &body, const std::string &content_type,
  5005. ContentReceiver receiver, DownloadProgress progress) {
  5006. return cli.Put(path, headers, body, content_type, receiver, progress);
  5007. });
  5008. }
  5009. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5011. using ClientT = SSLClient;
  5012. #else
  5013. using ClientT = Client;
  5014. #endif
  5015. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5016. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5017. const std::string &body, const std::string &content_type,
  5018. ContentReceiver receiver, DownloadProgress progress) {
  5019. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5020. });
  5021. }
  5022. template <typename ClientType>
  5023. void TestWithHeadersAndContentReceiverError(
  5024. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5025. const Headers &, const std::string &,
  5026. const std::string &, ContentReceiver)>
  5027. request_func) {
  5028. Headers headers;
  5029. headers.emplace("X-Error-Test", "true");
  5030. std::string received_body;
  5031. auto receiver_failed = false;
  5032. auto res =
  5033. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5034. [&](const char *data, size_t data_length) {
  5035. received_body.append(data, data_length);
  5036. receiver_failed = true;
  5037. return false;
  5038. });
  5039. ASSERT_FALSE(res);
  5040. EXPECT_TRUE(receiver_failed);
  5041. }
  5042. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5044. using ClientT = SSLClient;
  5045. #else
  5046. using ClientT = Client;
  5047. #endif
  5048. TestWithHeadersAndContentReceiverError<ClientT>(
  5049. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5050. const std::string &body, const std::string &content_type,
  5051. ContentReceiver receiver) {
  5052. return cli.Post(path, headers, body, content_type, receiver);
  5053. });
  5054. }
  5055. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5057. using ClientT = SSLClient;
  5058. #else
  5059. using ClientT = Client;
  5060. #endif
  5061. TestWithHeadersAndContentReceiverError<ClientT>(
  5062. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5063. const std::string &body, const std::string &content_type,
  5064. ContentReceiver receiver) {
  5065. return cli.Put(path, headers, body, content_type, receiver);
  5066. });
  5067. }
  5068. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5070. using ClientT = SSLClient;
  5071. #else
  5072. using ClientT = Client;
  5073. #endif
  5074. TestWithHeadersAndContentReceiverError<ClientT>(
  5075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5076. const std::string &body, const std::string &content_type,
  5077. ContentReceiver receiver) {
  5078. return cli.Patch(path, headers, body, content_type, receiver);
  5079. });
  5080. }
  5081. TEST_F(ServerTest, PostQueryStringAndBody) {
  5082. auto res =
  5083. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5084. ASSERT_TRUE(res);
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, HTTP2Magic) {
  5088. Request req;
  5089. req.method = "PRI";
  5090. req.path = "*";
  5091. req.body = "SM";
  5092. auto res = std::make_shared<Response>();
  5093. auto error = Error::Success;
  5094. auto ret = cli_.send(req, *res, error);
  5095. ASSERT_TRUE(ret);
  5096. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5097. }
  5098. TEST_F(ServerTest, KeepAlive) {
  5099. auto res = cli_.Get("/hi");
  5100. ASSERT_TRUE(res);
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5103. EXPECT_EQ("Hello World!", res->body);
  5104. res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5108. EXPECT_EQ("Hello World!", res->body);
  5109. res = cli_.Get("/hi");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("Hello World!", res->body);
  5114. res = cli_.Get("/not-exist");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5117. res = cli_.Post("/empty", "", "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. EXPECT_EQ("close", res->get_header_value("Connection"));
  5123. res = cli_.Post(
  5124. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5125. "text/plain");
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5129. EXPECT_EQ("empty", res->body);
  5130. cli_.set_keep_alive(false);
  5131. res = cli_.Get("/last-request");
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::OK_200, res->status);
  5134. EXPECT_EQ("close", res->get_header_value("Connection"));
  5135. }
  5136. TEST_F(ServerTest, TooManyRedirect) {
  5137. cli_.set_follow_location(true);
  5138. auto res = cli_.Get("/redirect/0");
  5139. ASSERT_TRUE(!res);
  5140. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5141. }
  5142. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5143. Request req;
  5144. req.method = "FOOBAR";
  5145. req.path = "/hi";
  5146. cli_.set_keep_alive(true);
  5147. auto res = cli_.send(req);
  5148. ASSERT_TRUE(res);
  5149. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5150. EXPECT_EQ("close", res->get_header_value("Connection"));
  5151. EXPECT_FALSE(cli_.is_socket_open());
  5152. }
  5153. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5154. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5155. TEST_F(ServerTest, Gzip) {
  5156. Headers headers;
  5157. headers.emplace("Accept-Encoding", "gzip, deflate");
  5158. auto res = cli_.Get("/compress", headers);
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5164. "7890123456789012345678901234567890",
  5165. res->body);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. }
  5168. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5169. Headers headers;
  5170. headers.emplace("Accept-Encoding", "");
  5171. auto res = cli_.Get("/compress", headers);
  5172. ASSERT_TRUE(res);
  5173. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5177. "7890123456789012345678901234567890",
  5178. res->body);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. }
  5181. TEST_F(ServerTest, GzipWithContentReceiver) {
  5182. Headers headers;
  5183. headers.emplace("Accept-Encoding", "gzip, deflate");
  5184. std::string body;
  5185. auto res = cli_.Get("/compress", headers,
  5186. [&](const char *data, uint64_t data_length) {
  5187. EXPECT_EQ(100U, data_length);
  5188. body.append(data, data_length);
  5189. return true;
  5190. });
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5196. "7890123456789012345678901234567890",
  5197. body);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. }
  5200. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5201. Headers headers;
  5202. headers.emplace("Accept-Encoding", "gzip, deflate");
  5203. cli_.set_decompress(false);
  5204. auto res = cli_.Get("/compress", headers);
  5205. ASSERT_TRUE(res);
  5206. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5208. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5209. EXPECT_EQ(33U, res->body.size());
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5213. Headers headers;
  5214. headers.emplace("Accept-Encoding", "");
  5215. std::string body;
  5216. auto res = cli_.Get("/compress", headers,
  5217. [&](const char *data, uint64_t data_length) {
  5218. EXPECT_EQ(100U, data_length);
  5219. body.append(data, data_length);
  5220. return true;
  5221. });
  5222. ASSERT_TRUE(res);
  5223. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5226. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5227. "7890123456789012345678901234567890",
  5228. body);
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. }
  5231. TEST_F(ServerTest, NoGzip) {
  5232. Headers headers;
  5233. headers.emplace("Accept-Encoding", "gzip, deflate");
  5234. auto res = cli_.Get("/nocompress", headers);
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5237. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5238. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5239. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5240. "7890123456789012345678901234567890",
  5241. res->body);
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. }
  5244. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "gzip, deflate");
  5247. std::string body;
  5248. auto res = cli_.Get("/nocompress", headers,
  5249. [&](const char *data, uint64_t data_length) {
  5250. EXPECT_EQ(100U, data_length);
  5251. body.append(data, data_length);
  5252. return true;
  5253. });
  5254. ASSERT_TRUE(res);
  5255. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5256. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5258. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5259. "7890123456789012345678901234567890",
  5260. body);
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. }
  5263. TEST_F(ServerTest, MultipartFormDataGzip) {
  5264. UploadFormDataItems items = {
  5265. {"key1", "test", "", ""},
  5266. {"key2", "--abcdefg123", "", ""},
  5267. };
  5268. cli_.set_compress(true);
  5269. auto res = cli_.Post("/compress-multipart", items);
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. #endif
  5274. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5275. TEST_F(ServerTest, Brotli) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "br");
  5278. auto res = cli_.Get("/compress", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5282. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5284. "7890123456789012345678901234567890",
  5285. res->body);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. #endif
  5289. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5290. TEST_F(ServerTest, Zstd) {
  5291. Headers headers;
  5292. headers.emplace("Accept-Encoding", "zstd");
  5293. auto res = cli_.Get("/compress", headers);
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5299. "7890123456789012345678901234567890",
  5300. res->body);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. }
  5303. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5304. Headers headers;
  5305. headers.emplace("Accept-Encoding", "");
  5306. auto res = cli_.Get("/compress", headers);
  5307. ASSERT_TRUE(res);
  5308. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5310. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5311. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5312. "7890123456789012345678901234567890",
  5313. res->body);
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. }
  5316. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5317. Headers headers;
  5318. headers.emplace("Accept-Encoding", "zstd");
  5319. std::string body;
  5320. auto res = cli_.Get("/compress", headers,
  5321. [&](const char *data, uint64_t data_length) {
  5322. EXPECT_EQ(100U, data_length);
  5323. body.append(data, data_length);
  5324. return true;
  5325. });
  5326. ASSERT_TRUE(res);
  5327. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5329. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5331. "7890123456789012345678901234567890",
  5332. body);
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. }
  5335. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5336. Headers headers;
  5337. headers.emplace("Accept-Encoding", "zstd");
  5338. cli_.set_decompress(false);
  5339. auto res = cli_.Get("/compress", headers);
  5340. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5341. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5342. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5343. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5347. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5348. EXPECT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ(26U, res->body.size());
  5350. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5351. 0);
  5352. }
  5353. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5354. Headers headers;
  5355. headers.emplace("Accept-Encoding", "");
  5356. std::string body;
  5357. auto res = cli_.Get("/compress", headers,
  5358. [&](const char *data, uint64_t data_length) {
  5359. EXPECT_EQ(100U, data_length);
  5360. body.append(data, data_length);
  5361. return true;
  5362. });
  5363. ASSERT_TRUE(res);
  5364. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5365. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5366. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5367. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5368. "7890123456789012345678901234567890",
  5369. body);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, NoZstd) {
  5373. Headers headers;
  5374. headers.emplace("Accept-Encoding", "zstd");
  5375. auto res = cli_.Get("/nocompress", headers);
  5376. ASSERT_TRUE(res);
  5377. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5378. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5380. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5381. "7890123456789012345678901234567890",
  5382. res->body);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. }
  5385. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5386. Headers headers;
  5387. headers.emplace("Accept-Encoding", "zstd");
  5388. std::string body;
  5389. auto res = cli_.Get("/nocompress", headers,
  5390. [&](const char *data, uint64_t data_length) {
  5391. EXPECT_EQ(100U, data_length);
  5392. body.append(data, data_length);
  5393. return true;
  5394. });
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5397. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. // TODO: How to enable zstd ??
  5405. TEST_F(ServerTest, MultipartFormDataZstd) {
  5406. UploadFormDataItems items = {
  5407. {"key1", "test", "", ""},
  5408. {"key2", "--abcdefg123", "", ""},
  5409. };
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Post("/compress-multipart", headers, items);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "zstd");
  5420. cli_.set_compress(true);
  5421. auto res = cli_.Put(
  5422. "/put", headers, 3,
  5423. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5424. sink.os << "PUT";
  5425. return true;
  5426. },
  5427. "text/plain");
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("PUT", res->body);
  5431. }
  5432. // Pre-compression logging tests
  5433. TEST_F(ServerTest, PreCompressionLogging) {
  5434. // Test data for compression (matches the actual /compress endpoint content)
  5435. const std::string test_content =
  5436. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5437. "3456789012345678901234567890";
  5438. // Variables to capture logging data
  5439. std::string pre_compression_body;
  5440. std::string pre_compression_content_type;
  5441. std::string pre_compression_content_encoding;
  5442. std::string post_compression_body;
  5443. std::string post_compression_content_type;
  5444. std::string post_compression_content_encoding;
  5445. // Set up pre-compression logger
  5446. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5447. const Response &res) {
  5448. pre_compression_body = res.body;
  5449. pre_compression_content_type = res.get_header_value("Content-Type");
  5450. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5451. });
  5452. // Set up post-compression logger
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. post_compression_content_type = res.get_header_value("Content-Type");
  5456. post_compression_content_encoding =
  5457. res.get_header_value("Content-Encoding");
  5458. });
  5459. // Test with gzip compression
  5460. Headers headers;
  5461. headers.emplace("Accept-Encoding", "gzip");
  5462. auto res = cli_.Get("/compress", headers);
  5463. // Verify response was compressed
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5467. // Verify pre-compression logger captured uncompressed content
  5468. EXPECT_EQ(test_content, pre_compression_body);
  5469. EXPECT_EQ("text/plain", pre_compression_content_type);
  5470. EXPECT_TRUE(pre_compression_content_encoding
  5471. .empty()); // No encoding header before compression
  5472. // Verify post-compression logger captured compressed content
  5473. EXPECT_NE(test_content,
  5474. post_compression_body); // Should be different after compression
  5475. EXPECT_EQ("text/plain", post_compression_content_type);
  5476. EXPECT_EQ("gzip", post_compression_content_encoding);
  5477. // Verify compressed content is smaller
  5478. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5479. }
  5480. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5481. const std::string test_content =
  5482. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5483. "3456789012345678901234567890";
  5484. std::string pre_compression_body;
  5485. std::string post_compression_body;
  5486. svr_.set_pre_compression_logger(
  5487. [&](const Request & /*req*/, const Response &res) {
  5488. pre_compression_body = res.body;
  5489. });
  5490. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5491. post_compression_body = res.body;
  5492. });
  5493. Headers headers;
  5494. headers.emplace("Accept-Encoding", "br");
  5495. auto res = cli_.Get("/compress", headers);
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5499. // Verify pre-compression content is uncompressed
  5500. EXPECT_EQ(test_content, pre_compression_body);
  5501. // Verify post-compression content is compressed
  5502. EXPECT_NE(test_content, post_compression_body);
  5503. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5504. }
  5505. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5506. const std::string test_content =
  5507. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5508. "3456789012345678901234567890";
  5509. std::string pre_compression_body;
  5510. std::string post_compression_body;
  5511. svr_.set_pre_compression_logger(
  5512. [&](const Request & /*req*/, const Response &res) {
  5513. pre_compression_body = res.body;
  5514. });
  5515. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5516. post_compression_body = res.body;
  5517. });
  5518. // Request without compression (use /nocompress endpoint)
  5519. Headers headers;
  5520. auto res = cli_.Get("/nocompress", headers);
  5521. ASSERT_TRUE(res);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5524. // Pre-compression logger should not be called when no compression is applied
  5525. EXPECT_TRUE(
  5526. pre_compression_body.empty()); // Pre-compression logger not called
  5527. EXPECT_EQ(
  5528. test_content,
  5529. post_compression_body); // Post-compression logger captures final content
  5530. }
  5531. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5532. const std::string test_content =
  5533. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5534. "3456789012345678901234567890";
  5535. std::string pre_compression_body;
  5536. bool pre_logger_called = false;
  5537. // Set only pre-compression logger
  5538. svr_.set_pre_compression_logger(
  5539. [&](const Request & /*req*/, const Response &res) {
  5540. pre_compression_body = res.body;
  5541. pre_logger_called = true;
  5542. });
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "gzip");
  5545. auto res = cli_.Get("/compress", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5549. // Verify pre-compression logger was called
  5550. EXPECT_TRUE(pre_logger_called);
  5551. EXPECT_EQ(test_content, pre_compression_body);
  5552. }
  5553. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5554. {
  5555. // Test with Expect: 100-continue header - success case
  5556. // Server returns 100 Continue, client sends body, server returns 200 OK
  5557. Request req;
  5558. req.method = "POST";
  5559. req.path = "/post-large";
  5560. req.set_header("Expect", "100-continue");
  5561. req.body = LARGE_DATA;
  5562. Response res;
  5563. auto error = Error::Success;
  5564. cli_.set_keep_alive(true);
  5565. auto ret = cli_.send(req, res, error);
  5566. EXPECT_TRUE(ret);
  5567. EXPECT_EQ(StatusCode::OK_200, res.status);
  5568. EXPECT_EQ(LARGE_DATA, res.body);
  5569. }
  5570. {
  5571. // Test with Expect: 100-continue header - error case
  5572. // Client should not send the body when server returns an error
  5573. Request req;
  5574. req.method = "POST";
  5575. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5576. req.set_header("Expect", "100-continue");
  5577. req.body = LARGE_DATA;
  5578. Response res;
  5579. auto error = Error::Success;
  5580. auto start = std::chrono::high_resolution_clock::now();
  5581. cli_.set_keep_alive(true);
  5582. auto ret = cli_.send(req, res, error);
  5583. auto end = std::chrono::high_resolution_clock::now();
  5584. auto elapsed =
  5585. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5586. .count();
  5587. // With Expect: 100-continue, request completes successfully but with error
  5588. EXPECT_TRUE(ret);
  5589. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5590. EXPECT_EQ("close", res.get_header_value("Connection"));
  5591. EXPECT_FALSE(cli_.is_socket_open());
  5592. EXPECT_LE(elapsed, 200);
  5593. }
  5594. {
  5595. // Send an extra GET request to ensure error recovery without hanging
  5596. Request req;
  5597. req.method = "GET";
  5598. req.path = "/hi";
  5599. auto start = std::chrono::high_resolution_clock::now();
  5600. auto res = cli_.send(req);
  5601. auto end = std::chrono::high_resolution_clock::now();
  5602. auto elapsed =
  5603. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5604. .count();
  5605. ASSERT_TRUE(res);
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. EXPECT_EQ("Hello World!", res->body);
  5608. EXPECT_LE(elapsed, 100);
  5609. }
  5610. }
  5611. TEST(ZstdDecompressor, ChunkedDecompression) {
  5612. std::string data;
  5613. for (size_t i = 0; i < 32 * 1024; ++i) {
  5614. data.push_back(static_cast<char>('a' + i % 26));
  5615. }
  5616. std::string compressed_data;
  5617. {
  5618. httplib::detail::zstd_compressor compressor;
  5619. bool result = compressor.compress(
  5620. data.data(), data.size(),
  5621. /*last=*/true,
  5622. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5623. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5624. compressed_data_size);
  5625. return true;
  5626. });
  5627. ASSERT_TRUE(result);
  5628. }
  5629. std::string decompressed_data;
  5630. {
  5631. httplib::detail::zstd_decompressor decompressor;
  5632. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5633. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5634. size_t chunk_size = 130;
  5635. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5636. chunk_begin += chunk_size) {
  5637. size_t current_chunk_size =
  5638. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5639. bool result = decompressor.decompress(
  5640. compressed_data.data() + chunk_begin, current_chunk_size,
  5641. [&](const char *decompressed_data_chunk,
  5642. size_t decompressed_data_chunk_size) {
  5643. decompressed_data.insert(decompressed_data.size(),
  5644. decompressed_data_chunk,
  5645. decompressed_data_chunk_size);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(result);
  5649. }
  5650. }
  5651. ASSERT_EQ(data, decompressed_data);
  5652. }
  5653. TEST(ZstdDecompressor, Decompress) {
  5654. std::string original_text = "Compressed with ZSTD";
  5655. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5656. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5657. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5658. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5659. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5660. std::string decompressed_data;
  5661. {
  5662. httplib::detail::zstd_decompressor decompressor;
  5663. bool result = decompressor.decompress(
  5664. compressed_data.data(), compressed_data.size(),
  5665. [&](const char *decompressed_data_chunk,
  5666. size_t decompressed_data_chunk_size) {
  5667. decompressed_data.insert(decompressed_data.size(),
  5668. decompressed_data_chunk,
  5669. decompressed_data_chunk_size);
  5670. return true;
  5671. });
  5672. ASSERT_TRUE(result);
  5673. }
  5674. ASSERT_EQ(original_text, decompressed_data);
  5675. }
  5676. #endif
  5677. // Sends a raw request to a server listening at HOST:PORT.
  5678. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5679. std::string *resp = nullptr) {
  5680. auto error = Error::Success;
  5681. auto client_sock = detail::create_client_socket(
  5682. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5683. /*connection_timeout_sec=*/5, 0,
  5684. /*read_timeout_sec=*/5, 0,
  5685. /*write_timeout_sec=*/5, 0, std::string(), error);
  5686. if (client_sock == INVALID_SOCKET) { return false; }
  5687. auto ret = detail::process_client_socket(
  5688. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5689. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5690. if (req.size() !=
  5691. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5692. return false;
  5693. }
  5694. char buf[512];
  5695. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5696. while (line_reader.getline()) {
  5697. if (resp) { *resp += line_reader.ptr(); }
  5698. }
  5699. return true;
  5700. });
  5701. detail::close_socket(client_sock);
  5702. return ret;
  5703. }
  5704. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5705. Server svr;
  5706. std::string header_value;
  5707. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5708. header_value = req.get_header_value("foo");
  5709. res.set_content("ok", "text/plain");
  5710. });
  5711. thread t = thread([&] { svr.listen(HOST, PORT); });
  5712. auto se = detail::scope_exit([&] {
  5713. svr.stop();
  5714. t.join();
  5715. ASSERT_FALSE(svr.is_running());
  5716. });
  5717. svr.wait_until_ready();
  5718. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5719. // like characters are not treated the same - use vertical tab and escape.
  5720. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5721. "foo: \t \v bar \x1B\t \r\n"
  5722. "Connection: close\r\n"
  5723. "\r\n";
  5724. std::string res;
  5725. ASSERT_TRUE(send_request(5, req, &res));
  5726. EXPECT_EQ(header_value, "");
  5727. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5728. }
  5729. // Sends a raw request and verifies that there isn't a crash or exception.
  5730. static void test_raw_request(const std::string &req,
  5731. std::string *out = nullptr) {
  5732. Server svr;
  5733. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5734. res.set_content("ok", "text/plain");
  5735. });
  5736. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5737. res.set_content("ok", "text/plain");
  5738. });
  5739. svr.Get("/header_field_value_check",
  5740. [&](const Request & /*req*/, Response &res) {
  5741. res.set_content("ok", "text/plain");
  5742. });
  5743. // Server read timeout must be longer than the client read timeout for the
  5744. // bug to reproduce, probably to force the server to process a request
  5745. // without a trailing blank line.
  5746. const time_t client_read_timeout_sec = 1;
  5747. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5748. bool listen_thread_ok = false;
  5749. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5750. auto se = detail::scope_exit([&] {
  5751. svr.stop();
  5752. t.join();
  5753. ASSERT_FALSE(svr.is_running());
  5754. EXPECT_TRUE(listen_thread_ok);
  5755. });
  5756. svr.wait_until_ready();
  5757. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5758. }
  5759. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5760. // A certain header line causes an exception if the header property is parsed
  5761. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5762. test_raw_request(
  5763. "GET /hi HTTP/1.1\r\n"
  5764. " : "
  5765. " "
  5766. " ");
  5767. }
  5768. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5769. // A certain header line causes an exception if the header property *name* is
  5770. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5771. // greedy matcher and requires backtracking when there are a lot of ":"
  5772. // characters.
  5773. // This occurs with libc++ but not libstdc++.
  5774. test_raw_request(
  5775. "GET /hi HTTP/1.1\r\n"
  5776. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5777. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5778. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5779. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5780. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5781. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5782. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5783. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5784. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5785. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5786. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5787. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5788. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5789. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5790. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5791. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5792. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5793. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5794. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5795. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5796. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5797. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5798. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5799. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5800. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5801. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5802. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5803. "&&&%%%");
  5804. }
  5805. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5806. // Make sure this doesn't crash the server.
  5807. // In a previous version of the header line regex, the "\r" rendered the line
  5808. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5809. // a new position where the leading white space ended and the field value
  5810. // began.
  5811. // The crash occurs with libc++ but not libstdc++.
  5812. test_raw_request("GET /hi HTTP/1.1\r\n"
  5813. "a:" +
  5814. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5815. "\r\n"
  5816. "\r\n");
  5817. }
  5818. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5819. std::string out;
  5820. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5821. "Content-Type: text/plain\r\n"
  5822. "Transfer-Encoding: chunked\r\n"
  5823. "\r\n"
  5824. "nothex\r\n",
  5825. &out);
  5826. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5827. }
  5828. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5829. std::string out;
  5830. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5831. "Content-Type: text/plain\r\n"
  5832. "Transfer-Encoding: chunked\r\n"
  5833. "\r\n"
  5834. "3\r\n"
  5835. "xyz\r\n"
  5836. "NaN\r\n",
  5837. &out);
  5838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5839. }
  5840. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5841. std::string out;
  5842. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5843. "Content-Type: text/plain\r\n"
  5844. "Transfer-Encoding: chunked\r\n"
  5845. "\r\n"
  5846. // Length is too large for 64 bits.
  5847. "1ffffffffffffffff\r\n"
  5848. "xyz\r\n",
  5849. &out);
  5850. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5851. }
  5852. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5853. test_raw_request("GET /hi HTTP/1.1\r\n"
  5854. "Content-Type: text/plain\r\n\r");
  5855. }
  5856. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5857. std::string out;
  5858. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5859. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5860. }
  5861. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5862. Server svr;
  5863. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5864. EXPECT_TRUE(!req.remote_addr.empty());
  5865. });
  5866. thread t = thread([&] { svr.listen(HOST, PORT); });
  5867. auto se = detail::scope_exit([&] {
  5868. svr.stop();
  5869. t.join();
  5870. ASSERT_FALSE(svr.is_running());
  5871. });
  5872. svr.wait_until_ready();
  5873. // Send an invalid request line to trigger Bad Request
  5874. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5875. std::string out;
  5876. ASSERT_TRUE(send_request(5, bad_req, &out));
  5877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5878. }
  5879. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5880. std::string out;
  5881. std::string request(
  5882. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5883. test_raw_request(request, &out);
  5884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5885. }
  5886. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5887. std::string out;
  5888. std::string request(
  5889. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5890. test_raw_request(request, &out);
  5891. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5892. }
  5893. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5894. std::string out;
  5895. std::string request(
  5896. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5897. test_raw_request(request, &out);
  5898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5899. }
  5900. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5901. std::string out;
  5902. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5903. "Test: \r\n\r\n",
  5904. &out);
  5905. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5906. }
  5907. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5908. Server svr;
  5909. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5910. res.set_header("Cache-Control", "no-cache");
  5911. res.set_chunked_content_provider(
  5912. "text/event-stream", [](size_t offset, DataSink &sink) {
  5913. std::string s = "data:";
  5914. s += std::to_string(offset);
  5915. s += "\n\n";
  5916. auto ret = sink.write(s.data(), s.size());
  5917. EXPECT_TRUE(ret);
  5918. std::this_thread::sleep_for(std::chrono::seconds(1));
  5919. return true;
  5920. });
  5921. });
  5922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5923. svr.wait_until_ready();
  5924. Client client(HOST, PORT);
  5925. const Headers headers = {{"Accept", "text/event-stream"}};
  5926. auto get_thread = std::thread([&client, &headers]() {
  5927. auto res = client.Get(
  5928. "/events", headers,
  5929. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5930. });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. get_thread.join();
  5934. listen_thread.join();
  5935. ASSERT_FALSE(svr.is_running());
  5936. });
  5937. // Give GET time to get a few messages.
  5938. std::this_thread::sleep_for(std::chrono::seconds(2));
  5939. }
  5940. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5941. httplib::Server svr;
  5942. svr.Post("/hi",
  5943. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5944. res.status = StatusCode::OK_200;
  5945. });
  5946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5947. svr.wait_until_ready();
  5948. Client cli(HOST, PORT);
  5949. auto res = cli.Post("/hi", "data", "text/plain");
  5950. ASSERT_TRUE(res);
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. svr.stop();
  5953. thread.join();
  5954. ASSERT_FALSE(svr.is_running());
  5955. res = cli.Post("/hi", "data", "text/plain");
  5956. ASSERT_FALSE(res);
  5957. }
  5958. TEST(ServerStopTest, ListenFailure) {
  5959. Server svr;
  5960. auto t = thread([&]() {
  5961. auto ret = svr.listen("????", PORT);
  5962. EXPECT_FALSE(ret);
  5963. });
  5964. svr.wait_until_ready();
  5965. svr.stop();
  5966. t.join();
  5967. }
  5968. TEST(ServerStopTest, Decommision) {
  5969. Server svr;
  5970. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5971. for (int i = 0; i < 4; i++) {
  5972. auto is_even = !(i % 2);
  5973. std::thread t{[&] {
  5974. try {
  5975. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5976. if (is_even) {
  5977. throw std::runtime_error("Some thing that happens to go wrong.");
  5978. }
  5979. svr.listen(HOST, PORT);
  5980. } catch (...) { svr.decommission(); }
  5981. }};
  5982. svr.wait_until_ready();
  5983. // Server is up
  5984. {
  5985. Client cli(HOST, PORT);
  5986. auto res = cli.Get("/hi");
  5987. if (is_even) {
  5988. EXPECT_FALSE(res);
  5989. } else {
  5990. EXPECT_TRUE(res);
  5991. EXPECT_EQ("hi...", res->body);
  5992. }
  5993. }
  5994. svr.stop();
  5995. t.join();
  5996. // Server is down...
  5997. {
  5998. Client cli(HOST, PORT);
  5999. auto res = cli.Get("/hi");
  6000. EXPECT_FALSE(res);
  6001. }
  6002. }
  6003. }
  6004. // Helper function for string body upload progress tests
  6005. template <typename SetupHandler, typename ClientCall>
  6006. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6007. ClientCall &&client_call,
  6008. const string &body) {
  6009. Server svr;
  6010. setup_handler(svr);
  6011. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6012. auto se = detail::scope_exit([&] {
  6013. svr.stop();
  6014. t.join();
  6015. });
  6016. svr.wait_until_ready();
  6017. Client cli(HOST, PORT);
  6018. vector<uint64_t> progress_values;
  6019. bool progress_called = false;
  6020. auto res =
  6021. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6022. progress_values.push_back(current);
  6023. progress_called = true;
  6024. return true;
  6025. });
  6026. ASSERT_TRUE(res);
  6027. EXPECT_EQ(200, res->status);
  6028. EXPECT_TRUE(progress_called);
  6029. }
  6030. TEST(UploadProgressTest, PostStringBodyBasic) {
  6031. TestStringBodyUploadProgress(
  6032. [](Server &svr) {
  6033. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6034. res.set_content("received", "text/plain");
  6035. });
  6036. },
  6037. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6038. return cli.Post("/test", body, "text/plain", progress_callback);
  6039. },
  6040. "test data for upload progress");
  6041. }
  6042. TEST(UploadProgressTest, PutStringBodyBasic) {
  6043. TestStringBodyUploadProgress(
  6044. [](Server &svr) {
  6045. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6046. res.set_content("put received", "text/plain");
  6047. });
  6048. },
  6049. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6050. return cli.Put("/test", body, "text/plain", progress_callback);
  6051. },
  6052. "put test data for upload progress");
  6053. }
  6054. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6055. TestStringBodyUploadProgress(
  6056. [](Server &svr) {
  6057. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6058. res.set_content("patch received", "text/plain");
  6059. });
  6060. },
  6061. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6062. return cli.Patch("/test", body, "text/plain", progress_callback);
  6063. },
  6064. "patch test data for upload progress");
  6065. }
  6066. // Helper function for content provider upload progress tests
  6067. template <typename SetupHandler, typename ClientCall>
  6068. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6069. ClientCall &&client_call) {
  6070. Server svr;
  6071. setup_handler(svr);
  6072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. t.join();
  6076. });
  6077. svr.wait_until_ready();
  6078. Client cli(HOST, PORT);
  6079. vector<uint64_t> progress_values;
  6080. auto res =
  6081. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6082. progress_values.push_back(current);
  6083. return true;
  6084. });
  6085. ASSERT_TRUE(res);
  6086. EXPECT_EQ(200, res->status);
  6087. EXPECT_FALSE(progress_values.empty());
  6088. }
  6089. TEST(UploadProgressTest, PostContentProviderProgress) {
  6090. TestContentProviderUploadProgress(
  6091. [](Server &svr) {
  6092. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6093. res.set_content("provider received", "text/plain");
  6094. });
  6095. },
  6096. [](Client &cli, UploadProgress progress_callback) {
  6097. return cli.Post(
  6098. "/test", 10,
  6099. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6100. sink.os << "test data";
  6101. return true;
  6102. },
  6103. "text/plain", progress_callback);
  6104. });
  6105. }
  6106. // Helper function for multipart upload progress tests
  6107. template <typename SetupHandler, typename ClientCall>
  6108. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6109. ClientCall &&client_call,
  6110. const string &endpoint) {
  6111. Server svr;
  6112. setup_handler(svr);
  6113. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6114. auto se = detail::scope_exit([&] {
  6115. svr.stop();
  6116. t.join();
  6117. });
  6118. svr.wait_until_ready();
  6119. Client cli(HOST, PORT);
  6120. vector<uint64_t> progress_values;
  6121. UploadFormDataItems items = {
  6122. {"field1", "value1", "", ""},
  6123. {"field2", "longer value for progress tracking test", "", ""},
  6124. {"file1", "file content data for upload progress", "test.txt",
  6125. "text/plain"}};
  6126. auto res = client_call(cli, endpoint, items,
  6127. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6128. progress_values.push_back(current);
  6129. return true;
  6130. });
  6131. ASSERT_TRUE(res);
  6132. EXPECT_EQ(200, res->status);
  6133. EXPECT_FALSE(progress_values.empty());
  6134. }
  6135. TEST(UploadProgressTest, PostMultipartProgress) {
  6136. TestMultipartUploadProgress(
  6137. [](Server &svr) {
  6138. svr.Post("/multipart", [](const Request &req, Response &res) {
  6139. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6140. res.set_content("multipart received", "text/plain");
  6141. });
  6142. },
  6143. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6144. UploadProgress progress_callback) {
  6145. return cli.Post(endpoint, items, progress_callback);
  6146. },
  6147. "/multipart");
  6148. }
  6149. // Helper function for basic download progress tests
  6150. template <typename SetupHandler, typename ClientCall>
  6151. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6152. ClientCall &&client_call, const string &endpoint,
  6153. size_t expected_content_size) {
  6154. Server svr;
  6155. setup_handler(svr);
  6156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6157. auto se = detail::scope_exit([&] {
  6158. svr.stop();
  6159. t.join();
  6160. });
  6161. svr.wait_until_ready();
  6162. Client cli(HOST, PORT);
  6163. vector<uint64_t> progress_values;
  6164. auto res = client_call(cli, endpoint,
  6165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6166. progress_values.push_back(current);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(res);
  6170. EXPECT_EQ(200, res->status);
  6171. EXPECT_FALSE(progress_values.empty());
  6172. EXPECT_EQ(expected_content_size, res->body.size());
  6173. }
  6174. TEST(DownloadProgressTest, GetBasic) {
  6175. TestBasicDownloadProgress(
  6176. [](Server &svr) {
  6177. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6178. string content(1000, 'D');
  6179. res.set_content(content, "text/plain");
  6180. });
  6181. },
  6182. [](Client &cli, const string &endpoint,
  6183. DownloadProgress progress_callback) {
  6184. return cli.Get(endpoint, progress_callback);
  6185. },
  6186. "/download", 1000u);
  6187. }
  6188. // Helper function for content receiver download progress tests
  6189. template <typename SetupHandler, typename ClientCall>
  6190. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6191. ClientCall &&client_call,
  6192. const string &endpoint,
  6193. size_t expected_content_size) {
  6194. Server svr;
  6195. setup_handler(svr);
  6196. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6197. auto se = detail::scope_exit([&] {
  6198. svr.stop();
  6199. t.join();
  6200. });
  6201. svr.wait_until_ready();
  6202. Client cli(HOST, PORT);
  6203. vector<uint64_t> progress_values;
  6204. string received_body;
  6205. auto res = client_call(
  6206. cli, endpoint,
  6207. [&](const char *data, size_t data_length) -> bool {
  6208. received_body.append(data, data_length);
  6209. return true;
  6210. },
  6211. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6212. progress_values.push_back(current);
  6213. return true;
  6214. });
  6215. ASSERT_TRUE(res);
  6216. EXPECT_EQ(200, res->status);
  6217. EXPECT_FALSE(progress_values.empty());
  6218. EXPECT_EQ(expected_content_size, received_body.size());
  6219. EXPECT_TRUE(res->body.empty());
  6220. }
  6221. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6222. TestContentReceiverDownloadProgress(
  6223. [](Server &svr) {
  6224. svr.Get("/download-receiver",
  6225. [](const Request & /*req*/, Response &res) {
  6226. string content(2000, 'R');
  6227. res.set_content(content, "text/plain");
  6228. });
  6229. },
  6230. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6231. DownloadProgress progress_callback) {
  6232. return cli.Get(endpoint, content_receiver, progress_callback);
  6233. },
  6234. "/download-receiver", 2000u);
  6235. }
  6236. TEST(StreamingTest, NoContentLengthStreaming) {
  6237. Server svr;
  6238. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6239. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6240. if (offset < 6) {
  6241. sink.os << (offset < 3 ? "a" : "b");
  6242. } else {
  6243. sink.done();
  6244. }
  6245. return true;
  6246. });
  6247. });
  6248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6249. auto listen_se = detail::scope_exit([&] {
  6250. svr.stop();
  6251. listen_thread.join();
  6252. ASSERT_FALSE(svr.is_running());
  6253. });
  6254. svr.wait_until_ready();
  6255. Client client(HOST, PORT);
  6256. auto get_thread = std::thread([&client]() {
  6257. std::string s;
  6258. auto res =
  6259. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6260. s += std::string(data, len);
  6261. return true;
  6262. });
  6263. ASSERT_TRUE(res);
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. EXPECT_EQ("aaabbb", s);
  6266. });
  6267. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6268. // Give GET time to get a few messages.
  6269. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6270. }
  6271. TEST(MountTest, Unmount) {
  6272. Server svr;
  6273. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6274. auto se = detail::scope_exit([&] {
  6275. svr.stop();
  6276. listen_thread.join();
  6277. ASSERT_FALSE(svr.is_running());
  6278. });
  6279. svr.wait_until_ready();
  6280. Client cli("localhost", PORT);
  6281. svr.set_mount_point("/mount2", "./www2");
  6282. auto res = cli.Get("/");
  6283. ASSERT_TRUE(res);
  6284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6285. res = cli.Get("/mount2/dir/test.html");
  6286. ASSERT_TRUE(res);
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. svr.set_mount_point("/", "./www");
  6289. res = cli.Get("/dir/");
  6290. ASSERT_TRUE(res);
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. svr.remove_mount_point("/");
  6293. res = cli.Get("/dir/");
  6294. ASSERT_TRUE(res);
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. svr.remove_mount_point("/mount2");
  6297. res = cli.Get("/mount2/dir/test.html");
  6298. ASSERT_TRUE(res);
  6299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6300. }
  6301. TEST(MountTest, Redicect) {
  6302. Server svr;
  6303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6304. auto se = detail::scope_exit([&] {
  6305. svr.stop();
  6306. listen_thread.join();
  6307. ASSERT_FALSE(svr.is_running());
  6308. });
  6309. svr.set_mount_point("/", "./www");
  6310. svr.wait_until_ready();
  6311. Client cli("localhost", PORT);
  6312. auto res = cli.Get("/dir/");
  6313. ASSERT_TRUE(res);
  6314. EXPECT_EQ(StatusCode::OK_200, res->status);
  6315. res = cli.Get("/dir");
  6316. ASSERT_TRUE(res);
  6317. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6318. res = cli.Get("/file");
  6319. ASSERT_TRUE(res);
  6320. EXPECT_EQ(StatusCode::OK_200, res->status);
  6321. res = cli.Get("/file/");
  6322. ASSERT_TRUE(res);
  6323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6324. cli.set_follow_location(true);
  6325. res = cli.Get("/dir");
  6326. ASSERT_TRUE(res);
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. }
  6329. TEST(MountTest, MultibytesPathName) {
  6330. Server svr;
  6331. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6332. auto se = detail::scope_exit([&] {
  6333. svr.stop();
  6334. listen_thread.join();
  6335. ASSERT_FALSE(svr.is_running());
  6336. });
  6337. svr.set_mount_point("/", "./www");
  6338. svr.wait_until_ready();
  6339. Client cli("localhost", PORT);
  6340. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6341. ASSERT_TRUE(res);
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6344. }
  6345. TEST(KeepAliveTest, ReadTimeout) {
  6346. Server svr;
  6347. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6348. std::this_thread::sleep_for(std::chrono::seconds(2));
  6349. res.set_content("a", "text/plain");
  6350. });
  6351. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6352. res.set_content("b", "text/plain");
  6353. });
  6354. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6355. auto se = detail::scope_exit([&] {
  6356. svr.stop();
  6357. listen_thread.join();
  6358. ASSERT_FALSE(svr.is_running());
  6359. });
  6360. svr.wait_until_ready();
  6361. Client cli("localhost", PORT);
  6362. cli.set_keep_alive(true);
  6363. cli.set_read_timeout(std::chrono::seconds(1));
  6364. auto resa = cli.Get("/a");
  6365. ASSERT_FALSE(resa);
  6366. EXPECT_EQ(Error::Read, resa.error());
  6367. auto resb = cli.Get("/b");
  6368. ASSERT_TRUE(resb);
  6369. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6370. EXPECT_EQ("b", resb->body);
  6371. }
  6372. TEST(KeepAliveTest, MaxCount) {
  6373. size_t keep_alive_max_count = 3;
  6374. Server svr;
  6375. svr.set_keep_alive_max_count(keep_alive_max_count);
  6376. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6377. res.set_content("Hello World!", "text/plain");
  6378. });
  6379. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6380. auto se = detail::scope_exit([&] {
  6381. svr.stop();
  6382. listen_thread.join();
  6383. ASSERT_FALSE(svr.is_running());
  6384. });
  6385. svr.wait_until_ready();
  6386. Client cli(HOST, PORT);
  6387. cli.set_keep_alive(true);
  6388. for (size_t i = 0; i < 5; i++) {
  6389. auto result = cli.Get("/hi");
  6390. ASSERT_TRUE(result);
  6391. EXPECT_EQ(StatusCode::OK_200, result->status);
  6392. if (i == keep_alive_max_count - 1) {
  6393. EXPECT_EQ("close", result->get_header_value("Connection"));
  6394. } else {
  6395. EXPECT_FALSE(result->has_header("Connection"));
  6396. }
  6397. }
  6398. }
  6399. TEST(KeepAliveTest, Issue1041) {
  6400. Server svr;
  6401. svr.set_keep_alive_timeout(3);
  6402. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6403. res.set_content("Hello World!", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. Client cli(HOST, PORT);
  6413. cli.set_keep_alive(true);
  6414. auto result = cli.Get("/hi");
  6415. ASSERT_TRUE(result);
  6416. EXPECT_EQ(StatusCode::OK_200, result->status);
  6417. std::this_thread::sleep_for(std::chrono::seconds(5));
  6418. result = cli.Get("/hi");
  6419. ASSERT_TRUE(result);
  6420. EXPECT_EQ(StatusCode::OK_200, result->status);
  6421. }
  6422. TEST(KeepAliveTest, Issue1959) {
  6423. Server svr;
  6424. svr.set_keep_alive_timeout(5);
  6425. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6426. res.set_content("a", "text/plain");
  6427. });
  6428. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6429. auto se = detail::scope_exit([&] {
  6430. if (!svr.is_running()) return;
  6431. svr.stop();
  6432. listen_thread.join();
  6433. ASSERT_FALSE(svr.is_running());
  6434. });
  6435. svr.wait_until_ready();
  6436. Client cli("localhost", PORT);
  6437. cli.set_keep_alive(true);
  6438. using namespace std::chrono;
  6439. auto start = steady_clock::now();
  6440. cli.Get("/a");
  6441. svr.stop();
  6442. listen_thread.join();
  6443. auto end = steady_clock::now();
  6444. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6445. EXPECT_LT(elapsed, 5000);
  6446. }
  6447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6448. TEST(KeepAliveTest, SSLClientReconnection) {
  6449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6450. ASSERT_TRUE(svr.is_valid());
  6451. svr.set_keep_alive_timeout(1);
  6452. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6453. res.set_content("Hello World!", "text/plain");
  6454. });
  6455. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. listen_thread.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. SSLClient cli(HOST, PORT);
  6463. cli.enable_server_certificate_verification(false);
  6464. cli.set_keep_alive(true);
  6465. auto result = cli.Get("/hi");
  6466. ASSERT_TRUE(result);
  6467. EXPECT_EQ(StatusCode::OK_200, result->status);
  6468. result = cli.Get("/hi");
  6469. ASSERT_TRUE(result);
  6470. EXPECT_EQ(StatusCode::OK_200, result->status);
  6471. std::this_thread::sleep_for(std::chrono::seconds(2));
  6472. // Recoonect
  6473. result = cli.Get("/hi");
  6474. ASSERT_TRUE(result);
  6475. EXPECT_EQ(StatusCode::OK_200, result->status);
  6476. result = cli.Get("/hi");
  6477. ASSERT_TRUE(result);
  6478. EXPECT_EQ(StatusCode::OK_200, result->status);
  6479. }
  6480. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6482. ASSERT_TRUE(svr.is_valid());
  6483. svr.set_keep_alive_timeout(1);
  6484. std::string content = "reconnect";
  6485. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6486. res.set_content("Hello World!", "text/plain");
  6487. });
  6488. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6489. auto se = detail::scope_exit([&] {
  6490. svr.stop();
  6491. listen_thread.join();
  6492. ASSERT_FALSE(svr.is_running());
  6493. });
  6494. svr.wait_until_ready();
  6495. SSLClient cli(HOST, PORT);
  6496. cli.enable_server_certificate_verification(false);
  6497. cli.set_keep_alive(true);
  6498. auto result = cli.Post(
  6499. "/hi", content.size(),
  6500. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6501. sink.write(content.c_str(), content.size());
  6502. return true;
  6503. },
  6504. "text/plain");
  6505. ASSERT_TRUE(result);
  6506. EXPECT_EQ(200, result->status);
  6507. std::this_thread::sleep_for(std::chrono::seconds(2));
  6508. // Recoonect
  6509. result = cli.Post(
  6510. "/hi", content.size(),
  6511. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6512. sink.write(content.c_str(), content.size());
  6513. return true;
  6514. },
  6515. "text/plain");
  6516. ASSERT_TRUE(result);
  6517. EXPECT_EQ(200, result->status);
  6518. result = cli.Post(
  6519. "/hi", content.size(),
  6520. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6521. sink.write(content.c_str(), content.size());
  6522. return true;
  6523. },
  6524. "text/plain");
  6525. ASSERT_TRUE(result);
  6526. EXPECT_EQ(200, result->status);
  6527. }
  6528. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6529. {
  6530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6531. ASSERT_TRUE(svr.is_valid());
  6532. svr.Get("/sni", [&](const Request &req, Response &res) {
  6533. std::string expected;
  6534. if (req.ssl) {
  6535. if (const char *sni =
  6536. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6537. expected = sni;
  6538. }
  6539. }
  6540. EXPECT_EQ(expected, req.get_param_value("expected"));
  6541. res.set_content("ok", "text/plain");
  6542. });
  6543. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6544. auto se = detail::scope_exit([&] {
  6545. svr.stop();
  6546. listen_thread.join();
  6547. ASSERT_FALSE(svr.is_running());
  6548. });
  6549. svr.wait_until_ready();
  6550. {
  6551. SSLClient cli("localhost", PORT);
  6552. cli.enable_server_certificate_verification(false);
  6553. auto res = cli.Get("/sni?expected=localhost");
  6554. ASSERT_TRUE(res);
  6555. }
  6556. {
  6557. SSLClient cli("::1", PORT);
  6558. cli.enable_server_certificate_verification(false);
  6559. auto res = cli.Get("/sni?expected=");
  6560. // NOTE: This may fail if the server is listening on IPv4 only
  6561. // (e.g., when localhost resolves to 127.0.0.1 only)
  6562. if (res) {
  6563. EXPECT_EQ(StatusCode::OK_200, res->status);
  6564. } else {
  6565. EXPECT_EQ(Error::Connection, res.error());
  6566. }
  6567. }
  6568. }
  6569. }
  6570. #endif
  6571. TEST(ClientProblemDetectionTest, ContentProvider) {
  6572. Server svr;
  6573. size_t content_length = 1024 * 1024;
  6574. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6575. res.set_content_provider(
  6576. content_length, "text/plain",
  6577. [&](size_t offset, size_t length, DataSink &sink) {
  6578. auto out_len = std::min(length, static_cast<size_t>(1024));
  6579. std::string out(out_len, '@');
  6580. sink.write(out.data(), out_len);
  6581. return offset < 4096;
  6582. },
  6583. [](bool success) { ASSERT_FALSE(success); });
  6584. });
  6585. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6586. res.set_content_provider(
  6587. 0, "text/plain",
  6588. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6589. EXPECT_TRUE(false);
  6590. return true;
  6591. },
  6592. [](bool success) { ASSERT_FALSE(success); });
  6593. });
  6594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6595. auto se = detail::scope_exit([&] {
  6596. svr.stop();
  6597. listen_thread.join();
  6598. ASSERT_FALSE(svr.is_running());
  6599. });
  6600. svr.wait_until_ready();
  6601. Client cli("localhost", PORT);
  6602. {
  6603. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6604. size_t /*data_length*/) { return false; });
  6605. ASSERT_FALSE(res);
  6606. }
  6607. {
  6608. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6609. size_t /*data_length*/) { return false; });
  6610. ASSERT_TRUE(res);
  6611. }
  6612. }
  6613. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6614. Server svr;
  6615. svr.set_error_handler([](Request const &, Response &res) -> void {
  6616. res.set_chunked_content_provider(
  6617. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6618. sink.os << "hello";
  6619. sink.os << "world";
  6620. sink.done();
  6621. return true;
  6622. });
  6623. });
  6624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6625. auto se = detail::scope_exit([&] {
  6626. svr.stop();
  6627. listen_thread.join();
  6628. ASSERT_FALSE(svr.is_running());
  6629. });
  6630. svr.wait_until_ready();
  6631. Client cli("localhost", PORT);
  6632. auto res = cli.Get("/");
  6633. ASSERT_TRUE(res);
  6634. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6635. EXPECT_EQ("helloworld", res->body);
  6636. }
  6637. TEST(LongPollingTest, ClientCloseDetection) {
  6638. Server svr;
  6639. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6640. res.set_chunked_content_provider(
  6641. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6642. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6643. sink.os << "hello";
  6644. auto count = 10;
  6645. while (count > 0 && sink.is_writable()) {
  6646. this_thread::sleep_for(chrono::milliseconds(10));
  6647. count--;
  6648. }
  6649. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6650. return true;
  6651. });
  6652. });
  6653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6654. auto se = detail::scope_exit([&] {
  6655. svr.stop();
  6656. listen_thread.join();
  6657. ASSERT_FALSE(svr.is_running());
  6658. });
  6659. svr.wait_until_ready();
  6660. Client cli("localhost", PORT);
  6661. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6662. EXPECT_EQ("hello", string(data, data_length));
  6663. return false; // close the socket immediately.
  6664. });
  6665. ASSERT_FALSE(res);
  6666. }
  6667. TEST(GetWithParametersTest, GetWithParameters) {
  6668. Server svr;
  6669. svr.Get("/", [&](const Request &req, Response &) {
  6670. EXPECT_EQ("world", req.get_param_value("hello"));
  6671. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6672. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6673. });
  6674. svr.Get("/params", [&](const Request &req, Response &) {
  6675. EXPECT_EQ("world", req.get_param_value("hello"));
  6676. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6677. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6678. });
  6679. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6680. EXPECT_EQ("resource-id", req.matches[1]);
  6681. EXPECT_EQ("foo", req.get_param_value("param1"));
  6682. EXPECT_EQ("bar", req.get_param_value("param2"));
  6683. });
  6684. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6685. EXPECT_EQ("user-id", req.path_params.at("id"));
  6686. EXPECT_EQ("foo", req.get_param_value("param1"));
  6687. EXPECT_EQ("bar", req.get_param_value("param2"));
  6688. });
  6689. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. listen_thread.join();
  6693. ASSERT_FALSE(svr.is_running());
  6694. });
  6695. svr.wait_until_ready();
  6696. {
  6697. Client cli(HOST, PORT);
  6698. Params params;
  6699. params.emplace("hello", "world");
  6700. params.emplace("hello2", "world2");
  6701. params.emplace("hello3", "world3");
  6702. auto res = cli.Get("/", params, Headers{});
  6703. ASSERT_TRUE(res);
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. }
  6706. {
  6707. Client cli(HOST, PORT);
  6708. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6709. ASSERT_TRUE(res);
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. }
  6712. {
  6713. Client cli(HOST, PORT);
  6714. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6715. ASSERT_TRUE(res);
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. }
  6718. {
  6719. Client cli(HOST, PORT);
  6720. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6721. ASSERT_TRUE(res);
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. }
  6725. TEST(GetWithParametersTest, GetWithParameters2) {
  6726. Server svr;
  6727. svr.Get("/", [&](const Request &req, Response &res) {
  6728. auto text = req.get_param_value("hello");
  6729. res.set_content(text, "text/plain");
  6730. });
  6731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6732. auto se = detail::scope_exit([&] {
  6733. svr.stop();
  6734. listen_thread.join();
  6735. ASSERT_FALSE(svr.is_running());
  6736. });
  6737. svr.wait_until_ready();
  6738. Client cli("localhost", PORT);
  6739. Params params;
  6740. params.emplace("hello", "world");
  6741. std::string body;
  6742. auto res = cli.Get("/", params, Headers{},
  6743. [&](const char *data, size_t data_length) {
  6744. body.append(data, data_length);
  6745. return true;
  6746. });
  6747. ASSERT_TRUE(res);
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. EXPECT_EQ("world", body);
  6750. }
  6751. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6752. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6753. auto host = "httpcan.org";
  6754. auto path = std::string{"/range/32"};
  6755. #else
  6756. auto host = "nghttp2.org";
  6757. auto path = std::string{"/httpbin/range/32"};
  6758. #endif
  6759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6760. SSLClient cli(host);
  6761. #else
  6762. Client cli(host);
  6763. #endif
  6764. cli.set_default_headers({make_range_header({{1, 10}})});
  6765. cli.set_connection_timeout(5);
  6766. {
  6767. auto res = cli.Get(path);
  6768. ASSERT_TRUE(res);
  6769. EXPECT_EQ("bcdefghijk", res->body);
  6770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6771. }
  6772. {
  6773. auto res = cli.Get(path);
  6774. ASSERT_TRUE(res);
  6775. EXPECT_EQ("bcdefghijk", res->body);
  6776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6777. }
  6778. }
  6779. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6780. Server svr;
  6781. svr.set_default_headers({{"Hello", "World"}});
  6782. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6783. res.set_content("ok", "text/plain");
  6784. });
  6785. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6786. auto se = detail::scope_exit([&] {
  6787. svr.stop();
  6788. listen_thread.join();
  6789. ASSERT_FALSE(svr.is_running());
  6790. });
  6791. svr.wait_until_ready();
  6792. Client cli("localhost", PORT);
  6793. auto res = cli.Get("/");
  6794. ASSERT_TRUE(res);
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("ok", res->body);
  6797. EXPECT_EQ("World", res->get_header_value("Hello"));
  6798. }
  6799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6800. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6802. ASSERT_TRUE(svr.is_valid());
  6803. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6804. std::this_thread::sleep_for(std::chrono::seconds(2));
  6805. res.set_content("a", "text/plain");
  6806. });
  6807. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6808. res.set_content("b", "text/plain");
  6809. });
  6810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6811. auto se = detail::scope_exit([&] {
  6812. svr.stop();
  6813. listen_thread.join();
  6814. ASSERT_FALSE(svr.is_running());
  6815. });
  6816. svr.wait_until_ready();
  6817. SSLClient cli("localhost", PORT);
  6818. cli.enable_server_certificate_verification(false);
  6819. cli.set_keep_alive(true);
  6820. cli.set_read_timeout(std::chrono::seconds(1));
  6821. auto resa = cli.Get("/a");
  6822. ASSERT_TRUE(!resa);
  6823. EXPECT_EQ(Error::Read, resa.error());
  6824. auto resb = cli.Get("/b");
  6825. ASSERT_TRUE(resb);
  6826. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6827. EXPECT_EQ("b", resb->body);
  6828. }
  6829. #endif
  6830. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6831. protected:
  6832. ServerTestWithAI_PASSIVE()
  6833. : cli_(HOST, PORT)
  6834. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6835. ,
  6836. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6837. #endif
  6838. {
  6839. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6840. cli_.enable_server_certificate_verification(false);
  6841. #endif
  6842. }
  6843. virtual void SetUp() {
  6844. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6845. res.set_content("Hello World!", "text/plain");
  6846. });
  6847. t_ = thread(
  6848. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6849. svr_.wait_until_ready();
  6850. }
  6851. virtual void TearDown() {
  6852. svr_.stop();
  6853. t_.join();
  6854. }
  6855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6856. SSLClient cli_;
  6857. SSLServer svr_;
  6858. #else
  6859. Client cli_;
  6860. Server svr_;
  6861. #endif
  6862. thread t_;
  6863. };
  6864. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6865. auto res = cli_.Get("/hi");
  6866. ASSERT_TRUE(res);
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ("Hello World!", res->body);
  6870. }
  6871. class ServerUpDownTest : public ::testing::Test {
  6872. protected:
  6873. ServerUpDownTest() : cli_(HOST, PORT) {}
  6874. virtual void SetUp() {
  6875. t_ = thread([&]() {
  6876. svr_.bind_to_any_port(HOST);
  6877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6878. ASSERT_TRUE(svr_.listen_after_bind());
  6879. });
  6880. svr_.wait_until_ready();
  6881. }
  6882. virtual void TearDown() {
  6883. svr_.stop();
  6884. t_.join();
  6885. }
  6886. Client cli_;
  6887. Server svr_;
  6888. thread t_;
  6889. };
  6890. TEST_F(ServerUpDownTest, QuickStartStop) {
  6891. // Should not crash, especially when run with
  6892. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6893. }
  6894. class PayloadMaxLengthTest : public ::testing::Test {
  6895. protected:
  6896. PayloadMaxLengthTest()
  6897. : cli_(HOST, PORT)
  6898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6899. ,
  6900. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6901. #endif
  6902. {
  6903. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6904. cli_.enable_server_certificate_verification(false);
  6905. #endif
  6906. }
  6907. virtual void SetUp() {
  6908. svr_.set_payload_max_length(8);
  6909. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6910. res.set_content("test", "text/plain");
  6911. });
  6912. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6913. svr_.wait_until_ready();
  6914. }
  6915. virtual void TearDown() {
  6916. svr_.stop();
  6917. t_.join();
  6918. }
  6919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6920. SSLClient cli_;
  6921. SSLServer svr_;
  6922. #else
  6923. Client cli_;
  6924. Server svr_;
  6925. #endif
  6926. thread t_;
  6927. };
  6928. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6929. auto res = cli_.Post("/test", "123456789", "text/plain");
  6930. ASSERT_TRUE(res);
  6931. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6932. res = cli_.Post("/test", "12345678", "text/plain");
  6933. ASSERT_TRUE(res);
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. }
  6936. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6937. // Test chunked encoding with payload exceeding the 8-byte limit
  6938. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6939. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6940. ASSERT_TRUE(res);
  6941. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6942. }
  6943. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6944. // Test chunked encoding with payload within the 8-byte limit
  6945. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6946. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6947. ASSERT_TRUE(res);
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6951. // Test using send_request to send chunked data exceeding payload limit
  6952. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6953. "Host: " +
  6954. std::string(HOST) + ":" + std::to_string(PORT) +
  6955. "\r\n"
  6956. "Transfer-Encoding: chunked\r\n"
  6957. "Connection: close\r\n"
  6958. "\r\n"
  6959. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6960. "0123456789\r\n"
  6961. "0\r\n" // End chunk
  6962. "\r\n";
  6963. std::string response;
  6964. bool result = send_request(1, chunked_request, &response);
  6965. if (!result) {
  6966. // If send_request fails, it might be because the server closed the
  6967. // connection due to payload limit enforcement, which is acceptable
  6968. SUCCEED()
  6969. << "Server rejected oversized chunked request (connection closed)";
  6970. } else {
  6971. // If we got a response, check if it's an error response or connection was
  6972. // closed early Short response length indicates connection was closed due to
  6973. // payload limit
  6974. if (response.length() <= 10) {
  6975. SUCCEED() << "Server closed connection for oversized chunked request";
  6976. } else {
  6977. // Check for error status codes
  6978. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6979. response.find("Payload Too Large") != std::string::npos ||
  6980. response.find("400") != std::string::npos);
  6981. }
  6982. }
  6983. }
  6984. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6985. // Test request without Content-Length header exceeding payload limit
  6986. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6987. "Host: " +
  6988. std::string(HOST) + ":" +
  6989. std::to_string(PORT) +
  6990. "\r\n"
  6991. "Connection: close\r\n"
  6992. "\r\n";
  6993. // Add payload exceeding the 8-byte limit
  6994. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6995. request_without_content_length += large_payload;
  6996. std::string response;
  6997. bool result = send_request(1, request_without_content_length, &response);
  6998. if (!result) {
  6999. // If send_request fails, server likely closed connection due to payload
  7000. // limit
  7001. SUCCEED() << "Server rejected oversized request without Content-Length "
  7002. "(connection closed)";
  7003. } else {
  7004. // Check if server responded with error or closed connection early
  7005. if (response.length() <= 10) {
  7006. SUCCEED() << "Server closed connection for oversized request without "
  7007. "Content-Length";
  7008. } else {
  7009. // Check for error status codes
  7010. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7011. response.find("Payload Too Large") != std::string::npos ||
  7012. response.find("400") != std::string::npos);
  7013. }
  7014. }
  7015. }
  7016. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7017. // Test request without Content-Length header within payload limit
  7018. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7019. "Host: " +
  7020. std::string(HOST) + ":" +
  7021. std::to_string(PORT) +
  7022. "\r\n"
  7023. "Connection: close\r\n"
  7024. "\r\n";
  7025. // Add payload within the 8-byte limit
  7026. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7027. request_without_content_length += small_payload;
  7028. std::string response;
  7029. bool result = send_request(1, request_without_content_length, &response);
  7030. // For requests without Content-Length, the server may have different behavior
  7031. // The key is that it should not reject due to payload limit for small
  7032. // payloads
  7033. if (result) {
  7034. // Check for any HTTP response (success or error, but not connection closed)
  7035. if (response.length() > 10) {
  7036. SUCCEED()
  7037. << "Server processed request without Content-Length within limit";
  7038. } else {
  7039. // Short response might indicate connection closed, which is acceptable
  7040. SUCCEED() << "Server closed connection for request without "
  7041. "Content-Length (acceptable behavior)";
  7042. }
  7043. } else {
  7044. // Connection failure might be due to protocol requirements
  7045. SUCCEED() << "Connection issue with request without Content-Length "
  7046. "(environment-specific)";
  7047. }
  7048. }
  7049. class LargePayloadMaxLengthTest : public ::testing::Test {
  7050. protected:
  7051. LargePayloadMaxLengthTest()
  7052. : cli_(HOST, PORT)
  7053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7054. ,
  7055. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7056. #endif
  7057. {
  7058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7059. cli_.enable_server_certificate_verification(false);
  7060. #endif
  7061. }
  7062. virtual void SetUp() {
  7063. // Set 10MB payload limit
  7064. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7065. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7066. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7067. res.set_content("Large payload test", "text/plain");
  7068. });
  7069. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7070. svr_.wait_until_ready();
  7071. }
  7072. virtual void TearDown() {
  7073. svr_.stop();
  7074. t_.join();
  7075. }
  7076. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7077. SSLClient cli_;
  7078. SSLServer svr_;
  7079. #else
  7080. Client cli_;
  7081. Server svr_;
  7082. #endif
  7083. thread t_;
  7084. };
  7085. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7086. // Test chunked encoding with payload within 10MB limit
  7087. std::string medium_payload(5 * 1024 * 1024,
  7088. 'A'); // 5MB payload, within 10MB limit
  7089. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7090. ASSERT_TRUE(res);
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. }
  7093. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7094. // Test chunked encoding with payload exceeding 10MB limit
  7095. std::string large_payload(12 * 1024 * 1024,
  7096. 'B'); // 12MB payload, exceeds 10MB limit
  7097. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7098. ASSERT_TRUE(res);
  7099. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7100. }
  7101. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7102. // Test request without Content-Length header within 10MB limit
  7103. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7104. "Host: " +
  7105. std::string(HOST) + ":" +
  7106. std::to_string(PORT) +
  7107. "\r\n"
  7108. "Connection: close\r\n"
  7109. "\r\n";
  7110. // Add 1MB payload (within 10MB limit)
  7111. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7112. request_without_content_length += medium_payload;
  7113. std::string response;
  7114. bool result = send_request(5, request_without_content_length, &response);
  7115. if (result) {
  7116. // Should get a proper HTTP response for payloads within limit
  7117. if (response.length() > 10) {
  7118. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7119. "10MB limit";
  7120. } else {
  7121. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7122. "Content-Length)";
  7123. }
  7124. } else {
  7125. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7126. }
  7127. }
  7128. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7129. // Test request without Content-Length header exceeding 10MB limit
  7130. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7131. "Host: " +
  7132. std::string(HOST) + ":" +
  7133. std::to_string(PORT) +
  7134. "\r\n"
  7135. "Connection: close\r\n"
  7136. "\r\n";
  7137. // Add 12MB payload (exceeds 10MB limit)
  7138. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7139. request_without_content_length += large_payload;
  7140. std::string response;
  7141. bool result = send_request(10, request_without_content_length, &response);
  7142. if (!result) {
  7143. // Server should close connection due to payload limit
  7144. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7145. "(connection closed)";
  7146. } else {
  7147. // Check for error response
  7148. if (response.length() <= 10) {
  7149. SUCCEED()
  7150. << "Server closed connection for 12MB request exceeding 10MB limit";
  7151. } else {
  7152. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7153. response.find("Payload Too Large") != std::string::npos ||
  7154. response.find("400") != std::string::npos);
  7155. }
  7156. }
  7157. }
  7158. TEST(HostAndPortPropertiesTest, NoSSL) {
  7159. httplib::Client cli("www.google.com", 1234);
  7160. ASSERT_EQ("www.google.com", cli.host());
  7161. ASSERT_EQ(1234, cli.port());
  7162. }
  7163. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7164. httplib::Client cli("www.google.com:1234");
  7165. ASSERT_EQ("www.google.com", cli.host());
  7166. ASSERT_EQ(1234, cli.port());
  7167. }
  7168. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7169. TEST(HostAndPortPropertiesTest, SSL) {
  7170. httplib::SSLClient cli("www.google.com");
  7171. ASSERT_EQ("www.google.com", cli.host());
  7172. ASSERT_EQ(443, cli.port());
  7173. }
  7174. #endif
  7175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7176. TEST(SSLClientTest, UpdateCAStore) {
  7177. httplib::SSLClient httplib_client("www.google.com");
  7178. auto ca_store_1 = X509_STORE_new();
  7179. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7180. nullptr);
  7181. httplib_client.set_ca_cert_store(ca_store_1);
  7182. auto ca_store_2 = X509_STORE_new();
  7183. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7184. nullptr);
  7185. httplib_client.set_ca_cert_store(ca_store_2);
  7186. }
  7187. TEST(SSLClientTest, ServerNameIndication_Online) {
  7188. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7189. auto host = "httpcan.org";
  7190. auto path = std::string{"/get"};
  7191. #else
  7192. auto host = "nghttp2.org";
  7193. auto path = std::string{"/httpbin/get"};
  7194. #endif
  7195. SSLClient cli(host, 443);
  7196. auto res = cli.Get(path);
  7197. ASSERT_TRUE(res);
  7198. ASSERT_EQ(StatusCode::OK_200, res->status);
  7199. }
  7200. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7201. // Use a site that will cause SSL verification failure due to self-signed cert
  7202. SSLClient cli("self-signed.badssl.com", 443);
  7203. cli.enable_server_certificate_verification(true);
  7204. auto res = cli.Get("/");
  7205. ASSERT_TRUE(!res);
  7206. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7207. // For SSL server verification errors, ssl_error should be 0, only
  7208. // ssl_openssl_error should be set
  7209. EXPECT_EQ(0, res.ssl_error());
  7210. // Verify OpenSSL error is captured for SSLServerVerification
  7211. // This occurs when SSL_get_verify_result() returns a verification failure
  7212. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7213. res.ssl_openssl_error());
  7214. }
  7215. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7216. // Use a site where hostname doesn't match the certificate
  7217. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7218. SSLClient cli("wrong.host.badssl.com", 443);
  7219. cli.enable_server_certificate_verification(true);
  7220. cli.enable_server_hostname_verification(true);
  7221. auto res = cli.Get("/");
  7222. ASSERT_TRUE(!res);
  7223. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7224. // For SSL hostname verification errors, ssl_error should be 0, only
  7225. // ssl_openssl_error should be set
  7226. EXPECT_EQ(0, res.ssl_error());
  7227. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7228. // This occurs when verify_host() fails due to hostname mismatch
  7229. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7230. res.ssl_openssl_error());
  7231. }
  7232. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7233. Client cli("https://google.com");
  7234. auto res = cli.Get("/");
  7235. ASSERT_TRUE(res);
  7236. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7237. }
  7238. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7239. SSLClient cli("google.com");
  7240. cli.set_ca_cert_path(CA_CERT_FILE);
  7241. auto res = cli.Get("/");
  7242. ASSERT_TRUE(res);
  7243. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7244. }
  7245. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7246. SSLClient cli("google.com");
  7247. cli.enable_server_certificate_verification(true);
  7248. cli.set_ca_cert_path("hello");
  7249. auto res = cli.Get("/");
  7250. ASSERT_TRUE(!res);
  7251. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7252. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7253. // should be set
  7254. EXPECT_EQ(0, res.ssl_error());
  7255. // Verify OpenSSL error is captured for SSLLoadingCerts
  7256. // This error occurs when SSL_CTX_load_verify_locations() fails
  7257. // > openssl errstr 0x80000002
  7258. // error:80000002:system library::No such file or directory
  7259. // > openssl errstr 0xA000126
  7260. // error:0A000126:SSL routines::unexpected eof while reading
  7261. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7262. res.ssl_openssl_error() == 0xA000126);
  7263. }
  7264. TEST(SSLClientTest, ServerCertificateVerification4) {
  7265. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7266. ASSERT_TRUE(svr.is_valid());
  7267. svr.Get("/test", [&](const Request &, Response &res) {
  7268. res.set_content("test", "text/plain");
  7269. svr.stop();
  7270. ASSERT_TRUE(true);
  7271. });
  7272. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7273. auto se = detail::scope_exit([&] {
  7274. t.join();
  7275. ASSERT_FALSE(svr.is_running());
  7276. });
  7277. svr.wait_until_ready();
  7278. SSLClient cli("127.0.0.1", PORT);
  7279. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7280. cli.enable_server_certificate_verification(true);
  7281. cli.set_connection_timeout(30);
  7282. auto res = cli.Get("/test");
  7283. ASSERT_TRUE(res);
  7284. ASSERT_EQ(StatusCode::OK_200, res->status);
  7285. }
  7286. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7287. std::string cert;
  7288. read_file(CA_CERT_FILE, cert);
  7289. SSLClient cli("google.com");
  7290. cli.load_ca_cert_store(cert.data(), cert.size());
  7291. const auto res = cli.Get("/");
  7292. ASSERT_TRUE(res);
  7293. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7294. }
  7295. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7296. // clang-format off
  7297. static constexpr char cert[] =
  7298. "GlobalSign Root CA\n"
  7299. "==================\n"
  7300. "-----BEGIN CERTIFICATE-----\n"
  7301. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7302. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7303. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7304. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7305. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7306. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7307. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7308. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7309. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7310. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7311. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7312. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7313. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7314. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7315. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7316. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7317. "-----END CERTIFICATE-----\n";
  7318. // clang-format on
  7319. SSLClient cli("google.com");
  7320. cli.load_ca_cert_store(cert, sizeof(cert));
  7321. const auto res = cli.Get("/");
  7322. ASSERT_TRUE(res);
  7323. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7324. }
  7325. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7326. SSLClient cli("www.youtube.com");
  7327. cli.set_ca_cert_path(CA_CERT_FILE);
  7328. cli.enable_server_certificate_verification(true);
  7329. cli.set_follow_location(true);
  7330. auto res = cli.Get("/");
  7331. ASSERT_TRUE(res);
  7332. ASSERT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST(SSLClientTest, Issue2004_Online) {
  7335. Client client("https://google.com");
  7336. client.set_follow_location(true);
  7337. auto res = client.Get("/");
  7338. ASSERT_TRUE(res);
  7339. ASSERT_EQ(StatusCode::OK_200, res->status);
  7340. auto body = res->body;
  7341. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7342. }
  7343. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7344. // Create SSLClient with invalid cert/key to make is_valid() return false
  7345. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7346. "nonexistent_key.pem");
  7347. // is_valid() should be false due to cert loading failure
  7348. ASSERT_FALSE(cli.is_valid());
  7349. auto res = cli.Get("/");
  7350. ASSERT_FALSE(res);
  7351. EXPECT_EQ(Error::SSLConnection, res.error());
  7352. }
  7353. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7354. // Test for Issue #2251: SSL error not properly reported when client cert
  7355. // and key paths are swapped or mismatched
  7356. // This simulates the scenario where user accidentally swaps the cert and key
  7357. // files
  7358. // Using client cert file as private key and vice versa (completely wrong)
  7359. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7360. // Should fail validation due to cert/key mismatch
  7361. ASSERT_FALSE(cli.is_valid());
  7362. // Attempt to make a request should fail with proper error
  7363. auto res = cli.Get("/");
  7364. ASSERT_FALSE(res);
  7365. EXPECT_EQ(Error::SSLConnection, res.error());
  7366. // SSL error should be recorded in the Result object (this is the key fix for
  7367. // Issue #2251)
  7368. auto openssl_error = res.ssl_openssl_error();
  7369. EXPECT_NE(0u, openssl_error);
  7370. }
  7371. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7372. // Another variant: using valid file paths but with mismatched cert/key pair
  7373. // This tests the case where files exist but contain incompatible key material
  7374. // Using client cert with wrong key (cert2 key)
  7375. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7376. // Should fail validation
  7377. ASSERT_FALSE(cli.is_valid());
  7378. auto res = cli.Get("/");
  7379. ASSERT_FALSE(res);
  7380. // Must report error properly, not appear as success
  7381. EXPECT_EQ(Error::SSLConnection, res.error());
  7382. // OpenSSL error should be captured in Result
  7383. EXPECT_NE(0u, res.ssl_openssl_error());
  7384. }
  7385. #if 0
  7386. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7387. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7388. ASSERT_TRUE(cli != nullptr);
  7389. cli->set_address_family(AF_INET6);
  7390. cli->set_interface("en0");
  7391. auto res = cli->Get("/get");
  7392. ASSERT_TRUE(res);
  7393. ASSERT_EQ(StatusCode::OK_200, res->status);
  7394. }
  7395. #endif
  7396. void ClientCertPresent(
  7397. const std::string &client_cert_file,
  7398. const std::string &client_private_key_file,
  7399. const std::string &client_encrypted_private_key_pass = std::string()) {
  7400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7401. CLIENT_CA_CERT_DIR);
  7402. ASSERT_TRUE(svr.is_valid());
  7403. svr.Get("/test", [&](const Request &req, Response &res) {
  7404. res.set_content("test", "text/plain");
  7405. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7406. ASSERT_TRUE(peer_cert != nullptr);
  7407. auto subject_name = X509_get_subject_name(peer_cert);
  7408. ASSERT_TRUE(subject_name != nullptr);
  7409. std::string common_name;
  7410. {
  7411. char name[BUFSIZ];
  7412. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7413. name, sizeof(name));
  7414. common_name.assign(name, static_cast<size_t>(name_len));
  7415. }
  7416. EXPECT_EQ("Common Name", common_name);
  7417. X509_free(peer_cert);
  7418. });
  7419. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7420. auto se = detail::scope_exit([&] {
  7421. svr.stop();
  7422. t.join();
  7423. ASSERT_FALSE(svr.is_running());
  7424. });
  7425. svr.wait_until_ready();
  7426. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7427. client_encrypted_private_key_pass);
  7428. cli.enable_server_certificate_verification(false);
  7429. cli.set_connection_timeout(30);
  7430. auto res = cli.Get("/test");
  7431. ASSERT_TRUE(res);
  7432. ASSERT_EQ(StatusCode::OK_200, res->status);
  7433. }
  7434. TEST(SSLClientServerTest, ClientCertPresent) {
  7435. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7436. }
  7437. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7438. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7439. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7440. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7441. }
  7442. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7443. void MemoryClientCertPresent(
  7444. const std::string &client_cert_file,
  7445. const std::string &client_private_key_file,
  7446. const std::string &client_encrypted_private_key_pass = std::string()) {
  7447. auto f = fopen(SERVER_CERT_FILE, "r+");
  7448. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7449. fclose(f);
  7450. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7451. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7452. fclose(f);
  7453. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7454. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7455. auto client_ca_cert_store = X509_STORE_new();
  7456. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7457. X509_free(client_cert);
  7458. fclose(f);
  7459. f = fopen(client_cert_file.c_str(), "r+");
  7460. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7461. fclose(f);
  7462. f = fopen(client_private_key_file.c_str(), "r+");
  7463. auto client_private_key = PEM_read_PrivateKey(
  7464. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7465. fclose(f);
  7466. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7467. ASSERT_TRUE(svr.is_valid());
  7468. svr.Get("/test", [&](const Request &req, Response &res) {
  7469. res.set_content("test", "text/plain");
  7470. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7471. ASSERT_TRUE(peer_cert != nullptr);
  7472. auto subject_name = X509_get_subject_name(peer_cert);
  7473. ASSERT_TRUE(subject_name != nullptr);
  7474. std::string common_name;
  7475. {
  7476. char name[BUFSIZ];
  7477. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7478. name, sizeof(name));
  7479. common_name.assign(name, static_cast<size_t>(name_len));
  7480. }
  7481. EXPECT_EQ("Common Name", common_name);
  7482. X509_free(peer_cert);
  7483. });
  7484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7485. auto se = detail::scope_exit([&] {
  7486. svr.stop();
  7487. t.join();
  7488. ASSERT_FALSE(svr.is_running());
  7489. });
  7490. svr.wait_until_ready();
  7491. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7492. client_encrypted_private_key_pass);
  7493. cli.enable_server_certificate_verification(false);
  7494. cli.set_connection_timeout(30);
  7495. auto res = cli.Get("/test");
  7496. ASSERT_TRUE(res);
  7497. ASSERT_EQ(StatusCode::OK_200, res->status);
  7498. X509_free(server_cert);
  7499. EVP_PKEY_free(server_private_key);
  7500. X509_free(client_cert);
  7501. EVP_PKEY_free(client_private_key);
  7502. }
  7503. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7504. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7505. }
  7506. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7507. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7508. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7509. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7510. }
  7511. #endif
  7512. TEST(SSLClientServerTest, ClientCertMissing) {
  7513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7514. CLIENT_CA_CERT_DIR);
  7515. ASSERT_TRUE(svr.is_valid());
  7516. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7517. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7518. auto se = detail::scope_exit([&] {
  7519. svr.stop();
  7520. t.join();
  7521. ASSERT_FALSE(svr.is_running());
  7522. });
  7523. svr.wait_until_ready();
  7524. SSLClient cli(HOST, PORT);
  7525. cli.set_connection_timeout(30);
  7526. auto res = cli.Get("/test");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7529. // For SSL server verification errors, ssl_error should be 0, only
  7530. // ssl_openssl_error should be set
  7531. EXPECT_EQ(0, res.ssl_error());
  7532. // Verify OpenSSL error is captured for SSLServerVerification
  7533. // Note: This test may have different error codes depending on the exact
  7534. // verification failure
  7535. EXPECT_NE(0UL, res.ssl_openssl_error());
  7536. }
  7537. TEST(SSLClientServerTest, TrustDirOptional) {
  7538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7539. ASSERT_TRUE(svr.is_valid());
  7540. svr.Get("/test", [&](const Request &, Response &res) {
  7541. res.set_content("test", "text/plain");
  7542. });
  7543. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7544. auto se = detail::scope_exit([&] {
  7545. svr.stop();
  7546. t.join();
  7547. ASSERT_FALSE(svr.is_running());
  7548. });
  7549. svr.wait_until_ready();
  7550. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7551. cli.enable_server_certificate_verification(false);
  7552. cli.set_connection_timeout(30);
  7553. auto res = cli.Get("/test");
  7554. ASSERT_TRUE(res);
  7555. ASSERT_EQ(StatusCode::OK_200, res->status);
  7556. }
  7557. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7558. class NoListenSSLServer : public SSLServer {
  7559. public:
  7560. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7561. const char *client_ca_cert_file_path,
  7562. const char *client_ca_cert_dir_path = nullptr)
  7563. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7564. client_ca_cert_dir_path),
  7565. stop_(false) {}
  7566. std::atomic_bool stop_;
  7567. private:
  7568. bool process_and_close_socket(socket_t /*sock*/) override {
  7569. // Don't create SSL context
  7570. while (!stop_.load()) {
  7571. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7572. }
  7573. return true;
  7574. }
  7575. };
  7576. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7577. CLIENT_CA_CERT_FILE);
  7578. ASSERT_TRUE(svr.is_valid());
  7579. svr.Get("/test", [&](const Request &, Response &res) {
  7580. res.set_content("test", "text/plain");
  7581. });
  7582. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7583. auto se = detail::scope_exit([&] {
  7584. svr.stop_ = true;
  7585. svr.stop();
  7586. t.join();
  7587. ASSERT_FALSE(svr.is_running());
  7588. });
  7589. svr.wait_until_ready();
  7590. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7591. cli.enable_server_certificate_verification(false);
  7592. cli.set_connection_timeout(1);
  7593. auto res = cli.Get("/test");
  7594. ASSERT_TRUE(!res);
  7595. EXPECT_EQ(Error::SSLConnection, res.error());
  7596. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7597. }
  7598. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7599. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7600. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7601. SSL_CTX_set_options(&ssl_ctx,
  7602. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7603. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7604. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7605. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7606. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7607. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7608. "ECDHE-DSS-AES128-SHA256:"
  7609. "ECDHE-RSA-AES256-SHA256:"
  7610. "ECDHE-DSS-AES256-SHA256:";
  7611. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7612. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7613. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7614. SSL_FILETYPE_PEM) != 1) {
  7615. return false;
  7616. }
  7617. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7618. CLIENT_CA_CERT_DIR);
  7619. SSL_CTX_set_verify(
  7620. &ssl_ctx,
  7621. SSL_VERIFY_PEER |
  7622. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7623. nullptr);
  7624. return true;
  7625. };
  7626. SSLServer svr(setup_ssl_ctx_callback);
  7627. ASSERT_TRUE(svr.is_valid());
  7628. svr.Get("/test", [&](const Request &req, Response &res) {
  7629. res.set_content("test", "text/plain");
  7630. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7631. ASSERT_TRUE(peer_cert != nullptr);
  7632. auto subject_name = X509_get_subject_name(peer_cert);
  7633. ASSERT_TRUE(subject_name != nullptr);
  7634. std::string common_name;
  7635. {
  7636. char name[BUFSIZ];
  7637. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7638. name, sizeof(name));
  7639. common_name.assign(name, static_cast<size_t>(name_len));
  7640. }
  7641. EXPECT_EQ("Common Name", common_name);
  7642. X509_free(peer_cert);
  7643. });
  7644. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7645. auto se = detail::scope_exit([&] {
  7646. svr.stop();
  7647. t.join();
  7648. ASSERT_FALSE(svr.is_running());
  7649. });
  7650. svr.wait_until_ready();
  7651. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7652. cli.enable_server_certificate_verification(false);
  7653. cli.set_connection_timeout(30);
  7654. auto res = cli.Get("/test");
  7655. ASSERT_TRUE(res);
  7656. ASSERT_EQ(StatusCode::OK_200, res->status);
  7657. }
  7658. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7660. ASSERT_TRUE(svr.is_valid());
  7661. // Set up a handler to verify client certificate is present
  7662. bool client_cert_verified = false;
  7663. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7664. // Verify that client certificate was provided
  7665. client_cert_verified = true;
  7666. res.set_content("success", "text/plain");
  7667. });
  7668. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7669. auto se = detail::scope_exit([&] {
  7670. svr.stop();
  7671. t.join();
  7672. ASSERT_FALSE(svr.is_running());
  7673. });
  7674. svr.wait_until_ready();
  7675. // Client with certificate
  7676. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7677. cli.enable_server_certificate_verification(false);
  7678. cli.set_connection_timeout(30);
  7679. auto res = cli.Get("/test");
  7680. ASSERT_TRUE(res);
  7681. ASSERT_EQ(StatusCode::OK_200, res->status);
  7682. ASSERT_TRUE(client_cert_verified);
  7683. EXPECT_EQ("success", res->body);
  7684. }
  7685. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7686. // Test that when client CA cert file is provided,
  7687. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7688. // Create a server with client authentication
  7689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7690. ASSERT_TRUE(svr.is_valid());
  7691. // We can't directly access the SSL_CTX from SSLServer to verify,
  7692. // but we can test that the server properly requests client certificates
  7693. // and accepts valid ones from the specified CA
  7694. bool handler_called = false;
  7695. svr.Get("/test", [&](const Request &req, Response &res) {
  7696. handler_called = true;
  7697. // Verify that a client certificate was provided
  7698. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7699. ASSERT_TRUE(peer_cert != nullptr);
  7700. // Get the issuer name
  7701. auto issuer_name = X509_get_issuer_name(peer_cert);
  7702. ASSERT_TRUE(issuer_name != nullptr);
  7703. char issuer_buf[256];
  7704. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7705. // The client certificate should be issued by our test CA
  7706. std::string issuer_str(issuer_buf);
  7707. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7708. X509_free(peer_cert);
  7709. res.set_content("authenticated", "text/plain");
  7710. });
  7711. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7712. auto se = detail::scope_exit([&] {
  7713. svr.stop();
  7714. t.join();
  7715. ASSERT_FALSE(svr.is_running());
  7716. });
  7717. svr.wait_until_ready();
  7718. // Connect with a client certificate issued by the CA
  7719. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7720. cli.enable_server_certificate_verification(false);
  7721. cli.set_connection_timeout(30);
  7722. auto res = cli.Get("/test");
  7723. ASSERT_TRUE(res);
  7724. ASSERT_EQ(StatusCode::OK_200, res->status);
  7725. ASSERT_TRUE(handler_called);
  7726. EXPECT_EQ("authenticated", res->body);
  7727. }
  7728. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7729. // Test 1: Valid CA file - no error should be recorded
  7730. {
  7731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7732. CLIENT_CA_CERT_FILE);
  7733. ASSERT_TRUE(svr.is_valid());
  7734. // With valid setup, last_ssl_error should be 0
  7735. EXPECT_EQ(0, svr.ssl_last_error());
  7736. }
  7737. // Test 2: Invalid CA file content
  7738. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7739. {
  7740. // Create a temporary file with completely invalid content
  7741. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7742. {
  7743. std::ofstream ofs(temp_invalid_ca);
  7744. ofs << "This is not a certificate file at all\n";
  7745. ofs << "Just plain text content\n";
  7746. }
  7747. // Create server with invalid CA file
  7748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7749. // Clean up temporary file
  7750. std::remove(temp_invalid_ca);
  7751. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7752. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7753. // Note: SSL_CTX_load_verify_locations typically fails first,
  7754. // but our error handling code path is still exercised
  7755. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7756. }
  7757. }
  7758. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7759. // Test SSL server using X509_STORE constructor with client CA certificates
  7760. // This test verifies that Phase 2 implementation correctly extracts CA names
  7761. // from an X509_STORE and sets them in the SSL context
  7762. // Load the CA certificate into memory
  7763. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7764. ASSERT_NE(nullptr, bio);
  7765. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7766. BIO_free(bio);
  7767. ASSERT_NE(nullptr, ca_cert);
  7768. // Create an X509_STORE and add the CA certificate
  7769. auto store = X509_STORE_new();
  7770. ASSERT_NE(nullptr, store);
  7771. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7772. // Load server certificate and private key
  7773. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7774. ASSERT_NE(nullptr, cert_bio);
  7775. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7776. BIO_free(cert_bio);
  7777. ASSERT_NE(nullptr, server_cert);
  7778. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7779. ASSERT_NE(nullptr, key_bio);
  7780. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7781. BIO_free(key_bio);
  7782. ASSERT_NE(nullptr, server_key);
  7783. // Create SSLServer with X509_STORE constructor
  7784. // Note: X509_STORE ownership is transferred to SSL_CTX
  7785. SSLServer svr(server_cert, server_key, store);
  7786. ASSERT_TRUE(svr.is_valid());
  7787. // No SSL error should be recorded for valid setup
  7788. EXPECT_EQ(0, svr.ssl_last_error());
  7789. // Set up server endpoints
  7790. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7791. res.set_content("ok", "text/plain");
  7792. });
  7793. // Start server in a thread
  7794. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7795. svr.wait_until_ready();
  7796. // Connect with client certificate (using constructor with paths)
  7797. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7798. cli.enable_server_certificate_verification(false);
  7799. auto res = cli.Get("/test-x509store");
  7800. ASSERT_TRUE(res);
  7801. EXPECT_EQ(200, res->status);
  7802. EXPECT_EQ("ok", res->body);
  7803. // Clean up
  7804. X509_free(server_cert);
  7805. EVP_PKEY_free(server_key);
  7806. X509_free(ca_cert);
  7807. svr.stop();
  7808. server_thread.join();
  7809. }
  7810. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7811. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7812. // prepare large data
  7813. std::random_device seed_gen;
  7814. std::mt19937 random(seed_gen());
  7815. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7816. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7817. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7818. // server
  7819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7820. ASSERT_TRUE(svr.is_valid());
  7821. svr.Post("/binary", [&](const Request &req, Response &res) {
  7822. EXPECT_EQ(large_size_byte, req.body.size());
  7823. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7824. res.set_content(req.body, "application/octet-stream");
  7825. });
  7826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7827. auto se = detail::scope_exit([&] {
  7828. svr.stop();
  7829. listen_thread.join();
  7830. ASSERT_FALSE(svr.is_running());
  7831. });
  7832. svr.wait_until_ready();
  7833. // client POST
  7834. SSLClient cli("localhost", PORT);
  7835. cli.enable_server_certificate_verification(false);
  7836. cli.set_read_timeout(std::chrono::seconds(100));
  7837. cli.set_write_timeout(std::chrono::seconds(100));
  7838. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7839. large_size_byte, "application/octet-stream");
  7840. // compare
  7841. EXPECT_EQ(StatusCode::OK_200, res->status);
  7842. EXPECT_EQ(large_size_byte, res->body.size());
  7843. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7844. }
  7845. #endif
  7846. #ifdef _WIN32
  7847. TEST(CleanupTest, WSACleanup) {
  7848. int ret = WSACleanup();
  7849. ASSERT_EQ(0, ret);
  7850. }
  7851. #endif
  7852. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7853. TEST(NoSSLSupport, SimpleInterface) {
  7854. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7855. }
  7856. #endif
  7857. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7858. TEST(InvalidScheme, SimpleInterface) {
  7859. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7860. }
  7861. #endif
  7862. TEST(NoScheme, SimpleInterface) {
  7863. Client cli("yahoo.com:80");
  7864. ASSERT_TRUE(cli.is_valid());
  7865. }
  7866. TEST(SendAPI, SimpleInterface_Online) {
  7867. Client cli("http://yahoo.com");
  7868. Request req;
  7869. req.method = "GET";
  7870. req.path = "/";
  7871. auto res = cli.send(req);
  7872. ASSERT_TRUE(res);
  7873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7874. }
  7875. TEST(SendAPI, WithParamsInRequest) {
  7876. Server svr;
  7877. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7878. EXPECT_TRUE(req.has_param("test"));
  7879. EXPECT_EQ("test_value", req.get_param_value("test"));
  7880. });
  7881. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7882. auto se = detail::scope_exit([&] {
  7883. svr.stop();
  7884. t.join();
  7885. ASSERT_FALSE(svr.is_running());
  7886. });
  7887. svr.wait_until_ready();
  7888. Client cli(HOST, PORT);
  7889. {
  7890. Request req;
  7891. req.method = "GET";
  7892. req.path = "/";
  7893. req.params.emplace("test", "test_value");
  7894. auto res = cli.send(req);
  7895. ASSERT_TRUE(res);
  7896. }
  7897. {
  7898. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7899. ASSERT_TRUE(res);
  7900. }
  7901. }
  7902. TEST(ClientImplMethods, GetSocketTest) {
  7903. httplib::Server svr;
  7904. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7905. res.status = StatusCode::OK_200;
  7906. });
  7907. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7908. auto se = detail::scope_exit([&] {
  7909. svr.stop();
  7910. thread.join();
  7911. ASSERT_FALSE(svr.is_running());
  7912. });
  7913. svr.wait_until_ready();
  7914. {
  7915. httplib::Client cli("http://127.0.0.1:3333");
  7916. cli.set_keep_alive(true);
  7917. // Use the behavior of cpp-httplib of opening the connection
  7918. // only when the first request happens. If that changes,
  7919. // this test would be obsolete.
  7920. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7921. // This also implicitly tests the server. But other tests would fail much
  7922. // earlier than this one to be considered.
  7923. auto res = cli.Get("/");
  7924. ASSERT_TRUE(res);
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7927. }
  7928. }
  7929. // Disabled due to out-of-memory problem on GitHub Actions
  7930. #ifdef _WIN64
  7931. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7932. // allocate content size larger than 2GB in memory
  7933. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7934. char *content = (char *)malloc(content_size);
  7935. ASSERT_TRUE(content);
  7936. Server svr;
  7937. svr.Get("/foo",
  7938. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7939. res.set_content(content, content_size, "application/octet-stream");
  7940. });
  7941. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7942. auto se = detail::scope_exit([&] {
  7943. svr.stop();
  7944. listen_thread.join();
  7945. if (content) free(content);
  7946. ASSERT_FALSE(svr.is_running());
  7947. });
  7948. svr.wait_until_ready();
  7949. Client cli(HOST, PORT);
  7950. auto res = cli.Get("/foo");
  7951. ASSERT_TRUE(res);
  7952. EXPECT_EQ(StatusCode::OK_200, res->status);
  7953. EXPECT_EQ(content_size, res->body.length());
  7954. }
  7955. #endif
  7956. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7957. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7958. Client cli("http://yahoo.com");
  7959. auto res = cli.Get("/");
  7960. ASSERT_TRUE(res);
  7961. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7962. cli.set_follow_location(true);
  7963. res = cli.Get("/");
  7964. ASSERT_TRUE(res);
  7965. EXPECT_EQ(StatusCode::OK_200, res->status);
  7966. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7967. }
  7968. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7969. Client cli("https://yahoo.com");
  7970. auto res = cli.Get("/");
  7971. ASSERT_TRUE(res);
  7972. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7973. cli.set_follow_location(true);
  7974. res = cli.Get("/");
  7975. ASSERT_TRUE(res);
  7976. EXPECT_EQ(StatusCode::OK_200, res->status);
  7977. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7978. }
  7979. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7980. Client cli("https://yahoo.com");
  7981. auto res = cli.Get("/");
  7982. ASSERT_TRUE(res);
  7983. ASSERT_FALSE(!res);
  7984. ASSERT_TRUE(res);
  7985. ASSERT_FALSE(res == nullptr);
  7986. ASSERT_TRUE(res != nullptr);
  7987. EXPECT_EQ(Error::Success, res.error());
  7988. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7989. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7990. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7991. cli.set_follow_location(true);
  7992. res = cli.Get("/");
  7993. ASSERT_TRUE(res);
  7994. EXPECT_EQ(Error::Success, res.error());
  7995. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7996. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7999. }
  8000. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8001. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8002. Client cli("https://cdnjs.cloudflare.com");
  8003. auto res =
  8004. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8005. ASSERT_TRUE(res);
  8006. EXPECT_EQ(StatusCode::OK_200, res->status);
  8007. EXPECT_EQ(287630U, res->body.size());
  8008. EXPECT_EQ("application/javascript; charset=utf-8",
  8009. res->get_header_value("Content-Type"));
  8010. }
  8011. #endif
  8012. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8013. #undef REDIR_HOST // Silence compiler warning
  8014. #define REDIR_HOST "https://httpbingo.org"
  8015. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8016. Client cli(REDIR_HOST);
  8017. cli.set_follow_location(true);
  8018. auto res =
  8019. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8020. ASSERT_TRUE(res);
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. }
  8023. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8024. Client cli(REDIR_HOST);
  8025. cli.set_follow_location(true);
  8026. Params params;
  8027. params.emplace("url", "http://example.com");
  8028. params.emplace("status_code", "302");
  8029. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8030. ASSERT_TRUE(res);
  8031. EXPECT_EQ(StatusCode::OK_200, res->status);
  8032. }
  8033. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8034. Client cli(REDIR_HOST);
  8035. cli.set_follow_location(true);
  8036. Params params;
  8037. params.emplace("url", "http://example.com");
  8038. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8039. ASSERT_TRUE(res);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST(HttpToHttpsRedirectTest, CertFile) {
  8043. Server svr;
  8044. ASSERT_TRUE(svr.is_valid());
  8045. svr.Get("/index", [&](const Request &, Response &res) {
  8046. res.set_redirect("https://127.0.0.1:1235/index");
  8047. svr.stop();
  8048. });
  8049. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8050. ASSERT_TRUE(ssl_svr.is_valid());
  8051. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8052. res.set_content("test", "text/plain");
  8053. ssl_svr.stop();
  8054. });
  8055. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8056. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8057. auto se = detail::scope_exit([&] {
  8058. t2.join();
  8059. t.join();
  8060. ASSERT_FALSE(svr.is_running());
  8061. });
  8062. svr.wait_until_ready();
  8063. ssl_svr.wait_until_ready();
  8064. Client cli("127.0.0.1", PORT);
  8065. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8066. cli.enable_server_certificate_verification(true);
  8067. cli.set_follow_location(true);
  8068. cli.set_connection_timeout(30);
  8069. auto res = cli.Get("/index");
  8070. ASSERT_TRUE(res);
  8071. ASSERT_EQ(StatusCode::OK_200, res->status);
  8072. }
  8073. TEST(SSLClientRedirectTest, CertFile) {
  8074. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8075. ASSERT_TRUE(ssl_svr1.is_valid());
  8076. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8077. res.set_redirect("https://127.0.0.1:1235/index");
  8078. ssl_svr1.stop();
  8079. });
  8080. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8081. ASSERT_TRUE(ssl_svr2.is_valid());
  8082. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8083. res.set_content("test", "text/plain");
  8084. ssl_svr2.stop();
  8085. });
  8086. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8087. thread t2 =
  8088. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8089. auto se = detail::scope_exit([&] {
  8090. t2.join();
  8091. t.join();
  8092. ASSERT_FALSE(ssl_svr1.is_running());
  8093. });
  8094. ssl_svr1.wait_until_ready();
  8095. ssl_svr2.wait_until_ready();
  8096. SSLClient cli("127.0.0.1", PORT);
  8097. std::string cert;
  8098. read_file(SERVER_CERT2_FILE, cert);
  8099. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8100. cli.enable_server_certificate_verification(true);
  8101. cli.set_follow_location(true);
  8102. cli.set_connection_timeout(30);
  8103. auto res = cli.Get("/index");
  8104. ASSERT_TRUE(res);
  8105. ASSERT_EQ(StatusCode::OK_200, res->status);
  8106. }
  8107. // Test that set_ca_cert_store() skips system certs (consistent with
  8108. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  8109. // should be trusted - system certs should NOT be loaded.
  8110. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  8111. // Load a specific cert that is NOT a system CA cert
  8112. std::string cert;
  8113. read_file(SERVER_CERT2_FILE, cert);
  8114. SSLClient cli("google.com");
  8115. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8116. cli.enable_server_certificate_verification(true);
  8117. // This should FAIL because:
  8118. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  8119. // 2. System certs should NOT be loaded when custom store is set
  8120. // If system certs WERE loaded, this would succeed
  8121. auto res = cli.Get("/");
  8122. ASSERT_FALSE(res);
  8123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8124. }
  8125. TEST(MultipartFormDataTest, LargeData) {
  8126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8127. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8128. const ContentReader &content_reader) {
  8129. if (req.is_multipart_form_data()) {
  8130. std::vector<FormData> items;
  8131. content_reader(
  8132. [&](const FormData &file) {
  8133. items.push_back(file);
  8134. return true;
  8135. },
  8136. [&](const char *data, size_t data_length) {
  8137. items.back().content.append(data, data_length);
  8138. return true;
  8139. });
  8140. EXPECT_TRUE(std::string(items[0].name) == "document");
  8141. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8142. EXPECT_TRUE(items[0].filename == "2MB_data");
  8143. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8144. EXPECT_TRUE(items[1].name == "hello");
  8145. EXPECT_TRUE(items[1].content == "world");
  8146. EXPECT_TRUE(items[1].filename == "");
  8147. EXPECT_TRUE(items[1].content_type == "");
  8148. } else {
  8149. std::string body;
  8150. content_reader([&](const char *data, size_t data_length) {
  8151. body.append(data, data_length);
  8152. return true;
  8153. });
  8154. }
  8155. });
  8156. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8157. auto se = detail::scope_exit([&] {
  8158. svr.stop();
  8159. t.join();
  8160. ASSERT_FALSE(svr.is_running());
  8161. });
  8162. svr.wait_until_ready();
  8163. {
  8164. std::string data(1024 * 1024 * 2, '.');
  8165. std::stringstream buffer;
  8166. buffer << data;
  8167. Client cli("https://localhost:8080");
  8168. cli.enable_server_certificate_verification(false);
  8169. UploadFormDataItems items{
  8170. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8171. {"hello", "world", "", ""},
  8172. };
  8173. auto res = cli.Post("/post", items);
  8174. ASSERT_TRUE(res);
  8175. ASSERT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. }
  8178. TEST(MultipartFormDataTest, DataProviderItems) {
  8179. std::random_device seed_gen;
  8180. std::mt19937 random(seed_gen());
  8181. std::string rand1;
  8182. rand1.resize(1000);
  8183. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8184. std::string rand2;
  8185. rand2.resize(3000);
  8186. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8188. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8189. const ContentReader &content_reader) {
  8190. ASSERT_FALSE(req.is_multipart_form_data());
  8191. std::string body;
  8192. content_reader([&](const char *data, size_t data_length) {
  8193. body.append(data, data_length);
  8194. return true;
  8195. });
  8196. EXPECT_EQ(body, "");
  8197. });
  8198. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8199. const ContentReader &content_reader) {
  8200. ASSERT_TRUE(req.is_multipart_form_data());
  8201. std::vector<FormData> items;
  8202. content_reader(
  8203. [&](const FormData &file) {
  8204. items.push_back(file);
  8205. return true;
  8206. },
  8207. [&](const char *data, size_t data_length) {
  8208. items.back().content.append(data, data_length);
  8209. return true;
  8210. });
  8211. ASSERT_TRUE(items.size() == 2);
  8212. EXPECT_EQ(std::string(items[0].name), "name1");
  8213. EXPECT_EQ(items[0].content, "Testing123");
  8214. EXPECT_EQ(items[0].filename, "filename1");
  8215. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8216. EXPECT_EQ(items[1].name, "name2");
  8217. EXPECT_EQ(items[1].content, "Testing456");
  8218. EXPECT_EQ(items[1].filename, "");
  8219. EXPECT_EQ(items[1].content_type, "");
  8220. });
  8221. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8222. const ContentReader &content_reader) {
  8223. ASSERT_TRUE(req.is_multipart_form_data());
  8224. std::vector<FormData> items;
  8225. content_reader(
  8226. [&](const FormData &file) {
  8227. items.push_back(file);
  8228. return true;
  8229. },
  8230. [&](const char *data, size_t data_length) {
  8231. items.back().content.append(data, data_length);
  8232. return true;
  8233. });
  8234. ASSERT_TRUE(items.size() == 2);
  8235. EXPECT_EQ(items[0].name, "name3");
  8236. EXPECT_EQ(items[0].content, rand1);
  8237. EXPECT_EQ(items[0].filename, "filename3");
  8238. EXPECT_EQ(items[0].content_type, "");
  8239. EXPECT_EQ(items[1].name, "name4");
  8240. EXPECT_EQ(items[1].content, rand2);
  8241. EXPECT_EQ(items[1].filename, "filename4");
  8242. EXPECT_EQ(items[1].content_type, "");
  8243. });
  8244. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8245. const ContentReader &content_reader) {
  8246. ASSERT_TRUE(req.is_multipart_form_data());
  8247. std::vector<FormData> items;
  8248. content_reader(
  8249. [&](const FormData &file) {
  8250. items.push_back(file);
  8251. return true;
  8252. },
  8253. [&](const char *data, size_t data_length) {
  8254. items.back().content.append(data, data_length);
  8255. return true;
  8256. });
  8257. ASSERT_TRUE(items.size() == 4);
  8258. EXPECT_EQ(std::string(items[0].name), "name1");
  8259. EXPECT_EQ(items[0].content, "Testing123");
  8260. EXPECT_EQ(items[0].filename, "filename1");
  8261. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8262. EXPECT_EQ(items[1].name, "name2");
  8263. EXPECT_EQ(items[1].content, "Testing456");
  8264. EXPECT_EQ(items[1].filename, "");
  8265. EXPECT_EQ(items[1].content_type, "");
  8266. EXPECT_EQ(items[2].name, "name3");
  8267. EXPECT_EQ(items[2].content, rand1);
  8268. EXPECT_EQ(items[2].filename, "filename3");
  8269. EXPECT_EQ(items[2].content_type, "");
  8270. EXPECT_EQ(items[3].name, "name4");
  8271. EXPECT_EQ(items[3].content, rand2);
  8272. EXPECT_EQ(items[3].filename, "filename4");
  8273. EXPECT_EQ(items[3].content_type, "");
  8274. });
  8275. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8276. auto se = detail::scope_exit([&] {
  8277. svr.stop();
  8278. t.join();
  8279. ASSERT_FALSE(svr.is_running());
  8280. });
  8281. svr.wait_until_ready();
  8282. {
  8283. Client cli("https://localhost:8080");
  8284. cli.enable_server_certificate_verification(false);
  8285. UploadFormDataItems items{
  8286. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8287. {"name2", "Testing456", "", ""}, // not a file
  8288. };
  8289. {
  8290. auto res = cli.Post("/post-none", {}, {}, {});
  8291. ASSERT_TRUE(res);
  8292. ASSERT_EQ(StatusCode::OK_200, res->status);
  8293. }
  8294. FormDataProviderItems providers;
  8295. {
  8296. auto res =
  8297. cli.Post("/post-items", {}, items, providers); // empty providers
  8298. ASSERT_TRUE(res);
  8299. ASSERT_EQ(StatusCode::OK_200, res->status);
  8300. }
  8301. providers.push_back({"name3",
  8302. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8303. // test the offset is given correctly at each step
  8304. if (!offset)
  8305. sink.os.write(rand1.data(), 30);
  8306. else if (offset == 30)
  8307. sink.os.write(rand1.data() + 30, 300);
  8308. else if (offset == 330)
  8309. sink.os.write(rand1.data() + 330, 670);
  8310. else if (offset == rand1.size())
  8311. sink.done();
  8312. return true;
  8313. },
  8314. "filename3",
  8315. {}});
  8316. providers.push_back({"name4",
  8317. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8318. // test the offset is given correctly at each step
  8319. if (!offset)
  8320. sink.os.write(rand2.data(), 2000);
  8321. else if (offset == 2000)
  8322. sink.os.write(rand2.data() + 2000, 1);
  8323. else if (offset == 2001)
  8324. sink.os.write(rand2.data() + 2001, 999);
  8325. else if (offset == rand2.size())
  8326. sink.done();
  8327. return true;
  8328. },
  8329. "filename4",
  8330. {}});
  8331. {
  8332. auto res = cli.Post("/post-providers", {}, {}, providers);
  8333. ASSERT_TRUE(res);
  8334. ASSERT_EQ(StatusCode::OK_200, res->status);
  8335. }
  8336. {
  8337. auto res = cli.Post("/post-both", {}, items, providers);
  8338. ASSERT_TRUE(res);
  8339. ASSERT_EQ(StatusCode::OK_200, res->status);
  8340. }
  8341. }
  8342. }
  8343. TEST(MultipartFormDataTest, BadHeader) {
  8344. Server svr;
  8345. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8346. res.set_content("ok", "text/plain");
  8347. });
  8348. thread t = thread([&] { svr.listen(HOST, PORT); });
  8349. auto se = detail::scope_exit([&] {
  8350. svr.stop();
  8351. t.join();
  8352. ASSERT_FALSE(svr.is_running());
  8353. });
  8354. svr.wait_until_ready();
  8355. const std::string body =
  8356. "This is the preamble. It is to be ignored, though it\r\n"
  8357. "is a handy place for composition agents to include an\r\n"
  8358. "explanatory note to non-MIME conformant readers.\r\n"
  8359. "\r\n"
  8360. "\r\n"
  8361. "--simple boundary\r\n"
  8362. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8363. ": BAD...\r\n"
  8364. "\r\n"
  8365. "value1\r\n"
  8366. "--simple boundary\r\n"
  8367. "Content-Disposition: form-data; name=\"field2\"; "
  8368. "filename=\"example.txt\"\r\n"
  8369. "\r\n"
  8370. "value2\r\n"
  8371. "--simple boundary--\r\n"
  8372. "This is the epilogue. It is also to be ignored.\r\n";
  8373. std::string content_type =
  8374. R"(multipart/form-data; boundary="simple boundary")";
  8375. Client cli(HOST, PORT);
  8376. auto res = cli.Post("/post", body, content_type.c_str());
  8377. ASSERT_TRUE(res);
  8378. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8379. }
  8380. TEST(MultipartFormDataTest, WithPreamble) {
  8381. Server svr;
  8382. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8383. res.set_content("ok", "text/plain");
  8384. });
  8385. thread t = thread([&] { svr.listen(HOST, PORT); });
  8386. auto se = detail::scope_exit([&] {
  8387. svr.stop();
  8388. t.join();
  8389. ASSERT_FALSE(svr.is_running());
  8390. });
  8391. svr.wait_until_ready();
  8392. const std::string body =
  8393. "This is the preamble. It is to be ignored, though it\r\n"
  8394. "is a handy place for composition agents to include an\r\n"
  8395. "explanatory note to non-MIME conformant readers.\r\n"
  8396. "\r\n"
  8397. "\r\n"
  8398. "--simple boundary\r\n"
  8399. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8400. "\r\n"
  8401. "value1\r\n"
  8402. "--simple boundary\r\n"
  8403. "Content-Disposition: form-data; name=\"field2\"; "
  8404. "filename=\"example.txt\"\r\n"
  8405. "\r\n"
  8406. "value2\r\n"
  8407. "--simple boundary--\r\n"
  8408. "This is the epilogue. It is also to be ignored.\r\n";
  8409. std::string content_type =
  8410. R"(multipart/form-data; boundary="simple boundary")";
  8411. Client cli(HOST, PORT);
  8412. auto res = cli.Post("/post", body, content_type.c_str());
  8413. ASSERT_TRUE(res);
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8417. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8418. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8419. const ContentReader &content_reader) {
  8420. if (req.is_multipart_form_data()) {
  8421. std::vector<FormData> items;
  8422. content_reader(
  8423. [&](const FormData &file) {
  8424. items.push_back(file);
  8425. return true;
  8426. },
  8427. [&](const char *data, size_t data_length) {
  8428. items.back().content.append(data, data_length);
  8429. return true;
  8430. });
  8431. EXPECT_TRUE(std::string(items[0].name) == "document");
  8432. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8433. EXPECT_TRUE(items[0].filename == "2MB_data");
  8434. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8435. EXPECT_TRUE(items[1].name == "hello");
  8436. EXPECT_TRUE(items[1].content == "world");
  8437. EXPECT_TRUE(items[1].filename == "");
  8438. EXPECT_TRUE(items[1].content_type == "");
  8439. } else {
  8440. std::string body;
  8441. content_reader([&](const char *data, size_t data_length) {
  8442. body.append(data, data_length);
  8443. return true;
  8444. });
  8445. }
  8446. });
  8447. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. {
  8455. std::string data(1024 * 1024 * 2, '.');
  8456. std::stringstream buffer;
  8457. buffer << data;
  8458. Client cli("https://localhost:8080");
  8459. cli.enable_server_certificate_verification(false);
  8460. UploadFormDataItems items{
  8461. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8462. {"hello", "world", "", ""},
  8463. };
  8464. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8465. ASSERT_TRUE(res);
  8466. ASSERT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. }
  8469. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8470. std::string data(1024 * 1024 * 2, '&');
  8471. std::stringstream buffer;
  8472. buffer << data;
  8473. Client cli("https://localhost:8080");
  8474. UploadFormDataItems items{
  8475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8476. {"hello", "world", "", ""},
  8477. };
  8478. for (const char &c : " \t\r\n") {
  8479. auto res =
  8480. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8481. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8482. ASSERT_FALSE(res);
  8483. }
  8484. }
  8485. TEST(MultipartFormDataTest, PutFormData) {
  8486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8487. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8488. const ContentReader &content_reader) {
  8489. if (req.is_multipart_form_data()) {
  8490. std::vector<FormData> items;
  8491. content_reader(
  8492. [&](const FormData &file) {
  8493. items.push_back(file);
  8494. return true;
  8495. },
  8496. [&](const char *data, size_t data_length) {
  8497. items.back().content.append(data, data_length);
  8498. return true;
  8499. });
  8500. EXPECT_TRUE(std::string(items[0].name) == "document");
  8501. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8502. EXPECT_TRUE(items[0].filename == "2MB_data");
  8503. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8504. EXPECT_TRUE(items[1].name == "hello");
  8505. EXPECT_TRUE(items[1].content == "world");
  8506. EXPECT_TRUE(items[1].filename == "");
  8507. EXPECT_TRUE(items[1].content_type == "");
  8508. } else {
  8509. std::string body;
  8510. content_reader([&](const char *data, size_t data_length) {
  8511. body.append(data, data_length);
  8512. return true;
  8513. });
  8514. }
  8515. });
  8516. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8517. auto se = detail::scope_exit([&] {
  8518. svr.stop();
  8519. t.join();
  8520. ASSERT_FALSE(svr.is_running());
  8521. });
  8522. svr.wait_until_ready();
  8523. {
  8524. std::string data(1024 * 1024 * 2, '&');
  8525. std::stringstream buffer;
  8526. buffer << data;
  8527. Client cli("https://localhost:8080");
  8528. cli.enable_server_certificate_verification(false);
  8529. UploadFormDataItems items{
  8530. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8531. {"hello", "world", "", ""},
  8532. };
  8533. auto res = cli.Put("/put", items);
  8534. ASSERT_TRUE(res);
  8535. ASSERT_EQ(StatusCode::OK_200, res->status);
  8536. }
  8537. }
  8538. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8540. svr.Put("/put_customboundary",
  8541. [&](const Request &req, const Response & /*res*/,
  8542. const ContentReader &content_reader) {
  8543. if (req.is_multipart_form_data()) {
  8544. std::vector<FormData> items;
  8545. content_reader(
  8546. [&](const FormData &file) {
  8547. items.push_back(file);
  8548. return true;
  8549. },
  8550. [&](const char *data, size_t data_length) {
  8551. items.back().content.append(data, data_length);
  8552. return true;
  8553. });
  8554. EXPECT_TRUE(std::string(items[0].name) == "document");
  8555. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8556. EXPECT_TRUE(items[0].filename == "2MB_data");
  8557. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8558. EXPECT_TRUE(items[1].name == "hello");
  8559. EXPECT_TRUE(items[1].content == "world");
  8560. EXPECT_TRUE(items[1].filename == "");
  8561. EXPECT_TRUE(items[1].content_type == "");
  8562. } else {
  8563. std::string body;
  8564. content_reader([&](const char *data, size_t data_length) {
  8565. body.append(data, data_length);
  8566. return true;
  8567. });
  8568. }
  8569. });
  8570. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8571. auto se = detail::scope_exit([&] {
  8572. svr.stop();
  8573. t.join();
  8574. ASSERT_FALSE(svr.is_running());
  8575. });
  8576. svr.wait_until_ready();
  8577. {
  8578. std::string data(1024 * 1024 * 2, '&');
  8579. std::stringstream buffer;
  8580. buffer << data;
  8581. Client cli("https://localhost:8080");
  8582. cli.enable_server_certificate_verification(false);
  8583. UploadFormDataItems items{
  8584. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8585. {"hello", "world", "", ""},
  8586. };
  8587. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8588. ASSERT_TRUE(res);
  8589. ASSERT_EQ(StatusCode::OK_200, res->status);
  8590. }
  8591. }
  8592. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8593. std::string data(1024 * 1024 * 2, '&');
  8594. std::stringstream buffer;
  8595. buffer << data;
  8596. Client cli("https://localhost:8080");
  8597. cli.enable_server_certificate_verification(false);
  8598. UploadFormDataItems items{
  8599. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8600. {"hello", "world", "", ""},
  8601. };
  8602. for (const char &c : " \t\r\n") {
  8603. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8604. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8605. ASSERT_FALSE(res);
  8606. }
  8607. }
  8608. TEST(MultipartFormDataTest, AlternateFilename) {
  8609. auto handled = false;
  8610. Server svr;
  8611. svr.Post("/test", [&](const Request &req, Response &res) {
  8612. ASSERT_EQ(2u, req.form.files.size());
  8613. ASSERT_EQ(1u, req.form.fields.size());
  8614. // Test files
  8615. const auto &file1 = req.form.get_file("file1");
  8616. ASSERT_EQ("file1", file1.name);
  8617. ASSERT_EQ("A.txt", file1.filename);
  8618. ASSERT_EQ("text/plain", file1.content_type);
  8619. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8620. const auto &file2 = req.form.get_file("file2");
  8621. ASSERT_EQ("file2", file2.name);
  8622. ASSERT_EQ("a.html", file2.filename);
  8623. ASSERT_EQ("text/html", file2.content_type);
  8624. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8625. file2.content);
  8626. // Test text field
  8627. const auto &text = req.form.get_field("text");
  8628. ASSERT_EQ("text default", text);
  8629. res.set_content("ok", "text/plain");
  8630. handled = true;
  8631. });
  8632. thread t = thread([&] { svr.listen(HOST, PORT); });
  8633. auto se = detail::scope_exit([&] {
  8634. svr.stop();
  8635. t.join();
  8636. ASSERT_FALSE(svr.is_running());
  8637. ASSERT_TRUE(handled);
  8638. });
  8639. svr.wait_until_ready();
  8640. auto req = "POST /test HTTP/1.1\r\n"
  8641. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8642. "Content-Length: 399\r\n"
  8643. "\r\n"
  8644. "----------\r\n"
  8645. "Content-Disposition: form-data; name=\"text\"\r\n"
  8646. "\r\n"
  8647. "text default\r\n"
  8648. "----------\r\n"
  8649. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8650. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8651. "Content-Type: text/plain\r\n"
  8652. "\r\n"
  8653. "Content of a.txt.\r\n"
  8654. "\r\n"
  8655. "----------\r\n"
  8656. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8657. "\"a.html\"\r\n"
  8658. "Content-Type: text/html\r\n"
  8659. "\r\n"
  8660. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8661. "\r\n"
  8662. "------------\r\n";
  8663. ASSERT_TRUE(send_request(1, req));
  8664. }
  8665. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8666. auto handled = false;
  8667. Server svr;
  8668. svr.Post("/test", [&](const Request &req, Response &) {
  8669. ASSERT_EQ(2u, req.form.fields.size());
  8670. const auto &text1 = req.form.get_field("text1");
  8671. ASSERT_EQ("text1", text1);
  8672. const auto &text2 = req.form.get_field("text2");
  8673. ASSERT_EQ("text2", text2);
  8674. handled = true;
  8675. });
  8676. thread t = thread([&] { svr.listen(HOST, PORT); });
  8677. auto se = detail::scope_exit([&] {
  8678. svr.stop();
  8679. t.join();
  8680. ASSERT_FALSE(svr.is_running());
  8681. ASSERT_TRUE(handled);
  8682. });
  8683. svr.wait_until_ready();
  8684. auto req = "POST /test HTTP/1.1\r\n"
  8685. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8686. "Content-Length: 146\r\n"
  8687. "\r\n----------\r\n"
  8688. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8689. "\r\n"
  8690. "text1"
  8691. "\r\n----------\r\n"
  8692. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8693. "\r\n"
  8694. "text2"
  8695. "\r\n------------";
  8696. std::string response;
  8697. ASSERT_TRUE(send_request(1, req, &response));
  8698. ASSERT_EQ("200", response.substr(9, 3));
  8699. }
  8700. TEST(MultipartFormDataTest, ContentLength) {
  8701. auto handled = false;
  8702. Server svr;
  8703. svr.Post("/test", [&](const Request &req, Response &) {
  8704. ASSERT_EQ(2u, req.form.fields.size());
  8705. const auto &text1 = req.form.get_field("text1");
  8706. ASSERT_EQ("text1", text1);
  8707. const auto &text2 = req.form.get_field("text2");
  8708. ASSERT_EQ("text2", text2);
  8709. handled = true;
  8710. });
  8711. thread t = thread([&] { svr.listen(HOST, PORT); });
  8712. auto se = detail::scope_exit([&] {
  8713. svr.stop();
  8714. t.join();
  8715. ASSERT_FALSE(svr.is_running());
  8716. ASSERT_TRUE(handled);
  8717. });
  8718. svr.wait_until_ready();
  8719. auto req = "POST /test HTTP/1.1\r\n"
  8720. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8721. "Content-Length: 167\r\n"
  8722. "\r\n----------\r\n"
  8723. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8724. "Content-Length: 5\r\n"
  8725. "\r\n"
  8726. "text1"
  8727. "\r\n----------\r\n"
  8728. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8729. "\r\n"
  8730. "text2"
  8731. "\r\n------------\r\n";
  8732. std::string response;
  8733. ASSERT_TRUE(send_request(1, req, &response));
  8734. ASSERT_EQ("200", response.substr(9, 3));
  8735. }
  8736. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8737. auto handled = false;
  8738. Server svr;
  8739. svr.Post("/test", [&](const Request &req, Response &) {
  8740. ASSERT_EQ(2u, req.form.fields.size());
  8741. const auto &text1 = req.form.get_field("text1");
  8742. ASSERT_EQ("text1", text1);
  8743. // TODO: Add header access for text fields if needed
  8744. const auto &text2 = req.form.get_field("text2");
  8745. ASSERT_EQ("text2", text2);
  8746. // TODO: Header access for text fields needs to be implemented
  8747. // auto &headers = it->second.headers;
  8748. // ASSERT_EQ(3U, headers.size());
  8749. // auto custom_header = headers.find("x-whatever");
  8750. // ASSERT_TRUE(custom_header != headers.end());
  8751. // ASSERT_NE("customvalue", custom_header->second);
  8752. // ASSERT_EQ("CustomValue", custom_header->second);
  8753. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8754. handled = true;
  8755. });
  8756. thread t = thread([&] { svr.listen(HOST, PORT); });
  8757. auto se = detail::scope_exit([&] {
  8758. svr.stop();
  8759. t.join();
  8760. ASSERT_FALSE(svr.is_running());
  8761. ASSERT_TRUE(handled);
  8762. });
  8763. svr.wait_until_ready();
  8764. auto req = "POST /test HTTP/1.1\r\n"
  8765. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8766. "Content-Length: 232\r\n"
  8767. "\r\n----------\r\n"
  8768. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8769. "Content-Length: 5\r\n"
  8770. "X-Test: 1\r\n"
  8771. "\r\n"
  8772. "text1"
  8773. "\r\n----------\r\n"
  8774. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8775. "Content-Type: text/plain\r\n"
  8776. "X-Whatever: CustomValue\r\n"
  8777. "\r\n"
  8778. "text2"
  8779. "\r\n------------\r\n"
  8780. "That should be disregarded. Not even read";
  8781. std::string response;
  8782. ASSERT_TRUE(send_request(1, req, &response));
  8783. ASSERT_EQ("200", response.substr(9, 3));
  8784. }
  8785. #endif
  8786. TEST(MultipartFormDataTest, LargeHeader) {
  8787. auto handled = false;
  8788. Server svr;
  8789. svr.Post("/test", [&](const Request &req, Response &) {
  8790. ASSERT_EQ(1u, req.form.fields.size());
  8791. const auto &text = req.form.get_field("name1");
  8792. ASSERT_EQ("text1", text);
  8793. handled = true;
  8794. });
  8795. thread t = thread([&] { svr.listen(HOST, PORT); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. t.join();
  8799. ASSERT_FALSE(svr.is_running());
  8800. ASSERT_TRUE(handled);
  8801. });
  8802. svr.wait_until_ready();
  8803. auto boundary = std::string("cpp-httplib-multipart-data");
  8804. std::string content = "--" + boundary +
  8805. "\r\n"
  8806. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8807. "\r\n"
  8808. "text1\r\n"
  8809. "--" +
  8810. boundary + "--\r\n";
  8811. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8812. "Content-Type: multipart/form-data;boundary=" +
  8813. boundary +
  8814. "\r\n"
  8815. "Content-Length: " +
  8816. std::to_string(content.size()) +
  8817. "\r\n"
  8818. "Dummy-Header: ";
  8819. std::string header_suffix = "\r\n"
  8820. "\r\n";
  8821. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8822. size_t header_dummy_size =
  8823. read_buff_size -
  8824. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8825. auto header_dummy = std::string(header_dummy_size, '@');
  8826. auto req = header_prefix + header_dummy + header_suffix + content;
  8827. std::string response;
  8828. ASSERT_TRUE(send_request(1, req, &response));
  8829. ASSERT_EQ("200", response.substr(9, 3));
  8830. }
  8831. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8832. static constexpr unsigned int number_of_tasks{1000000};
  8833. std::atomic_uint count{0};
  8834. std::unique_ptr<TaskQueue> task_queue{
  8835. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8836. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8837. auto queued = task_queue->enqueue(
  8838. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8839. EXPECT_TRUE(queued);
  8840. }
  8841. EXPECT_NO_THROW(task_queue->shutdown());
  8842. EXPECT_EQ(number_of_tasks, count.load());
  8843. }
  8844. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8845. static constexpr unsigned int number_of_tasks{1000000};
  8846. static constexpr unsigned int qlimit{2};
  8847. unsigned int queued_count{0};
  8848. std::atomic_uint count{0};
  8849. std::unique_ptr<TaskQueue> task_queue{
  8850. new ThreadPool{/*num_threads=*/1, qlimit}};
  8851. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8852. if (task_queue->enqueue(
  8853. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8854. queued_count++;
  8855. }
  8856. }
  8857. EXPECT_NO_THROW(task_queue->shutdown());
  8858. EXPECT_EQ(queued_count, count.load());
  8859. EXPECT_TRUE(queued_count <= number_of_tasks);
  8860. EXPECT_TRUE(queued_count >= qlimit);
  8861. }
  8862. TEST(TaskQueueTest, MaxQueuedRequests) {
  8863. static constexpr unsigned int qlimit{3};
  8864. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8865. std::condition_variable sem_cv;
  8866. std::mutex sem_mtx;
  8867. int credits = 0;
  8868. bool queued;
  8869. /* Fill up the queue with tasks that will block until we give them credits to
  8870. * complete. */
  8871. for (unsigned int n = 0; n <= qlimit;) {
  8872. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8873. std::unique_lock<std::mutex> lock(sem_mtx);
  8874. while (credits <= 0) {
  8875. sem_cv.wait(lock);
  8876. }
  8877. /* Consume the credit and signal the test code if they are all gone. */
  8878. if (--credits == 0) { sem_cv.notify_one(); }
  8879. });
  8880. if (n < qlimit) {
  8881. /* The first qlimit enqueues must succeed. */
  8882. EXPECT_TRUE(queued);
  8883. } else {
  8884. /* The last one will succeed only when the worker thread
  8885. * starts and dequeues the first blocking task. Although
  8886. * not necessary for the correctness of this test, we sleep for
  8887. * a short while to avoid busy waiting. */
  8888. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8889. }
  8890. if (queued) { n++; }
  8891. }
  8892. /* Further enqueues must fail since the queue is full. */
  8893. for (auto i = 0; i < 4; i++) {
  8894. queued = task_queue->enqueue([] {});
  8895. EXPECT_FALSE(queued);
  8896. }
  8897. /* Give the credits to allow the previous tasks to complete. */
  8898. {
  8899. std::unique_lock<std::mutex> lock(sem_mtx);
  8900. credits += qlimit + 1;
  8901. }
  8902. sem_cv.notify_all();
  8903. /* Wait for all the credits to be consumed. */
  8904. {
  8905. std::unique_lock<std::mutex> lock(sem_mtx);
  8906. while (credits > 0) {
  8907. sem_cv.wait(lock);
  8908. }
  8909. }
  8910. /* Check that we are able again to enqueue at least qlimit tasks. */
  8911. for (unsigned int i = 0; i < qlimit; i++) {
  8912. queued = task_queue->enqueue([] {});
  8913. EXPECT_TRUE(queued);
  8914. }
  8915. EXPECT_NO_THROW(task_queue->shutdown());
  8916. }
  8917. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8918. Server svr;
  8919. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8920. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8921. });
  8922. svr.Get("/hello", [](const Request &req, Response &res) {
  8923. res.set_content(req.get_param_value("key"), "text/plain");
  8924. });
  8925. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8926. auto se = detail::scope_exit([&] {
  8927. svr.stop();
  8928. thread.join();
  8929. ASSERT_FALSE(svr.is_running());
  8930. });
  8931. svr.wait_until_ready();
  8932. {
  8933. Client cli(HOST, PORT);
  8934. cli.set_follow_location(true);
  8935. auto res = cli.Get("/");
  8936. ASSERT_TRUE(res);
  8937. EXPECT_EQ(StatusCode::OK_200, res->status);
  8938. EXPECT_EQ("val&key2=val2", res->body);
  8939. }
  8940. }
  8941. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8942. Server svr;
  8943. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8944. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8945. });
  8946. svr.Get("/hello", [](const Request &req, Response &res) {
  8947. res.set_content(req.get_param_value("key"), "text/plain");
  8948. });
  8949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8950. auto se = detail::scope_exit([&] {
  8951. svr.stop();
  8952. thread.join();
  8953. ASSERT_FALSE(svr.is_running());
  8954. });
  8955. svr.wait_until_ready();
  8956. {
  8957. Client cli(HOST, PORT);
  8958. cli.set_follow_location(true);
  8959. auto res = cli.Get("/");
  8960. ASSERT_TRUE(res);
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8963. }
  8964. }
  8965. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8966. TEST(RedirectTest, Issue2185_Online) {
  8967. SSLClient client("github.com");
  8968. client.set_follow_location(true);
  8969. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8970. "Coollab-Windows.zip");
  8971. ASSERT_TRUE(res);
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. EXPECT_EQ(9920427U, res->body.size());
  8974. }
  8975. #endif
  8976. TEST(VulnerabilityTest, CRLFInjection) {
  8977. Server svr;
  8978. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8979. res.set_content("Hello 1", "text/plain");
  8980. });
  8981. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8982. res.set_content("Hello 2", "text/plain");
  8983. });
  8984. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8985. res.set_content("Hello 3", "text/plain");
  8986. });
  8987. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8988. res.set_content("Hello 4", "text/plain");
  8989. });
  8990. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8991. for (const auto &x : req.headers) {
  8992. auto key = x.first;
  8993. EXPECT_STRNE("evil", key.c_str());
  8994. }
  8995. });
  8996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8997. auto se = detail::scope_exit([&] {
  8998. svr.stop();
  8999. thread.join();
  9000. ASSERT_FALSE(svr.is_running());
  9001. });
  9002. svr.wait_until_ready();
  9003. {
  9004. Client cli(HOST, PORT);
  9005. cli.Post("/test1", "A=B",
  9006. "application/x-www-form-urlencoded\r\nevil: hello1");
  9007. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9008. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9009. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9010. }
  9011. }
  9012. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9013. auto server_thread = std::thread([] {
  9014. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9015. default_socket_options(srv);
  9016. sockaddr_in addr{};
  9017. addr.sin_family = AF_INET;
  9018. addr.sin_port = htons(PORT + 1);
  9019. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9020. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9021. ::listen(srv, 1);
  9022. sockaddr_in cli_addr{};
  9023. socklen_t cli_len = sizeof(cli_addr);
  9024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9025. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9026. std::string buf_all;
  9027. char buf[2048];
  9028. ssize_t n;
  9029. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9030. buf_all.append(buf, static_cast<size_t>(n));
  9031. size_t pos;
  9032. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9033. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9034. auto e = request_block.find("\r\n");
  9035. if (e != std::string::npos) {
  9036. auto request_line = request_block.substr(0, e);
  9037. std::string msg =
  9038. "CRLF injection detected in request line: '" + request_line + "'";
  9039. EXPECT_FALSE(true) << msg;
  9040. }
  9041. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9042. ::send(cli,
  9043. #ifdef _WIN32
  9044. static_cast<const char *>(resp.c_str()),
  9045. static_cast<int>(resp.size()),
  9046. #else
  9047. resp.c_str(), resp.size(),
  9048. #endif
  9049. 0);
  9050. buf_all.erase(0, pos + 4);
  9051. }
  9052. }
  9053. detail::close_socket(cli);
  9054. detail::close_socket(srv);
  9055. });
  9056. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9057. auto cli = Client("127.0.0.1", PORT + 1);
  9058. auto headers = Headers{
  9059. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9060. {"Connection", "keep-alive"}};
  9061. auto res = cli.Get("/hi", headers);
  9062. EXPECT_FALSE(res);
  9063. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9064. server_thread.join();
  9065. }
  9066. TEST(PathParamsTest, StaticMatch) {
  9067. const auto pattern = "/users/all";
  9068. detail::PathParamsMatcher matcher(pattern);
  9069. Request request;
  9070. request.path = "/users/all";
  9071. ASSERT_TRUE(matcher.match(request));
  9072. std::unordered_map<std::string, std::string> expected_params = {};
  9073. EXPECT_EQ(request.path_params, expected_params);
  9074. }
  9075. TEST(PathParamsTest, StaticMismatch) {
  9076. const auto pattern = "/users/all";
  9077. detail::PathParamsMatcher matcher(pattern);
  9078. Request request;
  9079. request.path = "/users/1";
  9080. ASSERT_FALSE(matcher.match(request));
  9081. }
  9082. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9083. const auto pattern = "/users/:id/subscriptions";
  9084. detail::PathParamsMatcher matcher(pattern);
  9085. Request request;
  9086. request.path = "/users/42/subscriptions";
  9087. ASSERT_TRUE(matcher.match(request));
  9088. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9089. EXPECT_EQ(request.path_params, expected_params);
  9090. }
  9091. TEST(PathParamsTest, SingleParamInTheEnd) {
  9092. const auto pattern = "/users/:id";
  9093. detail::PathParamsMatcher matcher(pattern);
  9094. Request request;
  9095. request.path = "/users/24";
  9096. ASSERT_TRUE(matcher.match(request));
  9097. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9098. EXPECT_EQ(request.path_params, expected_params);
  9099. }
  9100. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9101. const auto pattern = "/users/:id/";
  9102. detail::PathParamsMatcher matcher(pattern);
  9103. Request request;
  9104. request.path = "/users/42/";
  9105. ASSERT_TRUE(matcher.match(request));
  9106. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9107. EXPECT_EQ(request.path_params, expected_params);
  9108. }
  9109. TEST(PathParamsTest, EmptyParam) {
  9110. const auto pattern = "/users/:id/";
  9111. detail::PathParamsMatcher matcher(pattern);
  9112. Request request;
  9113. request.path = "/users//";
  9114. ASSERT_TRUE(matcher.match(request));
  9115. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9116. EXPECT_EQ(request.path_params, expected_params);
  9117. }
  9118. TEST(PathParamsTest, FragmentMismatch) {
  9119. const auto pattern = "/users/:id/";
  9120. detail::PathParamsMatcher matcher(pattern);
  9121. Request request;
  9122. request.path = "/admins/24/";
  9123. ASSERT_FALSE(matcher.match(request));
  9124. }
  9125. TEST(PathParamsTest, ExtraFragments) {
  9126. const auto pattern = "/users/:id";
  9127. detail::PathParamsMatcher matcher(pattern);
  9128. Request request;
  9129. request.path = "/users/42/subscriptions";
  9130. ASSERT_FALSE(matcher.match(request));
  9131. }
  9132. TEST(PathParamsTest, MissingTrailingParam) {
  9133. const auto pattern = "/users/:id";
  9134. detail::PathParamsMatcher matcher(pattern);
  9135. Request request;
  9136. request.path = "/users";
  9137. ASSERT_FALSE(matcher.match(request));
  9138. }
  9139. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9140. const auto pattern = "/users/:id/subscriptions";
  9141. detail::PathParamsMatcher matcher(pattern);
  9142. Request request;
  9143. request.path = "/users/subscriptions";
  9144. ASSERT_FALSE(matcher.match(request));
  9145. }
  9146. TEST(PathParamsTest, MultipleParams) {
  9147. const auto pattern = "/users/:userid/subscriptions/:subid";
  9148. detail::PathParamsMatcher matcher(pattern);
  9149. Request request;
  9150. request.path = "/users/42/subscriptions/2";
  9151. ASSERT_TRUE(matcher.match(request));
  9152. std::unordered_map<std::string, std::string> expected_params = {
  9153. {"userid", "42"}, {"subid", "2"}};
  9154. EXPECT_EQ(request.path_params, expected_params);
  9155. }
  9156. TEST(PathParamsTest, SequenceOfParams) {
  9157. const auto pattern = "/values/:x/:y/:z";
  9158. detail::PathParamsMatcher matcher(pattern);
  9159. Request request;
  9160. request.path = "/values/1/2/3";
  9161. ASSERT_TRUE(matcher.match(request));
  9162. std::unordered_map<std::string, std::string> expected_params = {
  9163. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9164. EXPECT_EQ(request.path_params, expected_params);
  9165. }
  9166. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9167. const auto pattern = "/prefix:suffix";
  9168. detail::PathParamsMatcher matcher(pattern);
  9169. Request request;
  9170. request.path = "/prefix:suffix";
  9171. ASSERT_TRUE(matcher.match(request));
  9172. const std::unordered_map<std::string, std::string> expected_params = {};
  9173. EXPECT_EQ(request.path_params, expected_params);
  9174. }
  9175. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9176. // If ipv6 regex working, regex match codepath is taken.
  9177. // else port will default to 80 in Client impl
  9178. int clientImplMagicPort = 80;
  9179. int port = 4321;
  9180. // above ports must be different to avoid false negative
  9181. EXPECT_NE(clientImplMagicPort, port);
  9182. std::string ipV6TestURL = "http://[ff06::c3]";
  9183. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9184. CLIENT_PRIVATE_KEY_FILE);
  9185. EXPECT_EQ(cli.port(), port);
  9186. }
  9187. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9188. auto file_path = "./www/dir/index.html";
  9189. auto dir_path = "./www/dir";
  9190. detail::FileStat stat_file(file_path);
  9191. EXPECT_TRUE(stat_file.is_file());
  9192. EXPECT_FALSE(stat_file.is_dir());
  9193. detail::FileStat stat_dir(dir_path);
  9194. EXPECT_FALSE(stat_dir.is_file());
  9195. EXPECT_TRUE(stat_dir.is_dir());
  9196. }
  9197. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9198. // IPv4 with default HTTP port (80)
  9199. EXPECT_EQ("example.com",
  9200. detail::make_host_and_port_string("example.com", 80, false));
  9201. // IPv4 with default HTTPS port (443)
  9202. EXPECT_EQ("example.com",
  9203. detail::make_host_and_port_string("example.com", 443, true));
  9204. // IPv4 with non-default HTTP port
  9205. EXPECT_EQ("example.com:8080",
  9206. detail::make_host_and_port_string("example.com", 8080, false));
  9207. // IPv4 with non-default HTTPS port
  9208. EXPECT_EQ("example.com:8443",
  9209. detail::make_host_and_port_string("example.com", 8443, true));
  9210. // IPv6 with default HTTP port (80)
  9211. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9212. // IPv6 with default HTTPS port (443)
  9213. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9214. // IPv6 with non-default HTTP port
  9215. EXPECT_EQ("[::1]:8080",
  9216. detail::make_host_and_port_string("::1", 8080, false));
  9217. // IPv6 with non-default HTTPS port
  9218. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9219. // IPv6 full address with default port
  9220. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9221. detail::make_host_and_port_string(
  9222. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9223. // IPv6 full address with non-default port
  9224. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9225. detail::make_host_and_port_string(
  9226. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9227. // IPv6 localhost with non-default port
  9228. EXPECT_EQ("[::1]:3000",
  9229. detail::make_host_and_port_string("::1", 3000, false));
  9230. // IPv6 with zone ID (link-local address) with default port
  9231. EXPECT_EQ("[fe80::1%eth0]",
  9232. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9233. // IPv6 with zone ID (link-local address) with non-default port
  9234. EXPECT_EQ("[fe80::1%eth0]:8080",
  9235. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9236. // Edge case: Port 443 with is_ssl=false (should add port)
  9237. EXPECT_EQ("example.com:443",
  9238. detail::make_host_and_port_string("example.com", 443, false));
  9239. // Edge case: Port 80 with is_ssl=true (should add port)
  9240. EXPECT_EQ("example.com:80",
  9241. detail::make_host_and_port_string("example.com", 80, true));
  9242. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9243. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9244. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9245. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9246. // Security fix: Already bracketed IPv6 should not get double brackets
  9247. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9248. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9249. EXPECT_EQ("[::1]:8080",
  9250. detail::make_host_and_port_string("[::1]", 8080, false));
  9251. EXPECT_EQ("[2001:db8::1]:8080",
  9252. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9253. EXPECT_EQ("[fe80::1%eth0]",
  9254. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9255. EXPECT_EQ("[fe80::1%eth0]:8080",
  9256. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9257. // Edge case: Empty host (should return as-is)
  9258. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9259. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9260. // This is a known limitation but shouldn't crash
  9261. EXPECT_EQ("[host:name]",
  9262. detail::make_host_and_port_string("host:name", 80, false));
  9263. // Port number edge cases (no validation, but should not crash)
  9264. EXPECT_EQ("example.com:0",
  9265. detail::make_host_and_port_string("example.com", 0, false));
  9266. EXPECT_EQ("example.com:-1",
  9267. detail::make_host_and_port_string("example.com", -1, false));
  9268. EXPECT_EQ("example.com:65535",
  9269. detail::make_host_and_port_string("example.com", 65535, false));
  9270. EXPECT_EQ("example.com:65536",
  9271. detail::make_host_and_port_string("example.com", 65536, false));
  9272. }
  9273. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9274. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9275. httplib::SSLClient cli("roblox.com", 443);
  9276. cli.set_follow_location(true);
  9277. auto res = cli.Get("/");
  9278. ASSERT_TRUE(res);
  9279. EXPECT_EQ(StatusCode::OK_200, res->status);
  9280. }
  9281. #endif
  9282. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9283. Server svr;
  9284. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9285. EXPECT_EQ(res.status, 400);
  9286. });
  9287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9288. auto se = detail::scope_exit([&] {
  9289. svr.stop();
  9290. thread.join();
  9291. ASSERT_FALSE(svr.is_running());
  9292. });
  9293. svr.wait_until_ready();
  9294. Client cli(HOST, PORT);
  9295. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9296. }
  9297. TEST(InvalidHeaderCharsTest, is_field_name) {
  9298. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9299. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9300. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9301. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9302. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9303. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9304. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9305. EXPECT_FALSE(detail::fields::is_field_name(""));
  9306. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9307. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9308. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9309. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9310. }
  9311. TEST(InvalidHeaderCharsTest, is_field_value) {
  9312. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9313. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9314. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9315. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9316. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9317. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9318. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9319. EXPECT_TRUE(detail::fields::is_field_value(""));
  9320. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9321. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9322. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9323. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9324. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9325. }
  9326. TEST(InvalidHeaderCharsTest, OnServer) {
  9327. Server svr;
  9328. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9329. std::string header = "Not Set";
  9330. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9331. res.set_header(header, "value");
  9332. res.set_content("Page Content Page Content", "text/plain");
  9333. });
  9334. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9335. std::string header = "Not Set";
  9336. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9337. res.set_header("X-Test", header);
  9338. res.set_content("Page Content Page Content", "text/plain");
  9339. });
  9340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9341. auto se = detail::scope_exit([&] {
  9342. svr.stop();
  9343. thread.join();
  9344. ASSERT_FALSE(svr.is_running());
  9345. });
  9346. svr.wait_until_ready();
  9347. Client cli(HOST, PORT);
  9348. {
  9349. auto res = cli.Get(
  9350. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9351. ASSERT_TRUE(res);
  9352. EXPECT_EQ("Page Content Page Content", res->body);
  9353. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9354. }
  9355. {
  9356. auto res = cli.Get(
  9357. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9358. ASSERT_TRUE(res);
  9359. EXPECT_EQ("Page Content Page Content", res->body);
  9360. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9361. }
  9362. }
  9363. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9364. auto handled = false;
  9365. Server svr;
  9366. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9367. thread t = thread([&] { svr.listen(HOST, PORT); });
  9368. auto se = detail::scope_exit([&] {
  9369. svr.stop();
  9370. t.join();
  9371. ASSERT_FALSE(svr.is_running());
  9372. ASSERT_FALSE(handled);
  9373. });
  9374. svr.wait_until_ready();
  9375. auto req = "POST /test HTTP/1.1\r\n"
  9376. "Content-Length: x\r\n"
  9377. "\r\n";
  9378. std::string response;
  9379. ASSERT_TRUE(send_request(1, req, &response));
  9380. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9381. response.substr(0, response.find("\r\n")));
  9382. }
  9383. #ifndef _WIN32
  9384. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9385. static constexpr char reject[] = "Unauthorized";
  9386. static constexpr char accept[] = "Upload accepted";
  9387. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9388. Server svr;
  9389. svr.set_expect_100_continue_handler(
  9390. [](const Request & /*req*/, Response &res) {
  9391. res.status = StatusCode::Unauthorized_401;
  9392. res.set_content(reject, "text/plain");
  9393. return res.status;
  9394. });
  9395. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9396. res.set_content(accept, "text/plain");
  9397. });
  9398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. thread.join();
  9402. ASSERT_FALSE(svr.is_running());
  9403. });
  9404. svr.wait_until_ready();
  9405. {
  9406. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9407. curl_easy_init(), &curl_easy_cleanup};
  9408. ASSERT_NE(curl, nullptr);
  9409. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9410. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9411. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9412. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9413. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9414. &curl_slist_free_all};
  9415. ASSERT_NE(list, nullptr);
  9416. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9417. struct read_data {
  9418. size_t read_size;
  9419. size_t total_size;
  9420. } data = {0, total_size};
  9421. using read_callback_t =
  9422. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9423. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9424. void *userdata) -> size_t {
  9425. read_data *data = (read_data *)userdata;
  9426. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9427. std::fill_n(ptr, size * nmemb, 'A');
  9428. data->read_size += size * nmemb;
  9429. return size * nmemb;
  9430. };
  9431. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9432. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9433. std::vector<char> buffer;
  9434. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9435. using write_callback_t =
  9436. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9437. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9438. void *userdata) -> size_t {
  9439. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9440. buffer->reserve(buffer->size() + size * nmemb + 1);
  9441. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9442. return size * nmemb;
  9443. };
  9444. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9445. {
  9446. const auto res = curl_easy_perform(curl.get());
  9447. ASSERT_EQ(res, CURLE_OK);
  9448. }
  9449. {
  9450. auto response_code = long{};
  9451. const auto res =
  9452. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9453. ASSERT_EQ(res, CURLE_OK);
  9454. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9455. }
  9456. {
  9457. auto dl = curl_off_t{};
  9458. const auto res =
  9459. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9460. ASSERT_EQ(res, CURLE_OK);
  9461. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9462. }
  9463. {
  9464. buffer.push_back('\0');
  9465. ASSERT_STRCASEEQ(buffer.data(), reject);
  9466. }
  9467. }
  9468. }
  9469. #endif
  9470. template <typename S, typename C>
  9471. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9472. svr.Get("/stream", [&](const Request &, Response &res) {
  9473. auto data = new std::string("01234567890123456789");
  9474. res.set_content_provider(
  9475. data->size(), "text/plain",
  9476. [&, data](size_t offset, size_t length, DataSink &sink) {
  9477. const size_t DATA_CHUNK_SIZE = 4;
  9478. const auto &d = *data;
  9479. std::this_thread::sleep_for(std::chrono::seconds(1));
  9480. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9481. return true;
  9482. },
  9483. [data](bool success) {
  9484. EXPECT_FALSE(success);
  9485. delete data;
  9486. });
  9487. });
  9488. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9489. auto i = new size_t(0);
  9490. res.set_content_provider(
  9491. "text/plain",
  9492. [i](size_t, DataSink &sink) {
  9493. if (*i < 5) {
  9494. std::this_thread::sleep_for(std::chrono::seconds(1));
  9495. sink.write("abcd", 4);
  9496. (*i)++;
  9497. } else {
  9498. sink.done();
  9499. }
  9500. return true;
  9501. },
  9502. [i](bool success) {
  9503. EXPECT_FALSE(success);
  9504. delete i;
  9505. });
  9506. });
  9507. svr.Get("/chunked", [&](const Request &, Response &res) {
  9508. auto i = new size_t(0);
  9509. res.set_chunked_content_provider(
  9510. "text/plain",
  9511. [i](size_t, DataSink &sink) {
  9512. if (*i < 5) {
  9513. std::this_thread::sleep_for(std::chrono::seconds(1));
  9514. sink.os << "abcd";
  9515. (*i)++;
  9516. } else {
  9517. sink.done();
  9518. }
  9519. return true;
  9520. },
  9521. [i](bool success) {
  9522. EXPECT_FALSE(success);
  9523. delete i;
  9524. });
  9525. });
  9526. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9527. auto se = detail::scope_exit([&] {
  9528. svr.stop();
  9529. listen_thread.join();
  9530. ASSERT_FALSE(svr.is_running());
  9531. });
  9532. svr.wait_until_ready();
  9533. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9534. {
  9535. auto start = std::chrono::steady_clock::now();
  9536. auto res = cli.Get("/stream");
  9537. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9538. std::chrono::steady_clock::now() - start)
  9539. .count();
  9540. ASSERT_FALSE(res);
  9541. EXPECT_EQ(Error::Read, res.error());
  9542. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9543. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9544. }
  9545. {
  9546. auto start = std::chrono::steady_clock::now();
  9547. auto res = cli.Get("/stream_without_length");
  9548. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9549. std::chrono::steady_clock::now() - start)
  9550. .count();
  9551. ASSERT_FALSE(res);
  9552. EXPECT_EQ(Error::Read, res.error());
  9553. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9554. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9555. }
  9556. {
  9557. auto start = std::chrono::steady_clock::now();
  9558. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9559. EXPECT_EQ("abcd", string(data, data_length));
  9560. return true;
  9561. });
  9562. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9563. std::chrono::steady_clock::now() - start)
  9564. .count();
  9565. ASSERT_FALSE(res);
  9566. EXPECT_EQ(Error::Read, res.error());
  9567. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9568. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9569. }
  9570. }
  9571. TEST(MaxTimeoutTest, ContentStream) {
  9572. time_t timeout = 2000;
  9573. time_t threshold = 200;
  9574. Server svr;
  9575. Client cli("localhost", PORT);
  9576. max_timeout_test(svr, cli, timeout, threshold);
  9577. }
  9578. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9579. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9580. time_t timeout = 2000;
  9581. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9583. SSLClient cli("localhost", PORT);
  9584. cli.enable_server_certificate_verification(false);
  9585. max_timeout_test(svr, cli, timeout, threshold);
  9586. }
  9587. #endif
  9588. class EventDispatcher {
  9589. public:
  9590. EventDispatcher() {}
  9591. bool wait_event(DataSink *sink) {
  9592. unique_lock<mutex> lk(m_);
  9593. int id = id_;
  9594. // Wait with timeout to prevent hanging if client disconnects
  9595. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9596. [&] { return cid_ == id; })) {
  9597. return false; // Timeout occurred
  9598. }
  9599. sink->write(message_.data(), message_.size());
  9600. return true;
  9601. }
  9602. void send_event(const string &message) {
  9603. lock_guard<mutex> lk(m_);
  9604. cid_ = id_++;
  9605. message_ = message;
  9606. cv_.notify_all();
  9607. }
  9608. private:
  9609. mutex m_;
  9610. condition_variable cv_;
  9611. atomic_int id_{0};
  9612. atomic_int cid_{-1};
  9613. string message_;
  9614. };
  9615. TEST(ClientInThreadTest, Issue2068) {
  9616. EventDispatcher ed;
  9617. Server svr;
  9618. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9619. res.set_chunked_content_provider("text/event-stream",
  9620. [&](size_t /*offset*/, DataSink &sink) {
  9621. return ed.wait_event(&sink);
  9622. });
  9623. });
  9624. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9625. svr.wait_until_ready();
  9626. thread event_thread([&] {
  9627. int id = 0;
  9628. while (svr.is_running()) {
  9629. this_thread::sleep_for(chrono::milliseconds(500));
  9630. std::stringstream ss;
  9631. ss << "data: " << id << "\n\n";
  9632. ed.send_event(ss.str());
  9633. id++;
  9634. }
  9635. });
  9636. auto se = detail::scope_exit([&] {
  9637. svr.stop();
  9638. listen_thread.join();
  9639. event_thread.join();
  9640. ASSERT_FALSE(svr.is_running());
  9641. });
  9642. {
  9643. auto client = detail::make_unique<Client>(HOST, PORT);
  9644. client->set_read_timeout(std::chrono::minutes(10));
  9645. std::atomic<bool> stop{false};
  9646. std::thread t([&] {
  9647. client->Get("/event1",
  9648. [&](const char *, size_t) -> bool { return !stop; });
  9649. });
  9650. std::this_thread::sleep_for(std::chrono::seconds(2));
  9651. stop = true;
  9652. client->stop();
  9653. t.join();
  9654. // Reset client after thread has finished
  9655. client.reset();
  9656. }
  9657. }
  9658. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9659. Server svr;
  9660. svr.Get("/", [](const Request &req, Response &res) {
  9661. EXPECT_EQ(2U, req.trailers.size());
  9662. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9663. // Denied
  9664. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9665. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9666. // Accepted
  9667. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9668. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9669. EXPECT_TRUE(req.has_trailer("X-World"));
  9670. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9671. res.set_content("ok", "text/plain");
  9672. });
  9673. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9674. auto se = detail::scope_exit([&] {
  9675. svr.stop();
  9676. t.join();
  9677. ASSERT_FALSE(svr.is_running());
  9678. });
  9679. svr.wait_until_ready();
  9680. const std::string req = "GET / HTTP/1.1\r\n"
  9681. "Transfer-Encoding: chunked\r\n"
  9682. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9683. "\r\n"
  9684. "0\r\n"
  9685. "Content-Length: 10\r\n"
  9686. "Host: internal.local\r\n"
  9687. "Content-Type: malicious/content\r\n"
  9688. "Cookie: any\r\n"
  9689. "Set-Cookie: any\r\n"
  9690. "X-Forwarded-For: attacker.com\r\n"
  9691. "X-Real-Ip: 1.1.1.1\r\n"
  9692. "X-Hello: hello\r\n"
  9693. "X-World: world\r\n"
  9694. "\r\n";
  9695. std::string res;
  9696. ASSERT_TRUE(send_request(1, req, &res));
  9697. }
  9698. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9699. Server svr;
  9700. std::string observed_remote_addr;
  9701. std::string observed_xff;
  9702. svr.Get("/ip", [&](const Request &req, Response &res) {
  9703. observed_remote_addr = req.remote_addr;
  9704. observed_xff = req.get_header_value("X-Forwarded-For");
  9705. res.set_content("ok", "text/plain");
  9706. });
  9707. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9708. auto se = detail::scope_exit([&] {
  9709. svr.stop();
  9710. t.join();
  9711. ASSERT_FALSE(svr.is_running());
  9712. });
  9713. svr.wait_until_ready();
  9714. Client cli(HOST, PORT);
  9715. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9716. ASSERT_TRUE(res);
  9717. EXPECT_EQ(StatusCode::OK_200, res->status);
  9718. EXPECT_EQ(observed_xff, "203.0.113.66");
  9719. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9720. observed_remote_addr == "127.0.0.1");
  9721. }
  9722. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9723. Server svr;
  9724. svr.set_trusted_proxies({"203.0.113.66"});
  9725. std::string observed_remote_addr;
  9726. std::string observed_xff;
  9727. svr.Get("/ip", [&](const Request &req, Response &res) {
  9728. observed_remote_addr = req.remote_addr;
  9729. observed_xff = req.get_header_value("X-Forwarded-For");
  9730. res.set_content("ok", "text/plain");
  9731. });
  9732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9733. auto se = detail::scope_exit([&] {
  9734. svr.stop();
  9735. t.join();
  9736. ASSERT_FALSE(svr.is_running());
  9737. });
  9738. svr.wait_until_ready();
  9739. Client cli(HOST, PORT);
  9740. auto res = cli.Get("/ip");
  9741. ASSERT_TRUE(res);
  9742. EXPECT_EQ(StatusCode::OK_200, res->status);
  9743. EXPECT_EQ(observed_xff, "");
  9744. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9745. observed_remote_addr == "127.0.0.1");
  9746. }
  9747. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9748. Server svr;
  9749. svr.set_trusted_proxies({"203.0.113.66"});
  9750. std::string observed_remote_addr;
  9751. std::string observed_xff;
  9752. svr.Get("/ip", [&](const Request &req, Response &res) {
  9753. observed_remote_addr = req.remote_addr;
  9754. observed_xff = req.get_header_value("X-Forwarded-For");
  9755. res.set_content("ok", "text/plain");
  9756. });
  9757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9758. auto se = detail::scope_exit([&] {
  9759. svr.stop();
  9760. t.join();
  9761. ASSERT_FALSE(svr.is_running());
  9762. });
  9763. svr.wait_until_ready();
  9764. Client cli(HOST, PORT);
  9765. auto res =
  9766. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9767. ASSERT_TRUE(res);
  9768. EXPECT_EQ(StatusCode::OK_200, res->status);
  9769. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9770. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9771. }
  9772. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9773. Server svr;
  9774. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9775. std::string observed_remote_addr;
  9776. std::string observed_xff;
  9777. svr.Get("/ip", [&](const Request &req, Response &res) {
  9778. observed_remote_addr = req.remote_addr;
  9779. observed_xff = req.get_header_value("X-Forwarded-For");
  9780. res.set_content("ok", "text/plain");
  9781. });
  9782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9783. auto se = detail::scope_exit([&] {
  9784. svr.stop();
  9785. t.join();
  9786. ASSERT_FALSE(svr.is_running());
  9787. });
  9788. svr.wait_until_ready();
  9789. Client cli(HOST, PORT);
  9790. auto res = cli.Get(
  9791. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9792. ASSERT_TRUE(res);
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9795. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9796. }
  9797. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9798. Server svr;
  9799. svr.set_trusted_proxies({"192.0.2.45"});
  9800. std::string observed_remote_addr;
  9801. std::string observed_xff;
  9802. svr.Get("/ip", [&](const Request &req, Response &res) {
  9803. observed_remote_addr = req.remote_addr;
  9804. observed_xff = req.get_header_value("X-Forwarded-For");
  9805. res.set_content("ok", "text/plain");
  9806. });
  9807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9808. auto se = detail::scope_exit([&] {
  9809. svr.stop();
  9810. t.join();
  9811. ASSERT_FALSE(svr.is_running());
  9812. });
  9813. svr.wait_until_ready();
  9814. Client cli(HOST, PORT);
  9815. auto res =
  9816. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9817. ASSERT_TRUE(res);
  9818. EXPECT_EQ(StatusCode::OK_200, res->status);
  9819. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9820. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9821. }
  9822. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9823. Server svr;
  9824. svr.set_trusted_proxies({"192.0.2.45"});
  9825. std::string observed_remote_addr;
  9826. std::string observed_xff;
  9827. svr.Get("/ip", [&](const Request &req, Response &res) {
  9828. observed_remote_addr = req.remote_addr;
  9829. observed_xff = req.get_header_value("X-Forwarded-For");
  9830. res.set_content("ok", "text/plain");
  9831. });
  9832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9833. auto se = detail::scope_exit([&] {
  9834. svr.stop();
  9835. t.join();
  9836. ASSERT_FALSE(svr.is_running());
  9837. });
  9838. svr.wait_until_ready();
  9839. Client cli(HOST, PORT);
  9840. auto res = cli.Get(
  9841. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9842. ASSERT_TRUE(res);
  9843. EXPECT_EQ(StatusCode::OK_200, res->status);
  9844. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9845. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9846. }
  9847. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9848. Server svr;
  9849. svr.set_trusted_proxies({"192.0.2.45"});
  9850. std::string observed_remote_addr;
  9851. std::string observed_xff;
  9852. svr.Get("/ip", [&](const Request &req, Response &res) {
  9853. observed_remote_addr = req.remote_addr;
  9854. observed_xff = req.get_header_value("X-Forwarded-For");
  9855. res.set_content("ok", "text/plain");
  9856. });
  9857. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. t.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.wait_until_ready();
  9864. std::string raw_req =
  9865. "GET /ip HTTP/1.1\r\n"
  9866. "Host: localhost\r\n"
  9867. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9868. "Connection: close\r\n"
  9869. "\r\n";
  9870. std::string out;
  9871. ASSERT_TRUE(send_request(5, raw_req, &out));
  9872. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9873. // Header parser trims surrounding whitespace of the header value
  9874. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9875. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9876. }
  9877. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9878. Server svr;
  9879. svr.Post("/post", [&](const Request &req, Response &res) {
  9880. res.set_content(req.body, "text/plain");
  9881. });
  9882. svr.Put("/put", [&](const Request &req, Response &res) {
  9883. res.set_content(req.body, "text/plain");
  9884. });
  9885. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9886. res.set_content(req.body, "text/plain");
  9887. });
  9888. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9889. res.set_content(req.body, "text/plain");
  9890. });
  9891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. t.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. std::string resp;
  9899. // POST without Content-Length
  9900. ASSERT_TRUE(send_request(5,
  9901. "POST /post HTTP/1.1\r\n"
  9902. "Host: localhost\r\n"
  9903. "Connection: close\r\n"
  9904. "\r\n",
  9905. &resp));
  9906. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9907. // PUT without Content-Length
  9908. resp.clear();
  9909. ASSERT_TRUE(send_request(5,
  9910. "PUT /put HTTP/1.1\r\n"
  9911. "Host: localhost\r\n"
  9912. "Connection: close\r\n"
  9913. "\r\n",
  9914. &resp));
  9915. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9916. // PATCH without Content-Length
  9917. resp.clear();
  9918. ASSERT_TRUE(send_request(5,
  9919. "PATCH /patch HTTP/1.1\r\n"
  9920. "Host: localhost\r\n"
  9921. "Connection: close\r\n"
  9922. "\r\n",
  9923. &resp));
  9924. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9925. // DELETE without Content-Length
  9926. resp.clear();
  9927. ASSERT_TRUE(send_request(5,
  9928. "DELETE /delete HTTP/1.1\r\n"
  9929. "Host: localhost\r\n"
  9930. "Connection: close\r\n"
  9931. "\r\n",
  9932. &resp));
  9933. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9934. }
  9935. //==============================================================================
  9936. // open_stream() Tests
  9937. //==============================================================================
  9938. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9939. std::string result;
  9940. char buf[8192];
  9941. ssize_t n;
  9942. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9943. result.append(buf, static_cast<size_t>(n));
  9944. }
  9945. return result;
  9946. }
  9947. // Mock stream for unit tests
  9948. class MockStream : public Stream {
  9949. public:
  9950. std::string data;
  9951. size_t pos = 0;
  9952. ssize_t error_after = -1; // -1 = no error
  9953. explicit MockStream(const std::string &d, ssize_t err = -1)
  9954. : data(d), error_after(err) {}
  9955. bool is_readable() const override { return true; }
  9956. bool wait_readable() const override { return true; }
  9957. bool wait_writable() const override { return true; }
  9958. ssize_t read(char *ptr, size_t size) override {
  9959. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9960. if (pos >= data.size()) return 0;
  9961. size_t limit =
  9962. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9963. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9964. std::memcpy(ptr, data.data() + pos, to_read);
  9965. pos += to_read;
  9966. return static_cast<ssize_t>(to_read);
  9967. }
  9968. ssize_t write(const char *, size_t) override { return -1; }
  9969. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9970. ip = "127.0.0.1";
  9971. port = 0;
  9972. }
  9973. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9974. ip = "127.0.0.1";
  9975. port = 0;
  9976. }
  9977. socket_t socket() const override { return INVALID_SOCKET; }
  9978. time_t duration() const override { return 0; }
  9979. };
  9980. TEST(StreamHandleTest, Basic) {
  9981. ClientImpl::StreamHandle handle;
  9982. EXPECT_FALSE(handle.is_valid());
  9983. handle.response = detail::make_unique<Response>();
  9984. handle.error = Error::Connection;
  9985. EXPECT_FALSE(handle.is_valid());
  9986. handle.error = Error::Success;
  9987. EXPECT_TRUE(handle.is_valid());
  9988. }
  9989. TEST(BodyReaderTest, Basic) {
  9990. MockStream stream("Hello, World!");
  9991. detail::BodyReader reader;
  9992. reader.stream = &stream;
  9993. reader.content_length = 13;
  9994. char buf[32];
  9995. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9996. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9997. EXPECT_TRUE(reader.eof);
  9998. }
  9999. TEST(BodyReaderTest, NoStream) {
  10000. detail::BodyReader reader;
  10001. char buf[32];
  10002. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10003. EXPECT_EQ(Error::Connection, reader.last_error);
  10004. }
  10005. TEST(BodyReaderTest, Error) {
  10006. MockStream stream("Hello, World!", 5);
  10007. detail::BodyReader reader;
  10008. reader.stream = &stream;
  10009. reader.content_length = 13;
  10010. char buf[32];
  10011. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10012. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10013. EXPECT_EQ(Error::Read, reader.last_error);
  10014. }
  10015. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10016. // Mock-based StreamHandle tests relying on private internals are removed.
  10017. class OpenStreamTest : public ::testing::Test {
  10018. protected:
  10019. void SetUp() override {
  10020. svr_.Get("/hello", [](const Request &, Response &res) {
  10021. res.set_content("Hello World!", "text/plain");
  10022. });
  10023. svr_.Get("/large", [](const Request &, Response &res) {
  10024. res.set_content(std::string(10000, 'X'), "text/plain");
  10025. });
  10026. svr_.Get("/chunked", [](const Request &, Response &res) {
  10027. res.set_chunked_content_provider("text/plain",
  10028. [](size_t offset, DataSink &sink) {
  10029. if (offset < 15) {
  10030. sink.write("chunk", 5);
  10031. return true;
  10032. }
  10033. sink.done();
  10034. return true;
  10035. });
  10036. });
  10037. svr_.Get("/compressible", [](const Request &, Response &res) {
  10038. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10039. DataSink &sink) {
  10040. if (offset < 100 * 1024) {
  10041. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10042. sink.write(chunk.data(), chunk.size());
  10043. return true;
  10044. }
  10045. sink.done();
  10046. return true;
  10047. });
  10048. });
  10049. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10050. [](const Request & /*req*/, Response &res) {
  10051. auto i = new int(0);
  10052. res.set_header("Trailer", "Content-Length, X-Allowed");
  10053. res.set_chunked_content_provider(
  10054. "text/plain",
  10055. [i](size_t /*offset*/, DataSink &sink) {
  10056. switch (*i) {
  10057. case 0: sink.os << "123"; break;
  10058. case 1: sink.os << "456"; break;
  10059. case 2: sink.os << "789"; break;
  10060. case 3: {
  10061. sink.done_with_trailer(
  10062. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10063. } break;
  10064. }
  10065. (*i)++;
  10066. return true;
  10067. },
  10068. [i](bool success) {
  10069. EXPECT_TRUE(success);
  10070. delete i;
  10071. });
  10072. });
  10073. // Echo headers endpoint for header-related tests
  10074. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10075. std::string body;
  10076. for (const auto &h : req.headers) {
  10077. body.append(h.first);
  10078. body.push_back(':');
  10079. body.append(h.second);
  10080. body.push_back('\n');
  10081. }
  10082. res.set_content(body, "text/plain");
  10083. });
  10084. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10085. std::string body;
  10086. for (const auto &h : req.headers) {
  10087. body.append(h.first);
  10088. body.push_back(':');
  10089. body.append(h.second);
  10090. body.push_back('\n');
  10091. }
  10092. res.set_content(body, "text/plain");
  10093. });
  10094. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10095. svr_.wait_until_ready();
  10096. }
  10097. void TearDown() override {
  10098. svr_.stop();
  10099. if (thread_.joinable()) thread_.join();
  10100. }
  10101. Server svr_;
  10102. std::thread thread_;
  10103. };
  10104. TEST_F(OpenStreamTest, Basic) {
  10105. Client cli("127.0.0.1", 8787);
  10106. auto handle = cli.open_stream("GET", "/hello");
  10107. EXPECT_TRUE(handle.is_valid());
  10108. EXPECT_EQ("Hello World!", read_all(handle));
  10109. }
  10110. TEST_F(OpenStreamTest, SmallBuffer) {
  10111. Client cli("127.0.0.1", 8787);
  10112. auto handle = cli.open_stream("GET", "/hello");
  10113. std::string result;
  10114. char buf[4];
  10115. ssize_t n;
  10116. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10117. result.append(buf, static_cast<size_t>(n));
  10118. EXPECT_EQ("Hello World!", result);
  10119. }
  10120. TEST_F(OpenStreamTest, DefaultHeaders) {
  10121. Client cli("127.0.0.1", 8787);
  10122. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10123. {
  10124. auto handle = cli.open_stream("GET", "/echo-headers");
  10125. ASSERT_TRUE(handle.is_valid());
  10126. auto body = read_all(handle);
  10127. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10128. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10129. std::string::npos);
  10130. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10131. }
  10132. // open_stream POST with body and no explicit content_type should NOT add
  10133. // text/plain Content-Type (behavior differs from non-streaming path), but
  10134. // should include Content-Length
  10135. {
  10136. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10137. ASSERT_TRUE(handle.is_valid());
  10138. auto body = read_all(handle);
  10139. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10140. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10141. }
  10142. // open_stream POST with explicit Content-Type should preserve it
  10143. {
  10144. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10145. {{"Content-Type", "application/custom"}},
  10146. "{}", "application/custom");
  10147. ASSERT_TRUE(handle.is_valid());
  10148. auto body = read_all(handle);
  10149. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10150. }
  10151. // User-specified User-Agent must not be overwritten for stream API
  10152. {
  10153. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10154. {{"User-Agent", "MyAgent/1.2"}});
  10155. ASSERT_TRUE(handle.is_valid());
  10156. auto body = read_all(handle);
  10157. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10158. }
  10159. }
  10160. TEST_F(OpenStreamTest, Large) {
  10161. Client cli("127.0.0.1", 8787);
  10162. auto handle = cli.open_stream("GET", "/large");
  10163. EXPECT_EQ(10000u, read_all(handle).size());
  10164. }
  10165. TEST_F(OpenStreamTest, ConnectionError) {
  10166. Client cli("127.0.0.1", 9999);
  10167. auto handle = cli.open_stream("GET", "/hello");
  10168. EXPECT_FALSE(handle.is_valid());
  10169. }
  10170. TEST_F(OpenStreamTest, Chunked) {
  10171. Client cli("127.0.0.1", 8787);
  10172. auto handle = cli.open_stream("GET", "/chunked");
  10173. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10174. "Transfer-Encoding") == "chunked");
  10175. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10176. }
  10177. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10178. Client cli("127.0.0.1", 8787);
  10179. auto handle =
  10180. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10181. ASSERT_TRUE(handle.is_valid());
  10182. // Consume body to allow trailers to be received/parsed
  10183. auto body = read_all(handle);
  10184. // Explicitly parse trailers (ensure trailers are available for assertion)
  10185. handle.parse_trailers_if_needed();
  10186. EXPECT_EQ(std::string("123456789"), body);
  10187. // The response should include a Trailer header declaring both names
  10188. ASSERT_TRUE(handle.response);
  10189. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10190. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10191. handle.response->get_header_value("Trailer"));
  10192. // Prohibited trailer must not be present
  10193. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10194. // Allowed trailer should be present
  10195. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10196. EXPECT_EQ(std::string("yes"),
  10197. handle.response->get_trailer_value("X-Allowed"));
  10198. // Verify trailers are NOT present as regular headers
  10199. EXPECT_EQ(std::string(""),
  10200. handle.response->get_header_value("Content-Length"));
  10201. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10202. }
  10203. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10204. TEST_F(OpenStreamTest, Gzip) {
  10205. Client cli("127.0.0.1", 8787);
  10206. auto handle = cli.open_stream("GET", "/compressible", {},
  10207. {{"Accept-Encoding", "gzip"}});
  10208. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10209. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10210. }
  10211. #endif
  10212. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10213. TEST_F(OpenStreamTest, Brotli) {
  10214. Client cli("127.0.0.1", 8787);
  10215. auto handle =
  10216. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10217. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10218. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10219. }
  10220. #endif
  10221. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10222. TEST_F(OpenStreamTest, Zstd) {
  10223. Client cli("127.0.0.1", 8787);
  10224. auto handle = cli.open_stream("GET", "/compressible", {},
  10225. {{"Accept-Encoding", "zstd"}});
  10226. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10227. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10228. }
  10229. #endif
  10230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10231. class SSLOpenStreamTest : public ::testing::Test {
  10232. protected:
  10233. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10234. void SetUp() override {
  10235. svr_.Get("/hello", [](const Request &, Response &res) {
  10236. res.set_content("Hello SSL World!", "text/plain");
  10237. });
  10238. svr_.Get("/chunked", [](const Request &, Response &res) {
  10239. res.set_chunked_content_provider("text/plain",
  10240. [](size_t offset, DataSink &sink) {
  10241. if (offset < 15) {
  10242. sink.write("chunk", 5);
  10243. return true;
  10244. }
  10245. sink.done();
  10246. return true;
  10247. });
  10248. });
  10249. svr_.Post("/echo", [](const Request &req, Response &res) {
  10250. res.set_content(req.body, req.get_header_value("Content-Type"));
  10251. });
  10252. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10253. std::string body = req.body;
  10254. res.set_chunked_content_provider(
  10255. "text/plain", [body](size_t offset, DataSink &sink) {
  10256. if (offset < body.size()) {
  10257. sink.write(body.data() + offset, body.size() - offset);
  10258. }
  10259. sink.done();
  10260. return true;
  10261. });
  10262. });
  10263. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10264. svr_.wait_until_ready();
  10265. }
  10266. void TearDown() override {
  10267. svr_.stop();
  10268. if (thread_.joinable()) thread_.join();
  10269. }
  10270. SSLServer svr_;
  10271. std::thread thread_;
  10272. };
  10273. TEST_F(SSLOpenStreamTest, Basic) {
  10274. SSLClient cli("127.0.0.1", 8788);
  10275. cli.enable_server_certificate_verification(false);
  10276. auto handle = cli.open_stream("GET", "/hello");
  10277. ASSERT_TRUE(handle.is_valid());
  10278. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10279. }
  10280. TEST_F(SSLOpenStreamTest, Chunked) {
  10281. SSLClient cli("127.0.0.1", 8788);
  10282. cli.enable_server_certificate_verification(false);
  10283. auto handle = cli.open_stream("GET", "/chunked");
  10284. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10285. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10286. "Transfer-Encoding") == "chunked");
  10287. auto body = read_all(handle);
  10288. EXPECT_EQ("chunkchunkchunk", body);
  10289. }
  10290. TEST_F(SSLOpenStreamTest, Post) {
  10291. SSLClient cli("127.0.0.1", 8788);
  10292. cli.enable_server_certificate_verification(false);
  10293. auto handle =
  10294. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10295. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10296. EXPECT_EQ(200, handle.response->status);
  10297. auto body = read_all(handle);
  10298. EXPECT_EQ("Hello SSL POST", body);
  10299. }
  10300. TEST_F(SSLOpenStreamTest, PostChunked) {
  10301. SSLClient cli("127.0.0.1", 8788);
  10302. cli.enable_server_certificate_verification(false);
  10303. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10304. "Chunked SSL Data", "text/plain");
  10305. ASSERT_TRUE(handle.is_valid());
  10306. EXPECT_EQ(200, handle.response->status);
  10307. auto body = read_all(handle);
  10308. EXPECT_EQ("Chunked SSL Data", body);
  10309. }
  10310. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10311. //==============================================================================
  10312. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10313. // results for various scenarios.
  10314. //==============================================================================
  10315. TEST(ParityTest, GetVsOpenStream) {
  10316. Server svr;
  10317. const std::string path = "/parity";
  10318. const std::string content = "Parity test content: hello world";
  10319. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10320. res.set_content(content, "text/plain");
  10321. });
  10322. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. t.join();
  10326. ASSERT_FALSE(svr.is_running());
  10327. });
  10328. svr.wait_until_ready();
  10329. Client cli(HOST, PORT);
  10330. // Non-stream path
  10331. auto r1 = cli.Get(path);
  10332. ASSERT_TRUE(r1);
  10333. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10334. // Stream path
  10335. auto h = cli.open_stream("GET", path);
  10336. ASSERT_TRUE(h.is_valid());
  10337. EXPECT_EQ(r1->body, read_all(h));
  10338. }
  10339. // Helper to compress data with provided compressor type T
  10340. template <typename Compressor>
  10341. static std::string compress_payload_for_parity(const std::string &in) {
  10342. std::string out;
  10343. Compressor compressor;
  10344. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10345. [&](const char *data, size_t n) {
  10346. out.append(data, n);
  10347. return true;
  10348. });
  10349. EXPECT_TRUE(ok);
  10350. return out;
  10351. }
  10352. // Helper function for compression parity tests
  10353. template <typename Compressor>
  10354. static void test_compression_parity(const std::string &original,
  10355. const std::string &path,
  10356. const std::string &encoding) {
  10357. const std::string compressed =
  10358. compress_payload_for_parity<Compressor>(original);
  10359. Server svr;
  10360. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10361. res.set_content(compressed, "application/octet-stream");
  10362. res.set_header("Content-Encoding", encoding);
  10363. });
  10364. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10365. auto se = detail::scope_exit([&] {
  10366. svr.stop();
  10367. t.join();
  10368. ASSERT_FALSE(svr.is_running());
  10369. });
  10370. svr.wait_until_ready();
  10371. Client cli(HOST, PORT);
  10372. // Non-streaming
  10373. {
  10374. auto res = cli.Get(path);
  10375. ASSERT_TRUE(res);
  10376. EXPECT_EQ(StatusCode::OK_200, res->status);
  10377. EXPECT_EQ(original, res->body);
  10378. }
  10379. // Streaming
  10380. {
  10381. auto h = cli.open_stream("GET", path);
  10382. ASSERT_TRUE(h.is_valid());
  10383. EXPECT_EQ(original, read_all(h));
  10384. }
  10385. }
  10386. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10387. TEST(ParityTest, Gzip) {
  10388. test_compression_parity<detail::gzip_compressor>(
  10389. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10390. }
  10391. #endif
  10392. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10393. TEST(ParityTest, Brotli) {
  10394. test_compression_parity<detail::brotli_compressor>(
  10395. "Hello, brotli parity test payload", "/parity-br", "br");
  10396. }
  10397. #endif
  10398. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10399. TEST(ParityTest, Zstd) {
  10400. test_compression_parity<detail::zstd_compressor>(
  10401. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10402. }
  10403. #endif
  10404. //==============================================================================
  10405. // New Stream API Tests
  10406. //==============================================================================
  10407. inline std::string read_body(httplib::stream::Result &result) {
  10408. std::string body;
  10409. while (result.next()) {
  10410. body.append(result.data(), result.size());
  10411. }
  10412. return body;
  10413. }
  10414. TEST(ClientConnectionTest, Basic) {
  10415. httplib::ClientConnection conn;
  10416. EXPECT_FALSE(conn.is_open());
  10417. conn.sock = 1;
  10418. EXPECT_TRUE(conn.is_open());
  10419. httplib::ClientConnection conn2(std::move(conn));
  10420. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10421. conn2.sock = INVALID_SOCKET;
  10422. }
  10423. // Unified test server for all stream::* tests
  10424. class StreamApiTest : public ::testing::Test {
  10425. protected:
  10426. void SetUp() override {
  10427. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10428. res.set_content("Hello World!", "text/plain");
  10429. });
  10430. svr_.Get("/echo-params",
  10431. [](const httplib::Request &req, httplib::Response &res) {
  10432. std::string r;
  10433. for (const auto &p : req.params) {
  10434. if (!r.empty()) r += "&";
  10435. r += p.first + "=" + p.second;
  10436. }
  10437. res.set_content(r, "text/plain");
  10438. });
  10439. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10440. res.set_content(req.body, req.get_header_value("Content-Type"));
  10441. });
  10442. svr_.Post("/echo-headers",
  10443. [](const httplib::Request &req, httplib::Response &res) {
  10444. std::string r;
  10445. for (const auto &h : req.headers)
  10446. r += h.first + ": " + h.second + "\n";
  10447. res.set_content(r, "text/plain");
  10448. });
  10449. svr_.Post("/echo-params",
  10450. [](const httplib::Request &req, httplib::Response &res) {
  10451. std::string r = "params:";
  10452. for (const auto &p : req.params)
  10453. r += p.first + "=" + p.second + ";";
  10454. res.set_content(r + " body:" + req.body, "text/plain");
  10455. });
  10456. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10457. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10458. });
  10459. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10460. res.set_content("PUT:" + req.body, "text/plain");
  10461. });
  10462. svr_.Patch("/echo",
  10463. [](const httplib::Request &req, httplib::Response &res) {
  10464. res.set_content("PATCH:" + req.body, "text/plain");
  10465. });
  10466. svr_.Delete(
  10467. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10468. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10469. "text/plain");
  10470. });
  10471. svr_.Get("/head-test",
  10472. [](const httplib::Request &, httplib::Response &res) {
  10473. res.set_content("body for HEAD", "text/plain");
  10474. });
  10475. svr_.Options("/options",
  10476. [](const httplib::Request &, httplib::Response &res) {
  10477. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10478. });
  10479. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10480. svr_.wait_until_ready();
  10481. }
  10482. void TearDown() override {
  10483. svr_.stop();
  10484. if (thread_.joinable()) thread_.join();
  10485. }
  10486. httplib::Server svr_;
  10487. std::thread thread_;
  10488. };
  10489. // stream::Get tests
  10490. TEST_F(StreamApiTest, GetBasic) {
  10491. httplib::Client cli(HOST, PORT);
  10492. auto result = httplib::stream::Get(cli, "/hello");
  10493. ASSERT_TRUE(result.is_valid());
  10494. EXPECT_EQ(200, result.status());
  10495. EXPECT_EQ("Hello World!", read_body(result));
  10496. }
  10497. TEST_F(StreamApiTest, GetWithParams) {
  10498. httplib::Client cli(HOST, PORT);
  10499. httplib::Params params{{"foo", "bar"}};
  10500. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10501. ASSERT_TRUE(result.is_valid());
  10502. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10503. }
  10504. TEST_F(StreamApiTest, GetConnectionError) {
  10505. httplib::Client cli(HOST, 9999);
  10506. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10507. }
  10508. TEST_F(StreamApiTest, Get404) {
  10509. httplib::Client cli(HOST, PORT);
  10510. auto result = httplib::stream::Get(cli, "/nonexistent");
  10511. EXPECT_TRUE(result.is_valid());
  10512. EXPECT_EQ(404, result.status());
  10513. }
  10514. // stream::Post tests
  10515. TEST_F(StreamApiTest, PostBasic) {
  10516. httplib::Client cli(HOST, PORT);
  10517. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10518. "application/json");
  10519. ASSERT_TRUE(result.is_valid());
  10520. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10521. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10522. }
  10523. TEST_F(StreamApiTest, PostWithHeaders) {
  10524. httplib::Client cli(HOST, PORT);
  10525. httplib::Headers headers{{"X-Custom", "value"}};
  10526. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10527. "text/plain");
  10528. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10529. }
  10530. TEST_F(StreamApiTest, PostWithParams) {
  10531. httplib::Client cli(HOST, PORT);
  10532. httplib::Params params{{"k", "v"}};
  10533. auto result =
  10534. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10535. auto body = read_body(result);
  10536. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10537. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10538. }
  10539. TEST_F(StreamApiTest, PostLarge) {
  10540. httplib::Client cli(HOST, PORT);
  10541. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10542. size_t total = 0;
  10543. while (result.next()) {
  10544. total += result.size();
  10545. }
  10546. EXPECT_EQ(100u * 1024u, total);
  10547. }
  10548. // stream::Put/Patch tests
  10549. TEST_F(StreamApiTest, PutAndPatch) {
  10550. httplib::Client cli(HOST, PORT);
  10551. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10552. EXPECT_EQ("PUT:test", read_body(put));
  10553. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10554. EXPECT_EQ("PATCH:test", read_body(patch));
  10555. }
  10556. // stream::Delete tests
  10557. TEST_F(StreamApiTest, Delete) {
  10558. httplib::Client cli(HOST, PORT);
  10559. auto del1 = httplib::stream::Delete(cli, "/resource");
  10560. EXPECT_EQ("Deleted", read_body(del1));
  10561. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10562. EXPECT_EQ("Deleted:data", read_body(del2));
  10563. }
  10564. // stream::Head/Options tests
  10565. TEST_F(StreamApiTest, HeadAndOptions) {
  10566. httplib::Client cli(HOST, PORT);
  10567. auto head = httplib::stream::Head(cli, "/head-test");
  10568. EXPECT_TRUE(head.is_valid());
  10569. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10570. auto opts = httplib::stream::Options(cli, "/options");
  10571. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10572. }
  10573. // SSL stream::* tests
  10574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10575. class SSLStreamApiTest : public ::testing::Test {
  10576. protected:
  10577. void SetUp() override {
  10578. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10579. res.set_content("Hello SSL!", "text/plain");
  10580. });
  10581. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10582. res.set_content(req.body, "text/plain");
  10583. });
  10584. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10585. svr_.wait_until_ready();
  10586. }
  10587. void TearDown() override {
  10588. svr_.stop();
  10589. if (thread_.joinable()) thread_.join();
  10590. }
  10591. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10592. std::thread thread_;
  10593. };
  10594. TEST_F(SSLStreamApiTest, GetAndPost) {
  10595. httplib::SSLClient cli("127.0.0.1", 8803);
  10596. cli.enable_server_certificate_verification(false);
  10597. auto get = httplib::stream::Get(cli, "/hello");
  10598. EXPECT_EQ("Hello SSL!", read_body(get));
  10599. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10600. EXPECT_EQ("test", read_body(post));
  10601. }
  10602. #endif
  10603. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10604. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10605. // BodyReader
  10606. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10607. // Test that read timeout during streaming is detected
  10608. // Use a large content-length response where server delays mid-stream
  10609. Server svr;
  10610. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10611. // Send a large response with delay in the middle
  10612. res.set_content_provider(
  10613. 1000, // content_length
  10614. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10615. if (offset < 100) {
  10616. // Send first 100 bytes immediately
  10617. std::string data(100, 'A');
  10618. sink.write(data.c_str(), data.size());
  10619. return true;
  10620. }
  10621. // Then delay longer than client timeout
  10622. std::this_thread::sleep_for(std::chrono::seconds(3));
  10623. std::string data(900, 'B');
  10624. sink.write(data.c_str(), data.size());
  10625. return true;
  10626. });
  10627. });
  10628. auto port = 8091;
  10629. std::thread t([&]() { svr.listen("localhost", port); });
  10630. svr.wait_until_ready();
  10631. Client cli("localhost", port);
  10632. cli.set_read_timeout(1, 0); // 1 second timeout
  10633. auto handle = cli.open_stream("GET", "/slow-stream");
  10634. ASSERT_TRUE(handle.is_valid());
  10635. char buf[256];
  10636. ssize_t total = 0;
  10637. ssize_t n;
  10638. bool got_error = false;
  10639. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10640. total += n;
  10641. }
  10642. if (n < 0) {
  10643. got_error = true;
  10644. // Should be timeout or read error
  10645. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10646. handle.get_read_error() == Error::Read)
  10647. << "Actual error: " << to_string(handle.get_read_error());
  10648. }
  10649. // Either we got an error, or we got less data than expected
  10650. EXPECT_TRUE(got_error || total < 1000)
  10651. << "Expected timeout but got all " << total << " bytes";
  10652. svr.stop();
  10653. t.join();
  10654. }
  10655. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10656. // Test connection closed detection via BodyReader
  10657. Server svr;
  10658. std::atomic<bool> close_now{false};
  10659. svr.Get("/will-close", [&](const Request &, Response &res) {
  10660. res.set_content_provider(
  10661. 10000, // Large content_length that we won't fully send
  10662. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10663. if (offset < 100) {
  10664. std::string data(100, 'X');
  10665. sink.write(data.c_str(), data.size());
  10666. return true;
  10667. }
  10668. // Wait for signal then abort
  10669. while (!close_now) {
  10670. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10671. }
  10672. return false; // Abort - server will close connection
  10673. });
  10674. });
  10675. auto port = 8092;
  10676. std::thread t([&]() { svr.listen("localhost", port); });
  10677. svr.wait_until_ready();
  10678. Client cli("localhost", port);
  10679. auto handle = cli.open_stream("GET", "/will-close");
  10680. ASSERT_TRUE(handle.is_valid());
  10681. char buf[256];
  10682. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10683. EXPECT_GT(n, 0) << "First read should succeed";
  10684. // Signal server to close
  10685. close_now = true;
  10686. // Keep reading until error or EOF
  10687. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10688. // Keep reading
  10689. }
  10690. // Should get an error since content_length wasn't satisfied
  10691. if (n < 0) {
  10692. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10693. handle.get_read_error() == Error::Read)
  10694. << "Actual error: " << to_string(handle.get_read_error());
  10695. }
  10696. svr.stop();
  10697. t.join();
  10698. }
  10699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10700. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10701. // Test that read timeout during SSL streaming is detected
  10702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10703. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10704. res.set_content_provider(
  10705. 1000, "text/plain",
  10706. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10707. if (offset < 100) {
  10708. std::string data(100, 'A');
  10709. sink.write(data.c_str(), data.size());
  10710. return true;
  10711. }
  10712. std::this_thread::sleep_for(std::chrono::seconds(3));
  10713. std::string data(900, 'B');
  10714. sink.write(data.c_str(), data.size());
  10715. return true;
  10716. });
  10717. });
  10718. auto port = 8093;
  10719. std::thread t([&]() { svr.listen("localhost", port); });
  10720. svr.wait_until_ready();
  10721. SSLClient cli("localhost", port);
  10722. cli.enable_server_certificate_verification(false);
  10723. cli.set_read_timeout(1, 0); // 1 second timeout
  10724. auto handle = cli.open_stream("GET", "/slow-stream");
  10725. ASSERT_TRUE(handle.is_valid());
  10726. char buf[256];
  10727. ssize_t total = 0;
  10728. ssize_t n;
  10729. bool got_error = false;
  10730. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10731. total += n;
  10732. }
  10733. if (n < 0) {
  10734. got_error = true;
  10735. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10736. handle.get_read_error() == Error::Read)
  10737. << "Actual error: " << to_string(handle.get_read_error());
  10738. }
  10739. EXPECT_TRUE(got_error || total < 1000)
  10740. << "Expected timeout but got all " << total << " bytes";
  10741. svr.stop();
  10742. t.join();
  10743. }
  10744. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10745. // Test SSL connection closed detection
  10746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10747. std::atomic<bool> close_now{false};
  10748. svr.Get("/will-close", [&](const Request &, Response &res) {
  10749. res.set_content_provider(
  10750. 10000, "text/plain",
  10751. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10752. if (offset < 100) {
  10753. std::string data(100, 'X');
  10754. sink.write(data.c_str(), data.size());
  10755. return true;
  10756. }
  10757. while (!close_now) {
  10758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10759. }
  10760. return false;
  10761. });
  10762. });
  10763. auto port = 8094;
  10764. std::thread t([&]() { svr.listen("localhost", port); });
  10765. svr.wait_until_ready();
  10766. SSLClient cli("localhost", port);
  10767. cli.enable_server_certificate_verification(false);
  10768. auto handle = cli.open_stream("GET", "/will-close");
  10769. ASSERT_TRUE(handle.is_valid());
  10770. char buf[256];
  10771. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10772. EXPECT_GT(n, 0);
  10773. // Signal server to close
  10774. close_now = true;
  10775. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10776. // Keep reading
  10777. }
  10778. if (n < 0) {
  10779. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10780. handle.get_read_error() == Error::Read)
  10781. << "Actual error: " << to_string(handle.get_read_error());
  10782. }
  10783. svr.stop();
  10784. t.join();
  10785. }
  10786. #endif
  10787. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10788. using namespace httplib;
  10789. // Create a test file
  10790. const char *fname = "etag_testfile.txt";
  10791. const char *content = "etag-content";
  10792. {
  10793. std::ofstream ofs(fname);
  10794. ofs << content;
  10795. ASSERT_TRUE(ofs.good());
  10796. }
  10797. Server svr;
  10798. svr.set_mount_point("/static", ".");
  10799. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10800. svr.wait_until_ready();
  10801. Client cli(HOST, PORT);
  10802. // First request: should get 200 with ETag header
  10803. auto res1 = cli.Get("/static/etag_testfile.txt");
  10804. ASSERT_TRUE(res1);
  10805. ASSERT_EQ(200, res1->status);
  10806. ASSERT_TRUE(res1->has_header("ETag"));
  10807. std::string etag = res1->get_header_value("ETag");
  10808. EXPECT_FALSE(etag.empty());
  10809. // Verify ETag format: W/"hex-hex"
  10810. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10811. EXPECT_EQ('W', etag[0]);
  10812. EXPECT_EQ('/', etag[1]);
  10813. EXPECT_EQ('"', etag[2]);
  10814. EXPECT_EQ('"', etag.back());
  10815. // Exact match: expect 304 Not Modified
  10816. Headers h2 = {{"If-None-Match", etag}};
  10817. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10818. ASSERT_TRUE(res2);
  10819. EXPECT_EQ(304, res2->status);
  10820. // Wildcard match: expect 304 Not Modified
  10821. Headers h3 = {{"If-None-Match", "*"}};
  10822. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10823. ASSERT_TRUE(res3);
  10824. EXPECT_EQ(304, res3->status);
  10825. // Non-matching ETag: expect 200
  10826. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10827. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10828. ASSERT_TRUE(res4);
  10829. EXPECT_EQ(200, res4->status);
  10830. // Multiple ETags with one matching: expect 304
  10831. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10832. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10833. ASSERT_TRUE(res5);
  10834. EXPECT_EQ(304, res5->status);
  10835. svr.stop();
  10836. t.join();
  10837. std::remove(fname);
  10838. }
  10839. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10840. using namespace httplib;
  10841. Server svr;
  10842. svr.set_mount_point("/static", ".");
  10843. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10844. svr.wait_until_ready();
  10845. Client cli(HOST, PORT);
  10846. // Send If-None-Match: * to a non-existent file
  10847. Headers h = {{"If-None-Match", "*"}};
  10848. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10849. ASSERT_TRUE(res);
  10850. EXPECT_EQ(404, res->status);
  10851. svr.stop();
  10852. t.join();
  10853. }
  10854. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10855. using namespace httplib;
  10856. // Create a test file
  10857. const char *fname = "ims_testfile.txt";
  10858. const char *content = "if-modified-since-test";
  10859. {
  10860. std::ofstream ofs(fname);
  10861. ofs << content;
  10862. ASSERT_TRUE(ofs.good());
  10863. }
  10864. Server svr;
  10865. svr.set_mount_point("/static", ".");
  10866. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10867. svr.wait_until_ready();
  10868. Client cli(HOST, PORT);
  10869. // First request: should get 200 with Last-Modified header
  10870. auto res1 = cli.Get("/static/ims_testfile.txt");
  10871. ASSERT_TRUE(res1);
  10872. ASSERT_EQ(200, res1->status);
  10873. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10874. std::string last_modified = res1->get_header_value("Last-Modified");
  10875. EXPECT_FALSE(last_modified.empty());
  10876. // If-Modified-Since with same time: expect 304
  10877. Headers h2 = {{"If-Modified-Since", last_modified}};
  10878. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10879. ASSERT_TRUE(res2);
  10880. EXPECT_EQ(304, res2->status);
  10881. // If-Modified-Since with future time: expect 304
  10882. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10883. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10884. ASSERT_TRUE(res3);
  10885. EXPECT_EQ(304, res3->status);
  10886. // If-Modified-Since with past time: expect 200
  10887. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10888. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10889. ASSERT_TRUE(res4);
  10890. EXPECT_EQ(200, res4->status);
  10891. // If-None-Match takes precedence over If-Modified-Since
  10892. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10893. ASSERT_TRUE(res1->has_header("ETag"));
  10894. std::string etag = res1->get_header_value("ETag");
  10895. Headers h5 = {{"If-None-Match", etag},
  10896. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10897. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10898. ASSERT_TRUE(res5);
  10899. EXPECT_EQ(304, res5->status);
  10900. svr.stop();
  10901. t.join();
  10902. std::remove(fname);
  10903. }
  10904. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10905. using namespace httplib;
  10906. Server svr;
  10907. // Endpoint that returns compressible content
  10908. svr.Get("/compressible", [](const Request &, Response &res) {
  10909. // Return a large enough body to trigger compression
  10910. std::string body(1000, 'a');
  10911. res.set_content(body, "text/plain");
  10912. });
  10913. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10914. svr.wait_until_ready();
  10915. Client cli(HOST, PORT);
  10916. // Request with gzip support: should get Vary header when compressed
  10917. cli.set_compress(true);
  10918. auto res1 = cli.Get("/compressible");
  10919. ASSERT_TRUE(res1);
  10920. EXPECT_EQ(200, res1->status);
  10921. // If Content-Encoding is set, Vary should also be set
  10922. if (res1->has_header("Content-Encoding")) {
  10923. EXPECT_TRUE(res1->has_header("Vary"));
  10924. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10925. }
  10926. // Request without Accept-Encoding header: should not have compression
  10927. Headers h_no_compress;
  10928. auto res2 = cli.Get("/compressible", h_no_compress);
  10929. ASSERT_TRUE(res2);
  10930. EXPECT_EQ(200, res2->status);
  10931. // Verify Vary header is present when compression is applied
  10932. // (the exact behavior depends on server configuration)
  10933. svr.stop();
  10934. t.join();
  10935. }
  10936. TEST(ETagTest, IfRangeWithETag) {
  10937. using namespace httplib;
  10938. // Create a test file with known content
  10939. const char *fname = "if_range_testfile.txt";
  10940. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10941. {
  10942. std::ofstream ofs(fname);
  10943. ofs << content;
  10944. ASSERT_TRUE(ofs.good());
  10945. }
  10946. Server svr;
  10947. svr.set_mount_point("/static", ".");
  10948. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10949. svr.wait_until_ready();
  10950. Client cli(HOST, PORT);
  10951. // First request: get ETag
  10952. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10953. ASSERT_TRUE(res1);
  10954. ASSERT_EQ(200, res1->status);
  10955. ASSERT_TRUE(res1->has_header("ETag"));
  10956. std::string etag = res1->get_header_value("ETag");
  10957. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10958. // Since our server generates weak ETags (W/"..."), If-Range with our
  10959. // ETag should NOT result in partial content - it should return full content.
  10960. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10961. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10962. ASSERT_TRUE(res2);
  10963. // Weak ETag in If-Range -> full content (200), not partial (206)
  10964. EXPECT_EQ(200, res2->status);
  10965. EXPECT_EQ(content, res2->body);
  10966. EXPECT_FALSE(res2->has_header("Content-Range"));
  10967. // Range request with non-matching If-Range (ETag): should get 200 (full
  10968. // content)
  10969. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10970. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10971. ASSERT_TRUE(res3);
  10972. EXPECT_EQ(200, res3->status);
  10973. EXPECT_EQ(content, res3->body);
  10974. EXPECT_FALSE(res3->has_header("Content-Range"));
  10975. // Range request with strong ETag (hypothetical - our server doesn't generate
  10976. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10977. // should return full content)
  10978. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10979. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10980. ASSERT_TRUE(res4);
  10981. EXPECT_EQ(200, res4->status);
  10982. EXPECT_EQ(content, res4->body);
  10983. EXPECT_FALSE(res4->has_header("Content-Range"));
  10984. svr.stop();
  10985. t.join();
  10986. std::remove(fname);
  10987. }
  10988. TEST(ETagTest, IfRangeWithDate) {
  10989. using namespace httplib;
  10990. // Create a test file
  10991. const char *fname = "if_range_date_testfile.txt";
  10992. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10993. {
  10994. std::ofstream ofs(fname);
  10995. ofs << content;
  10996. ASSERT_TRUE(ofs.good());
  10997. }
  10998. Server svr;
  10999. svr.set_mount_point("/static", ".");
  11000. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11001. svr.wait_until_ready();
  11002. Client cli(HOST, PORT);
  11003. // First request: get Last-Modified
  11004. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11005. ASSERT_TRUE(res1);
  11006. ASSERT_EQ(200, res1->status);
  11007. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11008. std::string last_modified = res1->get_header_value("Last-Modified");
  11009. // Range request with matching If-Range (date): should get 206
  11010. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11011. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11012. ASSERT_TRUE(res2);
  11013. EXPECT_EQ(206, res2->status);
  11014. EXPECT_EQ("FGHIJ", res2->body);
  11015. // Range request with old If-Range date: should get 200 (full content)
  11016. Headers h3 = {{"Range", "bytes=5-9"},
  11017. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11018. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11019. ASSERT_TRUE(res3);
  11020. EXPECT_EQ(200, res3->status);
  11021. EXPECT_EQ(content, res3->body);
  11022. // Range request with future If-Range date: should get 206
  11023. Headers h4 = {{"Range", "bytes=0-4"},
  11024. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11025. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11026. ASSERT_TRUE(res4);
  11027. EXPECT_EQ(206, res4->status);
  11028. EXPECT_EQ("ABCDE", res4->body);
  11029. svr.stop();
  11030. t.join();
  11031. std::remove(fname);
  11032. }
  11033. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11034. using namespace httplib;
  11035. const char *fname = "etag_malformed.txt";
  11036. const char *content = "malformed-etag";
  11037. {
  11038. std::ofstream ofs(fname);
  11039. ofs << content;
  11040. ASSERT_TRUE(ofs.good());
  11041. }
  11042. Server svr;
  11043. svr.set_mount_point("/static", ".");
  11044. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11045. svr.wait_until_ready();
  11046. Client cli(HOST, PORT);
  11047. // baseline: should get 200 and an ETag
  11048. auto res1 = cli.Get("/static/etag_malformed.txt");
  11049. ASSERT_TRUE(res1);
  11050. ASSERT_EQ(200, res1->status);
  11051. ASSERT_TRUE(res1->has_header("ETag"));
  11052. // Malformed ETag value (missing quotes) should be treated as non-matching
  11053. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11054. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11055. ASSERT_TRUE(res_bad);
  11056. EXPECT_EQ(200, res_bad->status);
  11057. // Whitespace-only header value should be considered invalid / non-matching
  11058. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11059. "Host: localhost\r\n"
  11060. "If-None-Match: \r\n"
  11061. "Connection: close\r\n"
  11062. "\r\n";
  11063. std::string out;
  11064. ASSERT_TRUE(send_request(5, raw_req, &out));
  11065. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11066. svr.stop();
  11067. t.join();
  11068. std::remove(fname);
  11069. }
  11070. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11071. using namespace httplib;
  11072. const char *fname = "ims_invalid_format.txt";
  11073. const char *content = "ims-bad-format";
  11074. {
  11075. std::ofstream ofs(fname);
  11076. ofs << content;
  11077. ASSERT_TRUE(ofs.good());
  11078. }
  11079. Server svr;
  11080. svr.set_mount_point("/static", ".");
  11081. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11082. svr.wait_until_ready();
  11083. Client cli(HOST, PORT);
  11084. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11085. ASSERT_TRUE(res1);
  11086. ASSERT_EQ(200, res1->status);
  11087. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11088. // If-Modified-Since with invalid format should not result in 304
  11089. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11090. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11091. ASSERT_TRUE(res_bad);
  11092. EXPECT_EQ(200, res_bad->status);
  11093. // If-Range with invalid date format should be treated as mismatch -> full
  11094. // content (200)
  11095. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11096. {"If-Range", "invalid-date"}};
  11097. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11098. ASSERT_TRUE(res_ifrange);
  11099. EXPECT_EQ(200, res_ifrange->status);
  11100. svr.stop();
  11101. t.join();
  11102. std::remove(fname);
  11103. }
  11104. TEST(ETagTest, IfRangeWithMalformedETag) {
  11105. using namespace httplib;
  11106. const char *fname = "ifrange_malformed.txt";
  11107. const std::string content = "0123456789";
  11108. {
  11109. std::ofstream ofs(fname);
  11110. ofs << content;
  11111. ASSERT_TRUE(ofs.good());
  11112. }
  11113. Server svr;
  11114. svr.set_mount_point("/static", ".");
  11115. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11116. svr.wait_until_ready();
  11117. Client cli(HOST, PORT);
  11118. // First request: get ETag
  11119. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11120. ASSERT_TRUE(res1);
  11121. ASSERT_EQ(200, res1->status);
  11122. ASSERT_TRUE(res1->has_header("ETag"));
  11123. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11124. // full content (200)
  11125. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11126. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11127. ASSERT_TRUE(res2);
  11128. EXPECT_EQ(200, res2->status);
  11129. EXPECT_EQ(content, res2->body);
  11130. svr.stop();
  11131. t.join();
  11132. std::remove(fname);
  11133. }
  11134. TEST(ETagTest, ExtremeLargeDateValues) {
  11135. using namespace httplib;
  11136. const char *fname = "ims_extreme_date.txt";
  11137. const char *content = "ims-extreme-date";
  11138. {
  11139. std::ofstream ofs(fname);
  11140. ofs << content;
  11141. ASSERT_TRUE(ofs.good());
  11142. }
  11143. Server svr;
  11144. svr.set_mount_point("/static", ".");
  11145. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11146. svr.wait_until_ready();
  11147. Client cli(HOST, PORT);
  11148. auto res1 = cli.Get(std::string("/static/") + fname);
  11149. ASSERT_TRUE(res1);
  11150. ASSERT_EQ(200, res1->status);
  11151. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11152. // Extremely large year that may overflow date parsing routines.
  11153. Headers h_large_date = {
  11154. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11155. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11156. ASSERT_TRUE(res_bad);
  11157. // Expect server to treat this as invalid/mismatch and return full content
  11158. EXPECT_EQ(200, res_bad->status);
  11159. // If-Range with extremely large date should be treated as mismatch -> full
  11160. // content (200)
  11161. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11162. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11163. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11164. ASSERT_TRUE(res_ifrange);
  11165. EXPECT_EQ(200, res_ifrange->status);
  11166. svr.stop();
  11167. t.join();
  11168. std::remove(fname);
  11169. }
  11170. TEST(ETagTest, NegativeFileModificationTime) {
  11171. using namespace httplib;
  11172. const char *fname = "ims_negative_mtime.txt";
  11173. const std::string content = "negative-mtime";
  11174. {
  11175. std::ofstream ofs(fname);
  11176. ofs << content;
  11177. ASSERT_TRUE(ofs.good());
  11178. }
  11179. // Try to set file mtime to a negative value. This may fail on some
  11180. // platforms/filesystems; if it fails, the test will still verify server
  11181. // behaves safely by performing a regular conditional request.
  11182. #if defined(__APPLE__) || defined(__linux__)
  11183. bool set_negative = false;
  11184. do {
  11185. struct timeval times[2];
  11186. // access time: now
  11187. times[0].tv_sec = time(nullptr);
  11188. times[0].tv_usec = 0;
  11189. // modification time: negative (e.g., -1)
  11190. times[1].tv_sec = -1;
  11191. times[1].tv_usec = 0;
  11192. if (utimes(fname, times) == 0) { set_negative = true; }
  11193. } while (0);
  11194. #else
  11195. bool set_negative = false;
  11196. #endif
  11197. Server svr;
  11198. svr.set_mount_point("/static", ".");
  11199. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11200. svr.wait_until_ready();
  11201. Client cli(HOST, PORT);
  11202. auto res1 = cli.Get(std::string("/static/") + fname);
  11203. ASSERT_TRUE(res1);
  11204. ASSERT_EQ(200, res1->status);
  11205. bool has_last_modified = res1->has_header("Last-Modified");
  11206. std::string last_modified;
  11207. if (has_last_modified) {
  11208. last_modified = res1->get_header_value("Last-Modified");
  11209. }
  11210. if (set_negative) {
  11211. // If we successfully set a negative mtime, ensure server returns a
  11212. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11213. // with an old date and ensure server handles it without crash.
  11214. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11215. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11216. ASSERT_TRUE(res2);
  11217. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11218. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11219. } else {
  11220. // Could not set negative mtime on this platform; fall back to verifying
  11221. // that normal invalid/malformed dates are treated safely (non-304).
  11222. Headers h_bad_date = {
  11223. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11224. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11225. ASSERT_TRUE(res_bad);
  11226. EXPECT_EQ(200, res_bad->status);
  11227. }
  11228. svr.stop();
  11229. t.join();
  11230. std::remove(fname);
  11231. }
  11232. //==============================================================================
  11233. // SSE Parsing Tests
  11234. //==============================================================================
  11235. class SSEParsingTest : public ::testing::Test {
  11236. protected:
  11237. // Test helper that mimics SSE parsing behavior
  11238. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11239. int &retry_ms) {
  11240. // Blank line signals end of event
  11241. if (line.empty() || line == "\r") { return true; }
  11242. // Lines starting with ':' are comments (ignored)
  11243. if (!line.empty() && line[0] == ':') { return false; }
  11244. // Find the colon separator
  11245. auto colon_pos = line.find(':');
  11246. if (colon_pos == std::string::npos) {
  11247. // Line with no colon is treated as field name with empty value
  11248. return false;
  11249. }
  11250. std::string field = line.substr(0, colon_pos);
  11251. std::string value;
  11252. // Value starts after colon, skip optional single space
  11253. if (colon_pos + 1 < line.size()) {
  11254. size_t value_start = colon_pos + 1;
  11255. if (line[value_start] == ' ') { value_start++; }
  11256. value = line.substr(value_start);
  11257. // Remove trailing \r if present
  11258. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11259. }
  11260. // Handle known fields
  11261. if (field == "event") {
  11262. msg.event = value;
  11263. } else if (field == "data") {
  11264. // Multiple data lines are concatenated with newlines
  11265. if (!msg.data.empty()) { msg.data += "\n"; }
  11266. msg.data += value;
  11267. } else if (field == "id") {
  11268. // Empty id is valid (clears the last event ID)
  11269. msg.id = value;
  11270. } else if (field == "retry") {
  11271. // Parse retry interval in milliseconds
  11272. try {
  11273. retry_ms = std::stoi(value);
  11274. } catch (...) {
  11275. // Invalid retry value, ignore
  11276. }
  11277. }
  11278. // Unknown fields are ignored per SSE spec
  11279. return false;
  11280. }
  11281. };
  11282. // Test: Single-line data
  11283. TEST_F(SSEParsingTest, SingleLineData) {
  11284. sse::SSEMessage msg;
  11285. int retry_ms = 3000;
  11286. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11287. EXPECT_EQ(msg.data, "hello");
  11288. EXPECT_EQ(msg.event, "message");
  11289. // Blank line ends event
  11290. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11291. }
  11292. // Test: Multi-line data
  11293. TEST_F(SSEParsingTest, MultiLineData) {
  11294. sse::SSEMessage msg;
  11295. int retry_ms = 3000;
  11296. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11297. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11298. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11299. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11300. }
  11301. // Test: Custom event types
  11302. TEST_F(SSEParsingTest, CustomEventType) {
  11303. sse::SSEMessage msg;
  11304. int retry_ms = 3000;
  11305. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11306. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11307. EXPECT_EQ(msg.event, "update");
  11308. EXPECT_EQ(msg.data, "payload");
  11309. }
  11310. // Test: Event ID handling
  11311. TEST_F(SSEParsingTest, EventIdHandling) {
  11312. sse::SSEMessage msg;
  11313. int retry_ms = 3000;
  11314. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11315. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11316. EXPECT_EQ(msg.id, "12345");
  11317. }
  11318. // Test: Empty event ID (clears last event ID)
  11319. TEST_F(SSEParsingTest, EmptyEventId) {
  11320. sse::SSEMessage msg;
  11321. msg.id = "previous";
  11322. int retry_ms = 3000;
  11323. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11324. EXPECT_EQ(msg.id, "");
  11325. }
  11326. // Test: Retry field parsing
  11327. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11328. sse::SSEMessage msg;
  11329. int retry_ms = 3000;
  11330. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11331. EXPECT_EQ(retry_ms, 5000);
  11332. }
  11333. // Test: Invalid retry value
  11334. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11335. sse::SSEMessage msg;
  11336. int retry_ms = 3000;
  11337. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11338. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11339. }
  11340. // Test: Comments (lines starting with :)
  11341. TEST_F(SSEParsingTest, CommentsIgnored) {
  11342. sse::SSEMessage msg;
  11343. int retry_ms = 3000;
  11344. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11345. EXPECT_EQ(msg.data, "");
  11346. EXPECT_EQ(msg.event, "message");
  11347. }
  11348. // Test: Colon in value
  11349. TEST_F(SSEParsingTest, ColonInValue) {
  11350. sse::SSEMessage msg;
  11351. int retry_ms = 3000;
  11352. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11353. EXPECT_EQ(msg.data, "hello:world:test");
  11354. }
  11355. // Test: Line with no colon (field name only)
  11356. TEST_F(SSEParsingTest, FieldNameOnly) {
  11357. sse::SSEMessage msg;
  11358. int retry_ms = 3000;
  11359. // According to SSE spec, this is treated as field name with empty value
  11360. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11361. // Since we don't recognize "data" without colon, data should be empty
  11362. EXPECT_EQ(msg.data, "");
  11363. }
  11364. // Test: Trailing \r handling
  11365. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11366. sse::SSEMessage msg;
  11367. int retry_ms = 3000;
  11368. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11369. EXPECT_EQ(msg.data, "hello");
  11370. }
  11371. // Test: Unknown fields ignored
  11372. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11373. sse::SSEMessage msg;
  11374. int retry_ms = 3000;
  11375. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11376. EXPECT_EQ(msg.data, "");
  11377. EXPECT_EQ(msg.event, "message");
  11378. }
  11379. // Test: Space after colon is optional
  11380. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11381. sse::SSEMessage msg1, msg2;
  11382. int retry_ms = 3000;
  11383. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11384. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11385. EXPECT_EQ(msg1.data, "hello");
  11386. EXPECT_EQ(msg2.data, "hello");
  11387. }
  11388. // Test: SSEMessage clear
  11389. TEST_F(SSEParsingTest, MessageClear) {
  11390. sse::SSEMessage msg;
  11391. msg.event = "custom";
  11392. msg.data = "some data";
  11393. msg.id = "123";
  11394. msg.clear();
  11395. EXPECT_EQ(msg.event, "message");
  11396. EXPECT_EQ(msg.data, "");
  11397. EXPECT_EQ(msg.id, "");
  11398. }
  11399. // Test: Complete event parsing
  11400. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11401. sse::SSEMessage msg;
  11402. int retry_ms = 3000;
  11403. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11404. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11405. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11406. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11407. // Blank line ends event
  11408. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11409. EXPECT_EQ(msg.event, "notification");
  11410. EXPECT_EQ(msg.id, "evt-42");
  11411. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11412. EXPECT_EQ(retry_ms, 1000);
  11413. }
  11414. //==============================================================================
  11415. // Integration Tests with Server
  11416. //==============================================================================
  11417. class SSEIntegrationTest : public ::testing::Test {
  11418. protected:
  11419. void SetUp() override {
  11420. stop_server_.store(false);
  11421. events_.clear();
  11422. server_ = httplib::detail::make_unique<Server>();
  11423. setup_server();
  11424. start_server();
  11425. }
  11426. void TearDown() override {
  11427. stop_server_.store(true);
  11428. event_cv_.notify_all();
  11429. server_->stop();
  11430. if (server_thread_.joinable()) { server_thread_.join(); }
  11431. }
  11432. void setup_server() {
  11433. // Simple SSE endpoint
  11434. server_->Get("/events", [this](const Request &req, Response &res) {
  11435. auto last_id = req.get_header_value("Last-Event-ID");
  11436. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11437. res.set_chunked_content_provider(
  11438. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11439. std::unique_lock<std::mutex> lock(event_mutex_);
  11440. if (event_cv_.wait_for(
  11441. lock, std::chrono::milliseconds(200), [this] {
  11442. return !events_.empty() || stop_server_.load();
  11443. })) {
  11444. if (stop_server_.load()) { return false; }
  11445. if (!events_.empty()) {
  11446. std::string event = events_.front();
  11447. events_.erase(events_.begin());
  11448. sink.write(event.data(), event.size());
  11449. return true;
  11450. }
  11451. }
  11452. return !stop_server_.load();
  11453. });
  11454. });
  11455. // Endpoint that returns error
  11456. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11457. res.status = 500;
  11458. res.set_content("Internal Server Error", "text/plain");
  11459. });
  11460. // Endpoint for custom event types
  11461. server_->Get("/custom-events", [](const Request &, Response &res) {
  11462. res.set_chunked_content_provider(
  11463. "text/event-stream", [](size_t offset, DataSink &sink) {
  11464. if (offset == 0) {
  11465. std::string event = "event: update\ndata: updated\n\n"
  11466. "event: delete\ndata: deleted\n\n";
  11467. sink.write(event.data(), event.size());
  11468. }
  11469. return false; // End stream after sending
  11470. });
  11471. });
  11472. }
  11473. void start_server() {
  11474. port_ = server_->bind_to_any_port(HOST);
  11475. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11476. // Wait for server to start
  11477. while (!server_->is_running()) {
  11478. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11479. }
  11480. }
  11481. int get_port() const { return port_; }
  11482. void send_event(const std::string &event) {
  11483. std::lock_guard<std::mutex> lock(event_mutex_);
  11484. events_.push_back(event);
  11485. event_cv_.notify_all();
  11486. }
  11487. std::unique_ptr<Server> server_;
  11488. std::thread server_thread_;
  11489. std::mutex event_mutex_;
  11490. std::condition_variable event_cv_;
  11491. std::vector<std::string> events_;
  11492. std::atomic<bool> stop_server_{false};
  11493. std::string last_received_event_id_;
  11494. int port_ = 0;
  11495. };
  11496. // Test: Successful connection and on_open callback
  11497. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11498. // Add a simple endpoint that sends one event and closes
  11499. server_->Get("/simple-event", [](const Request &, Response &res) {
  11500. res.set_chunked_content_provider(
  11501. "text/event-stream", [](size_t offset, DataSink &sink) {
  11502. if (offset == 0) {
  11503. std::string event = "data: hello\n\n";
  11504. sink.write(event.data(), event.size());
  11505. }
  11506. return false; // Close stream after sending
  11507. });
  11508. });
  11509. Client client("localhost", get_port());
  11510. sse::SSEClient sse(client, "/simple-event");
  11511. std::atomic<bool> open_called{false};
  11512. std::atomic<bool> message_received{false};
  11513. sse.on_open([&open_called]() { open_called.store(true); });
  11514. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11515. if (msg.data == "hello") { message_received.store(true); }
  11516. });
  11517. sse.set_reconnect_interval(100);
  11518. sse.set_max_reconnect_attempts(1);
  11519. // Start async
  11520. sse.start_async();
  11521. // Wait for message to be processed
  11522. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11523. sse.stop();
  11524. EXPECT_TRUE(open_called.load());
  11525. EXPECT_TRUE(message_received.load());
  11526. }
  11527. // Test: on_message callback
  11528. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11529. // Endpoint that sends multiple events then closes
  11530. server_->Get("/multi-event", [](const Request &, Response &res) {
  11531. res.set_chunked_content_provider(
  11532. "text/event-stream", [](size_t offset, DataSink &sink) {
  11533. if (offset == 0) {
  11534. std::string events = "data: message1\n\ndata: message2\n\n";
  11535. sink.write(events.data(), events.size());
  11536. }
  11537. return false;
  11538. });
  11539. });
  11540. Client client("localhost", get_port());
  11541. sse::SSEClient sse(client, "/multi-event");
  11542. std::vector<std::string> received_messages;
  11543. std::mutex messages_mutex;
  11544. sse.on_message([&](const sse::SSEMessage &msg) {
  11545. std::lock_guard<std::mutex> lock(messages_mutex);
  11546. received_messages.push_back(msg.data);
  11547. });
  11548. sse.set_reconnect_interval(100);
  11549. sse.set_max_reconnect_attempts(1);
  11550. sse.start_async();
  11551. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11552. sse.stop();
  11553. std::lock_guard<std::mutex> lock(messages_mutex);
  11554. EXPECT_GE(received_messages.size(), 2u);
  11555. if (received_messages.size() >= 2) {
  11556. EXPECT_EQ(received_messages[0], "message1");
  11557. EXPECT_EQ(received_messages[1], "message2");
  11558. }
  11559. }
  11560. // Test: on_event for specific types
  11561. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11562. Client client("localhost", get_port());
  11563. sse::SSEClient sse(client, "/custom-events");
  11564. std::atomic<bool> update_received{false};
  11565. std::atomic<bool> delete_received{false};
  11566. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11567. if (msg.data == "updated") { update_received.store(true); }
  11568. });
  11569. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11570. if (msg.data == "deleted") { delete_received.store(true); }
  11571. });
  11572. sse.set_max_reconnect_attempts(1);
  11573. sse.start_async();
  11574. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11575. sse.stop();
  11576. EXPECT_TRUE(update_received.load());
  11577. EXPECT_TRUE(delete_received.load());
  11578. }
  11579. // Test: on_error callback on connection failure
  11580. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11581. // Connect to a non-existent port
  11582. Client client("localhost", 59999);
  11583. sse::SSEClient sse(client, "/events");
  11584. std::atomic<bool> error_called{false};
  11585. Error received_error = Error::Success;
  11586. sse.on_error([&](Error err) {
  11587. error_called.store(true);
  11588. received_error = err;
  11589. });
  11590. sse.set_reconnect_interval(50);
  11591. sse.set_max_reconnect_attempts(1);
  11592. sse.start_async();
  11593. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11594. sse.stop();
  11595. EXPECT_TRUE(error_called.load());
  11596. EXPECT_NE(received_error, Error::Success);
  11597. }
  11598. // Test: Last-Event-ID header sent on reconnect
  11599. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11600. // Endpoint that sends event with ID
  11601. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11602. res.set_chunked_content_provider(
  11603. "text/event-stream", [](size_t offset, DataSink &sink) {
  11604. if (offset == 0) {
  11605. std::string event = "id: evt-123\ndata: test\n\n";
  11606. sink.write(event.data(), event.size());
  11607. }
  11608. return false;
  11609. });
  11610. });
  11611. Client client("localhost", get_port());
  11612. sse::SSEClient sse(client, "/event-with-id");
  11613. std::atomic<bool> id_received{false};
  11614. sse.on_message([&](const sse::SSEMessage &msg) {
  11615. if (!msg.id.empty()) { id_received.store(true); }
  11616. });
  11617. sse.set_reconnect_interval(100);
  11618. sse.set_max_reconnect_attempts(1);
  11619. sse.start_async();
  11620. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11621. sse.stop();
  11622. EXPECT_TRUE(id_received.load());
  11623. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11624. }
  11625. // Test: Manual stop
  11626. TEST_F(SSEIntegrationTest, ManualStop) {
  11627. // Endpoint that sends one event and stays open briefly
  11628. std::atomic<bool> handler_running{true};
  11629. server_->Get("/stay-open", [&handler_running](const Request &,
  11630. Response &res) {
  11631. res.set_chunked_content_provider(
  11632. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11633. if (offset == 0) {
  11634. std::string event = "data: connected\n\n";
  11635. sink.write(event.data(), event.size());
  11636. }
  11637. // Keep connection open while handler_running is true
  11638. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11639. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11640. }
  11641. return false;
  11642. });
  11643. });
  11644. Client client("localhost", get_port());
  11645. sse::SSEClient sse(client, "/stay-open");
  11646. std::atomic<bool> connected{false};
  11647. sse.on_open([&connected]() { connected.store(true); });
  11648. sse.set_reconnect_interval(100);
  11649. sse.set_max_reconnect_attempts(1);
  11650. sse.start_async();
  11651. // Wait for connection to establish
  11652. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11653. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11654. }
  11655. EXPECT_TRUE(connected.load());
  11656. EXPECT_TRUE(sse.is_connected());
  11657. // Signal handler to stop
  11658. handler_running.store(false);
  11659. // Stop SSE client
  11660. sse.stop();
  11661. EXPECT_FALSE(sse.is_connected());
  11662. }
  11663. // Test: SSEClient with custom headers
  11664. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11665. // Setup a server endpoint that checks for custom header
  11666. std::atomic<bool> header_received{false};
  11667. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11668. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11669. header_received.store(true);
  11670. }
  11671. res.set_chunked_content_provider("text/event-stream",
  11672. [](size_t, DataSink &) { return false; });
  11673. });
  11674. Client client("localhost", get_port());
  11675. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11676. sse::SSEClient sse(client, "/header-check", headers);
  11677. sse.set_max_reconnect_attempts(1);
  11678. sse.start_async();
  11679. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11680. sse.stop();
  11681. EXPECT_TRUE(header_received.load());
  11682. }
  11683. // Test: Reconnect interval configuration
  11684. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11685. Client client("localhost", get_port());
  11686. sse::SSEClient sse(client, "/events");
  11687. auto &result = sse.set_reconnect_interval(500);
  11688. // Builder pattern should return reference to self
  11689. EXPECT_EQ(&result, &sse);
  11690. }
  11691. // Test: Max reconnect attempts
  11692. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11693. // Connect to non-existent port to force reconnects
  11694. Client client("localhost", 59998);
  11695. sse::SSEClient sse(client, "/events");
  11696. std::atomic<int> error_count{0};
  11697. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11698. sse.set_reconnect_interval(50);
  11699. sse.set_max_reconnect_attempts(2);
  11700. auto start = std::chrono::steady_clock::now();
  11701. sse.start(); // Blocking call
  11702. auto end = std::chrono::steady_clock::now();
  11703. // Should have stopped after 2 failed attempts
  11704. EXPECT_GE(error_count.load(), 2);
  11705. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11706. auto duration =
  11707. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11708. #ifdef _WIN32
  11709. // Windows is much slower for socket connection failures
  11710. EXPECT_LT(duration.count(), 7000);
  11711. #else
  11712. EXPECT_LT(duration.count(), 1000);
  11713. #endif
  11714. }
  11715. // Test: Multi-line data in integration
  11716. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11717. // Endpoint with multi-line data
  11718. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11719. res.set_chunked_content_provider(
  11720. "text/event-stream", [](size_t offset, DataSink &sink) {
  11721. if (offset == 0) {
  11722. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11723. sink.write(event.data(), event.size());
  11724. }
  11725. return false;
  11726. });
  11727. });
  11728. Client client("localhost", get_port());
  11729. sse::SSEClient sse(client, "/multiline-data");
  11730. std::string received_data;
  11731. std::mutex data_mutex;
  11732. sse.on_message([&](const sse::SSEMessage &msg) {
  11733. std::lock_guard<std::mutex> lock(data_mutex);
  11734. received_data = msg.data;
  11735. });
  11736. sse.set_reconnect_interval(100);
  11737. sse.set_max_reconnect_attempts(1);
  11738. sse.start_async();
  11739. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11740. sse.stop();
  11741. std::lock_guard<std::mutex> lock(data_mutex);
  11742. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11743. }
  11744. // Test: Auto-reconnect after server disconnection
  11745. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11746. std::atomic<int> connection_count{0};
  11747. std::atomic<int> message_count{0};
  11748. // Endpoint that sends one event and closes, forcing reconnect
  11749. server_->Get("/reconnect-test",
  11750. [&connection_count](const Request &, Response &res) {
  11751. connection_count.fetch_add(1);
  11752. res.set_chunked_content_provider(
  11753. "text/event-stream", [](size_t offset, DataSink &sink) {
  11754. if (offset == 0) {
  11755. std::string event = "data: hello\n\n";
  11756. sink.write(event.data(), event.size());
  11757. }
  11758. return false; // Close connection after sending
  11759. });
  11760. });
  11761. Client client("localhost", get_port());
  11762. sse::SSEClient sse(client, "/reconnect-test");
  11763. sse.on_message([&message_count](const sse::SSEMessage &) {
  11764. message_count.fetch_add(1);
  11765. });
  11766. sse.set_reconnect_interval(100);
  11767. sse.set_max_reconnect_attempts(3);
  11768. sse.start_async();
  11769. // Wait long enough for multiple reconnects
  11770. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11771. sse.stop();
  11772. // Should have connected multiple times (initial + reconnects)
  11773. EXPECT_GE(connection_count.load(), 2);
  11774. // Should have received messages from multiple connections
  11775. EXPECT_GE(message_count.load(), 2);
  11776. }
  11777. // Test: Last-Event-ID sent on reconnect
  11778. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11779. std::atomic<int> connection_count{0};
  11780. std::vector<std::string> received_last_event_ids;
  11781. std::mutex id_mutex;
  11782. // Endpoint that checks Last-Event-ID header and sends event with ID
  11783. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11784. int conn = connection_count.fetch_add(1);
  11785. // Capture the Last-Event-ID header from each connection
  11786. {
  11787. std::lock_guard<std::mutex> lock(id_mutex);
  11788. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11789. }
  11790. res.set_chunked_content_provider(
  11791. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11792. if (offset == 0) {
  11793. std::string event =
  11794. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11795. sink.write(event.data(), event.size());
  11796. }
  11797. return false;
  11798. });
  11799. });
  11800. Client client("localhost", get_port());
  11801. sse::SSEClient sse(client, "/reconnect-with-id");
  11802. sse.set_reconnect_interval(100);
  11803. sse.set_max_reconnect_attempts(3);
  11804. sse.start_async();
  11805. // Wait for at least 2 connections
  11806. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11807. sse.stop();
  11808. // Verify behavior
  11809. std::lock_guard<std::mutex> lock(id_mutex);
  11810. EXPECT_GE(received_last_event_ids.size(), 2u);
  11811. // First connection should have no Last-Event-ID
  11812. if (!received_last_event_ids.empty()) {
  11813. EXPECT_EQ(received_last_event_ids[0], "");
  11814. }
  11815. // Second connection should have Last-Event-ID from first connection
  11816. if (received_last_event_ids.size() >= 2) {
  11817. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11818. }
  11819. }
  11820. TEST(Issue2318Test, EmptyHostString) {
  11821. {
  11822. httplib::Client cli_empty("", PORT);
  11823. auto res = cli_empty.Get("/");
  11824. ASSERT_FALSE(res);
  11825. EXPECT_EQ(httplib::Error::Connection, res.error());
  11826. }
  11827. {
  11828. httplib::Client cli(" ", PORT);
  11829. auto res = cli.Get("/");
  11830. ASSERT_FALSE(res);
  11831. EXPECT_EQ(httplib::Error::Connection, res.error());
  11832. }
  11833. }
  11834. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11835. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  11836. Server svr;
  11837. // Set a small payload limit (1KB)
  11838. svr.set_payload_max_length(1024);
  11839. svr.Post("/test", [&](const Request &req, Response &res) {
  11840. res.set_content("Body size: " + std::to_string(req.body.size()),
  11841. "text/plain");
  11842. });
  11843. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11844. auto se = detail::scope_exit([&] {
  11845. svr.stop();
  11846. listen_thread.join();
  11847. });
  11848. svr.wait_until_ready();
  11849. // Create data that compresses well but exceeds limit when decompressed
  11850. // 8KB of repeated null bytes compresses to a very small size
  11851. std::string original_data(8 * 1024, '\0');
  11852. // Compress the data using gzip
  11853. std::string compressed_data;
  11854. detail::gzip_compressor compressor;
  11855. compressor.compress(original_data.data(), original_data.size(), true,
  11856. [&](const char *data, size_t size) {
  11857. compressed_data.append(data, size);
  11858. return true;
  11859. });
  11860. // Verify compression worked (compressed should be much smaller)
  11861. ASSERT_LT(compressed_data.size(), original_data.size());
  11862. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  11863. // Send compressed data with Content-Encoding: gzip
  11864. Client cli(HOST, PORT);
  11865. Headers headers = {{"Content-Encoding", "gzip"}};
  11866. auto res =
  11867. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  11868. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  11869. ASSERT_TRUE(res);
  11870. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11871. }
  11872. #endif