test.cc 336 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940
  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 <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1092. auto host = "unresolvableaddress.local";
  1093. auto path = std::string{"/"};
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(1);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_FALSE(res);
  1105. }
  1106. std::this_thread::sleep_for(std::chrono::seconds(8));
  1107. }
  1108. TEST(ConnectionErrorTest, InvalidHost) {
  1109. auto host = "-abcde.com";
  1110. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1111. auto port = 443;
  1112. SSLClient cli(host, port);
  1113. #else
  1114. auto port = 80;
  1115. Client cli(host, port);
  1116. #endif
  1117. cli.set_connection_timeout(std::chrono::seconds(2));
  1118. auto res = cli.Get("/");
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Connection, res.error());
  1121. }
  1122. TEST(ConnectionErrorTest, InvalidHost2) {
  1123. auto host = "httpbin.org/";
  1124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1125. SSLClient cli(host);
  1126. #else
  1127. Client cli(host);
  1128. #endif
  1129. cli.set_connection_timeout(std::chrono::seconds(2));
  1130. auto res = cli.Get("/");
  1131. ASSERT_TRUE(!res);
  1132. EXPECT_EQ(Error::Connection, res.error());
  1133. }
  1134. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1135. auto host = "httpbin.org/";
  1136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1137. SSLClient cli(host);
  1138. #else
  1139. Client cli(host);
  1140. #endif
  1141. cli.set_connection_timeout(std::chrono::seconds(2));
  1142. auto res = cli.Get("/");
  1143. ASSERT_TRUE(!res);
  1144. stringstream s;
  1145. s << "error code: " << res.error();
  1146. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1147. }
  1148. TEST(ConnectionErrorTest, InvalidPort) {
  1149. auto host = "localhost";
  1150. auto port = 44380;
  1151. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1152. SSLClient cli(host, port);
  1153. #else
  1154. Client cli(host, port);
  1155. #endif
  1156. cli.set_connection_timeout(std::chrono::seconds(2));
  1157. auto res = cli.Get("/");
  1158. ASSERT_TRUE(!res);
  1159. EXPECT_TRUE(Error::Connection == res.error() ||
  1160. Error::ConnectionTimeout == res.error());
  1161. }
  1162. TEST(ConnectionErrorTest, Timeout_Online) {
  1163. auto host = "google.com";
  1164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1165. auto port = 44380;
  1166. SSLClient cli(host, port);
  1167. #else
  1168. auto port = 8080;
  1169. Client cli(host, port);
  1170. #endif
  1171. cli.set_connection_timeout(std::chrono::seconds(2));
  1172. // only probe one address type so that the error reason
  1173. // correlates to the timed-out IPv4, not the unsupported
  1174. // IPv6 connection attempt
  1175. cli.set_address_family(AF_INET);
  1176. auto res = cli.Get("/");
  1177. ASSERT_TRUE(!res);
  1178. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1179. }
  1180. TEST(CancelTest, NoCancel_Online) {
  1181. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1182. auto host = "httpbin.org";
  1183. auto path = std::string{"/range/32"};
  1184. #else
  1185. auto host = "nghttp2.org";
  1186. auto path = std::string{"/httpbin/range/32"};
  1187. #endif
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. auto port = 443;
  1190. SSLClient cli(host, port);
  1191. #else
  1192. auto port = 80;
  1193. Client cli(host, port);
  1194. #endif
  1195. cli.set_connection_timeout(std::chrono::seconds(5));
  1196. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1197. ASSERT_TRUE(res);
  1198. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. }
  1201. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1202. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1203. auto host = "httpbin.org";
  1204. auto path = std::string{"/range/32"};
  1205. #else
  1206. auto host = "nghttp2.org";
  1207. auto path = std::string{"/httpbin/range/32"};
  1208. #endif
  1209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1210. auto port = 443;
  1211. SSLClient cli(host, port);
  1212. #else
  1213. auto port = 80;
  1214. Client cli(host, port);
  1215. #endif
  1216. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1217. cli.set_connection_timeout(std::chrono::seconds(5));
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Canceled, res.error());
  1220. }
  1221. TEST(CancelTest, WithCancelLargePayload_Online) {
  1222. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1223. auto host = "httpbin.org";
  1224. auto path = std::string{"/range/65536"};
  1225. #else
  1226. auto host = "nghttp2.org";
  1227. auto path = std::string{"/httpbin/range/65536"};
  1228. #endif
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. auto port = 443;
  1231. SSLClient cli(host, port);
  1232. #else
  1233. auto port = 80;
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(5));
  1237. uint32_t count = 0;
  1238. auto res =
  1239. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1240. ASSERT_TRUE(!res);
  1241. EXPECT_EQ(Error::Canceled, res.error());
  1242. }
  1243. TEST(CancelTest, NoCancelPost) {
  1244. Server svr;
  1245. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1246. res.set_content("Hello World!", "text/plain");
  1247. });
  1248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1249. auto se = detail::scope_exit([&] {
  1250. svr.stop();
  1251. thread.join();
  1252. ASSERT_FALSE(svr.is_running());
  1253. });
  1254. svr.wait_until_ready();
  1255. Client cli(HOST, PORT);
  1256. cli.set_connection_timeout(std::chrono::seconds(5));
  1257. auto res =
  1258. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1259. "application/json", [](uint64_t, uint64_t) { return true; });
  1260. ASSERT_TRUE(res);
  1261. EXPECT_EQ("Hello World!", res->body);
  1262. EXPECT_EQ(StatusCode::OK_200, res->status);
  1263. }
  1264. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1265. Server svr;
  1266. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return false; });
  1281. ASSERT_TRUE(!res);
  1282. EXPECT_EQ(Error::Canceled, res.error());
  1283. }
  1284. TEST(CancelTest, WithCancelLargePayloadPost) {
  1285. Server svr;
  1286. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1287. res.set_content(LARGE_DATA, "text/plain");
  1288. });
  1289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1290. auto se = detail::scope_exit([&] {
  1291. svr.stop();
  1292. thread.join();
  1293. ASSERT_FALSE(svr.is_running());
  1294. });
  1295. svr.wait_until_ready();
  1296. Client cli(HOST, PORT);
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res =
  1299. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1300. "application/json", [](uint64_t, uint64_t) { return false; });
  1301. ASSERT_TRUE(!res);
  1302. EXPECT_EQ(Error::Canceled, res.error());
  1303. }
  1304. TEST(CancelTest, NoCancelPut) {
  1305. Server svr;
  1306. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1307. res.set_content("Hello World!", "text/plain");
  1308. });
  1309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1310. auto se = detail::scope_exit([&] {
  1311. svr.stop();
  1312. thread.join();
  1313. ASSERT_FALSE(svr.is_running());
  1314. });
  1315. svr.wait_until_ready();
  1316. Client cli(HOST, PORT);
  1317. cli.set_connection_timeout(std::chrono::seconds(5));
  1318. auto res =
  1319. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1320. "application/json", [](uint64_t, uint64_t) { return true; });
  1321. ASSERT_TRUE(res);
  1322. EXPECT_EQ("Hello World!", res->body);
  1323. EXPECT_EQ(StatusCode::OK_200, res->status);
  1324. }
  1325. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1326. Server svr;
  1327. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1328. res.set_content("Hello World!", "text/plain");
  1329. });
  1330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1331. auto se = detail::scope_exit([&] {
  1332. svr.stop();
  1333. thread.join();
  1334. ASSERT_FALSE(svr.is_running());
  1335. });
  1336. svr.wait_until_ready();
  1337. Client cli(HOST, PORT);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res =
  1340. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1341. "application/json", [](uint64_t, uint64_t) { return false; });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, WithCancelLargePayloadPut) {
  1346. Server svr;
  1347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content(LARGE_DATA, "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return false; });
  1362. ASSERT_TRUE(!res);
  1363. EXPECT_EQ(Error::Canceled, res.error());
  1364. }
  1365. TEST(CancelTest, NoCancelPatch) {
  1366. Server svr;
  1367. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1368. res.set_content("Hello World!", "text/plain");
  1369. });
  1370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1371. auto se = detail::scope_exit([&] {
  1372. svr.stop();
  1373. thread.join();
  1374. ASSERT_FALSE(svr.is_running());
  1375. });
  1376. svr.wait_until_ready();
  1377. Client cli(HOST, PORT);
  1378. cli.set_connection_timeout(std::chrono::seconds(5));
  1379. auto res =
  1380. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1381. "application/json", [](uint64_t, uint64_t) { return true; });
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("Hello World!", res->body);
  1384. EXPECT_EQ(StatusCode::OK_200, res->status);
  1385. }
  1386. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1387. Server svr;
  1388. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1389. res.set_content("Hello World!", "text/plain");
  1390. });
  1391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1392. auto se = detail::scope_exit([&] {
  1393. svr.stop();
  1394. thread.join();
  1395. ASSERT_FALSE(svr.is_running());
  1396. });
  1397. svr.wait_until_ready();
  1398. Client cli(HOST, PORT);
  1399. cli.set_connection_timeout(std::chrono::seconds(5));
  1400. auto res =
  1401. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1402. "application/json", [](uint64_t, uint64_t) { return false; });
  1403. ASSERT_TRUE(!res);
  1404. EXPECT_EQ(Error::Canceled, res.error());
  1405. }
  1406. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1407. Server svr;
  1408. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1409. res.set_content(LARGE_DATA, "text/plain");
  1410. });
  1411. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1412. auto se = detail::scope_exit([&] {
  1413. svr.stop();
  1414. thread.join();
  1415. ASSERT_FALSE(svr.is_running());
  1416. });
  1417. svr.wait_until_ready();
  1418. Client cli(HOST, PORT);
  1419. cli.set_connection_timeout(std::chrono::seconds(5));
  1420. auto res =
  1421. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1422. "application/json", [](uint64_t, uint64_t) { return false; });
  1423. ASSERT_TRUE(!res);
  1424. EXPECT_EQ(Error::Canceled, res.error());
  1425. }
  1426. TEST(CancelTest, NoCancelDelete) {
  1427. Server svr;
  1428. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1429. res.set_content("Hello World!", "text/plain");
  1430. });
  1431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. thread.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. Client cli(HOST, PORT);
  1439. cli.set_connection_timeout(std::chrono::seconds(5));
  1440. auto res =
  1441. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1442. "application/json", [](uint64_t, uint64_t) { return true; });
  1443. ASSERT_TRUE(res);
  1444. EXPECT_EQ("Hello World!", res->body);
  1445. EXPECT_EQ(StatusCode::OK_200, res->status);
  1446. }
  1447. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1448. Server svr;
  1449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("Hello World!", "text/plain");
  1451. });
  1452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1453. auto se = detail::scope_exit([&] {
  1454. svr.stop();
  1455. thread.join();
  1456. ASSERT_FALSE(svr.is_running());
  1457. });
  1458. svr.wait_until_ready();
  1459. Client cli(HOST, PORT);
  1460. cli.set_connection_timeout(std::chrono::seconds(5));
  1461. auto res =
  1462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1463. "application/json", [](uint64_t, uint64_t) { return false; });
  1464. ASSERT_TRUE(!res);
  1465. EXPECT_EQ(Error::Canceled, res.error());
  1466. }
  1467. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1468. Server svr;
  1469. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1470. res.set_content(LARGE_DATA, "text/plain");
  1471. });
  1472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1473. auto se = detail::scope_exit([&] {
  1474. svr.stop();
  1475. thread.join();
  1476. ASSERT_FALSE(svr.is_running());
  1477. });
  1478. svr.wait_until_ready();
  1479. Client cli(HOST, PORT);
  1480. cli.set_connection_timeout(std::chrono::seconds(5));
  1481. auto res =
  1482. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1483. "application/json", [](uint64_t, uint64_t) { return false; });
  1484. ASSERT_TRUE(!res);
  1485. EXPECT_EQ(Error::Canceled, res.error());
  1486. }
  1487. static std::string remove_whitespace(const std::string &input) {
  1488. std::string output;
  1489. output.reserve(input.size());
  1490. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1491. [](unsigned char c) { return !std::isspace(c); });
  1492. return output;
  1493. }
  1494. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1495. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1496. auto host = "httpbin.org";
  1497. auto path = std::string{"/basic-auth/hello/world"};
  1498. #else
  1499. auto host = "nghttp2.org";
  1500. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1501. #endif
  1502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1503. auto port = 443;
  1504. SSLClient cli(host, port);
  1505. #else
  1506. auto port = 80;
  1507. Client cli(host, port);
  1508. #endif
  1509. {
  1510. auto res = cli.Get(path);
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1513. }
  1514. {
  1515. auto res =
  1516. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1517. ASSERT_TRUE(res);
  1518. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1519. remove_whitespace(res->body));
  1520. EXPECT_EQ(StatusCode::OK_200, res->status);
  1521. }
  1522. {
  1523. cli.set_basic_auth("hello", "world");
  1524. auto res = cli.Get(path);
  1525. ASSERT_TRUE(res);
  1526. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1527. remove_whitespace(res->body));
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. }
  1530. {
  1531. cli.set_basic_auth("hello", "bad");
  1532. auto res = cli.Get(path);
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1535. }
  1536. {
  1537. cli.set_basic_auth("bad", "world");
  1538. auto res = cli.Get(path);
  1539. ASSERT_TRUE(res);
  1540. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1541. }
  1542. }
  1543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1544. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1545. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1546. auto host = "httpbin.org";
  1547. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1548. auto paths = std::vector<std::string>{
  1549. "/digest-auth/auth/hello/world/MD5",
  1550. "/digest-auth/auth/hello/world/SHA-256",
  1551. "/digest-auth/auth/hello/world/SHA-512",
  1552. "/digest-auth/auth-int/hello/world/MD5",
  1553. };
  1554. #else
  1555. auto host = "nghttp2.org";
  1556. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1557. auto paths = std::vector<std::string>{
  1558. "/httpbin/digest-auth/auth/hello/world/MD5",
  1559. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1560. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1561. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1562. };
  1563. #endif
  1564. auto port = 443;
  1565. SSLClient cli(host, port);
  1566. {
  1567. auto res = cli.Get(unauth_path);
  1568. ASSERT_TRUE(res);
  1569. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1570. }
  1571. {
  1572. cli.set_digest_auth("hello", "world");
  1573. for (const auto &path : paths) {
  1574. auto res = cli.Get(path.c_str());
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1577. remove_whitespace(res->body));
  1578. EXPECT_EQ(StatusCode::OK_200, res->status);
  1579. }
  1580. cli.set_digest_auth("hello", "bad");
  1581. for (const auto &path : paths) {
  1582. auto res = cli.Get(path.c_str());
  1583. ASSERT_TRUE(res);
  1584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1585. }
  1586. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1587. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1588. // cli.set_digest_auth("bad", "world");
  1589. // for (const auto& path : paths) {
  1590. // auto res = cli.Get(path.c_str());
  1591. // ASSERT_TRUE(res);
  1592. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1593. // }
  1594. }
  1595. }
  1596. #endif
  1597. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1598. auto host = "google.com";
  1599. auto another_host = "example.com";
  1600. auto wrong_ip = "0.0.0.0";
  1601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1602. SSLClient cli(host);
  1603. #else
  1604. Client cli(host);
  1605. #endif
  1606. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1607. auto res = cli.Get("/");
  1608. ASSERT_TRUE(res);
  1609. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1610. }
  1611. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1612. auto host = "google.com";
  1613. auto wrong_ip = "0.0.0.0";
  1614. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1615. SSLClient cli(host);
  1616. #else
  1617. Client cli(host);
  1618. #endif
  1619. cli.set_hostname_addr_map({{host, wrong_ip}});
  1620. auto res = cli.Get("/");
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Connection, res.error());
  1623. }
  1624. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1625. auto host = "nghttp2.org";
  1626. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1627. SSLClient cli(host);
  1628. #else
  1629. Client cli(host);
  1630. #endif
  1631. cli.set_follow_location(true);
  1632. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1633. ASSERT_TRUE(res);
  1634. EXPECT_EQ(StatusCode::OK_200, res->status);
  1635. }
  1636. TEST(RedirectTest, Redirect_Online) {
  1637. auto host = "nghttp2.org";
  1638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1639. SSLClient cli(host);
  1640. #else
  1641. Client cli(host);
  1642. #endif
  1643. cli.set_follow_location(true);
  1644. auto res = cli.Get("/httpbin/redirect/3");
  1645. ASSERT_TRUE(res);
  1646. EXPECT_EQ(StatusCode::OK_200, res->status);
  1647. }
  1648. TEST(RelativeRedirectTest, Redirect_Online) {
  1649. auto host = "nghttp2.org";
  1650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1651. SSLClient cli(host);
  1652. #else
  1653. Client cli(host);
  1654. #endif
  1655. cli.set_follow_location(true);
  1656. auto res = cli.Get("/httpbin/relative-redirect/3");
  1657. ASSERT_TRUE(res);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(TooManyRedirectTest, Redirect_Online) {
  1661. auto host = "nghttp2.org";
  1662. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1663. SSLClient cli(host);
  1664. #else
  1665. Client cli(host);
  1666. #endif
  1667. cli.set_follow_location(true);
  1668. auto res = cli.Get("/httpbin/redirect/21");
  1669. ASSERT_TRUE(!res);
  1670. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1671. }
  1672. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1673. TEST(YahooRedirectTest, Redirect_Online) {
  1674. Client cli("yahoo.com");
  1675. auto res = cli.Get("/");
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1678. cli.set_follow_location(true);
  1679. res = cli.Get("/");
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::OK_200, res->status);
  1682. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1683. }
  1684. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1685. #define REDIR_HOST "httpbingo.org"
  1686. #define REDIR_PATH "/redirect-to"
  1687. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1688. SSLClient cli(REDIR_HOST);
  1689. cli.set_follow_location(true);
  1690. auto res =
  1691. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::OK_200, res->status);
  1694. }
  1695. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1696. SSLClient cli(REDIR_HOST);
  1697. cli.set_follow_location(true);
  1698. Params params;
  1699. params.emplace("url", "http://example.com");
  1700. params.emplace("status_code", "302");
  1701. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1702. ASSERT_TRUE(res);
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. }
  1705. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1706. SSLClient cli(REDIR_HOST);
  1707. cli.set_follow_location(true);
  1708. Params params;
  1709. params.emplace("url", "http://example.com");
  1710. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1711. ASSERT_TRUE(res);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. TEST(UrlWithSpace, Redirect_Online) {
  1715. SSLClient cli("edge.forgecdn.net");
  1716. cli.set_follow_location(true);
  1717. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1721. }
  1722. #endif
  1723. #if !defined(_WIN32) && !defined(_WIN64)
  1724. TEST(ReceiveSignals, Signal) {
  1725. auto setupSignalHandlers = []() {
  1726. struct sigaction act;
  1727. sigemptyset(&act.sa_mask);
  1728. act.sa_flags = SA_SIGINFO;
  1729. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1730. switch (sig) {
  1731. case SIGINT:
  1732. default: break;
  1733. }
  1734. };
  1735. ::sigaction(SIGINT, &act, nullptr);
  1736. };
  1737. Server svr;
  1738. int port = 0;
  1739. auto thread = std::thread([&]() {
  1740. setupSignalHandlers();
  1741. port = svr.bind_to_any_port("localhost");
  1742. svr.listen_after_bind();
  1743. });
  1744. auto se = detail::scope_exit([&] {
  1745. svr.stop();
  1746. thread.join();
  1747. ASSERT_FALSE(svr.is_running());
  1748. });
  1749. svr.wait_until_ready();
  1750. ASSERT_TRUE(svr.is_running());
  1751. pthread_kill(thread.native_handle(), SIGINT);
  1752. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1753. ASSERT_TRUE(svr.is_running());
  1754. }
  1755. #endif
  1756. TEST(RedirectToDifferentPort, Redirect) {
  1757. Server svr1;
  1758. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1759. res.set_content("Hello World!", "text/plain");
  1760. });
  1761. int svr1_port = 0;
  1762. auto thread1 = std::thread([&]() {
  1763. svr1_port = svr1.bind_to_any_port("localhost");
  1764. svr1.listen_after_bind();
  1765. });
  1766. Server svr2;
  1767. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1768. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1769. });
  1770. int svr2_port = 0;
  1771. auto thread2 = std::thread([&]() {
  1772. svr2_port = svr2.bind_to_any_port("localhost");
  1773. svr2.listen_after_bind();
  1774. });
  1775. auto se = detail::scope_exit([&] {
  1776. svr2.stop();
  1777. thread2.join();
  1778. svr1.stop();
  1779. thread1.join();
  1780. ASSERT_FALSE(svr2.is_running());
  1781. ASSERT_FALSE(svr1.is_running());
  1782. });
  1783. svr1.wait_until_ready();
  1784. svr2.wait_until_ready();
  1785. Client cli("localhost", svr2_port);
  1786. cli.set_follow_location(true);
  1787. auto res = cli.Get("/2");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. TEST(RedirectFromPageWithContent, Redirect) {
  1793. Server svr;
  1794. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1795. res.set_content("___", "text/plain");
  1796. res.set_redirect("/2");
  1797. });
  1798. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1799. res.set_content("Hello World!", "text/plain");
  1800. });
  1801. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1802. auto se = detail::scope_exit([&] {
  1803. svr.stop();
  1804. th.join();
  1805. ASSERT_FALSE(svr.is_running());
  1806. });
  1807. svr.wait_until_ready();
  1808. {
  1809. Client cli("localhost", PORT);
  1810. cli.set_follow_location(true);
  1811. std::string body;
  1812. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1813. body.append(data, data_length);
  1814. return true;
  1815. });
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. EXPECT_EQ("Hello World!", body);
  1819. }
  1820. {
  1821. Client cli("localhost", PORT);
  1822. std::string body;
  1823. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1824. body.append(data, data_length);
  1825. return true;
  1826. });
  1827. ASSERT_TRUE(res);
  1828. EXPECT_EQ(StatusCode::Found_302, res->status);
  1829. EXPECT_EQ("___", body);
  1830. }
  1831. }
  1832. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1833. Server svr;
  1834. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1835. res.set_content("___", "text/plain");
  1836. // res.set_redirect("/2");
  1837. res.set_redirect("http://[::1]:1234/2");
  1838. });
  1839. svr.Get("/2", [&](const Request &req, Response &res) {
  1840. auto host_header = req.headers.find("Host");
  1841. ASSERT_TRUE(host_header != req.headers.end());
  1842. EXPECT_EQ("[::1]:1234", host_header->second);
  1843. res.set_content("Hello World!", "text/plain");
  1844. });
  1845. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. th.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1852. // actually starts anything, so the condition !svr.is_running() will
  1853. // always remain true, and the loop never stops.
  1854. // This basically counts how many milliseconds have passed since the
  1855. // call to svr.listen(), and if after 5 seconds nothing started yet
  1856. // aborts the test.
  1857. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1858. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1859. ASSERT_LT(milliseconds, 5000U);
  1860. }
  1861. {
  1862. Client cli("http://[::1]:1234");
  1863. cli.set_follow_location(true);
  1864. std::string body;
  1865. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1866. body.append(data, data_length);
  1867. return true;
  1868. });
  1869. ASSERT_TRUE(res);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. EXPECT_EQ("Hello World!", body);
  1872. }
  1873. {
  1874. Client cli("http://[::1]:1234");
  1875. std::string body;
  1876. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1877. body.append(data, data_length);
  1878. return true;
  1879. });
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::Found_302, res->status);
  1882. EXPECT_EQ("___", body);
  1883. }
  1884. }
  1885. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1886. Server svr;
  1887. svr.Get("/foo", [](const Request &req, Response &res) {
  1888. auto a = req.params.find("a");
  1889. if (a != req.params.end()) {
  1890. res.set_content((*a).second, "text/plain");
  1891. res.status = StatusCode::OK_200;
  1892. } else {
  1893. res.status = StatusCode::BadRequest_400;
  1894. }
  1895. });
  1896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1897. auto se = detail::scope_exit([&] {
  1898. svr.stop();
  1899. thread.join();
  1900. ASSERT_FALSE(svr.is_running());
  1901. });
  1902. svr.wait_until_ready();
  1903. {
  1904. Client cli(HOST, PORT);
  1905. cli.set_path_encode(false);
  1906. auto res = cli.Get("/foo?a=explicitly+encoded");
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. // This expects it back with a space, as the `+` won't have been
  1910. // url-encoded, and server-side the params get decoded turning `+`
  1911. // into spaces.
  1912. EXPECT_EQ("explicitly encoded", res->body);
  1913. }
  1914. }
  1915. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1916. Server svr;
  1917. svr.Get("/", [](const Request &req, Response &) {
  1918. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. {
  1928. Client cli(HOST, PORT);
  1929. cli.set_path_encode(false);
  1930. auto res = cli.Get("/?something=%0A");
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. }
  1934. }
  1935. TEST(BindServerTest, DISABLED_BindDualStack) {
  1936. Server svr;
  1937. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1938. res.set_content("Hello World!", "text/plain");
  1939. });
  1940. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1941. auto se = detail::scope_exit([&] {
  1942. svr.stop();
  1943. thread.join();
  1944. ASSERT_FALSE(svr.is_running());
  1945. });
  1946. svr.wait_until_ready();
  1947. {
  1948. Client cli("127.0.0.1", PORT);
  1949. auto res = cli.Get("/1");
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::OK_200, res->status);
  1952. EXPECT_EQ("Hello World!", res->body);
  1953. }
  1954. {
  1955. Client cli("::1", PORT);
  1956. auto res = cli.Get("/1");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", res->body);
  1960. }
  1961. }
  1962. TEST(BindServerTest, BindAndListenSeparately) {
  1963. Server svr;
  1964. int port = svr.bind_to_any_port("0.0.0.0");
  1965. ASSERT_TRUE(svr.is_valid());
  1966. ASSERT_TRUE(port > 0);
  1967. svr.stop();
  1968. }
  1969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1970. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1972. CLIENT_CA_CERT_DIR);
  1973. int port = svr.bind_to_any_port("0.0.0.0");
  1974. ASSERT_TRUE(svr.is_valid());
  1975. ASSERT_TRUE(port > 0);
  1976. svr.stop();
  1977. }
  1978. #endif
  1979. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1980. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1981. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1982. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1983. int port = svr.bind_to_any_port("0.0.0.0");
  1984. ASSERT_TRUE(svr.is_valid());
  1985. ASSERT_TRUE(port > 0);
  1986. svr.stop();
  1987. }
  1988. #endif
  1989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1990. X509 *readCertificate(const std::string &strFileName) {
  1991. std::ifstream inStream(strFileName);
  1992. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1993. std::istreambuf_iterator<char>());
  1994. if (strCertPEM.empty()) return (nullptr);
  1995. BIO *pbCert = BIO_new(BIO_s_mem());
  1996. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1997. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1998. BIO_free(pbCert);
  1999. return (pCert);
  2000. }
  2001. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2002. std::ifstream inStream(strFileName);
  2003. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2004. std::istreambuf_iterator<char>());
  2005. if (strPrivateKeyPEM.empty()) return (nullptr);
  2006. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2007. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2008. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2009. BIO_free(pbPrivKey);
  2010. return (pPrivateKey);
  2011. }
  2012. TEST(BindServerTest, UpdateCerts) {
  2013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2014. int port = svr.bind_to_any_port("0.0.0.0");
  2015. ASSERT_TRUE(svr.is_valid());
  2016. ASSERT_TRUE(port > 0);
  2017. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2018. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2019. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2020. ASSERT_TRUE(cert != nullptr);
  2021. ASSERT_TRUE(ca_cert != nullptr);
  2022. ASSERT_TRUE(key != nullptr);
  2023. X509_STORE *cert_store = X509_STORE_new();
  2024. X509_STORE_add_cert(cert_store, ca_cert);
  2025. svr.update_certs(cert, key, cert_store);
  2026. ASSERT_TRUE(svr.is_valid());
  2027. svr.stop();
  2028. X509_free(cert);
  2029. X509_free(ca_cert);
  2030. EVP_PKEY_free(key);
  2031. }
  2032. #endif
  2033. TEST(ErrorHandlerTest, ContentLength) {
  2034. Server svr;
  2035. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2036. res.status = StatusCode::OK_200;
  2037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2038. "text/html"); // <= Content-Length still 13
  2039. });
  2040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2041. res.set_content("Hello World!\n", "text/plain");
  2042. res.status = 524;
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. Client cli(HOST, PORT);
  2053. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(StatusCode::OK_200, res->status);
  2056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2057. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2058. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2059. }
  2060. }
  2061. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2062. TEST(ExceptionTest, WithoutExceptionHandler) {
  2063. Server svr;
  2064. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2065. throw std::runtime_error("exception...");
  2066. });
  2067. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2068. throw std::runtime_error("exception\r\n...");
  2069. });
  2070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2071. auto se = detail::scope_exit([&] {
  2072. svr.stop();
  2073. listen_thread.join();
  2074. ASSERT_FALSE(svr.is_running());
  2075. });
  2076. svr.wait_until_ready();
  2077. Client cli("localhost", PORT);
  2078. {
  2079. auto res = cli.Get("/exception");
  2080. ASSERT_TRUE(res);
  2081. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2082. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2083. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2084. }
  2085. {
  2086. auto res = cli.Get("/unknown");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2089. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2090. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2091. }
  2092. }
  2093. TEST(ExceptionTest, WithExceptionHandler) {
  2094. Server svr;
  2095. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2096. std::exception_ptr ep) {
  2097. EXPECT_FALSE(ep == nullptr);
  2098. try {
  2099. std::rethrow_exception(ep);
  2100. } catch (std::exception &e) {
  2101. EXPECT_EQ("abc", std::string(e.what()));
  2102. } catch (...) {}
  2103. res.status = StatusCode::InternalServerError_500;
  2104. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2105. "text/html"); // <= Content-Length still 13 at this point
  2106. });
  2107. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2108. res.set_content("Hello World!\n", "text/plain");
  2109. throw std::runtime_error("abc");
  2110. });
  2111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2112. auto se = detail::scope_exit([&] {
  2113. svr.stop();
  2114. thread.join();
  2115. ASSERT_FALSE(svr.is_running());
  2116. });
  2117. svr.wait_until_ready();
  2118. for (size_t i = 0; i < 10; i++) {
  2119. Client cli(HOST, PORT);
  2120. for (size_t j = 0; j < 100; j++) {
  2121. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2127. }
  2128. cli.set_keep_alive(true);
  2129. for (size_t j = 0; j < 100; j++) {
  2130. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2131. ASSERT_TRUE(res);
  2132. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2134. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2135. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2136. }
  2137. }
  2138. }
  2139. TEST(ExceptionTest, AndErrorHandler) {
  2140. Server svr;
  2141. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2142. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2143. });
  2144. svr.set_exception_handler(
  2145. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2146. EXPECT_FALSE(ep == nullptr);
  2147. try {
  2148. std::rethrow_exception(ep);
  2149. } catch (std::exception &e) {
  2150. res.set_content(e.what(), "text/html");
  2151. } catch (...) {}
  2152. res.status = StatusCode::InternalServerError_500;
  2153. });
  2154. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2155. throw std::runtime_error("EXCEPTION");
  2156. });
  2157. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2158. res.set_content("ERROR", "text/html");
  2159. res.status = StatusCode::InternalServerError_500;
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. {
  2170. auto res = cli.Get("/exception");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2173. EXPECT_EQ("EXCEPTION", res->body);
  2174. }
  2175. {
  2176. auto res = cli.Get("/error");
  2177. ASSERT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2179. EXPECT_EQ("ERROR", res->body);
  2180. }
  2181. {
  2182. auto res = cli.Get("/invalid");
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2185. EXPECT_EQ("NOT_FOUND", res->body);
  2186. }
  2187. }
  2188. #endif
  2189. TEST(NoContentTest, ContentLength) {
  2190. Server svr;
  2191. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2192. res.status = StatusCode::NoContent_204;
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. {
  2202. Client cli(HOST, PORT);
  2203. auto res = cli.Get("/hi");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2206. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2207. }
  2208. }
  2209. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2212. ASSERT_TRUE(svr.is_valid());
  2213. #else
  2214. Server svr;
  2215. #endif
  2216. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2217. if (req.path == "/routing_handler") {
  2218. res.set_header("PRE_ROUTING", "on");
  2219. res.set_content("Routing Handler", "text/plain");
  2220. return httplib::Server::HandlerResponse::Handled;
  2221. }
  2222. return httplib::Server::HandlerResponse::Unhandled;
  2223. });
  2224. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2225. res.set_content("Error", "text/html");
  2226. });
  2227. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2228. if (req.path == "/routing_handler") {
  2229. res.set_header("POST_ROUTING", "on");
  2230. }
  2231. });
  2232. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2233. res.set_content("Hello World!\n", "text/plain");
  2234. });
  2235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2236. auto se = detail::scope_exit([&] {
  2237. svr.stop();
  2238. thread.join();
  2239. ASSERT_FALSE(svr.is_running());
  2240. });
  2241. svr.wait_until_ready();
  2242. {
  2243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2244. SSLClient cli(HOST, PORT);
  2245. cli.enable_server_certificate_verification(false);
  2246. #else
  2247. Client cli(HOST, PORT);
  2248. #endif
  2249. auto res = cli.Get("/routing_handler");
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(StatusCode::OK_200, res->status);
  2252. EXPECT_EQ("Routing Handler", res->body);
  2253. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2254. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2255. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2256. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2257. }
  2258. {
  2259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2260. SSLClient cli(HOST, PORT);
  2261. cli.enable_server_certificate_verification(false);
  2262. #else
  2263. Client cli(HOST, PORT);
  2264. #endif
  2265. auto res = cli.Get("/hi");
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ("Hello World!\n", res->body);
  2269. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2270. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2271. }
  2272. {
  2273. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2274. SSLClient cli(HOST, PORT);
  2275. cli.enable_server_certificate_verification(false);
  2276. #else
  2277. Client cli(HOST, PORT);
  2278. #endif
  2279. auto res = cli.Get("/aaa");
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2282. EXPECT_EQ("Error", res->body);
  2283. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2284. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2285. }
  2286. }
  2287. TEST(RequestHandlerTest, PreRequestHandler) {
  2288. auto route_path = "/user/:user";
  2289. Server svr;
  2290. svr.Get("/hi", [](const Request &, Response &res) {
  2291. res.set_content("hi", "text/plain");
  2292. });
  2293. svr.Get(route_path, [](const Request &req, Response &res) {
  2294. res.set_content(req.path_params.at("user"), "text/plain");
  2295. });
  2296. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2297. if (req.matched_route == route_path) {
  2298. auto user = req.path_params.at("user");
  2299. if (user != "john") {
  2300. res.status = StatusCode::Forbidden_403;
  2301. res.set_content("error", "text/html");
  2302. return Server::HandlerResponse::Handled;
  2303. }
  2304. }
  2305. return Server::HandlerResponse::Unhandled;
  2306. });
  2307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2308. auto se = detail::scope_exit([&] {
  2309. svr.stop();
  2310. thread.join();
  2311. ASSERT_FALSE(svr.is_running());
  2312. });
  2313. svr.wait_until_ready();
  2314. Client cli(HOST, PORT);
  2315. {
  2316. auto res = cli.Get("/hi");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::OK_200, res->status);
  2319. EXPECT_EQ("hi", res->body);
  2320. }
  2321. {
  2322. auto res = cli.Get("/user/john");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::OK_200, res->status);
  2325. EXPECT_EQ("john", res->body);
  2326. }
  2327. {
  2328. auto res = cli.Get("/user/invalid-user");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2331. EXPECT_EQ("error", res->body);
  2332. }
  2333. }
  2334. TEST(InvalidFormatTest, StatusCode) {
  2335. Server svr;
  2336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!\n", "text/plain");
  2338. res.status = 9999; // Status should be a three-digit code...
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. {
  2348. Client cli(HOST, PORT);
  2349. auto res = cli.Get("/hi");
  2350. ASSERT_FALSE(res);
  2351. }
  2352. }
  2353. TEST(URLFragmentTest, WithFragment) {
  2354. Server svr;
  2355. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2356. EXPECT_TRUE(req.target == "/hi");
  2357. });
  2358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2359. auto se = detail::scope_exit([&] {
  2360. svr.stop();
  2361. thread.join();
  2362. ASSERT_FALSE(svr.is_running());
  2363. });
  2364. svr.wait_until_ready();
  2365. {
  2366. Client cli(HOST, PORT);
  2367. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2368. EXPECT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. res = cli.Get("/hi%23key1=val1=key2=val2");
  2371. EXPECT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. }
  2374. }
  2375. TEST(HeaderWriter, SetHeaderWriter) {
  2376. Server svr;
  2377. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2378. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2379. return detail::write_headers(strm, hdrs);
  2380. });
  2381. svr.Get("/hi", [](const Request &req, Response &res) {
  2382. auto it = req.headers.find("CustomClientHeader");
  2383. EXPECT_TRUE(it != req.headers.end());
  2384. EXPECT_EQ(it->second, "CustomClientValue");
  2385. res.set_content("Hello World!\n", "text/plain");
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. {
  2395. Client cli(HOST, PORT);
  2396. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2397. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2398. return detail::write_headers(strm, hdrs);
  2399. });
  2400. auto res = cli.Get("/hi");
  2401. EXPECT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::OK_200, res->status);
  2403. auto it = res->headers.find("CustomServerHeader");
  2404. EXPECT_TRUE(it != res->headers.end());
  2405. EXPECT_EQ(it->second, "CustomServerValue");
  2406. }
  2407. }
  2408. class ServerTest : public ::testing::Test {
  2409. protected:
  2410. ServerTest()
  2411. : cli_(HOST, PORT)
  2412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2413. ,
  2414. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2415. #endif
  2416. {
  2417. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2418. cli_.enable_server_certificate_verification(false);
  2419. #endif
  2420. }
  2421. virtual void SetUp() {
  2422. svr_.set_mount_point("/", "./www");
  2423. svr_.set_mount_point("/mount", "./www2");
  2424. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2425. svr_.Get("/hi",
  2426. [&](const Request & /*req*/, Response &res) {
  2427. res.set_content("Hello World!", "text/plain");
  2428. })
  2429. .Get("/file_content",
  2430. [&](const Request & /*req*/, Response &res) {
  2431. res.set_file_content("./www/dir/test.html");
  2432. })
  2433. .Get("/file_content_with_content_type",
  2434. [&](const Request & /*req*/, Response &res) {
  2435. res.set_file_content("./www/file", "text/plain");
  2436. })
  2437. .Get("/invalid_file_content",
  2438. [&](const Request & /*req*/, Response &res) {
  2439. res.set_file_content("./www/dir/invalid_file_path");
  2440. })
  2441. .Get("/http_response_splitting",
  2442. [&](const Request & /*req*/, Response &res) {
  2443. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2444. EXPECT_EQ(0U, res.headers.size());
  2445. EXPECT_FALSE(res.has_header("a"));
  2446. res.set_header("a", "1\nSet-Cookie: a=1");
  2447. EXPECT_EQ(0U, res.headers.size());
  2448. EXPECT_FALSE(res.has_header("a"));
  2449. res.set_header("a", "1\rSet-Cookie: a=1");
  2450. EXPECT_EQ(0U, res.headers.size());
  2451. EXPECT_FALSE(res.has_header("a"));
  2452. res.set_header("a\r\nb", "0");
  2453. EXPECT_EQ(0U, res.headers.size());
  2454. EXPECT_FALSE(res.has_header("a"));
  2455. res.set_header("a\rb", "0");
  2456. EXPECT_EQ(0U, res.headers.size());
  2457. EXPECT_FALSE(res.has_header("a"));
  2458. res.set_header("a\nb", "0");
  2459. EXPECT_EQ(0U, res.headers.size());
  2460. EXPECT_FALSE(res.has_header("a"));
  2461. res.set_redirect("1\r\nSet-Cookie: a=1");
  2462. EXPECT_EQ(0U, res.headers.size());
  2463. EXPECT_FALSE(res.has_header("Location"));
  2464. })
  2465. .Get("/slow",
  2466. [&](const Request & /*req*/, Response &res) {
  2467. std::this_thread::sleep_for(std::chrono::seconds(2));
  2468. res.set_content("slow", "text/plain");
  2469. })
  2470. #if 0
  2471. .Post("/slowpost",
  2472. [&](const Request & /*req*/, Response &res) {
  2473. std::this_thread::sleep_for(std::chrono::seconds(2));
  2474. res.set_content("slow", "text/plain");
  2475. })
  2476. #endif
  2477. .Get("/remote_addr",
  2478. [&](const Request &req, Response &res) {
  2479. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2480. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2481. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2482. EXPECT_EQ(req.remote_port,
  2483. std::stoi(req.get_header_value("REMOTE_PORT")));
  2484. res.set_content(remote_addr.c_str(), "text/plain");
  2485. })
  2486. .Get("/local_addr",
  2487. [&](const Request &req, Response &res) {
  2488. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2489. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2490. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2491. auto local_port = req.get_header_value("LOCAL_PORT");
  2492. EXPECT_EQ(req.local_addr, local_addr);
  2493. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2494. res.set_content(local_addr.append(":").append(local_port),
  2495. "text/plain");
  2496. })
  2497. .Get("/endwith%",
  2498. [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. })
  2501. .Get("/a\\+\\+b",
  2502. [&](const Request &req, Response &res) {
  2503. ASSERT_TRUE(req.has_param("a +b"));
  2504. auto val = req.get_param_value("a +b");
  2505. res.set_content(val, "text/plain");
  2506. })
  2507. .Get("/", [&](const Request & /*req*/,
  2508. Response &res) { res.set_redirect("/hi"); })
  2509. .Post("/1",
  2510. [](const Request & /*req*/, Response &res) {
  2511. res.set_redirect("/2", StatusCode::SeeOther_303);
  2512. })
  2513. .Get("/2",
  2514. [](const Request & /*req*/, Response &res) {
  2515. res.set_content("redirected.", "text/plain");
  2516. res.status = StatusCode::OK_200;
  2517. })
  2518. .Post("/person",
  2519. [&](const Request &req, Response &res) {
  2520. if (req.has_param("name") && req.has_param("note")) {
  2521. persons_[req.get_param_value("name")] =
  2522. req.get_param_value("note");
  2523. } else {
  2524. res.status = StatusCode::BadRequest_400;
  2525. }
  2526. })
  2527. .Put("/person",
  2528. [&](const Request &req, Response &res) {
  2529. if (req.has_param("name") && req.has_param("note")) {
  2530. persons_[req.get_param_value("name")] =
  2531. req.get_param_value("note");
  2532. } else {
  2533. res.status = StatusCode::BadRequest_400;
  2534. }
  2535. })
  2536. .Get("/person/(.*)",
  2537. [&](const Request &req, Response &res) {
  2538. string name = req.matches[1];
  2539. if (persons_.find(name) != persons_.end()) {
  2540. auto note = persons_[name];
  2541. res.set_content(note, "text/plain");
  2542. } else {
  2543. res.status = StatusCode::NotFound_404;
  2544. }
  2545. })
  2546. .Delete("/person",
  2547. [&](const Request &req, Response &res) {
  2548. if (req.has_param("name")) {
  2549. string name = req.get_param_value("name");
  2550. if (persons_.find(name) != persons_.end()) {
  2551. persons_.erase(name);
  2552. res.set_content("DELETED", "text/plain");
  2553. } else {
  2554. res.status = StatusCode::NotFound_404;
  2555. }
  2556. } else {
  2557. res.status = StatusCode::BadRequest_400;
  2558. }
  2559. })
  2560. .Post("/x-www-form-urlencoded-json",
  2561. [&](const Request &req, Response &res) {
  2562. auto json = req.get_param_value("json");
  2563. ASSERT_EQ(JSON_DATA, json);
  2564. res.set_content(json, "appliation/json");
  2565. res.status = StatusCode::OK_200;
  2566. })
  2567. .Get("/streamed-chunked",
  2568. [&](const Request & /*req*/, Response &res) {
  2569. res.set_chunked_content_provider(
  2570. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2571. sink.os << "123";
  2572. sink.os << "456";
  2573. sink.os << "789";
  2574. sink.done();
  2575. return true;
  2576. });
  2577. })
  2578. .Get("/streamed-chunked2",
  2579. [&](const Request & /*req*/, Response &res) {
  2580. auto i = new int(0);
  2581. res.set_chunked_content_provider(
  2582. "text/plain",
  2583. [i](size_t /*offset*/, DataSink &sink) {
  2584. switch (*i) {
  2585. case 0: sink.os << "123"; break;
  2586. case 1: sink.os << "456"; break;
  2587. case 2: sink.os << "789"; break;
  2588. case 3: sink.done(); break;
  2589. }
  2590. (*i)++;
  2591. return true;
  2592. },
  2593. [i](bool success) {
  2594. EXPECT_TRUE(success);
  2595. delete i;
  2596. });
  2597. })
  2598. .Get("/streamed-chunked-with-trailer",
  2599. [&](const Request & /*req*/, Response &res) {
  2600. auto i = new int(0);
  2601. res.set_header("Trailer", "Dummy1, Dummy2");
  2602. res.set_chunked_content_provider(
  2603. "text/plain",
  2604. [i](size_t /*offset*/, DataSink &sink) {
  2605. switch (*i) {
  2606. case 0: sink.os << "123"; break;
  2607. case 1: sink.os << "456"; break;
  2608. case 2: sink.os << "789"; break;
  2609. case 3: {
  2610. sink.done_with_trailer(
  2611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2612. } break;
  2613. }
  2614. (*i)++;
  2615. return true;
  2616. },
  2617. [i](bool success) {
  2618. EXPECT_TRUE(success);
  2619. delete i;
  2620. });
  2621. })
  2622. .Get("/streamed",
  2623. [&](const Request & /*req*/, Response &res) {
  2624. res.set_content_provider(
  2625. 6, "text/plain",
  2626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2627. sink.os << (offset < 3 ? "a" : "b");
  2628. return true;
  2629. });
  2630. })
  2631. .Get("/streamed-with-range",
  2632. [&](const Request &req, Response &res) {
  2633. auto data = new std::string("abcdefg");
  2634. res.set_content_provider(
  2635. data->size(), "text/plain",
  2636. [data](size_t offset, size_t length, DataSink &sink) {
  2637. size_t DATA_CHUNK_SIZE = 4;
  2638. const auto &d = *data;
  2639. auto out_len =
  2640. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2641. auto ret =
  2642. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2643. EXPECT_TRUE(ret);
  2644. return true;
  2645. },
  2646. [data, &req](bool success) {
  2647. EXPECT_EQ(success, !req.has_param("error"));
  2648. delete data;
  2649. });
  2650. })
  2651. .Get("/streamed-cancel",
  2652. [&](const Request & /*req*/, Response &res) {
  2653. res.set_content_provider(
  2654. size_t(-1), "text/plain",
  2655. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2656. sink.os << "data_chunk";
  2657. return true;
  2658. });
  2659. })
  2660. .Get("/regex-with-delimiter",
  2661. [&](const Request &req, Response & /*res*/) {
  2662. ASSERT_TRUE(req.has_param("key"));
  2663. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2664. })
  2665. .Get("/with-range",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. res.set_content("abcdefg", "text/plain");
  2668. })
  2669. .Get("/test-start-time",
  2670. [&](const Request &req, Response & /*res*/) {
  2671. EXPECT_NE(req.start_time_,
  2672. std::chrono::steady_clock::time_point::min());
  2673. })
  2674. .Get("/with-range-customized-response",
  2675. [&](const Request & /*req*/, Response &res) {
  2676. res.status = StatusCode::BadRequest_400;
  2677. res.set_content(JSON_DATA, "application/json");
  2678. })
  2679. .Post("/chunked",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(req.body, "dechunked post body");
  2682. })
  2683. .Post("/large-chunked",
  2684. [&](const Request &req, Response & /*res*/) {
  2685. std::string expected(6 * 30 * 1024u, 'a');
  2686. EXPECT_EQ(req.body, expected);
  2687. })
  2688. .Post("/multipart",
  2689. [&](const Request &req, Response & /*res*/) {
  2690. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2691. req.form.get_field_count("text2") +
  2692. req.form.get_field_count("file3") +
  2693. req.form.get_field_count("file4"));
  2694. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2695. req.form.get_file_count("file2"));
  2696. ASSERT_TRUE(!req.form.has_file("???"));
  2697. ASSERT_TRUE(!req.form.has_field("???"));
  2698. ASSERT_TRUE(req.body.empty());
  2699. {
  2700. const auto &text = req.form.get_field("text1");
  2701. EXPECT_EQ("text default", text);
  2702. }
  2703. {
  2704. const auto &text = req.form.get_field("text2");
  2705. EXPECT_EQ("aωb", text);
  2706. }
  2707. {
  2708. const auto &file = req.form.get_file("file1");
  2709. EXPECT_EQ("hello.txt", file.filename);
  2710. EXPECT_EQ("text/plain", file.content_type);
  2711. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2712. }
  2713. {
  2714. const auto &file = req.form.get_file("file2");
  2715. EXPECT_EQ("world.json", file.filename);
  2716. EXPECT_EQ("application/json", file.content_type);
  2717. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2718. }
  2719. {
  2720. const auto &text = req.form.get_field("file3");
  2721. EXPECT_EQ(0u, text.size());
  2722. }
  2723. {
  2724. const auto &text = req.form.get_field("file4");
  2725. EXPECT_EQ(0u, text.size());
  2726. }
  2727. })
  2728. .Post("/multipart/multi_file_values",
  2729. [&](const Request &req, Response & /*res*/) {
  2730. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2731. req.form.get_field_count("multi_text1"));
  2732. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2733. ASSERT_TRUE(!req.form.has_file("???"));
  2734. ASSERT_TRUE(!req.form.has_field("???"));
  2735. ASSERT_TRUE(req.body.empty());
  2736. {
  2737. const auto &text = req.form.get_field("text");
  2738. EXPECT_EQ("default text", text);
  2739. }
  2740. {
  2741. const auto &text1_values = req.form.get_fields("multi_text1");
  2742. EXPECT_EQ(2u, text1_values.size());
  2743. EXPECT_EQ("aaaaa", text1_values[0]);
  2744. EXPECT_EQ("bbbbb", text1_values[1]);
  2745. }
  2746. {
  2747. const auto &file1_values = req.form.get_files("multi_file1");
  2748. EXPECT_EQ(2u, file1_values.size());
  2749. auto file1 = file1_values[0];
  2750. EXPECT_EQ(file1.filename, "hello.txt");
  2751. EXPECT_EQ(file1.content_type, "text/plain");
  2752. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2753. auto file2 = file1_values[1];
  2754. EXPECT_EQ(file2.filename, "world.json");
  2755. EXPECT_EQ(file2.content_type, "application/json");
  2756. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2757. }
  2758. })
  2759. .Post("/empty",
  2760. [&](const Request &req, Response &res) {
  2761. EXPECT_EQ(req.body, "");
  2762. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2763. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2764. res.set_content("empty", "text/plain");
  2765. })
  2766. .Post("/empty-no-content-type",
  2767. [&](const Request &req, Response &res) {
  2768. EXPECT_EQ(req.body, "");
  2769. EXPECT_FALSE(req.has_header("Content-Type"));
  2770. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2771. res.set_content("empty-no-content-type", "text/plain");
  2772. })
  2773. .Post("/path-only",
  2774. [&](const Request &req, Response &res) {
  2775. EXPECT_EQ(req.body, "");
  2776. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2777. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2778. res.set_content("path-only", "text/plain");
  2779. })
  2780. .Post("/path-headers-only",
  2781. [&](const Request &req, Response &res) {
  2782. EXPECT_EQ(req.body, "");
  2783. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2784. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2785. EXPECT_EQ("world", req.get_header_value("hello"));
  2786. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2787. res.set_content("path-headers-only", "text/plain");
  2788. })
  2789. .Post("/post-large",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, LARGE_DATA);
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Put("/empty-no-content-type",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(req.body, "");
  2797. EXPECT_FALSE(req.has_header("Content-Type"));
  2798. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2799. res.set_content("empty-no-content-type", "text/plain");
  2800. })
  2801. .Put("/put",
  2802. [&](const Request &req, Response &res) {
  2803. EXPECT_EQ(req.body, "PUT");
  2804. res.set_content(req.body, "text/plain");
  2805. })
  2806. .Put("/put-large",
  2807. [&](const Request &req, Response &res) {
  2808. EXPECT_EQ(req.body, LARGE_DATA);
  2809. res.set_content(req.body, "text/plain");
  2810. })
  2811. .Patch("/patch",
  2812. [&](const Request &req, Response &res) {
  2813. EXPECT_EQ(req.body, "PATCH");
  2814. res.set_content(req.body, "text/plain");
  2815. })
  2816. .Delete("/delete",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. res.set_content("DELETE", "text/plain");
  2819. })
  2820. .Delete("/delete-body",
  2821. [&](const Request &req, Response &res) {
  2822. EXPECT_EQ(req.body, "content");
  2823. res.set_content(req.body, "text/plain");
  2824. })
  2825. .Options(R"(\*)",
  2826. [&](const Request & /*req*/, Response &res) {
  2827. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2828. })
  2829. .Get("/request-target",
  2830. [&](const Request &req, Response & /*res*/) {
  2831. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2832. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2833. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2834. })
  2835. .Get("/long-query-value",
  2836. [&](const Request &req, Response & /*res*/) {
  2837. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2838. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2839. })
  2840. .Get("/too-long-query-value",
  2841. [&](const Request &req, Response & /*res*/) {
  2842. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2843. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2844. })
  2845. .Get("/array-param",
  2846. [&](const Request &req, Response & /*res*/) {
  2847. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2848. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2849. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2850. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2851. })
  2852. .Post("/validate-no-multiple-headers",
  2853. [&](const Request &req, Response & /*res*/) {
  2854. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2855. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2856. })
  2857. .Post("/content_receiver",
  2858. [&](const Request &req, Response &res,
  2859. const ContentReader &content_reader) {
  2860. if (req.is_multipart_form_data()) {
  2861. std::vector<FormData> items;
  2862. content_reader(
  2863. [&](const FormData &file) {
  2864. items.push_back(file);
  2865. return true;
  2866. },
  2867. [&](const char *data, size_t data_length) {
  2868. items.back().content.append(data, data_length);
  2869. return true;
  2870. });
  2871. EXPECT_EQ(5u, items.size());
  2872. {
  2873. const auto &file = get_file_value(items, "text1");
  2874. EXPECT_TRUE(file.filename.empty());
  2875. EXPECT_EQ("text default", file.content);
  2876. }
  2877. {
  2878. const auto &file = get_file_value(items, "text2");
  2879. EXPECT_TRUE(file.filename.empty());
  2880. EXPECT_EQ("aωb", file.content);
  2881. }
  2882. {
  2883. const auto &file = get_file_value(items, "file1");
  2884. EXPECT_EQ("hello.txt", file.filename);
  2885. EXPECT_EQ("text/plain", file.content_type);
  2886. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2887. }
  2888. {
  2889. const auto &file = get_file_value(items, "file2");
  2890. EXPECT_EQ("world.json", file.filename);
  2891. EXPECT_EQ("application/json", file.content_type);
  2892. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2893. }
  2894. {
  2895. const auto &file = get_file_value(items, "file3");
  2896. EXPECT_TRUE(file.filename.empty());
  2897. EXPECT_EQ("application/octet-stream", file.content_type);
  2898. EXPECT_EQ(0u, file.content.size());
  2899. }
  2900. } else {
  2901. std::string body;
  2902. content_reader([&](const char *data, size_t data_length) {
  2903. EXPECT_EQ(7U, data_length);
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. EXPECT_EQ(body, "content");
  2908. res.set_content(body, "text/plain");
  2909. }
  2910. })
  2911. .Put("/content_receiver",
  2912. [&](const Request & /*req*/, Response &res,
  2913. const ContentReader &content_reader) {
  2914. std::string body;
  2915. content_reader([&](const char *data, size_t data_length) {
  2916. body.append(data, data_length);
  2917. return true;
  2918. });
  2919. EXPECT_EQ(body, "content");
  2920. res.set_content(body, "text/plain");
  2921. })
  2922. .Patch("/content_receiver",
  2923. [&](const Request & /*req*/, Response &res,
  2924. const ContentReader &content_reader) {
  2925. std::string body;
  2926. content_reader([&](const char *data, size_t data_length) {
  2927. body.append(data, data_length);
  2928. return true;
  2929. });
  2930. EXPECT_EQ(body, "content");
  2931. res.set_content(body, "text/plain");
  2932. })
  2933. .Post("/query-string-and-body",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. ASSERT_TRUE(req.has_param("key"));
  2936. EXPECT_EQ(req.get_param_value("key"), "value");
  2937. EXPECT_EQ(req.body, "content");
  2938. })
  2939. .Get("/last-request",
  2940. [&](const Request &req, Response & /*res*/) {
  2941. EXPECT_EQ("close", req.get_header_value("Connection"));
  2942. })
  2943. .Get(R"(/redirect/(\d+))",
  2944. [&](const Request &req, Response &res) {
  2945. auto num = std::stoi(req.matches[1]) + 1;
  2946. std::string url = "/redirect/" + std::to_string(num);
  2947. res.set_redirect(url);
  2948. })
  2949. .Post("/binary",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(4U, req.body.size());
  2952. EXPECT_EQ("application/octet-stream",
  2953. req.get_header_value("Content-Type"));
  2954. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2955. res.set_content(req.body, "application/octet-stream");
  2956. })
  2957. .Put("/binary",
  2958. [&](const Request &req, Response &res) {
  2959. EXPECT_EQ(4U, req.body.size());
  2960. EXPECT_EQ("application/octet-stream",
  2961. req.get_header_value("Content-Type"));
  2962. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2963. res.set_content(req.body, "application/octet-stream");
  2964. })
  2965. .Patch("/binary",
  2966. [&](const Request &req, Response &res) {
  2967. EXPECT_EQ(4U, req.body.size());
  2968. EXPECT_EQ("application/octet-stream",
  2969. req.get_header_value("Content-Type"));
  2970. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2971. res.set_content(req.body, "application/octet-stream");
  2972. })
  2973. .Delete("/binary",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(4U, req.body.size());
  2976. EXPECT_EQ("application/octet-stream",
  2977. req.get_header_value("Content-Type"));
  2978. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2979. res.set_content(req.body, "application/octet-stream");
  2980. })
  2981. .Get("/issue1772",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = 401;
  2984. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2985. })
  2986. .Delete("/issue609",
  2987. [](const httplib::Request &, httplib::Response &res,
  2988. const httplib::ContentReader &) {
  2989. res.set_content("ok", "text/plain");
  2990. })
  2991. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2992. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2993. .Get("/compress",
  2994. [&](const Request & /*req*/, Response &res) {
  2995. res.set_content(
  2996. "12345678901234567890123456789012345678901234567890123456789"
  2997. "01234567890123456789012345678901234567890",
  2998. "text/plain");
  2999. })
  3000. .Get("/nocompress",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content(
  3003. "12345678901234567890123456789012345678901234567890123456789"
  3004. "01234567890123456789012345678901234567890",
  3005. "application/octet-stream");
  3006. })
  3007. .Post("/compress-multipart",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_EQ(2u, req.form.fields.size());
  3010. ASSERT_TRUE(!req.form.has_field("???"));
  3011. {
  3012. const auto &text = req.form.get_field("key1");
  3013. EXPECT_EQ("test", text);
  3014. }
  3015. {
  3016. const auto &text = req.form.get_field("key2");
  3017. EXPECT_EQ("--abcdefg123", text);
  3018. }
  3019. })
  3020. #endif
  3021. ;
  3022. persons_["john"] = "programmer";
  3023. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3024. svr_.wait_until_ready();
  3025. }
  3026. virtual void TearDown() {
  3027. svr_.stop();
  3028. if (!request_threads_.empty()) {
  3029. std::this_thread::sleep_for(std::chrono::seconds(1));
  3030. for (auto &t : request_threads_) {
  3031. t.join();
  3032. }
  3033. }
  3034. t_.join();
  3035. }
  3036. map<string, string> persons_;
  3037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3038. SSLClient cli_;
  3039. SSLServer svr_;
  3040. #else
  3041. Client cli_;
  3042. Server svr_;
  3043. #endif
  3044. thread t_;
  3045. std::vector<thread> request_threads_;
  3046. };
  3047. TEST_F(ServerTest, GetMethod200) {
  3048. auto res = cli_.Get("/hi");
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ("HTTP/1.1", res->version);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. EXPECT_EQ("OK", res->reason);
  3053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3054. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3055. EXPECT_EQ("Hello World!", res->body);
  3056. }
  3057. void performance_test(const char *host) {
  3058. auto port = 1234;
  3059. Server svr;
  3060. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3061. res.set_content("Benchmark Response", "text/plain");
  3062. });
  3063. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. listen_thread.join();
  3067. ASSERT_FALSE(svr.is_running());
  3068. });
  3069. svr.wait_until_ready();
  3070. Client cli(host, port);
  3071. auto start = std::chrono::high_resolution_clock::now();
  3072. auto res = cli.Get("/benchmark");
  3073. ASSERT_TRUE(res);
  3074. EXPECT_EQ(StatusCode::OK_200, res->status);
  3075. auto end = std::chrono::high_resolution_clock::now();
  3076. auto elapsed =
  3077. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3078. .count();
  3079. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3080. << "ms (Issue #1777)";
  3081. }
  3082. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3083. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3084. TEST_F(ServerTest, GetEmptyFile) {
  3085. auto res = cli_.Get("/empty_file");
  3086. ASSERT_TRUE(res);
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3089. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3090. EXPECT_EQ("", res->body);
  3091. }
  3092. TEST_F(ServerTest, GetFileContent) {
  3093. auto res = cli_.Get("/file_content");
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3097. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3098. EXPECT_EQ("test.html", res->body);
  3099. }
  3100. TEST_F(ServerTest, GetFileContentWithRange) {
  3101. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3105. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3106. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3107. EXPECT_EQ("est", res->body);
  3108. }
  3109. TEST_F(ServerTest, GetFileContentWithContentType) {
  3110. auto res = cli_.Get("/file_content_with_content_type");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3114. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3115. EXPECT_EQ("file\n", res->body);
  3116. }
  3117. TEST_F(ServerTest, GetInvalidFileContent) {
  3118. auto res = cli_.Get("/invalid_file_content");
  3119. ASSERT_TRUE(res);
  3120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3121. }
  3122. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3123. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3124. ASSERT_TRUE(res);
  3125. EXPECT_EQ("HTTP/1.1", res->version);
  3126. EXPECT_EQ(StatusCode::OK_200, res->status);
  3127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3128. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3129. EXPECT_EQ("Hello World!", res->body);
  3130. }
  3131. TEST_F(ServerTest, GetMethod302) {
  3132. auto res = cli_.Get("/");
  3133. ASSERT_TRUE(res);
  3134. EXPECT_EQ(StatusCode::Found_302, res->status);
  3135. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3136. }
  3137. TEST_F(ServerTest, GetMethod302Redirect) {
  3138. cli_.set_follow_location(true);
  3139. auto res = cli_.Get("/");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. EXPECT_EQ("/hi", res->location);
  3144. }
  3145. TEST_F(ServerTest, GetMethod404) {
  3146. auto res = cli_.Get("/invalid");
  3147. ASSERT_TRUE(res);
  3148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3149. }
  3150. TEST_F(ServerTest, HeadMethod200) {
  3151. auto res = cli_.Head("/hi");
  3152. ASSERT_TRUE(res);
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3155. EXPECT_TRUE(res->body.empty());
  3156. }
  3157. TEST_F(ServerTest, HeadMethod200Static) {
  3158. auto res = cli_.Head("/mount/dir/index.html");
  3159. ASSERT_TRUE(res);
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3162. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3163. EXPECT_TRUE(res->body.empty());
  3164. }
  3165. TEST_F(ServerTest, HeadMethod404) {
  3166. auto res = cli_.Head("/invalid");
  3167. ASSERT_TRUE(res);
  3168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3169. EXPECT_TRUE(res->body.empty());
  3170. }
  3171. TEST_F(ServerTest, GetMethodPersonJohn) {
  3172. auto res = cli_.Get("/person/john");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3176. EXPECT_EQ("programmer", res->body);
  3177. }
  3178. TEST_F(ServerTest, PostMethod1) {
  3179. auto res = cli_.Get("/person/john1");
  3180. ASSERT_TRUE(res);
  3181. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3182. res = cli_.Post("/person", "name=john1&note=coder",
  3183. "application/x-www-form-urlencoded");
  3184. ASSERT_TRUE(res);
  3185. ASSERT_EQ(StatusCode::OK_200, res->status);
  3186. res = cli_.Get("/person/john1");
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::OK_200, res->status);
  3189. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3190. ASSERT_EQ("coder", res->body);
  3191. }
  3192. TEST_F(ServerTest, PostMethod2) {
  3193. auto res = cli_.Get("/person/john2");
  3194. ASSERT_TRUE(res);
  3195. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3196. Params params;
  3197. params.emplace("name", "john2");
  3198. params.emplace("note", "coder");
  3199. res = cli_.Post("/person", params);
  3200. ASSERT_TRUE(res);
  3201. ASSERT_EQ(StatusCode::OK_200, res->status);
  3202. res = cli_.Get("/person/john2");
  3203. ASSERT_TRUE(res);
  3204. ASSERT_EQ(StatusCode::OK_200, res->status);
  3205. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3206. ASSERT_EQ("coder", res->body);
  3207. }
  3208. TEST_F(ServerTest, PutMethod3) {
  3209. auto res = cli_.Get("/person/john3");
  3210. ASSERT_TRUE(res);
  3211. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3212. Params params;
  3213. params.emplace("name", "john3");
  3214. params.emplace("note", "coder");
  3215. res = cli_.Put("/person", params);
  3216. ASSERT_TRUE(res);
  3217. ASSERT_EQ(StatusCode::OK_200, res->status);
  3218. res = cli_.Get("/person/john3");
  3219. ASSERT_TRUE(res);
  3220. ASSERT_EQ(StatusCode::OK_200, res->status);
  3221. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. ASSERT_EQ("coder", res->body);
  3223. }
  3224. TEST_F(ServerTest, DeleteMethod1) {
  3225. auto res = cli_.Get("/person/john4");
  3226. ASSERT_TRUE(res);
  3227. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3228. Params params;
  3229. params.emplace("name", "john4");
  3230. params.emplace("note", "coder");
  3231. res = cli_.Post("/person", params);
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. res = cli_.Get("/person/john4");
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(StatusCode::OK_200, res->status);
  3237. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3238. ASSERT_EQ("coder", res->body);
  3239. Params delete_params;
  3240. delete_params.emplace("name", "john4");
  3241. res = cli_.Delete("/person", delete_params);
  3242. ASSERT_TRUE(res);
  3243. ASSERT_EQ(StatusCode::OK_200, res->status);
  3244. ASSERT_EQ("DELETED", res->body);
  3245. res = cli_.Get("/person/john4");
  3246. ASSERT_TRUE(res);
  3247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3248. }
  3249. TEST_F(ServerTest, DeleteMethod2) {
  3250. auto res = cli_.Get("/person/john5");
  3251. ASSERT_TRUE(res);
  3252. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3253. Params params;
  3254. params.emplace("name", "john5");
  3255. params.emplace("note", "developer");
  3256. res = cli_.Post("/person", params);
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. res = cli_.Get("/person/john5");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::OK_200, res->status);
  3262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. ASSERT_EQ("developer", res->body);
  3264. Params delete_params;
  3265. delete_params.emplace("name", "john5");
  3266. Headers headers;
  3267. headers.emplace("Custom-Header", "test-value");
  3268. res = cli_.Delete("/person", headers, delete_params);
  3269. ASSERT_TRUE(res);
  3270. ASSERT_EQ(StatusCode::OK_200, res->status);
  3271. ASSERT_EQ("DELETED", res->body);
  3272. res = cli_.Get("/person/john5");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3275. }
  3276. TEST_F(ServerTest, DeleteMethod3) {
  3277. auto res = cli_.Get("/person/john6");
  3278. ASSERT_TRUE(res);
  3279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3280. Params params;
  3281. params.emplace("name", "john6");
  3282. params.emplace("note", "tester");
  3283. res = cli_.Post("/person", params);
  3284. ASSERT_TRUE(res);
  3285. ASSERT_EQ(StatusCode::OK_200, res->status);
  3286. res = cli_.Get("/person/john6");
  3287. ASSERT_TRUE(res);
  3288. ASSERT_EQ(StatusCode::OK_200, res->status);
  3289. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3290. ASSERT_EQ("tester", res->body);
  3291. Params delete_params;
  3292. delete_params.emplace("name", "john6");
  3293. Headers headers;
  3294. headers.emplace("Custom-Header", "test-value");
  3295. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john6");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3304. Params params;
  3305. params.emplace("json", JSON_DATA);
  3306. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3307. ASSERT_TRUE(res);
  3308. ASSERT_EQ(StatusCode::OK_200, res->status);
  3309. ASSERT_EQ(JSON_DATA, res->body);
  3310. }
  3311. TEST_F(ServerTest, PostEmptyContent) {
  3312. auto res = cli_.Post("/empty", "", "text/plain");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::OK_200, res->status);
  3315. ASSERT_EQ("empty", res->body);
  3316. }
  3317. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3318. auto res = cli_.Post("/empty-no-content-type");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("empty-no-content-type", res->body);
  3322. }
  3323. TEST_F(ServerTest, PostPathOnly) {
  3324. auto res = cli_.Post("/path-only");
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::OK_200, res->status);
  3327. ASSERT_EQ("path-only", res->body);
  3328. }
  3329. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3330. auto res = cli_.Post("/path-headers-only",
  3331. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ("path-headers-only", res->body);
  3335. }
  3336. TEST_F(ServerTest, PostLarge) {
  3337. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. EXPECT_EQ(LARGE_DATA, res->body);
  3341. }
  3342. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3343. auto res = cli_.Put("/empty-no-content-type");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("empty-no-content-type", res->body);
  3347. }
  3348. TEST_F(ServerTest, GetMethodDir) {
  3349. auto res = cli_.Get("/dir/");
  3350. ASSERT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3353. auto body = R"(<html>
  3354. <head>
  3355. </head>
  3356. <body>
  3357. <a href="/dir/test.html">Test</a>
  3358. <a href="/hi">hi</a>
  3359. </body>
  3360. </html>
  3361. )";
  3362. EXPECT_EQ(body, res->body);
  3363. }
  3364. TEST_F(ServerTest, GetMethodDirTest) {
  3365. auto res = cli_.Get("/dir/test.html");
  3366. ASSERT_TRUE(res);
  3367. EXPECT_EQ(StatusCode::OK_200, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("test.html", res->body);
  3370. }
  3371. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3372. auto res = cli_.Get("/dir/../dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3376. EXPECT_EQ("test.html", res->body);
  3377. }
  3378. TEST_F(ServerTest, GetMethodInvalidPath) {
  3379. auto res = cli_.Get("/dir/../test.html");
  3380. ASSERT_TRUE(res);
  3381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3382. }
  3383. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3384. auto res = cli_.Get("/../www/dir/test.html");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3387. }
  3388. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3389. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3392. }
  3393. TEST_F(ServerTest, GetMethodDirMountTest) {
  3394. auto res = cli_.Get("/mount/dir/test.html");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ("test.html", res->body);
  3399. }
  3400. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3401. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::OK_200, res->status);
  3404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3405. EXPECT_EQ("test.html", res->body);
  3406. }
  3407. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3408. auto res = cli_.Get("/mount/dir/../test.html");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3413. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3418. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3421. }
  3422. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3423. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3426. }
  3427. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3428. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3429. ASSERT_TRUE(res);
  3430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3431. }
  3432. TEST_F(ServerTest, PostMethod303) {
  3433. auto res = cli_.Post("/1", "body", "text/plain");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3436. EXPECT_EQ("/2", res->get_header_value("Location"));
  3437. }
  3438. TEST_F(ServerTest, PostMethod303Redirect) {
  3439. cli_.set_follow_location(true);
  3440. auto res = cli_.Post("/1", "body", "text/plain");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("redirected.", res->body);
  3444. EXPECT_EQ("/2", res->location);
  3445. }
  3446. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3447. auto res = cli_.Get("/dir/test.abcde");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ("abcde", res->body);
  3452. }
  3453. TEST_F(ServerTest, StaticFileRange) {
  3454. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3457. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ(true, res->has_header("Content-Range"));
  3460. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3461. EXPECT_EQ(std::string("cd"), res->body);
  3462. }
  3463. TEST_F(ServerTest, StaticFileRanges) {
  3464. auto res =
  3465. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_TRUE(
  3469. res->get_header_value("Content-Type")
  3470. .find(
  3471. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3472. 0);
  3473. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3474. }
  3475. TEST_F(ServerTest, StaticFileRangeHead) {
  3476. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3480. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3481. EXPECT_EQ(true, res->has_header("Content-Range"));
  3482. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3483. }
  3484. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3485. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3486. ASSERT_TRUE(res);
  3487. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3489. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3490. EXPECT_EQ(true, res->has_header("Content-Range"));
  3491. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3492. res->get_header_value("Content-Range"));
  3493. EXPECT_EQ("LAST\n", res->body);
  3494. }
  3495. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3496. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3500. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3501. EXPECT_EQ(true, res->has_header("Content-Range"));
  3502. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3503. }
  3504. TEST_F(ServerTest, StaticFileBigFile) {
  3505. auto res = cli_.Get("/dir/1MB.txt");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3509. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3510. }
  3511. TEST_F(ServerTest, InvalidBaseDirMount) {
  3512. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3513. }
  3514. TEST_F(ServerTest, Binary) {
  3515. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3516. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3517. "application/octet-stream");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. ASSERT_EQ(4U, res->body.size());
  3521. res = cli_.Put("/binary", binary.data(), binary.size(),
  3522. "application/octet-stream");
  3523. ASSERT_TRUE(res);
  3524. ASSERT_EQ(StatusCode::OK_200, res->status);
  3525. ASSERT_EQ(4U, res->body.size());
  3526. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3527. "application/octet-stream");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. ASSERT_EQ(4U, res->body.size());
  3531. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3532. "application/octet-stream");
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. ASSERT_EQ(4U, res->body.size());
  3536. }
  3537. TEST_F(ServerTest, BinaryString) {
  3538. auto binary = std::string("\x00\x01\x02\x03", 4);
  3539. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ(4U, res->body.size());
  3543. res = cli_.Put("/binary", binary, "application/octet-stream");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::OK_200, res->status);
  3546. ASSERT_EQ(4U, res->body.size());
  3547. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ(4U, res->body.size());
  3551. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ(4U, res->body.size());
  3555. }
  3556. TEST_F(ServerTest, EmptyRequest) {
  3557. auto res = cli_.Get("");
  3558. ASSERT_TRUE(!res);
  3559. EXPECT_EQ(Error::Connection, res.error());
  3560. }
  3561. TEST_F(ServerTest, LongRequest) {
  3562. std::string request;
  3563. for (size_t i = 0; i < 545; i++) {
  3564. request += "/TooLongRequest";
  3565. }
  3566. request += "OK";
  3567. auto res = cli_.Get(request.c_str());
  3568. ASSERT_TRUE(res);
  3569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3570. }
  3571. TEST_F(ServerTest, TooLongRequest) {
  3572. std::string request;
  3573. for (size_t i = 0; i < 546; i++) {
  3574. request += "/TooLongRequest";
  3575. }
  3576. request += "_NG";
  3577. auto res = cli_.Get(request.c_str());
  3578. ASSERT_TRUE(res);
  3579. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3580. }
  3581. TEST_F(ServerTest, AlmostTooLongRequest) {
  3582. // test for #2046 - URI length check shouldn't include other content on req
  3583. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3584. // leading /, space, HTTP/1.1)
  3585. std::string request =
  3586. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3587. auto res = cli_.Get(request.c_str());
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3590. }
  3591. TEST_F(ServerTest, LongHeader) {
  3592. Request req;
  3593. req.method = "GET";
  3594. req.path = "/hi";
  3595. std::string host_and_port;
  3596. host_and_port += HOST;
  3597. host_and_port += ":";
  3598. host_and_port += std::to_string(PORT);
  3599. req.headers.emplace("Host", host_and_port.c_str());
  3600. req.headers.emplace("Accept", "*/*");
  3601. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3602. req.headers.emplace(
  3603. "Header-Name",
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@");
  3633. auto res = std::make_shared<Response>();
  3634. auto error = Error::Success;
  3635. auto ret = cli_.send(req, *res, error);
  3636. ASSERT_TRUE(ret);
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. }
  3639. TEST_F(ServerTest, LongQueryValue) {
  3640. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3643. }
  3644. TEST_F(ServerTest, TooLongQueryValue) {
  3645. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3646. ASSERT_FALSE(res);
  3647. EXPECT_EQ(Error::Read, res.error());
  3648. }
  3649. TEST_F(ServerTest, TooLongHeader) {
  3650. Request req;
  3651. req.method = "GET";
  3652. req.path = "/hi";
  3653. std::string host_and_port;
  3654. host_and_port += HOST;
  3655. host_and_port += ":";
  3656. host_and_port += std::to_string(PORT);
  3657. req.headers.emplace("Host", host_and_port.c_str());
  3658. req.headers.emplace("Accept", "*/*");
  3659. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3660. req.headers.emplace(
  3661. "Header-Name",
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@");
  3691. auto res = std::make_shared<Response>();
  3692. auto error = Error::Success;
  3693. auto ret = cli_.send(req, *res, error);
  3694. ASSERT_TRUE(ret);
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. }
  3697. TEST_F(ServerTest, HeaderCountAtLimit) {
  3698. // Test with headers just under the 100 limit
  3699. httplib::Headers headers;
  3700. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3701. // This should keep us just under the 100 header limit
  3702. for (int i = 0; i < 95; i++) {
  3703. std::string name = "X-Test-Header-" + std::to_string(i);
  3704. std::string value = "value" + std::to_string(i);
  3705. headers.emplace(name, value);
  3706. }
  3707. // This should work fine as we're under the limit
  3708. auto res = cli_.Get("/hi", headers);
  3709. EXPECT_TRUE(res);
  3710. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3711. }
  3712. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3713. // Test with many headers to exceed the 100 limit
  3714. httplib::Headers headers;
  3715. // Add 150 headers to definitely exceed the 100 limit
  3716. for (int i = 0; i < 150; i++) {
  3717. std::string name = "X-Test-Header-" + std::to_string(i);
  3718. std::string value = "value" + std::to_string(i);
  3719. headers.emplace(name, value);
  3720. }
  3721. // This should fail due to exceeding header count limit
  3722. auto res = cli_.Get("/hi", headers);
  3723. // The request should either fail or return 400 Bad Request
  3724. if (res) {
  3725. // If we get a response, it should be 400 Bad Request
  3726. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3727. } else {
  3728. // Or the request should fail entirely
  3729. EXPECT_FALSE(res);
  3730. }
  3731. }
  3732. TEST_F(ServerTest, PercentEncoding) {
  3733. auto res = cli_.Get("/e%6edwith%");
  3734. ASSERT_TRUE(res);
  3735. EXPECT_EQ(StatusCode::OK_200, res->status);
  3736. }
  3737. TEST_F(ServerTest, PercentEncodingUnicode) {
  3738. auto res = cli_.Get("/e%u006edwith%");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, InvalidPercentEncoding) {
  3743. auto res = cli_.Get("/%endwith%");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3748. auto res = cli_.Get("/%uendwith%");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3753. auto res = cli_.Get("/hello?aaa=bbb%");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, PlusSignEncoding) {
  3758. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. EXPECT_EQ("a +b", res->body);
  3762. }
  3763. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3764. // This test simulates a potential DoS attack using many headers
  3765. // to verify our security fix prevents memory exhaustion
  3766. httplib::Headers attack_headers;
  3767. // Attempt to add many headers like an attacker would (200 headers to far
  3768. // exceed limit)
  3769. for (int i = 0; i < 200; i++) {
  3770. std::string name = "X-Attack-Header-" + std::to_string(i);
  3771. std::string value = "attack_payload_" + std::to_string(i);
  3772. attack_headers.emplace(name, value);
  3773. }
  3774. // Try to POST with excessive headers
  3775. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3776. // Should either fail or return 400 Bad Request due to security limit
  3777. if (res) {
  3778. // If we get a response, it should be 400 Bad Request
  3779. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3780. } else {
  3781. // Request failed, which is the expected behavior for DoS protection
  3782. EXPECT_FALSE(res);
  3783. }
  3784. }
  3785. TEST_F(ServerTest, MultipartFormData) {
  3786. UploadFormDataItems items = {
  3787. {"text1", "text default", "", ""},
  3788. {"text2", "aωb", "", ""},
  3789. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3790. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3791. {"file3", "", "", "application/octet-stream"},
  3792. {"file4", "", "", " application/json tmp-string "}};
  3793. auto res = cli_.Post("/multipart", items);
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::OK_200, res->status);
  3796. }
  3797. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3798. UploadFormDataItems items = {
  3799. {"text", "default text", "", ""},
  3800. {"multi_text1", "aaaaa", "", ""},
  3801. {"multi_text1", "bbbbb", "", ""},
  3802. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3803. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3804. "application/json"},
  3805. };
  3806. auto res = cli_.Post("/multipart/multi_file_values", items);
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. }
  3810. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3811. auto res = cli_.Get("/hi");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3815. EXPECT_EQ("Hello World!", res->body);
  3816. }
  3817. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3818. Request req;
  3819. req.method = "POST";
  3820. req.path = "/chunked";
  3821. std::string host_and_port;
  3822. host_and_port += HOST;
  3823. host_and_port += ":";
  3824. host_and_port += std::to_string(PORT);
  3825. req.headers.emplace("Host", host_and_port.c_str());
  3826. req.headers.emplace("Accept", "*/*");
  3827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3828. req.headers.emplace("Content-Type", "text/plain");
  3829. req.headers.emplace("Content-Length", "0");
  3830. req.headers.emplace(
  3831. "Transfer-Encoding",
  3832. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3833. // Client does not chunk, so make a chunked body manually.
  3834. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3835. auto res = std::make_shared<Response>();
  3836. auto error = Error::Success;
  3837. auto ret = cli_.send(req, *res, error);
  3838. ASSERT_TRUE(ret);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. }
  3841. TEST_F(ServerTest, GetStreamed2) {
  3842. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3845. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3846. EXPECT_EQ(true, res->has_header("Content-Range"));
  3847. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3848. EXPECT_EQ(std::string("ab"), res->body);
  3849. }
  3850. TEST_F(ServerTest, GetStreamed) {
  3851. auto res = cli_.Get("/streamed");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::OK_200, res->status);
  3854. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3855. EXPECT_EQ(std::string("aaabbb"), res->body);
  3856. }
  3857. TEST_F(ServerTest, GetStreamedWithRange1) {
  3858. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3859. ASSERT_TRUE(res);
  3860. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3861. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3862. EXPECT_EQ(true, res->has_header("Content-Range"));
  3863. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3864. EXPECT_EQ(std::string("def"), res->body);
  3865. }
  3866. TEST_F(ServerTest, GetStreamedWithRange2) {
  3867. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3870. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3871. EXPECT_EQ(true, res->has_header("Content-Range"));
  3872. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3873. EXPECT_EQ(std::string("bcdefg"), res->body);
  3874. }
  3875. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3876. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3879. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3880. EXPECT_EQ(true, res->has_header("Content-Range"));
  3881. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3882. EXPECT_EQ(std::string("efg"), res->body);
  3883. }
  3884. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3885. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3888. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(false, res->has_header("Content-Range"));
  3890. EXPECT_EQ(0U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3893. auto res = cli_.Get("/streamed-with-range",
  3894. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3895. "92233720368547758079223372036854775807"}});
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3898. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3899. EXPECT_EQ(false, res->has_header("Content-Range"));
  3900. EXPECT_EQ(0U, res->body.size());
  3901. }
  3902. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3903. auto res = cli_.Get(
  3904. "/with-range",
  3905. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3906. {"Accept-Encoding", ""}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(true, res->has_header("Content-Range"));
  3911. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3912. EXPECT_EQ(std::string("abcdefg"), res->body);
  3913. }
  3914. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3915. auto res = cli_.Get("/with-range", {
  3916. {"Range", "bytes=0-"},
  3917. {"Accept-Encoding", ""},
  3918. });
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3921. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3922. EXPECT_EQ(true, res->has_header("Content-Range"));
  3923. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3924. EXPECT_EQ(std::string("abcdefg"), res->body);
  3925. }
  3926. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3927. auto res =
  3928. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3929. ASSERT_TRUE(res);
  3930. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3931. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(false, res->has_header("Content-Range"));
  3933. EXPECT_EQ(267U, res->body.size());
  3934. // Check that both range contents are present
  3935. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3936. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3937. // Check that Content-Range headers are present for both ranges
  3938. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3939. std::string::npos);
  3940. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3941. std::string::npos);
  3942. }
  3943. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3944. Ranges ranges;
  3945. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3946. ranges.emplace_back(0, -1);
  3947. }
  3948. auto res =
  3949. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3952. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3953. EXPECT_EQ(false, res->has_header("Content-Range"));
  3954. EXPECT_EQ(0U, res->body.size());
  3955. }
  3956. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3957. auto res =
  3958. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ(5U, res->body.size());
  3962. // Check that overlapping ranges are coalesced into a single range
  3963. EXPECT_EQ("bcdef", res->body);
  3964. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3965. // Should be single range, not multipart
  3966. EXPECT_TRUE(res->has_header("Content-Range"));
  3967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3968. }
  3969. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3970. auto res =
  3971. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3974. EXPECT_EQ(268U, res->body.size());
  3975. // Check that both range contents are present
  3976. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3977. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3978. // Check that Content-Range headers are present for both ranges
  3979. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3980. std::string::npos);
  3981. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3982. std::string::npos);
  3983. }
  3984. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3985. auto res =
  3986. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3987. ASSERT_TRUE(res);
  3988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3989. EXPECT_EQ(269U, res->body.size());
  3990. // Check that both duplicate range contents are present
  3991. size_t first_abc = res->body.find("abc\r\n");
  3992. EXPECT_TRUE(first_abc != std::string::npos);
  3993. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3994. EXPECT_TRUE(second_abc != std::string::npos);
  3995. // Check that Content-Range headers are present for both ranges
  3996. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3997. EXPECT_TRUE(first_range != std::string::npos);
  3998. size_t second_range =
  3999. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4000. EXPECT_TRUE(second_range != std::string::npos);
  4001. }
  4002. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4003. auto res = cli_.Get("/streamed-with-range?error",
  4004. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. EXPECT_EQ(false, res->has_header("Content-Range"));
  4009. EXPECT_EQ(0U, res->body.size());
  4010. }
  4011. TEST_F(ServerTest, GetStreamedEndless) {
  4012. uint64_t offset = 0;
  4013. auto res = cli_.Get("/streamed-cancel",
  4014. [&](const char * /*data*/, uint64_t data_length) {
  4015. if (offset < 100) {
  4016. offset += data_length;
  4017. return true;
  4018. }
  4019. return false;
  4020. });
  4021. ASSERT_TRUE(!res);
  4022. EXPECT_EQ(Error::Canceled, res.error());
  4023. }
  4024. TEST_F(ServerTest, ClientStop) {
  4025. std::atomic_size_t count{4};
  4026. std::vector<std::thread> threads;
  4027. for (auto i = count.load(); i != 0; --i) {
  4028. threads.emplace_back([&]() {
  4029. auto res = cli_.Get("/streamed-cancel",
  4030. [&](const char *, uint64_t) { return true; });
  4031. --count;
  4032. ASSERT_TRUE(!res);
  4033. EXPECT_TRUE(res.error() == Error::Canceled ||
  4034. res.error() == Error::Read || res.error() == Error::Write);
  4035. });
  4036. }
  4037. std::this_thread::sleep_for(std::chrono::seconds(2));
  4038. while (count != 0) {
  4039. cli_.stop();
  4040. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4041. }
  4042. for (auto &t : threads) {
  4043. t.join();
  4044. }
  4045. }
  4046. TEST_F(ServerTest, GetWithRange1) {
  4047. auto res = cli_.Get("/with-range", {
  4048. make_range_header({{3, 5}}),
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("def"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetWithRange2) {
  4059. auto res = cli_.Get("/with-range", {
  4060. make_range_header({{1, -1}}),
  4061. {"Accept-Encoding", ""},
  4062. });
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4068. EXPECT_EQ(std::string("bcdefg"), res->body);
  4069. }
  4070. TEST_F(ServerTest, GetWithRange3) {
  4071. auto res = cli_.Get("/with-range", {
  4072. make_range_header({{0, 0}}),
  4073. {"Accept-Encoding", ""},
  4074. });
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4077. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4078. EXPECT_EQ(true, res->has_header("Content-Range"));
  4079. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4080. EXPECT_EQ(std::string("a"), res->body);
  4081. }
  4082. TEST_F(ServerTest, GetWithRange4) {
  4083. auto res = cli_.Get("/with-range", {
  4084. make_range_header({{-1, 2}}),
  4085. {"Accept-Encoding", ""},
  4086. });
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4089. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4090. EXPECT_EQ(true, res->has_header("Content-Range"));
  4091. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4092. EXPECT_EQ(std::string("fg"), res->body);
  4093. }
  4094. TEST_F(ServerTest, GetWithRange5) {
  4095. auto res = cli_.Get("/with-range", {
  4096. make_range_header({{0, 5}}),
  4097. {"Accept-Encoding", ""},
  4098. });
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("abcdef"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4107. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4110. }
  4111. TEST_F(ServerTest, GetWithRangeMultipart) {
  4112. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4115. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4116. EXPECT_EQ(false, res->has_header("Content-Range"));
  4117. EXPECT_EQ(267U, res->body.size());
  4118. }
  4119. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4120. auto res =
  4121. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4124. }
  4125. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4126. auto res = cli_.Get("/with-range-customized-response",
  4127. {{make_range_header({{1, 2}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4130. EXPECT_EQ(true, res->has_header("Content-Length"));
  4131. EXPECT_EQ(false, res->has_header("Content-Range"));
  4132. EXPECT_EQ(JSON_DATA, res->body);
  4133. }
  4134. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4135. auto res = cli_.Get("/with-range-customized-response",
  4136. {{make_range_header({{1, 2}, {4, 5}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4139. EXPECT_EQ(true, res->has_header("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(JSON_DATA, res->body);
  4142. }
  4143. TEST_F(ServerTest, Issue1772) {
  4144. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4147. }
  4148. TEST_F(ServerTest, Issue609) {
  4149. auto res = cli_.Delete("/issue609");
  4150. ASSERT_TRUE(res);
  4151. EXPECT_EQ(StatusCode::OK_200, res->status);
  4152. EXPECT_EQ(std::string("ok"), res->body);
  4153. }
  4154. TEST_F(ServerTest, GetStreamedChunked) {
  4155. auto res = cli_.Get("/streamed-chunked");
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::OK_200, res->status);
  4158. EXPECT_EQ(std::string("123456789"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetStreamedChunked2) {
  4161. auto res = cli_.Get("/streamed-chunked2");
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::OK_200, res->status);
  4164. EXPECT_EQ(std::string("123456789"), res->body);
  4165. }
  4166. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4167. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. EXPECT_EQ(std::string("123456789"), res->body);
  4171. EXPECT_TRUE(res->has_header("Trailer"));
  4172. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4173. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4174. // Trailers are now stored separately from headers (security fix)
  4175. EXPECT_EQ(2U, res->trailers.size());
  4176. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4177. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4178. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4179. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4180. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4181. // Verify trailers are NOT in headers (security verification)
  4182. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4183. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4184. }
  4185. TEST_F(ServerTest, LargeChunkedPost) {
  4186. Request req;
  4187. req.method = "POST";
  4188. req.path = "/large-chunked";
  4189. std::string host_and_port;
  4190. host_and_port += HOST;
  4191. host_and_port += ":";
  4192. host_and_port += std::to_string(PORT);
  4193. req.headers.emplace("Host", host_and_port.c_str());
  4194. req.headers.emplace("Accept", "*/*");
  4195. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4196. req.headers.emplace("Content-Type", "text/plain");
  4197. req.headers.emplace("Content-Length", "0");
  4198. req.headers.emplace("Transfer-Encoding", "chunked");
  4199. std::string long_string(30 * 1024u, 'a');
  4200. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4201. // Attempt to make a large enough post to exceed OS buffers, to test that
  4202. // the server handles short reads if the full chunk data isn't available.
  4203. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4204. auto res = std::make_shared<Response>();
  4205. auto error = Error::Success;
  4206. auto ret = cli_.send(req, *res, error);
  4207. ASSERT_TRUE(ret);
  4208. EXPECT_EQ(StatusCode::OK_200, res->status);
  4209. }
  4210. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4211. auto res = cli_.Get("/remote_addr");
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4215. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4216. }
  4217. TEST_F(ServerTest, GetMethodLocalAddr) {
  4218. auto res = cli_.Get("/local_addr");
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4222. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4223. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4224. }
  4225. TEST_F(ServerTest, HTTPResponseSplitting) {
  4226. auto res = cli_.Get("/http_response_splitting");
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. }
  4230. TEST_F(ServerTest, SlowRequest) {
  4231. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4232. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4233. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4234. }
  4235. #if 0
  4236. TEST_F(ServerTest, SlowPost) {
  4237. char buffer[64 * 1024];
  4238. memset(buffer, 0x42, sizeof(buffer));
  4239. auto res = cli_.Post(
  4240. "/slowpost", 64 * 1024 * 1024,
  4241. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4242. auto ret = sink.write(buffer, sizeof(buffer));
  4243. EXPECT_TRUE(ret);
  4244. return true;
  4245. },
  4246. "text/plain");
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::OK_200, res->status);
  4249. }
  4250. TEST_F(ServerTest, SlowPostFail) {
  4251. char buffer[64 * 1024];
  4252. memset(buffer, 0x42, sizeof(buffer));
  4253. cli_.set_write_timeout(std::chrono::seconds(0));
  4254. auto res = cli_.Post(
  4255. "/slowpost", 64 * 1024 * 1024,
  4256. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4257. sink.write(buffer, sizeof(buffer));
  4258. return true;
  4259. },
  4260. "text/plain");
  4261. ASSERT_TRUE(!res);
  4262. EXPECT_EQ(Error::Write, res.error());
  4263. }
  4264. #endif
  4265. TEST_F(ServerTest, Put) {
  4266. auto res = cli_.Put("/put", "PUT", "text/plain");
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::OK_200, res->status);
  4269. EXPECT_EQ("PUT", res->body);
  4270. }
  4271. TEST_F(ServerTest, PutWithContentProvider) {
  4272. auto res = cli_.Put(
  4273. "/put", 3,
  4274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4275. sink.os << "PUT";
  4276. return true;
  4277. },
  4278. "text/plain");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("PUT", res->body);
  4282. }
  4283. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4284. auto res = cli_.Post(
  4285. "/post", 42,
  4286. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4287. return false;
  4288. },
  4289. "text/plain");
  4290. ASSERT_TRUE(!res);
  4291. EXPECT_EQ(Error::Canceled, res.error());
  4292. }
  4293. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4294. auto res = cli_.Put(
  4295. "/put",
  4296. [](size_t /*offset*/, DataSink &sink) {
  4297. sink.os << "PUT";
  4298. sink.done();
  4299. return true;
  4300. },
  4301. "text/plain");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("PUT", res->body);
  4305. }
  4306. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4307. auto res = cli_.Post(
  4308. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4309. "text/plain");
  4310. ASSERT_TRUE(!res);
  4311. EXPECT_EQ(Error::Canceled, res.error());
  4312. }
  4313. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4314. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4315. cli_.set_compress(true);
  4316. auto res = cli_.Put(
  4317. "/put", 3,
  4318. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4319. sink.os << "PUT";
  4320. return true;
  4321. },
  4322. "text/plain");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("PUT", res->body);
  4326. }
  4327. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4328. cli_.set_compress(true);
  4329. auto res = cli_.Post(
  4330. "/post", 42,
  4331. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4332. return false;
  4333. },
  4334. "text/plain");
  4335. ASSERT_TRUE(!res);
  4336. EXPECT_EQ(Error::Canceled, res.error());
  4337. }
  4338. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4339. cli_.set_compress(true);
  4340. auto res = cli_.Put(
  4341. "/put",
  4342. [](size_t /*offset*/, DataSink &sink) {
  4343. sink.os << "PUT";
  4344. sink.done();
  4345. return true;
  4346. },
  4347. "text/plain");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("PUT", res->body);
  4351. }
  4352. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4353. cli_.set_compress(true);
  4354. auto res = cli_.Post(
  4355. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4356. "text/plain");
  4357. ASSERT_TRUE(!res);
  4358. EXPECT_EQ(Error::Canceled, res.error());
  4359. }
  4360. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4361. cli_.set_compress(true);
  4362. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4363. ASSERT_TRUE(res);
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ(LARGE_DATA, res->body);
  4366. }
  4367. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4369. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4370. Client cli(s.c_str());
  4371. cli.enable_server_certificate_verification(false);
  4372. #else
  4373. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4374. Client cli(s.c_str());
  4375. #endif
  4376. cli.set_compress(true);
  4377. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(StatusCode::OK_200, res->status);
  4380. EXPECT_EQ(LARGE_DATA, res->body);
  4381. // The compressed size should be less than a 10th of the original. May vary
  4382. // depending on the zlib library.
  4383. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4384. static_cast<uint64_t>(10 * 1024 * 1024));
  4385. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4386. }
  4387. TEST_F(ServerTest, PutContentWithDeflate) {
  4388. cli_.set_compress(false);
  4389. Headers headers;
  4390. headers.emplace("Content-Encoding", "deflate");
  4391. // PUT in deflate format:
  4392. auto res = cli_.Put("/put", headers,
  4393. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("PUT", res->body);
  4397. }
  4398. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4399. Headers headers;
  4400. headers.emplace("Accept-Encoding", "gzip, deflate");
  4401. auto res = cli_.Get("/streamed-chunked", headers);
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ(std::string("123456789"), res->body);
  4405. }
  4406. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4407. Headers headers;
  4408. headers.emplace("Accept-Encoding", "gzip, deflate");
  4409. auto res = cli_.Get("/streamed-chunked2", headers);
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ(std::string("123456789"), res->body);
  4413. }
  4414. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4415. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. }
  4419. TEST(GzipDecompressor, ChunkedDecompression) {
  4420. std::string data;
  4421. for (size_t i = 0; i < 32 * 1024; ++i) {
  4422. data.push_back(static_cast<char>('a' + i % 26));
  4423. }
  4424. std::string compressed_data;
  4425. {
  4426. httplib::detail::gzip_compressor compressor;
  4427. bool result = compressor.compress(
  4428. data.data(), data.size(),
  4429. /*last=*/true,
  4430. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4431. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4432. compressed_data_size);
  4433. return true;
  4434. });
  4435. ASSERT_TRUE(result);
  4436. }
  4437. std::string decompressed_data;
  4438. {
  4439. httplib::detail::gzip_decompressor decompressor;
  4440. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4441. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4442. size_t chunk_size = 130;
  4443. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4444. chunk_begin += chunk_size) {
  4445. size_t current_chunk_size =
  4446. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4447. bool result = decompressor.decompress(
  4448. compressed_data.data() + chunk_begin, current_chunk_size,
  4449. [&](const char *decompressed_data_chunk,
  4450. size_t decompressed_data_chunk_size) {
  4451. decompressed_data.insert(decompressed_data.size(),
  4452. decompressed_data_chunk,
  4453. decompressed_data_chunk_size);
  4454. return true;
  4455. });
  4456. ASSERT_TRUE(result);
  4457. }
  4458. }
  4459. ASSERT_EQ(data, decompressed_data);
  4460. }
  4461. TEST(GzipDecompressor, DeflateDecompression) {
  4462. std::string original_text = "Raw deflate without gzip";
  4463. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4464. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4465. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4466. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4467. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4468. std::string decompressed_data;
  4469. {
  4470. httplib::detail::gzip_decompressor decompressor;
  4471. bool result = decompressor.decompress(
  4472. compressed_data.data(), compressed_data.size(),
  4473. [&](const char *decompressed_data_chunk,
  4474. size_t decompressed_data_chunk_size) {
  4475. decompressed_data.insert(decompressed_data.size(),
  4476. decompressed_data_chunk,
  4477. decompressed_data_chunk_size);
  4478. return true;
  4479. });
  4480. ASSERT_TRUE(result);
  4481. }
  4482. ASSERT_EQ(original_text, decompressed_data);
  4483. }
  4484. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4485. std::string original_text = "Raw deflate without gzip";
  4486. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4487. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4488. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4489. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4490. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4491. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4492. std::string decompressed_data;
  4493. {
  4494. httplib::detail::gzip_decompressor decompressor;
  4495. bool result = decompressor.decompress(
  4496. compressed_data.data(), compressed_data.size(),
  4497. [&](const char *decompressed_data_chunk,
  4498. size_t decompressed_data_chunk_size) {
  4499. decompressed_data.insert(decompressed_data.size(),
  4500. decompressed_data_chunk,
  4501. decompressed_data_chunk_size);
  4502. return true;
  4503. });
  4504. ASSERT_TRUE(result);
  4505. }
  4506. ASSERT_EQ(original_text, decompressed_data);
  4507. }
  4508. #ifdef _WIN32
  4509. TEST(GzipDecompressor, LargeRandomData) {
  4510. // prepare large random data that is difficult to be compressed and is
  4511. // expected to have large size even when compressed
  4512. std::random_device seed_gen;
  4513. std::mt19937 random(seed_gen());
  4514. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4515. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4516. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4517. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4518. // compress data over 4GiB
  4519. std::string compressed_data;
  4520. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4521. httplib::detail::gzip_compressor compressor;
  4522. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4523. data.size() * sizeof(std::uint32_t), true,
  4524. [&](const char *data, size_t size) {
  4525. compressed_data.insert(
  4526. compressed_data.size(), data, size);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(result);
  4530. // FIXME: compressed data size is expected to be greater than 4GiB,
  4531. // but there is no guarantee
  4532. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4533. // decompress data over 4GiB
  4534. std::string decompressed_data;
  4535. decompressed_data.reserve(data_size);
  4536. httplib::detail::gzip_decompressor decompressor;
  4537. result = decompressor.decompress(
  4538. compressed_data.data(), compressed_data.size(),
  4539. [&](const char *data, size_t size) {
  4540. decompressed_data.insert(decompressed_data.size(), data, size);
  4541. return true;
  4542. });
  4543. ASSERT_TRUE(result);
  4544. // compare
  4545. ASSERT_EQ(data_size, decompressed_data.size());
  4546. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4547. 0);
  4548. }
  4549. #endif
  4550. #endif
  4551. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4552. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4553. Headers headers;
  4554. headers.emplace("Accept-Encoding", "br");
  4555. auto res = cli_.Get("/streamed-chunked", headers);
  4556. ASSERT_TRUE(res);
  4557. EXPECT_EQ(StatusCode::OK_200, res->status);
  4558. EXPECT_EQ(std::string("123456789"), res->body);
  4559. }
  4560. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4561. Headers headers;
  4562. headers.emplace("Accept-Encoding", "br");
  4563. auto res = cli_.Get("/streamed-chunked2", headers);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ(std::string("123456789"), res->body);
  4567. }
  4568. #endif
  4569. TEST_F(ServerTest, Patch) {
  4570. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4571. ASSERT_TRUE(res);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. EXPECT_EQ("PATCH", res->body);
  4574. }
  4575. TEST_F(ServerTest, Delete) {
  4576. auto res = cli_.Delete("/delete");
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. EXPECT_EQ("DELETE", res->body);
  4580. }
  4581. TEST_F(ServerTest, DeleteContentReceiver) {
  4582. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("content", res->body);
  4586. }
  4587. TEST_F(ServerTest, Options) {
  4588. auto res = cli_.Options("*");
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4592. EXPECT_TRUE(res->body.empty());
  4593. }
  4594. TEST_F(ServerTest, URL) {
  4595. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. }
  4599. TEST_F(ServerTest, ArrayParam) {
  4600. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. }
  4604. TEST_F(ServerTest, NoMultipleHeaders) {
  4605. Headers headers = {{"Content-Length", "5"}};
  4606. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4607. "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. TEST_F(ServerTest, PostContentReceiver) {
  4612. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4613. ASSERT_TRUE(res);
  4614. ASSERT_EQ(StatusCode::OK_200, res->status);
  4615. ASSERT_EQ("content", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4618. UploadFormDataItems items = {
  4619. {"text1", "text default", "", ""},
  4620. {"text2", "aωb", "", ""},
  4621. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4622. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4623. {"file3", "", "", "application/octet-stream"},
  4624. };
  4625. auto res = cli_.Post("/content_receiver", items);
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::OK_200, res->status);
  4628. }
  4629. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4630. UploadFormDataItems items = {
  4631. {"text1", "text default", "", ""},
  4632. {"text2", "aωb", "", ""},
  4633. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4634. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4635. {"file3", "", "", "application/octet-stream"},
  4636. };
  4637. auto boundary = std::string("+++++");
  4638. std::string body;
  4639. for (const auto &item : items) {
  4640. body += "--" + boundary + "\r\n";
  4641. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4642. if (!item.filename.empty()) {
  4643. body += "; filename=\"" + item.filename + "\"";
  4644. }
  4645. body += "\r\n";
  4646. if (!item.content_type.empty()) {
  4647. body += "Content-Type: " + item.content_type + "\r\n";
  4648. }
  4649. body += "\r\n";
  4650. body += item.content + "\r\n";
  4651. }
  4652. body += "--" + boundary + "--\r\n";
  4653. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4654. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. }
  4658. TEST_F(ServerTest, PostContentReceiverGzip) {
  4659. cli_.set_compress(true);
  4660. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4661. ASSERT_TRUE(res);
  4662. ASSERT_EQ(StatusCode::OK_200, res->status);
  4663. ASSERT_EQ("content", res->body);
  4664. }
  4665. TEST_F(ServerTest, PutContentReceiver) {
  4666. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4667. ASSERT_TRUE(res);
  4668. ASSERT_EQ(StatusCode::OK_200, res->status);
  4669. ASSERT_EQ("content", res->body);
  4670. }
  4671. TEST_F(ServerTest, PatchContentReceiver) {
  4672. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4673. ASSERT_TRUE(res);
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("content", res->body);
  4676. }
  4677. template <typename ClientType>
  4678. void TestWithHeadersAndContentReceiver(
  4679. ClientType &cli,
  4680. std::function<Result(ClientType &, const std::string &, const Headers &,
  4681. const std::string &, const std::string &,
  4682. ContentReceiver, DownloadProgress)>
  4683. request_func) {
  4684. Headers headers;
  4685. headers.emplace("X-Custom-Header", "test-value");
  4686. std::string received_body;
  4687. auto res = request_func(
  4688. cli, "/content_receiver", headers, "content", "application/json",
  4689. [&](const char *data, size_t data_length) {
  4690. received_body.append(data, data_length);
  4691. return true;
  4692. },
  4693. nullptr);
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ("content", received_body);
  4697. }
  4698. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4700. using ClientT = SSLClient;
  4701. #else
  4702. using ClientT = Client;
  4703. #endif
  4704. TestWithHeadersAndContentReceiver<ClientT>(
  4705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4706. const std::string &body, const std::string &content_type,
  4707. ContentReceiver receiver, DownloadProgress progress) {
  4708. return cli.Post(path, headers, body, content_type, receiver, progress);
  4709. });
  4710. }
  4711. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4713. using ClientT = SSLClient;
  4714. #else
  4715. using ClientT = Client;
  4716. #endif
  4717. TestWithHeadersAndContentReceiver<ClientT>(
  4718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4719. const std::string &body, const std::string &content_type,
  4720. ContentReceiver receiver, DownloadProgress progress) {
  4721. return cli.Put(path, headers, body, content_type, receiver, progress);
  4722. });
  4723. }
  4724. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4726. using ClientT = SSLClient;
  4727. #else
  4728. using ClientT = Client;
  4729. #endif
  4730. TestWithHeadersAndContentReceiver<ClientT>(
  4731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4732. const std::string &body, const std::string &content_type,
  4733. ContentReceiver receiver, DownloadProgress progress) {
  4734. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4735. });
  4736. }
  4737. template <typename ClientType>
  4738. void TestWithHeadersAndContentReceiverWithProgress(
  4739. ClientType &cli,
  4740. std::function<Result(ClientType &, const std::string &, const Headers &,
  4741. const std::string &, const std::string &,
  4742. ContentReceiver, DownloadProgress)>
  4743. request_func) {
  4744. Headers headers;
  4745. headers.emplace("X-Test-Header", "progress-test");
  4746. std::string received_body;
  4747. auto progress_called = false;
  4748. auto res = request_func(
  4749. cli, "/content_receiver", headers, "content", "text/plain",
  4750. [&](const char *data, size_t data_length) {
  4751. received_body.append(data, data_length);
  4752. return true;
  4753. },
  4754. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4755. progress_called = true;
  4756. return true;
  4757. });
  4758. ASSERT_TRUE(res);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. EXPECT_EQ("content", received_body);
  4761. EXPECT_TRUE(progress_called);
  4762. }
  4763. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4765. using ClientT = SSLClient;
  4766. #else
  4767. using ClientT = Client;
  4768. #endif
  4769. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4770. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4771. const std::string &body, const std::string &content_type,
  4772. ContentReceiver receiver, DownloadProgress progress) {
  4773. return cli.Post(path, headers, body, content_type, receiver, progress);
  4774. });
  4775. }
  4776. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4777. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4778. using ClientT = SSLClient;
  4779. #else
  4780. using ClientT = Client;
  4781. #endif
  4782. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4783. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4784. const std::string &body, const std::string &content_type,
  4785. ContentReceiver receiver, DownloadProgress progress) {
  4786. return cli.Put(path, headers, body, content_type, receiver, progress);
  4787. });
  4788. }
  4789. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4791. using ClientT = SSLClient;
  4792. #else
  4793. using ClientT = Client;
  4794. #endif
  4795. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4796. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4797. const std::string &body, const std::string &content_type,
  4798. ContentReceiver receiver, DownloadProgress progress) {
  4799. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4800. });
  4801. }
  4802. template <typename ClientType>
  4803. void TestWithHeadersAndContentReceiverError(
  4804. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4805. const Headers &, const std::string &,
  4806. const std::string &, ContentReceiver)>
  4807. request_func) {
  4808. Headers headers;
  4809. headers.emplace("X-Error-Test", "true");
  4810. std::string received_body;
  4811. auto receiver_failed = false;
  4812. auto res =
  4813. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4814. [&](const char *data, size_t data_length) {
  4815. received_body.append(data, data_length);
  4816. receiver_failed = true;
  4817. return false;
  4818. });
  4819. ASSERT_FALSE(res);
  4820. EXPECT_TRUE(receiver_failed);
  4821. }
  4822. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4823. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4824. using ClientT = SSLClient;
  4825. #else
  4826. using ClientT = Client;
  4827. #endif
  4828. TestWithHeadersAndContentReceiverError<ClientT>(
  4829. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4830. const std::string &body, const std::string &content_type,
  4831. ContentReceiver receiver) {
  4832. return cli.Post(path, headers, body, content_type, receiver);
  4833. });
  4834. }
  4835. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4837. using ClientT = SSLClient;
  4838. #else
  4839. using ClientT = Client;
  4840. #endif
  4841. TestWithHeadersAndContentReceiverError<ClientT>(
  4842. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4843. const std::string &body, const std::string &content_type,
  4844. ContentReceiver receiver) {
  4845. return cli.Put(path, headers, body, content_type, receiver);
  4846. });
  4847. }
  4848. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4849. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4850. using ClientT = SSLClient;
  4851. #else
  4852. using ClientT = Client;
  4853. #endif
  4854. TestWithHeadersAndContentReceiverError<ClientT>(
  4855. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4856. const std::string &body, const std::string &content_type,
  4857. ContentReceiver receiver) {
  4858. return cli.Patch(path, headers, body, content_type, receiver);
  4859. });
  4860. }
  4861. TEST_F(ServerTest, PostQueryStringAndBody) {
  4862. auto res =
  4863. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4864. ASSERT_TRUE(res);
  4865. ASSERT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, HTTP2Magic) {
  4868. Request req;
  4869. req.method = "PRI";
  4870. req.path = "*";
  4871. req.body = "SM";
  4872. auto res = std::make_shared<Response>();
  4873. auto error = Error::Success;
  4874. auto ret = cli_.send(req, *res, error);
  4875. ASSERT_TRUE(ret);
  4876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4877. }
  4878. TEST_F(ServerTest, KeepAlive) {
  4879. auto res = cli_.Get("/hi");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4883. EXPECT_EQ("Hello World!", res->body);
  4884. res = cli_.Get("/hi");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("Hello World!", res->body);
  4889. res = cli_.Get("/hi");
  4890. ASSERT_TRUE(res);
  4891. EXPECT_EQ(StatusCode::OK_200, res->status);
  4892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. EXPECT_EQ("Hello World!", res->body);
  4894. res = cli_.Get("/not-exist");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4897. res = cli_.Post("/empty", "", "text/plain");
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4901. EXPECT_EQ("empty", res->body);
  4902. EXPECT_EQ("close", res->get_header_value("Connection"));
  4903. res = cli_.Post(
  4904. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4905. "text/plain");
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("empty", res->body);
  4910. cli_.set_keep_alive(false);
  4911. res = cli_.Get("/last-request");
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. EXPECT_EQ("close", res->get_header_value("Connection"));
  4915. }
  4916. TEST_F(ServerTest, TooManyRedirect) {
  4917. cli_.set_follow_location(true);
  4918. auto res = cli_.Get("/redirect/0");
  4919. ASSERT_TRUE(!res);
  4920. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4921. }
  4922. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4924. TEST_F(ServerTest, Gzip) {
  4925. Headers headers;
  4926. headers.emplace("Accept-Encoding", "gzip, deflate");
  4927. auto res = cli_.Get("/compress", headers);
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4933. "7890123456789012345678901234567890",
  4934. res->body);
  4935. EXPECT_EQ(StatusCode::OK_200, res->status);
  4936. }
  4937. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "");
  4940. auto res = cli_.Get("/compress", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4946. "7890123456789012345678901234567890",
  4947. res->body);
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. }
  4950. TEST_F(ServerTest, GzipWithContentReceiver) {
  4951. Headers headers;
  4952. headers.emplace("Accept-Encoding", "gzip, deflate");
  4953. std::string body;
  4954. auto res = cli_.Get("/compress", headers,
  4955. [&](const char *data, uint64_t data_length) {
  4956. EXPECT_EQ(100U, data_length);
  4957. body.append(data, data_length);
  4958. return true;
  4959. });
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4963. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4964. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4965. "7890123456789012345678901234567890",
  4966. body);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. }
  4969. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4970. Headers headers;
  4971. headers.emplace("Accept-Encoding", "gzip, deflate");
  4972. cli_.set_decompress(false);
  4973. auto res = cli_.Get("/compress", headers);
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4977. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4978. EXPECT_EQ(33U, res->body.size());
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. }
  4981. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4982. Headers headers;
  4983. headers.emplace("Accept-Encoding", "");
  4984. std::string body;
  4985. auto res = cli_.Get("/compress", headers,
  4986. [&](const char *data, uint64_t data_length) {
  4987. EXPECT_EQ(100U, data_length);
  4988. body.append(data, data_length);
  4989. return true;
  4990. });
  4991. ASSERT_TRUE(res);
  4992. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4996. "7890123456789012345678901234567890",
  4997. body);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. }
  5000. TEST_F(ServerTest, NoGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/nocompress", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5006. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5007. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5009. "7890123456789012345678901234567890",
  5010. res->body);
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. }
  5013. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5014. Headers headers;
  5015. headers.emplace("Accept-Encoding", "gzip, deflate");
  5016. std::string body;
  5017. auto res = cli_.Get("/nocompress", headers,
  5018. [&](const char *data, uint64_t data_length) {
  5019. EXPECT_EQ(100U, data_length);
  5020. body.append(data, data_length);
  5021. return true;
  5022. });
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5028. "7890123456789012345678901234567890",
  5029. body);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. }
  5032. TEST_F(ServerTest, MultipartFormDataGzip) {
  5033. UploadFormDataItems items = {
  5034. {"key1", "test", "", ""},
  5035. {"key2", "--abcdefg123", "", ""},
  5036. };
  5037. cli_.set_compress(true);
  5038. auto res = cli_.Post("/compress-multipart", items);
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. }
  5042. #endif
  5043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5044. TEST_F(ServerTest, Brotli) {
  5045. Headers headers;
  5046. headers.emplace("Accept-Encoding", "br");
  5047. auto res = cli_.Get("/compress", headers);
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5053. "7890123456789012345678901234567890",
  5054. res->body);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. }
  5057. #endif
  5058. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5059. TEST_F(ServerTest, Zstd) {
  5060. Headers headers;
  5061. headers.emplace("Accept-Encoding", "zstd");
  5062. auto res = cli_.Get("/compress", headers);
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5068. "7890123456789012345678901234567890",
  5069. res->body);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5073. Headers headers;
  5074. headers.emplace("Accept-Encoding", "");
  5075. auto res = cli_.Get("/compress", headers);
  5076. ASSERT_TRUE(res);
  5077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5081. "7890123456789012345678901234567890",
  5082. res->body);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "zstd");
  5088. std::string body;
  5089. auto res = cli_.Get("/compress", headers,
  5090. [&](const char *data, uint64_t data_length) {
  5091. EXPECT_EQ(100U, data_length);
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. ASSERT_TRUE(res);
  5096. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5098. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5100. "7890123456789012345678901234567890",
  5101. body);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5105. Headers headers;
  5106. headers.emplace("Accept-Encoding", "zstd");
  5107. cli_.set_decompress(false);
  5108. auto res = cli_.Get("/compress", headers);
  5109. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5110. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5111. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5112. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5116. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ(26U, res->body.size());
  5119. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5120. 0);
  5121. }
  5122. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5123. Headers headers;
  5124. headers.emplace("Accept-Encoding", "");
  5125. std::string body;
  5126. auto res = cli_.Get("/compress", headers,
  5127. [&](const char *data, uint64_t data_length) {
  5128. EXPECT_EQ(100U, data_length);
  5129. body.append(data, data_length);
  5130. return true;
  5131. });
  5132. ASSERT_TRUE(res);
  5133. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5135. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5136. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5137. "7890123456789012345678901234567890",
  5138. body);
  5139. EXPECT_EQ(StatusCode::OK_200, res->status);
  5140. }
  5141. TEST_F(ServerTest, NoZstd) {
  5142. Headers headers;
  5143. headers.emplace("Accept-Encoding", "zstd");
  5144. auto res = cli_.Get("/nocompress", headers);
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5147. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5149. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5150. "7890123456789012345678901234567890",
  5151. res->body);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. }
  5154. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5155. Headers headers;
  5156. headers.emplace("Accept-Encoding", "zstd");
  5157. std::string body;
  5158. auto res = cli_.Get("/nocompress", headers,
  5159. [&](const char *data, uint64_t data_length) {
  5160. EXPECT_EQ(100U, data_length);
  5161. body.append(data, data_length);
  5162. return true;
  5163. });
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. // TODO: How to enable zstd ??
  5174. TEST_F(ServerTest, MultipartFormDataZstd) {
  5175. UploadFormDataItems items = {
  5176. {"key1", "test", "", ""},
  5177. {"key2", "--abcdefg123", "", ""},
  5178. };
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "zstd");
  5181. cli_.set_compress(true);
  5182. auto res = cli_.Post("/compress-multipart", headers, items);
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. }
  5186. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5187. Headers headers;
  5188. headers.emplace("Accept-Encoding", "zstd");
  5189. cli_.set_compress(true);
  5190. auto res = cli_.Put(
  5191. "/put", headers, 3,
  5192. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5193. sink.os << "PUT";
  5194. return true;
  5195. },
  5196. "text/plain");
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. EXPECT_EQ("PUT", res->body);
  5200. }
  5201. // Pre-compression logging tests
  5202. TEST_F(ServerTest, PreCompressionLogging) {
  5203. // Test data for compression (matches the actual /compress endpoint content)
  5204. const std::string test_content =
  5205. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5206. "3456789012345678901234567890";
  5207. // Variables to capture logging data
  5208. std::string pre_compression_body;
  5209. std::string pre_compression_content_type;
  5210. std::string pre_compression_content_encoding;
  5211. std::string post_compression_body;
  5212. std::string post_compression_content_type;
  5213. std::string post_compression_content_encoding;
  5214. // Set up pre-compression logger
  5215. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5216. const Response &res) {
  5217. pre_compression_body = res.body;
  5218. pre_compression_content_type = res.get_header_value("Content-Type");
  5219. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5220. });
  5221. // Set up post-compression logger
  5222. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5223. post_compression_body = res.body;
  5224. post_compression_content_type = res.get_header_value("Content-Type");
  5225. post_compression_content_encoding =
  5226. res.get_header_value("Content-Encoding");
  5227. });
  5228. // Test with gzip compression
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "gzip");
  5231. auto res = cli_.Get("/compress", headers);
  5232. // Verify response was compressed
  5233. ASSERT_TRUE(res);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5236. // Verify pre-compression logger captured uncompressed content
  5237. EXPECT_EQ(test_content, pre_compression_body);
  5238. EXPECT_EQ("text/plain", pre_compression_content_type);
  5239. EXPECT_TRUE(pre_compression_content_encoding
  5240. .empty()); // No encoding header before compression
  5241. // Verify post-compression logger captured compressed content
  5242. EXPECT_NE(test_content,
  5243. post_compression_body); // Should be different after compression
  5244. EXPECT_EQ("text/plain", post_compression_content_type);
  5245. EXPECT_EQ("gzip", post_compression_content_encoding);
  5246. // Verify compressed content is smaller
  5247. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5248. }
  5249. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5250. const std::string test_content =
  5251. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5252. "3456789012345678901234567890";
  5253. std::string pre_compression_body;
  5254. std::string post_compression_body;
  5255. svr_.set_pre_compression_logger(
  5256. [&](const Request & /*req*/, const Response &res) {
  5257. pre_compression_body = res.body;
  5258. });
  5259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5260. post_compression_body = res.body;
  5261. });
  5262. Headers headers;
  5263. headers.emplace("Accept-Encoding", "br");
  5264. auto res = cli_.Get("/compress", headers);
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5268. // Verify pre-compression content is uncompressed
  5269. EXPECT_EQ(test_content, pre_compression_body);
  5270. // Verify post-compression content is compressed
  5271. EXPECT_NE(test_content, post_compression_body);
  5272. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5273. }
  5274. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5275. const std::string test_content =
  5276. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5277. "3456789012345678901234567890";
  5278. std::string pre_compression_body;
  5279. std::string post_compression_body;
  5280. svr_.set_pre_compression_logger(
  5281. [&](const Request & /*req*/, const Response &res) {
  5282. pre_compression_body = res.body;
  5283. });
  5284. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5285. post_compression_body = res.body;
  5286. });
  5287. // Request without compression (use /nocompress endpoint)
  5288. Headers headers;
  5289. auto res = cli_.Get("/nocompress", headers);
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5293. // Pre-compression logger should not be called when no compression is applied
  5294. EXPECT_TRUE(
  5295. pre_compression_body.empty()); // Pre-compression logger not called
  5296. EXPECT_EQ(
  5297. test_content,
  5298. post_compression_body); // Post-compression logger captures final content
  5299. }
  5300. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5301. const std::string test_content =
  5302. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5303. "3456789012345678901234567890";
  5304. std::string pre_compression_body;
  5305. bool pre_logger_called = false;
  5306. // Set only pre-compression logger
  5307. svr_.set_pre_compression_logger(
  5308. [&](const Request & /*req*/, const Response &res) {
  5309. pre_compression_body = res.body;
  5310. pre_logger_called = true;
  5311. });
  5312. Headers headers;
  5313. headers.emplace("Accept-Encoding", "gzip");
  5314. auto res = cli_.Get("/compress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5318. // Verify pre-compression logger was called
  5319. EXPECT_TRUE(pre_logger_called);
  5320. EXPECT_EQ(test_content, pre_compression_body);
  5321. }
  5322. TEST(ZstdDecompressor, ChunkedDecompression) {
  5323. std::string data;
  5324. for (size_t i = 0; i < 32 * 1024; ++i) {
  5325. data.push_back(static_cast<char>('a' + i % 26));
  5326. }
  5327. std::string compressed_data;
  5328. {
  5329. httplib::detail::zstd_compressor compressor;
  5330. bool result = compressor.compress(
  5331. data.data(), data.size(),
  5332. /*last=*/true,
  5333. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5334. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5335. compressed_data_size);
  5336. return true;
  5337. });
  5338. ASSERT_TRUE(result);
  5339. }
  5340. std::string decompressed_data;
  5341. {
  5342. httplib::detail::zstd_decompressor decompressor;
  5343. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5344. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5345. size_t chunk_size = 130;
  5346. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5347. chunk_begin += chunk_size) {
  5348. size_t current_chunk_size =
  5349. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5350. bool result = decompressor.decompress(
  5351. compressed_data.data() + chunk_begin, current_chunk_size,
  5352. [&](const char *decompressed_data_chunk,
  5353. size_t decompressed_data_chunk_size) {
  5354. decompressed_data.insert(decompressed_data.size(),
  5355. decompressed_data_chunk,
  5356. decompressed_data_chunk_size);
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(result);
  5360. }
  5361. }
  5362. ASSERT_EQ(data, decompressed_data);
  5363. }
  5364. TEST(ZstdDecompressor, Decompress) {
  5365. std::string original_text = "Compressed with ZSTD";
  5366. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5367. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5368. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5369. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5370. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5371. std::string decompressed_data;
  5372. {
  5373. httplib::detail::zstd_decompressor decompressor;
  5374. bool result = decompressor.decompress(
  5375. compressed_data.data(), compressed_data.size(),
  5376. [&](const char *decompressed_data_chunk,
  5377. size_t decompressed_data_chunk_size) {
  5378. decompressed_data.insert(decompressed_data.size(),
  5379. decompressed_data_chunk,
  5380. decompressed_data_chunk_size);
  5381. return true;
  5382. });
  5383. ASSERT_TRUE(result);
  5384. }
  5385. ASSERT_EQ(original_text, decompressed_data);
  5386. }
  5387. #endif
  5388. // Sends a raw request to a server listening at HOST:PORT.
  5389. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5390. std::string *resp = nullptr) {
  5391. auto error = Error::Success;
  5392. auto client_sock = detail::create_client_socket(
  5393. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5394. /*connection_timeout_sec=*/5, 0,
  5395. /*read_timeout_sec=*/5, 0,
  5396. /*write_timeout_sec=*/5, 0, std::string(), error);
  5397. if (client_sock == INVALID_SOCKET) { return false; }
  5398. auto ret = detail::process_client_socket(
  5399. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5400. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5401. if (req.size() !=
  5402. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5403. return false;
  5404. }
  5405. char buf[512];
  5406. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5407. while (line_reader.getline()) {
  5408. if (resp) { *resp += line_reader.ptr(); }
  5409. }
  5410. return true;
  5411. });
  5412. detail::close_socket(client_sock);
  5413. return ret;
  5414. }
  5415. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5416. Server svr;
  5417. std::string header_value;
  5418. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5419. header_value = req.get_header_value("foo");
  5420. res.set_content("ok", "text/plain");
  5421. });
  5422. thread t = thread([&] { svr.listen(HOST, PORT); });
  5423. auto se = detail::scope_exit([&] {
  5424. svr.stop();
  5425. t.join();
  5426. ASSERT_FALSE(svr.is_running());
  5427. });
  5428. svr.wait_until_ready();
  5429. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5430. // like characters are not treated the same - use vertical tab and escape.
  5431. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5432. "foo: \t \v bar \x1B\t \r\n"
  5433. "Connection: close\r\n"
  5434. "\r\n";
  5435. std::string res;
  5436. ASSERT_TRUE(send_request(5, req, &res));
  5437. EXPECT_EQ(header_value, "");
  5438. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5439. }
  5440. // Sends a raw request and verifies that there isn't a crash or exception.
  5441. static void test_raw_request(const std::string &req,
  5442. std::string *out = nullptr) {
  5443. Server svr;
  5444. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5445. res.set_content("ok", "text/plain");
  5446. });
  5447. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5448. res.set_content("ok", "text/plain");
  5449. });
  5450. svr.Get("/header_field_value_check",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.set_content("ok", "text/plain");
  5453. });
  5454. // Server read timeout must be longer than the client read timeout for the
  5455. // bug to reproduce, probably to force the server to process a request
  5456. // without a trailing blank line.
  5457. const time_t client_read_timeout_sec = 1;
  5458. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5459. bool listen_thread_ok = false;
  5460. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5461. auto se = detail::scope_exit([&] {
  5462. svr.stop();
  5463. t.join();
  5464. ASSERT_FALSE(svr.is_running());
  5465. EXPECT_TRUE(listen_thread_ok);
  5466. });
  5467. svr.wait_until_ready();
  5468. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5469. }
  5470. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5471. // A certain header line causes an exception if the header property is parsed
  5472. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5473. test_raw_request(
  5474. "GET /hi HTTP/1.1\r\n"
  5475. " : "
  5476. " "
  5477. " ");
  5478. }
  5479. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5480. // A certain header line causes an exception if the header property *name* is
  5481. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5482. // greedy matcher and requires backtracking when there are a lot of ":"
  5483. // characters.
  5484. // This occurs with libc++ but not libstdc++.
  5485. test_raw_request(
  5486. "GET /hi HTTP/1.1\r\n"
  5487. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5488. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5489. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5490. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5491. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5492. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5493. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5494. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5495. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5496. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5497. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5498. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5499. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5500. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5501. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5502. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5503. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5504. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5505. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5506. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5507. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5508. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5509. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5510. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5511. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5512. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5513. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5514. "&&&%%%");
  5515. }
  5516. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5517. // Make sure this doesn't crash the server.
  5518. // In a previous version of the header line regex, the "\r" rendered the line
  5519. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5520. // a new position where the leading white space ended and the field value
  5521. // began.
  5522. // The crash occurs with libc++ but not libstdc++.
  5523. test_raw_request("GET /hi HTTP/1.1\r\n"
  5524. "a:" +
  5525. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5526. "\r\n"
  5527. "\r\n");
  5528. }
  5529. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5530. std::string out;
  5531. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5532. "Content-Type: text/plain\r\n"
  5533. "Transfer-Encoding: chunked\r\n"
  5534. "\r\n"
  5535. "nothex\r\n",
  5536. &out);
  5537. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5538. }
  5539. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5540. std::string out;
  5541. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5542. "Content-Type: text/plain\r\n"
  5543. "Transfer-Encoding: chunked\r\n"
  5544. "\r\n"
  5545. "3\r\n"
  5546. "xyz\r\n"
  5547. "NaN\r\n",
  5548. &out);
  5549. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5550. }
  5551. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5552. std::string out;
  5553. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5554. "Content-Type: text/plain\r\n"
  5555. "Transfer-Encoding: chunked\r\n"
  5556. "\r\n"
  5557. // Length is too large for 64 bits.
  5558. "1ffffffffffffffff\r\n"
  5559. "xyz\r\n",
  5560. &out);
  5561. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5562. }
  5563. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5564. test_raw_request("GET /hi HTTP/1.1\r\n"
  5565. "Content-Type: text/plain\r\n\r");
  5566. }
  5567. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5568. std::string out;
  5569. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5570. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5571. }
  5572. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5573. std::string out;
  5574. std::string request(
  5575. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5576. test_raw_request(request, &out);
  5577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5578. }
  5579. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5580. std::string out;
  5581. std::string request(
  5582. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5583. test_raw_request(request, &out);
  5584. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5585. }
  5586. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5587. std::string out;
  5588. std::string request(
  5589. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5590. test_raw_request(request, &out);
  5591. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5592. }
  5593. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5594. std::string out;
  5595. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5596. "Test: \r\n\r\n",
  5597. &out);
  5598. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5599. }
  5600. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5601. Server svr;
  5602. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5603. res.set_header("Cache-Control", "no-cache");
  5604. res.set_chunked_content_provider(
  5605. "text/event-stream", [](size_t offset, DataSink &sink) {
  5606. std::string s = "data:";
  5607. s += std::to_string(offset);
  5608. s += "\n\n";
  5609. auto ret = sink.write(s.data(), s.size());
  5610. EXPECT_TRUE(ret);
  5611. std::this_thread::sleep_for(std::chrono::seconds(1));
  5612. return true;
  5613. });
  5614. });
  5615. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5616. svr.wait_until_ready();
  5617. Client client(HOST, PORT);
  5618. const Headers headers = {{"Accept", "text/event-stream"}};
  5619. auto get_thread = std::thread([&client, &headers]() {
  5620. auto res = client.Get(
  5621. "/events", headers,
  5622. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5623. });
  5624. auto se = detail::scope_exit([&] {
  5625. svr.stop();
  5626. get_thread.join();
  5627. listen_thread.join();
  5628. ASSERT_FALSE(svr.is_running());
  5629. });
  5630. // Give GET time to get a few messages.
  5631. std::this_thread::sleep_for(std::chrono::seconds(2));
  5632. }
  5633. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5634. httplib::Server svr;
  5635. svr.Post("/hi",
  5636. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5637. res.status = StatusCode::OK_200;
  5638. });
  5639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5640. svr.wait_until_ready();
  5641. Client cli(HOST, PORT);
  5642. auto res = cli.Post("/hi", "data", "text/plain");
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ(StatusCode::OK_200, res->status);
  5645. svr.stop();
  5646. thread.join();
  5647. ASSERT_FALSE(svr.is_running());
  5648. res = cli.Post("/hi", "data", "text/plain");
  5649. ASSERT_FALSE(res);
  5650. }
  5651. TEST(ServerStopTest, ListenFailure) {
  5652. Server svr;
  5653. auto t = thread([&]() {
  5654. auto ret = svr.listen("????", PORT);
  5655. EXPECT_FALSE(ret);
  5656. });
  5657. svr.wait_until_ready();
  5658. svr.stop();
  5659. t.join();
  5660. }
  5661. TEST(ServerStopTest, Decommision) {
  5662. Server svr;
  5663. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5664. for (int i = 0; i < 4; i++) {
  5665. auto is_even = !(i % 2);
  5666. std::thread t{[&] {
  5667. try {
  5668. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5669. if (is_even) {
  5670. throw std::runtime_error("Some thing that happens to go wrong.");
  5671. }
  5672. svr.listen(HOST, PORT);
  5673. } catch (...) { svr.decommission(); }
  5674. }};
  5675. svr.wait_until_ready();
  5676. // Server is up
  5677. {
  5678. Client cli(HOST, PORT);
  5679. auto res = cli.Get("/hi");
  5680. if (is_even) {
  5681. EXPECT_FALSE(res);
  5682. } else {
  5683. EXPECT_TRUE(res);
  5684. EXPECT_EQ("hi...", res->body);
  5685. }
  5686. }
  5687. svr.stop();
  5688. t.join();
  5689. // Server is down...
  5690. {
  5691. Client cli(HOST, PORT);
  5692. auto res = cli.Get("/hi");
  5693. EXPECT_FALSE(res);
  5694. }
  5695. }
  5696. }
  5697. // Helper function for string body upload progress tests
  5698. template <typename SetupHandler, typename ClientCall>
  5699. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5700. ClientCall &&client_call,
  5701. const string &body) {
  5702. Server svr;
  5703. setup_handler(svr);
  5704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5705. auto se = detail::scope_exit([&] {
  5706. svr.stop();
  5707. t.join();
  5708. });
  5709. svr.wait_until_ready();
  5710. Client cli(HOST, PORT);
  5711. vector<uint64_t> progress_values;
  5712. bool progress_called = false;
  5713. auto res =
  5714. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5715. progress_values.push_back(current);
  5716. progress_called = true;
  5717. return true;
  5718. });
  5719. ASSERT_TRUE(res);
  5720. EXPECT_EQ(200, res->status);
  5721. EXPECT_TRUE(progress_called);
  5722. }
  5723. TEST(UploadProgressTest, PostStringBodyBasic) {
  5724. TestStringBodyUploadProgress(
  5725. [](Server &svr) {
  5726. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5727. res.set_content("received", "text/plain");
  5728. });
  5729. },
  5730. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5731. return cli.Post("/test", body, "text/plain", progress_callback);
  5732. },
  5733. "test data for upload progress");
  5734. }
  5735. TEST(UploadProgressTest, PutStringBodyBasic) {
  5736. TestStringBodyUploadProgress(
  5737. [](Server &svr) {
  5738. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5739. res.set_content("put received", "text/plain");
  5740. });
  5741. },
  5742. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5743. return cli.Put("/test", body, "text/plain", progress_callback);
  5744. },
  5745. "put test data for upload progress");
  5746. }
  5747. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5748. TestStringBodyUploadProgress(
  5749. [](Server &svr) {
  5750. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5751. res.set_content("patch received", "text/plain");
  5752. });
  5753. },
  5754. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5755. return cli.Patch("/test", body, "text/plain", progress_callback);
  5756. },
  5757. "patch test data for upload progress");
  5758. }
  5759. // Helper function for content provider upload progress tests
  5760. template <typename SetupHandler, typename ClientCall>
  5761. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5762. ClientCall &&client_call) {
  5763. Server svr;
  5764. setup_handler(svr);
  5765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5766. auto se = detail::scope_exit([&] {
  5767. svr.stop();
  5768. t.join();
  5769. });
  5770. svr.wait_until_ready();
  5771. Client cli(HOST, PORT);
  5772. vector<uint64_t> progress_values;
  5773. auto res =
  5774. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5775. progress_values.push_back(current);
  5776. return true;
  5777. });
  5778. ASSERT_TRUE(res);
  5779. EXPECT_EQ(200, res->status);
  5780. EXPECT_FALSE(progress_values.empty());
  5781. }
  5782. TEST(UploadProgressTest, PostContentProviderProgress) {
  5783. TestContentProviderUploadProgress(
  5784. [](Server &svr) {
  5785. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5786. res.set_content("provider received", "text/plain");
  5787. });
  5788. },
  5789. [](Client &cli, UploadProgress progress_callback) {
  5790. return cli.Post(
  5791. "/test", 10,
  5792. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5793. sink.os << "test data";
  5794. return true;
  5795. },
  5796. "text/plain", progress_callback);
  5797. });
  5798. }
  5799. // Helper function for multipart upload progress tests
  5800. template <typename SetupHandler, typename ClientCall>
  5801. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5802. ClientCall &&client_call,
  5803. const string &endpoint) {
  5804. Server svr;
  5805. setup_handler(svr);
  5806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5807. auto se = detail::scope_exit([&] {
  5808. svr.stop();
  5809. t.join();
  5810. });
  5811. svr.wait_until_ready();
  5812. Client cli(HOST, PORT);
  5813. vector<uint64_t> progress_values;
  5814. UploadFormDataItems items = {
  5815. {"field1", "value1", "", ""},
  5816. {"field2", "longer value for progress tracking test", "", ""},
  5817. {"file1", "file content data for upload progress", "test.txt",
  5818. "text/plain"}};
  5819. auto res = client_call(cli, endpoint, items,
  5820. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5821. progress_values.push_back(current);
  5822. return true;
  5823. });
  5824. ASSERT_TRUE(res);
  5825. EXPECT_EQ(200, res->status);
  5826. EXPECT_FALSE(progress_values.empty());
  5827. }
  5828. TEST(UploadProgressTest, PostMultipartProgress) {
  5829. TestMultipartUploadProgress(
  5830. [](Server &svr) {
  5831. svr.Post("/multipart", [](const Request &req, Response &res) {
  5832. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5833. res.set_content("multipart received", "text/plain");
  5834. });
  5835. },
  5836. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5837. UploadProgress progress_callback) {
  5838. return cli.Post(endpoint, items, progress_callback);
  5839. },
  5840. "/multipart");
  5841. }
  5842. // Helper function for basic download progress tests
  5843. template <typename SetupHandler, typename ClientCall>
  5844. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5845. ClientCall &&client_call, const string &endpoint,
  5846. size_t expected_content_size) {
  5847. Server svr;
  5848. setup_handler(svr);
  5849. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5850. auto se = detail::scope_exit([&] {
  5851. svr.stop();
  5852. t.join();
  5853. });
  5854. svr.wait_until_ready();
  5855. Client cli(HOST, PORT);
  5856. vector<uint64_t> progress_values;
  5857. auto res = client_call(cli, endpoint,
  5858. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5859. progress_values.push_back(current);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res);
  5863. EXPECT_EQ(200, res->status);
  5864. EXPECT_FALSE(progress_values.empty());
  5865. EXPECT_EQ(expected_content_size, res->body.size());
  5866. }
  5867. TEST(DownloadProgressTest, GetBasic) {
  5868. TestBasicDownloadProgress(
  5869. [](Server &svr) {
  5870. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5871. string content(1000, 'D');
  5872. res.set_content(content, "text/plain");
  5873. });
  5874. },
  5875. [](Client &cli, const string &endpoint,
  5876. DownloadProgress progress_callback) {
  5877. return cli.Get(endpoint, progress_callback);
  5878. },
  5879. "/download", 1000u);
  5880. }
  5881. // Helper function for content receiver download progress tests
  5882. template <typename SetupHandler, typename ClientCall>
  5883. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5884. ClientCall &&client_call,
  5885. const string &endpoint,
  5886. size_t expected_content_size) {
  5887. Server svr;
  5888. setup_handler(svr);
  5889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. });
  5894. svr.wait_until_ready();
  5895. Client cli(HOST, PORT);
  5896. vector<uint64_t> progress_values;
  5897. string received_body;
  5898. auto res = client_call(
  5899. cli, endpoint,
  5900. [&](const char *data, size_t data_length) -> bool {
  5901. received_body.append(data, data_length);
  5902. return true;
  5903. },
  5904. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5905. progress_values.push_back(current);
  5906. return true;
  5907. });
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(200, res->status);
  5910. EXPECT_FALSE(progress_values.empty());
  5911. EXPECT_EQ(expected_content_size, received_body.size());
  5912. EXPECT_TRUE(res->body.empty());
  5913. }
  5914. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5915. TestContentReceiverDownloadProgress(
  5916. [](Server &svr) {
  5917. svr.Get("/download-receiver",
  5918. [](const Request & /*req*/, Response &res) {
  5919. string content(2000, 'R');
  5920. res.set_content(content, "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5924. DownloadProgress progress_callback) {
  5925. return cli.Get(endpoint, content_receiver, progress_callback);
  5926. },
  5927. "/download-receiver", 2000u);
  5928. }
  5929. TEST(StreamingTest, NoContentLengthStreaming) {
  5930. Server svr;
  5931. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5932. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5933. if (offset < 6) {
  5934. sink.os << (offset < 3 ? "a" : "b");
  5935. } else {
  5936. sink.done();
  5937. }
  5938. return true;
  5939. });
  5940. });
  5941. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5942. auto listen_se = detail::scope_exit([&] {
  5943. svr.stop();
  5944. listen_thread.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. svr.wait_until_ready();
  5948. Client client(HOST, PORT);
  5949. auto get_thread = std::thread([&client]() {
  5950. std::string s;
  5951. auto res =
  5952. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5953. s += std::string(data, len);
  5954. return true;
  5955. });
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. EXPECT_EQ("aaabbb", s);
  5959. });
  5960. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5961. // Give GET time to get a few messages.
  5962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5963. }
  5964. TEST(MountTest, Unmount) {
  5965. Server svr;
  5966. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. listen_thread.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. Client cli("localhost", PORT);
  5974. svr.set_mount_point("/mount2", "./www2");
  5975. auto res = cli.Get("/");
  5976. ASSERT_TRUE(res);
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. res = cli.Get("/mount2/dir/test.html");
  5979. ASSERT_TRUE(res);
  5980. EXPECT_EQ(StatusCode::OK_200, res->status);
  5981. svr.set_mount_point("/", "./www");
  5982. res = cli.Get("/dir/");
  5983. ASSERT_TRUE(res);
  5984. EXPECT_EQ(StatusCode::OK_200, res->status);
  5985. svr.remove_mount_point("/");
  5986. res = cli.Get("/dir/");
  5987. ASSERT_TRUE(res);
  5988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5989. svr.remove_mount_point("/mount2");
  5990. res = cli.Get("/mount2/dir/test.html");
  5991. ASSERT_TRUE(res);
  5992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5993. }
  5994. TEST(MountTest, Redicect) {
  5995. Server svr;
  5996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5997. auto se = detail::scope_exit([&] {
  5998. svr.stop();
  5999. listen_thread.join();
  6000. ASSERT_FALSE(svr.is_running());
  6001. });
  6002. svr.set_mount_point("/", "./www");
  6003. svr.wait_until_ready();
  6004. Client cli("localhost", PORT);
  6005. auto res = cli.Get("/dir/");
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. res = cli.Get("/dir");
  6009. ASSERT_TRUE(res);
  6010. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6011. res = cli.Get("/file");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. res = cli.Get("/file/");
  6015. ASSERT_TRUE(res);
  6016. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6017. cli.set_follow_location(true);
  6018. res = cli.Get("/dir");
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. }
  6022. TEST(MountTest, MultibytesPathName) {
  6023. Server svr;
  6024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6025. auto se = detail::scope_exit([&] {
  6026. svr.stop();
  6027. listen_thread.join();
  6028. ASSERT_FALSE(svr.is_running());
  6029. });
  6030. svr.set_mount_point("/", "./www");
  6031. svr.wait_until_ready();
  6032. Client cli("localhost", PORT);
  6033. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6037. }
  6038. TEST(KeepAliveTest, ReadTimeout) {
  6039. Server svr;
  6040. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6041. std::this_thread::sleep_for(std::chrono::seconds(2));
  6042. res.set_content("a", "text/plain");
  6043. });
  6044. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6045. res.set_content("b", "text/plain");
  6046. });
  6047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. listen_thread.join();
  6051. ASSERT_FALSE(svr.is_running());
  6052. });
  6053. svr.wait_until_ready();
  6054. Client cli("localhost", PORT);
  6055. cli.set_keep_alive(true);
  6056. cli.set_read_timeout(std::chrono::seconds(1));
  6057. auto resa = cli.Get("/a");
  6058. ASSERT_FALSE(resa);
  6059. EXPECT_EQ(Error::Read, resa.error());
  6060. auto resb = cli.Get("/b");
  6061. ASSERT_TRUE(resb);
  6062. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6063. EXPECT_EQ("b", resb->body);
  6064. }
  6065. TEST(KeepAliveTest, MaxCount) {
  6066. size_t keep_alive_max_count = 3;
  6067. Server svr;
  6068. svr.set_keep_alive_max_count(keep_alive_max_count);
  6069. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6070. res.set_content("Hello World!", "text/plain");
  6071. });
  6072. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. listen_thread.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli(HOST, PORT);
  6080. cli.set_keep_alive(true);
  6081. for (size_t i = 0; i < 5; i++) {
  6082. auto result = cli.Get("/hi");
  6083. ASSERT_TRUE(result);
  6084. EXPECT_EQ(StatusCode::OK_200, result->status);
  6085. if (i == keep_alive_max_count - 1) {
  6086. EXPECT_EQ("close", result->get_header_value("Connection"));
  6087. } else {
  6088. EXPECT_FALSE(result->has_header("Connection"));
  6089. }
  6090. }
  6091. }
  6092. TEST(KeepAliveTest, Issue1041) {
  6093. Server svr;
  6094. svr.set_keep_alive_timeout(3);
  6095. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6096. res.set_content("Hello World!", "text/plain");
  6097. });
  6098. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6099. auto se = detail::scope_exit([&] {
  6100. svr.stop();
  6101. listen_thread.join();
  6102. ASSERT_FALSE(svr.is_running());
  6103. });
  6104. svr.wait_until_ready();
  6105. Client cli(HOST, PORT);
  6106. cli.set_keep_alive(true);
  6107. auto result = cli.Get("/hi");
  6108. ASSERT_TRUE(result);
  6109. EXPECT_EQ(StatusCode::OK_200, result->status);
  6110. std::this_thread::sleep_for(std::chrono::seconds(5));
  6111. result = cli.Get("/hi");
  6112. ASSERT_TRUE(result);
  6113. EXPECT_EQ(StatusCode::OK_200, result->status);
  6114. }
  6115. TEST(KeepAliveTest, Issue1959) {
  6116. Server svr;
  6117. svr.set_keep_alive_timeout(5);
  6118. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6119. res.set_content("a", "text/plain");
  6120. });
  6121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6122. auto se = detail::scope_exit([&] {
  6123. if (!svr.is_running()) return;
  6124. svr.stop();
  6125. listen_thread.join();
  6126. ASSERT_FALSE(svr.is_running());
  6127. });
  6128. svr.wait_until_ready();
  6129. Client cli("localhost", PORT);
  6130. cli.set_keep_alive(true);
  6131. using namespace std::chrono;
  6132. auto start = steady_clock::now();
  6133. cli.Get("/a");
  6134. svr.stop();
  6135. listen_thread.join();
  6136. auto end = steady_clock::now();
  6137. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6138. EXPECT_LT(elapsed, 5000);
  6139. }
  6140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6141. TEST(KeepAliveTest, SSLClientReconnection) {
  6142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6143. ASSERT_TRUE(svr.is_valid());
  6144. svr.set_keep_alive_timeout(1);
  6145. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6146. res.set_content("Hello World!", "text/plain");
  6147. });
  6148. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6149. auto se = detail::scope_exit([&] {
  6150. svr.stop();
  6151. listen_thread.join();
  6152. ASSERT_FALSE(svr.is_running());
  6153. });
  6154. svr.wait_until_ready();
  6155. SSLClient cli(HOST, PORT);
  6156. cli.enable_server_certificate_verification(false);
  6157. cli.set_keep_alive(true);
  6158. auto result = cli.Get("/hi");
  6159. ASSERT_TRUE(result);
  6160. EXPECT_EQ(StatusCode::OK_200, result->status);
  6161. result = cli.Get("/hi");
  6162. ASSERT_TRUE(result);
  6163. EXPECT_EQ(StatusCode::OK_200, result->status);
  6164. std::this_thread::sleep_for(std::chrono::seconds(2));
  6165. // Recoonect
  6166. result = cli.Get("/hi");
  6167. ASSERT_TRUE(result);
  6168. EXPECT_EQ(StatusCode::OK_200, result->status);
  6169. result = cli.Get("/hi");
  6170. ASSERT_TRUE(result);
  6171. EXPECT_EQ(StatusCode::OK_200, result->status);
  6172. }
  6173. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6175. ASSERT_TRUE(svr.is_valid());
  6176. svr.set_keep_alive_timeout(1);
  6177. std::string content = "reconnect";
  6178. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6179. res.set_content("Hello World!", "text/plain");
  6180. });
  6181. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6182. auto se = detail::scope_exit([&] {
  6183. svr.stop();
  6184. listen_thread.join();
  6185. ASSERT_FALSE(svr.is_running());
  6186. });
  6187. svr.wait_until_ready();
  6188. SSLClient cli(HOST, PORT);
  6189. cli.enable_server_certificate_verification(false);
  6190. cli.set_keep_alive(true);
  6191. auto result = cli.Post(
  6192. "/hi", content.size(),
  6193. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6194. sink.write(content.c_str(), content.size());
  6195. return true;
  6196. },
  6197. "text/plain");
  6198. ASSERT_TRUE(result);
  6199. EXPECT_EQ(200, result->status);
  6200. std::this_thread::sleep_for(std::chrono::seconds(2));
  6201. // Recoonect
  6202. result = cli.Post(
  6203. "/hi", content.size(),
  6204. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6205. sink.write(content.c_str(), content.size());
  6206. return true;
  6207. },
  6208. "text/plain");
  6209. ASSERT_TRUE(result);
  6210. EXPECT_EQ(200, result->status);
  6211. result = cli.Post(
  6212. "/hi", content.size(),
  6213. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6214. sink.write(content.c_str(), content.size());
  6215. return true;
  6216. },
  6217. "text/plain");
  6218. ASSERT_TRUE(result);
  6219. EXPECT_EQ(200, result->status);
  6220. }
  6221. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6222. {
  6223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6224. ASSERT_TRUE(svr.is_valid());
  6225. svr.Get("/sni", [&](const Request &req, Response &res) {
  6226. std::string expected;
  6227. if (req.ssl) {
  6228. if (const char *sni =
  6229. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6230. expected = sni;
  6231. }
  6232. }
  6233. EXPECT_EQ(expected, req.get_param_value("expected"));
  6234. res.set_content("ok", "text/plain");
  6235. });
  6236. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6237. auto se = detail::scope_exit([&] {
  6238. svr.stop();
  6239. listen_thread.join();
  6240. ASSERT_FALSE(svr.is_running());
  6241. });
  6242. svr.wait_until_ready();
  6243. {
  6244. SSLClient cli("localhost", PORT);
  6245. cli.enable_server_certificate_verification(false);
  6246. auto res = cli.Get("/sni?expected=localhost");
  6247. ASSERT_TRUE(res);
  6248. }
  6249. {
  6250. SSLClient cli("::1", PORT);
  6251. cli.enable_server_certificate_verification(false);
  6252. auto res = cli.Get("/sni?expected=");
  6253. ASSERT_TRUE(res);
  6254. }
  6255. }
  6256. }
  6257. #endif
  6258. TEST(ClientProblemDetectionTest, ContentProvider) {
  6259. Server svr;
  6260. size_t content_length = 1024 * 1024;
  6261. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6262. res.set_content_provider(
  6263. content_length, "text/plain",
  6264. [&](size_t offset, size_t length, DataSink &sink) {
  6265. auto out_len = std::min(length, static_cast<size_t>(1024));
  6266. std::string out(out_len, '@');
  6267. sink.write(out.data(), out_len);
  6268. return offset < 4096;
  6269. },
  6270. [](bool success) { ASSERT_FALSE(success); });
  6271. });
  6272. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6273. res.set_content_provider(
  6274. 0, "text/plain",
  6275. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6276. EXPECT_TRUE(false);
  6277. return true;
  6278. },
  6279. [](bool success) { ASSERT_FALSE(success); });
  6280. });
  6281. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6282. auto se = detail::scope_exit([&] {
  6283. svr.stop();
  6284. listen_thread.join();
  6285. ASSERT_FALSE(svr.is_running());
  6286. });
  6287. svr.wait_until_ready();
  6288. Client cli("localhost", PORT);
  6289. {
  6290. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6291. size_t /*data_length*/) { return false; });
  6292. ASSERT_FALSE(res);
  6293. }
  6294. {
  6295. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6296. size_t /*data_length*/) { return false; });
  6297. ASSERT_TRUE(res);
  6298. }
  6299. }
  6300. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6301. Server svr;
  6302. svr.set_error_handler([](Request const &, Response &res) -> void {
  6303. res.set_chunked_content_provider(
  6304. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6305. sink.os << "hello";
  6306. sink.os << "world";
  6307. sink.done();
  6308. return true;
  6309. });
  6310. });
  6311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6312. auto se = detail::scope_exit([&] {
  6313. svr.stop();
  6314. listen_thread.join();
  6315. ASSERT_FALSE(svr.is_running());
  6316. });
  6317. svr.wait_until_ready();
  6318. Client cli("localhost", PORT);
  6319. auto res = cli.Get("/");
  6320. ASSERT_TRUE(res);
  6321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6322. EXPECT_EQ("helloworld", res->body);
  6323. }
  6324. TEST(LongPollingTest, ClientCloseDetection) {
  6325. Server svr;
  6326. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6327. res.set_chunked_content_provider(
  6328. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6329. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6330. sink.os << "hello";
  6331. auto count = 10;
  6332. while (count > 0 && sink.is_writable()) {
  6333. this_thread::sleep_for(chrono::milliseconds(10));
  6334. count--;
  6335. }
  6336. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6337. return true;
  6338. });
  6339. });
  6340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. listen_thread.join();
  6344. ASSERT_FALSE(svr.is_running());
  6345. });
  6346. svr.wait_until_ready();
  6347. Client cli("localhost", PORT);
  6348. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6349. EXPECT_EQ("hello", string(data, data_length));
  6350. return false; // close the socket immediately.
  6351. });
  6352. ASSERT_FALSE(res);
  6353. }
  6354. TEST(GetWithParametersTest, GetWithParameters) {
  6355. Server svr;
  6356. svr.Get("/", [&](const Request &req, Response &) {
  6357. EXPECT_EQ("world", req.get_param_value("hello"));
  6358. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6359. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6360. });
  6361. svr.Get("/params", [&](const Request &req, Response &) {
  6362. EXPECT_EQ("world", req.get_param_value("hello"));
  6363. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6364. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6365. });
  6366. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6367. EXPECT_EQ("resource-id", req.matches[1]);
  6368. EXPECT_EQ("foo", req.get_param_value("param1"));
  6369. EXPECT_EQ("bar", req.get_param_value("param2"));
  6370. });
  6371. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6372. EXPECT_EQ("user-id", req.path_params.at("id"));
  6373. EXPECT_EQ("foo", req.get_param_value("param1"));
  6374. EXPECT_EQ("bar", req.get_param_value("param2"));
  6375. });
  6376. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. ASSERT_FALSE(svr.is_running());
  6381. });
  6382. svr.wait_until_ready();
  6383. {
  6384. Client cli(HOST, PORT);
  6385. Params params;
  6386. params.emplace("hello", "world");
  6387. params.emplace("hello2", "world2");
  6388. params.emplace("hello3", "world3");
  6389. auto res = cli.Get("/", params, Headers{});
  6390. ASSERT_TRUE(res);
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. {
  6394. Client cli(HOST, PORT);
  6395. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ(StatusCode::OK_200, res->status);
  6398. }
  6399. {
  6400. Client cli(HOST, PORT);
  6401. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6402. ASSERT_TRUE(res);
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. }
  6405. {
  6406. Client cli(HOST, PORT);
  6407. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6408. ASSERT_TRUE(res);
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. }
  6412. TEST(GetWithParametersTest, GetWithParameters2) {
  6413. Server svr;
  6414. svr.Get("/", [&](const Request &req, Response &res) {
  6415. auto text = req.get_param_value("hello");
  6416. res.set_content(text, "text/plain");
  6417. });
  6418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6419. auto se = detail::scope_exit([&] {
  6420. svr.stop();
  6421. listen_thread.join();
  6422. ASSERT_FALSE(svr.is_running());
  6423. });
  6424. svr.wait_until_ready();
  6425. Client cli("localhost", PORT);
  6426. Params params;
  6427. params.emplace("hello", "world");
  6428. std::string body;
  6429. auto res = cli.Get("/", params, Headers{},
  6430. [&](const char *data, size_t data_length) {
  6431. body.append(data, data_length);
  6432. return true;
  6433. });
  6434. ASSERT_TRUE(res);
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. EXPECT_EQ("world", body);
  6437. }
  6438. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6439. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6440. auto host = "httpbin.org";
  6441. auto path = std::string{"/range/32"};
  6442. #else
  6443. auto host = "nghttp2.org";
  6444. auto path = std::string{"/httpbin/range/32"};
  6445. #endif
  6446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6447. SSLClient cli(host);
  6448. #else
  6449. Client cli(host);
  6450. #endif
  6451. cli.set_default_headers({make_range_header({{1, 10}})});
  6452. cli.set_connection_timeout(5);
  6453. {
  6454. auto res = cli.Get(path);
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ("bcdefghijk", res->body);
  6457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6458. }
  6459. {
  6460. auto res = cli.Get(path);
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ("bcdefghijk", res->body);
  6463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6464. }
  6465. }
  6466. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6467. Server svr;
  6468. svr.set_default_headers({{"Hello", "World"}});
  6469. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6470. res.set_content("ok", "text/plain");
  6471. });
  6472. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6473. auto se = detail::scope_exit([&] {
  6474. svr.stop();
  6475. listen_thread.join();
  6476. ASSERT_FALSE(svr.is_running());
  6477. });
  6478. svr.wait_until_ready();
  6479. Client cli("localhost", PORT);
  6480. auto res = cli.Get("/");
  6481. ASSERT_TRUE(res);
  6482. EXPECT_EQ(StatusCode::OK_200, res->status);
  6483. EXPECT_EQ("ok", res->body);
  6484. EXPECT_EQ("World", res->get_header_value("Hello"));
  6485. }
  6486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6487. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6489. ASSERT_TRUE(svr.is_valid());
  6490. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6491. std::this_thread::sleep_for(std::chrono::seconds(2));
  6492. res.set_content("a", "text/plain");
  6493. });
  6494. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6495. res.set_content("b", "text/plain");
  6496. });
  6497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. listen_thread.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. SSLClient cli("localhost", PORT);
  6505. cli.enable_server_certificate_verification(false);
  6506. cli.set_keep_alive(true);
  6507. cli.set_read_timeout(std::chrono::seconds(1));
  6508. auto resa = cli.Get("/a");
  6509. ASSERT_TRUE(!resa);
  6510. EXPECT_EQ(Error::Read, resa.error());
  6511. auto resb = cli.Get("/b");
  6512. ASSERT_TRUE(resb);
  6513. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6514. EXPECT_EQ("b", resb->body);
  6515. }
  6516. #endif
  6517. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6518. protected:
  6519. ServerTestWithAI_PASSIVE()
  6520. : cli_(HOST, PORT)
  6521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6522. ,
  6523. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6524. #endif
  6525. {
  6526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6527. cli_.enable_server_certificate_verification(false);
  6528. #endif
  6529. }
  6530. virtual void SetUp() {
  6531. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6532. res.set_content("Hello World!", "text/plain");
  6533. });
  6534. t_ = thread(
  6535. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6536. svr_.wait_until_ready();
  6537. }
  6538. virtual void TearDown() {
  6539. svr_.stop();
  6540. t_.join();
  6541. }
  6542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6543. SSLClient cli_;
  6544. SSLServer svr_;
  6545. #else
  6546. Client cli_;
  6547. Server svr_;
  6548. #endif
  6549. thread t_;
  6550. };
  6551. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6552. auto res = cli_.Get("/hi");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6556. EXPECT_EQ("Hello World!", res->body);
  6557. }
  6558. class ServerUpDownTest : public ::testing::Test {
  6559. protected:
  6560. ServerUpDownTest() : cli_(HOST, PORT) {}
  6561. virtual void SetUp() {
  6562. t_ = thread([&]() {
  6563. svr_.bind_to_any_port(HOST);
  6564. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6565. ASSERT_TRUE(svr_.listen_after_bind());
  6566. });
  6567. svr_.wait_until_ready();
  6568. }
  6569. virtual void TearDown() {
  6570. svr_.stop();
  6571. t_.join();
  6572. }
  6573. Client cli_;
  6574. Server svr_;
  6575. thread t_;
  6576. };
  6577. TEST_F(ServerUpDownTest, QuickStartStop) {
  6578. // Should not crash, especially when run with
  6579. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6580. }
  6581. class PayloadMaxLengthTest : public ::testing::Test {
  6582. protected:
  6583. PayloadMaxLengthTest()
  6584. : cli_(HOST, PORT)
  6585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6586. ,
  6587. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6588. #endif
  6589. {
  6590. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6591. cli_.enable_server_certificate_verification(false);
  6592. #endif
  6593. }
  6594. virtual void SetUp() {
  6595. svr_.set_payload_max_length(8);
  6596. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6597. res.set_content("test", "text/plain");
  6598. });
  6599. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6600. svr_.wait_until_ready();
  6601. }
  6602. virtual void TearDown() {
  6603. svr_.stop();
  6604. t_.join();
  6605. }
  6606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6607. SSLClient cli_;
  6608. SSLServer svr_;
  6609. #else
  6610. Client cli_;
  6611. Server svr_;
  6612. #endif
  6613. thread t_;
  6614. };
  6615. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6616. auto res = cli_.Post("/test", "123456789", "text/plain");
  6617. ASSERT_TRUE(res);
  6618. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6619. res = cli_.Post("/test", "12345678", "text/plain");
  6620. ASSERT_TRUE(res);
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. }
  6623. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6624. // Test chunked encoding with payload exceeding the 8-byte limit
  6625. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6626. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6627. ASSERT_TRUE(res);
  6628. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6629. }
  6630. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6631. // Test chunked encoding with payload within the 8-byte limit
  6632. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6633. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6634. ASSERT_TRUE(res);
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. }
  6637. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6638. // Test using send_request to send chunked data exceeding payload limit
  6639. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6640. "Host: " +
  6641. std::string(HOST) + ":" + std::to_string(PORT) +
  6642. "\r\n"
  6643. "Transfer-Encoding: chunked\r\n"
  6644. "Connection: close\r\n"
  6645. "\r\n"
  6646. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6647. "0123456789\r\n"
  6648. "0\r\n" // End chunk
  6649. "\r\n";
  6650. std::string response;
  6651. bool result = send_request(1, chunked_request, &response);
  6652. if (!result) {
  6653. // If send_request fails, it might be because the server closed the
  6654. // connection due to payload limit enforcement, which is acceptable
  6655. SUCCEED()
  6656. << "Server rejected oversized chunked request (connection closed)";
  6657. } else {
  6658. // If we got a response, check if it's an error response or connection was
  6659. // closed early Short response length indicates connection was closed due to
  6660. // payload limit
  6661. if (response.length() <= 10) {
  6662. SUCCEED() << "Server closed connection for oversized chunked request";
  6663. } else {
  6664. // Check for error status codes
  6665. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6666. response.find("Payload Too Large") != std::string::npos ||
  6667. response.find("400") != std::string::npos);
  6668. }
  6669. }
  6670. }
  6671. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6672. // Test request without Content-Length header exceeding payload limit
  6673. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6674. "Host: " +
  6675. std::string(HOST) + ":" +
  6676. std::to_string(PORT) +
  6677. "\r\n"
  6678. "Connection: close\r\n"
  6679. "\r\n";
  6680. // Add payload exceeding the 8-byte limit
  6681. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6682. request_without_content_length += large_payload;
  6683. std::string response;
  6684. bool result = send_request(1, request_without_content_length, &response);
  6685. if (!result) {
  6686. // If send_request fails, server likely closed connection due to payload
  6687. // limit
  6688. SUCCEED() << "Server rejected oversized request without Content-Length "
  6689. "(connection closed)";
  6690. } else {
  6691. // Check if server responded with error or closed connection early
  6692. if (response.length() <= 10) {
  6693. SUCCEED() << "Server closed connection for oversized request without "
  6694. "Content-Length";
  6695. } else {
  6696. // Check for error status codes
  6697. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6698. response.find("Payload Too Large") != std::string::npos ||
  6699. response.find("400") != std::string::npos);
  6700. }
  6701. }
  6702. }
  6703. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6704. // Test request without Content-Length header within payload limit
  6705. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6706. "Host: " +
  6707. std::string(HOST) + ":" +
  6708. std::to_string(PORT) +
  6709. "\r\n"
  6710. "Connection: close\r\n"
  6711. "\r\n";
  6712. // Add payload within the 8-byte limit
  6713. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6714. request_without_content_length += small_payload;
  6715. std::string response;
  6716. bool result = send_request(1, request_without_content_length, &response);
  6717. // For requests without Content-Length, the server may have different behavior
  6718. // The key is that it should not reject due to payload limit for small
  6719. // payloads
  6720. if (result) {
  6721. // Check for any HTTP response (success or error, but not connection closed)
  6722. if (response.length() > 10) {
  6723. SUCCEED()
  6724. << "Server processed request without Content-Length within limit";
  6725. } else {
  6726. // Short response might indicate connection closed, which is acceptable
  6727. SUCCEED() << "Server closed connection for request without "
  6728. "Content-Length (acceptable behavior)";
  6729. }
  6730. } else {
  6731. // Connection failure might be due to protocol requirements
  6732. SUCCEED() << "Connection issue with request without Content-Length "
  6733. "(environment-specific)";
  6734. }
  6735. }
  6736. class LargePayloadMaxLengthTest : public ::testing::Test {
  6737. protected:
  6738. LargePayloadMaxLengthTest()
  6739. : cli_(HOST, PORT)
  6740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6741. ,
  6742. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6743. #endif
  6744. {
  6745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6746. cli_.enable_server_certificate_verification(false);
  6747. #endif
  6748. }
  6749. virtual void SetUp() {
  6750. // Set 10MB payload limit
  6751. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6752. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6753. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6754. res.set_content("Large payload test", "text/plain");
  6755. });
  6756. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6757. svr_.wait_until_ready();
  6758. }
  6759. virtual void TearDown() {
  6760. svr_.stop();
  6761. t_.join();
  6762. }
  6763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6764. SSLClient cli_;
  6765. SSLServer svr_;
  6766. #else
  6767. Client cli_;
  6768. Server svr_;
  6769. #endif
  6770. thread t_;
  6771. };
  6772. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6773. // Test chunked encoding with payload within 10MB limit
  6774. std::string medium_payload(5 * 1024 * 1024,
  6775. 'A'); // 5MB payload, within 10MB limit
  6776. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6777. ASSERT_TRUE(res);
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. }
  6780. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6781. // Test chunked encoding with payload exceeding 10MB limit
  6782. std::string large_payload(12 * 1024 * 1024,
  6783. 'B'); // 12MB payload, exceeds 10MB limit
  6784. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6785. ASSERT_TRUE(res);
  6786. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6787. }
  6788. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6789. // Test request without Content-Length header within 10MB limit
  6790. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6791. "Host: " +
  6792. std::string(HOST) + ":" +
  6793. std::to_string(PORT) +
  6794. "\r\n"
  6795. "Connection: close\r\n"
  6796. "\r\n";
  6797. // Add 1MB payload (within 10MB limit)
  6798. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6799. request_without_content_length += medium_payload;
  6800. std::string response;
  6801. bool result = send_request(5, request_without_content_length, &response);
  6802. if (result) {
  6803. // Should get a proper HTTP response for payloads within limit
  6804. if (response.length() > 10) {
  6805. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6806. "10MB limit";
  6807. } else {
  6808. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6809. "Content-Length)";
  6810. }
  6811. } else {
  6812. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6813. }
  6814. }
  6815. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6816. // Test request without Content-Length header exceeding 10MB limit
  6817. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6818. "Host: " +
  6819. std::string(HOST) + ":" +
  6820. std::to_string(PORT) +
  6821. "\r\n"
  6822. "Connection: close\r\n"
  6823. "\r\n";
  6824. // Add 12MB payload (exceeds 10MB limit)
  6825. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6826. request_without_content_length += large_payload;
  6827. std::string response;
  6828. bool result = send_request(10, request_without_content_length, &response);
  6829. if (!result) {
  6830. // Server should close connection due to payload limit
  6831. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6832. "(connection closed)";
  6833. } else {
  6834. // Check for error response
  6835. if (response.length() <= 10) {
  6836. SUCCEED()
  6837. << "Server closed connection for 12MB request exceeding 10MB limit";
  6838. } else {
  6839. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6840. response.find("Payload Too Large") != std::string::npos ||
  6841. response.find("400") != std::string::npos);
  6842. }
  6843. }
  6844. }
  6845. TEST(HostAndPortPropertiesTest, NoSSL) {
  6846. httplib::Client cli("www.google.com", 1234);
  6847. ASSERT_EQ("www.google.com", cli.host());
  6848. ASSERT_EQ(1234, cli.port());
  6849. }
  6850. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6851. httplib::Client cli("www.google.com:1234");
  6852. ASSERT_EQ("www.google.com", cli.host());
  6853. ASSERT_EQ(1234, cli.port());
  6854. }
  6855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6856. TEST(HostAndPortPropertiesTest, SSL) {
  6857. httplib::SSLClient cli("www.google.com");
  6858. ASSERT_EQ("www.google.com", cli.host());
  6859. ASSERT_EQ(443, cli.port());
  6860. }
  6861. #endif
  6862. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6863. TEST(SSLClientTest, UpdateCAStore) {
  6864. httplib::SSLClient httplib_client("www.google.com");
  6865. auto ca_store_1 = X509_STORE_new();
  6866. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6867. nullptr);
  6868. httplib_client.set_ca_cert_store(ca_store_1);
  6869. auto ca_store_2 = X509_STORE_new();
  6870. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6871. nullptr);
  6872. httplib_client.set_ca_cert_store(ca_store_2);
  6873. }
  6874. TEST(SSLClientTest, ServerNameIndication_Online) {
  6875. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6876. auto host = "httpbin.org";
  6877. auto path = std::string{"/get"};
  6878. #else
  6879. auto host = "nghttp2.org";
  6880. auto path = std::string{"/httpbin/get"};
  6881. #endif
  6882. SSLClient cli(host, 443);
  6883. auto res = cli.Get(path);
  6884. ASSERT_TRUE(res);
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. }
  6887. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6888. // Use a site that will cause SSL verification failure due to self-signed cert
  6889. SSLClient cli("self-signed.badssl.com", 443);
  6890. cli.enable_server_certificate_verification(true);
  6891. auto res = cli.Get("/");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6894. // For SSL server verification errors, ssl_error should be 0, only
  6895. // ssl_openssl_error should be set
  6896. EXPECT_EQ(0, res.ssl_error());
  6897. // Verify OpenSSL error is captured for SSLServerVerification
  6898. // This occurs when SSL_get_verify_result() returns a verification failure
  6899. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6900. res.ssl_openssl_error());
  6901. }
  6902. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6903. // Use a site where hostname doesn't match the certificate
  6904. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6905. SSLClient cli("wrong.host.badssl.com", 443);
  6906. cli.enable_server_certificate_verification(true);
  6907. cli.enable_server_hostname_verification(true);
  6908. auto res = cli.Get("/");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6911. // For SSL hostname verification errors, ssl_error should be 0, only
  6912. // ssl_openssl_error should be set
  6913. EXPECT_EQ(0, res.ssl_error());
  6914. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6915. // This occurs when verify_host() fails due to hostname mismatch
  6916. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6917. res.ssl_openssl_error());
  6918. }
  6919. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6920. Client cli("https://google.com");
  6921. auto res = cli.Get("/");
  6922. ASSERT_TRUE(res);
  6923. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6924. }
  6925. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6926. SSLClient cli("google.com");
  6927. cli.set_ca_cert_path(CA_CERT_FILE);
  6928. auto res = cli.Get("/");
  6929. ASSERT_TRUE(res);
  6930. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6931. }
  6932. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6933. SSLClient cli("google.com");
  6934. cli.enable_server_certificate_verification(true);
  6935. cli.set_ca_cert_path("hello");
  6936. auto res = cli.Get("/");
  6937. ASSERT_TRUE(!res);
  6938. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6939. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6940. // should be set
  6941. EXPECT_EQ(0, res.ssl_error());
  6942. // Verify OpenSSL error is captured for SSLLoadingCerts
  6943. // This error occurs when SSL_CTX_load_verify_locations() fails
  6944. // > openssl errstr 0x80000002
  6945. // error:80000002:system library::No such file or directory
  6946. // > openssl errstr 0xA000126
  6947. // error:0A000126:SSL routines::unexpected eof while reading
  6948. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6949. res.ssl_openssl_error() == 0xA000126);
  6950. }
  6951. TEST(SSLClientTest, ServerCertificateVerification4) {
  6952. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6953. ASSERT_TRUE(svr.is_valid());
  6954. svr.Get("/test", [&](const Request &, Response &res) {
  6955. res.set_content("test", "text/plain");
  6956. svr.stop();
  6957. ASSERT_TRUE(true);
  6958. });
  6959. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6960. auto se = detail::scope_exit([&] {
  6961. t.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. SSLClient cli("127.0.0.1", PORT);
  6966. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6967. cli.enable_server_certificate_verification(true);
  6968. cli.set_connection_timeout(30);
  6969. auto res = cli.Get("/test");
  6970. ASSERT_TRUE(res);
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. }
  6973. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6974. std::string cert;
  6975. read_file(CA_CERT_FILE, cert);
  6976. SSLClient cli("google.com");
  6977. cli.load_ca_cert_store(cert.data(), cert.size());
  6978. const auto res = cli.Get("/");
  6979. ASSERT_TRUE(res);
  6980. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6981. }
  6982. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6983. // clang-format off
  6984. static constexpr char cert[] =
  6985. "GlobalSign Root CA\n"
  6986. "==================\n"
  6987. "-----BEGIN CERTIFICATE-----\n"
  6988. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6989. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6990. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6991. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6992. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6993. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6994. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6995. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6996. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6997. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6998. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6999. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7000. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7001. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7002. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7003. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7004. "-----END CERTIFICATE-----\n";
  7005. // clang-format on
  7006. SSLClient cli("google.com");
  7007. cli.load_ca_cert_store(cert, sizeof(cert));
  7008. const auto res = cli.Get("/");
  7009. ASSERT_TRUE(res);
  7010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7011. }
  7012. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7013. SSLClient cli("www.youtube.com");
  7014. cli.set_ca_cert_path(CA_CERT_FILE);
  7015. cli.enable_server_certificate_verification(true);
  7016. cli.set_follow_location(true);
  7017. auto res = cli.Get("/");
  7018. ASSERT_TRUE(res);
  7019. ASSERT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. TEST(SSLClientTest, Issue2004_Online) {
  7022. Client client("https://google.com");
  7023. client.set_follow_location(true);
  7024. auto res = client.Get("/");
  7025. ASSERT_TRUE(res);
  7026. ASSERT_EQ(StatusCode::OK_200, res->status);
  7027. auto body = res->body;
  7028. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7029. }
  7030. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7031. // Create SSLClient with invalid cert/key to make is_valid() return false
  7032. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7033. "nonexistent_key.pem");
  7034. // is_valid() should be false due to cert loading failure
  7035. ASSERT_FALSE(cli.is_valid());
  7036. auto res = cli.Get("/");
  7037. ASSERT_FALSE(res);
  7038. EXPECT_EQ(Error::SSLConnection, res.error());
  7039. }
  7040. #if 0
  7041. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7042. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7043. ASSERT_TRUE(cli != nullptr);
  7044. cli->set_address_family(AF_INET6);
  7045. cli->set_interface("en0");
  7046. auto res = cli->Get("/get");
  7047. ASSERT_TRUE(res);
  7048. ASSERT_EQ(StatusCode::OK_200, res->status);
  7049. }
  7050. #endif
  7051. void ClientCertPresent(
  7052. const std::string &client_cert_file,
  7053. const std::string &client_private_key_file,
  7054. const std::string &client_encrypted_private_key_pass = std::string()) {
  7055. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7056. CLIENT_CA_CERT_DIR);
  7057. ASSERT_TRUE(svr.is_valid());
  7058. svr.Get("/test", [&](const Request &req, Response &res) {
  7059. res.set_content("test", "text/plain");
  7060. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7061. ASSERT_TRUE(peer_cert != nullptr);
  7062. auto subject_name = X509_get_subject_name(peer_cert);
  7063. ASSERT_TRUE(subject_name != nullptr);
  7064. std::string common_name;
  7065. {
  7066. char name[BUFSIZ];
  7067. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7068. name, sizeof(name));
  7069. common_name.assign(name, static_cast<size_t>(name_len));
  7070. }
  7071. EXPECT_EQ("Common Name", common_name);
  7072. X509_free(peer_cert);
  7073. });
  7074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7075. auto se = detail::scope_exit([&] {
  7076. svr.stop();
  7077. t.join();
  7078. ASSERT_FALSE(svr.is_running());
  7079. });
  7080. svr.wait_until_ready();
  7081. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7082. client_encrypted_private_key_pass);
  7083. cli.enable_server_certificate_verification(false);
  7084. cli.set_connection_timeout(30);
  7085. auto res = cli.Get("/test");
  7086. ASSERT_TRUE(res);
  7087. ASSERT_EQ(StatusCode::OK_200, res->status);
  7088. }
  7089. TEST(SSLClientServerTest, ClientCertPresent) {
  7090. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7091. }
  7092. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7093. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7094. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7095. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7096. }
  7097. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7098. void MemoryClientCertPresent(
  7099. const std::string &client_cert_file,
  7100. const std::string &client_private_key_file,
  7101. const std::string &client_encrypted_private_key_pass = std::string()) {
  7102. auto f = fopen(SERVER_CERT_FILE, "r+");
  7103. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7104. fclose(f);
  7105. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7106. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7107. fclose(f);
  7108. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7109. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7110. auto client_ca_cert_store = X509_STORE_new();
  7111. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7112. X509_free(client_cert);
  7113. fclose(f);
  7114. f = fopen(client_cert_file.c_str(), "r+");
  7115. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7116. fclose(f);
  7117. f = fopen(client_private_key_file.c_str(), "r+");
  7118. auto client_private_key = PEM_read_PrivateKey(
  7119. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7120. fclose(f);
  7121. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7122. ASSERT_TRUE(svr.is_valid());
  7123. svr.Get("/test", [&](const Request &req, Response &res) {
  7124. res.set_content("test", "text/plain");
  7125. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7126. ASSERT_TRUE(peer_cert != nullptr);
  7127. auto subject_name = X509_get_subject_name(peer_cert);
  7128. ASSERT_TRUE(subject_name != nullptr);
  7129. std::string common_name;
  7130. {
  7131. char name[BUFSIZ];
  7132. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7133. name, sizeof(name));
  7134. common_name.assign(name, static_cast<size_t>(name_len));
  7135. }
  7136. EXPECT_EQ("Common Name", common_name);
  7137. X509_free(peer_cert);
  7138. });
  7139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7140. auto se = detail::scope_exit([&] {
  7141. svr.stop();
  7142. t.join();
  7143. ASSERT_FALSE(svr.is_running());
  7144. });
  7145. svr.wait_until_ready();
  7146. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7147. client_encrypted_private_key_pass);
  7148. cli.enable_server_certificate_verification(false);
  7149. cli.set_connection_timeout(30);
  7150. auto res = cli.Get("/test");
  7151. ASSERT_TRUE(res);
  7152. ASSERT_EQ(StatusCode::OK_200, res->status);
  7153. X509_free(server_cert);
  7154. EVP_PKEY_free(server_private_key);
  7155. X509_free(client_cert);
  7156. EVP_PKEY_free(client_private_key);
  7157. }
  7158. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7159. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7160. }
  7161. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7162. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7163. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7164. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7165. }
  7166. #endif
  7167. TEST(SSLClientServerTest, ClientCertMissing) {
  7168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7169. CLIENT_CA_CERT_DIR);
  7170. ASSERT_TRUE(svr.is_valid());
  7171. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7172. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7173. auto se = detail::scope_exit([&] {
  7174. svr.stop();
  7175. t.join();
  7176. ASSERT_FALSE(svr.is_running());
  7177. });
  7178. svr.wait_until_ready();
  7179. SSLClient cli(HOST, PORT);
  7180. cli.set_connection_timeout(30);
  7181. auto res = cli.Get("/test");
  7182. ASSERT_TRUE(!res);
  7183. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7184. // For SSL server verification errors, ssl_error should be 0, only
  7185. // ssl_openssl_error should be set
  7186. EXPECT_EQ(0, res.ssl_error());
  7187. // Verify OpenSSL error is captured for SSLServerVerification
  7188. // Note: This test may have different error codes depending on the exact
  7189. // verification failure
  7190. EXPECT_NE(0UL, res.ssl_openssl_error());
  7191. }
  7192. TEST(SSLClientServerTest, TrustDirOptional) {
  7193. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7194. ASSERT_TRUE(svr.is_valid());
  7195. svr.Get("/test", [&](const Request &, Response &res) {
  7196. res.set_content("test", "text/plain");
  7197. });
  7198. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7199. auto se = detail::scope_exit([&] {
  7200. svr.stop();
  7201. t.join();
  7202. ASSERT_FALSE(svr.is_running());
  7203. });
  7204. svr.wait_until_ready();
  7205. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7206. cli.enable_server_certificate_verification(false);
  7207. cli.set_connection_timeout(30);
  7208. auto res = cli.Get("/test");
  7209. ASSERT_TRUE(res);
  7210. ASSERT_EQ(StatusCode::OK_200, res->status);
  7211. }
  7212. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7213. class NoListenSSLServer : public SSLServer {
  7214. public:
  7215. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7216. const char *client_ca_cert_file_path,
  7217. const char *client_ca_cert_dir_path = nullptr)
  7218. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7219. client_ca_cert_dir_path),
  7220. stop_(false) {}
  7221. std::atomic_bool stop_;
  7222. private:
  7223. bool process_and_close_socket(socket_t /*sock*/) override {
  7224. // Don't create SSL context
  7225. while (!stop_.load()) {
  7226. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7227. }
  7228. return true;
  7229. }
  7230. };
  7231. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7232. CLIENT_CA_CERT_FILE);
  7233. ASSERT_TRUE(svr.is_valid());
  7234. svr.Get("/test", [&](const Request &, Response &res) {
  7235. res.set_content("test", "text/plain");
  7236. });
  7237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7238. auto se = detail::scope_exit([&] {
  7239. svr.stop_ = true;
  7240. svr.stop();
  7241. t.join();
  7242. ASSERT_FALSE(svr.is_running());
  7243. });
  7244. svr.wait_until_ready();
  7245. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7246. cli.enable_server_certificate_verification(false);
  7247. cli.set_connection_timeout(1);
  7248. auto res = cli.Get("/test");
  7249. ASSERT_TRUE(!res);
  7250. EXPECT_EQ(Error::SSLConnection, res.error());
  7251. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7252. }
  7253. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7254. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7255. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7256. SSL_CTX_set_options(&ssl_ctx,
  7257. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7258. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7259. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7260. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7261. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7262. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7263. "ECDHE-DSS-AES128-SHA256:"
  7264. "ECDHE-RSA-AES256-SHA256:"
  7265. "ECDHE-DSS-AES256-SHA256:";
  7266. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7267. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7268. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7269. SSL_FILETYPE_PEM) != 1) {
  7270. return false;
  7271. }
  7272. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7273. CLIENT_CA_CERT_DIR);
  7274. SSL_CTX_set_verify(
  7275. &ssl_ctx,
  7276. SSL_VERIFY_PEER |
  7277. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7278. nullptr);
  7279. return true;
  7280. };
  7281. SSLServer svr(setup_ssl_ctx_callback);
  7282. ASSERT_TRUE(svr.is_valid());
  7283. svr.Get("/test", [&](const Request &req, Response &res) {
  7284. res.set_content("test", "text/plain");
  7285. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7286. ASSERT_TRUE(peer_cert != nullptr);
  7287. auto subject_name = X509_get_subject_name(peer_cert);
  7288. ASSERT_TRUE(subject_name != nullptr);
  7289. std::string common_name;
  7290. {
  7291. char name[BUFSIZ];
  7292. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7293. name, sizeof(name));
  7294. common_name.assign(name, static_cast<size_t>(name_len));
  7295. }
  7296. EXPECT_EQ("Common Name", common_name);
  7297. X509_free(peer_cert);
  7298. });
  7299. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7300. auto se = detail::scope_exit([&] {
  7301. svr.stop();
  7302. t.join();
  7303. ASSERT_FALSE(svr.is_running());
  7304. });
  7305. svr.wait_until_ready();
  7306. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7307. cli.enable_server_certificate_verification(false);
  7308. cli.set_connection_timeout(30);
  7309. auto res = cli.Get("/test");
  7310. ASSERT_TRUE(res);
  7311. ASSERT_EQ(StatusCode::OK_200, res->status);
  7312. }
  7313. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7314. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7315. // prepare large data
  7316. std::random_device seed_gen;
  7317. std::mt19937 random(seed_gen());
  7318. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7319. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7320. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7321. // server
  7322. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7323. ASSERT_TRUE(svr.is_valid());
  7324. svr.Post("/binary", [&](const Request &req, Response &res) {
  7325. EXPECT_EQ(large_size_byte, req.body.size());
  7326. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7327. res.set_content(req.body, "application/octet-stream");
  7328. });
  7329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7330. auto se = detail::scope_exit([&] {
  7331. svr.stop();
  7332. listen_thread.join();
  7333. ASSERT_FALSE(svr.is_running());
  7334. });
  7335. svr.wait_until_ready();
  7336. // client POST
  7337. SSLClient cli("localhost", PORT);
  7338. cli.enable_server_certificate_verification(false);
  7339. cli.set_read_timeout(std::chrono::seconds(100));
  7340. cli.set_write_timeout(std::chrono::seconds(100));
  7341. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7342. large_size_byte, "application/octet-stream");
  7343. // compare
  7344. EXPECT_EQ(StatusCode::OK_200, res->status);
  7345. EXPECT_EQ(large_size_byte, res->body.size());
  7346. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7347. }
  7348. #endif
  7349. #ifdef _WIN32
  7350. TEST(CleanupTest, WSACleanup) {
  7351. int ret = WSACleanup();
  7352. ASSERT_EQ(0, ret);
  7353. }
  7354. #endif
  7355. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7356. TEST(NoSSLSupport, SimpleInterface) {
  7357. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7358. }
  7359. #endif
  7360. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7361. TEST(InvalidScheme, SimpleInterface) {
  7362. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7363. }
  7364. #endif
  7365. TEST(NoScheme, SimpleInterface) {
  7366. Client cli("yahoo.com:80");
  7367. ASSERT_TRUE(cli.is_valid());
  7368. }
  7369. TEST(SendAPI, SimpleInterface_Online) {
  7370. Client cli("http://yahoo.com");
  7371. Request req;
  7372. req.method = "GET";
  7373. req.path = "/";
  7374. auto res = cli.send(req);
  7375. ASSERT_TRUE(res);
  7376. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7377. }
  7378. TEST(SendAPI, WithParamsInRequest) {
  7379. Server svr;
  7380. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7381. EXPECT_TRUE(req.has_param("test"));
  7382. EXPECT_EQ("test_value", req.get_param_value("test"));
  7383. });
  7384. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7385. auto se = detail::scope_exit([&] {
  7386. svr.stop();
  7387. t.join();
  7388. ASSERT_FALSE(svr.is_running());
  7389. });
  7390. svr.wait_until_ready();
  7391. Client cli(HOST, PORT);
  7392. {
  7393. Request req;
  7394. req.method = "GET";
  7395. req.path = "/";
  7396. req.params.emplace("test", "test_value");
  7397. auto res = cli.send(req);
  7398. ASSERT_TRUE(res);
  7399. }
  7400. {
  7401. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7402. ASSERT_TRUE(res);
  7403. }
  7404. }
  7405. TEST(ClientImplMethods, GetSocketTest) {
  7406. httplib::Server svr;
  7407. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7408. res.status = StatusCode::OK_200;
  7409. });
  7410. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7411. auto se = detail::scope_exit([&] {
  7412. svr.stop();
  7413. thread.join();
  7414. ASSERT_FALSE(svr.is_running());
  7415. });
  7416. svr.wait_until_ready();
  7417. {
  7418. httplib::Client cli("http://127.0.0.1:3333");
  7419. cli.set_keep_alive(true);
  7420. // Use the behavior of cpp-httplib of opening the connection
  7421. // only when the first request happens. If that changes,
  7422. // this test would be obsolete.
  7423. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7424. // This also implicitly tests the server. But other tests would fail much
  7425. // earlier than this one to be considered.
  7426. auto res = cli.Get("/");
  7427. ASSERT_TRUE(res);
  7428. EXPECT_EQ(StatusCode::OK_200, res->status);
  7429. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7430. }
  7431. }
  7432. // Disabled due to out-of-memory problem on GitHub Actions
  7433. #ifdef _WIN64
  7434. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7435. // allocate content size larger than 2GB in memory
  7436. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7437. char *content = (char *)malloc(content_size);
  7438. ASSERT_TRUE(content);
  7439. Server svr;
  7440. svr.Get("/foo",
  7441. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7442. res.set_content(content, content_size, "application/octet-stream");
  7443. });
  7444. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7445. auto se = detail::scope_exit([&] {
  7446. svr.stop();
  7447. listen_thread.join();
  7448. if (content) free(content);
  7449. ASSERT_FALSE(svr.is_running());
  7450. });
  7451. svr.wait_until_ready();
  7452. Client cli(HOST, PORT);
  7453. auto res = cli.Get("/foo");
  7454. ASSERT_TRUE(res);
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ(content_size, res->body.length());
  7457. }
  7458. #endif
  7459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7460. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7461. Client cli("http://yahoo.com");
  7462. auto res = cli.Get("/");
  7463. ASSERT_TRUE(res);
  7464. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7465. cli.set_follow_location(true);
  7466. res = cli.Get("/");
  7467. ASSERT_TRUE(res);
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7470. }
  7471. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7472. Client cli("https://yahoo.com");
  7473. auto res = cli.Get("/");
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7476. cli.set_follow_location(true);
  7477. res = cli.Get("/");
  7478. ASSERT_TRUE(res);
  7479. EXPECT_EQ(StatusCode::OK_200, res->status);
  7480. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7481. }
  7482. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7483. Client cli("https://yahoo.com");
  7484. auto res = cli.Get("/");
  7485. ASSERT_TRUE(res);
  7486. ASSERT_FALSE(!res);
  7487. ASSERT_TRUE(res);
  7488. ASSERT_FALSE(res == nullptr);
  7489. ASSERT_TRUE(res != nullptr);
  7490. EXPECT_EQ(Error::Success, res.error());
  7491. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7492. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7493. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7494. cli.set_follow_location(true);
  7495. res = cli.Get("/");
  7496. ASSERT_TRUE(res);
  7497. EXPECT_EQ(Error::Success, res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7499. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7500. EXPECT_EQ(StatusCode::OK_200, res->status);
  7501. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7502. }
  7503. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7504. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7505. Client cli("https://cdnjs.cloudflare.com");
  7506. auto res =
  7507. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7508. ASSERT_TRUE(res);
  7509. EXPECT_EQ(StatusCode::OK_200, res->status);
  7510. EXPECT_EQ(287630U, res->body.size());
  7511. EXPECT_EQ("application/javascript; charset=utf-8",
  7512. res->get_header_value("Content-Type"));
  7513. }
  7514. #endif
  7515. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7516. #undef REDIR_HOST // Silence compiler warning
  7517. #define REDIR_HOST "https://httpbingo.org"
  7518. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7519. Client cli(REDIR_HOST);
  7520. cli.set_follow_location(true);
  7521. auto res =
  7522. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7523. ASSERT_TRUE(res);
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. }
  7526. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7527. Client cli(REDIR_HOST);
  7528. cli.set_follow_location(true);
  7529. Params params;
  7530. params.emplace("url", "http://example.com");
  7531. params.emplace("status_code", "302");
  7532. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7533. ASSERT_TRUE(res);
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. }
  7536. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7537. Client cli(REDIR_HOST);
  7538. cli.set_follow_location(true);
  7539. Params params;
  7540. params.emplace("url", "http://example.com");
  7541. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7542. ASSERT_TRUE(res);
  7543. EXPECT_EQ(StatusCode::OK_200, res->status);
  7544. }
  7545. TEST(HttpToHttpsRedirectTest, CertFile) {
  7546. Server svr;
  7547. ASSERT_TRUE(svr.is_valid());
  7548. svr.Get("/index", [&](const Request &, Response &res) {
  7549. res.set_redirect("https://127.0.0.1:1235/index");
  7550. svr.stop();
  7551. });
  7552. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7553. ASSERT_TRUE(ssl_svr.is_valid());
  7554. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7555. res.set_content("test", "text/plain");
  7556. ssl_svr.stop();
  7557. });
  7558. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7559. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7560. auto se = detail::scope_exit([&] {
  7561. t2.join();
  7562. t.join();
  7563. ASSERT_FALSE(svr.is_running());
  7564. });
  7565. svr.wait_until_ready();
  7566. ssl_svr.wait_until_ready();
  7567. Client cli("127.0.0.1", PORT);
  7568. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7569. cli.enable_server_certificate_verification(true);
  7570. cli.set_follow_location(true);
  7571. cli.set_connection_timeout(30);
  7572. auto res = cli.Get("/index");
  7573. ASSERT_TRUE(res);
  7574. ASSERT_EQ(StatusCode::OK_200, res->status);
  7575. }
  7576. TEST(SSLClientRedirectTest, CertFile) {
  7577. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7578. ASSERT_TRUE(ssl_svr1.is_valid());
  7579. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7580. res.set_redirect("https://127.0.0.1:1235/index");
  7581. ssl_svr1.stop();
  7582. });
  7583. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7584. ASSERT_TRUE(ssl_svr2.is_valid());
  7585. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7586. res.set_content("test", "text/plain");
  7587. ssl_svr2.stop();
  7588. });
  7589. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7590. thread t2 =
  7591. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7592. auto se = detail::scope_exit([&] {
  7593. t2.join();
  7594. t.join();
  7595. ASSERT_FALSE(ssl_svr1.is_running());
  7596. });
  7597. ssl_svr1.wait_until_ready();
  7598. ssl_svr2.wait_until_ready();
  7599. SSLClient cli("127.0.0.1", PORT);
  7600. std::string cert;
  7601. read_file(SERVER_CERT2_FILE, cert);
  7602. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7603. cli.enable_server_certificate_verification(true);
  7604. cli.set_follow_location(true);
  7605. cli.set_connection_timeout(30);
  7606. auto res = cli.Get("/index");
  7607. ASSERT_TRUE(res);
  7608. ASSERT_EQ(StatusCode::OK_200, res->status);
  7609. }
  7610. TEST(MultipartFormDataTest, LargeData) {
  7611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7612. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7613. const ContentReader &content_reader) {
  7614. if (req.is_multipart_form_data()) {
  7615. std::vector<FormData> items;
  7616. content_reader(
  7617. [&](const FormData &file) {
  7618. items.push_back(file);
  7619. return true;
  7620. },
  7621. [&](const char *data, size_t data_length) {
  7622. items.back().content.append(data, data_length);
  7623. return true;
  7624. });
  7625. EXPECT_TRUE(std::string(items[0].name) == "document");
  7626. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7627. EXPECT_TRUE(items[0].filename == "2MB_data");
  7628. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7629. EXPECT_TRUE(items[1].name == "hello");
  7630. EXPECT_TRUE(items[1].content == "world");
  7631. EXPECT_TRUE(items[1].filename == "");
  7632. EXPECT_TRUE(items[1].content_type == "");
  7633. } else {
  7634. std::string body;
  7635. content_reader([&](const char *data, size_t data_length) {
  7636. body.append(data, data_length);
  7637. return true;
  7638. });
  7639. }
  7640. });
  7641. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7642. auto se = detail::scope_exit([&] {
  7643. svr.stop();
  7644. t.join();
  7645. ASSERT_FALSE(svr.is_running());
  7646. });
  7647. svr.wait_until_ready();
  7648. {
  7649. std::string data(1024 * 1024 * 2, '.');
  7650. std::stringstream buffer;
  7651. buffer << data;
  7652. Client cli("https://localhost:8080");
  7653. cli.enable_server_certificate_verification(false);
  7654. UploadFormDataItems items{
  7655. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7656. {"hello", "world", "", ""},
  7657. };
  7658. auto res = cli.Post("/post", items);
  7659. ASSERT_TRUE(res);
  7660. ASSERT_EQ(StatusCode::OK_200, res->status);
  7661. }
  7662. }
  7663. TEST(MultipartFormDataTest, DataProviderItems) {
  7664. std::random_device seed_gen;
  7665. std::mt19937 random(seed_gen());
  7666. std::string rand1;
  7667. rand1.resize(1000);
  7668. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7669. std::string rand2;
  7670. rand2.resize(3000);
  7671. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7673. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7674. const ContentReader &content_reader) {
  7675. ASSERT_FALSE(req.is_multipart_form_data());
  7676. std::string body;
  7677. content_reader([&](const char *data, size_t data_length) {
  7678. body.append(data, data_length);
  7679. return true;
  7680. });
  7681. EXPECT_EQ(body, "");
  7682. });
  7683. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7684. const ContentReader &content_reader) {
  7685. ASSERT_TRUE(req.is_multipart_form_data());
  7686. std::vector<FormData> items;
  7687. content_reader(
  7688. [&](const FormData &file) {
  7689. items.push_back(file);
  7690. return true;
  7691. },
  7692. [&](const char *data, size_t data_length) {
  7693. items.back().content.append(data, data_length);
  7694. return true;
  7695. });
  7696. ASSERT_TRUE(items.size() == 2);
  7697. EXPECT_EQ(std::string(items[0].name), "name1");
  7698. EXPECT_EQ(items[0].content, "Testing123");
  7699. EXPECT_EQ(items[0].filename, "filename1");
  7700. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7701. EXPECT_EQ(items[1].name, "name2");
  7702. EXPECT_EQ(items[1].content, "Testing456");
  7703. EXPECT_EQ(items[1].filename, "");
  7704. EXPECT_EQ(items[1].content_type, "");
  7705. });
  7706. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7707. const ContentReader &content_reader) {
  7708. ASSERT_TRUE(req.is_multipart_form_data());
  7709. std::vector<FormData> items;
  7710. content_reader(
  7711. [&](const FormData &file) {
  7712. items.push_back(file);
  7713. return true;
  7714. },
  7715. [&](const char *data, size_t data_length) {
  7716. items.back().content.append(data, data_length);
  7717. return true;
  7718. });
  7719. ASSERT_TRUE(items.size() == 2);
  7720. EXPECT_EQ(items[0].name, "name3");
  7721. EXPECT_EQ(items[0].content, rand1);
  7722. EXPECT_EQ(items[0].filename, "filename3");
  7723. EXPECT_EQ(items[0].content_type, "");
  7724. EXPECT_EQ(items[1].name, "name4");
  7725. EXPECT_EQ(items[1].content, rand2);
  7726. EXPECT_EQ(items[1].filename, "filename4");
  7727. EXPECT_EQ(items[1].content_type, "");
  7728. });
  7729. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7730. const ContentReader &content_reader) {
  7731. ASSERT_TRUE(req.is_multipart_form_data());
  7732. std::vector<FormData> items;
  7733. content_reader(
  7734. [&](const FormData &file) {
  7735. items.push_back(file);
  7736. return true;
  7737. },
  7738. [&](const char *data, size_t data_length) {
  7739. items.back().content.append(data, data_length);
  7740. return true;
  7741. });
  7742. ASSERT_TRUE(items.size() == 4);
  7743. EXPECT_EQ(std::string(items[0].name), "name1");
  7744. EXPECT_EQ(items[0].content, "Testing123");
  7745. EXPECT_EQ(items[0].filename, "filename1");
  7746. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7747. EXPECT_EQ(items[1].name, "name2");
  7748. EXPECT_EQ(items[1].content, "Testing456");
  7749. EXPECT_EQ(items[1].filename, "");
  7750. EXPECT_EQ(items[1].content_type, "");
  7751. EXPECT_EQ(items[2].name, "name3");
  7752. EXPECT_EQ(items[2].content, rand1);
  7753. EXPECT_EQ(items[2].filename, "filename3");
  7754. EXPECT_EQ(items[2].content_type, "");
  7755. EXPECT_EQ(items[3].name, "name4");
  7756. EXPECT_EQ(items[3].content, rand2);
  7757. EXPECT_EQ(items[3].filename, "filename4");
  7758. EXPECT_EQ(items[3].content_type, "");
  7759. });
  7760. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7761. auto se = detail::scope_exit([&] {
  7762. svr.stop();
  7763. t.join();
  7764. ASSERT_FALSE(svr.is_running());
  7765. });
  7766. svr.wait_until_ready();
  7767. {
  7768. Client cli("https://localhost:8080");
  7769. cli.enable_server_certificate_verification(false);
  7770. UploadFormDataItems items{
  7771. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7772. {"name2", "Testing456", "", ""}, // not a file
  7773. };
  7774. {
  7775. auto res = cli.Post("/post-none", {}, {}, {});
  7776. ASSERT_TRUE(res);
  7777. ASSERT_EQ(StatusCode::OK_200, res->status);
  7778. }
  7779. FormDataProviderItems providers;
  7780. {
  7781. auto res =
  7782. cli.Post("/post-items", {}, items, providers); // empty providers
  7783. ASSERT_TRUE(res);
  7784. ASSERT_EQ(StatusCode::OK_200, res->status);
  7785. }
  7786. providers.push_back({"name3",
  7787. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7788. // test the offset is given correctly at each step
  7789. if (!offset)
  7790. sink.os.write(rand1.data(), 30);
  7791. else if (offset == 30)
  7792. sink.os.write(rand1.data() + 30, 300);
  7793. else if (offset == 330)
  7794. sink.os.write(rand1.data() + 330, 670);
  7795. else if (offset == rand1.size())
  7796. sink.done();
  7797. return true;
  7798. },
  7799. "filename3",
  7800. {}});
  7801. providers.push_back({"name4",
  7802. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7803. // test the offset is given correctly at each step
  7804. if (!offset)
  7805. sink.os.write(rand2.data(), 2000);
  7806. else if (offset == 2000)
  7807. sink.os.write(rand2.data() + 2000, 1);
  7808. else if (offset == 2001)
  7809. sink.os.write(rand2.data() + 2001, 999);
  7810. else if (offset == rand2.size())
  7811. sink.done();
  7812. return true;
  7813. },
  7814. "filename4",
  7815. {}});
  7816. {
  7817. auto res = cli.Post("/post-providers", {}, {}, providers);
  7818. ASSERT_TRUE(res);
  7819. ASSERT_EQ(StatusCode::OK_200, res->status);
  7820. }
  7821. {
  7822. auto res = cli.Post("/post-both", {}, items, providers);
  7823. ASSERT_TRUE(res);
  7824. ASSERT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. }
  7827. }
  7828. TEST(MultipartFormDataTest, BadHeader) {
  7829. Server svr;
  7830. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7831. res.set_content("ok", "text/plain");
  7832. });
  7833. thread t = thread([&] { svr.listen(HOST, PORT); });
  7834. auto se = detail::scope_exit([&] {
  7835. svr.stop();
  7836. t.join();
  7837. ASSERT_FALSE(svr.is_running());
  7838. });
  7839. svr.wait_until_ready();
  7840. const std::string body =
  7841. "This is the preamble. It is to be ignored, though it\r\n"
  7842. "is a handy place for composition agents to include an\r\n"
  7843. "explanatory note to non-MIME conformant readers.\r\n"
  7844. "\r\n"
  7845. "\r\n"
  7846. "--simple boundary\r\n"
  7847. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7848. ": BAD...\r\n"
  7849. "\r\n"
  7850. "value1\r\n"
  7851. "--simple boundary\r\n"
  7852. "Content-Disposition: form-data; name=\"field2\"; "
  7853. "filename=\"example.txt\"\r\n"
  7854. "\r\n"
  7855. "value2\r\n"
  7856. "--simple boundary--\r\n"
  7857. "This is the epilogue. It is also to be ignored.\r\n";
  7858. std::string content_type =
  7859. R"(multipart/form-data; boundary="simple boundary")";
  7860. Client cli(HOST, PORT);
  7861. auto res = cli.Post("/post", body, content_type.c_str());
  7862. ASSERT_TRUE(res);
  7863. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7864. }
  7865. TEST(MultipartFormDataTest, WithPreamble) {
  7866. Server svr;
  7867. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7868. res.set_content("ok", "text/plain");
  7869. });
  7870. thread t = thread([&] { svr.listen(HOST, PORT); });
  7871. auto se = detail::scope_exit([&] {
  7872. svr.stop();
  7873. t.join();
  7874. ASSERT_FALSE(svr.is_running());
  7875. });
  7876. svr.wait_until_ready();
  7877. const std::string body =
  7878. "This is the preamble. It is to be ignored, though it\r\n"
  7879. "is a handy place for composition agents to include an\r\n"
  7880. "explanatory note to non-MIME conformant readers.\r\n"
  7881. "\r\n"
  7882. "\r\n"
  7883. "--simple boundary\r\n"
  7884. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7885. "\r\n"
  7886. "value1\r\n"
  7887. "--simple boundary\r\n"
  7888. "Content-Disposition: form-data; name=\"field2\"; "
  7889. "filename=\"example.txt\"\r\n"
  7890. "\r\n"
  7891. "value2\r\n"
  7892. "--simple boundary--\r\n"
  7893. "This is the epilogue. It is also to be ignored.\r\n";
  7894. std::string content_type =
  7895. R"(multipart/form-data; boundary="simple boundary")";
  7896. Client cli(HOST, PORT);
  7897. auto res = cli.Post("/post", body, content_type.c_str());
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7903. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7904. const ContentReader &content_reader) {
  7905. if (req.is_multipart_form_data()) {
  7906. std::vector<FormData> items;
  7907. content_reader(
  7908. [&](const FormData &file) {
  7909. items.push_back(file);
  7910. return true;
  7911. },
  7912. [&](const char *data, size_t data_length) {
  7913. items.back().content.append(data, data_length);
  7914. return true;
  7915. });
  7916. EXPECT_TRUE(std::string(items[0].name) == "document");
  7917. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7918. EXPECT_TRUE(items[0].filename == "2MB_data");
  7919. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7920. EXPECT_TRUE(items[1].name == "hello");
  7921. EXPECT_TRUE(items[1].content == "world");
  7922. EXPECT_TRUE(items[1].filename == "");
  7923. EXPECT_TRUE(items[1].content_type == "");
  7924. } else {
  7925. std::string body;
  7926. content_reader([&](const char *data, size_t data_length) {
  7927. body.append(data, data_length);
  7928. return true;
  7929. });
  7930. }
  7931. });
  7932. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7933. auto se = detail::scope_exit([&] {
  7934. svr.stop();
  7935. t.join();
  7936. ASSERT_FALSE(svr.is_running());
  7937. });
  7938. svr.wait_until_ready();
  7939. {
  7940. std::string data(1024 * 1024 * 2, '.');
  7941. std::stringstream buffer;
  7942. buffer << data;
  7943. Client cli("https://localhost:8080");
  7944. cli.enable_server_certificate_verification(false);
  7945. UploadFormDataItems items{
  7946. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7947. {"hello", "world", "", ""},
  7948. };
  7949. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7950. ASSERT_TRUE(res);
  7951. ASSERT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. }
  7954. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7955. std::string data(1024 * 1024 * 2, '&');
  7956. std::stringstream buffer;
  7957. buffer << data;
  7958. Client cli("https://localhost:8080");
  7959. UploadFormDataItems items{
  7960. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7961. {"hello", "world", "", ""},
  7962. };
  7963. for (const char &c : " \t\r\n") {
  7964. auto res =
  7965. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7966. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7967. ASSERT_FALSE(res);
  7968. }
  7969. }
  7970. TEST(MultipartFormDataTest, PutFormData) {
  7971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7972. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7973. const ContentReader &content_reader) {
  7974. if (req.is_multipart_form_data()) {
  7975. std::vector<FormData> items;
  7976. content_reader(
  7977. [&](const FormData &file) {
  7978. items.push_back(file);
  7979. return true;
  7980. },
  7981. [&](const char *data, size_t data_length) {
  7982. items.back().content.append(data, data_length);
  7983. return true;
  7984. });
  7985. EXPECT_TRUE(std::string(items[0].name) == "document");
  7986. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7987. EXPECT_TRUE(items[0].filename == "2MB_data");
  7988. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7989. EXPECT_TRUE(items[1].name == "hello");
  7990. EXPECT_TRUE(items[1].content == "world");
  7991. EXPECT_TRUE(items[1].filename == "");
  7992. EXPECT_TRUE(items[1].content_type == "");
  7993. } else {
  7994. std::string body;
  7995. content_reader([&](const char *data, size_t data_length) {
  7996. body.append(data, data_length);
  7997. return true;
  7998. });
  7999. }
  8000. });
  8001. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8002. auto se = detail::scope_exit([&] {
  8003. svr.stop();
  8004. t.join();
  8005. ASSERT_FALSE(svr.is_running());
  8006. });
  8007. svr.wait_until_ready();
  8008. {
  8009. std::string data(1024 * 1024 * 2, '&');
  8010. std::stringstream buffer;
  8011. buffer << data;
  8012. Client cli("https://localhost:8080");
  8013. cli.enable_server_certificate_verification(false);
  8014. UploadFormDataItems items{
  8015. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8016. {"hello", "world", "", ""},
  8017. };
  8018. auto res = cli.Put("/put", items);
  8019. ASSERT_TRUE(res);
  8020. ASSERT_EQ(StatusCode::OK_200, res->status);
  8021. }
  8022. }
  8023. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8025. svr.Put("/put_customboundary",
  8026. [&](const Request &req, const Response & /*res*/,
  8027. const ContentReader &content_reader) {
  8028. if (req.is_multipart_form_data()) {
  8029. std::vector<FormData> items;
  8030. content_reader(
  8031. [&](const FormData &file) {
  8032. items.push_back(file);
  8033. return true;
  8034. },
  8035. [&](const char *data, size_t data_length) {
  8036. items.back().content.append(data, data_length);
  8037. return true;
  8038. });
  8039. EXPECT_TRUE(std::string(items[0].name) == "document");
  8040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8041. EXPECT_TRUE(items[0].filename == "2MB_data");
  8042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8043. EXPECT_TRUE(items[1].name == "hello");
  8044. EXPECT_TRUE(items[1].content == "world");
  8045. EXPECT_TRUE(items[1].filename == "");
  8046. EXPECT_TRUE(items[1].content_type == "");
  8047. } else {
  8048. std::string body;
  8049. content_reader([&](const char *data, size_t data_length) {
  8050. body.append(data, data_length);
  8051. return true;
  8052. });
  8053. }
  8054. });
  8055. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. t.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. {
  8063. std::string data(1024 * 1024 * 2, '&');
  8064. std::stringstream buffer;
  8065. buffer << data;
  8066. Client cli("https://localhost:8080");
  8067. cli.enable_server_certificate_verification(false);
  8068. UploadFormDataItems items{
  8069. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8070. {"hello", "world", "", ""},
  8071. };
  8072. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8073. ASSERT_TRUE(res);
  8074. ASSERT_EQ(StatusCode::OK_200, res->status);
  8075. }
  8076. }
  8077. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8078. std::string data(1024 * 1024 * 2, '&');
  8079. std::stringstream buffer;
  8080. buffer << data;
  8081. Client cli("https://localhost:8080");
  8082. cli.enable_server_certificate_verification(false);
  8083. UploadFormDataItems items{
  8084. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8085. {"hello", "world", "", ""},
  8086. };
  8087. for (const char &c : " \t\r\n") {
  8088. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8089. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8090. ASSERT_FALSE(res);
  8091. }
  8092. }
  8093. TEST(MultipartFormDataTest, AlternateFilename) {
  8094. auto handled = false;
  8095. Server svr;
  8096. svr.Post("/test", [&](const Request &req, Response &res) {
  8097. ASSERT_EQ(2u, req.form.files.size());
  8098. ASSERT_EQ(1u, req.form.fields.size());
  8099. // Test files
  8100. const auto &file1 = req.form.get_file("file1");
  8101. ASSERT_EQ("file1", file1.name);
  8102. ASSERT_EQ("A.txt", file1.filename);
  8103. ASSERT_EQ("text/plain", file1.content_type);
  8104. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8105. const auto &file2 = req.form.get_file("file2");
  8106. ASSERT_EQ("file2", file2.name);
  8107. ASSERT_EQ("a.html", file2.filename);
  8108. ASSERT_EQ("text/html", file2.content_type);
  8109. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8110. file2.content);
  8111. // Test text field
  8112. const auto &text = req.form.get_field("text");
  8113. ASSERT_EQ("text default", text);
  8114. res.set_content("ok", "text/plain");
  8115. handled = true;
  8116. });
  8117. thread t = thread([&] { svr.listen(HOST, PORT); });
  8118. auto se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. t.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. ASSERT_TRUE(handled);
  8123. });
  8124. svr.wait_until_ready();
  8125. auto req = "POST /test HTTP/1.1\r\n"
  8126. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8127. "Content-Length: 399\r\n"
  8128. "\r\n"
  8129. "----------\r\n"
  8130. "Content-Disposition: form-data; name=\"text\"\r\n"
  8131. "\r\n"
  8132. "text default\r\n"
  8133. "----------\r\n"
  8134. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8135. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8136. "Content-Type: text/plain\r\n"
  8137. "\r\n"
  8138. "Content of a.txt.\r\n"
  8139. "\r\n"
  8140. "----------\r\n"
  8141. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8142. "\"a.html\"\r\n"
  8143. "Content-Type: text/html\r\n"
  8144. "\r\n"
  8145. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8146. "\r\n"
  8147. "------------\r\n";
  8148. ASSERT_TRUE(send_request(1, req));
  8149. }
  8150. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8151. auto handled = false;
  8152. Server svr;
  8153. svr.Post("/test", [&](const Request &req, Response &) {
  8154. ASSERT_EQ(2u, req.form.fields.size());
  8155. const auto &text1 = req.form.get_field("text1");
  8156. ASSERT_EQ("text1", text1);
  8157. const auto &text2 = req.form.get_field("text2");
  8158. ASSERT_EQ("text2", text2);
  8159. handled = true;
  8160. });
  8161. thread t = thread([&] { svr.listen(HOST, PORT); });
  8162. auto se = detail::scope_exit([&] {
  8163. svr.stop();
  8164. t.join();
  8165. ASSERT_FALSE(svr.is_running());
  8166. ASSERT_TRUE(handled);
  8167. });
  8168. svr.wait_until_ready();
  8169. auto req = "POST /test HTTP/1.1\r\n"
  8170. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8171. "Content-Length: 146\r\n"
  8172. "\r\n----------\r\n"
  8173. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8174. "\r\n"
  8175. "text1"
  8176. "\r\n----------\r\n"
  8177. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8178. "\r\n"
  8179. "text2"
  8180. "\r\n------------";
  8181. std::string response;
  8182. ASSERT_TRUE(send_request(1, req, &response));
  8183. ASSERT_EQ("200", response.substr(9, 3));
  8184. }
  8185. TEST(MultipartFormDataTest, ContentLength) {
  8186. auto handled = false;
  8187. Server svr;
  8188. svr.Post("/test", [&](const Request &req, Response &) {
  8189. ASSERT_EQ(2u, req.form.fields.size());
  8190. const auto &text1 = req.form.get_field("text1");
  8191. ASSERT_EQ("text1", text1);
  8192. const auto &text2 = req.form.get_field("text2");
  8193. ASSERT_EQ("text2", text2);
  8194. handled = true;
  8195. });
  8196. thread t = thread([&] { svr.listen(HOST, PORT); });
  8197. auto se = detail::scope_exit([&] {
  8198. svr.stop();
  8199. t.join();
  8200. ASSERT_FALSE(svr.is_running());
  8201. ASSERT_TRUE(handled);
  8202. });
  8203. svr.wait_until_ready();
  8204. auto req = "POST /test HTTP/1.1\r\n"
  8205. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8206. "Content-Length: 167\r\n"
  8207. "\r\n----------\r\n"
  8208. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8209. "Content-Length: 5\r\n"
  8210. "\r\n"
  8211. "text1"
  8212. "\r\n----------\r\n"
  8213. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8214. "\r\n"
  8215. "text2"
  8216. "\r\n------------\r\n";
  8217. std::string response;
  8218. ASSERT_TRUE(send_request(1, req, &response));
  8219. ASSERT_EQ("200", response.substr(9, 3));
  8220. }
  8221. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8222. auto handled = false;
  8223. Server svr;
  8224. svr.Post("/test", [&](const Request &req, Response &) {
  8225. ASSERT_EQ(2u, req.form.fields.size());
  8226. const auto &text1 = req.form.get_field("text1");
  8227. ASSERT_EQ("text1", text1);
  8228. // TODO: Add header access for text fields if needed
  8229. const auto &text2 = req.form.get_field("text2");
  8230. ASSERT_EQ("text2", text2);
  8231. // TODO: Header access for text fields needs to be implemented
  8232. // auto &headers = it->second.headers;
  8233. // ASSERT_EQ(3U, headers.size());
  8234. // auto custom_header = headers.find("x-whatever");
  8235. // ASSERT_TRUE(custom_header != headers.end());
  8236. // ASSERT_NE("customvalue", custom_header->second);
  8237. // ASSERT_EQ("CustomValue", custom_header->second);
  8238. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8239. handled = true;
  8240. });
  8241. thread t = thread([&] { svr.listen(HOST, PORT); });
  8242. auto se = detail::scope_exit([&] {
  8243. svr.stop();
  8244. t.join();
  8245. ASSERT_FALSE(svr.is_running());
  8246. ASSERT_TRUE(handled);
  8247. });
  8248. svr.wait_until_ready();
  8249. auto req = "POST /test HTTP/1.1\r\n"
  8250. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8251. "Content-Length: 232\r\n"
  8252. "\r\n----------\r\n"
  8253. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8254. "Content-Length: 5\r\n"
  8255. "X-Test: 1\r\n"
  8256. "\r\n"
  8257. "text1"
  8258. "\r\n----------\r\n"
  8259. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8260. "Content-Type: text/plain\r\n"
  8261. "X-Whatever: CustomValue\r\n"
  8262. "\r\n"
  8263. "text2"
  8264. "\r\n------------\r\n"
  8265. "That should be disregarded. Not even read";
  8266. std::string response;
  8267. ASSERT_TRUE(send_request(1, req, &response));
  8268. ASSERT_EQ("200", response.substr(9, 3));
  8269. }
  8270. #endif
  8271. TEST(MultipartFormDataTest, LargeHeader) {
  8272. auto handled = false;
  8273. Server svr;
  8274. svr.Post("/test", [&](const Request &req, Response &) {
  8275. ASSERT_EQ(1u, req.form.fields.size());
  8276. const auto &text = req.form.get_field("name1");
  8277. ASSERT_EQ("text1", text);
  8278. handled = true;
  8279. });
  8280. thread t = thread([&] { svr.listen(HOST, PORT); });
  8281. auto se = detail::scope_exit([&] {
  8282. svr.stop();
  8283. t.join();
  8284. ASSERT_FALSE(svr.is_running());
  8285. ASSERT_TRUE(handled);
  8286. });
  8287. svr.wait_until_ready();
  8288. auto boundary = std::string("cpp-httplib-multipart-data");
  8289. std::string content = "--" + boundary +
  8290. "\r\n"
  8291. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8292. "\r\n"
  8293. "text1\r\n"
  8294. "--" +
  8295. boundary + "--\r\n";
  8296. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8297. "Content-Type: multipart/form-data;boundary=" +
  8298. boundary +
  8299. "\r\n"
  8300. "Content-Length: " +
  8301. std::to_string(content.size()) +
  8302. "\r\n"
  8303. "Dummy-Header: ";
  8304. std::string header_suffix = "\r\n"
  8305. "\r\n";
  8306. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8307. size_t header_dummy_size =
  8308. read_buff_size -
  8309. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8310. auto header_dummy = std::string(header_dummy_size, '@');
  8311. auto req = header_prefix + header_dummy + header_suffix + content;
  8312. std::string response;
  8313. ASSERT_TRUE(send_request(1, req, &response));
  8314. ASSERT_EQ("200", response.substr(9, 3));
  8315. }
  8316. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8317. static constexpr unsigned int number_of_tasks{1000000};
  8318. std::atomic_uint count{0};
  8319. std::unique_ptr<TaskQueue> task_queue{
  8320. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8321. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8322. auto queued = task_queue->enqueue(
  8323. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8324. EXPECT_TRUE(queued);
  8325. }
  8326. EXPECT_NO_THROW(task_queue->shutdown());
  8327. EXPECT_EQ(number_of_tasks, count.load());
  8328. }
  8329. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8330. static constexpr unsigned int number_of_tasks{1000000};
  8331. static constexpr unsigned int qlimit{2};
  8332. unsigned int queued_count{0};
  8333. std::atomic_uint count{0};
  8334. std::unique_ptr<TaskQueue> task_queue{
  8335. new ThreadPool{/*num_threads=*/1, qlimit}};
  8336. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8337. if (task_queue->enqueue(
  8338. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8339. queued_count++;
  8340. }
  8341. }
  8342. EXPECT_NO_THROW(task_queue->shutdown());
  8343. EXPECT_EQ(queued_count, count.load());
  8344. EXPECT_TRUE(queued_count <= number_of_tasks);
  8345. EXPECT_TRUE(queued_count >= qlimit);
  8346. }
  8347. TEST(TaskQueueTest, MaxQueuedRequests) {
  8348. static constexpr unsigned int qlimit{3};
  8349. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8350. std::condition_variable sem_cv;
  8351. std::mutex sem_mtx;
  8352. int credits = 0;
  8353. bool queued;
  8354. /* Fill up the queue with tasks that will block until we give them credits to
  8355. * complete. */
  8356. for (unsigned int n = 0; n <= qlimit;) {
  8357. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8358. std::unique_lock<std::mutex> lock(sem_mtx);
  8359. while (credits <= 0) {
  8360. sem_cv.wait(lock);
  8361. }
  8362. /* Consume the credit and signal the test code if they are all gone. */
  8363. if (--credits == 0) { sem_cv.notify_one(); }
  8364. });
  8365. if (n < qlimit) {
  8366. /* The first qlimit enqueues must succeed. */
  8367. EXPECT_TRUE(queued);
  8368. } else {
  8369. /* The last one will succeed only when the worker thread
  8370. * starts and dequeues the first blocking task. Although
  8371. * not necessary for the correctness of this test, we sleep for
  8372. * a short while to avoid busy waiting. */
  8373. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8374. }
  8375. if (queued) { n++; }
  8376. }
  8377. /* Further enqueues must fail since the queue is full. */
  8378. for (auto i = 0; i < 4; i++) {
  8379. queued = task_queue->enqueue([] {});
  8380. EXPECT_FALSE(queued);
  8381. }
  8382. /* Give the credits to allow the previous tasks to complete. */
  8383. {
  8384. std::unique_lock<std::mutex> lock(sem_mtx);
  8385. credits += qlimit + 1;
  8386. }
  8387. sem_cv.notify_all();
  8388. /* Wait for all the credits to be consumed. */
  8389. {
  8390. std::unique_lock<std::mutex> lock(sem_mtx);
  8391. while (credits > 0) {
  8392. sem_cv.wait(lock);
  8393. }
  8394. }
  8395. /* Check that we are able again to enqueue at least qlimit tasks. */
  8396. for (unsigned int i = 0; i < qlimit; i++) {
  8397. queued = task_queue->enqueue([] {});
  8398. EXPECT_TRUE(queued);
  8399. }
  8400. EXPECT_NO_THROW(task_queue->shutdown());
  8401. }
  8402. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8403. Server svr;
  8404. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8405. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8406. });
  8407. svr.Get("/hello", [](const Request &req, Response &res) {
  8408. res.set_content(req.get_param_value("key"), "text/plain");
  8409. });
  8410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8411. auto se = detail::scope_exit([&] {
  8412. svr.stop();
  8413. thread.join();
  8414. ASSERT_FALSE(svr.is_running());
  8415. });
  8416. svr.wait_until_ready();
  8417. {
  8418. Client cli(HOST, PORT);
  8419. cli.set_follow_location(true);
  8420. auto res = cli.Get("/");
  8421. ASSERT_TRUE(res);
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. EXPECT_EQ("val&key2=val2", res->body);
  8424. }
  8425. }
  8426. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8427. Server svr;
  8428. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8429. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8430. });
  8431. svr.Get("/hello", [](const Request &req, Response &res) {
  8432. res.set_content(req.get_param_value("key"), "text/plain");
  8433. });
  8434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8435. auto se = detail::scope_exit([&] {
  8436. svr.stop();
  8437. thread.join();
  8438. ASSERT_FALSE(svr.is_running());
  8439. });
  8440. svr.wait_until_ready();
  8441. {
  8442. Client cli(HOST, PORT);
  8443. cli.set_follow_location(true);
  8444. auto res = cli.Get("/");
  8445. ASSERT_TRUE(res);
  8446. EXPECT_EQ(StatusCode::OK_200, res->status);
  8447. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8448. }
  8449. }
  8450. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8451. TEST(RedirectTest, Issue2185_Online) {
  8452. SSLClient client("github.com");
  8453. client.set_follow_location(true);
  8454. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8455. "Coollab-Windows.zip");
  8456. ASSERT_TRUE(res);
  8457. EXPECT_EQ(StatusCode::OK_200, res->status);
  8458. EXPECT_EQ(9920427U, res->body.size());
  8459. }
  8460. #endif
  8461. TEST(VulnerabilityTest, CRLFInjection) {
  8462. Server svr;
  8463. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8464. res.set_content("Hello 1", "text/plain");
  8465. });
  8466. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8467. res.set_content("Hello 2", "text/plain");
  8468. });
  8469. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8470. res.set_content("Hello 3", "text/plain");
  8471. });
  8472. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8473. res.set_content("Hello 4", "text/plain");
  8474. });
  8475. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8476. for (const auto &x : req.headers) {
  8477. auto key = x.first;
  8478. EXPECT_STRNE("evil", key.c_str());
  8479. }
  8480. });
  8481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. thread.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. {
  8489. Client cli(HOST, PORT);
  8490. cli.Post("/test1", "A=B",
  8491. "application/x-www-form-urlencoded\r\nevil: hello1");
  8492. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8493. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8494. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8495. }
  8496. }
  8497. TEST(PathParamsTest, StaticMatch) {
  8498. const auto pattern = "/users/all";
  8499. detail::PathParamsMatcher matcher(pattern);
  8500. Request request;
  8501. request.path = "/users/all";
  8502. ASSERT_TRUE(matcher.match(request));
  8503. std::unordered_map<std::string, std::string> expected_params = {};
  8504. EXPECT_EQ(request.path_params, expected_params);
  8505. }
  8506. TEST(PathParamsTest, StaticMismatch) {
  8507. const auto pattern = "/users/all";
  8508. detail::PathParamsMatcher matcher(pattern);
  8509. Request request;
  8510. request.path = "/users/1";
  8511. ASSERT_FALSE(matcher.match(request));
  8512. }
  8513. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8514. const auto pattern = "/users/:id/subscriptions";
  8515. detail::PathParamsMatcher matcher(pattern);
  8516. Request request;
  8517. request.path = "/users/42/subscriptions";
  8518. ASSERT_TRUE(matcher.match(request));
  8519. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8520. EXPECT_EQ(request.path_params, expected_params);
  8521. }
  8522. TEST(PathParamsTest, SingleParamInTheEnd) {
  8523. const auto pattern = "/users/:id";
  8524. detail::PathParamsMatcher matcher(pattern);
  8525. Request request;
  8526. request.path = "/users/24";
  8527. ASSERT_TRUE(matcher.match(request));
  8528. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8529. EXPECT_EQ(request.path_params, expected_params);
  8530. }
  8531. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8532. const auto pattern = "/users/:id/";
  8533. detail::PathParamsMatcher matcher(pattern);
  8534. Request request;
  8535. request.path = "/users/42/";
  8536. ASSERT_TRUE(matcher.match(request));
  8537. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8538. EXPECT_EQ(request.path_params, expected_params);
  8539. }
  8540. TEST(PathParamsTest, EmptyParam) {
  8541. const auto pattern = "/users/:id/";
  8542. detail::PathParamsMatcher matcher(pattern);
  8543. Request request;
  8544. request.path = "/users//";
  8545. ASSERT_TRUE(matcher.match(request));
  8546. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8547. EXPECT_EQ(request.path_params, expected_params);
  8548. }
  8549. TEST(PathParamsTest, FragmentMismatch) {
  8550. const auto pattern = "/users/:id/";
  8551. detail::PathParamsMatcher matcher(pattern);
  8552. Request request;
  8553. request.path = "/admins/24/";
  8554. ASSERT_FALSE(matcher.match(request));
  8555. }
  8556. TEST(PathParamsTest, ExtraFragments) {
  8557. const auto pattern = "/users/:id";
  8558. detail::PathParamsMatcher matcher(pattern);
  8559. Request request;
  8560. request.path = "/users/42/subscriptions";
  8561. ASSERT_FALSE(matcher.match(request));
  8562. }
  8563. TEST(PathParamsTest, MissingTrailingParam) {
  8564. const auto pattern = "/users/:id";
  8565. detail::PathParamsMatcher matcher(pattern);
  8566. Request request;
  8567. request.path = "/users";
  8568. ASSERT_FALSE(matcher.match(request));
  8569. }
  8570. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8571. const auto pattern = "/users/:id/subscriptions";
  8572. detail::PathParamsMatcher matcher(pattern);
  8573. Request request;
  8574. request.path = "/users/subscriptions";
  8575. ASSERT_FALSE(matcher.match(request));
  8576. }
  8577. TEST(PathParamsTest, MultipleParams) {
  8578. const auto pattern = "/users/:userid/subscriptions/:subid";
  8579. detail::PathParamsMatcher matcher(pattern);
  8580. Request request;
  8581. request.path = "/users/42/subscriptions/2";
  8582. ASSERT_TRUE(matcher.match(request));
  8583. std::unordered_map<std::string, std::string> expected_params = {
  8584. {"userid", "42"}, {"subid", "2"}};
  8585. EXPECT_EQ(request.path_params, expected_params);
  8586. }
  8587. TEST(PathParamsTest, SequenceOfParams) {
  8588. const auto pattern = "/values/:x/:y/:z";
  8589. detail::PathParamsMatcher matcher(pattern);
  8590. Request request;
  8591. request.path = "/values/1/2/3";
  8592. ASSERT_TRUE(matcher.match(request));
  8593. std::unordered_map<std::string, std::string> expected_params = {
  8594. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8595. EXPECT_EQ(request.path_params, expected_params);
  8596. }
  8597. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8598. const auto pattern = "/prefix:suffix";
  8599. detail::PathParamsMatcher matcher(pattern);
  8600. Request request;
  8601. request.path = "/prefix:suffix";
  8602. ASSERT_TRUE(matcher.match(request));
  8603. const std::unordered_map<std::string, std::string> expected_params = {};
  8604. EXPECT_EQ(request.path_params, expected_params);
  8605. }
  8606. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8607. // If ipv6 regex working, regex match codepath is taken.
  8608. // else port will default to 80 in Client impl
  8609. int clientImplMagicPort = 80;
  8610. int port = 4321;
  8611. // above ports must be different to avoid false negative
  8612. EXPECT_NE(clientImplMagicPort, port);
  8613. std::string ipV6TestURL = "http://[ff06::c3]";
  8614. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8615. CLIENT_PRIVATE_KEY_FILE);
  8616. EXPECT_EQ(cli.port(), port);
  8617. }
  8618. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8619. auto file_path = "./www/dir/index.html";
  8620. auto dir_path = "./www/dir";
  8621. detail::FileStat stat_file(file_path);
  8622. EXPECT_TRUE(stat_file.is_file());
  8623. EXPECT_FALSE(stat_file.is_dir());
  8624. detail::FileStat stat_dir(dir_path);
  8625. EXPECT_FALSE(stat_dir.is_file());
  8626. EXPECT_TRUE(stat_dir.is_dir());
  8627. }
  8628. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8629. // IPv4 with default HTTP port (80)
  8630. EXPECT_EQ("example.com",
  8631. detail::make_host_and_port_string("example.com", 80, false));
  8632. // IPv4 with default HTTPS port (443)
  8633. EXPECT_EQ("example.com",
  8634. detail::make_host_and_port_string("example.com", 443, true));
  8635. // IPv4 with non-default HTTP port
  8636. EXPECT_EQ("example.com:8080",
  8637. detail::make_host_and_port_string("example.com", 8080, false));
  8638. // IPv4 with non-default HTTPS port
  8639. EXPECT_EQ("example.com:8443",
  8640. detail::make_host_and_port_string("example.com", 8443, true));
  8641. // IPv6 with default HTTP port (80)
  8642. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8643. // IPv6 with default HTTPS port (443)
  8644. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8645. // IPv6 with non-default HTTP port
  8646. EXPECT_EQ("[::1]:8080",
  8647. detail::make_host_and_port_string("::1", 8080, false));
  8648. // IPv6 with non-default HTTPS port
  8649. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8650. // IPv6 full address with default port
  8651. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8652. detail::make_host_and_port_string(
  8653. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8654. // IPv6 full address with non-default port
  8655. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8656. detail::make_host_and_port_string(
  8657. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8658. // IPv6 localhost with non-default port
  8659. EXPECT_EQ("[::1]:3000",
  8660. detail::make_host_and_port_string("::1", 3000, false));
  8661. // IPv6 with zone ID (link-local address) with default port
  8662. EXPECT_EQ("[fe80::1%eth0]",
  8663. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8664. // IPv6 with zone ID (link-local address) with non-default port
  8665. EXPECT_EQ("[fe80::1%eth0]:8080",
  8666. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8667. // Edge case: Port 443 with is_ssl=false (should add port)
  8668. EXPECT_EQ("example.com:443",
  8669. detail::make_host_and_port_string("example.com", 443, false));
  8670. // Edge case: Port 80 with is_ssl=true (should add port)
  8671. EXPECT_EQ("example.com:80",
  8672. detail::make_host_and_port_string("example.com", 80, true));
  8673. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8674. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8675. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8676. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8677. // Security fix: Already bracketed IPv6 should not get double brackets
  8678. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8679. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8680. EXPECT_EQ("[::1]:8080",
  8681. detail::make_host_and_port_string("[::1]", 8080, false));
  8682. EXPECT_EQ("[2001:db8::1]:8080",
  8683. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8684. EXPECT_EQ("[fe80::1%eth0]",
  8685. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8686. EXPECT_EQ("[fe80::1%eth0]:8080",
  8687. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8688. // Edge case: Empty host (should return as-is)
  8689. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8690. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8691. // This is a known limitation but shouldn't crash
  8692. EXPECT_EQ("[host:name]",
  8693. detail::make_host_and_port_string("host:name", 80, false));
  8694. // Port number edge cases (no validation, but should not crash)
  8695. EXPECT_EQ("example.com:0",
  8696. detail::make_host_and_port_string("example.com", 0, false));
  8697. EXPECT_EQ("example.com:-1",
  8698. detail::make_host_and_port_string("example.com", -1, false));
  8699. EXPECT_EQ("example.com:65535",
  8700. detail::make_host_and_port_string("example.com", 65535, false));
  8701. EXPECT_EQ("example.com:65536",
  8702. detail::make_host_and_port_string("example.com", 65536, false));
  8703. }
  8704. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8705. Server svr;
  8706. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8707. EXPECT_EQ(res.status, 400);
  8708. });
  8709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8710. auto se = detail::scope_exit([&] {
  8711. svr.stop();
  8712. thread.join();
  8713. ASSERT_FALSE(svr.is_running());
  8714. });
  8715. svr.wait_until_ready();
  8716. Client cli(HOST, PORT);
  8717. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8718. }
  8719. TEST(InvalidHeaderCharsTest, is_field_name) {
  8720. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8721. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8722. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8723. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8724. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8725. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8726. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8727. EXPECT_FALSE(detail::fields::is_field_name(""));
  8728. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8729. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8730. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8731. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8732. }
  8733. TEST(InvalidHeaderCharsTest, is_field_value) {
  8734. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8735. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8736. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8737. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8738. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8739. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8740. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8741. EXPECT_TRUE(detail::fields::is_field_value(""));
  8742. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8743. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8744. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8745. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8746. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8747. }
  8748. TEST(InvalidHeaderCharsTest, OnServer) {
  8749. Server svr;
  8750. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8751. std::string header = "Not Set";
  8752. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8753. res.set_header(header, "value");
  8754. res.set_content("Page Content Page Content", "text/plain");
  8755. });
  8756. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8757. std::string header = "Not Set";
  8758. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8759. res.set_header("X-Test", header);
  8760. res.set_content("Page Content Page Content", "text/plain");
  8761. });
  8762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8763. auto se = detail::scope_exit([&] {
  8764. svr.stop();
  8765. thread.join();
  8766. ASSERT_FALSE(svr.is_running());
  8767. });
  8768. svr.wait_until_ready();
  8769. Client cli(HOST, PORT);
  8770. {
  8771. auto res = cli.Get(
  8772. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8773. ASSERT_TRUE(res);
  8774. EXPECT_EQ("Page Content Page Content", res->body);
  8775. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8776. }
  8777. {
  8778. auto res = cli.Get(
  8779. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8780. ASSERT_TRUE(res);
  8781. EXPECT_EQ("Page Content Page Content", res->body);
  8782. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8783. }
  8784. }
  8785. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8786. auto handled = false;
  8787. Server svr;
  8788. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8789. thread t = thread([&] { svr.listen(HOST, PORT); });
  8790. auto se = detail::scope_exit([&] {
  8791. svr.stop();
  8792. t.join();
  8793. ASSERT_FALSE(svr.is_running());
  8794. ASSERT_FALSE(handled);
  8795. });
  8796. svr.wait_until_ready();
  8797. auto req = "POST /test HTTP/1.1\r\n"
  8798. "Content-Length: x\r\n"
  8799. "\r\n";
  8800. std::string response;
  8801. ASSERT_TRUE(send_request(1, req, &response));
  8802. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8803. response.substr(0, response.find("\r\n")));
  8804. }
  8805. #ifndef _WIN32
  8806. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8807. static constexpr char reject[] = "Unauthorized";
  8808. static constexpr char accept[] = "Upload accepted";
  8809. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8810. Server svr;
  8811. svr.set_expect_100_continue_handler(
  8812. [](const Request & /*req*/, Response &res) {
  8813. res.status = StatusCode::Unauthorized_401;
  8814. res.set_content(reject, "text/plain");
  8815. return res.status;
  8816. });
  8817. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8818. res.set_content(accept, "text/plain");
  8819. });
  8820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8821. auto se = detail::scope_exit([&] {
  8822. svr.stop();
  8823. thread.join();
  8824. ASSERT_FALSE(svr.is_running());
  8825. });
  8826. svr.wait_until_ready();
  8827. {
  8828. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8829. curl_easy_init(), &curl_easy_cleanup};
  8830. ASSERT_NE(curl, nullptr);
  8831. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8832. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8833. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8834. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8835. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8836. &curl_slist_free_all};
  8837. ASSERT_NE(list, nullptr);
  8838. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8839. struct read_data {
  8840. size_t read_size;
  8841. size_t total_size;
  8842. } data = {0, total_size};
  8843. using read_callback_t =
  8844. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8845. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8846. void *userdata) -> size_t {
  8847. read_data *data = (read_data *)userdata;
  8848. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8849. std::fill_n(ptr, size * nmemb, 'A');
  8850. data->read_size += size * nmemb;
  8851. return size * nmemb;
  8852. };
  8853. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8854. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8855. std::vector<char> buffer;
  8856. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8857. using write_callback_t =
  8858. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8859. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8860. void *userdata) -> size_t {
  8861. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8862. buffer->reserve(buffer->size() + size * nmemb + 1);
  8863. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8864. return size * nmemb;
  8865. };
  8866. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8867. {
  8868. const auto res = curl_easy_perform(curl.get());
  8869. ASSERT_EQ(res, CURLE_OK);
  8870. }
  8871. {
  8872. auto response_code = long{};
  8873. const auto res =
  8874. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8875. ASSERT_EQ(res, CURLE_OK);
  8876. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8877. }
  8878. {
  8879. auto dl = curl_off_t{};
  8880. const auto res =
  8881. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8882. ASSERT_EQ(res, CURLE_OK);
  8883. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8884. }
  8885. {
  8886. buffer.push_back('\0');
  8887. ASSERT_STRCASEEQ(buffer.data(), reject);
  8888. }
  8889. }
  8890. }
  8891. #endif
  8892. template <typename S, typename C>
  8893. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8894. svr.Get("/stream", [&](const Request &, Response &res) {
  8895. auto data = new std::string("01234567890123456789");
  8896. res.set_content_provider(
  8897. data->size(), "text/plain",
  8898. [&, data](size_t offset, size_t length, DataSink &sink) {
  8899. const size_t DATA_CHUNK_SIZE = 4;
  8900. const auto &d = *data;
  8901. std::this_thread::sleep_for(std::chrono::seconds(1));
  8902. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8903. return true;
  8904. },
  8905. [data](bool success) {
  8906. EXPECT_FALSE(success);
  8907. delete data;
  8908. });
  8909. });
  8910. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8911. auto i = new size_t(0);
  8912. res.set_content_provider(
  8913. "text/plain",
  8914. [i](size_t, DataSink &sink) {
  8915. if (*i < 5) {
  8916. std::this_thread::sleep_for(std::chrono::seconds(1));
  8917. sink.write("abcd", 4);
  8918. (*i)++;
  8919. } else {
  8920. sink.done();
  8921. }
  8922. return true;
  8923. },
  8924. [i](bool success) {
  8925. EXPECT_FALSE(success);
  8926. delete i;
  8927. });
  8928. });
  8929. svr.Get("/chunked", [&](const Request &, Response &res) {
  8930. auto i = new size_t(0);
  8931. res.set_chunked_content_provider(
  8932. "text/plain",
  8933. [i](size_t, DataSink &sink) {
  8934. if (*i < 5) {
  8935. std::this_thread::sleep_for(std::chrono::seconds(1));
  8936. sink.os << "abcd";
  8937. (*i)++;
  8938. } else {
  8939. sink.done();
  8940. }
  8941. return true;
  8942. },
  8943. [i](bool success) {
  8944. EXPECT_FALSE(success);
  8945. delete i;
  8946. });
  8947. });
  8948. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8949. auto se = detail::scope_exit([&] {
  8950. svr.stop();
  8951. listen_thread.join();
  8952. ASSERT_FALSE(svr.is_running());
  8953. });
  8954. svr.wait_until_ready();
  8955. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8956. {
  8957. auto start = std::chrono::steady_clock::now();
  8958. auto res = cli.Get("/stream");
  8959. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8960. std::chrono::steady_clock::now() - start)
  8961. .count();
  8962. ASSERT_FALSE(res);
  8963. EXPECT_EQ(Error::Read, res.error());
  8964. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8965. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8966. }
  8967. {
  8968. auto start = std::chrono::steady_clock::now();
  8969. auto res = cli.Get("/stream_without_length");
  8970. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8971. std::chrono::steady_clock::now() - start)
  8972. .count();
  8973. ASSERT_FALSE(res);
  8974. EXPECT_EQ(Error::Read, res.error());
  8975. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8976. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8977. }
  8978. {
  8979. auto start = std::chrono::steady_clock::now();
  8980. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8981. EXPECT_EQ("abcd", string(data, data_length));
  8982. return true;
  8983. });
  8984. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8985. std::chrono::steady_clock::now() - start)
  8986. .count();
  8987. ASSERT_FALSE(res);
  8988. EXPECT_EQ(Error::Read, res.error());
  8989. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8990. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8991. }
  8992. }
  8993. TEST(MaxTimeoutTest, ContentStream) {
  8994. time_t timeout = 2000;
  8995. time_t threshold = 200;
  8996. Server svr;
  8997. Client cli("localhost", PORT);
  8998. max_timeout_test(svr, cli, timeout, threshold);
  8999. }
  9000. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9001. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9002. time_t timeout = 2000;
  9003. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9005. SSLClient cli("localhost", PORT);
  9006. cli.enable_server_certificate_verification(false);
  9007. max_timeout_test(svr, cli, timeout, threshold);
  9008. }
  9009. #endif
  9010. class EventDispatcher {
  9011. public:
  9012. EventDispatcher() {}
  9013. void wait_event(DataSink *sink) {
  9014. unique_lock<mutex> lk(m_);
  9015. int id = id_;
  9016. cv_.wait(lk, [&] { return cid_ == id; });
  9017. sink->write(message_.data(), message_.size());
  9018. }
  9019. void send_event(const string &message) {
  9020. lock_guard<mutex> lk(m_);
  9021. cid_ = id_++;
  9022. message_ = message;
  9023. cv_.notify_all();
  9024. }
  9025. private:
  9026. mutex m_;
  9027. condition_variable cv_;
  9028. atomic_int id_{0};
  9029. atomic_int cid_{-1};
  9030. string message_;
  9031. };
  9032. TEST(ClientInThreadTest, Issue2068) {
  9033. EventDispatcher ed;
  9034. Server svr;
  9035. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9036. res.set_chunked_content_provider("text/event-stream",
  9037. [&](size_t /*offset*/, DataSink &sink) {
  9038. ed.wait_event(&sink);
  9039. return true;
  9040. });
  9041. });
  9042. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9043. svr.wait_until_ready();
  9044. thread event_thread([&] {
  9045. int id = 0;
  9046. while (svr.is_running()) {
  9047. this_thread::sleep_for(chrono::milliseconds(500));
  9048. std::stringstream ss;
  9049. ss << "data: " << id << "\n\n";
  9050. ed.send_event(ss.str());
  9051. id++;
  9052. }
  9053. });
  9054. auto se = detail::scope_exit([&] {
  9055. svr.stop();
  9056. listen_thread.join();
  9057. event_thread.join();
  9058. ASSERT_FALSE(svr.is_running());
  9059. });
  9060. {
  9061. auto client = detail::make_unique<Client>(HOST, PORT);
  9062. client->set_read_timeout(std::chrono::minutes(10));
  9063. std::atomic<bool> stop{false};
  9064. std::thread t([&] {
  9065. client->Get("/event1",
  9066. [&](const char *, size_t) -> bool { return !stop; });
  9067. });
  9068. std::this_thread::sleep_for(std::chrono::seconds(2));
  9069. stop = true;
  9070. client->stop();
  9071. client.reset();
  9072. t.join();
  9073. }
  9074. }
  9075. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9076. Server svr;
  9077. svr.Get("/", [](const Request &req, Response &res) {
  9078. EXPECT_EQ(2U, req.trailers.size());
  9079. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9080. // Denied
  9081. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9082. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9083. // Accepted
  9084. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9085. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9086. EXPECT_TRUE(req.has_trailer("X-World"));
  9087. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9088. res.set_content("ok", "text/plain");
  9089. });
  9090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9091. auto se = detail::scope_exit([&] {
  9092. svr.stop();
  9093. t.join();
  9094. ASSERT_FALSE(svr.is_running());
  9095. });
  9096. svr.wait_until_ready();
  9097. const std::string req = "GET / HTTP/1.1\r\n"
  9098. "Transfer-Encoding: chunked\r\n"
  9099. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9100. "\r\n"
  9101. "0\r\n"
  9102. "Content-Length: 10\r\n"
  9103. "Host: internal.local\r\n"
  9104. "Content-Type: malicious/content\r\n"
  9105. "Cookie: any\r\n"
  9106. "Set-Cookie: any\r\n"
  9107. "X-Forwarded-For: attacker.com\r\n"
  9108. "X-Real-Ip: 1.1.1.1\r\n"
  9109. "X-Hello: hello\r\n"
  9110. "X-World: world\r\n"
  9111. "\r\n";
  9112. std::string res;
  9113. ASSERT_TRUE(send_request(1, req, &res));
  9114. }