test.cc 196 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid multipart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  136. string content_type = "multipart/form-data; boundary=something";
  137. string boundary;
  138. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  139. EXPECT_TRUE(ret);
  140. EXPECT_EQ(boundary, "something");
  141. }
  142. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  143. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  144. string boundary;
  145. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  148. }
  149. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  150. string content_type =
  151. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  152. string boundary;
  153. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  154. EXPECT_TRUE(ret);
  155. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  156. }
  157. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  158. string content_type =
  159. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  160. string boundary;
  161. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  162. EXPECT_TRUE(ret);
  163. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  164. }
  165. TEST(GetHeaderValueTest, DefaultValue) {
  166. Headers headers = {{"Dummy", "Dummy"}};
  167. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  168. EXPECT_STREQ("text/plain", val);
  169. }
  170. TEST(GetHeaderValueTest, DefaultValueInt) {
  171. Headers headers = {{"Dummy", "Dummy"}};
  172. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 100);
  173. EXPECT_EQ(100ull, val);
  174. }
  175. TEST(GetHeaderValueTest, RegularValue) {
  176. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  177. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  178. EXPECT_STREQ("text/html", val);
  179. }
  180. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  181. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  182. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  183. EXPECT_STREQ("text/html", val);
  184. }
  185. TEST(GetHeaderValueTest, SetContent) {
  186. Response res;
  187. res.set_content("html", "text/html");
  188. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  189. res.set_content("text", "text/plain");
  190. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  191. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  192. }
  193. TEST(GetHeaderValueTest, RegularValueInt) {
  194. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  195. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  196. EXPECT_EQ(100ull, val);
  197. }
  198. TEST(GetHeaderValueTest, Range) {
  199. {
  200. Headers headers = {make_range_header({{1, -1}})};
  201. auto val = detail::get_header_value(headers, "Range", 0, 0);
  202. EXPECT_STREQ("bytes=1-", val);
  203. }
  204. {
  205. Headers headers = {make_range_header({{-1, 1}})};
  206. auto val = detail::get_header_value(headers, "Range", 0, 0);
  207. EXPECT_STREQ("bytes=-1", val);
  208. }
  209. {
  210. Headers headers = {make_range_header({{1, 10}})};
  211. auto val = detail::get_header_value(headers, "Range", 0, 0);
  212. EXPECT_STREQ("bytes=1-10", val);
  213. }
  214. {
  215. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  216. auto val = detail::get_header_value(headers, "Range", 0, 0);
  217. EXPECT_STREQ("bytes=1-10, 100-", val);
  218. }
  219. {
  220. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  221. auto val = detail::get_header_value(headers, "Range", 0, 0);
  222. EXPECT_STREQ("bytes=1-10, 100-200", val);
  223. }
  224. {
  225. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  226. auto val = detail::get_header_value(headers, "Range", 0, 0);
  227. EXPECT_STREQ("bytes=0-0, -1", val);
  228. }
  229. }
  230. TEST(ParseHeaderValueTest, Range) {
  231. {
  232. Ranges ranges;
  233. auto ret = detail::parse_range_header("bytes=1-", ranges);
  234. EXPECT_TRUE(ret);
  235. EXPECT_EQ(1u, ranges.size());
  236. EXPECT_EQ(1u, ranges[0].first);
  237. EXPECT_EQ(-1, ranges[0].second);
  238. }
  239. {
  240. Ranges ranges;
  241. auto ret = detail::parse_range_header("bytes=-1", ranges);
  242. EXPECT_TRUE(ret);
  243. EXPECT_EQ(1u, ranges.size());
  244. EXPECT_EQ(-1, ranges[0].first);
  245. EXPECT_EQ(1u, ranges[0].second);
  246. }
  247. {
  248. Ranges ranges;
  249. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  250. EXPECT_TRUE(ret);
  251. EXPECT_EQ(1u, ranges.size());
  252. EXPECT_EQ(1u, ranges[0].first);
  253. EXPECT_EQ(10u, ranges[0].second);
  254. }
  255. {
  256. Ranges ranges;
  257. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  258. EXPECT_FALSE(ret);
  259. }
  260. {
  261. Ranges ranges;
  262. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  263. EXPECT_TRUE(ret);
  264. EXPECT_EQ(2u, ranges.size());
  265. EXPECT_EQ(1u, ranges[0].first);
  266. EXPECT_EQ(10u, ranges[0].second);
  267. EXPECT_EQ(100u, ranges[1].first);
  268. EXPECT_EQ(-1, ranges[1].second);
  269. }
  270. {
  271. Ranges ranges;
  272. auto ret =
  273. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  274. EXPECT_TRUE(ret);
  275. EXPECT_EQ(3u, ranges.size());
  276. EXPECT_EQ(1u, ranges[0].first);
  277. EXPECT_EQ(10u, ranges[0].second);
  278. EXPECT_EQ(100u, ranges[1].first);
  279. EXPECT_EQ(200u, ranges[1].second);
  280. EXPECT_EQ(300u, ranges[2].first);
  281. EXPECT_EQ(400u, ranges[2].second);
  282. }
  283. }
  284. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  285. Request req;
  286. req.set_header("Accept-Encoding", "gzip");
  287. Response res;
  288. res.set_header("Content-Type", "text/plain");
  289. auto ret = detail::encoding_type(req, res);
  290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  291. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  292. #else
  293. EXPECT_TRUE(ret == detail::EncodingType::None);
  294. #endif
  295. }
  296. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  297. Request req;
  298. req.set_header("Accept-Encoding", "gzip, deflate, br");
  299. Response res;
  300. res.set_header("Content-Type", "text/plain");
  301. auto ret = detail::encoding_type(req, res);
  302. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  303. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  304. #elif CPPHTTPLIB_ZLIB_SUPPORT
  305. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  306. #else
  307. EXPECT_TRUE(ret == detail::EncodingType::None);
  308. #endif
  309. }
  310. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  311. Request req;
  312. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  313. Response res;
  314. res.set_header("Content-Type", "text/plain");
  315. auto ret = detail::encoding_type(req, res);
  316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  317. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  318. #elif CPPHTTPLIB_ZLIB_SUPPORT
  319. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  320. #else
  321. EXPECT_TRUE(ret == detail::EncodingType::None);
  322. #endif
  323. }
  324. TEST(BufferStreamTest, read) {
  325. detail::BufferStream strm1;
  326. Stream &strm = strm1;
  327. EXPECT_EQ(5, strm.write("hello"));
  328. char buf[512];
  329. EXPECT_EQ(2, strm.read(buf, 2));
  330. EXPECT_EQ('h', buf[0]);
  331. EXPECT_EQ('e', buf[1]);
  332. EXPECT_EQ(2, strm.read(buf, 2));
  333. EXPECT_EQ('l', buf[0]);
  334. EXPECT_EQ('l', buf[1]);
  335. EXPECT_EQ(1, strm.read(buf, 1));
  336. EXPECT_EQ('o', buf[0]);
  337. EXPECT_EQ(0, strm.read(buf, 1));
  338. }
  339. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  340. auto host = "www.httpwatch.com";
  341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  342. auto port = 443;
  343. SSLClient cli(host, port);
  344. #else
  345. auto port = 80;
  346. Client cli(host, port);
  347. #endif
  348. cli.set_connection_timeout(2);
  349. auto res =
  350. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  351. ASSERT_TRUE(res);
  352. std::string out;
  353. detail::read_file("./image.jpg", out);
  354. EXPECT_EQ(200, res->status);
  355. EXPECT_EQ(out, res->body);
  356. }
  357. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  358. auto host = "www.httpwatch.com";
  359. auto ip = hosted_at(host);
  360. EXPECT_EQ("23.96.13.243", ip);
  361. std::vector<std::string> addrs;
  362. hosted_at(host, addrs);
  363. EXPECT_EQ(1u, addrs.size());
  364. }
  365. #if 0 // It depends on each test environment...
  366. TEST(HostnameToIPConversionTest, YouTube_Online) {
  367. auto host = "www.youtube.com";
  368. std::vector<std::string> addrs;
  369. hosted_at(host, addrs);
  370. EXPECT_EQ(20u, addrs.size());
  371. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  372. EXPECT_TRUE(it != addrs.end());
  373. }
  374. #endif
  375. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  376. auto host = "www.httpwatch.com";
  377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  378. auto port = 443;
  379. SSLClient cli(host, port);
  380. #else
  381. auto port = 80;
  382. Client cli(host, port);
  383. #endif
  384. cli.set_connection_timeout(2);
  385. std::string body;
  386. auto res =
  387. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  388. [&](const char *data, size_t data_length) {
  389. body.append(data, data_length);
  390. return true;
  391. });
  392. ASSERT_TRUE(res);
  393. std::string out;
  394. detail::read_file("./image.jpg", out);
  395. EXPECT_EQ(200, res->status);
  396. EXPECT_EQ(out, body);
  397. }
  398. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  399. auto host = "www.httpwatch.com";
  400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  401. auto port = 443;
  402. SSLClient cli(host, port);
  403. #else
  404. auto port = 80;
  405. Client cli(host, port);
  406. #endif
  407. cli.set_connection_timeout(2);
  408. std::string body;
  409. auto res = cli.Get(
  410. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  411. [&](const Response &response) {
  412. EXPECT_EQ(200, response.status);
  413. return true;
  414. },
  415. [&](const char *data, size_t data_length) {
  416. body.append(data, data_length);
  417. return true;
  418. });
  419. ASSERT_TRUE(res);
  420. std::string out;
  421. detail::read_file("./image.jpg", out);
  422. EXPECT_EQ(200, res->status);
  423. EXPECT_EQ(out, body);
  424. }
  425. TEST(RangeTest, FromHTTPBin_Online) {
  426. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  427. auto host = "httpbin.org";
  428. auto path = std::string{"/range/32"};
  429. #else
  430. auto host = "nghttp2.org";
  431. auto path = std::string{"/httpbin/range/32"};
  432. #endif
  433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  434. auto port = 443;
  435. SSLClient cli(host, port);
  436. #else
  437. auto port = 80;
  438. Client cli(host, port);
  439. #endif
  440. cli.set_connection_timeout(5);
  441. {
  442. auto res = cli.Get(path);
  443. ASSERT_TRUE(res);
  444. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  445. EXPECT_EQ(200, res->status);
  446. }
  447. {
  448. Headers headers = {make_range_header({{1, -1}})};
  449. auto res = cli.Get(path, headers);
  450. ASSERT_TRUE(res);
  451. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  452. EXPECT_EQ(206, res->status);
  453. }
  454. {
  455. Headers headers = {make_range_header({{1, 10}})};
  456. auto res = cli.Get(path, headers);
  457. ASSERT_TRUE(res);
  458. EXPECT_EQ("bcdefghijk", res->body);
  459. EXPECT_EQ(206, res->status);
  460. }
  461. {
  462. Headers headers = {make_range_header({{0, 31}})};
  463. auto res = cli.Get(path, headers);
  464. ASSERT_TRUE(res);
  465. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  466. EXPECT_EQ(200, res->status);
  467. }
  468. {
  469. Headers headers = {make_range_header({{0, -1}})};
  470. auto res = cli.Get(path, headers);
  471. ASSERT_TRUE(res);
  472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  473. EXPECT_EQ(200, res->status);
  474. }
  475. {
  476. Headers headers = {make_range_header({{0, 32}})};
  477. auto res = cli.Get(path, headers);
  478. ASSERT_TRUE(res);
  479. EXPECT_EQ(416, res->status);
  480. }
  481. }
  482. TEST(ConnectionErrorTest, InvalidHost) {
  483. auto host = "-abcde.com";
  484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  485. auto port = 443;
  486. SSLClient cli(host, port);
  487. #else
  488. auto port = 80;
  489. Client cli(host, port);
  490. #endif
  491. cli.set_connection_timeout(std::chrono::seconds(2));
  492. auto res = cli.Get("/");
  493. ASSERT_TRUE(!res);
  494. EXPECT_EQ(Error::Connection, res.error());
  495. }
  496. TEST(ConnectionErrorTest, InvalidHost2) {
  497. auto host = "httpbin.org/";
  498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  499. SSLClient cli(host);
  500. #else
  501. Client cli(host);
  502. #endif
  503. cli.set_connection_timeout(std::chrono::seconds(2));
  504. auto res = cli.Get("/");
  505. ASSERT_TRUE(!res);
  506. EXPECT_EQ(Error::Connection, res.error());
  507. }
  508. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  509. auto host = "httpbin.org/";
  510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  511. SSLClient cli(host);
  512. #else
  513. Client cli(host);
  514. #endif
  515. cli.set_connection_timeout(std::chrono::seconds(2));
  516. auto res = cli.Get("/");
  517. ASSERT_TRUE(!res);
  518. stringstream s;
  519. s << "error code: " << res.error();
  520. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  521. }
  522. TEST(ConnectionErrorTest, InvalidPort) {
  523. auto host = "localhost";
  524. auto port = 44380;
  525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  526. SSLClient cli(host, port);
  527. #else
  528. Client cli(host, port);
  529. #endif
  530. cli.set_connection_timeout(std::chrono::seconds(2));
  531. auto res = cli.Get("/");
  532. ASSERT_TRUE(!res);
  533. EXPECT_TRUE(Error::Connection == res.error() ||
  534. Error::ConnectionTimeout == res.error());
  535. }
  536. TEST(ConnectionErrorTest, Timeout_Online) {
  537. auto host = "google.com";
  538. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  539. auto port = 44380;
  540. SSLClient cli(host, port);
  541. #else
  542. auto port = 8080;
  543. Client cli(host, port);
  544. #endif
  545. cli.set_connection_timeout(std::chrono::seconds(2));
  546. // only probe one address type so that the error reason
  547. // correlates to the timed-out IPv4, not the unsupported
  548. // IPv6 connection attempt
  549. cli.set_address_family(AF_INET);
  550. auto res = cli.Get("/");
  551. ASSERT_TRUE(!res);
  552. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  553. }
  554. TEST(CancelTest, NoCancel_Online) {
  555. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  556. auto host = "httpbin.org";
  557. auto path = std::string{"/range/32"};
  558. #else
  559. auto host = "nghttp2.org";
  560. auto path = std::string{"/httpbin/range/32"};
  561. #endif
  562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  563. auto port = 443;
  564. SSLClient cli(host, port);
  565. #else
  566. auto port = 80;
  567. Client cli(host, port);
  568. #endif
  569. cli.set_connection_timeout(std::chrono::seconds(5));
  570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  571. ASSERT_TRUE(res);
  572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  573. EXPECT_EQ(200, res->status);
  574. }
  575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  576. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  577. auto host = "httpbin.org";
  578. auto path = std::string{"/range/32"};
  579. #else
  580. auto host = "nghttp2.org";
  581. auto path = std::string{"/httpbin/range/32"};
  582. #endif
  583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  584. auto port = 443;
  585. SSLClient cli(host, port);
  586. #else
  587. auto port = 80;
  588. Client cli(host, port);
  589. #endif
  590. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  591. cli.set_connection_timeout(std::chrono::seconds(5));
  592. ASSERT_TRUE(!res);
  593. EXPECT_EQ(Error::Canceled, res.error());
  594. }
  595. TEST(CancelTest, WithCancelLargePayload_Online) {
  596. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  597. auto host = "httpbin.org";
  598. auto path = std::string{"/range/65536"};
  599. #else
  600. auto host = "nghttp2.org";
  601. auto path = std::string{"/httpbin/range/65536"};
  602. #endif
  603. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  604. auto port = 443;
  605. SSLClient cli(host, port);
  606. #else
  607. auto port = 80;
  608. Client cli(host, port);
  609. #endif
  610. cli.set_connection_timeout(std::chrono::seconds(5));
  611. uint32_t count = 0;
  612. auto res =
  613. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  614. ASSERT_TRUE(!res);
  615. EXPECT_EQ(Error::Canceled, res.error());
  616. }
  617. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  618. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  619. auto host = "httpbin.org";
  620. auto path = std::string{"/basic-auth/hello/world"};
  621. #else
  622. auto host = "nghttp2.org";
  623. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  624. #endif
  625. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  626. auto port = 443;
  627. SSLClient cli(host, port);
  628. #else
  629. auto port = 80;
  630. Client cli(host, port);
  631. #endif
  632. {
  633. auto res = cli.Get(path);
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(401, res->status);
  636. }
  637. {
  638. auto res =
  639. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  640. ASSERT_TRUE(res);
  641. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  642. res->body);
  643. EXPECT_EQ(200, res->status);
  644. }
  645. {
  646. cli.set_basic_auth("hello", "world");
  647. auto res = cli.Get(path);
  648. ASSERT_TRUE(res);
  649. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  650. res->body);
  651. EXPECT_EQ(200, res->status);
  652. }
  653. {
  654. cli.set_basic_auth("hello", "bad");
  655. auto res = cli.Get(path);
  656. ASSERT_TRUE(res);
  657. EXPECT_EQ(401, res->status);
  658. }
  659. {
  660. cli.set_basic_auth("bad", "world");
  661. auto res = cli.Get(path);
  662. ASSERT_TRUE(res);
  663. EXPECT_EQ(401, res->status);
  664. }
  665. }
  666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  667. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  669. auto host = "httpbin.org";
  670. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  671. auto paths = std::vector<std::string>{
  672. "/digest-auth/auth/hello/world/MD5",
  673. "/digest-auth/auth/hello/world/SHA-256",
  674. "/digest-auth/auth/hello/world/SHA-512",
  675. "/digest-auth/auth-int/hello/world/MD5",
  676. };
  677. #else
  678. auto host = "nghttp2.org";
  679. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  680. auto paths = std::vector<std::string>{
  681. "/httpbin/digest-auth/auth/hello/world/MD5",
  682. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  683. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  684. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  685. };
  686. #endif
  687. auto port = 443;
  688. SSLClient cli(host, port);
  689. {
  690. auto res = cli.Get(unauth_path);
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(401, res->status);
  693. }
  694. {
  695. cli.set_digest_auth("hello", "world");
  696. for (const auto &path : paths) {
  697. auto res = cli.Get(path.c_str());
  698. ASSERT_TRUE(res);
  699. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  700. res->body);
  701. EXPECT_EQ(200, res->status);
  702. }
  703. cli.set_digest_auth("hello", "bad");
  704. for (const auto &path : paths) {
  705. auto res = cli.Get(path.c_str());
  706. ASSERT_TRUE(res);
  707. EXPECT_EQ(401, res->status);
  708. }
  709. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  710. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  711. // cli.set_digest_auth("bad", "world");
  712. // for (const auto& path : paths) {
  713. // auto res = cli.Get(path.c_str());
  714. // ASSERT_TRUE(res);
  715. // EXPECT_EQ(400, res->status);
  716. // }
  717. }
  718. }
  719. #endif
  720. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  721. auto host = "google.com";
  722. auto another_host = "example.com";
  723. auto wrong_ip = "0.0.0.0";
  724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  725. SSLClient cli(host);
  726. #else
  727. Client cli(host);
  728. #endif
  729. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  730. auto res = cli.Get("/");
  731. ASSERT_TRUE(res);
  732. ASSERT_EQ(301, res->status);
  733. }
  734. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  735. auto host = "google.com";
  736. auto wrong_ip = "0.0.0.0";
  737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  738. SSLClient cli(host);
  739. #else
  740. Client cli(host);
  741. #endif
  742. cli.set_hostname_addr_map({{host, wrong_ip}});
  743. auto res = cli.Get("/");
  744. ASSERT_TRUE(!res);
  745. EXPECT_EQ(Error::Connection, res.error());
  746. }
  747. TEST(AbsoluteRedirectTest, Redirect_Online) {
  748. auto host = "nghttp2.org";
  749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  750. SSLClient cli(host);
  751. #else
  752. Client cli(host);
  753. #endif
  754. cli.set_follow_location(true);
  755. auto res = cli.Get("/httpbin/absolute-redirect/3");
  756. ASSERT_TRUE(res);
  757. EXPECT_EQ(200, res->status);
  758. }
  759. TEST(RedirectTest, Redirect_Online) {
  760. auto host = "nghttp2.org";
  761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  762. SSLClient cli(host);
  763. #else
  764. Client cli(host);
  765. #endif
  766. cli.set_follow_location(true);
  767. auto res = cli.Get("/httpbin/redirect/3");
  768. ASSERT_TRUE(res);
  769. EXPECT_EQ(200, res->status);
  770. }
  771. TEST(RelativeRedirectTest, Redirect_Online) {
  772. auto host = "nghttp2.org";
  773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  774. SSLClient cli(host);
  775. #else
  776. Client cli(host);
  777. #endif
  778. cli.set_follow_location(true);
  779. auto res = cli.Get("/httpbin/relative-redirect/3");
  780. ASSERT_TRUE(res);
  781. EXPECT_EQ(200, res->status);
  782. }
  783. TEST(TooManyRedirectTest, Redirect_Online) {
  784. auto host = "nghttp2.org";
  785. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  786. SSLClient cli(host);
  787. #else
  788. Client cli(host);
  789. #endif
  790. cli.set_follow_location(true);
  791. auto res = cli.Get("/httpbin/redirect/21");
  792. ASSERT_TRUE(!res);
  793. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  794. }
  795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  796. TEST(YahooRedirectTest, Redirect_Online) {
  797. Client cli("yahoo.com");
  798. auto res = cli.Get("/");
  799. ASSERT_TRUE(res);
  800. EXPECT_EQ(301, res->status);
  801. cli.set_follow_location(true);
  802. res = cli.Get("/");
  803. ASSERT_TRUE(res);
  804. EXPECT_EQ(200, res->status);
  805. EXPECT_EQ("https://www.yahoo.com/", res->location);
  806. }
  807. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  808. SSLClient cli("nghttp2.org");
  809. cli.set_follow_location(true);
  810. auto res = cli.Get(
  811. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  812. ASSERT_TRUE(res);
  813. EXPECT_EQ(200, res->status);
  814. }
  815. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  816. SSLClient cli("nghttp2.org");
  817. cli.set_follow_location(true);
  818. Params params;
  819. params.emplace("url", "http://www.google.com");
  820. params.emplace("status_code", "302");
  821. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  822. ASSERT_TRUE(res);
  823. EXPECT_EQ(200, res->status);
  824. }
  825. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  826. SSLClient cli("nghttp2.org");
  827. cli.set_follow_location(true);
  828. Params params;
  829. params.emplace("url", "http://www.google.com");
  830. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  831. ASSERT_TRUE(res);
  832. EXPECT_EQ(200, res->status);
  833. }
  834. TEST(UrlWithSpace, Redirect_Online) {
  835. SSLClient cli("edge.forgecdn.net");
  836. cli.set_follow_location(true);
  837. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  838. ASSERT_TRUE(res);
  839. EXPECT_EQ(200, res->status);
  840. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  841. }
  842. #endif
  843. #if !defined(_WIN32) && !defined(_WIN64)
  844. TEST(ReceiveSignals, Signal) {
  845. auto setupSignalHandlers = []() {
  846. struct sigaction act;
  847. sigemptyset(&act.sa_mask);
  848. act.sa_flags = SA_SIGINFO;
  849. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  850. switch (sig) {
  851. case SIGINT:
  852. default: break;
  853. }
  854. };
  855. ::sigaction(SIGINT, &act, nullptr);
  856. };
  857. Server svr;
  858. int port = 0;
  859. auto thread = std::thread([&]() {
  860. setupSignalHandlers();
  861. port = svr.bind_to_any_port("localhost");
  862. svr.listen_after_bind();
  863. });
  864. auto se = detail::scope_exit([&] {
  865. svr.stop();
  866. thread.join();
  867. ASSERT_FALSE(svr.is_running());
  868. });
  869. svr.wait_until_ready();
  870. ASSERT_TRUE(svr.is_running());
  871. pthread_kill(thread.native_handle(), SIGINT);
  872. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  873. ASSERT_TRUE(svr.is_running());
  874. }
  875. #endif
  876. TEST(RedirectToDifferentPort, Redirect) {
  877. Server svr1;
  878. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  879. res.set_content("Hello World!", "text/plain");
  880. });
  881. int svr1_port = 0;
  882. auto thread1 = std::thread([&]() {
  883. svr1_port = svr1.bind_to_any_port("localhost");
  884. svr1.listen_after_bind();
  885. });
  886. Server svr2;
  887. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  888. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  889. });
  890. int svr2_port = 0;
  891. auto thread2 = std::thread([&]() {
  892. svr2_port = svr2.bind_to_any_port("localhost");
  893. svr2.listen_after_bind();
  894. });
  895. auto se = detail::scope_exit([&] {
  896. svr2.stop();
  897. thread2.join();
  898. svr1.stop();
  899. thread1.join();
  900. ASSERT_FALSE(svr2.is_running());
  901. ASSERT_FALSE(svr1.is_running());
  902. });
  903. svr1.wait_until_ready();
  904. svr2.wait_until_ready();
  905. Client cli("localhost", svr2_port);
  906. cli.set_follow_location(true);
  907. auto res = cli.Get("/2");
  908. ASSERT_TRUE(res);
  909. EXPECT_EQ(200, res->status);
  910. EXPECT_EQ("Hello World!", res->body);
  911. }
  912. TEST(RedirectFromPageWithContent, Redirect) {
  913. Server svr;
  914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  915. res.set_content("___", "text/plain");
  916. res.set_redirect("/2");
  917. });
  918. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  919. res.set_content("Hello World!", "text/plain");
  920. });
  921. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  922. auto se = detail::scope_exit([&] {
  923. svr.stop();
  924. th.join();
  925. ASSERT_FALSE(svr.is_running());
  926. });
  927. svr.wait_until_ready();
  928. {
  929. Client cli("localhost", PORT);
  930. cli.set_follow_location(true);
  931. std::string body;
  932. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  933. body.append(data, data_length);
  934. return true;
  935. });
  936. ASSERT_TRUE(res);
  937. EXPECT_EQ(200, res->status);
  938. EXPECT_EQ("Hello World!", body);
  939. }
  940. {
  941. Client cli("localhost", PORT);
  942. std::string body;
  943. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  944. body.append(data, data_length);
  945. return true;
  946. });
  947. ASSERT_TRUE(res);
  948. EXPECT_EQ(302, res->status);
  949. EXPECT_EQ("___", body);
  950. }
  951. }
  952. TEST(RedirectFromPageWithContentIP6, Redirect) {
  953. Server svr;
  954. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  955. res.set_content("___", "text/plain");
  956. // res.set_redirect("/2");
  957. res.set_redirect("http://[::1]:1234/2");
  958. });
  959. svr.Get("/2", [&](const Request &req, Response &res) {
  960. auto host_header = req.headers.find("Host");
  961. ASSERT_TRUE(host_header != req.headers.end());
  962. EXPECT_EQ("[::1]:1234", host_header->second);
  963. res.set_content("Hello World!", "text/plain");
  964. });
  965. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  966. auto se = detail::scope_exit([&] {
  967. svr.stop();
  968. th.join();
  969. ASSERT_FALSE(svr.is_running());
  970. });
  971. // When IPV6 support isn't available svr.listen("::1", 1234) never
  972. // actually starts anything, so the condition !svr.is_running() will
  973. // always remain true, and the loop never stops.
  974. // This basically counts how many milliseconds have passed since the
  975. // call to svr.listen(), and if after 5 seconds nothing started yet
  976. // aborts the test.
  977. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  978. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  979. ASSERT_LT(milliseconds, 5000U);
  980. }
  981. {
  982. Client cli("http://[::1]:1234");
  983. cli.set_follow_location(true);
  984. std::string body;
  985. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  986. body.append(data, data_length);
  987. return true;
  988. });
  989. ASSERT_TRUE(res);
  990. EXPECT_EQ(200, res->status);
  991. EXPECT_EQ("Hello World!", body);
  992. }
  993. {
  994. Client cli("http://[::1]:1234");
  995. std::string body;
  996. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  997. body.append(data, data_length);
  998. return true;
  999. });
  1000. ASSERT_TRUE(res);
  1001. EXPECT_EQ(302, res->status);
  1002. EXPECT_EQ("___", body);
  1003. }
  1004. }
  1005. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1006. Server svr;
  1007. svr.Get("/foo", [](const Request &req, Response &res) {
  1008. auto a = req.params.find("a");
  1009. if (a != req.params.end()) {
  1010. res.set_content((*a).second, "text/plain");
  1011. res.status = 200;
  1012. } else {
  1013. res.status = 400;
  1014. }
  1015. });
  1016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1017. auto se = detail::scope_exit([&] {
  1018. svr.stop();
  1019. thread.join();
  1020. ASSERT_FALSE(svr.is_running());
  1021. });
  1022. svr.wait_until_ready();
  1023. {
  1024. Client cli(HOST, PORT);
  1025. cli.set_url_encode(false);
  1026. auto res = cli.Get("/foo?a=explicitly+encoded");
  1027. ASSERT_TRUE(res);
  1028. EXPECT_EQ(200, res->status);
  1029. // This expects it back with a space, as the `+` won't have been
  1030. // url-encoded, and server-side the params get decoded turning `+`
  1031. // into spaces.
  1032. EXPECT_EQ("explicitly encoded", res->body);
  1033. }
  1034. }
  1035. TEST(BindServerTest, DISABLED_BindDualStack) {
  1036. Server svr;
  1037. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1038. res.set_content("Hello World!", "text/plain");
  1039. });
  1040. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1041. auto se = detail::scope_exit([&] {
  1042. svr.stop();
  1043. thread.join();
  1044. ASSERT_FALSE(svr.is_running());
  1045. });
  1046. svr.wait_until_ready();
  1047. {
  1048. Client cli("127.0.0.1", PORT);
  1049. auto res = cli.Get("/1");
  1050. ASSERT_TRUE(res);
  1051. EXPECT_EQ(200, res->status);
  1052. EXPECT_EQ("Hello World!", res->body);
  1053. }
  1054. {
  1055. Client cli("::1", PORT);
  1056. auto res = cli.Get("/1");
  1057. ASSERT_TRUE(res);
  1058. EXPECT_EQ(200, res->status);
  1059. EXPECT_EQ("Hello World!", res->body);
  1060. }
  1061. }
  1062. TEST(BindServerTest, BindAndListenSeparately) {
  1063. Server svr;
  1064. int port = svr.bind_to_any_port("0.0.0.0");
  1065. ASSERT_TRUE(svr.is_valid());
  1066. ASSERT_TRUE(port > 0);
  1067. svr.stop();
  1068. }
  1069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1070. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1072. CLIENT_CA_CERT_DIR);
  1073. int port = svr.bind_to_any_port("0.0.0.0");
  1074. ASSERT_TRUE(svr.is_valid());
  1075. ASSERT_TRUE(port > 0);
  1076. svr.stop();
  1077. }
  1078. #endif
  1079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1080. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1081. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1082. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1083. int port = svr.bind_to_any_port("0.0.0.0");
  1084. ASSERT_TRUE(svr.is_valid());
  1085. ASSERT_TRUE(port > 0);
  1086. svr.stop();
  1087. }
  1088. #endif
  1089. TEST(ErrorHandlerTest, ContentLength) {
  1090. Server svr;
  1091. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1092. res.status = 200;
  1093. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1094. "text/html"); // <= Content-Length still 13
  1095. });
  1096. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1097. res.set_content("Hello World!\n", "text/plain");
  1098. res.status = 524;
  1099. });
  1100. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. thread.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. {
  1108. Client cli(HOST, PORT);
  1109. auto res = cli.Get("/hi");
  1110. ASSERT_TRUE(res);
  1111. EXPECT_EQ(200, res->status);
  1112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1113. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1114. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1115. }
  1116. }
  1117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1118. TEST(ExceptionHandlerTest, ContentLength) {
  1119. Server svr;
  1120. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1121. std::exception_ptr ep) {
  1122. EXPECT_FALSE(ep == nullptr);
  1123. try {
  1124. std::rethrow_exception(ep);
  1125. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1126. res.status = 500;
  1127. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1128. "text/html"); // <= Content-Length still 13 at this point
  1129. });
  1130. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1131. res.set_content("Hello World!\n", "text/plain");
  1132. throw std::runtime_error("abc");
  1133. });
  1134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1135. auto se = detail::scope_exit([&] {
  1136. svr.stop();
  1137. thread.join();
  1138. ASSERT_FALSE(svr.is_running());
  1139. });
  1140. svr.wait_until_ready();
  1141. for (size_t i = 0; i < 10; i++) {
  1142. Client cli(HOST, PORT);
  1143. for (size_t j = 0; j < 100; j++) {
  1144. auto res = cli.Get("/hi");
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ(500, res->status);
  1147. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1148. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1149. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1150. }
  1151. cli.set_keep_alive(true);
  1152. for (size_t j = 0; j < 100; j++) {
  1153. auto res = cli.Get("/hi");
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ(500, res->status);
  1156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1157. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1159. }
  1160. }
  1161. }
  1162. #endif
  1163. TEST(NoContentTest, ContentLength) {
  1164. Server svr;
  1165. svr.Get("/hi",
  1166. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1168. auto se = detail::scope_exit([&] {
  1169. svr.stop();
  1170. thread.join();
  1171. ASSERT_FALSE(svr.is_running());
  1172. });
  1173. svr.wait_until_ready();
  1174. {
  1175. Client cli(HOST, PORT);
  1176. auto res = cli.Get("/hi");
  1177. ASSERT_TRUE(res);
  1178. EXPECT_EQ(204, res->status);
  1179. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1180. }
  1181. }
  1182. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1185. ASSERT_TRUE(svr.is_valid());
  1186. #else
  1187. Server svr;
  1188. #endif
  1189. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1190. if (req.path == "/routing_handler") {
  1191. res.set_header("PRE_ROUTING", "on");
  1192. res.set_content("Routing Handler", "text/plain");
  1193. return httplib::Server::HandlerResponse::Handled;
  1194. }
  1195. return httplib::Server::HandlerResponse::Unhandled;
  1196. });
  1197. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1198. res.set_content("Error", "text/html");
  1199. });
  1200. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1201. if (req.path == "/routing_handler") {
  1202. res.set_header("POST_ROUTING", "on");
  1203. }
  1204. });
  1205. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1206. res.set_content("Hello World!\n", "text/plain");
  1207. });
  1208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. thread.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. {
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. SSLClient cli(HOST, PORT);
  1218. cli.enable_server_certificate_verification(false);
  1219. #else
  1220. Client cli(HOST, PORT);
  1221. #endif
  1222. auto res = cli.Get("/routing_handler");
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ(200, res->status);
  1225. EXPECT_EQ("Routing Handler", res->body);
  1226. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1227. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1228. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1229. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1230. }
  1231. {
  1232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1233. SSLClient cli(HOST, PORT);
  1234. cli.enable_server_certificate_verification(false);
  1235. #else
  1236. Client cli(HOST, PORT);
  1237. #endif
  1238. auto res = cli.Get("/hi");
  1239. ASSERT_TRUE(res);
  1240. EXPECT_EQ(200, res->status);
  1241. EXPECT_EQ("Hello World!\n", res->body);
  1242. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1243. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1244. }
  1245. {
  1246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1247. SSLClient cli(HOST, PORT);
  1248. cli.enable_server_certificate_verification(false);
  1249. #else
  1250. Client cli(HOST, PORT);
  1251. #endif
  1252. auto res = cli.Get("/aaa");
  1253. ASSERT_TRUE(res);
  1254. EXPECT_EQ(404, res->status);
  1255. EXPECT_EQ("Error", res->body);
  1256. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1257. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1258. }
  1259. }
  1260. TEST(InvalidFormatTest, StatusCode) {
  1261. Server svr;
  1262. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1263. res.set_content("Hello World!\n", "text/plain");
  1264. res.status = 9999; // Status should be a three-digit code...
  1265. });
  1266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1267. auto se = detail::scope_exit([&] {
  1268. svr.stop();
  1269. thread.join();
  1270. ASSERT_FALSE(svr.is_running());
  1271. });
  1272. svr.wait_until_ready();
  1273. {
  1274. Client cli(HOST, PORT);
  1275. auto res = cli.Get("/hi");
  1276. ASSERT_FALSE(res);
  1277. }
  1278. }
  1279. TEST(URLFragmentTest, WithFragment) {
  1280. Server svr;
  1281. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1282. EXPECT_TRUE(req.target == "/hi");
  1283. });
  1284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1285. auto se = detail::scope_exit([&] {
  1286. svr.stop();
  1287. thread.join();
  1288. ASSERT_FALSE(svr.is_running());
  1289. });
  1290. svr.wait_until_ready();
  1291. {
  1292. Client cli(HOST, PORT);
  1293. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1294. EXPECT_TRUE(res);
  1295. EXPECT_EQ(200, res->status);
  1296. res = cli.Get("/hi%23key1=val1=key2=val2");
  1297. EXPECT_TRUE(res);
  1298. EXPECT_EQ(404, res->status);
  1299. }
  1300. }
  1301. TEST(HeaderWriter, SetHeaderWriter) {
  1302. Server svr;
  1303. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1304. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1305. return detail::write_headers(strm, hdrs);
  1306. });
  1307. svr.Get("/hi", [](const Request &req, Response &res) {
  1308. auto it = req.headers.find("CustomClientHeader");
  1309. EXPECT_TRUE(it != req.headers.end());
  1310. EXPECT_EQ(it->second, "CustomClientValue");
  1311. res.set_content("Hello World!\n", "text/plain");
  1312. });
  1313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1314. auto se = detail::scope_exit([&] {
  1315. svr.stop();
  1316. thread.join();
  1317. ASSERT_FALSE(svr.is_running());
  1318. });
  1319. svr.wait_until_ready();
  1320. {
  1321. Client cli(HOST, PORT);
  1322. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1323. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1324. return detail::write_headers(strm, hdrs);
  1325. });
  1326. auto res = cli.Get("/hi");
  1327. EXPECT_TRUE(res);
  1328. EXPECT_EQ(200, res->status);
  1329. auto it = res->headers.find("CustomServerHeader");
  1330. EXPECT_TRUE(it != res->headers.end());
  1331. EXPECT_EQ(it->second, "CustomServerValue");
  1332. }
  1333. }
  1334. class ServerTest : public ::testing::Test {
  1335. protected:
  1336. ServerTest()
  1337. : cli_(HOST, PORT)
  1338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1339. ,
  1340. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1341. #endif
  1342. {
  1343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1344. cli_.enable_server_certificate_verification(false);
  1345. #endif
  1346. }
  1347. virtual void SetUp() {
  1348. svr_.set_mount_point("/", "./www");
  1349. svr_.set_mount_point("/mount", "./www2");
  1350. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1351. svr_.Get("/hi",
  1352. [&](const Request & /*req*/, Response &res) {
  1353. res.set_content("Hello World!", "text/plain");
  1354. })
  1355. .Get("/http_response_splitting",
  1356. [&](const Request & /*req*/, Response &res) {
  1357. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1358. EXPECT_EQ(0U, res.headers.size());
  1359. EXPECT_FALSE(res.has_header("a"));
  1360. res.set_header("a", "1\nSet-Cookie: a=1");
  1361. EXPECT_EQ(0U, res.headers.size());
  1362. EXPECT_FALSE(res.has_header("a"));
  1363. res.set_header("a", "1\rSet-Cookie: a=1");
  1364. EXPECT_EQ(0U, res.headers.size());
  1365. EXPECT_FALSE(res.has_header("a"));
  1366. res.set_header("a\r\nb", "0");
  1367. EXPECT_EQ(0U, res.headers.size());
  1368. EXPECT_FALSE(res.has_header("a"));
  1369. res.set_header("a\rb", "0");
  1370. EXPECT_EQ(0U, res.headers.size());
  1371. EXPECT_FALSE(res.has_header("a"));
  1372. res.set_header("a\nb", "0");
  1373. EXPECT_EQ(0U, res.headers.size());
  1374. EXPECT_FALSE(res.has_header("a"));
  1375. res.set_redirect("1\r\nSet-Cookie: a=1");
  1376. EXPECT_EQ(0U, res.headers.size());
  1377. EXPECT_FALSE(res.has_header("Location"));
  1378. })
  1379. .Get("/slow",
  1380. [&](const Request & /*req*/, Response &res) {
  1381. std::this_thread::sleep_for(std::chrono::seconds(2));
  1382. res.set_content("slow", "text/plain");
  1383. })
  1384. #if 0
  1385. .Post("/slowpost",
  1386. [&](const Request & /*req*/, Response &res) {
  1387. std::this_thread::sleep_for(std::chrono::seconds(2));
  1388. res.set_content("slow", "text/plain");
  1389. })
  1390. #endif
  1391. .Get("/remote_addr",
  1392. [&](const Request &req, Response &res) {
  1393. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1394. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1395. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1396. EXPECT_EQ(req.remote_port,
  1397. std::stoi(req.get_header_value("REMOTE_PORT")));
  1398. res.set_content(remote_addr.c_str(), "text/plain");
  1399. })
  1400. .Get("/local_addr",
  1401. [&](const Request &req, Response &res) {
  1402. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1403. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1404. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1405. auto local_port = req.get_header_value("LOCAL_PORT");
  1406. EXPECT_EQ(req.local_addr, local_addr);
  1407. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1408. res.set_content(local_addr.append(":").append(local_port),
  1409. "text/plain");
  1410. })
  1411. .Get("/endwith%",
  1412. [&](const Request & /*req*/, Response &res) {
  1413. res.set_content("Hello World!", "text/plain");
  1414. })
  1415. .Get("/a\\+\\+b",
  1416. [&](const Request &req, Response &res) {
  1417. ASSERT_TRUE(req.has_param("a +b"));
  1418. auto val = req.get_param_value("a +b");
  1419. res.set_content(val, "text/plain");
  1420. })
  1421. .Get("/", [&](const Request & /*req*/,
  1422. Response &res) { res.set_redirect("/hi"); })
  1423. .Post("/1", [](const Request & /*req*/,
  1424. Response &res) { res.set_redirect("/2", 303); })
  1425. .Get("/2",
  1426. [](const Request & /*req*/, Response &res) {
  1427. res.set_content("redirected.", "text/plain");
  1428. res.status = 200;
  1429. })
  1430. .Post("/person",
  1431. [&](const Request &req, Response &res) {
  1432. if (req.has_param("name") && req.has_param("note")) {
  1433. persons_[req.get_param_value("name")] =
  1434. req.get_param_value("note");
  1435. } else {
  1436. res.status = 400;
  1437. }
  1438. })
  1439. .Put("/person",
  1440. [&](const Request &req, Response &res) {
  1441. if (req.has_param("name") && req.has_param("note")) {
  1442. persons_[req.get_param_value("name")] =
  1443. req.get_param_value("note");
  1444. } else {
  1445. res.status = 400;
  1446. }
  1447. })
  1448. .Get("/person/(.*)",
  1449. [&](const Request &req, Response &res) {
  1450. string name = req.matches[1];
  1451. if (persons_.find(name) != persons_.end()) {
  1452. auto note = persons_[name];
  1453. res.set_content(note, "text/plain");
  1454. } else {
  1455. res.status = 404;
  1456. }
  1457. })
  1458. .Post("/x-www-form-urlencoded-json",
  1459. [&](const Request &req, Response &res) {
  1460. auto json = req.get_param_value("json");
  1461. ASSERT_EQ(JSON_DATA, json);
  1462. res.set_content(json, "appliation/json");
  1463. res.status = 200;
  1464. })
  1465. .Get("/streamed-chunked",
  1466. [&](const Request & /*req*/, Response &res) {
  1467. res.set_chunked_content_provider(
  1468. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1469. sink.os << "123";
  1470. sink.os << "456";
  1471. sink.os << "789";
  1472. sink.done();
  1473. return true;
  1474. });
  1475. })
  1476. .Get("/streamed-chunked2",
  1477. [&](const Request & /*req*/, Response &res) {
  1478. auto i = new int(0);
  1479. res.set_chunked_content_provider(
  1480. "text/plain",
  1481. [i](size_t /*offset*/, DataSink &sink) {
  1482. switch (*i) {
  1483. case 0: sink.os << "123"; break;
  1484. case 1: sink.os << "456"; break;
  1485. case 2: sink.os << "789"; break;
  1486. case 3: sink.done(); break;
  1487. }
  1488. (*i)++;
  1489. return true;
  1490. },
  1491. [i](bool success) {
  1492. EXPECT_TRUE(success);
  1493. delete i;
  1494. });
  1495. })
  1496. .Get("/streamed-chunked-with-trailer",
  1497. [&](const Request & /*req*/, Response &res) {
  1498. auto i = new int(0);
  1499. res.set_header("Trailer", "Dummy1, Dummy2");
  1500. res.set_chunked_content_provider(
  1501. "text/plain",
  1502. [i](size_t /*offset*/, DataSink &sink) {
  1503. switch (*i) {
  1504. case 0: sink.os << "123"; break;
  1505. case 1: sink.os << "456"; break;
  1506. case 2: sink.os << "789"; break;
  1507. case 3: {
  1508. sink.done_with_trailer(
  1509. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  1510. } break;
  1511. }
  1512. (*i)++;
  1513. return true;
  1514. },
  1515. [i](bool success) {
  1516. EXPECT_TRUE(success);
  1517. delete i;
  1518. });
  1519. })
  1520. .Get("/streamed",
  1521. [&](const Request & /*req*/, Response &res) {
  1522. res.set_content_provider(
  1523. 6, "text/plain",
  1524. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1525. sink.os << (offset < 3 ? "a" : "b");
  1526. return true;
  1527. });
  1528. })
  1529. .Get("/streamed-with-range",
  1530. [&](const Request & /*req*/, Response &res) {
  1531. auto data = new std::string("abcdefg");
  1532. res.set_content_provider(
  1533. data->size(), "text/plain",
  1534. [data](size_t offset, size_t length, DataSink &sink) {
  1535. size_t DATA_CHUNK_SIZE = 4;
  1536. const auto &d = *data;
  1537. auto out_len =
  1538. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1539. auto ret =
  1540. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1541. EXPECT_TRUE(ret);
  1542. return true;
  1543. },
  1544. [data](bool success) {
  1545. EXPECT_TRUE(success);
  1546. delete data;
  1547. });
  1548. })
  1549. .Get("/streamed-cancel",
  1550. [&](const Request & /*req*/, Response &res) {
  1551. res.set_content_provider(
  1552. size_t(-1), "text/plain",
  1553. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1554. sink.os << "data_chunk";
  1555. return true;
  1556. });
  1557. })
  1558. .Get("/with-range",
  1559. [&](const Request & /*req*/, Response &res) {
  1560. res.set_content("abcdefg", "text/plain");
  1561. })
  1562. .Post("/chunked",
  1563. [&](const Request &req, Response & /*res*/) {
  1564. EXPECT_EQ(req.body, "dechunked post body");
  1565. })
  1566. .Post("/large-chunked",
  1567. [&](const Request &req, Response & /*res*/) {
  1568. std::string expected(6 * 30 * 1024u, 'a');
  1569. EXPECT_EQ(req.body, expected);
  1570. })
  1571. .Post("/multipart",
  1572. [&](const Request &req, Response & /*res*/) {
  1573. EXPECT_EQ(6u, req.files.size());
  1574. ASSERT_TRUE(!req.has_file("???"));
  1575. ASSERT_TRUE(req.body.empty());
  1576. {
  1577. const auto &file = req.get_file_value("text1");
  1578. EXPECT_TRUE(file.filename.empty());
  1579. EXPECT_EQ("text default", file.content);
  1580. }
  1581. {
  1582. const auto &file = req.get_file_value("text2");
  1583. EXPECT_TRUE(file.filename.empty());
  1584. EXPECT_EQ("aωb", file.content);
  1585. }
  1586. {
  1587. const auto &file = req.get_file_value("file1");
  1588. EXPECT_EQ("hello.txt", file.filename);
  1589. EXPECT_EQ("text/plain", file.content_type);
  1590. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1591. }
  1592. {
  1593. const auto &file = req.get_file_value("file3");
  1594. EXPECT_TRUE(file.filename.empty());
  1595. EXPECT_EQ("application/octet-stream", file.content_type);
  1596. EXPECT_EQ(0u, file.content.size());
  1597. }
  1598. {
  1599. const auto &file = req.get_file_value("file4");
  1600. EXPECT_TRUE(file.filename.empty());
  1601. EXPECT_EQ(0u, file.content.size());
  1602. EXPECT_EQ("application/json tmp-string", file.content_type);
  1603. }
  1604. })
  1605. .Post("/multipart/multi_file_values",
  1606. [&](const Request &req, Response & /*res*/) {
  1607. EXPECT_EQ(5u, req.files.size());
  1608. ASSERT_TRUE(!req.has_file("???"));
  1609. ASSERT_TRUE(req.body.empty());
  1610. {
  1611. const auto &text_value = req.get_file_values("text");
  1612. EXPECT_EQ(1u, text_value.size());
  1613. auto &text = text_value[0];
  1614. EXPECT_TRUE(text.filename.empty());
  1615. EXPECT_EQ("default text", text.content);
  1616. }
  1617. {
  1618. const auto &text1_values = req.get_file_values("multi_text1");
  1619. EXPECT_EQ(2u, text1_values.size());
  1620. EXPECT_EQ("aaaaa", text1_values[0].content);
  1621. EXPECT_EQ("bbbbb", text1_values[1].content);
  1622. }
  1623. {
  1624. const auto &file1_values = req.get_file_values("multi_file1");
  1625. EXPECT_EQ(2u, file1_values.size());
  1626. auto file1 = file1_values[0];
  1627. EXPECT_EQ(file1.filename, "hello.txt");
  1628. EXPECT_EQ(file1.content_type, "text/plain");
  1629. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1630. auto file2 = file1_values[1];
  1631. EXPECT_EQ(file2.filename, "world.json");
  1632. EXPECT_EQ(file2.content_type, "application/json");
  1633. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1634. }
  1635. })
  1636. .Post("/empty",
  1637. [&](const Request &req, Response &res) {
  1638. EXPECT_EQ(req.body, "");
  1639. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1640. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1641. res.set_content("empty", "text/plain");
  1642. })
  1643. .Post("/empty-no-content-type",
  1644. [&](const Request &req, Response &res) {
  1645. EXPECT_EQ(req.body, "");
  1646. EXPECT_FALSE(req.has_header("Content-Type"));
  1647. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1648. res.set_content("empty-no-content-type", "text/plain");
  1649. })
  1650. .Post("/path-only",
  1651. [&](const Request &req, Response &res) {
  1652. EXPECT_EQ(req.body, "");
  1653. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1654. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1655. res.set_content("path-only", "text/plain");
  1656. })
  1657. .Post("/path-headers-only",
  1658. [&](const Request &req, Response &res) {
  1659. EXPECT_EQ(req.body, "");
  1660. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1661. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1662. EXPECT_EQ("world", req.get_header_value("hello"));
  1663. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1664. res.set_content("path-headers-only", "text/plain");
  1665. })
  1666. .Post("/post-large",
  1667. [&](const Request &req, Response &res) {
  1668. EXPECT_EQ(req.body, LARGE_DATA);
  1669. res.set_content(req.body, "text/plain");
  1670. })
  1671. .Put("/empty-no-content-type",
  1672. [&](const Request &req, Response &res) {
  1673. EXPECT_EQ(req.body, "");
  1674. EXPECT_FALSE(req.has_header("Content-Type"));
  1675. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1676. res.set_content("empty-no-content-type", "text/plain");
  1677. })
  1678. .Put("/put",
  1679. [&](const Request &req, Response &res) {
  1680. EXPECT_EQ(req.body, "PUT");
  1681. res.set_content(req.body, "text/plain");
  1682. })
  1683. .Put("/put-large",
  1684. [&](const Request &req, Response &res) {
  1685. EXPECT_EQ(req.body, LARGE_DATA);
  1686. res.set_content(req.body, "text/plain");
  1687. })
  1688. .Patch("/patch",
  1689. [&](const Request &req, Response &res) {
  1690. EXPECT_EQ(req.body, "PATCH");
  1691. res.set_content(req.body, "text/plain");
  1692. })
  1693. .Delete("/delete",
  1694. [&](const Request & /*req*/, Response &res) {
  1695. res.set_content("DELETE", "text/plain");
  1696. })
  1697. .Delete("/delete-body",
  1698. [&](const Request &req, Response &res) {
  1699. EXPECT_EQ(req.body, "content");
  1700. res.set_content(req.body, "text/plain");
  1701. })
  1702. .Options(R"(\*)",
  1703. [&](const Request & /*req*/, Response &res) {
  1704. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1705. })
  1706. .Get("/request-target",
  1707. [&](const Request &req, Response & /*res*/) {
  1708. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1709. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1710. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1711. })
  1712. .Get("/long-query-value",
  1713. [&](const Request &req, Response & /*res*/) {
  1714. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1715. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1716. })
  1717. .Get("/array-param",
  1718. [&](const Request &req, Response & /*res*/) {
  1719. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1720. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1721. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1722. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1723. })
  1724. .Post("/validate-no-multiple-headers",
  1725. [&](const Request &req, Response & /*res*/) {
  1726. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1727. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1728. })
  1729. .Post("/content_receiver",
  1730. [&](const Request &req, Response &res,
  1731. const ContentReader &content_reader) {
  1732. if (req.is_multipart_form_data()) {
  1733. MultipartFormDataItems files;
  1734. content_reader(
  1735. [&](const MultipartFormData &file) {
  1736. files.push_back(file);
  1737. return true;
  1738. },
  1739. [&](const char *data, size_t data_length) {
  1740. files.back().content.append(data, data_length);
  1741. return true;
  1742. });
  1743. EXPECT_EQ(5u, files.size());
  1744. {
  1745. const auto &file = get_file_value(files, "text1");
  1746. EXPECT_TRUE(file.filename.empty());
  1747. EXPECT_EQ("text default", file.content);
  1748. }
  1749. {
  1750. const auto &file = get_file_value(files, "text2");
  1751. EXPECT_TRUE(file.filename.empty());
  1752. EXPECT_EQ("aωb", file.content);
  1753. }
  1754. {
  1755. const auto &file = get_file_value(files, "file1");
  1756. EXPECT_EQ("hello.txt", file.filename);
  1757. EXPECT_EQ("text/plain", file.content_type);
  1758. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1759. }
  1760. {
  1761. const auto &file = get_file_value(files, "file3");
  1762. EXPECT_TRUE(file.filename.empty());
  1763. EXPECT_EQ("application/octet-stream", file.content_type);
  1764. EXPECT_EQ(0u, file.content.size());
  1765. }
  1766. } else {
  1767. std::string body;
  1768. content_reader([&](const char *data, size_t data_length) {
  1769. EXPECT_EQ(7U, data_length);
  1770. body.append(data, data_length);
  1771. return true;
  1772. });
  1773. EXPECT_EQ(body, "content");
  1774. res.set_content(body, "text/plain");
  1775. }
  1776. })
  1777. .Put("/content_receiver",
  1778. [&](const Request & /*req*/, Response &res,
  1779. const ContentReader &content_reader) {
  1780. std::string body;
  1781. content_reader([&](const char *data, size_t data_length) {
  1782. body.append(data, data_length);
  1783. return true;
  1784. });
  1785. EXPECT_EQ(body, "content");
  1786. res.set_content(body, "text/plain");
  1787. })
  1788. .Patch("/content_receiver",
  1789. [&](const Request & /*req*/, Response &res,
  1790. const ContentReader &content_reader) {
  1791. std::string body;
  1792. content_reader([&](const char *data, size_t data_length) {
  1793. body.append(data, data_length);
  1794. return true;
  1795. });
  1796. EXPECT_EQ(body, "content");
  1797. res.set_content(body, "text/plain");
  1798. })
  1799. .Post("/query-string-and-body",
  1800. [&](const Request &req, Response & /*res*/) {
  1801. ASSERT_TRUE(req.has_param("key"));
  1802. EXPECT_EQ(req.get_param_value("key"), "value");
  1803. EXPECT_EQ(req.body, "content");
  1804. })
  1805. .Get("/last-request",
  1806. [&](const Request &req, Response & /*res*/) {
  1807. EXPECT_EQ("close", req.get_header_value("Connection"));
  1808. })
  1809. .Get(R"(/redirect/(\d+))",
  1810. [&](const Request &req, Response &res) {
  1811. auto num = std::stoi(req.matches[1]) + 1;
  1812. std::string url = "/redirect/" + std::to_string(num);
  1813. res.set_redirect(url);
  1814. })
  1815. .Post("/binary",
  1816. [&](const Request &req, Response &res) {
  1817. EXPECT_EQ(4U, req.body.size());
  1818. EXPECT_EQ("application/octet-stream",
  1819. req.get_header_value("Content-Type"));
  1820. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1821. res.set_content(req.body, "application/octet-stream");
  1822. })
  1823. .Put("/binary",
  1824. [&](const Request &req, Response &res) {
  1825. EXPECT_EQ(4U, req.body.size());
  1826. EXPECT_EQ("application/octet-stream",
  1827. req.get_header_value("Content-Type"));
  1828. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1829. res.set_content(req.body, "application/octet-stream");
  1830. })
  1831. .Patch("/binary",
  1832. [&](const Request &req, Response &res) {
  1833. EXPECT_EQ(4U, req.body.size());
  1834. EXPECT_EQ("application/octet-stream",
  1835. req.get_header_value("Content-Type"));
  1836. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1837. res.set_content(req.body, "application/octet-stream");
  1838. })
  1839. .Delete("/binary",
  1840. [&](const Request &req, Response &res) {
  1841. EXPECT_EQ(4U, req.body.size());
  1842. EXPECT_EQ("application/octet-stream",
  1843. req.get_header_value("Content-Type"));
  1844. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1845. res.set_content(req.body, "application/octet-stream");
  1846. })
  1847. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1848. .Get("/compress",
  1849. [&](const Request & /*req*/, Response &res) {
  1850. res.set_content(
  1851. "12345678901234567890123456789012345678901234567890123456789"
  1852. "01234567890123456789012345678901234567890",
  1853. "text/plain");
  1854. })
  1855. .Get("/nocompress",
  1856. [&](const Request & /*req*/, Response &res) {
  1857. res.set_content(
  1858. "12345678901234567890123456789012345678901234567890123456789"
  1859. "01234567890123456789012345678901234567890",
  1860. "application/octet-stream");
  1861. })
  1862. .Post("/compress-multipart",
  1863. [&](const Request &req, Response & /*res*/) {
  1864. EXPECT_EQ(2u, req.files.size());
  1865. ASSERT_TRUE(!req.has_file("???"));
  1866. {
  1867. const auto &file = req.get_file_value("key1");
  1868. EXPECT_TRUE(file.filename.empty());
  1869. EXPECT_EQ("test", file.content);
  1870. }
  1871. {
  1872. const auto &file = req.get_file_value("key2");
  1873. EXPECT_TRUE(file.filename.empty());
  1874. EXPECT_EQ("--abcdefg123", file.content);
  1875. }
  1876. })
  1877. #endif
  1878. ;
  1879. persons_["john"] = "programmer";
  1880. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1881. svr_.wait_until_ready();
  1882. }
  1883. virtual void TearDown() {
  1884. svr_.stop();
  1885. if (!request_threads_.empty()) {
  1886. std::this_thread::sleep_for(std::chrono::seconds(1));
  1887. for (auto &t : request_threads_) {
  1888. t.join();
  1889. }
  1890. }
  1891. t_.join();
  1892. }
  1893. map<string, string> persons_;
  1894. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1895. SSLClient cli_;
  1896. SSLServer svr_;
  1897. #else
  1898. Client cli_;
  1899. Server svr_;
  1900. #endif
  1901. thread t_;
  1902. std::vector<thread> request_threads_;
  1903. };
  1904. TEST_F(ServerTest, GetMethod200) {
  1905. auto res = cli_.Get("/hi");
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("HTTP/1.1", res->version);
  1908. EXPECT_EQ(200, res->status);
  1909. EXPECT_EQ("OK", res->reason);
  1910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1911. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1912. EXPECT_EQ("Hello World!", res->body);
  1913. }
  1914. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1915. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1916. ASSERT_TRUE(res);
  1917. EXPECT_EQ("HTTP/1.1", res->version);
  1918. EXPECT_EQ(200, res->status);
  1919. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1920. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1921. EXPECT_EQ("Hello World!", res->body);
  1922. }
  1923. TEST_F(ServerTest, GetMethod302) {
  1924. auto res = cli_.Get("/");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(302, res->status);
  1927. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1928. }
  1929. TEST_F(ServerTest, GetMethod302Redirect) {
  1930. cli_.set_follow_location(true);
  1931. auto res = cli_.Get("/");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(200, res->status);
  1934. EXPECT_EQ("Hello World!", res->body);
  1935. EXPECT_EQ("/hi", res->location);
  1936. }
  1937. TEST_F(ServerTest, GetMethod404) {
  1938. auto res = cli_.Get("/invalid");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(404, res->status);
  1941. }
  1942. TEST_F(ServerTest, HeadMethod200) {
  1943. auto res = cli_.Head("/hi");
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(200, res->status);
  1946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1947. EXPECT_TRUE(res->body.empty());
  1948. }
  1949. TEST_F(ServerTest, HeadMethod200Static) {
  1950. auto res = cli_.Head("/mount/dir/index.html");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(200, res->status);
  1953. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1954. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1955. EXPECT_TRUE(res->body.empty());
  1956. }
  1957. TEST_F(ServerTest, HeadMethod404) {
  1958. auto res = cli_.Head("/invalid");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(404, res->status);
  1961. EXPECT_TRUE(res->body.empty());
  1962. }
  1963. TEST_F(ServerTest, GetMethodPersonJohn) {
  1964. auto res = cli_.Get("/person/john");
  1965. ASSERT_TRUE(res);
  1966. EXPECT_EQ(200, res->status);
  1967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1968. EXPECT_EQ("programmer", res->body);
  1969. }
  1970. TEST_F(ServerTest, PostMethod1) {
  1971. auto res = cli_.Get("/person/john1");
  1972. ASSERT_TRUE(res);
  1973. ASSERT_EQ(404, res->status);
  1974. res = cli_.Post("/person", "name=john1&note=coder",
  1975. "application/x-www-form-urlencoded");
  1976. ASSERT_TRUE(res);
  1977. ASSERT_EQ(200, res->status);
  1978. res = cli_.Get("/person/john1");
  1979. ASSERT_TRUE(res);
  1980. ASSERT_EQ(200, res->status);
  1981. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1982. ASSERT_EQ("coder", res->body);
  1983. }
  1984. TEST_F(ServerTest, PostMethod2) {
  1985. auto res = cli_.Get("/person/john2");
  1986. ASSERT_TRUE(res);
  1987. ASSERT_EQ(404, res->status);
  1988. Params params;
  1989. params.emplace("name", "john2");
  1990. params.emplace("note", "coder");
  1991. res = cli_.Post("/person", params);
  1992. ASSERT_TRUE(res);
  1993. ASSERT_EQ(200, res->status);
  1994. res = cli_.Get("/person/john2");
  1995. ASSERT_TRUE(res);
  1996. ASSERT_EQ(200, res->status);
  1997. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1998. ASSERT_EQ("coder", res->body);
  1999. }
  2000. TEST_F(ServerTest, PutMethod3) {
  2001. auto res = cli_.Get("/person/john3");
  2002. ASSERT_TRUE(res);
  2003. ASSERT_EQ(404, res->status);
  2004. Params params;
  2005. params.emplace("name", "john3");
  2006. params.emplace("note", "coder");
  2007. res = cli_.Put("/person", params);
  2008. ASSERT_TRUE(res);
  2009. ASSERT_EQ(200, res->status);
  2010. res = cli_.Get("/person/john3");
  2011. ASSERT_TRUE(res);
  2012. ASSERT_EQ(200, res->status);
  2013. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2014. ASSERT_EQ("coder", res->body);
  2015. }
  2016. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2017. Params params;
  2018. params.emplace("json", JSON_DATA);
  2019. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2020. ASSERT_TRUE(res);
  2021. ASSERT_EQ(200, res->status);
  2022. ASSERT_EQ(JSON_DATA, res->body);
  2023. }
  2024. TEST_F(ServerTest, PostEmptyContent) {
  2025. auto res = cli_.Post("/empty", "", "text/plain");
  2026. ASSERT_TRUE(res);
  2027. ASSERT_EQ(200, res->status);
  2028. ASSERT_EQ("empty", res->body);
  2029. }
  2030. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2031. auto res = cli_.Post("/empty-no-content-type");
  2032. ASSERT_TRUE(res);
  2033. ASSERT_EQ(200, res->status);
  2034. ASSERT_EQ("empty-no-content-type", res->body);
  2035. }
  2036. TEST_F(ServerTest, PostPathOnly) {
  2037. auto res = cli_.Post("/path-only");
  2038. ASSERT_TRUE(res);
  2039. ASSERT_EQ(200, res->status);
  2040. ASSERT_EQ("path-only", res->body);
  2041. }
  2042. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2043. auto res = cli_.Post("/path-headers-only",
  2044. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2045. ASSERT_TRUE(res);
  2046. ASSERT_EQ(200, res->status);
  2047. ASSERT_EQ("path-headers-only", res->body);
  2048. }
  2049. TEST_F(ServerTest, PostLarge) {
  2050. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2051. ASSERT_TRUE(res);
  2052. ASSERT_EQ(200, res->status);
  2053. EXPECT_EQ(LARGE_DATA, res->body);
  2054. }
  2055. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2056. auto res = cli_.Put("/empty-no-content-type");
  2057. ASSERT_TRUE(res);
  2058. ASSERT_EQ(200, res->status);
  2059. ASSERT_EQ("empty-no-content-type", res->body);
  2060. }
  2061. TEST_F(ServerTest, GetMethodDir) {
  2062. auto res = cli_.Get("/dir/");
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(200, res->status);
  2065. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2066. auto body = R"(<html>
  2067. <head>
  2068. </head>
  2069. <body>
  2070. <a href="/dir/test.html">Test</a>
  2071. <a href="/hi">hi</a>
  2072. </body>
  2073. </html>
  2074. )";
  2075. EXPECT_EQ(body, res->body);
  2076. }
  2077. TEST_F(ServerTest, GetMethodDirTest) {
  2078. auto res = cli_.Get("/dir/test.html");
  2079. ASSERT_TRUE(res);
  2080. EXPECT_EQ(200, res->status);
  2081. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2082. EXPECT_EQ("test.html", res->body);
  2083. }
  2084. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2085. auto res = cli_.Get("/dir/../dir/test.html");
  2086. ASSERT_TRUE(res);
  2087. EXPECT_EQ(200, res->status);
  2088. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2089. EXPECT_EQ("test.html", res->body);
  2090. }
  2091. TEST_F(ServerTest, GetMethodInvalidPath) {
  2092. auto res = cli_.Get("/dir/../test.html");
  2093. ASSERT_TRUE(res);
  2094. EXPECT_EQ(404, res->status);
  2095. }
  2096. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2097. auto res = cli_.Get("/../www/dir/test.html");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(404, res->status);
  2100. }
  2101. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2102. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2103. ASSERT_TRUE(res);
  2104. EXPECT_EQ(404, res->status);
  2105. }
  2106. TEST_F(ServerTest, GetMethodDirMountTest) {
  2107. auto res = cli_.Get("/mount/dir/test.html");
  2108. ASSERT_TRUE(res);
  2109. EXPECT_EQ(200, res->status);
  2110. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2111. EXPECT_EQ("test.html", res->body);
  2112. }
  2113. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2114. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2115. ASSERT_TRUE(res);
  2116. EXPECT_EQ(200, res->status);
  2117. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2118. EXPECT_EQ("test.html", res->body);
  2119. }
  2120. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2121. auto res = cli_.Get("/mount/dir/../test.html");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(404, res->status);
  2124. }
  2125. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2126. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(404, res->status);
  2129. }
  2130. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2131. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(404, res->status);
  2134. }
  2135. TEST_F(ServerTest, PostMethod303) {
  2136. auto res = cli_.Post("/1", "body", "text/plain");
  2137. ASSERT_TRUE(res);
  2138. EXPECT_EQ(303, res->status);
  2139. EXPECT_EQ("/2", res->get_header_value("Location"));
  2140. }
  2141. TEST_F(ServerTest, PostMethod303Redirect) {
  2142. cli_.set_follow_location(true);
  2143. auto res = cli_.Post("/1", "body", "text/plain");
  2144. ASSERT_TRUE(res);
  2145. EXPECT_EQ(200, res->status);
  2146. EXPECT_EQ("redirected.", res->body);
  2147. EXPECT_EQ("/2", res->location);
  2148. }
  2149. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2150. auto res = cli_.Get("/dir/test.abcde");
  2151. ASSERT_TRUE(res);
  2152. EXPECT_EQ(200, res->status);
  2153. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2154. EXPECT_EQ("abcde", res->body);
  2155. }
  2156. TEST_F(ServerTest, StaticFileRange) {
  2157. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2158. ASSERT_TRUE(res);
  2159. EXPECT_EQ(206, res->status);
  2160. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2161. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2162. EXPECT_EQ(true, res->has_header("Content-Range"));
  2163. EXPECT_EQ(std::string("cd"), res->body);
  2164. }
  2165. TEST_F(ServerTest, StaticFileRanges) {
  2166. auto res =
  2167. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(206, res->status);
  2170. EXPECT_TRUE(
  2171. res->get_header_value("Content-Type")
  2172. .find(
  2173. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2174. 0);
  2175. EXPECT_EQ("265", res->get_header_value("Content-Length"));
  2176. }
  2177. TEST_F(ServerTest, StaticFileRangeHead) {
  2178. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2179. ASSERT_TRUE(res);
  2180. EXPECT_EQ(206, res->status);
  2181. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2182. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2183. EXPECT_EQ(true, res->has_header("Content-Range"));
  2184. }
  2185. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2186. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(206, res->status);
  2189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2190. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2191. EXPECT_EQ(true, res->has_header("Content-Range"));
  2192. EXPECT_EQ("LAST\n", res->body);
  2193. }
  2194. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2195. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2196. ASSERT_TRUE(res);
  2197. EXPECT_EQ(206, res->status);
  2198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2199. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2200. EXPECT_EQ(true, res->has_header("Content-Range"));
  2201. }
  2202. TEST_F(ServerTest, StaticFileBigFile) {
  2203. auto res = cli_.Get("/dir/1MB.txt");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(200, res->status);
  2206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2207. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2208. }
  2209. TEST_F(ServerTest, InvalidBaseDirMount) {
  2210. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2211. }
  2212. TEST_F(ServerTest, Binary) {
  2213. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2214. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2215. "application/octet-stream");
  2216. ASSERT_TRUE(res);
  2217. ASSERT_EQ(200, res->status);
  2218. ASSERT_EQ(4U, res->body.size());
  2219. res = cli_.Put("/binary", binary.data(), binary.size(),
  2220. "application/octet-stream");
  2221. ASSERT_TRUE(res);
  2222. ASSERT_EQ(200, res->status);
  2223. ASSERT_EQ(4U, res->body.size());
  2224. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2225. "application/octet-stream");
  2226. ASSERT_TRUE(res);
  2227. ASSERT_EQ(200, res->status);
  2228. ASSERT_EQ(4U, res->body.size());
  2229. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2230. "application/octet-stream");
  2231. ASSERT_TRUE(res);
  2232. ASSERT_EQ(200, res->status);
  2233. ASSERT_EQ(4U, res->body.size());
  2234. }
  2235. TEST_F(ServerTest, BinaryString) {
  2236. auto binary = std::string("\x00\x01\x02\x03", 4);
  2237. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2238. ASSERT_TRUE(res);
  2239. ASSERT_EQ(200, res->status);
  2240. ASSERT_EQ(4U, res->body.size());
  2241. res = cli_.Put("/binary", binary, "application/octet-stream");
  2242. ASSERT_TRUE(res);
  2243. ASSERT_EQ(200, res->status);
  2244. ASSERT_EQ(4U, res->body.size());
  2245. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2246. ASSERT_TRUE(res);
  2247. ASSERT_EQ(200, res->status);
  2248. ASSERT_EQ(4U, res->body.size());
  2249. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2250. ASSERT_TRUE(res);
  2251. ASSERT_EQ(200, res->status);
  2252. ASSERT_EQ(4U, res->body.size());
  2253. }
  2254. TEST_F(ServerTest, EmptyRequest) {
  2255. auto res = cli_.Get("");
  2256. ASSERT_TRUE(!res);
  2257. EXPECT_EQ(Error::Connection, res.error());
  2258. }
  2259. TEST_F(ServerTest, LongRequest) {
  2260. std::string request;
  2261. for (size_t i = 0; i < 545; i++) {
  2262. request += "/TooLongRequest";
  2263. }
  2264. request += "OK";
  2265. auto res = cli_.Get(request.c_str());
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(404, res->status);
  2268. }
  2269. TEST_F(ServerTest, TooLongRequest) {
  2270. std::string request;
  2271. for (size_t i = 0; i < 545; i++) {
  2272. request += "/TooLongRequest";
  2273. }
  2274. request += "_NG";
  2275. auto res = cli_.Get(request.c_str());
  2276. ASSERT_TRUE(res);
  2277. EXPECT_EQ(414, res->status);
  2278. }
  2279. TEST_F(ServerTest, LongHeader) {
  2280. Request req;
  2281. req.method = "GET";
  2282. req.path = "/hi";
  2283. std::string host_and_port;
  2284. host_and_port += HOST;
  2285. host_and_port += ":";
  2286. host_and_port += std::to_string(PORT);
  2287. req.headers.emplace("Host", host_and_port.c_str());
  2288. req.headers.emplace("Accept", "*/*");
  2289. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2290. req.headers.emplace(
  2291. "Header-Name",
  2292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2320. "@@@@@@@@@@@@@@@@");
  2321. auto res = std::make_shared<Response>();
  2322. auto error = Error::Success;
  2323. auto ret = cli_.send(req, *res, error);
  2324. ASSERT_TRUE(ret);
  2325. EXPECT_EQ(200, res->status);
  2326. }
  2327. TEST_F(ServerTest, LongQueryValue) {
  2328. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(414, res->status);
  2331. }
  2332. TEST_F(ServerTest, TooLongHeader) {
  2333. Request req;
  2334. req.method = "GET";
  2335. req.path = "/hi";
  2336. std::string host_and_port;
  2337. host_and_port += HOST;
  2338. host_and_port += ":";
  2339. host_and_port += std::to_string(PORT);
  2340. req.headers.emplace("Host", host_and_port.c_str());
  2341. req.headers.emplace("Accept", "*/*");
  2342. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2343. req.headers.emplace(
  2344. "Header-Name",
  2345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2373. "@@@@@@@@@@@@@@@@@");
  2374. auto res = std::make_shared<Response>();
  2375. auto error = Error::Success;
  2376. auto ret = cli_.send(req, *res, error);
  2377. ASSERT_TRUE(ret);
  2378. EXPECT_EQ(200, res->status);
  2379. }
  2380. TEST_F(ServerTest, PercentEncoding) {
  2381. auto res = cli_.Get("/e%6edwith%");
  2382. ASSERT_TRUE(res);
  2383. EXPECT_EQ(200, res->status);
  2384. }
  2385. TEST_F(ServerTest, PercentEncodingUnicode) {
  2386. auto res = cli_.Get("/e%u006edwith%");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(200, res->status);
  2389. }
  2390. TEST_F(ServerTest, InvalidPercentEncoding) {
  2391. auto res = cli_.Get("/%endwith%");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(404, res->status);
  2394. }
  2395. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2396. auto res = cli_.Get("/%uendwith%");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(404, res->status);
  2399. }
  2400. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2401. auto res = cli_.Get("/hello?aaa=bbb%");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(404, res->status);
  2404. }
  2405. TEST_F(ServerTest, PlusSignEncoding) {
  2406. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2407. ASSERT_TRUE(res);
  2408. EXPECT_EQ(200, res->status);
  2409. EXPECT_EQ("a +b", res->body);
  2410. }
  2411. TEST_F(ServerTest, MultipartFormData) {
  2412. MultipartFormDataItems items = {
  2413. {"text1", "text default", "", ""},
  2414. {"text2", "aωb", "", ""},
  2415. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2416. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2417. {"file3", "", "", "application/octet-stream"},
  2418. {"file4", "", "", " application/json tmp-string "}};
  2419. auto res = cli_.Post("/multipart", items);
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(200, res->status);
  2422. }
  2423. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2424. MultipartFormDataItems items = {
  2425. {"text", "default text", "", ""},
  2426. {"multi_text1", "aaaaa", "", ""},
  2427. {"multi_text1", "bbbbb", "", ""},
  2428. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2429. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2430. "application/json"},
  2431. };
  2432. auto res = cli_.Post("/multipart/multi_file_values", items);
  2433. ASSERT_TRUE(res);
  2434. EXPECT_EQ(200, res->status);
  2435. }
  2436. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2437. auto res = cli_.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(200, res->status);
  2440. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2441. EXPECT_EQ("Hello World!", res->body);
  2442. }
  2443. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2444. Request req;
  2445. req.method = "POST";
  2446. req.path = "/chunked";
  2447. std::string host_and_port;
  2448. host_and_port += HOST;
  2449. host_and_port += ":";
  2450. host_and_port += std::to_string(PORT);
  2451. req.headers.emplace("Host", host_and_port.c_str());
  2452. req.headers.emplace("Accept", "*/*");
  2453. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2454. req.headers.emplace("Content-Type", "text/plain");
  2455. req.headers.emplace("Content-Length", "0");
  2456. req.headers.emplace(
  2457. "Transfer-Encoding",
  2458. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2459. // Client does not chunk, so make a chunked body manually.
  2460. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2461. auto res = std::make_shared<Response>();
  2462. auto error = Error::Success;
  2463. auto ret = cli_.send(req, *res, error);
  2464. ASSERT_TRUE(ret);
  2465. EXPECT_EQ(200, res->status);
  2466. }
  2467. TEST_F(ServerTest, GetStreamed2) {
  2468. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(206, res->status);
  2471. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ(std::string("ab"), res->body);
  2473. }
  2474. TEST_F(ServerTest, GetStreamed) {
  2475. auto res = cli_.Get("/streamed");
  2476. ASSERT_TRUE(res);
  2477. EXPECT_EQ(200, res->status);
  2478. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2479. EXPECT_EQ(std::string("aaabbb"), res->body);
  2480. }
  2481. TEST_F(ServerTest, GetStreamedWithRange1) {
  2482. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2483. ASSERT_TRUE(res);
  2484. EXPECT_EQ(206, res->status);
  2485. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2486. EXPECT_EQ(true, res->has_header("Content-Range"));
  2487. EXPECT_EQ(std::string("def"), res->body);
  2488. }
  2489. TEST_F(ServerTest, GetStreamedWithRange2) {
  2490. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2491. ASSERT_TRUE(res);
  2492. EXPECT_EQ(206, res->status);
  2493. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2494. EXPECT_EQ(true, res->has_header("Content-Range"));
  2495. EXPECT_EQ(std::string("bcdefg"), res->body);
  2496. }
  2497. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2498. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(206, res->status);
  2501. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2502. EXPECT_EQ(true, res->has_header("Content-Range"));
  2503. EXPECT_EQ(std::string("efg"), res->body);
  2504. }
  2505. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2506. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2507. ASSERT_TRUE(res);
  2508. EXPECT_EQ(206, res->status);
  2509. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2510. EXPECT_EQ(true, res->has_header("Content-Range"));
  2511. EXPECT_EQ(std::string("abcdefg"), res->body);
  2512. }
  2513. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2514. auto res = cli_.Get("/streamed-with-range",
  2515. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2516. "92233720368547758079223372036854775807"}});
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(416, res->status);
  2519. }
  2520. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2521. auto res =
  2522. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2523. EXPECT_EQ(206, res->status);
  2524. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2525. EXPECT_EQ(true, res->has_header("Content-Range"));
  2526. EXPECT_EQ(std::string("abcdefg"), res->body);
  2527. }
  2528. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2529. auto res =
  2530. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(206, res->status);
  2533. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2534. EXPECT_EQ(false, res->has_header("Content-Range"));
  2535. EXPECT_EQ(267U, res->body.size());
  2536. }
  2537. TEST_F(ServerTest, GetStreamedEndless) {
  2538. uint64_t offset = 0;
  2539. auto res = cli_.Get("/streamed-cancel",
  2540. [&](const char * /*data*/, uint64_t data_length) {
  2541. if (offset < 100) {
  2542. offset += data_length;
  2543. return true;
  2544. }
  2545. return false;
  2546. });
  2547. ASSERT_TRUE(!res);
  2548. EXPECT_EQ(Error::Canceled, res.error());
  2549. }
  2550. TEST_F(ServerTest, ClientStop) {
  2551. std::atomic_size_t count{4};
  2552. std::vector<std::thread> threads;
  2553. for (auto i = count.load(); i != 0; --i) {
  2554. threads.emplace_back([&]() {
  2555. auto res = cli_.Get("/streamed-cancel",
  2556. [&](const char *, uint64_t) { return true; });
  2557. --count;
  2558. ASSERT_TRUE(!res);
  2559. EXPECT_TRUE(res.error() == Error::Canceled ||
  2560. res.error() == Error::Read || res.error() == Error::Write);
  2561. });
  2562. }
  2563. std::this_thread::sleep_for(std::chrono::seconds(2));
  2564. while (count != 0) {
  2565. cli_.stop();
  2566. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2567. }
  2568. for (auto &t : threads) {
  2569. t.join();
  2570. }
  2571. }
  2572. TEST_F(ServerTest, GetWithRange1) {
  2573. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2574. ASSERT_TRUE(res);
  2575. EXPECT_EQ(206, res->status);
  2576. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2577. EXPECT_EQ(true, res->has_header("Content-Range"));
  2578. EXPECT_EQ(std::string("def"), res->body);
  2579. }
  2580. TEST_F(ServerTest, GetWithRange2) {
  2581. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2582. ASSERT_TRUE(res);
  2583. EXPECT_EQ(206, res->status);
  2584. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2585. EXPECT_EQ(true, res->has_header("Content-Range"));
  2586. EXPECT_EQ(std::string("bcdefg"), res->body);
  2587. }
  2588. TEST_F(ServerTest, GetWithRange3) {
  2589. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2590. ASSERT_TRUE(res);
  2591. EXPECT_EQ(206, res->status);
  2592. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2593. EXPECT_EQ(true, res->has_header("Content-Range"));
  2594. EXPECT_EQ(std::string("a"), res->body);
  2595. }
  2596. TEST_F(ServerTest, GetWithRange4) {
  2597. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2598. ASSERT_TRUE(res);
  2599. EXPECT_EQ(206, res->status);
  2600. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2601. EXPECT_EQ(true, res->has_header("Content-Range"));
  2602. EXPECT_EQ(std::string("fg"), res->body);
  2603. }
  2604. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2605. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2606. ASSERT_TRUE(res);
  2607. EXPECT_EQ(416, res->status);
  2608. }
  2609. TEST_F(ServerTest, GetWithRangeMultipart) {
  2610. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2611. ASSERT_TRUE(res);
  2612. EXPECT_EQ(206, res->status);
  2613. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2614. EXPECT_EQ(false, res->has_header("Content-Range"));
  2615. EXPECT_EQ(267U, res->body.size());
  2616. }
  2617. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2618. auto res =
  2619. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2620. ASSERT_TRUE(res);
  2621. EXPECT_EQ(416, res->status);
  2622. }
  2623. TEST_F(ServerTest, GetStreamedChunked) {
  2624. auto res = cli_.Get("/streamed-chunked");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(200, res->status);
  2627. EXPECT_EQ(std::string("123456789"), res->body);
  2628. }
  2629. TEST_F(ServerTest, GetStreamedChunked2) {
  2630. auto res = cli_.Get("/streamed-chunked2");
  2631. ASSERT_TRUE(res);
  2632. EXPECT_EQ(200, res->status);
  2633. EXPECT_EQ(std::string("123456789"), res->body);
  2634. }
  2635. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2636. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(200, res->status);
  2639. EXPECT_EQ(std::string("123456789"), res->body);
  2640. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2641. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2642. }
  2643. TEST_F(ServerTest, LargeChunkedPost) {
  2644. Request req;
  2645. req.method = "POST";
  2646. req.path = "/large-chunked";
  2647. std::string host_and_port;
  2648. host_and_port += HOST;
  2649. host_and_port += ":";
  2650. host_and_port += std::to_string(PORT);
  2651. req.headers.emplace("Host", host_and_port.c_str());
  2652. req.headers.emplace("Accept", "*/*");
  2653. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2654. req.headers.emplace("Content-Type", "text/plain");
  2655. req.headers.emplace("Content-Length", "0");
  2656. req.headers.emplace("Transfer-Encoding", "chunked");
  2657. std::string long_string(30 * 1024u, 'a');
  2658. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2659. // Attempt to make a large enough post to exceed OS buffers, to test that
  2660. // the server handles short reads if the full chunk data isn't available.
  2661. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2662. auto res = std::make_shared<Response>();
  2663. auto error = Error::Success;
  2664. auto ret = cli_.send(req, *res, error);
  2665. ASSERT_TRUE(ret);
  2666. EXPECT_EQ(200, res->status);
  2667. }
  2668. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2669. auto res = cli_.Get("/remote_addr");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(200, res->status);
  2672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2673. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2674. }
  2675. TEST_F(ServerTest, GetMethodLocalAddr) {
  2676. auto res = cli_.Get("/local_addr");
  2677. ASSERT_TRUE(res);
  2678. EXPECT_EQ(200, res->status);
  2679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2680. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2681. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2682. }
  2683. TEST_F(ServerTest, HTTPResponseSplitting) {
  2684. auto res = cli_.Get("/http_response_splitting");
  2685. ASSERT_TRUE(res);
  2686. EXPECT_EQ(200, res->status);
  2687. }
  2688. TEST_F(ServerTest, SlowRequest) {
  2689. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2690. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2691. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2692. }
  2693. #if 0
  2694. TEST_F(ServerTest, SlowPost) {
  2695. char buffer[64 * 1024];
  2696. memset(buffer, 0x42, sizeof(buffer));
  2697. auto res = cli_.Post(
  2698. "/slowpost", 64 * 1024 * 1024,
  2699. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2700. auto ret = sink.write(buffer, sizeof(buffer));
  2701. EXPECT_TRUE(ret);
  2702. return true;
  2703. },
  2704. "text/plain");
  2705. ASSERT_TRUE(res);
  2706. EXPECT_EQ(200, res->status);
  2707. }
  2708. TEST_F(ServerTest, SlowPostFail) {
  2709. char buffer[64 * 1024];
  2710. memset(buffer, 0x42, sizeof(buffer));
  2711. cli_.set_write_timeout(std::chrono::seconds(0));
  2712. auto res = cli_.Post(
  2713. "/slowpost", 64 * 1024 * 1024,
  2714. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2715. sink.write(buffer, sizeof(buffer));
  2716. return true;
  2717. },
  2718. "text/plain");
  2719. ASSERT_TRUE(!res);
  2720. EXPECT_EQ(Error::Write, res.error());
  2721. }
  2722. #endif
  2723. TEST_F(ServerTest, Put) {
  2724. auto res = cli_.Put("/put", "PUT", "text/plain");
  2725. ASSERT_TRUE(res);
  2726. EXPECT_EQ(200, res->status);
  2727. EXPECT_EQ("PUT", res->body);
  2728. }
  2729. TEST_F(ServerTest, PutWithContentProvider) {
  2730. auto res = cli_.Put(
  2731. "/put", 3,
  2732. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2733. sink.os << "PUT";
  2734. return true;
  2735. },
  2736. "text/plain");
  2737. ASSERT_TRUE(res);
  2738. EXPECT_EQ(200, res->status);
  2739. EXPECT_EQ("PUT", res->body);
  2740. }
  2741. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2742. auto res = cli_.Post(
  2743. "/post", 42,
  2744. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2745. return false;
  2746. },
  2747. "text/plain");
  2748. ASSERT_TRUE(!res);
  2749. EXPECT_EQ(Error::Canceled, res.error());
  2750. }
  2751. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2752. auto res = cli_.Put(
  2753. "/put",
  2754. [](size_t /*offset*/, DataSink &sink) {
  2755. sink.os << "PUT";
  2756. sink.done();
  2757. return true;
  2758. },
  2759. "text/plain");
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(200, res->status);
  2762. EXPECT_EQ("PUT", res->body);
  2763. }
  2764. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2765. auto res = cli_.Post(
  2766. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2767. "text/plain");
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2772. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2773. cli_.set_compress(true);
  2774. auto res = cli_.Put(
  2775. "/put", 3,
  2776. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2777. sink.os << "PUT";
  2778. return true;
  2779. },
  2780. "text/plain");
  2781. ASSERT_TRUE(res);
  2782. EXPECT_EQ(200, res->status);
  2783. EXPECT_EQ("PUT", res->body);
  2784. }
  2785. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2786. cli_.set_compress(true);
  2787. auto res = cli_.Post(
  2788. "/post", 42,
  2789. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2790. return false;
  2791. },
  2792. "text/plain");
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2797. cli_.set_compress(true);
  2798. auto res = cli_.Put(
  2799. "/put",
  2800. [](size_t /*offset*/, DataSink &sink) {
  2801. sink.os << "PUT";
  2802. sink.done();
  2803. return true;
  2804. },
  2805. "text/plain");
  2806. ASSERT_TRUE(res);
  2807. EXPECT_EQ(200, res->status);
  2808. EXPECT_EQ("PUT", res->body);
  2809. }
  2810. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2811. cli_.set_compress(true);
  2812. auto res = cli_.Post(
  2813. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2814. "text/plain");
  2815. ASSERT_TRUE(!res);
  2816. EXPECT_EQ(Error::Canceled, res.error());
  2817. }
  2818. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2819. cli_.set_compress(true);
  2820. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2821. ASSERT_TRUE(res);
  2822. EXPECT_EQ(200, res->status);
  2823. EXPECT_EQ(LARGE_DATA, res->body);
  2824. }
  2825. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2826. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2827. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2828. Client cli(s.c_str());
  2829. cli.enable_server_certificate_verification(false);
  2830. #else
  2831. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2832. Client cli(s.c_str());
  2833. #endif
  2834. cli.set_compress(true);
  2835. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2836. ASSERT_TRUE(res);
  2837. EXPECT_EQ(200, res->status);
  2838. EXPECT_EQ(LARGE_DATA, res->body);
  2839. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  2840. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2841. }
  2842. TEST_F(ServerTest, PutContentWithDeflate) {
  2843. cli_.set_compress(false);
  2844. Headers headers;
  2845. headers.emplace("Content-Encoding", "deflate");
  2846. // PUT in deflate format:
  2847. auto res = cli_.Put("/put", headers,
  2848. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2849. ASSERT_TRUE(res);
  2850. EXPECT_EQ(200, res->status);
  2851. EXPECT_EQ("PUT", res->body);
  2852. }
  2853. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2854. Headers headers;
  2855. headers.emplace("Accept-Encoding", "gzip, deflate");
  2856. auto res = cli_.Get("/streamed-chunked", headers);
  2857. ASSERT_TRUE(res);
  2858. EXPECT_EQ(200, res->status);
  2859. EXPECT_EQ(std::string("123456789"), res->body);
  2860. }
  2861. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2862. Headers headers;
  2863. headers.emplace("Accept-Encoding", "gzip, deflate");
  2864. auto res = cli_.Get("/streamed-chunked2", headers);
  2865. ASSERT_TRUE(res);
  2866. EXPECT_EQ(200, res->status);
  2867. EXPECT_EQ(std::string("123456789"), res->body);
  2868. }
  2869. TEST(GzipDecompressor, ChunkedDecompression) {
  2870. std::string data;
  2871. for (size_t i = 0; i < 32 * 1024; ++i) {
  2872. data.push_back(static_cast<char>('a' + i % 26));
  2873. }
  2874. std::string compressed_data;
  2875. {
  2876. httplib::detail::gzip_compressor compressor;
  2877. bool result = compressor.compress(
  2878. data.data(), data.size(),
  2879. /*last=*/true,
  2880. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2881. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2882. compressed_data_size);
  2883. return true;
  2884. });
  2885. ASSERT_TRUE(result);
  2886. }
  2887. std::string decompressed_data;
  2888. {
  2889. httplib::detail::gzip_decompressor decompressor;
  2890. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2891. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2892. size_t chunk_size = 130;
  2893. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2894. chunk_begin += chunk_size) {
  2895. size_t current_chunk_size =
  2896. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2897. bool result = decompressor.decompress(
  2898. compressed_data.data() + chunk_begin, current_chunk_size,
  2899. [&](const char *decompressed_data_chunk,
  2900. size_t decompressed_data_chunk_size) {
  2901. decompressed_data.insert(decompressed_data.size(),
  2902. decompressed_data_chunk,
  2903. decompressed_data_chunk_size);
  2904. return true;
  2905. });
  2906. ASSERT_TRUE(result);
  2907. }
  2908. }
  2909. ASSERT_EQ(data, decompressed_data);
  2910. }
  2911. TEST(GzipDecompressor, DeflateDecompression) {
  2912. std::string original_text = "Raw deflate without gzip";
  2913. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2914. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2915. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2916. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  2917. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2918. std::string decompressed_data;
  2919. {
  2920. httplib::detail::gzip_decompressor decompressor;
  2921. bool result = decompressor.decompress(
  2922. compressed_data.data(), compressed_data.size(),
  2923. [&](const char *decompressed_data_chunk,
  2924. size_t decompressed_data_chunk_size) {
  2925. decompressed_data.insert(decompressed_data.size(),
  2926. decompressed_data_chunk,
  2927. decompressed_data_chunk_size);
  2928. return true;
  2929. });
  2930. ASSERT_TRUE(result);
  2931. }
  2932. ASSERT_EQ(original_text, decompressed_data);
  2933. }
  2934. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  2935. std::string original_text = "Raw deflate without gzip";
  2936. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2937. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2938. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2939. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  2940. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  2941. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2942. std::string decompressed_data;
  2943. {
  2944. httplib::detail::gzip_decompressor decompressor;
  2945. bool result = decompressor.decompress(
  2946. compressed_data.data(), compressed_data.size(),
  2947. [&](const char *decompressed_data_chunk,
  2948. size_t decompressed_data_chunk_size) {
  2949. decompressed_data.insert(decompressed_data.size(),
  2950. decompressed_data_chunk,
  2951. decompressed_data_chunk_size);
  2952. return true;
  2953. });
  2954. ASSERT_TRUE(result);
  2955. }
  2956. ASSERT_EQ(original_text, decompressed_data);
  2957. }
  2958. #ifdef _WIN32
  2959. TEST(GzipDecompressor, LargeRandomData) {
  2960. // prepare large random data that is difficult to be compressed and is
  2961. // expected to have large size even when compressed
  2962. std::random_device seed_gen;
  2963. std::mt19937 random(seed_gen());
  2964. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2965. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2966. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2967. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2968. // compress data over 4GiB
  2969. std::string compressed_data;
  2970. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2971. httplib::detail::gzip_compressor compressor;
  2972. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2973. data.size() * sizeof(std::uint32_t), true,
  2974. [&](const char *data, size_t size) {
  2975. compressed_data.insert(
  2976. compressed_data.size(), data, size);
  2977. return true;
  2978. });
  2979. ASSERT_TRUE(result);
  2980. // FIXME: compressed data size is expected to be greater than 4GiB,
  2981. // but there is no guarantee
  2982. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2983. // decompress data over 4GiB
  2984. std::string decompressed_data;
  2985. decompressed_data.reserve(data_size);
  2986. httplib::detail::gzip_decompressor decompressor;
  2987. result = decompressor.decompress(
  2988. compressed_data.data(), compressed_data.size(),
  2989. [&](const char *data, size_t size) {
  2990. decompressed_data.insert(decompressed_data.size(), data, size);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(result);
  2994. // compare
  2995. ASSERT_EQ(data_size, decompressed_data.size());
  2996. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2997. 0);
  2998. }
  2999. #endif
  3000. #endif
  3001. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3002. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3003. Headers headers;
  3004. headers.emplace("Accept-Encoding", "br");
  3005. auto res = cli_.Get("/streamed-chunked", headers);
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(200, res->status);
  3008. EXPECT_EQ(std::string("123456789"), res->body);
  3009. }
  3010. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3011. Headers headers;
  3012. headers.emplace("Accept-Encoding", "br");
  3013. auto res = cli_.Get("/streamed-chunked2", headers);
  3014. ASSERT_TRUE(res);
  3015. EXPECT_EQ(200, res->status);
  3016. EXPECT_EQ(std::string("123456789"), res->body);
  3017. }
  3018. #endif
  3019. TEST_F(ServerTest, Patch) {
  3020. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3021. ASSERT_TRUE(res);
  3022. EXPECT_EQ(200, res->status);
  3023. EXPECT_EQ("PATCH", res->body);
  3024. }
  3025. TEST_F(ServerTest, Delete) {
  3026. auto res = cli_.Delete("/delete");
  3027. ASSERT_TRUE(res);
  3028. EXPECT_EQ(200, res->status);
  3029. EXPECT_EQ("DELETE", res->body);
  3030. }
  3031. TEST_F(ServerTest, DeleteContentReceiver) {
  3032. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3033. ASSERT_TRUE(res);
  3034. EXPECT_EQ(200, res->status);
  3035. EXPECT_EQ("content", res->body);
  3036. }
  3037. TEST_F(ServerTest, Options) {
  3038. auto res = cli_.Options("*");
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(200, res->status);
  3041. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3042. EXPECT_TRUE(res->body.empty());
  3043. }
  3044. TEST_F(ServerTest, URL) {
  3045. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3046. ASSERT_TRUE(res);
  3047. EXPECT_EQ(200, res->status);
  3048. }
  3049. TEST_F(ServerTest, ArrayParam) {
  3050. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3051. ASSERT_TRUE(res);
  3052. EXPECT_EQ(200, res->status);
  3053. }
  3054. TEST_F(ServerTest, NoMultipleHeaders) {
  3055. Headers headers = {{"Content-Length", "5"}};
  3056. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3057. "text/plain");
  3058. ASSERT_TRUE(res);
  3059. EXPECT_EQ(200, res->status);
  3060. }
  3061. TEST_F(ServerTest, PostContentReceiver) {
  3062. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3063. ASSERT_TRUE(res);
  3064. ASSERT_EQ(200, res->status);
  3065. ASSERT_EQ("content", res->body);
  3066. }
  3067. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3068. MultipartFormDataItems items = {
  3069. {"text1", "text default", "", ""},
  3070. {"text2", "aωb", "", ""},
  3071. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3072. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3073. {"file3", "", "", "application/octet-stream"},
  3074. };
  3075. auto res = cli_.Post("/content_receiver", items);
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(200, res->status);
  3078. }
  3079. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3080. MultipartFormDataItems items = {
  3081. {"text1", "text default", "", ""},
  3082. {"text2", "aωb", "", ""},
  3083. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3084. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3085. {"file3", "", "", "application/octet-stream"},
  3086. };
  3087. auto boundary = std::string("+++++");
  3088. std::string body;
  3089. for (const auto &item : items) {
  3090. body += "--" + boundary + "\r\n";
  3091. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3092. if (!item.filename.empty()) {
  3093. body += "; filename=\"" + item.filename + "\"";
  3094. }
  3095. body += "\r\n";
  3096. if (!item.content_type.empty()) {
  3097. body += "Content-Type: " + item.content_type + "\r\n";
  3098. }
  3099. body += "\r\n";
  3100. body += item.content + "\r\n";
  3101. }
  3102. body += "--" + boundary + "--\r\n";
  3103. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3104. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3105. ASSERT_TRUE(res);
  3106. EXPECT_EQ(200, res->status);
  3107. }
  3108. TEST_F(ServerTest, PostContentReceiverGzip) {
  3109. cli_.set_compress(true);
  3110. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3111. ASSERT_TRUE(res);
  3112. ASSERT_EQ(200, res->status);
  3113. ASSERT_EQ("content", res->body);
  3114. }
  3115. TEST_F(ServerTest, PutContentReceiver) {
  3116. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3117. ASSERT_TRUE(res);
  3118. ASSERT_EQ(200, res->status);
  3119. ASSERT_EQ("content", res->body);
  3120. }
  3121. TEST_F(ServerTest, PatchContentReceiver) {
  3122. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(200, res->status);
  3125. ASSERT_EQ("content", res->body);
  3126. }
  3127. TEST_F(ServerTest, PostQueryStringAndBody) {
  3128. auto res =
  3129. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(200, res->status);
  3132. }
  3133. TEST_F(ServerTest, HTTP2Magic) {
  3134. Request req;
  3135. req.method = "PRI";
  3136. req.path = "*";
  3137. req.body = "SM";
  3138. auto res = std::make_shared<Response>();
  3139. auto error = Error::Success;
  3140. auto ret = cli_.send(req, *res, error);
  3141. ASSERT_TRUE(ret);
  3142. EXPECT_EQ(400, res->status);
  3143. }
  3144. TEST_F(ServerTest, KeepAlive) {
  3145. auto res = cli_.Get("/hi");
  3146. ASSERT_TRUE(res);
  3147. EXPECT_EQ(200, res->status);
  3148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3149. EXPECT_EQ("Hello World!", res->body);
  3150. res = cli_.Get("/hi");
  3151. ASSERT_TRUE(res);
  3152. EXPECT_EQ(200, res->status);
  3153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3154. EXPECT_EQ("Hello World!", res->body);
  3155. res = cli_.Get("/hi");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(200, res->status);
  3158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("Hello World!", res->body);
  3160. res = cli_.Get("/not-exist");
  3161. ASSERT_TRUE(res);
  3162. EXPECT_EQ(404, res->status);
  3163. res = cli_.Post("/empty", "", "text/plain");
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ(200, res->status);
  3166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. EXPECT_EQ("empty", res->body);
  3168. EXPECT_EQ("close", res->get_header_value("Connection"));
  3169. res = cli_.Post(
  3170. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3171. "text/plain");
  3172. ASSERT_TRUE(res);
  3173. EXPECT_EQ(200, res->status);
  3174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3175. EXPECT_EQ("empty", res->body);
  3176. cli_.set_keep_alive(false);
  3177. res = cli_.Get("/last-request");
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ(200, res->status);
  3180. EXPECT_EQ("close", res->get_header_value("Connection"));
  3181. }
  3182. TEST_F(ServerTest, TooManyRedirect) {
  3183. cli_.set_follow_location(true);
  3184. auto res = cli_.Get("/redirect/0");
  3185. ASSERT_TRUE(!res);
  3186. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3187. }
  3188. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3189. TEST_F(ServerTest, Gzip) {
  3190. Headers headers;
  3191. headers.emplace("Accept-Encoding", "gzip, deflate");
  3192. auto res = cli_.Get("/compress", headers);
  3193. ASSERT_TRUE(res);
  3194. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3196. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3197. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3198. "7890123456789012345678901234567890",
  3199. res->body);
  3200. EXPECT_EQ(200, res->status);
  3201. }
  3202. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3203. auto res = cli_.Get("/compress");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3207. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3208. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3209. "7890123456789012345678901234567890",
  3210. res->body);
  3211. EXPECT_EQ(200, res->status);
  3212. }
  3213. TEST_F(ServerTest, GzipWithContentReceiver) {
  3214. Headers headers;
  3215. headers.emplace("Accept-Encoding", "gzip, deflate");
  3216. std::string body;
  3217. auto res = cli_.Get("/compress", headers,
  3218. [&](const char *data, uint64_t data_length) {
  3219. EXPECT_EQ(100U, data_length);
  3220. body.append(data, data_length);
  3221. return true;
  3222. });
  3223. ASSERT_TRUE(res);
  3224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3226. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3228. "7890123456789012345678901234567890",
  3229. body);
  3230. EXPECT_EQ(200, res->status);
  3231. }
  3232. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3233. Headers headers;
  3234. headers.emplace("Accept-Encoding", "gzip, deflate");
  3235. cli_.set_decompress(false);
  3236. auto res = cli_.Get("/compress", headers);
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3240. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3241. EXPECT_EQ(33U, res->body.size());
  3242. EXPECT_EQ(200, res->status);
  3243. }
  3244. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3245. std::string body;
  3246. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3247. EXPECT_EQ(100U, data_length);
  3248. body.append(data, data_length);
  3249. return true;
  3250. });
  3251. ASSERT_TRUE(res);
  3252. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3254. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3255. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3256. "7890123456789012345678901234567890",
  3257. body);
  3258. EXPECT_EQ(200, res->status);
  3259. }
  3260. TEST_F(ServerTest, NoGzip) {
  3261. Headers headers;
  3262. headers.emplace("Accept-Encoding", "gzip, deflate");
  3263. auto res = cli_.Get("/nocompress", headers);
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3266. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3267. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3269. "7890123456789012345678901234567890",
  3270. res->body);
  3271. EXPECT_EQ(200, res->status);
  3272. }
  3273. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3274. Headers headers;
  3275. headers.emplace("Accept-Encoding", "gzip, deflate");
  3276. std::string body;
  3277. auto res = cli_.Get("/nocompress", headers,
  3278. [&](const char *data, uint64_t data_length) {
  3279. EXPECT_EQ(100U, data_length);
  3280. body.append(data, data_length);
  3281. return true;
  3282. });
  3283. ASSERT_TRUE(res);
  3284. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3285. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3286. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3287. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3288. "7890123456789012345678901234567890",
  3289. body);
  3290. EXPECT_EQ(200, res->status);
  3291. }
  3292. TEST_F(ServerTest, MultipartFormDataGzip) {
  3293. MultipartFormDataItems items = {
  3294. {"key1", "test", "", ""},
  3295. {"key2", "--abcdefg123", "", ""},
  3296. };
  3297. cli_.set_compress(true);
  3298. auto res = cli_.Post("/compress-multipart", items);
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(200, res->status);
  3301. }
  3302. #endif
  3303. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3304. TEST_F(ServerTest, Brotli) {
  3305. Headers headers;
  3306. headers.emplace("Accept-Encoding", "br");
  3307. auto res = cli_.Get("/compress", headers);
  3308. ASSERT_TRUE(res);
  3309. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3311. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3312. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3313. "7890123456789012345678901234567890",
  3314. res->body);
  3315. EXPECT_EQ(200, res->status);
  3316. }
  3317. #endif
  3318. // Sends a raw request to a server listening at HOST:PORT.
  3319. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3320. std::string *resp = nullptr) {
  3321. auto error = Error::Success;
  3322. auto client_sock = detail::create_client_socket(
  3323. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3324. /*connection_timeout_sec=*/5, 0,
  3325. /*read_timeout_sec=*/5, 0,
  3326. /*write_timeout_sec=*/5, 0, std::string(), error);
  3327. if (client_sock == INVALID_SOCKET) { return false; }
  3328. auto ret = detail::process_client_socket(
  3329. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3330. if (req.size() !=
  3331. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3332. return false;
  3333. }
  3334. char buf[512];
  3335. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3336. while (line_reader.getline()) {
  3337. if (resp) { *resp += line_reader.ptr(); }
  3338. }
  3339. return true;
  3340. });
  3341. detail::close_socket(client_sock);
  3342. return ret;
  3343. }
  3344. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3345. Server svr;
  3346. std::string header_value;
  3347. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3348. header_value = req.get_header_value("foo");
  3349. res.set_content("ok", "text/plain");
  3350. });
  3351. thread t = thread([&] { svr.listen(HOST, PORT); });
  3352. auto se = detail::scope_exit([&] {
  3353. svr.stop();
  3354. t.join();
  3355. ASSERT_FALSE(svr.is_running());
  3356. });
  3357. svr.wait_until_ready();
  3358. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3359. // like characters are not treated the same - use vertical tab and escape.
  3360. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3361. "foo: \t \v bar \x1B\t \r\n"
  3362. "Connection: close\r\n"
  3363. "\r\n";
  3364. ASSERT_TRUE(send_request(5, req));
  3365. EXPECT_EQ(header_value, "\v bar \x1B");
  3366. }
  3367. // Sends a raw request and verifies that there isn't a crash or exception.
  3368. static void test_raw_request(const std::string &req,
  3369. std::string *out = nullptr) {
  3370. Server svr;
  3371. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3372. res.set_content("ok", "text/plain");
  3373. });
  3374. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3375. res.set_content("ok", "text/plain");
  3376. });
  3377. // Server read timeout must be longer than the client read timeout for the
  3378. // bug to reproduce, probably to force the server to process a request
  3379. // without a trailing blank line.
  3380. const time_t client_read_timeout_sec = 1;
  3381. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3382. bool listen_thread_ok = false;
  3383. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. t.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. EXPECT_TRUE(listen_thread_ok);
  3389. });
  3390. svr.wait_until_ready();
  3391. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3392. }
  3393. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3394. // A certain header line causes an exception if the header property is parsed
  3395. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3396. test_raw_request(
  3397. "GET /hi HTTP/1.1\r\n"
  3398. " : "
  3399. " "
  3400. " ");
  3401. }
  3402. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3403. // A certain header line causes an exception if the header property *name* is
  3404. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3405. // greedy matcher and requires backtracking when there are a lot of ":"
  3406. // characters.
  3407. // This occurs with libc++ but not libstdc++.
  3408. test_raw_request(
  3409. "GET /hi HTTP/1.1\r\n"
  3410. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3411. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3412. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3413. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3414. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3415. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3416. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3417. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3418. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3419. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3420. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3421. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3422. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3423. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3424. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3425. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3426. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3427. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3428. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3429. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3430. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3431. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3432. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3433. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3434. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3435. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3436. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3437. "&&&%%%");
  3438. }
  3439. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3440. // Make sure this doesn't crash the server.
  3441. // In a previous version of the header line regex, the "\r" rendered the line
  3442. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3443. // a new position where the leading white space ended and the field value
  3444. // began.
  3445. // The crash occurs with libc++ but not libstdc++.
  3446. test_raw_request("GET /hi HTTP/1.1\r\n"
  3447. "a:" +
  3448. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3449. "\r\n"
  3450. "\r\n");
  3451. }
  3452. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3453. std::string out;
  3454. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3455. "Content-Type: text/plain\r\n"
  3456. "Transfer-Encoding: chunked\r\n"
  3457. "\r\n"
  3458. "nothex\r\n",
  3459. &out);
  3460. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3461. }
  3462. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3463. std::string out;
  3464. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3465. "Content-Type: text/plain\r\n"
  3466. "Transfer-Encoding: chunked\r\n"
  3467. "\r\n"
  3468. "3\r\n"
  3469. "xyz\r\n"
  3470. "NaN\r\n",
  3471. &out);
  3472. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3473. }
  3474. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3475. std::string out;
  3476. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3477. "Content-Type: text/plain\r\n"
  3478. "Transfer-Encoding: chunked\r\n"
  3479. "\r\n"
  3480. // Length is too large for 64 bits.
  3481. "1ffffffffffffffff\r\n"
  3482. "xyz\r\n",
  3483. &out);
  3484. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3485. }
  3486. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3487. test_raw_request("GET /hi HTTP/1.1\r\n"
  3488. "Content-Type: text/plain\r\n\r");
  3489. }
  3490. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3491. std::string out;
  3492. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3493. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3494. }
  3495. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3496. Server svr;
  3497. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3498. res.set_header("Cache-Control", "no-cache");
  3499. res.set_chunked_content_provider(
  3500. "text/event-stream", [](size_t offset, DataSink &sink) {
  3501. std::string s = "data:";
  3502. s += std::to_string(offset);
  3503. s += "\n\n";
  3504. auto ret = sink.write(s.data(), s.size());
  3505. EXPECT_TRUE(ret);
  3506. std::this_thread::sleep_for(std::chrono::seconds(1));
  3507. return true;
  3508. });
  3509. });
  3510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3511. svr.wait_until_ready();
  3512. Client client(HOST, PORT);
  3513. const Headers headers = {{"Accept", "text/event-stream"}};
  3514. auto get_thread = std::thread([&client, &headers]() {
  3515. auto res = client.Get(
  3516. "/events", headers,
  3517. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3518. });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. get_thread.join();
  3522. listen_thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. });
  3525. // Give GET time to get a few messages.
  3526. std::this_thread::sleep_for(std::chrono::seconds(2));
  3527. }
  3528. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3529. httplib::Server svr;
  3530. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3531. httplib::Response &res) { res.status = 200; });
  3532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3533. svr.wait_until_ready();
  3534. Client cli(HOST, PORT);
  3535. auto res = cli.Post("/hi", "data", "text/plain");
  3536. ASSERT_TRUE(res);
  3537. EXPECT_EQ(200, res->status);
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. res = cli.Post("/hi", "data", "text/plain");
  3542. ASSERT_FALSE(res);
  3543. }
  3544. TEST(ServerStopTest, ListenFailure) {
  3545. Server svr;
  3546. auto t = thread([&]() {
  3547. auto ret = svr.listen("????", PORT);
  3548. EXPECT_FALSE(ret);
  3549. });
  3550. svr.wait_until_ready();
  3551. svr.stop();
  3552. t.join();
  3553. }
  3554. TEST(StreamingTest, NoContentLengthStreaming) {
  3555. Server svr;
  3556. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3557. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3558. if (offset < 6) {
  3559. sink.os << (offset < 3 ? "a" : "b");
  3560. } else {
  3561. sink.done();
  3562. }
  3563. return true;
  3564. });
  3565. });
  3566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3567. auto listen_se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. listen_thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client client(HOST, PORT);
  3574. auto get_thread = std::thread([&client]() {
  3575. std::string s;
  3576. auto res =
  3577. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3578. s += std::string(data, len);
  3579. return true;
  3580. });
  3581. EXPECT_EQ("aaabbb", s);
  3582. });
  3583. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3584. // Give GET time to get a few messages.
  3585. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3586. }
  3587. TEST(MountTest, Unmount) {
  3588. Server svr;
  3589. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3590. auto se = detail::scope_exit([&] {
  3591. svr.stop();
  3592. listen_thread.join();
  3593. ASSERT_FALSE(svr.is_running());
  3594. });
  3595. svr.wait_until_ready();
  3596. Client cli("localhost", PORT);
  3597. svr.set_mount_point("/mount2", "./www2");
  3598. auto res = cli.Get("/");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(404, res->status);
  3601. res = cli.Get("/mount2/dir/test.html");
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(200, res->status);
  3604. svr.set_mount_point("/", "./www");
  3605. res = cli.Get("/dir/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(200, res->status);
  3608. svr.remove_mount_point("/");
  3609. res = cli.Get("/dir/");
  3610. ASSERT_TRUE(res);
  3611. EXPECT_EQ(404, res->status);
  3612. svr.remove_mount_point("/mount2");
  3613. res = cli.Get("/mount2/dir/test.html");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(404, res->status);
  3616. }
  3617. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3618. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3619. Server svr;
  3620. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3621. throw std::runtime_error("exception...");
  3622. });
  3623. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3624. throw std::runtime_error("exception\r\n...");
  3625. });
  3626. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. listen_thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. Client cli("localhost", PORT);
  3634. {
  3635. auto res = cli.Get("/exception");
  3636. ASSERT_TRUE(res);
  3637. EXPECT_EQ(500, res->status);
  3638. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3639. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3640. }
  3641. {
  3642. auto res = cli.Get("/unknown");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(500, res->status);
  3645. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3646. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3647. }
  3648. }
  3649. #endif
  3650. TEST(KeepAliveTest, ReadTimeout) {
  3651. Server svr;
  3652. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3653. std::this_thread::sleep_for(std::chrono::seconds(2));
  3654. res.set_content("a", "text/plain");
  3655. });
  3656. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3657. res.set_content("b", "text/plain");
  3658. });
  3659. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. listen_thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. Client cli("localhost", PORT);
  3667. cli.set_keep_alive(true);
  3668. cli.set_read_timeout(std::chrono::seconds(1));
  3669. auto resa = cli.Get("/a");
  3670. ASSERT_FALSE(resa);
  3671. EXPECT_EQ(Error::Read, resa.error());
  3672. auto resb = cli.Get("/b");
  3673. ASSERT_TRUE(resb);
  3674. EXPECT_EQ(200, resb->status);
  3675. EXPECT_EQ("b", resb->body);
  3676. }
  3677. TEST(KeepAliveTest, Issue1041) {
  3678. Server svr;
  3679. svr.set_keep_alive_timeout(3);
  3680. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3681. res.set_content("Hello World!", "text/plain");
  3682. });
  3683. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3684. auto se = detail::scope_exit([&] {
  3685. svr.stop();
  3686. listen_thread.join();
  3687. ASSERT_FALSE(svr.is_running());
  3688. });
  3689. svr.wait_until_ready();
  3690. Client cli(HOST, PORT);
  3691. cli.set_keep_alive(true);
  3692. auto result = cli.Get("/hi");
  3693. ASSERT_TRUE(result);
  3694. EXPECT_EQ(200, result->status);
  3695. std::this_thread::sleep_for(std::chrono::seconds(5));
  3696. result = cli.Get("/hi");
  3697. ASSERT_TRUE(result);
  3698. EXPECT_EQ(200, result->status);
  3699. }
  3700. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3701. TEST(KeepAliveTest, SSLClientReconnection) {
  3702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3703. ASSERT_TRUE(svr.is_valid());
  3704. svr.set_keep_alive_timeout(1);
  3705. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3706. res.set_content("Hello World!", "text/plain");
  3707. });
  3708. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3709. auto se = detail::scope_exit([&] {
  3710. svr.stop();
  3711. listen_thread.join();
  3712. ASSERT_FALSE(svr.is_running());
  3713. });
  3714. svr.wait_until_ready();
  3715. SSLClient cli(HOST, PORT);
  3716. cli.enable_server_certificate_verification(false);
  3717. cli.set_keep_alive(true);
  3718. auto result = cli.Get("/hi");
  3719. ASSERT_TRUE(result);
  3720. EXPECT_EQ(200, result->status);
  3721. result = cli.Get("/hi");
  3722. ASSERT_TRUE(result);
  3723. EXPECT_EQ(200, result->status);
  3724. std::this_thread::sleep_for(std::chrono::seconds(2));
  3725. // Recoonect
  3726. result = cli.Get("/hi");
  3727. ASSERT_TRUE(result);
  3728. EXPECT_EQ(200, result->status);
  3729. result = cli.Get("/hi");
  3730. ASSERT_TRUE(result);
  3731. EXPECT_EQ(200, result->status);
  3732. }
  3733. #endif
  3734. TEST(ClientProblemDetectionTest, ContentProvider) {
  3735. Server svr;
  3736. size_t content_length = 1024 * 1024;
  3737. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3738. res.set_content_provider(
  3739. content_length, "text/plain",
  3740. [&](size_t offset, size_t length, DataSink &sink) {
  3741. auto out_len = std::min(length, static_cast<size_t>(1024));
  3742. std::string out(out_len, '@');
  3743. sink.write(out.data(), out_len);
  3744. return offset < 4096;
  3745. },
  3746. [](bool success) { ASSERT_FALSE(success); });
  3747. });
  3748. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3749. res.set_content_provider(
  3750. 0, "text/plain",
  3751. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3752. EXPECT_TRUE(false);
  3753. return true;
  3754. },
  3755. [](bool success) { ASSERT_FALSE(success); });
  3756. });
  3757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3758. auto se = detail::scope_exit([&] {
  3759. svr.stop();
  3760. listen_thread.join();
  3761. ASSERT_FALSE(svr.is_running());
  3762. });
  3763. svr.wait_until_ready();
  3764. Client cli("localhost", PORT);
  3765. {
  3766. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3767. size_t /*data_length*/) { return false; });
  3768. ASSERT_FALSE(res);
  3769. }
  3770. {
  3771. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3772. size_t /*data_length*/) { return false; });
  3773. ASSERT_TRUE(res);
  3774. }
  3775. }
  3776. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3777. Server svr;
  3778. svr.set_error_handler([](Request const &, Response &res) -> void {
  3779. res.set_chunked_content_provider(
  3780. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3781. sink.os << "hello";
  3782. sink.os << "world";
  3783. sink.done();
  3784. return true;
  3785. });
  3786. });
  3787. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3788. auto se = detail::scope_exit([&] {
  3789. svr.stop();
  3790. listen_thread.join();
  3791. ASSERT_FALSE(svr.is_running());
  3792. });
  3793. svr.wait_until_ready();
  3794. Client cli("localhost", PORT);
  3795. auto res = cli.Get("/");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(404, res->status);
  3798. EXPECT_EQ("helloworld", res->body);
  3799. }
  3800. TEST(GetWithParametersTest, GetWithParameters) {
  3801. Server svr;
  3802. svr.Get("/", [&](const Request &req, Response &) {
  3803. EXPECT_EQ("world", req.get_param_value("hello"));
  3804. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3805. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3806. });
  3807. svr.Get("/params", [&](const Request &req, Response &) {
  3808. EXPECT_EQ("world", req.get_param_value("hello"));
  3809. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3810. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3811. });
  3812. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3813. EXPECT_EQ("resource-id", req.matches[1]);
  3814. EXPECT_EQ("foo", req.get_param_value("param1"));
  3815. EXPECT_EQ("bar", req.get_param_value("param2"));
  3816. });
  3817. svr.Get("/users/:id", [&](const Request &req, Response &) {
  3818. EXPECT_EQ("user-id", req.path_params.at("id"));
  3819. EXPECT_EQ("foo", req.get_param_value("param1"));
  3820. EXPECT_EQ("bar", req.get_param_value("param2"));
  3821. });
  3822. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3823. auto se = detail::scope_exit([&] {
  3824. svr.stop();
  3825. listen_thread.join();
  3826. ASSERT_FALSE(svr.is_running());
  3827. });
  3828. svr.wait_until_ready();
  3829. {
  3830. Client cli(HOST, PORT);
  3831. Params params;
  3832. params.emplace("hello", "world");
  3833. params.emplace("hello2", "world2");
  3834. params.emplace("hello3", "world3");
  3835. auto res = cli.Get("/", params, Headers{});
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(200, res->status);
  3838. }
  3839. {
  3840. Client cli(HOST, PORT);
  3841. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(200, res->status);
  3844. }
  3845. {
  3846. Client cli(HOST, PORT);
  3847. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3848. ASSERT_TRUE(res);
  3849. EXPECT_EQ(200, res->status);
  3850. }
  3851. {
  3852. Client cli(HOST, PORT);
  3853. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  3854. ASSERT_TRUE(res);
  3855. EXPECT_EQ(200, res->status);
  3856. }
  3857. }
  3858. TEST(GetWithParametersTest, GetWithParameters2) {
  3859. Server svr;
  3860. svr.Get("/", [&](const Request &req, Response &res) {
  3861. auto text = req.get_param_value("hello");
  3862. res.set_content(text, "text/plain");
  3863. });
  3864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. listen_thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. Client cli("localhost", PORT);
  3872. Params params;
  3873. params.emplace("hello", "world");
  3874. std::string body;
  3875. auto res = cli.Get("/", params, Headers{},
  3876. [&](const char *data, size_t data_length) {
  3877. body.append(data, data_length);
  3878. return true;
  3879. });
  3880. ASSERT_TRUE(res);
  3881. EXPECT_EQ(200, res->status);
  3882. EXPECT_EQ("world", body);
  3883. }
  3884. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3885. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  3886. auto host = "httpbin.org";
  3887. auto path = std::string{"/range/32"};
  3888. #else
  3889. auto host = "nghttp2.org";
  3890. auto path = std::string{"/httpbin/range/32"};
  3891. #endif
  3892. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3893. SSLClient cli(host);
  3894. #else
  3895. Client cli(host);
  3896. #endif
  3897. cli.set_default_headers({make_range_header({{1, 10}})});
  3898. cli.set_connection_timeout(5);
  3899. {
  3900. auto res = cli.Get(path);
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ("bcdefghijk", res->body);
  3903. EXPECT_EQ(206, res->status);
  3904. }
  3905. {
  3906. auto res = cli.Get(path);
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ("bcdefghijk", res->body);
  3909. EXPECT_EQ(206, res->status);
  3910. }
  3911. }
  3912. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3913. Server svr;
  3914. svr.set_default_headers({{"Hello", "World"}});
  3915. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3916. res.set_content("ok", "text/plain");
  3917. });
  3918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3919. auto se = detail::scope_exit([&] {
  3920. svr.stop();
  3921. listen_thread.join();
  3922. ASSERT_FALSE(svr.is_running());
  3923. });
  3924. svr.wait_until_ready();
  3925. Client cli("localhost", PORT);
  3926. auto res = cli.Get("/");
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(200, res->status);
  3929. EXPECT_EQ("ok", res->body);
  3930. EXPECT_EQ("World", res->get_header_value("Hello"));
  3931. }
  3932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3933. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3935. ASSERT_TRUE(svr.is_valid());
  3936. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3937. std::this_thread::sleep_for(std::chrono::seconds(2));
  3938. res.set_content("a", "text/plain");
  3939. });
  3940. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3941. res.set_content("b", "text/plain");
  3942. });
  3943. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. listen_thread.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. SSLClient cli("localhost", PORT);
  3951. cli.enable_server_certificate_verification(false);
  3952. cli.set_keep_alive(true);
  3953. cli.set_read_timeout(std::chrono::seconds(1));
  3954. auto resa = cli.Get("/a");
  3955. ASSERT_TRUE(!resa);
  3956. EXPECT_EQ(Error::Read, resa.error());
  3957. auto resb = cli.Get("/b");
  3958. ASSERT_TRUE(resb);
  3959. EXPECT_EQ(200, resb->status);
  3960. EXPECT_EQ("b", resb->body);
  3961. }
  3962. #endif
  3963. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3964. protected:
  3965. ServerTestWithAI_PASSIVE()
  3966. : cli_(HOST, PORT)
  3967. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3968. ,
  3969. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3970. #endif
  3971. {
  3972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3973. cli_.enable_server_certificate_verification(false);
  3974. #endif
  3975. }
  3976. virtual void SetUp() {
  3977. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3978. res.set_content("Hello World!", "text/plain");
  3979. });
  3980. t_ = thread(
  3981. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3982. svr_.wait_until_ready();
  3983. }
  3984. virtual void TearDown() {
  3985. svr_.stop();
  3986. t_.join();
  3987. }
  3988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3989. SSLClient cli_;
  3990. SSLServer svr_;
  3991. #else
  3992. Client cli_;
  3993. Server svr_;
  3994. #endif
  3995. thread t_;
  3996. };
  3997. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3998. auto res = cli_.Get("/hi");
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(200, res->status);
  4001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4002. EXPECT_EQ("Hello World!", res->body);
  4003. }
  4004. class ServerUpDownTest : public ::testing::Test {
  4005. protected:
  4006. ServerUpDownTest() : cli_(HOST, PORT) {}
  4007. virtual void SetUp() {
  4008. t_ = thread([&]() {
  4009. svr_.bind_to_any_port(HOST);
  4010. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4011. ASSERT_TRUE(svr_.listen_after_bind());
  4012. });
  4013. svr_.wait_until_ready();
  4014. }
  4015. virtual void TearDown() {
  4016. svr_.stop();
  4017. t_.join();
  4018. }
  4019. Client cli_;
  4020. Server svr_;
  4021. thread t_;
  4022. };
  4023. TEST_F(ServerUpDownTest, QuickStartStop) {
  4024. // Should not crash, especially when run with
  4025. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4026. }
  4027. class PayloadMaxLengthTest : public ::testing::Test {
  4028. protected:
  4029. PayloadMaxLengthTest()
  4030. : cli_(HOST, PORT)
  4031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4032. ,
  4033. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4034. #endif
  4035. {
  4036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4037. cli_.enable_server_certificate_verification(false);
  4038. #endif
  4039. }
  4040. virtual void SetUp() {
  4041. svr_.set_payload_max_length(8);
  4042. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4043. res.set_content("test", "text/plain");
  4044. });
  4045. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4046. svr_.wait_until_ready();
  4047. }
  4048. virtual void TearDown() {
  4049. svr_.stop();
  4050. t_.join();
  4051. }
  4052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4053. SSLClient cli_;
  4054. SSLServer svr_;
  4055. #else
  4056. Client cli_;
  4057. Server svr_;
  4058. #endif
  4059. thread t_;
  4060. };
  4061. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4062. auto res = cli_.Post("/test", "123456789", "text/plain");
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(413, res->status);
  4065. res = cli_.Post("/test", "12345678", "text/plain");
  4066. ASSERT_TRUE(res);
  4067. EXPECT_EQ(200, res->status);
  4068. }
  4069. TEST(HostAndPortPropertiesTest, NoSSL) {
  4070. httplib::Client cli("www.google.com", 1234);
  4071. ASSERT_EQ("www.google.com", cli.host());
  4072. ASSERT_EQ(1234, cli.port());
  4073. }
  4074. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4075. httplib::Client cli("www.google.com:1234");
  4076. ASSERT_EQ("www.google.com", cli.host());
  4077. ASSERT_EQ(1234, cli.port());
  4078. }
  4079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4080. TEST(HostAndPortPropertiesTest, SSL) {
  4081. httplib::SSLClient cli("www.google.com");
  4082. ASSERT_EQ("www.google.com", cli.host());
  4083. ASSERT_EQ(443, cli.port());
  4084. }
  4085. #endif
  4086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4087. TEST(SSLClientTest, UpdateCAStore) {
  4088. httplib::SSLClient httplib_client("www.google.com");
  4089. auto ca_store_1 = X509_STORE_new();
  4090. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4091. nullptr);
  4092. httplib_client.set_ca_cert_store(ca_store_1);
  4093. auto ca_store_2 = X509_STORE_new();
  4094. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4095. nullptr);
  4096. httplib_client.set_ca_cert_store(ca_store_2);
  4097. }
  4098. TEST(SSLClientTest, ServerNameIndication_Online) {
  4099. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4100. auto host = "httpbin.org";
  4101. auto path = std::string{"/get"};
  4102. #else
  4103. auto host = "nghttp2.org";
  4104. auto path = std::string{"/httpbin/get"};
  4105. #endif
  4106. SSLClient cli(host, 443);
  4107. auto res = cli.Get(path);
  4108. ASSERT_TRUE(res);
  4109. ASSERT_EQ(200, res->status);
  4110. }
  4111. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4112. Client cli("https://google.com");
  4113. auto res = cli.Get("/");
  4114. ASSERT_TRUE(res);
  4115. ASSERT_EQ(301, res->status);
  4116. }
  4117. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4118. SSLClient cli("google.com");
  4119. cli.enable_server_certificate_verification(true);
  4120. cli.set_ca_cert_path("hello");
  4121. auto res = cli.Get("/");
  4122. ASSERT_TRUE(!res);
  4123. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4124. }
  4125. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4126. SSLClient cli("google.com");
  4127. cli.set_ca_cert_path(CA_CERT_FILE);
  4128. auto res = cli.Get("/");
  4129. ASSERT_TRUE(res);
  4130. ASSERT_EQ(301, res->status);
  4131. }
  4132. TEST(SSLClientTest, ServerCertificateVerification4) {
  4133. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4134. ASSERT_TRUE(svr.is_valid());
  4135. svr.Get("/test", [&](const Request &, Response &res) {
  4136. res.set_content("test", "text/plain");
  4137. svr.stop();
  4138. ASSERT_TRUE(true);
  4139. });
  4140. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4141. auto se = detail::scope_exit([&] {
  4142. t.join();
  4143. ASSERT_FALSE(svr.is_running());
  4144. });
  4145. svr.wait_until_ready();
  4146. SSLClient cli("127.0.0.1", PORT);
  4147. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4148. cli.enable_server_certificate_verification(true);
  4149. cli.set_connection_timeout(30);
  4150. auto res = cli.Get("/test");
  4151. ASSERT_TRUE(res);
  4152. ASSERT_EQ(200, res->status);
  4153. }
  4154. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4155. std::string cert;
  4156. detail::read_file(CA_CERT_FILE, cert);
  4157. SSLClient cli("google.com");
  4158. cli.load_ca_cert_store(cert.data(), cert.size());
  4159. const auto res = cli.Get("/");
  4160. ASSERT_TRUE(res);
  4161. ASSERT_EQ(301, res->status);
  4162. }
  4163. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4164. // clang-format off
  4165. static constexpr char cert[] =
  4166. "GlobalSign Root CA\n"
  4167. "==================\n"
  4168. "-----BEGIN CERTIFICATE-----\n"
  4169. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4170. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4171. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4172. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4173. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4174. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4175. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4176. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4177. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4178. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4179. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4180. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4181. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4182. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4183. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4184. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4185. "-----END CERTIFICATE-----\n";
  4186. // clang-format on
  4187. SSLClient cli("google.com");
  4188. cli.load_ca_cert_store(cert, sizeof(cert));
  4189. const auto res = cli.Get("/");
  4190. ASSERT_TRUE(res);
  4191. ASSERT_EQ(301, res->status);
  4192. }
  4193. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4194. SSLClient cli("www.youtube.com");
  4195. cli.set_ca_cert_path(CA_CERT_FILE);
  4196. cli.enable_server_certificate_verification(true);
  4197. cli.set_follow_location(true);
  4198. auto res = cli.Get("/");
  4199. ASSERT_TRUE(res);
  4200. ASSERT_EQ(200, res->status);
  4201. }
  4202. #if 0
  4203. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4204. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4205. ASSERT_TRUE(cli != nullptr);
  4206. cli->set_address_family(AF_INET6);
  4207. cli->set_interface("en0");
  4208. auto res = cli->Get("/get");
  4209. ASSERT_TRUE(res);
  4210. ASSERT_EQ(200, res->status);
  4211. }
  4212. #endif
  4213. TEST(SSLClientServerTest, ClientCertPresent) {
  4214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4215. CLIENT_CA_CERT_DIR);
  4216. ASSERT_TRUE(svr.is_valid());
  4217. svr.Get("/test", [&](const Request &req, Response &res) {
  4218. res.set_content("test", "text/plain");
  4219. svr.stop();
  4220. ASSERT_TRUE(true);
  4221. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4222. ASSERT_TRUE(peer_cert != nullptr);
  4223. auto subject_name = X509_get_subject_name(peer_cert);
  4224. ASSERT_TRUE(subject_name != nullptr);
  4225. std::string common_name;
  4226. {
  4227. char name[BUFSIZ];
  4228. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4229. name, sizeof(name));
  4230. common_name.assign(name, static_cast<size_t>(name_len));
  4231. }
  4232. EXPECT_EQ("Common Name", common_name);
  4233. X509_free(peer_cert);
  4234. });
  4235. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4236. auto se = detail::scope_exit([&] {
  4237. t.join();
  4238. ASSERT_FALSE(svr.is_running());
  4239. });
  4240. svr.wait_until_ready();
  4241. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4242. cli.enable_server_certificate_verification(false);
  4243. cli.set_connection_timeout(30);
  4244. auto res = cli.Get("/test");
  4245. ASSERT_TRUE(res);
  4246. ASSERT_EQ(200, res->status);
  4247. }
  4248. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4249. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4250. X509 *server_cert;
  4251. EVP_PKEY *server_private_key;
  4252. X509_STORE *client_ca_cert_store;
  4253. X509 *client_cert;
  4254. EVP_PKEY *client_private_key;
  4255. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4256. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4257. fclose(f);
  4258. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4259. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4260. fclose(f);
  4261. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4262. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4263. client_ca_cert_store = X509_STORE_new();
  4264. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4265. X509_free(client_cert);
  4266. fclose(f);
  4267. f = fopen(CLIENT_CERT_FILE, "r+");
  4268. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4269. fclose(f);
  4270. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4271. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4272. fclose(f);
  4273. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4274. ASSERT_TRUE(svr.is_valid());
  4275. svr.Get("/test", [&](const Request &req, Response &res) {
  4276. res.set_content("test", "text/plain");
  4277. svr.stop();
  4278. ASSERT_TRUE(true);
  4279. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4280. ASSERT_TRUE(peer_cert != nullptr);
  4281. auto subject_name = X509_get_subject_name(peer_cert);
  4282. ASSERT_TRUE(subject_name != nullptr);
  4283. std::string common_name;
  4284. {
  4285. char name[BUFSIZ];
  4286. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4287. name, sizeof(name));
  4288. common_name.assign(name, static_cast<size_t>(name_len));
  4289. }
  4290. EXPECT_EQ("Common Name", common_name);
  4291. X509_free(peer_cert);
  4292. });
  4293. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4294. auto se = detail::scope_exit([&] {
  4295. t.join();
  4296. ASSERT_FALSE(svr.is_running());
  4297. });
  4298. svr.wait_until_ready();
  4299. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4300. cli.enable_server_certificate_verification(false);
  4301. cli.set_connection_timeout(30);
  4302. auto res = cli.Get("/test");
  4303. ASSERT_TRUE(res);
  4304. ASSERT_EQ(200, res->status);
  4305. X509_free(server_cert);
  4306. EVP_PKEY_free(server_private_key);
  4307. X509_free(client_cert);
  4308. EVP_PKEY_free(client_private_key);
  4309. }
  4310. #endif
  4311. TEST(SSLClientServerTest, ClientCertMissing) {
  4312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4313. CLIENT_CA_CERT_DIR);
  4314. ASSERT_TRUE(svr.is_valid());
  4315. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4317. auto se = detail::scope_exit([&] {
  4318. svr.stop();
  4319. t.join();
  4320. ASSERT_FALSE(svr.is_running());
  4321. });
  4322. svr.wait_until_ready();
  4323. SSLClient cli(HOST, PORT);
  4324. auto res = cli.Get("/test");
  4325. cli.set_connection_timeout(30);
  4326. ASSERT_TRUE(!res);
  4327. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4328. }
  4329. TEST(SSLClientServerTest, TrustDirOptional) {
  4330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4331. ASSERT_TRUE(svr.is_valid());
  4332. svr.Get("/test", [&](const Request &, Response &res) {
  4333. res.set_content("test", "text/plain");
  4334. svr.stop();
  4335. });
  4336. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4337. auto se = detail::scope_exit([&] {
  4338. t.join();
  4339. ASSERT_FALSE(svr.is_running());
  4340. });
  4341. svr.wait_until_ready();
  4342. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4343. cli.enable_server_certificate_verification(false);
  4344. cli.set_connection_timeout(30);
  4345. auto res = cli.Get("/test");
  4346. ASSERT_TRUE(res);
  4347. ASSERT_EQ(200, res->status);
  4348. }
  4349. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4350. class NoListenSSLServer : public SSLServer {
  4351. public:
  4352. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4353. const char *client_ca_cert_file_path,
  4354. const char *client_ca_cert_dir_path = nullptr)
  4355. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4356. client_ca_cert_dir_path),
  4357. stop_(false) {}
  4358. std::atomic_bool stop_;
  4359. private:
  4360. bool process_and_close_socket(socket_t /*sock*/) override {
  4361. // Don't create SSL context
  4362. while (!stop_.load()) {
  4363. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4364. }
  4365. return true;
  4366. }
  4367. };
  4368. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4369. CLIENT_CA_CERT_FILE);
  4370. ASSERT_TRUE(svr.is_valid());
  4371. svr.Get("/test", [&](const Request &, Response &res) {
  4372. res.set_content("test", "text/plain");
  4373. });
  4374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4375. auto se = detail::scope_exit([&] {
  4376. svr.stop_ = true;
  4377. svr.stop();
  4378. t.join();
  4379. ASSERT_FALSE(svr.is_running());
  4380. });
  4381. svr.wait_until_ready();
  4382. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4383. cli.enable_server_certificate_verification(false);
  4384. cli.set_connection_timeout(1);
  4385. auto res = cli.Get("/test");
  4386. ASSERT_TRUE(!res);
  4387. EXPECT_EQ(Error::SSLConnection, res.error());
  4388. }
  4389. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4390. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4391. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4392. SSL_CTX_set_options(&ssl_ctx,
  4393. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4394. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4395. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4396. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4397. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4398. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4399. "ECDHE-DSS-AES128-SHA256:"
  4400. "ECDHE-RSA-AES256-SHA256:"
  4401. "ECDHE-DSS-AES256-SHA256:";
  4402. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4403. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4404. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4405. SSL_FILETYPE_PEM) != 1) {
  4406. return false;
  4407. }
  4408. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4409. CLIENT_CA_CERT_DIR);
  4410. SSL_CTX_set_verify(
  4411. &ssl_ctx,
  4412. SSL_VERIFY_PEER |
  4413. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4414. nullptr);
  4415. return true;
  4416. };
  4417. SSLServer svr(setup_ssl_ctx_callback);
  4418. ASSERT_TRUE(svr.is_valid());
  4419. svr.Get("/test", [&](const Request &req, Response &res) {
  4420. res.set_content("test", "text/plain");
  4421. svr.stop();
  4422. ASSERT_TRUE(true);
  4423. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4424. ASSERT_TRUE(peer_cert != nullptr);
  4425. auto subject_name = X509_get_subject_name(peer_cert);
  4426. ASSERT_TRUE(subject_name != nullptr);
  4427. std::string common_name;
  4428. {
  4429. char name[BUFSIZ];
  4430. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4431. name, sizeof(name));
  4432. common_name.assign(name, static_cast<size_t>(name_len));
  4433. }
  4434. EXPECT_EQ("Common Name", common_name);
  4435. X509_free(peer_cert);
  4436. });
  4437. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4438. auto se = detail::scope_exit([&] {
  4439. t.join();
  4440. ASSERT_FALSE(svr.is_running());
  4441. });
  4442. svr.wait_until_ready();
  4443. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4444. cli.enable_server_certificate_verification(false);
  4445. cli.set_connection_timeout(30);
  4446. auto res = cli.Get("/test");
  4447. ASSERT_TRUE(res);
  4448. ASSERT_EQ(200, res->status);
  4449. }
  4450. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4451. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4452. // prepare large data
  4453. std::random_device seed_gen;
  4454. std::mt19937 random(seed_gen());
  4455. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4456. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4457. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4458. // server
  4459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4460. ASSERT_TRUE(svr.is_valid());
  4461. svr.Post("/binary", [&](const Request &req, Response &res) {
  4462. EXPECT_EQ(large_size_byte, req.body.size());
  4463. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4464. res.set_content(req.body, "application/octet-stream");
  4465. });
  4466. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. listen_thread.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. // client POST
  4474. SSLClient cli("localhost", PORT);
  4475. cli.enable_server_certificate_verification(false);
  4476. cli.set_read_timeout(std::chrono::seconds(100));
  4477. cli.set_write_timeout(std::chrono::seconds(100));
  4478. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4479. large_size_byte, "application/octet-stream");
  4480. // compare
  4481. EXPECT_EQ(200, res->status);
  4482. EXPECT_EQ(large_size_byte, res->body.size());
  4483. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4484. }
  4485. #endif
  4486. #ifdef _WIN32
  4487. TEST(CleanupTest, WSACleanup) {
  4488. int ret = WSACleanup();
  4489. ASSERT_EQ(0, ret);
  4490. }
  4491. #endif
  4492. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4493. TEST(NoSSLSupport, SimpleInterface) {
  4494. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4495. }
  4496. #endif
  4497. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4498. TEST(InvalidScheme, SimpleInterface) {
  4499. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4500. }
  4501. #endif
  4502. TEST(NoScheme, SimpleInterface) {
  4503. Client cli("yahoo.com:80");
  4504. ASSERT_TRUE(cli.is_valid());
  4505. }
  4506. TEST(SendAPI, SimpleInterface_Online) {
  4507. Client cli("http://yahoo.com");
  4508. Request req;
  4509. req.method = "GET";
  4510. req.path = "/";
  4511. auto res = cli.send(req);
  4512. ASSERT_TRUE(res);
  4513. EXPECT_EQ(301, res->status);
  4514. }
  4515. TEST(ClientImplMethods, GetSocketTest) {
  4516. httplib::Server svr;
  4517. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4518. res.status = 200;
  4519. });
  4520. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4521. auto se = detail::scope_exit([&] {
  4522. svr.stop();
  4523. thread.join();
  4524. ASSERT_FALSE(svr.is_running());
  4525. });
  4526. svr.wait_until_ready();
  4527. {
  4528. httplib::Client cli("http://127.0.0.1:3333");
  4529. cli.set_keep_alive(true);
  4530. // Use the behavior of cpp-httplib of opening the connection
  4531. // only when the first request happens. If that changes,
  4532. // this test would be obsolete.
  4533. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4534. // This also implicitly tests the server. But other tests would fail much
  4535. // earlier than this one to be considered.
  4536. auto res = cli.Get("/");
  4537. ASSERT_TRUE(res);
  4538. EXPECT_EQ(200, res->status);
  4539. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4540. }
  4541. }
  4542. // Disabled due to out-of-memory problem on GitHub Actions
  4543. #ifdef _WIN64
  4544. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4545. // allocate content size larger than 2GB in memory
  4546. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4547. char *content = (char *)malloc(content_size);
  4548. ASSERT_TRUE(content);
  4549. Server svr;
  4550. svr.Get("/foo",
  4551. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  4552. res.set_content(content, content_size, "application/octet-stream");
  4553. });
  4554. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. listen_thread.join();
  4558. if (content) free(content);
  4559. ASSERT_FALSE(svr.is_running());
  4560. });
  4561. svr.wait_until_ready();
  4562. Client cli(HOST, PORT);
  4563. auto res = cli.Get("/foo");
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(200, res->status);
  4566. EXPECT_EQ(content_size, res->body.length());
  4567. }
  4568. #endif
  4569. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4570. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4571. Client cli("http://yahoo.com");
  4572. auto res = cli.Get("/");
  4573. ASSERT_TRUE(res);
  4574. EXPECT_EQ(301, res->status);
  4575. cli.set_follow_location(true);
  4576. res = cli.Get("/");
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(200, res->status);
  4579. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4580. }
  4581. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4582. Client cli("https://yahoo.com");
  4583. auto res = cli.Get("/");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(301, res->status);
  4586. cli.set_follow_location(true);
  4587. res = cli.Get("/");
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(200, res->status);
  4590. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4591. }
  4592. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4593. Client cli("https://yahoo.com");
  4594. auto res = cli.Get("/");
  4595. ASSERT_TRUE(res);
  4596. ASSERT_FALSE(!res);
  4597. ASSERT_TRUE(res);
  4598. ASSERT_FALSE(res == nullptr);
  4599. ASSERT_TRUE(res != nullptr);
  4600. EXPECT_EQ(Error::Success, res.error());
  4601. EXPECT_EQ(301, res.value().status);
  4602. EXPECT_EQ(301, (*res).status);
  4603. EXPECT_EQ(301, res->status);
  4604. cli.set_follow_location(true);
  4605. res = cli.Get("/");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(Error::Success, res.error());
  4608. EXPECT_EQ(200, res.value().status);
  4609. EXPECT_EQ(200, (*res).status);
  4610. EXPECT_EQ(200, res->status);
  4611. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4612. }
  4613. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4614. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4615. Client cli("https://cdnjs.cloudflare.com");
  4616. auto res =
  4617. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4618. ASSERT_TRUE(res);
  4619. EXPECT_EQ(200, res->status);
  4620. EXPECT_EQ(287630U, res->body.size());
  4621. EXPECT_EQ("application/javascript; charset=utf-8",
  4622. res->get_header_value("Content-Type"));
  4623. }
  4624. #endif
  4625. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4626. Client cli("https://nghttp2.org");
  4627. cli.set_follow_location(true);
  4628. auto res =
  4629. cli.Get("/httpbin/"
  4630. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(200, res->status);
  4633. }
  4634. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4635. Client cli("https://nghttp2.org");
  4636. cli.set_follow_location(true);
  4637. Params params;
  4638. params.emplace("url", "http://www.google.com");
  4639. params.emplace("status_code", "302");
  4640. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4641. ASSERT_TRUE(res);
  4642. EXPECT_EQ(200, res->status);
  4643. }
  4644. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4645. Client cli("https://nghttp2.org");
  4646. cli.set_follow_location(true);
  4647. Params params;
  4648. params.emplace("url", "http://www.google.com");
  4649. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(200, res->status);
  4652. }
  4653. TEST(HttpToHttpsRedirectTest, CertFile) {
  4654. Server svr;
  4655. ASSERT_TRUE(svr.is_valid());
  4656. svr.Get("/index", [&](const Request &, Response &res) {
  4657. res.set_redirect("https://127.0.0.1:1235/index");
  4658. svr.stop();
  4659. });
  4660. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4661. ASSERT_TRUE(ssl_svr.is_valid());
  4662. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4663. res.set_content("test", "text/plain");
  4664. ssl_svr.stop();
  4665. });
  4666. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4667. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4668. auto se = detail::scope_exit([&] {
  4669. t2.join();
  4670. t.join();
  4671. ASSERT_FALSE(svr.is_running());
  4672. });
  4673. svr.wait_until_ready();
  4674. ssl_svr.wait_until_ready();
  4675. Client cli("127.0.0.1", PORT);
  4676. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4677. cli.enable_server_certificate_verification(true);
  4678. cli.set_follow_location(true);
  4679. cli.set_connection_timeout(30);
  4680. auto res = cli.Get("/index");
  4681. ASSERT_TRUE(res);
  4682. ASSERT_EQ(200, res->status);
  4683. }
  4684. TEST(MultipartFormDataTest, LargeData) {
  4685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4686. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4687. const ContentReader &content_reader) {
  4688. if (req.is_multipart_form_data()) {
  4689. MultipartFormDataItems files;
  4690. content_reader(
  4691. [&](const MultipartFormData &file) {
  4692. files.push_back(file);
  4693. return true;
  4694. },
  4695. [&](const char *data, size_t data_length) {
  4696. files.back().content.append(data, data_length);
  4697. return true;
  4698. });
  4699. EXPECT_TRUE(std::string(files[0].name) == "document");
  4700. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4701. EXPECT_TRUE(files[0].filename == "2MB_data");
  4702. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4703. EXPECT_TRUE(files[1].name == "hello");
  4704. EXPECT_TRUE(files[1].content == "world");
  4705. EXPECT_TRUE(files[1].filename == "");
  4706. EXPECT_TRUE(files[1].content_type == "");
  4707. } else {
  4708. std::string body;
  4709. content_reader([&](const char *data, size_t data_length) {
  4710. body.append(data, data_length);
  4711. return true;
  4712. });
  4713. }
  4714. });
  4715. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4716. auto se = detail::scope_exit([&] {
  4717. svr.stop();
  4718. t.join();
  4719. ASSERT_FALSE(svr.is_running());
  4720. });
  4721. svr.wait_until_ready();
  4722. {
  4723. std::string data(1024 * 1024 * 2, '.');
  4724. std::stringstream buffer;
  4725. buffer << data;
  4726. Client cli("https://localhost:8080");
  4727. cli.enable_server_certificate_verification(false);
  4728. MultipartFormDataItems items{
  4729. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4730. {"hello", "world", "", ""},
  4731. };
  4732. auto res = cli.Post("/post", items);
  4733. ASSERT_TRUE(res);
  4734. ASSERT_EQ(200, res->status);
  4735. }
  4736. }
  4737. TEST(MultipartFormDataTest, DataProviderItems) {
  4738. std::random_device seed_gen;
  4739. std::mt19937 random(seed_gen());
  4740. std::string rand1;
  4741. rand1.resize(1000);
  4742. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4743. std::string rand2;
  4744. rand2.resize(3000);
  4745. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4747. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4748. const ContentReader &content_reader) {
  4749. ASSERT_FALSE(req.is_multipart_form_data());
  4750. std::string body;
  4751. content_reader([&](const char *data, size_t data_length) {
  4752. body.append(data, data_length);
  4753. return true;
  4754. });
  4755. EXPECT_EQ(body, "");
  4756. });
  4757. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4758. const ContentReader &content_reader) {
  4759. ASSERT_TRUE(req.is_multipart_form_data());
  4760. MultipartFormDataItems files;
  4761. content_reader(
  4762. [&](const MultipartFormData &file) {
  4763. files.push_back(file);
  4764. return true;
  4765. },
  4766. [&](const char *data, size_t data_length) {
  4767. files.back().content.append(data, data_length);
  4768. return true;
  4769. });
  4770. ASSERT_TRUE(files.size() == 2);
  4771. EXPECT_EQ(std::string(files[0].name), "name1");
  4772. EXPECT_EQ(files[0].content, "Testing123");
  4773. EXPECT_EQ(files[0].filename, "filename1");
  4774. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4775. EXPECT_EQ(files[1].name, "name2");
  4776. EXPECT_EQ(files[1].content, "Testing456");
  4777. EXPECT_EQ(files[1].filename, "");
  4778. EXPECT_EQ(files[1].content_type, "");
  4779. });
  4780. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4781. const ContentReader &content_reader) {
  4782. ASSERT_TRUE(req.is_multipart_form_data());
  4783. MultipartFormDataItems files;
  4784. content_reader(
  4785. [&](const MultipartFormData &file) {
  4786. files.push_back(file);
  4787. return true;
  4788. },
  4789. [&](const char *data, size_t data_length) {
  4790. files.back().content.append(data, data_length);
  4791. return true;
  4792. });
  4793. ASSERT_TRUE(files.size() == 2);
  4794. EXPECT_EQ(files[0].name, "name3");
  4795. EXPECT_EQ(files[0].content, rand1);
  4796. EXPECT_EQ(files[0].filename, "filename3");
  4797. EXPECT_EQ(files[0].content_type, "");
  4798. EXPECT_EQ(files[1].name, "name4");
  4799. EXPECT_EQ(files[1].content, rand2);
  4800. EXPECT_EQ(files[1].filename, "filename4");
  4801. EXPECT_EQ(files[1].content_type, "");
  4802. });
  4803. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4804. const ContentReader &content_reader) {
  4805. ASSERT_TRUE(req.is_multipart_form_data());
  4806. MultipartFormDataItems files;
  4807. content_reader(
  4808. [&](const MultipartFormData &file) {
  4809. files.push_back(file);
  4810. return true;
  4811. },
  4812. [&](const char *data, size_t data_length) {
  4813. files.back().content.append(data, data_length);
  4814. return true;
  4815. });
  4816. ASSERT_TRUE(files.size() == 4);
  4817. EXPECT_EQ(std::string(files[0].name), "name1");
  4818. EXPECT_EQ(files[0].content, "Testing123");
  4819. EXPECT_EQ(files[0].filename, "filename1");
  4820. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4821. EXPECT_EQ(files[1].name, "name2");
  4822. EXPECT_EQ(files[1].content, "Testing456");
  4823. EXPECT_EQ(files[1].filename, "");
  4824. EXPECT_EQ(files[1].content_type, "");
  4825. EXPECT_EQ(files[2].name, "name3");
  4826. EXPECT_EQ(files[2].content, rand1);
  4827. EXPECT_EQ(files[2].filename, "filename3");
  4828. EXPECT_EQ(files[2].content_type, "");
  4829. EXPECT_EQ(files[3].name, "name4");
  4830. EXPECT_EQ(files[3].content, rand2);
  4831. EXPECT_EQ(files[3].filename, "filename4");
  4832. EXPECT_EQ(files[3].content_type, "");
  4833. });
  4834. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4835. auto se = detail::scope_exit([&] {
  4836. svr.stop();
  4837. t.join();
  4838. ASSERT_FALSE(svr.is_running());
  4839. });
  4840. svr.wait_until_ready();
  4841. {
  4842. Client cli("https://localhost:8080");
  4843. cli.enable_server_certificate_verification(false);
  4844. MultipartFormDataItems items{
  4845. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4846. {"name2", "Testing456", "", ""}, // not a file
  4847. };
  4848. {
  4849. auto res = cli.Post("/post-none", {}, {}, {});
  4850. ASSERT_TRUE(res);
  4851. ASSERT_EQ(200, res->status);
  4852. }
  4853. MultipartFormDataProviderItems providers;
  4854. {
  4855. auto res =
  4856. cli.Post("/post-items", {}, items, providers); // empty providers
  4857. ASSERT_TRUE(res);
  4858. ASSERT_EQ(200, res->status);
  4859. }
  4860. providers.push_back({"name3",
  4861. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4862. // test the offset is given correctly at each step
  4863. if (!offset)
  4864. sink.os.write(rand1.data(), 30);
  4865. else if (offset == 30)
  4866. sink.os.write(rand1.data() + 30, 300);
  4867. else if (offset == 330)
  4868. sink.os.write(rand1.data() + 330, 670);
  4869. else if (offset == rand1.size())
  4870. sink.done();
  4871. return true;
  4872. },
  4873. "filename3",
  4874. {}});
  4875. providers.push_back({"name4",
  4876. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4877. // test the offset is given correctly at each step
  4878. if (!offset)
  4879. sink.os.write(rand2.data(), 2000);
  4880. else if (offset == 2000)
  4881. sink.os.write(rand2.data() + 2000, 1);
  4882. else if (offset == 2001)
  4883. sink.os.write(rand2.data() + 2001, 999);
  4884. else if (offset == rand2.size())
  4885. sink.done();
  4886. return true;
  4887. },
  4888. "filename4",
  4889. {}});
  4890. {
  4891. auto res = cli.Post("/post-providers", {}, {}, providers);
  4892. ASSERT_TRUE(res);
  4893. ASSERT_EQ(200, res->status);
  4894. }
  4895. {
  4896. auto res = cli.Post("/post-both", {}, items, providers);
  4897. ASSERT_TRUE(res);
  4898. ASSERT_EQ(200, res->status);
  4899. }
  4900. }
  4901. }
  4902. TEST(MultipartFormDataTest, BadHeader) {
  4903. Server svr;
  4904. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4905. res.set_content("ok", "text/plain");
  4906. });
  4907. thread t = thread([&] { svr.listen(HOST, PORT); });
  4908. auto se = detail::scope_exit([&] {
  4909. svr.stop();
  4910. t.join();
  4911. ASSERT_FALSE(svr.is_running());
  4912. });
  4913. svr.wait_until_ready();
  4914. const std::string body =
  4915. "This is the preamble. It is to be ignored, though it\r\n"
  4916. "is a handy place for composition agents to include an\r\n"
  4917. "explanatory note to non-MIME conformant readers.\r\n"
  4918. "\r\n"
  4919. "\r\n"
  4920. "--simple boundary\r\n"
  4921. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4922. ": BAD...\r\n"
  4923. "\r\n"
  4924. "value1\r\n"
  4925. "--simple boundary\r\n"
  4926. "Content-Disposition: form-data; name=\"field2\"; "
  4927. "filename=\"example.txt\"\r\n"
  4928. "\r\n"
  4929. "value2\r\n"
  4930. "--simple boundary--\r\n"
  4931. "This is the epilogue. It is also to be ignored.\r\n";
  4932. std::string content_type =
  4933. R"(multipart/form-data; boundary="simple boundary")";
  4934. Client cli(HOST, PORT);
  4935. auto res = cli.Post("/post", body, content_type.c_str());
  4936. ASSERT_TRUE(res);
  4937. EXPECT_EQ(400, res->status);
  4938. }
  4939. TEST(MultipartFormDataTest, WithPreamble) {
  4940. Server svr;
  4941. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4942. res.set_content("ok", "text/plain");
  4943. });
  4944. thread t = thread([&] { svr.listen(HOST, PORT); });
  4945. auto se = detail::scope_exit([&] {
  4946. svr.stop();
  4947. t.join();
  4948. ASSERT_FALSE(svr.is_running());
  4949. });
  4950. svr.wait_until_ready();
  4951. const std::string body =
  4952. "This is the preamble. It is to be ignored, though it\r\n"
  4953. "is a handy place for composition agents to include an\r\n"
  4954. "explanatory note to non-MIME conformant readers.\r\n"
  4955. "\r\n"
  4956. "\r\n"
  4957. "--simple boundary\r\n"
  4958. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4959. "\r\n"
  4960. "value1\r\n"
  4961. "--simple boundary\r\n"
  4962. "Content-Disposition: form-data; name=\"field2\"; "
  4963. "filename=\"example.txt\"\r\n"
  4964. "\r\n"
  4965. "value2\r\n"
  4966. "--simple boundary--\r\n"
  4967. "This is the epilogue. It is also to be ignored.\r\n";
  4968. std::string content_type =
  4969. R"(multipart/form-data; boundary="simple boundary")";
  4970. Client cli(HOST, PORT);
  4971. auto res = cli.Post("/post", body, content_type.c_str());
  4972. ASSERT_TRUE(res);
  4973. EXPECT_EQ(200, res->status);
  4974. }
  4975. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4977. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4978. const ContentReader &content_reader) {
  4979. if (req.is_multipart_form_data()) {
  4980. MultipartFormDataItems files;
  4981. content_reader(
  4982. [&](const MultipartFormData &file) {
  4983. files.push_back(file);
  4984. return true;
  4985. },
  4986. [&](const char *data, size_t data_length) {
  4987. files.back().content.append(data, data_length);
  4988. return true;
  4989. });
  4990. EXPECT_TRUE(std::string(files[0].name) == "document");
  4991. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4992. EXPECT_TRUE(files[0].filename == "2MB_data");
  4993. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4994. EXPECT_TRUE(files[1].name == "hello");
  4995. EXPECT_TRUE(files[1].content == "world");
  4996. EXPECT_TRUE(files[1].filename == "");
  4997. EXPECT_TRUE(files[1].content_type == "");
  4998. } else {
  4999. std::string body;
  5000. content_reader([&](const char *data, size_t data_length) {
  5001. body.append(data, data_length);
  5002. return true;
  5003. });
  5004. }
  5005. });
  5006. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5007. auto se = detail::scope_exit([&] {
  5008. svr.stop();
  5009. t.join();
  5010. ASSERT_FALSE(svr.is_running());
  5011. });
  5012. svr.wait_until_ready();
  5013. {
  5014. std::string data(1024 * 1024 * 2, '.');
  5015. std::stringstream buffer;
  5016. buffer << data;
  5017. Client cli("https://localhost:8080");
  5018. cli.enable_server_certificate_verification(false);
  5019. MultipartFormDataItems items{
  5020. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5021. {"hello", "world", "", ""},
  5022. };
  5023. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5024. ASSERT_TRUE(res);
  5025. ASSERT_EQ(200, res->status);
  5026. }
  5027. }
  5028. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5029. std::string data(1024 * 1024 * 2, '&');
  5030. std::stringstream buffer;
  5031. buffer << data;
  5032. Client cli("https://localhost:8080");
  5033. MultipartFormDataItems items{
  5034. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5035. {"hello", "world", "", ""},
  5036. };
  5037. for (const char &c : " \t\r\n") {
  5038. auto res =
  5039. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5040. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5041. ASSERT_FALSE(res);
  5042. }
  5043. }
  5044. TEST(MultipartFormDataTest, PutFormData) {
  5045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5046. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5047. const ContentReader &content_reader) {
  5048. if (req.is_multipart_form_data()) {
  5049. MultipartFormDataItems files;
  5050. content_reader(
  5051. [&](const MultipartFormData &file) {
  5052. files.push_back(file);
  5053. return true;
  5054. },
  5055. [&](const char *data, size_t data_length) {
  5056. files.back().content.append(data, data_length);
  5057. return true;
  5058. });
  5059. EXPECT_TRUE(std::string(files[0].name) == "document");
  5060. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5061. EXPECT_TRUE(files[0].filename == "2MB_data");
  5062. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5063. EXPECT_TRUE(files[1].name == "hello");
  5064. EXPECT_TRUE(files[1].content == "world");
  5065. EXPECT_TRUE(files[1].filename == "");
  5066. EXPECT_TRUE(files[1].content_type == "");
  5067. } else {
  5068. std::string body;
  5069. content_reader([&](const char *data, size_t data_length) {
  5070. body.append(data, data_length);
  5071. return true;
  5072. });
  5073. }
  5074. });
  5075. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5076. auto se = detail::scope_exit([&] {
  5077. svr.stop();
  5078. t.join();
  5079. ASSERT_FALSE(svr.is_running());
  5080. });
  5081. svr.wait_until_ready();
  5082. {
  5083. std::string data(1024 * 1024 * 2, '&');
  5084. std::stringstream buffer;
  5085. buffer << data;
  5086. Client cli("https://localhost:8080");
  5087. cli.enable_server_certificate_verification(false);
  5088. MultipartFormDataItems items{
  5089. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5090. {"hello", "world", "", ""},
  5091. };
  5092. auto res = cli.Put("/put", items);
  5093. ASSERT_TRUE(res);
  5094. ASSERT_EQ(200, res->status);
  5095. }
  5096. }
  5097. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5099. svr.Put("/put_customboundary",
  5100. [&](const Request &req, const Response & /*res*/,
  5101. const ContentReader &content_reader) {
  5102. if (req.is_multipart_form_data()) {
  5103. MultipartFormDataItems files;
  5104. content_reader(
  5105. [&](const MultipartFormData &file) {
  5106. files.push_back(file);
  5107. return true;
  5108. },
  5109. [&](const char *data, size_t data_length) {
  5110. files.back().content.append(data, data_length);
  5111. return true;
  5112. });
  5113. EXPECT_TRUE(std::string(files[0].name) == "document");
  5114. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5115. EXPECT_TRUE(files[0].filename == "2MB_data");
  5116. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5117. EXPECT_TRUE(files[1].name == "hello");
  5118. EXPECT_TRUE(files[1].content == "world");
  5119. EXPECT_TRUE(files[1].filename == "");
  5120. EXPECT_TRUE(files[1].content_type == "");
  5121. } else {
  5122. std::string body;
  5123. content_reader([&](const char *data, size_t data_length) {
  5124. body.append(data, data_length);
  5125. return true;
  5126. });
  5127. }
  5128. });
  5129. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5130. auto se = detail::scope_exit([&] {
  5131. svr.stop();
  5132. t.join();
  5133. ASSERT_FALSE(svr.is_running());
  5134. });
  5135. svr.wait_until_ready();
  5136. {
  5137. std::string data(1024 * 1024 * 2, '&');
  5138. std::stringstream buffer;
  5139. buffer << data;
  5140. Client cli("https://localhost:8080");
  5141. cli.enable_server_certificate_verification(false);
  5142. MultipartFormDataItems items{
  5143. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5144. {"hello", "world", "", ""},
  5145. };
  5146. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5147. ASSERT_TRUE(res);
  5148. ASSERT_EQ(200, res->status);
  5149. }
  5150. }
  5151. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5152. std::string data(1024 * 1024 * 2, '&');
  5153. std::stringstream buffer;
  5154. buffer << data;
  5155. Client cli("https://localhost:8080");
  5156. cli.enable_server_certificate_verification(false);
  5157. MultipartFormDataItems items{
  5158. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5159. {"hello", "world", "", ""},
  5160. };
  5161. for (const char &c : " \t\r\n") {
  5162. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5163. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5164. ASSERT_FALSE(res);
  5165. }
  5166. }
  5167. TEST(MultipartFormDataTest, AlternateFilename) {
  5168. auto handled = false;
  5169. Server svr;
  5170. svr.Post("/test", [&](const Request &req, Response &res) {
  5171. ASSERT_EQ(3u, req.files.size());
  5172. auto it = req.files.begin();
  5173. ASSERT_EQ("file1", it->second.name);
  5174. ASSERT_EQ("A.txt", it->second.filename);
  5175. ASSERT_EQ("text/plain", it->second.content_type);
  5176. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5177. ++it;
  5178. ASSERT_EQ("file2", it->second.name);
  5179. ASSERT_EQ("a.html", it->second.filename);
  5180. ASSERT_EQ("text/html", it->second.content_type);
  5181. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5182. it->second.content);
  5183. ++it;
  5184. ASSERT_EQ("text", it->second.name);
  5185. ASSERT_EQ("", it->second.filename);
  5186. ASSERT_EQ("", it->second.content_type);
  5187. ASSERT_EQ("text default", it->second.content);
  5188. res.set_content("ok", "text/plain");
  5189. handled = true;
  5190. });
  5191. thread t = thread([&] { svr.listen(HOST, PORT); });
  5192. auto se = detail::scope_exit([&] {
  5193. svr.stop();
  5194. t.join();
  5195. ASSERT_FALSE(svr.is_running());
  5196. ASSERT_TRUE(handled);
  5197. });
  5198. svr.wait_until_ready();
  5199. auto req = "POST /test HTTP/1.1\r\n"
  5200. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5201. "Content-Length: 399\r\n"
  5202. "\r\n"
  5203. "----------\r\n"
  5204. "Content-Disposition: form-data; name=\"text\"\r\n"
  5205. "\r\n"
  5206. "text default\r\n"
  5207. "----------\r\n"
  5208. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  5209. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5210. "Content-Type: text/plain\r\n"
  5211. "\r\n"
  5212. "Content of a.txt.\r\n"
  5213. "\r\n"
  5214. "----------\r\n"
  5215. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5216. "\"a.html\"\r\n"
  5217. "Content-Type: text/html\r\n"
  5218. "\r\n"
  5219. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5220. "\r\n"
  5221. "------------\r\n";
  5222. ASSERT_TRUE(send_request(1, req));
  5223. }
  5224. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5225. auto handled = false;
  5226. Server svr;
  5227. svr.Post("/test", [&](const Request &req, Response &) {
  5228. ASSERT_EQ(2u, req.files.size());
  5229. auto it = req.files.begin();
  5230. ASSERT_EQ("text1", it->second.name);
  5231. ASSERT_EQ("text1", it->second.content);
  5232. ++it;
  5233. ASSERT_EQ("text2", it->second.name);
  5234. ASSERT_EQ("text2", it->second.content);
  5235. handled = true;
  5236. });
  5237. thread t = thread([&] { svr.listen(HOST, PORT); });
  5238. auto se = detail::scope_exit([&] {
  5239. svr.stop();
  5240. t.join();
  5241. ASSERT_FALSE(svr.is_running());
  5242. ASSERT_TRUE(handled);
  5243. });
  5244. svr.wait_until_ready();
  5245. auto req = "POST /test HTTP/1.1\r\n"
  5246. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5247. "Content-Length: 146\r\n"
  5248. "\r\n----------\r\n"
  5249. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5250. "\r\n"
  5251. "text1"
  5252. "\r\n----------\r\n"
  5253. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5254. "\r\n"
  5255. "text2"
  5256. "\r\n------------";
  5257. std::string resonse;
  5258. ASSERT_TRUE(send_request(1, req, &resonse));
  5259. ASSERT_EQ("200", resonse.substr(9, 3));
  5260. }
  5261. #endif
  5262. #ifndef _WIN32
  5263. class UnixSocketTest : public ::testing::Test {
  5264. protected:
  5265. void TearDown() override { std::remove(pathname_.c_str()); }
  5266. void client_GET(const std::string &addr) {
  5267. httplib::Client cli{addr};
  5268. cli.set_address_family(AF_UNIX);
  5269. ASSERT_TRUE(cli.is_valid());
  5270. const auto &result = cli.Get(pattern_);
  5271. ASSERT_TRUE(result) << "error: " << result.error();
  5272. const auto &resp = result.value();
  5273. EXPECT_EQ(resp.status, 200);
  5274. EXPECT_EQ(resp.body, content_);
  5275. }
  5276. const std::string pathname_{"./httplib-server.sock"};
  5277. const std::string pattern_{"/hi"};
  5278. const std::string content_{"Hello World!"};
  5279. };
  5280. TEST_F(UnixSocketTest, pathname) {
  5281. httplib::Server svr;
  5282. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5283. res.set_content(content_, "text/plain");
  5284. });
  5285. std::thread t{[&] {
  5286. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5287. }};
  5288. auto se = detail::scope_exit([&] {
  5289. svr.stop();
  5290. t.join();
  5291. ASSERT_FALSE(svr.is_running());
  5292. });
  5293. svr.wait_until_ready();
  5294. ASSERT_TRUE(svr.is_running());
  5295. client_GET(pathname_);
  5296. }
  5297. #if defined(__linux__) || \
  5298. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5299. TEST_F(UnixSocketTest, PeerPid) {
  5300. httplib::Server svr;
  5301. std::string remote_port_val;
  5302. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5303. res.set_content(content_, "text/plain");
  5304. remote_port_val = req.get_header_value("REMOTE_PORT");
  5305. });
  5306. std::thread t{[&] {
  5307. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5308. }};
  5309. auto se = detail::scope_exit([&] {
  5310. svr.stop();
  5311. t.join();
  5312. ASSERT_FALSE(svr.is_running());
  5313. });
  5314. svr.wait_until_ready();
  5315. ASSERT_TRUE(svr.is_running());
  5316. client_GET(pathname_);
  5317. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5318. }
  5319. #endif
  5320. #ifdef __linux__
  5321. TEST_F(UnixSocketTest, abstract) {
  5322. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5323. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5324. httplib::Server svr;
  5325. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5326. res.set_content(content_, "text/plain");
  5327. });
  5328. std::thread t{[&] {
  5329. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5330. }};
  5331. auto se = detail::scope_exit([&] {
  5332. svr.stop();
  5333. t.join();
  5334. ASSERT_FALSE(svr.is_running());
  5335. });
  5336. svr.wait_until_ready();
  5337. ASSERT_TRUE(svr.is_running());
  5338. client_GET(abstract_addr);
  5339. }
  5340. #endif
  5341. TEST(SocketStream, is_writable_UNIX) {
  5342. int fds[2];
  5343. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5344. const auto asSocketStream = [&](socket_t fd,
  5345. std::function<bool(Stream &)> func) {
  5346. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5347. };
  5348. asSocketStream(fds[0], [&](Stream &s0) {
  5349. EXPECT_EQ(s0.socket(), fds[0]);
  5350. EXPECT_TRUE(s0.is_writable());
  5351. EXPECT_EQ(0, close(fds[1]));
  5352. EXPECT_FALSE(s0.is_writable());
  5353. return true;
  5354. });
  5355. EXPECT_EQ(0, close(fds[0]));
  5356. }
  5357. TEST(SocketStream, is_writable_INET) {
  5358. sockaddr_in addr;
  5359. memset(&addr, 0, sizeof(addr));
  5360. addr.sin_family = AF_INET;
  5361. addr.sin_port = htons(PORT + 1);
  5362. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5363. int disconnected_svr_sock = -1;
  5364. std::thread svr{[&] {
  5365. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5366. ASSERT_LE(0, s);
  5367. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5368. ASSERT_EQ(0, listen(s, 1));
  5369. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5370. ASSERT_EQ(0, close(s));
  5371. }};
  5372. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5373. std::thread cli{[&] {
  5374. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5375. ASSERT_LE(0, s);
  5376. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5377. ASSERT_EQ(0, close(s));
  5378. }};
  5379. cli.join();
  5380. svr.join();
  5381. ASSERT_NE(disconnected_svr_sock, -1);
  5382. const auto asSocketStream = [&](socket_t fd,
  5383. std::function<bool(Stream &)> func) {
  5384. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5385. };
  5386. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5387. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5388. EXPECT_FALSE(ss.is_writable());
  5389. return true;
  5390. });
  5391. ASSERT_EQ(0, close(disconnected_svr_sock));
  5392. }
  5393. #endif // #ifndef _WIN32
  5394. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5395. static constexpr unsigned int number_of_task{1000000};
  5396. std::atomic_uint count{0};
  5397. std::unique_ptr<TaskQueue> task_queue{
  5398. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5399. for (unsigned int i = 0; i < number_of_task; ++i) {
  5400. task_queue->enqueue(
  5401. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5402. }
  5403. EXPECT_NO_THROW(task_queue->shutdown());
  5404. EXPECT_EQ(number_of_task, count.load());
  5405. }
  5406. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5407. Server svr;
  5408. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5409. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5410. });
  5411. svr.Get("/hello", [](const Request &req, Response &res) {
  5412. res.set_content(req.get_param_value("key"), "text/plain");
  5413. });
  5414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5415. auto se = detail::scope_exit([&] {
  5416. svr.stop();
  5417. thread.join();
  5418. ASSERT_FALSE(svr.is_running());
  5419. });
  5420. svr.wait_until_ready();
  5421. {
  5422. Client cli(HOST, PORT);
  5423. cli.set_follow_location(true);
  5424. auto res = cli.Get("/");
  5425. ASSERT_TRUE(res);
  5426. EXPECT_EQ(200, res->status);
  5427. EXPECT_EQ("val&key2=val2", res->body);
  5428. }
  5429. }
  5430. TEST(VulnerabilityTest, CRLFInjection) {
  5431. Server svr;
  5432. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  5433. res.set_content("Hello 1", "text/plain");
  5434. });
  5435. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  5436. res.set_content("Hello 2", "text/plain");
  5437. });
  5438. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  5439. res.set_content("Hello 3", "text/plain");
  5440. });
  5441. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  5442. res.set_content("Hello 4", "text/plain");
  5443. });
  5444. svr.set_logger([](const Request &req, const Response & /*res*/) {
  5445. for (const auto &x : req.headers) {
  5446. auto key = x.first;
  5447. EXPECT_STRNE("evil", key.c_str());
  5448. }
  5449. });
  5450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5451. auto se = detail::scope_exit([&] {
  5452. svr.stop();
  5453. thread.join();
  5454. ASSERT_FALSE(svr.is_running());
  5455. });
  5456. svr.wait_until_ready();
  5457. {
  5458. Client cli(HOST, PORT);
  5459. cli.Post("/test1", "A=B",
  5460. "application/x-www-form-urlencoded\r\nevil: hello1");
  5461. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  5462. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  5463. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  5464. }
  5465. }
  5466. TEST(PathParamsTest, StaticMatch) {
  5467. const auto pattern = "/users/all";
  5468. detail::PathParamsMatcher matcher(pattern);
  5469. Request request;
  5470. request.path = "/users/all";
  5471. ASSERT_TRUE(matcher.match(request));
  5472. std::unordered_map<std::string, std::string> expected_params = {};
  5473. EXPECT_EQ(request.path_params, expected_params);
  5474. }
  5475. TEST(PathParamsTest, StaticMismatch) {
  5476. const auto pattern = "/users/all";
  5477. detail::PathParamsMatcher matcher(pattern);
  5478. Request request;
  5479. request.path = "/users/1";
  5480. ASSERT_FALSE(matcher.match(request));
  5481. }
  5482. TEST(PathParamsTest, SingleParamInTheMiddle) {
  5483. const auto pattern = "/users/:id/subscriptions";
  5484. detail::PathParamsMatcher matcher(pattern);
  5485. Request request;
  5486. request.path = "/users/42/subscriptions";
  5487. ASSERT_TRUE(matcher.match(request));
  5488. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5489. EXPECT_EQ(request.path_params, expected_params);
  5490. }
  5491. TEST(PathParamsTest, SingleParamInTheEnd) {
  5492. const auto pattern = "/users/:id";
  5493. detail::PathParamsMatcher matcher(pattern);
  5494. Request request;
  5495. request.path = "/users/24";
  5496. ASSERT_TRUE(matcher.match(request));
  5497. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  5498. EXPECT_EQ(request.path_params, expected_params);
  5499. }
  5500. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  5501. const auto pattern = "/users/:id/";
  5502. detail::PathParamsMatcher matcher(pattern);
  5503. Request request;
  5504. request.path = "/users/42/";
  5505. ASSERT_TRUE(matcher.match(request));
  5506. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5507. EXPECT_EQ(request.path_params, expected_params);
  5508. }
  5509. TEST(PathParamsTest, EmptyParam) {
  5510. const auto pattern = "/users/:id/";
  5511. detail::PathParamsMatcher matcher(pattern);
  5512. Request request;
  5513. request.path = "/users//";
  5514. ASSERT_TRUE(matcher.match(request));
  5515. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  5516. EXPECT_EQ(request.path_params, expected_params);
  5517. }
  5518. TEST(PathParamsTest, FragmentMismatch) {
  5519. const auto pattern = "/users/:id/";
  5520. detail::PathParamsMatcher matcher(pattern);
  5521. Request request;
  5522. request.path = "/admins/24/";
  5523. ASSERT_FALSE(matcher.match(request));
  5524. }
  5525. TEST(PathParamsTest, ExtraFragments) {
  5526. const auto pattern = "/users/:id";
  5527. detail::PathParamsMatcher matcher(pattern);
  5528. Request request;
  5529. request.path = "/users/42/subscriptions";
  5530. ASSERT_FALSE(matcher.match(request));
  5531. }
  5532. TEST(PathParamsTest, MissingTrailingParam) {
  5533. const auto pattern = "/users/:id";
  5534. detail::PathParamsMatcher matcher(pattern);
  5535. Request request;
  5536. request.path = "/users";
  5537. ASSERT_FALSE(matcher.match(request));
  5538. }
  5539. TEST(PathParamsTest, MissingParamInTheMiddle) {
  5540. const auto pattern = "/users/:id/subscriptions";
  5541. detail::PathParamsMatcher matcher(pattern);
  5542. Request request;
  5543. request.path = "/users/subscriptions";
  5544. ASSERT_FALSE(matcher.match(request));
  5545. }
  5546. TEST(PathParamsTest, MultipleParams) {
  5547. const auto pattern = "/users/:userid/subscriptions/:subid";
  5548. detail::PathParamsMatcher matcher(pattern);
  5549. Request request;
  5550. request.path = "/users/42/subscriptions/2";
  5551. ASSERT_TRUE(matcher.match(request));
  5552. std::unordered_map<std::string, std::string> expected_params = {
  5553. {"userid", "42"}, {"subid", "2"}};
  5554. EXPECT_EQ(request.path_params, expected_params);
  5555. }
  5556. TEST(PathParamsTest, SequenceOfParams) {
  5557. const auto pattern = "/values/:x/:y/:z";
  5558. detail::PathParamsMatcher matcher(pattern);
  5559. Request request;
  5560. request.path = "/values/1/2/3";
  5561. ASSERT_TRUE(matcher.match(request));
  5562. std::unordered_map<std::string, std::string> expected_params = {
  5563. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  5564. EXPECT_EQ(request.path_params, expected_params);
  5565. }