test.cc 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774
  1. #include <httplib.h>
  2. #include <gtest/gtest.h>
  3. #include <atomic>
  4. #include <chrono>
  5. #include <future>
  6. #include <sstream>
  7. #include <stdexcept>
  8. #include <thread>
  9. #include <type_traits>
  10. #define SERVER_CERT_FILE "./cert.pem"
  11. #define SERVER_CERT2_FILE "./cert2.pem"
  12. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  13. #define CA_CERT_FILE "./ca-bundle.crt"
  14. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  15. #define CLIENT_CA_CERT_DIR "."
  16. #define CLIENT_CERT_FILE "./client.cert.pem"
  17. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  18. using namespace std;
  19. using namespace httplib;
  20. const char *HOST = "localhost";
  21. const int PORT = 1234;
  22. const string LONG_QUERY_VALUE = string(25000, '@');
  23. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  24. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  25. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  26. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  27. const char *key) {
  28. auto it = std::find_if(
  29. files.begin(), files.end(),
  30. [&](const MultipartFormData &file) { return file.name == key; });
  31. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  32. return *it;
  33. #else
  34. if (it != files.end()) { return *it; }
  35. throw std::runtime_error("invalid mulitpart form data name error");
  36. #endif
  37. }
  38. TEST(ConstructorTest, MoveConstructible) {
  39. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  40. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  41. }
  42. #ifdef _WIN32
  43. TEST(StartupTest, WSAStartup) {
  44. WSADATA wsaData;
  45. int ret = WSAStartup(0x0002, &wsaData);
  46. ASSERT_EQ(0, ret);
  47. }
  48. #endif
  49. TEST(DecodeURLTest, PercentCharacter) {
  50. EXPECT_EQ(
  51. detail::decode_url(
  52. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  53. false),
  54. R"(descrip=Gastos áéíóúñÑ 6)");
  55. }
  56. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  57. string unescapedCharacters = "-_.!~*'()";
  58. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  59. }
  60. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  61. string reservedCharacters = ";,/?:@&=+$";
  62. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  63. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  64. }
  65. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  66. string chineseCharacters = "中国語";
  67. string russianCharacters = "дом";
  68. string brazilianCharacters = "óculos";
  69. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  70. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  71. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  72. "%D0%B4%D0%BE%D0%BC");
  73. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  74. }
  75. TEST(TrimTests, TrimStringTests) {
  76. EXPECT_EQ("abc", detail::trim_copy("abc"));
  77. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  78. EXPECT_TRUE(detail::trim_copy("").empty());
  79. }
  80. TEST(SplitTest, ParseQueryString) {
  81. string s = "key1=val1&key2=val2&key3=val3";
  82. Params dic;
  83. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  84. [&](const char *b, const char *e) {
  85. string key, val;
  86. detail::split(b, e, '=', [&](const char *b, const char *e) {
  87. if (key.empty()) {
  88. key.assign(b, e);
  89. } else {
  90. val.assign(b, e);
  91. }
  92. });
  93. dic.emplace(key, val);
  94. });
  95. EXPECT_EQ("val1", dic.find("key1")->second);
  96. EXPECT_EQ("val2", dic.find("key2")->second);
  97. EXPECT_EQ("val3", dic.find("key3")->second);
  98. }
  99. TEST(SplitTest, ParseInvalidQueryTests) {
  100. {
  101. string s = " ";
  102. Params dict;
  103. detail::parse_query_text(s, dict);
  104. EXPECT_TRUE(dict.empty());
  105. }
  106. {
  107. string s = " = =";
  108. Params dict;
  109. detail::parse_query_text(s, dict);
  110. EXPECT_TRUE(dict.empty());
  111. }
  112. }
  113. TEST(ParseQueryTest, ParseQueryString) {
  114. string s = "key1=val1&key2=val2&key3=val3";
  115. Params dic;
  116. detail::parse_query_text(s, dic);
  117. EXPECT_EQ("val1", dic.find("key1")->second);
  118. EXPECT_EQ("val2", dic.find("key2")->second);
  119. EXPECT_EQ("val3", dic.find("key3")->second);
  120. }
  121. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  122. Params dic;
  123. EXPECT_EQ(detail::params_to_query_str(dic), "");
  124. dic.emplace("key1", "val1");
  125. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  126. dic.emplace("key2", "val2");
  127. dic.emplace("key3", "val3");
  128. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  129. }
  130. TEST(GetHeaderValueTest, DefaultValue) {
  131. Headers headers = {{"Dummy", "Dummy"}};
  132. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  133. EXPECT_STREQ("text/plain", val);
  134. }
  135. TEST(GetHeaderValueTest, DefaultValueInt) {
  136. Headers headers = {{"Dummy", "Dummy"}};
  137. auto val =
  138. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  139. EXPECT_EQ(100ull, val);
  140. }
  141. TEST(GetHeaderValueTest, RegularValue) {
  142. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  143. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  144. EXPECT_STREQ("text/html", val);
  145. }
  146. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  147. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  148. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  149. EXPECT_STREQ("text/html", val);
  150. }
  151. TEST(GetHeaderValueTest, SetContent) {
  152. Response res;
  153. res.set_content("html", "text/html");
  154. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  155. res.set_content("text", "text/plain");
  156. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  157. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  158. }
  159. TEST(GetHeaderValueTest, RegularValueInt) {
  160. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  161. auto val =
  162. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  163. EXPECT_EQ(100ull, val);
  164. }
  165. TEST(GetHeaderValueTest, Range) {
  166. {
  167. Headers headers = {make_range_header({{1, -1}})};
  168. auto val = detail::get_header_value(headers, "Range", 0, 0);
  169. EXPECT_STREQ("bytes=1-", val);
  170. }
  171. {
  172. Headers headers = {make_range_header({{-1, 1}})};
  173. auto val = detail::get_header_value(headers, "Range", 0, 0);
  174. EXPECT_STREQ("bytes=-1", val);
  175. }
  176. {
  177. Headers headers = {make_range_header({{1, 10}})};
  178. auto val = detail::get_header_value(headers, "Range", 0, 0);
  179. EXPECT_STREQ("bytes=1-10", val);
  180. }
  181. {
  182. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  183. auto val = detail::get_header_value(headers, "Range", 0, 0);
  184. EXPECT_STREQ("bytes=1-10, 100-", val);
  185. }
  186. {
  187. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  188. auto val = detail::get_header_value(headers, "Range", 0, 0);
  189. EXPECT_STREQ("bytes=1-10, 100-200", val);
  190. }
  191. {
  192. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  193. auto val = detail::get_header_value(headers, "Range", 0, 0);
  194. EXPECT_STREQ("bytes=0-0, -1", val);
  195. }
  196. }
  197. TEST(ParseHeaderValueTest, Range) {
  198. {
  199. Ranges ranges;
  200. auto ret = detail::parse_range_header("bytes=1-", ranges);
  201. EXPECT_TRUE(ret);
  202. EXPECT_EQ(1u, ranges.size());
  203. EXPECT_EQ(1u, ranges[0].first);
  204. EXPECT_EQ(-1, ranges[0].second);
  205. }
  206. {
  207. Ranges ranges;
  208. auto ret = detail::parse_range_header("bytes=-1", ranges);
  209. EXPECT_TRUE(ret);
  210. EXPECT_EQ(1u, ranges.size());
  211. EXPECT_EQ(-1, ranges[0].first);
  212. EXPECT_EQ(1u, ranges[0].second);
  213. }
  214. {
  215. Ranges ranges;
  216. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  217. EXPECT_TRUE(ret);
  218. EXPECT_EQ(1u, ranges.size());
  219. EXPECT_EQ(1u, ranges[0].first);
  220. EXPECT_EQ(10u, ranges[0].second);
  221. }
  222. {
  223. Ranges ranges;
  224. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  225. EXPECT_FALSE(ret);
  226. }
  227. {
  228. Ranges ranges;
  229. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  230. EXPECT_TRUE(ret);
  231. EXPECT_EQ(2u, ranges.size());
  232. EXPECT_EQ(1u, ranges[0].first);
  233. EXPECT_EQ(10u, ranges[0].second);
  234. EXPECT_EQ(100u, ranges[1].first);
  235. EXPECT_EQ(-1, ranges[1].second);
  236. }
  237. {
  238. Ranges ranges;
  239. auto ret =
  240. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  241. EXPECT_TRUE(ret);
  242. EXPECT_EQ(3u, ranges.size());
  243. EXPECT_EQ(1u, ranges[0].first);
  244. EXPECT_EQ(10u, ranges[0].second);
  245. EXPECT_EQ(100u, ranges[1].first);
  246. EXPECT_EQ(200u, ranges[1].second);
  247. EXPECT_EQ(300u, ranges[2].first);
  248. EXPECT_EQ(400u, ranges[2].second);
  249. }
  250. }
  251. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  252. Request req;
  253. req.set_header("Accept-Encoding", "gzip");
  254. Response res;
  255. res.set_header("Content-Type", "text/plain");
  256. auto ret = detail::encoding_type(req, res);
  257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  258. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  259. #else
  260. EXPECT_TRUE(ret == detail::EncodingType::None);
  261. #endif
  262. }
  263. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  264. Request req;
  265. req.set_header("Accept-Encoding", "gzip, deflate, br");
  266. Response res;
  267. res.set_header("Content-Type", "text/plain");
  268. auto ret = detail::encoding_type(req, res);
  269. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  270. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  271. #elif CPPHTTPLIB_ZLIB_SUPPORT
  272. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  273. #else
  274. EXPECT_TRUE(ret == detail::EncodingType::None);
  275. #endif
  276. }
  277. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  278. Request req;
  279. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  280. Response res;
  281. res.set_header("Content-Type", "text/plain");
  282. auto ret = detail::encoding_type(req, res);
  283. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  284. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  285. #elif CPPHTTPLIB_ZLIB_SUPPORT
  286. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  287. #else
  288. EXPECT_TRUE(ret == detail::EncodingType::None);
  289. #endif
  290. }
  291. TEST(BufferStreamTest, read) {
  292. detail::BufferStream strm1;
  293. Stream &strm = strm1;
  294. EXPECT_EQ(5, strm.write("hello"));
  295. char buf[512];
  296. EXPECT_EQ(2, strm.read(buf, 2));
  297. EXPECT_EQ('h', buf[0]);
  298. EXPECT_EQ('e', buf[1]);
  299. EXPECT_EQ(2, strm.read(buf, 2));
  300. EXPECT_EQ('l', buf[0]);
  301. EXPECT_EQ('l', buf[1]);
  302. EXPECT_EQ(1, strm.read(buf, 1));
  303. EXPECT_EQ('o', buf[0]);
  304. EXPECT_EQ(0, strm.read(buf, 1));
  305. }
  306. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  307. auto host = "www.httpwatch.com";
  308. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  309. auto port = 443;
  310. SSLClient cli(host, port);
  311. #else
  312. auto port = 80;
  313. Client cli(host, port);
  314. #endif
  315. cli.set_connection_timeout(2);
  316. auto res =
  317. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  318. ASSERT_TRUE(res);
  319. std::string out;
  320. detail::read_file("./image.jpg", out);
  321. EXPECT_EQ(200, res->status);
  322. EXPECT_EQ(out, res->body);
  323. }
  324. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  325. auto host = "www.httpwatch.com";
  326. auto ip = hosted_at(host);
  327. EXPECT_EQ("191.236.16.12", ip);
  328. std::vector<std::string> addrs;
  329. hosted_at(host, addrs);
  330. EXPECT_EQ(1u, addrs.size());
  331. }
  332. #if 0 // It depends on each test environment...
  333. TEST(HostnameToIPConversionTest, YouTube_Online) {
  334. auto host = "www.youtube.com";
  335. std::vector<std::string> addrs;
  336. hosted_at(host, addrs);
  337. EXPECT_EQ(20u, addrs.size());
  338. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  339. EXPECT_TRUE(it != addrs.end());
  340. }
  341. #endif
  342. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  343. auto host = "www.httpwatch.com";
  344. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  345. auto port = 443;
  346. SSLClient cli(host, port);
  347. #else
  348. auto port = 80;
  349. Client cli(host, port);
  350. #endif
  351. cli.set_connection_timeout(2);
  352. std::string body;
  353. auto res =
  354. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  355. [&](const char *data, size_t data_length) {
  356. body.append(data, data_length);
  357. return true;
  358. });
  359. ASSERT_TRUE(res);
  360. std::string out;
  361. detail::read_file("./image.jpg", out);
  362. EXPECT_EQ(200, res->status);
  363. EXPECT_EQ(out, body);
  364. }
  365. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  366. auto host = "www.httpwatch.com";
  367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  368. auto port = 443;
  369. SSLClient cli(host, port);
  370. #else
  371. auto port = 80;
  372. Client cli(host, port);
  373. #endif
  374. cli.set_connection_timeout(2);
  375. std::string body;
  376. auto res = cli.Get(
  377. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  378. [&](const Response &response) {
  379. EXPECT_EQ(200, response.status);
  380. return true;
  381. },
  382. [&](const char *data, size_t data_length) {
  383. body.append(data, data_length);
  384. return true;
  385. });
  386. ASSERT_TRUE(res);
  387. std::string out;
  388. detail::read_file("./image.jpg", out);
  389. EXPECT_EQ(200, res->status);
  390. EXPECT_EQ(out, body);
  391. }
  392. TEST(RangeTest, FromHTTPBin_Online) {
  393. auto host = "httpbin.org";
  394. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  395. auto port = 443;
  396. SSLClient cli(host, port);
  397. #else
  398. auto port = 80;
  399. Client cli(host, port);
  400. #endif
  401. cli.set_connection_timeout(5);
  402. {
  403. auto res = cli.Get("/range/32");
  404. ASSERT_TRUE(res);
  405. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  406. EXPECT_EQ(200, res->status);
  407. }
  408. {
  409. Headers headers = {make_range_header({{1, -1}})};
  410. auto res = cli.Get("/range/32", headers);
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  413. EXPECT_EQ(206, res->status);
  414. }
  415. {
  416. Headers headers = {make_range_header({{1, 10}})};
  417. auto res = cli.Get("/range/32", headers);
  418. ASSERT_TRUE(res);
  419. EXPECT_EQ("bcdefghijk", res->body);
  420. EXPECT_EQ(206, res->status);
  421. }
  422. {
  423. Headers headers = {make_range_header({{0, 31}})};
  424. auto res = cli.Get("/range/32", headers);
  425. ASSERT_TRUE(res);
  426. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  427. EXPECT_EQ(200, res->status);
  428. }
  429. {
  430. Headers headers = {make_range_header({{0, -1}})};
  431. auto res = cli.Get("/range/32", headers);
  432. ASSERT_TRUE(res);
  433. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  434. EXPECT_EQ(200, res->status);
  435. }
  436. {
  437. Headers headers = {make_range_header({{0, 32}})};
  438. auto res = cli.Get("/range/32", headers);
  439. ASSERT_TRUE(res);
  440. EXPECT_EQ(416, res->status);
  441. }
  442. }
  443. TEST(ConnectionErrorTest, InvalidHost) {
  444. auto host = "-abcde.com";
  445. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  446. auto port = 443;
  447. SSLClient cli(host, port);
  448. #else
  449. auto port = 80;
  450. Client cli(host, port);
  451. #endif
  452. cli.set_connection_timeout(std::chrono::seconds(2));
  453. auto res = cli.Get("/");
  454. ASSERT_TRUE(!res);
  455. EXPECT_EQ(Error::Connection, res.error());
  456. }
  457. TEST(ConnectionErrorTest, InvalidHost2) {
  458. auto host = "httpbin.org/";
  459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  460. SSLClient cli(host);
  461. #else
  462. Client cli(host);
  463. #endif
  464. cli.set_connection_timeout(std::chrono::seconds(2));
  465. auto res = cli.Get("/");
  466. ASSERT_TRUE(!res);
  467. EXPECT_EQ(Error::Connection, res.error());
  468. }
  469. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  470. auto host = "httpbin.org/";
  471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  472. SSLClient cli(host);
  473. #else
  474. Client cli(host);
  475. #endif
  476. cli.set_connection_timeout(std::chrono::seconds(2));
  477. auto res = cli.Get("/");
  478. ASSERT_TRUE(!res);
  479. stringstream s;
  480. s << "error code: " << res.error();
  481. EXPECT_EQ("error code: Connection (2)", s.str());
  482. }
  483. TEST(ConnectionErrorTest, InvalidPort) {
  484. auto host = "localhost";
  485. auto port = 44380;
  486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  487. SSLClient cli(host, port);
  488. #else
  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, Timeout) {
  497. auto host = "google.com";
  498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  499. auto port = 44380;
  500. SSLClient cli(host, port);
  501. #else
  502. auto port = 8080;
  503. Client cli(host, port);
  504. #endif
  505. cli.set_connection_timeout(std::chrono::seconds(2));
  506. auto res = cli.Get("/");
  507. ASSERT_TRUE(!res);
  508. EXPECT_TRUE(res.error() == Error::Connection);
  509. }
  510. TEST(CancelTest, NoCancel_Online) {
  511. auto host = "httpbin.org";
  512. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  513. auto port = 443;
  514. SSLClient cli(host, port);
  515. #else
  516. auto port = 80;
  517. Client cli(host, port);
  518. #endif
  519. cli.set_connection_timeout(std::chrono::seconds(5));
  520. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  521. ASSERT_TRUE(res);
  522. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  523. EXPECT_EQ(200, res->status);
  524. }
  525. TEST(CancelTest, WithCancelSmallPayload_Online) {
  526. auto host = "httpbin.org";
  527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  528. auto port = 443;
  529. SSLClient cli(host, port);
  530. #else
  531. auto port = 80;
  532. Client cli(host, port);
  533. #endif
  534. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  535. cli.set_connection_timeout(std::chrono::seconds(5));
  536. ASSERT_TRUE(!res);
  537. EXPECT_EQ(Error::Canceled, res.error());
  538. }
  539. TEST(CancelTest, WithCancelLargePayload_Online) {
  540. auto host = "httpbin.org";
  541. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  542. auto port = 443;
  543. SSLClient cli(host, port);
  544. #else
  545. auto port = 80;
  546. Client cli(host, port);
  547. #endif
  548. cli.set_connection_timeout(std::chrono::seconds(5));
  549. uint32_t count = 0;
  550. auto res = cli.Get("/range/65536",
  551. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  552. ASSERT_TRUE(!res);
  553. EXPECT_EQ(Error::Canceled, res.error());
  554. }
  555. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  556. auto host = "httpbin.org";
  557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  558. auto port = 443;
  559. SSLClient cli(host, port);
  560. #else
  561. auto port = 80;
  562. Client cli(host, port);
  563. #endif
  564. {
  565. auto res = cli.Get("/basic-auth/hello/world");
  566. ASSERT_TRUE(res);
  567. EXPECT_EQ(401, res->status);
  568. }
  569. {
  570. auto res = cli.Get("/basic-auth/hello/world",
  571. {make_basic_authentication_header("hello", "world")});
  572. ASSERT_TRUE(res);
  573. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  574. res->body);
  575. EXPECT_EQ(200, res->status);
  576. }
  577. {
  578. cli.set_basic_auth("hello", "world");
  579. auto res = cli.Get("/basic-auth/hello/world");
  580. ASSERT_TRUE(res);
  581. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  582. res->body);
  583. EXPECT_EQ(200, res->status);
  584. }
  585. {
  586. cli.set_basic_auth("hello", "bad");
  587. auto res = cli.Get("/basic-auth/hello/world");
  588. ASSERT_TRUE(res);
  589. EXPECT_EQ(401, res->status);
  590. }
  591. {
  592. cli.set_basic_auth("bad", "world");
  593. auto res = cli.Get("/basic-auth/hello/world");
  594. ASSERT_TRUE(res);
  595. EXPECT_EQ(401, res->status);
  596. }
  597. }
  598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  599. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  600. auto host = "httpbin.org";
  601. auto port = 443;
  602. SSLClient cli(host, port);
  603. {
  604. auto res = cli.Get("/digest-auth/auth/hello/world");
  605. ASSERT_TRUE(res);
  606. EXPECT_EQ(401, res->status);
  607. }
  608. {
  609. std::vector<std::string> paths = {
  610. "/digest-auth/auth/hello/world/MD5",
  611. "/digest-auth/auth/hello/world/SHA-256",
  612. "/digest-auth/auth/hello/world/SHA-512",
  613. "/digest-auth/auth-int/hello/world/MD5",
  614. };
  615. cli.set_digest_auth("hello", "world");
  616. for (auto path : paths) {
  617. auto res = cli.Get(path.c_str());
  618. ASSERT_TRUE(res);
  619. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  620. res->body);
  621. EXPECT_EQ(200, res->status);
  622. }
  623. cli.set_digest_auth("hello", "bad");
  624. for (auto path : paths) {
  625. auto res = cli.Get(path.c_str());
  626. ASSERT_TRUE(res);
  627. EXPECT_EQ(401, res->status);
  628. }
  629. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  630. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  631. // cli.set_digest_auth("bad", "world");
  632. // for (auto path : paths) {
  633. // auto res = cli.Get(path.c_str());
  634. // ASSERT_TRUE(res);
  635. // EXPECT_EQ(400, res->status);
  636. // }
  637. }
  638. }
  639. #endif
  640. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  641. auto host = "google.com";
  642. auto another_host = "example.com";
  643. auto wrong_ip = "0.0.0.0";
  644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  645. SSLClient cli(host);
  646. #else
  647. Client cli(host);
  648. #endif
  649. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  650. auto res = cli.Get("/");
  651. ASSERT_TRUE(res);
  652. ASSERT_EQ(301, res->status);
  653. }
  654. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  655. auto host = "google.com";
  656. auto wrong_ip = "0.0.0.0";
  657. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  658. SSLClient cli(host);
  659. #else
  660. Client cli(host);
  661. #endif
  662. cli.set_hostname_addr_map({{host, wrong_ip}});
  663. auto res = cli.Get("/");
  664. ASSERT_TRUE(!res);
  665. EXPECT_EQ(Error::Connection, res.error());
  666. }
  667. TEST(AbsoluteRedirectTest, Redirect_Online) {
  668. auto host = "nghttp2.org";
  669. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  670. SSLClient cli(host);
  671. #else
  672. Client cli(host);
  673. #endif
  674. cli.set_follow_location(true);
  675. auto res = cli.Get("/httpbin/absolute-redirect/3");
  676. ASSERT_TRUE(res);
  677. EXPECT_EQ(200, res->status);
  678. }
  679. TEST(RedirectTest, Redirect_Online) {
  680. auto host = "nghttp2.org";
  681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  682. SSLClient cli(host);
  683. #else
  684. Client cli(host);
  685. #endif
  686. cli.set_follow_location(true);
  687. auto res = cli.Get("/httpbin/redirect/3");
  688. ASSERT_TRUE(res);
  689. EXPECT_EQ(200, res->status);
  690. }
  691. TEST(RelativeRedirectTest, Redirect_Online) {
  692. auto host = "nghttp2.org";
  693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  694. SSLClient cli(host);
  695. #else
  696. Client cli(host);
  697. #endif
  698. cli.set_follow_location(true);
  699. auto res = cli.Get("/httpbin/relative-redirect/3");
  700. ASSERT_TRUE(res);
  701. EXPECT_EQ(200, res->status);
  702. }
  703. TEST(TooManyRedirectTest, Redirect_Online) {
  704. auto host = "nghttp2.org";
  705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  706. SSLClient cli(host);
  707. #else
  708. Client cli(host);
  709. #endif
  710. cli.set_follow_location(true);
  711. auto res = cli.Get("/httpbin/redirect/21");
  712. ASSERT_TRUE(!res);
  713. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  714. }
  715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  716. TEST(YahooRedirectTest, Redirect_Online) {
  717. Client cli("yahoo.com");
  718. auto res = cli.Get("/");
  719. ASSERT_TRUE(res);
  720. EXPECT_EQ(301, res->status);
  721. cli.set_follow_location(true);
  722. res = cli.Get("/");
  723. ASSERT_TRUE(res);
  724. EXPECT_EQ(200, res->status);
  725. EXPECT_EQ("https://yahoo.com/", res->location);
  726. }
  727. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  728. SSLClient cli("nghttp2.org");
  729. cli.set_follow_location(true);
  730. auto res = cli.Get(
  731. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  732. ASSERT_TRUE(res);
  733. EXPECT_EQ(200, res->status);
  734. }
  735. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  736. SSLClient cli("nghttp2.org");
  737. cli.set_follow_location(true);
  738. Params params;
  739. params.emplace("url", "http://www.google.com");
  740. params.emplace("status_code", "302");
  741. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  742. ASSERT_TRUE(res);
  743. EXPECT_EQ(200, res->status);
  744. }
  745. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  746. SSLClient cli("nghttp2.org");
  747. cli.set_follow_location(true);
  748. Params params;
  749. params.emplace("url", "http://www.google.com");
  750. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  751. ASSERT_TRUE(res);
  752. EXPECT_EQ(200, res->status);
  753. }
  754. TEST(UrlWithSpace, Redirect_Online) {
  755. SSLClient cli("edge.forgecdn.net");
  756. cli.set_follow_location(true);
  757. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  758. ASSERT_TRUE(res);
  759. EXPECT_EQ(200, res->status);
  760. EXPECT_EQ(18527U, res->get_header_value<uint64_t>("Content-Length"));
  761. }
  762. #endif
  763. TEST(RedirectToDifferentPort, Redirect) {
  764. Server svr1;
  765. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  766. res.set_content("Hello World!", "text/plain");
  767. });
  768. int svr1_port = 0;
  769. auto thread1 = std::thread([&]() {
  770. svr1_port = svr1.bind_to_any_port("localhost");
  771. svr1.listen_after_bind();
  772. });
  773. Server svr2;
  774. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  775. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  776. });
  777. int svr2_port = 0;
  778. auto thread2 = std::thread([&]() {
  779. svr2_port = svr2.bind_to_any_port("localhost");
  780. svr2.listen_after_bind();
  781. });
  782. while (!svr1.is_running() || !svr2.is_running()) {
  783. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  784. }
  785. // Give GET time to get a few messages.
  786. std::this_thread::sleep_for(std::chrono::seconds(1));
  787. Client cli("localhost", svr2_port);
  788. cli.set_follow_location(true);
  789. auto res = cli.Get("/2");
  790. ASSERT_TRUE(res);
  791. EXPECT_EQ(200, res->status);
  792. EXPECT_EQ("Hello World!", res->body);
  793. svr1.stop();
  794. svr2.stop();
  795. thread1.join();
  796. thread2.join();
  797. ASSERT_FALSE(svr1.is_running());
  798. ASSERT_FALSE(svr2.is_running());
  799. }
  800. TEST(RedirectFromPageWithContent, Redirect) {
  801. Server svr;
  802. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  803. res.set_content("___", "text/plain");
  804. res.set_redirect("/2");
  805. });
  806. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  807. res.set_content("Hello World!", "text/plain");
  808. });
  809. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  810. while (!svr.is_running()) {
  811. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  812. }
  813. // Give GET time to get a few messages.
  814. std::this_thread::sleep_for(std::chrono::seconds(1));
  815. {
  816. Client cli("localhost", PORT);
  817. cli.set_follow_location(true);
  818. std::string body;
  819. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  820. body.append(data, data_length);
  821. return true;
  822. });
  823. ASSERT_TRUE(res);
  824. EXPECT_EQ(200, res->status);
  825. EXPECT_EQ("Hello World!", body);
  826. }
  827. {
  828. Client cli("localhost", PORT);
  829. std::string body;
  830. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  831. body.append(data, data_length);
  832. return true;
  833. });
  834. ASSERT_TRUE(res);
  835. EXPECT_EQ(302, res->status);
  836. EXPECT_EQ("___", body);
  837. }
  838. svr.stop();
  839. th.join();
  840. ASSERT_FALSE(svr.is_running());
  841. }
  842. TEST(RedirectFromPageWithContentIP6, Redirect) {
  843. Server svr;
  844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  845. res.set_content("___", "text/plain");
  846. // res.set_redirect("/2");
  847. res.set_redirect("http://[::1]:1234/2");
  848. });
  849. svr.Get("/2", [&](const Request &req, Response &res) {
  850. auto host_header = req.headers.find("Host");
  851. ASSERT_TRUE(host_header != req.headers.end());
  852. EXPECT_EQ("[::1]:1234", host_header->second);
  853. res.set_content("Hello World!", "text/plain");
  854. });
  855. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  856. // When IPV6 support isn't available svr.listen("::1", 1234) never
  857. // actually starts anything, so the condition !svr.is_running() will
  858. // always remain true, and the loop never stops.
  859. // This basically counts how many milliseconds have passed since the
  860. // call to svr.listen(), and if after 5 seconds nothing started yet
  861. // aborts the test.
  862. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  863. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  864. ASSERT_LT(milliseconds, 5000U);
  865. }
  866. // Give GET time to get a few messages.
  867. std::this_thread::sleep_for(std::chrono::seconds(1));
  868. {
  869. Client cli("http://[::1]:1234");
  870. cli.set_follow_location(true);
  871. std::string body;
  872. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  873. body.append(data, data_length);
  874. return true;
  875. });
  876. ASSERT_TRUE(res);
  877. EXPECT_EQ(200, res->status);
  878. EXPECT_EQ("Hello World!", body);
  879. }
  880. {
  881. Client cli("http://[::1]:1234");
  882. std::string body;
  883. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  884. body.append(data, data_length);
  885. return true;
  886. });
  887. ASSERT_TRUE(res);
  888. EXPECT_EQ(302, res->status);
  889. EXPECT_EQ("___", body);
  890. }
  891. svr.stop();
  892. th.join();
  893. ASSERT_FALSE(svr.is_running());
  894. }
  895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  896. Server svr;
  897. svr.Get("/foo", [](const Request &req, Response &res) {
  898. auto a = req.params.find("a");
  899. if (a != req.params.end()) {
  900. res.set_content((*a).second, "text/plain");
  901. res.status = 200;
  902. } else {
  903. res.status = 400;
  904. }
  905. });
  906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  907. // Give GET time to get a few messages.
  908. std::this_thread::sleep_for(std::chrono::seconds(1));
  909. {
  910. Client cli(HOST, PORT);
  911. cli.set_url_encode(false);
  912. auto res = cli.Get("/foo?a=explicitly+encoded");
  913. ASSERT_TRUE(res);
  914. EXPECT_EQ(200, res->status);
  915. // This expects it back with a space, as the `+` won't have been
  916. // url-encoded, and server-side the params get decoded turning `+`
  917. // into spaces.
  918. EXPECT_EQ("explicitly encoded", res->body);
  919. }
  920. svr.stop();
  921. thread.join();
  922. ASSERT_FALSE(svr.is_running());
  923. }
  924. TEST(BindServerTest, BindDualStack) {
  925. Server svr;
  926. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  927. res.set_content("Hello World!", "text/plain");
  928. });
  929. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  930. // Give GET time to get a few messages.
  931. std::this_thread::sleep_for(std::chrono::seconds(1));
  932. {
  933. Client cli("127.0.0.1", PORT);
  934. auto res = cli.Get("/1");
  935. ASSERT_TRUE(res);
  936. EXPECT_EQ(200, res->status);
  937. EXPECT_EQ("Hello World!", res->body);
  938. }
  939. {
  940. Client cli("::1", PORT);
  941. auto res = cli.Get("/1");
  942. ASSERT_TRUE(res);
  943. EXPECT_EQ(200, res->status);
  944. EXPECT_EQ("Hello World!", res->body);
  945. }
  946. svr.stop();
  947. thread.join();
  948. ASSERT_FALSE(svr.is_running());
  949. }
  950. TEST(BindServerTest, BindAndListenSeparately) {
  951. Server svr;
  952. int port = svr.bind_to_any_port("0.0.0.0");
  953. ASSERT_TRUE(svr.is_valid());
  954. ASSERT_TRUE(port > 0);
  955. svr.stop();
  956. }
  957. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  958. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  960. CLIENT_CA_CERT_DIR);
  961. int port = svr.bind_to_any_port("0.0.0.0");
  962. ASSERT_TRUE(svr.is_valid());
  963. ASSERT_TRUE(port > 0);
  964. svr.stop();
  965. }
  966. #endif
  967. TEST(ErrorHandlerTest, ContentLength) {
  968. Server svr;
  969. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  970. res.status = 200;
  971. res.set_content("abcdefghijklmnopqrstuvwxyz",
  972. "text/html"); // <= Content-Length still 13
  973. });
  974. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  975. res.set_content("Hello World!\n", "text/plain");
  976. res.status = 524;
  977. });
  978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  979. // Give GET time to get a few messages.
  980. std::this_thread::sleep_for(std::chrono::seconds(1));
  981. {
  982. Client cli(HOST, PORT);
  983. auto res = cli.Get("/hi");
  984. ASSERT_TRUE(res);
  985. EXPECT_EQ(200, res->status);
  986. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  987. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  988. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  989. }
  990. svr.stop();
  991. thread.join();
  992. ASSERT_FALSE(svr.is_running());
  993. }
  994. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  995. TEST(ExceptionHandlerTest, ContentLength) {
  996. Server svr;
  997. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  998. std::exception &e) {
  999. EXPECT_EQ("abc", std::string(e.what()));
  1000. res.status = 500;
  1001. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1002. "text/html"); // <= Content-Length still 13 at this point
  1003. });
  1004. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1005. res.set_content("Hello World!\n", "text/plain");
  1006. throw std::runtime_error("abc");
  1007. });
  1008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1009. // Give GET time to get a few messages.
  1010. std::this_thread::sleep_for(std::chrono::seconds(1));
  1011. for (size_t i = 0; i < 10; i++) {
  1012. Client cli(HOST, PORT);
  1013. for (size_t j = 0; j < 100; j++) {
  1014. auto res = cli.Get("/hi");
  1015. ASSERT_TRUE(res);
  1016. EXPECT_EQ(500, res->status);
  1017. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1018. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1019. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1020. }
  1021. cli.set_keep_alive(true);
  1022. for (size_t j = 0; j < 100; j++) {
  1023. auto res = cli.Get("/hi");
  1024. ASSERT_TRUE(res);
  1025. EXPECT_EQ(500, res->status);
  1026. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1027. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1028. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1029. }
  1030. }
  1031. svr.stop();
  1032. thread.join();
  1033. ASSERT_FALSE(svr.is_running());
  1034. }
  1035. #endif
  1036. TEST(NoContentTest, ContentLength) {
  1037. Server svr;
  1038. svr.Get("/hi",
  1039. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1040. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1041. // Give GET time to get a few messages.
  1042. std::this_thread::sleep_for(std::chrono::seconds(1));
  1043. {
  1044. Client cli(HOST, PORT);
  1045. auto res = cli.Get("/hi");
  1046. ASSERT_TRUE(res);
  1047. EXPECT_EQ(204, res->status);
  1048. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1049. }
  1050. svr.stop();
  1051. thread.join();
  1052. ASSERT_FALSE(svr.is_running());
  1053. }
  1054. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1055. Server svr;
  1056. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1057. if (req.path == "/routing_handler") {
  1058. res.set_header("PRE_ROUTING", "on");
  1059. res.set_content("Routing Handler", "text/plain");
  1060. return httplib::Server::HandlerResponse::Handled;
  1061. }
  1062. return httplib::Server::HandlerResponse::Unhandled;
  1063. });
  1064. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1065. res.set_content("Error", "text/html");
  1066. });
  1067. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1068. if (req.path == "/routing_handler") {
  1069. res.set_header("POST_ROUTING", "on");
  1070. }
  1071. });
  1072. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1073. res.set_content("Hello World!\n", "text/plain");
  1074. });
  1075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1076. // Give GET time to get a few messages.
  1077. std::this_thread::sleep_for(std::chrono::seconds(1));
  1078. {
  1079. Client cli(HOST, PORT);
  1080. auto res = cli.Get("/routing_handler");
  1081. ASSERT_TRUE(res);
  1082. EXPECT_EQ(200, res->status);
  1083. EXPECT_EQ("Routing Handler", res->body);
  1084. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1085. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1086. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1087. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1088. }
  1089. {
  1090. Client cli(HOST, PORT);
  1091. auto res = cli.Get("/hi");
  1092. ASSERT_TRUE(res);
  1093. EXPECT_EQ(200, res->status);
  1094. EXPECT_EQ("Hello World!\n", res->body);
  1095. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1096. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1097. }
  1098. {
  1099. Client cli(HOST, PORT);
  1100. auto res = cli.Get("/aaa");
  1101. ASSERT_TRUE(res);
  1102. EXPECT_EQ(404, res->status);
  1103. EXPECT_EQ("Error", res->body);
  1104. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1105. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1106. }
  1107. svr.stop();
  1108. thread.join();
  1109. ASSERT_FALSE(svr.is_running());
  1110. }
  1111. TEST(InvalidFormatTest, StatusCode) {
  1112. Server svr;
  1113. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1114. res.set_content("Hello World!\n", "text/plain");
  1115. res.status = 9999; // Status should be a three-digit code...
  1116. });
  1117. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1118. // Give GET time to get a few messages.
  1119. std::this_thread::sleep_for(std::chrono::seconds(1));
  1120. {
  1121. Client cli(HOST, PORT);
  1122. auto res = cli.Get("/hi");
  1123. ASSERT_FALSE(res);
  1124. }
  1125. svr.stop();
  1126. thread.join();
  1127. ASSERT_FALSE(svr.is_running());
  1128. }
  1129. class ServerTest : public ::testing::Test {
  1130. protected:
  1131. ServerTest()
  1132. : cli_(HOST, PORT)
  1133. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1134. ,
  1135. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1136. #endif
  1137. {
  1138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1139. cli_.enable_server_certificate_verification(false);
  1140. #endif
  1141. }
  1142. virtual void SetUp() {
  1143. svr_.set_mount_point("/", "./www");
  1144. svr_.set_mount_point("/mount", "./www2");
  1145. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1146. svr_.Get("/hi",
  1147. [&](const Request & /*req*/, Response &res) {
  1148. res.set_content("Hello World!", "text/plain");
  1149. })
  1150. .Get("/http_response_splitting",
  1151. [&](const Request & /*req*/, Response &res) {
  1152. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1153. EXPECT_EQ(0U, res.headers.size());
  1154. EXPECT_FALSE(res.has_header("a"));
  1155. res.set_header("a", "1\nSet-Cookie: a=1");
  1156. EXPECT_EQ(0U, res.headers.size());
  1157. EXPECT_FALSE(res.has_header("a"));
  1158. res.set_header("a", "1\rSet-Cookie: a=1");
  1159. EXPECT_EQ(0U, res.headers.size());
  1160. EXPECT_FALSE(res.has_header("a"));
  1161. res.set_header("a\r\nb", "0");
  1162. EXPECT_EQ(0U, res.headers.size());
  1163. EXPECT_FALSE(res.has_header("a"));
  1164. res.set_header("a\rb", "0");
  1165. EXPECT_EQ(0U, res.headers.size());
  1166. EXPECT_FALSE(res.has_header("a"));
  1167. res.set_header("a\nb", "0");
  1168. EXPECT_EQ(0U, res.headers.size());
  1169. EXPECT_FALSE(res.has_header("a"));
  1170. res.set_redirect("1\r\nSet-Cookie: a=1");
  1171. EXPECT_EQ(0U, res.headers.size());
  1172. EXPECT_FALSE(res.has_header("Location"));
  1173. })
  1174. .Get("/slow",
  1175. [&](const Request & /*req*/, Response &res) {
  1176. std::this_thread::sleep_for(std::chrono::seconds(2));
  1177. res.set_content("slow", "text/plain");
  1178. })
  1179. #if 0
  1180. .Post("/slowpost",
  1181. [&](const Request & /*req*/, Response &res) {
  1182. std::this_thread::sleep_for(std::chrono::seconds(2));
  1183. res.set_content("slow", "text/plain");
  1184. })
  1185. #endif
  1186. .Get("/remote_addr",
  1187. [&](const Request &req, Response &res) {
  1188. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1189. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1190. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1191. EXPECT_EQ(req.remote_port,
  1192. std::stoi(req.get_header_value("REMOTE_PORT")));
  1193. res.set_content(remote_addr.c_str(), "text/plain");
  1194. })
  1195. .Get("/endwith%",
  1196. [&](const Request & /*req*/, Response &res) {
  1197. res.set_content("Hello World!", "text/plain");
  1198. })
  1199. .Get("/a\\+\\+b",
  1200. [&](const Request &req, Response &res) {
  1201. ASSERT_TRUE(req.has_param("a +b"));
  1202. auto val = req.get_param_value("a +b");
  1203. res.set_content(val, "text/plain");
  1204. })
  1205. .Get("/", [&](const Request & /*req*/,
  1206. Response &res) { res.set_redirect("/hi"); })
  1207. .Post("/1", [](const Request & /*req*/,
  1208. Response &res) { res.set_redirect("/2", 303); })
  1209. .Get("/2",
  1210. [](const Request & /*req*/, Response &res) {
  1211. res.set_content("redirected.", "text/plain");
  1212. res.status = 200;
  1213. })
  1214. .Post("/person",
  1215. [&](const Request &req, Response &res) {
  1216. if (req.has_param("name") && req.has_param("note")) {
  1217. persons_[req.get_param_value("name")] =
  1218. req.get_param_value("note");
  1219. } else {
  1220. res.status = 400;
  1221. }
  1222. })
  1223. .Put("/person",
  1224. [&](const Request &req, Response &res) {
  1225. if (req.has_param("name") && req.has_param("note")) {
  1226. persons_[req.get_param_value("name")] =
  1227. req.get_param_value("note");
  1228. } else {
  1229. res.status = 400;
  1230. }
  1231. })
  1232. .Get("/person/(.*)",
  1233. [&](const Request &req, Response &res) {
  1234. string name = req.matches[1];
  1235. if (persons_.find(name) != persons_.end()) {
  1236. auto note = persons_[name];
  1237. res.set_content(note, "text/plain");
  1238. } else {
  1239. res.status = 404;
  1240. }
  1241. })
  1242. .Post("/x-www-form-urlencoded-json",
  1243. [&](const Request &req, Response &res) {
  1244. auto json = req.get_param_value("json");
  1245. ASSERT_EQ(JSON_DATA, json);
  1246. res.set_content(json, "appliation/json");
  1247. res.status = 200;
  1248. })
  1249. .Get("/streamed-chunked",
  1250. [&](const Request & /*req*/, Response &res) {
  1251. res.set_chunked_content_provider(
  1252. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1253. EXPECT_TRUE(sink.is_writable());
  1254. sink.os << "123";
  1255. sink.os << "456";
  1256. sink.os << "789";
  1257. sink.done();
  1258. return true;
  1259. });
  1260. })
  1261. .Get("/streamed-chunked2",
  1262. [&](const Request & /*req*/, Response &res) {
  1263. auto i = new int(0);
  1264. res.set_chunked_content_provider(
  1265. "text/plain",
  1266. [i](size_t /*offset*/, DataSink &sink) {
  1267. EXPECT_TRUE(sink.is_writable());
  1268. switch (*i) {
  1269. case 0: sink.os << "123"; break;
  1270. case 1: sink.os << "456"; break;
  1271. case 2: sink.os << "789"; break;
  1272. case 3: sink.done(); break;
  1273. }
  1274. (*i)++;
  1275. return true;
  1276. },
  1277. [i](bool success) {
  1278. EXPECT_TRUE(success);
  1279. delete i;
  1280. });
  1281. })
  1282. .Get("/streamed",
  1283. [&](const Request & /*req*/, Response &res) {
  1284. res.set_content_provider(
  1285. 6, "text/plain",
  1286. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1287. sink.os << (offset < 3 ? "a" : "b");
  1288. return true;
  1289. });
  1290. })
  1291. .Get("/streamed-with-range",
  1292. [&](const Request & /*req*/, Response &res) {
  1293. auto data = new std::string("abcdefg");
  1294. res.set_content_provider(
  1295. data->size(), "text/plain",
  1296. [data](size_t offset, size_t length, DataSink &sink) {
  1297. EXPECT_TRUE(sink.is_writable());
  1298. size_t DATA_CHUNK_SIZE = 4;
  1299. const auto &d = *data;
  1300. auto out_len =
  1301. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1302. auto ret =
  1303. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1304. EXPECT_TRUE(ret);
  1305. return true;
  1306. },
  1307. [data](bool success) {
  1308. EXPECT_TRUE(success);
  1309. delete data;
  1310. });
  1311. })
  1312. .Get("/streamed-cancel",
  1313. [&](const Request & /*req*/, Response &res) {
  1314. res.set_content_provider(
  1315. size_t(-1), "text/plain",
  1316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1317. EXPECT_TRUE(sink.is_writable());
  1318. sink.os << "data_chunk";
  1319. return true;
  1320. });
  1321. })
  1322. .Get("/with-range",
  1323. [&](const Request & /*req*/, Response &res) {
  1324. res.set_content("abcdefg", "text/plain");
  1325. })
  1326. .Post("/chunked",
  1327. [&](const Request &req, Response & /*res*/) {
  1328. EXPECT_EQ(req.body, "dechunked post body");
  1329. })
  1330. .Post("/large-chunked",
  1331. [&](const Request &req, Response & /*res*/) {
  1332. std::string expected(6 * 30 * 1024u, 'a');
  1333. EXPECT_EQ(req.body, expected);
  1334. })
  1335. .Post("/multipart",
  1336. [&](const Request &req, Response & /*res*/) {
  1337. EXPECT_EQ(6u, req.files.size());
  1338. ASSERT_TRUE(!req.has_file("???"));
  1339. ASSERT_TRUE(req.body.empty());
  1340. {
  1341. const auto &file = req.get_file_value("text1");
  1342. EXPECT_TRUE(file.filename.empty());
  1343. EXPECT_EQ("text default", file.content);
  1344. }
  1345. {
  1346. const auto &file = req.get_file_value("text2");
  1347. EXPECT_TRUE(file.filename.empty());
  1348. EXPECT_EQ("aωb", file.content);
  1349. }
  1350. {
  1351. const auto &file = req.get_file_value("file1");
  1352. EXPECT_EQ("hello.txt", file.filename);
  1353. EXPECT_EQ("text/plain", file.content_type);
  1354. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1355. }
  1356. {
  1357. const auto &file = req.get_file_value("file3");
  1358. EXPECT_TRUE(file.filename.empty());
  1359. EXPECT_EQ("application/octet-stream", file.content_type);
  1360. EXPECT_EQ(0u, file.content.size());
  1361. }
  1362. {
  1363. const auto &file = req.get_file_value("file4");
  1364. EXPECT_TRUE(file.filename.empty());
  1365. EXPECT_EQ(0u, file.content.size());
  1366. EXPECT_EQ("application/json tmp-string", file.content_type);
  1367. }
  1368. })
  1369. .Post("/empty",
  1370. [&](const Request &req, Response &res) {
  1371. EXPECT_EQ(req.body, "");
  1372. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1373. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1374. res.set_content("empty", "text/plain");
  1375. })
  1376. .Post("/empty-no-content-type",
  1377. [&](const Request &req, Response &res) {
  1378. EXPECT_EQ(req.body, "");
  1379. EXPECT_FALSE(req.has_header("Content-Type"));
  1380. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1381. res.set_content("empty-no-content-type", "text/plain");
  1382. })
  1383. .Post("/post-large",
  1384. [&](const Request &req, Response &res) {
  1385. EXPECT_EQ(req.body, LARGE_DATA);
  1386. res.set_content(req.body, "text/plain");
  1387. })
  1388. .Put("/empty-no-content-type",
  1389. [&](const Request &req, Response &res) {
  1390. EXPECT_EQ(req.body, "");
  1391. EXPECT_FALSE(req.has_header("Content-Type"));
  1392. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1393. res.set_content("empty-no-content-type", "text/plain");
  1394. })
  1395. .Put("/put",
  1396. [&](const Request &req, Response &res) {
  1397. EXPECT_EQ(req.body, "PUT");
  1398. res.set_content(req.body, "text/plain");
  1399. })
  1400. .Put("/put-large",
  1401. [&](const Request &req, Response &res) {
  1402. EXPECT_EQ(req.body, LARGE_DATA);
  1403. res.set_content(req.body, "text/plain");
  1404. })
  1405. .Patch("/patch",
  1406. [&](const Request &req, Response &res) {
  1407. EXPECT_EQ(req.body, "PATCH");
  1408. res.set_content(req.body, "text/plain");
  1409. })
  1410. .Delete("/delete",
  1411. [&](const Request & /*req*/, Response &res) {
  1412. res.set_content("DELETE", "text/plain");
  1413. })
  1414. .Delete("/delete-body",
  1415. [&](const Request &req, Response &res) {
  1416. EXPECT_EQ(req.body, "content");
  1417. res.set_content(req.body, "text/plain");
  1418. })
  1419. .Options(R"(\*)",
  1420. [&](const Request & /*req*/, Response &res) {
  1421. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1422. })
  1423. .Get("/request-target",
  1424. [&](const Request &req, Response & /*res*/) {
  1425. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1426. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1427. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1428. })
  1429. .Get("/long-query-value",
  1430. [&](const Request &req, Response & /*res*/) {
  1431. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1432. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1433. })
  1434. .Get("/array-param",
  1435. [&](const Request &req, Response & /*res*/) {
  1436. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1437. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1438. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1439. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1440. })
  1441. .Post("/validate-no-multiple-headers",
  1442. [&](const Request &req, Response & /*res*/) {
  1443. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1444. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1445. })
  1446. .Post("/content_receiver",
  1447. [&](const Request &req, Response &res,
  1448. const ContentReader &content_reader) {
  1449. if (req.is_multipart_form_data()) {
  1450. MultipartFormDataItems files;
  1451. content_reader(
  1452. [&](const MultipartFormData &file) {
  1453. files.push_back(file);
  1454. return true;
  1455. },
  1456. [&](const char *data, size_t data_length) {
  1457. files.back().content.append(data, data_length);
  1458. return true;
  1459. });
  1460. EXPECT_EQ(5u, files.size());
  1461. {
  1462. const auto &file = get_file_value(files, "text1");
  1463. EXPECT_TRUE(file.filename.empty());
  1464. EXPECT_EQ("text default", file.content);
  1465. }
  1466. {
  1467. const auto &file = get_file_value(files, "text2");
  1468. EXPECT_TRUE(file.filename.empty());
  1469. EXPECT_EQ("aωb", file.content);
  1470. }
  1471. {
  1472. const auto &file = get_file_value(files, "file1");
  1473. EXPECT_EQ("hello.txt", file.filename);
  1474. EXPECT_EQ("text/plain", file.content_type);
  1475. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1476. }
  1477. {
  1478. const auto &file = get_file_value(files, "file3");
  1479. EXPECT_TRUE(file.filename.empty());
  1480. EXPECT_EQ("application/octet-stream", file.content_type);
  1481. EXPECT_EQ(0u, file.content.size());
  1482. }
  1483. } else {
  1484. std::string body;
  1485. content_reader([&](const char *data, size_t data_length) {
  1486. EXPECT_EQ(7U, data_length);
  1487. body.append(data, data_length);
  1488. return true;
  1489. });
  1490. EXPECT_EQ(body, "content");
  1491. res.set_content(body, "text/plain");
  1492. }
  1493. })
  1494. .Put("/content_receiver",
  1495. [&](const Request & /*req*/, Response &res,
  1496. const ContentReader &content_reader) {
  1497. std::string body;
  1498. content_reader([&](const char *data, size_t data_length) {
  1499. body.append(data, data_length);
  1500. return true;
  1501. });
  1502. EXPECT_EQ(body, "content");
  1503. res.set_content(body, "text/plain");
  1504. })
  1505. .Patch("/content_receiver",
  1506. [&](const Request & /*req*/, Response &res,
  1507. const ContentReader &content_reader) {
  1508. std::string body;
  1509. content_reader([&](const char *data, size_t data_length) {
  1510. body.append(data, data_length);
  1511. return true;
  1512. });
  1513. EXPECT_EQ(body, "content");
  1514. res.set_content(body, "text/plain");
  1515. })
  1516. .Post("/query-string-and-body",
  1517. [&](const Request &req, Response & /*res*/) {
  1518. ASSERT_TRUE(req.has_param("key"));
  1519. EXPECT_EQ(req.get_param_value("key"), "value");
  1520. EXPECT_EQ(req.body, "content");
  1521. })
  1522. .Get("/last-request",
  1523. [&](const Request &req, Response & /*res*/) {
  1524. EXPECT_EQ("close", req.get_header_value("Connection"));
  1525. })
  1526. .Get(R"(/redirect/(\d+))",
  1527. [&](const Request &req, Response &res) {
  1528. auto num = std::stoi(req.matches[1]) + 1;
  1529. std::string url = "/redirect/" + std::to_string(num);
  1530. res.set_redirect(url);
  1531. })
  1532. .Post("/binary",
  1533. [&](const Request &req, Response &res) {
  1534. EXPECT_EQ(4U, req.body.size());
  1535. EXPECT_EQ("application/octet-stream",
  1536. req.get_header_value("Content-Type"));
  1537. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1538. res.set_content(req.body, "application/octet-stream");
  1539. })
  1540. .Put("/binary",
  1541. [&](const Request &req, Response &res) {
  1542. EXPECT_EQ(4U, req.body.size());
  1543. EXPECT_EQ("application/octet-stream",
  1544. req.get_header_value("Content-Type"));
  1545. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1546. res.set_content(req.body, "application/octet-stream");
  1547. })
  1548. .Patch("/binary",
  1549. [&](const Request &req, Response &res) {
  1550. EXPECT_EQ(4U, req.body.size());
  1551. EXPECT_EQ("application/octet-stream",
  1552. req.get_header_value("Content-Type"));
  1553. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1554. res.set_content(req.body, "application/octet-stream");
  1555. })
  1556. .Delete("/binary",
  1557. [&](const Request &req, Response &res) {
  1558. EXPECT_EQ(4U, req.body.size());
  1559. EXPECT_EQ("application/octet-stream",
  1560. req.get_header_value("Content-Type"));
  1561. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1562. res.set_content(req.body, "application/octet-stream");
  1563. })
  1564. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1565. .Get("/compress",
  1566. [&](const Request & /*req*/, Response &res) {
  1567. res.set_content(
  1568. "12345678901234567890123456789012345678901234567890123456789"
  1569. "01234567890123456789012345678901234567890",
  1570. "text/plain");
  1571. })
  1572. .Get("/nocompress",
  1573. [&](const Request & /*req*/, Response &res) {
  1574. res.set_content(
  1575. "12345678901234567890123456789012345678901234567890123456789"
  1576. "01234567890123456789012345678901234567890",
  1577. "application/octet-stream");
  1578. })
  1579. .Post("/compress-multipart",
  1580. [&](const Request &req, Response & /*res*/) {
  1581. EXPECT_EQ(2u, req.files.size());
  1582. ASSERT_TRUE(!req.has_file("???"));
  1583. {
  1584. const auto &file = req.get_file_value("key1");
  1585. EXPECT_TRUE(file.filename.empty());
  1586. EXPECT_EQ("test", file.content);
  1587. }
  1588. {
  1589. const auto &file = req.get_file_value("key2");
  1590. EXPECT_TRUE(file.filename.empty());
  1591. EXPECT_EQ("--abcdefg123", file.content);
  1592. }
  1593. })
  1594. #endif
  1595. ;
  1596. persons_["john"] = "programmer";
  1597. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1598. while (!svr_.is_running()) {
  1599. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1600. }
  1601. }
  1602. virtual void TearDown() {
  1603. svr_.stop();
  1604. if (!request_threads_.empty()) {
  1605. std::this_thread::sleep_for(std::chrono::seconds(1));
  1606. for (auto &t : request_threads_) {
  1607. t.join();
  1608. }
  1609. }
  1610. t_.join();
  1611. }
  1612. map<string, string> persons_;
  1613. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1614. SSLClient cli_;
  1615. SSLServer svr_;
  1616. #else
  1617. Client cli_;
  1618. Server svr_;
  1619. #endif
  1620. thread t_;
  1621. std::vector<thread> request_threads_;
  1622. };
  1623. TEST_F(ServerTest, GetMethod200) {
  1624. auto res = cli_.Get("/hi");
  1625. ASSERT_TRUE(res);
  1626. EXPECT_EQ("HTTP/1.1", res->version);
  1627. EXPECT_EQ(200, res->status);
  1628. EXPECT_EQ("OK", res->reason);
  1629. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1630. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1631. EXPECT_EQ("Hello World!", res->body);
  1632. }
  1633. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1634. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ("HTTP/1.1", res->version);
  1637. EXPECT_EQ(200, res->status);
  1638. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1639. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1640. EXPECT_EQ("Hello World!", res->body);
  1641. }
  1642. TEST_F(ServerTest, GetMethod302) {
  1643. auto res = cli_.Get("/");
  1644. ASSERT_TRUE(res);
  1645. EXPECT_EQ(302, res->status);
  1646. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1647. }
  1648. TEST_F(ServerTest, GetMethod302Redirect) {
  1649. cli_.set_follow_location(true);
  1650. auto res = cli_.Get("/");
  1651. ASSERT_TRUE(res);
  1652. EXPECT_EQ(200, res->status);
  1653. EXPECT_EQ("Hello World!", res->body);
  1654. EXPECT_EQ("/hi", res->location);
  1655. }
  1656. TEST_F(ServerTest, GetMethod404) {
  1657. auto res = cli_.Get("/invalid");
  1658. ASSERT_TRUE(res);
  1659. EXPECT_EQ(404, res->status);
  1660. }
  1661. TEST_F(ServerTest, HeadMethod200) {
  1662. auto res = cli_.Head("/hi");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(200, res->status);
  1665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1666. EXPECT_TRUE(res->body.empty());
  1667. }
  1668. TEST_F(ServerTest, HeadMethod200Static) {
  1669. auto res = cli_.Head("/mount/dir/index.html");
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(200, res->status);
  1672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1673. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1674. EXPECT_TRUE(res->body.empty());
  1675. }
  1676. TEST_F(ServerTest, HeadMethod404) {
  1677. auto res = cli_.Head("/invalid");
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(404, res->status);
  1680. EXPECT_TRUE(res->body.empty());
  1681. }
  1682. TEST_F(ServerTest, GetMethodPersonJohn) {
  1683. auto res = cli_.Get("/person/john");
  1684. ASSERT_TRUE(res);
  1685. EXPECT_EQ(200, res->status);
  1686. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1687. EXPECT_EQ("programmer", res->body);
  1688. }
  1689. TEST_F(ServerTest, PostMethod1) {
  1690. auto res = cli_.Get("/person/john1");
  1691. ASSERT_TRUE(res);
  1692. ASSERT_EQ(404, res->status);
  1693. res = cli_.Post("/person", "name=john1&note=coder",
  1694. "application/x-www-form-urlencoded");
  1695. ASSERT_TRUE(res);
  1696. ASSERT_EQ(200, res->status);
  1697. res = cli_.Get("/person/john1");
  1698. ASSERT_TRUE(res);
  1699. ASSERT_EQ(200, res->status);
  1700. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1701. ASSERT_EQ("coder", res->body);
  1702. }
  1703. TEST_F(ServerTest, PostMethod2) {
  1704. auto res = cli_.Get("/person/john2");
  1705. ASSERT_TRUE(res);
  1706. ASSERT_EQ(404, res->status);
  1707. Params params;
  1708. params.emplace("name", "john2");
  1709. params.emplace("note", "coder");
  1710. res = cli_.Post("/person", params);
  1711. ASSERT_TRUE(res);
  1712. ASSERT_EQ(200, res->status);
  1713. res = cli_.Get("/person/john2");
  1714. ASSERT_TRUE(res);
  1715. ASSERT_EQ(200, res->status);
  1716. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1717. ASSERT_EQ("coder", res->body);
  1718. }
  1719. TEST_F(ServerTest, PutMethod3) {
  1720. auto res = cli_.Get("/person/john3");
  1721. ASSERT_TRUE(res);
  1722. ASSERT_EQ(404, res->status);
  1723. Params params;
  1724. params.emplace("name", "john3");
  1725. params.emplace("note", "coder");
  1726. res = cli_.Put("/person", params);
  1727. ASSERT_TRUE(res);
  1728. ASSERT_EQ(200, res->status);
  1729. res = cli_.Get("/person/john3");
  1730. ASSERT_TRUE(res);
  1731. ASSERT_EQ(200, res->status);
  1732. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1733. ASSERT_EQ("coder", res->body);
  1734. }
  1735. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1736. Params params;
  1737. params.emplace("json", JSON_DATA);
  1738. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1739. ASSERT_TRUE(res);
  1740. ASSERT_EQ(200, res->status);
  1741. ASSERT_EQ(JSON_DATA, res->body);
  1742. }
  1743. TEST_F(ServerTest, PostEmptyContent) {
  1744. auto res = cli_.Post("/empty", "", "text/plain");
  1745. ASSERT_TRUE(res);
  1746. ASSERT_EQ(200, res->status);
  1747. ASSERT_EQ("empty", res->body);
  1748. }
  1749. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1750. auto res = cli_.Post("/empty-no-content-type");
  1751. ASSERT_TRUE(res);
  1752. ASSERT_EQ(200, res->status);
  1753. ASSERT_EQ("empty-no-content-type", res->body);
  1754. }
  1755. TEST_F(ServerTest, PostLarge) {
  1756. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1757. ASSERT_TRUE(res);
  1758. ASSERT_EQ(200, res->status);
  1759. EXPECT_EQ(LARGE_DATA, res->body);
  1760. }
  1761. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1762. auto res = cli_.Put("/empty-no-content-type");
  1763. ASSERT_TRUE(res);
  1764. ASSERT_EQ(200, res->status);
  1765. ASSERT_EQ("empty-no-content-type", res->body);
  1766. }
  1767. TEST_F(ServerTest, GetMethodDir) {
  1768. auto res = cli_.Get("/dir/");
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ(200, res->status);
  1771. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1772. auto body = R"(<html>
  1773. <head>
  1774. </head>
  1775. <body>
  1776. <a href="/dir/test.html">Test</a>
  1777. <a href="/hi">hi</a>
  1778. </body>
  1779. </html>
  1780. )";
  1781. EXPECT_EQ(body, res->body);
  1782. }
  1783. TEST_F(ServerTest, GetMethodDirTest) {
  1784. auto res = cli_.Get("/dir/test.html");
  1785. ASSERT_TRUE(res);
  1786. EXPECT_EQ(200, res->status);
  1787. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1788. EXPECT_EQ("test.html", res->body);
  1789. }
  1790. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1791. auto res = cli_.Get("/dir/../dir/test.html");
  1792. ASSERT_TRUE(res);
  1793. EXPECT_EQ(200, res->status);
  1794. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1795. EXPECT_EQ("test.html", res->body);
  1796. }
  1797. TEST_F(ServerTest, GetMethodInvalidPath) {
  1798. auto res = cli_.Get("/dir/../test.html");
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(404, res->status);
  1801. }
  1802. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1803. auto res = cli_.Get("/../www/dir/test.html");
  1804. ASSERT_TRUE(res);
  1805. EXPECT_EQ(404, res->status);
  1806. }
  1807. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1808. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1809. ASSERT_TRUE(res);
  1810. EXPECT_EQ(404, res->status);
  1811. }
  1812. TEST_F(ServerTest, GetMethodDirMountTest) {
  1813. auto res = cli_.Get("/mount/dir/test.html");
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(200, res->status);
  1816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1817. EXPECT_EQ("test.html", res->body);
  1818. }
  1819. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1820. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1821. ASSERT_TRUE(res);
  1822. EXPECT_EQ(200, res->status);
  1823. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1824. EXPECT_EQ("test.html", res->body);
  1825. }
  1826. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1827. auto res = cli_.Get("/mount/dir/../test.html");
  1828. ASSERT_TRUE(res);
  1829. EXPECT_EQ(404, res->status);
  1830. }
  1831. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1832. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1833. ASSERT_TRUE(res);
  1834. EXPECT_EQ(404, res->status);
  1835. }
  1836. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1837. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1838. ASSERT_TRUE(res);
  1839. EXPECT_EQ(404, res->status);
  1840. }
  1841. TEST_F(ServerTest, PostMethod303) {
  1842. auto res = cli_.Post("/1", "body", "text/plain");
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(303, res->status);
  1845. EXPECT_EQ("/2", res->get_header_value("Location"));
  1846. }
  1847. TEST_F(ServerTest, PostMethod303Redirect) {
  1848. cli_.set_follow_location(true);
  1849. auto res = cli_.Post("/1", "body", "text/plain");
  1850. ASSERT_TRUE(res);
  1851. EXPECT_EQ(200, res->status);
  1852. EXPECT_EQ("redirected.", res->body);
  1853. EXPECT_EQ("/2", res->location);
  1854. }
  1855. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1856. auto res = cli_.Get("/dir/test.abcde");
  1857. ASSERT_TRUE(res);
  1858. EXPECT_EQ(200, res->status);
  1859. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1860. EXPECT_EQ("abcde", res->body);
  1861. }
  1862. TEST_F(ServerTest, StaticFileRange) {
  1863. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(206, res->status);
  1866. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1867. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1868. EXPECT_EQ(true, res->has_header("Content-Range"));
  1869. EXPECT_EQ(std::string("cd"), res->body);
  1870. }
  1871. TEST_F(ServerTest, InvalidBaseDirMount) {
  1872. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1873. }
  1874. TEST_F(ServerTest, Binary) {
  1875. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1876. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1877. "application/octet-stream");
  1878. ASSERT_TRUE(res);
  1879. ASSERT_EQ(200, res->status);
  1880. ASSERT_EQ(4U, res->body.size());
  1881. res = cli_.Put("/binary", binary.data(), binary.size(),
  1882. "application/octet-stream");
  1883. ASSERT_TRUE(res);
  1884. ASSERT_EQ(200, res->status);
  1885. ASSERT_EQ(4U, res->body.size());
  1886. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1887. "application/octet-stream");
  1888. ASSERT_TRUE(res);
  1889. ASSERT_EQ(200, res->status);
  1890. ASSERT_EQ(4U, res->body.size());
  1891. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1892. "application/octet-stream");
  1893. ASSERT_TRUE(res);
  1894. ASSERT_EQ(200, res->status);
  1895. ASSERT_EQ(4U, res->body.size());
  1896. }
  1897. TEST_F(ServerTest, BinaryString) {
  1898. auto binary = std::string("\x00\x01\x02\x03", 4);
  1899. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  1900. ASSERT_TRUE(res);
  1901. ASSERT_EQ(200, res->status);
  1902. ASSERT_EQ(4U, res->body.size());
  1903. res = cli_.Put("/binary", binary, "application/octet-stream");
  1904. ASSERT_TRUE(res);
  1905. ASSERT_EQ(200, res->status);
  1906. ASSERT_EQ(4U, res->body.size());
  1907. res = cli_.Patch("/binary", binary, "application/octet-stream");
  1908. ASSERT_TRUE(res);
  1909. ASSERT_EQ(200, res->status);
  1910. ASSERT_EQ(4U, res->body.size());
  1911. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1912. ASSERT_TRUE(res);
  1913. ASSERT_EQ(200, res->status);
  1914. ASSERT_EQ(4U, res->body.size());
  1915. }
  1916. TEST_F(ServerTest, EmptyRequest) {
  1917. auto res = cli_.Get("");
  1918. ASSERT_TRUE(!res);
  1919. EXPECT_EQ(Error::Connection, res.error());
  1920. }
  1921. TEST_F(ServerTest, LongRequest) {
  1922. std::string request;
  1923. for (size_t i = 0; i < 545; i++) {
  1924. request += "/TooLongRequest";
  1925. }
  1926. request += "OK";
  1927. auto res = cli_.Get(request.c_str());
  1928. ASSERT_TRUE(res);
  1929. EXPECT_EQ(404, res->status);
  1930. }
  1931. TEST_F(ServerTest, TooLongRequest) {
  1932. std::string request;
  1933. for (size_t i = 0; i < 545; i++) {
  1934. request += "/TooLongRequest";
  1935. }
  1936. request += "_NG";
  1937. auto res = cli_.Get(request.c_str());
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(414, res->status);
  1940. }
  1941. TEST_F(ServerTest, LongHeader) {
  1942. Request req;
  1943. req.method = "GET";
  1944. req.path = "/hi";
  1945. std::string host_and_port;
  1946. host_and_port += HOST;
  1947. host_and_port += ":";
  1948. host_and_port += std::to_string(PORT);
  1949. req.headers.emplace("Host", host_and_port.c_str());
  1950. req.headers.emplace("Accept", "*/*");
  1951. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1952. req.headers.emplace(
  1953. "Header-Name",
  1954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1982. "@@@@@@@@@@@@@@@@");
  1983. auto res = std::make_shared<Response>();
  1984. auto error = Error::Success;
  1985. auto ret = cli_.send(req, *res, error);
  1986. ASSERT_TRUE(ret);
  1987. EXPECT_EQ(200, res->status);
  1988. }
  1989. TEST_F(ServerTest, LongQueryValue) {
  1990. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1991. ASSERT_TRUE(res);
  1992. EXPECT_EQ(414, res->status);
  1993. }
  1994. TEST_F(ServerTest, TooLongHeader) {
  1995. Request req;
  1996. req.method = "GET";
  1997. req.path = "/hi";
  1998. std::string host_and_port;
  1999. host_and_port += HOST;
  2000. host_and_port += ":";
  2001. host_and_port += std::to_string(PORT);
  2002. req.headers.emplace("Host", host_and_port.c_str());
  2003. req.headers.emplace("Accept", "*/*");
  2004. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2005. req.headers.emplace(
  2006. "Header-Name",
  2007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2035. "@@@@@@@@@@@@@@@@@");
  2036. auto res = std::make_shared<Response>();
  2037. auto error = Error::Success;
  2038. auto ret = cli_.send(req, *res, error);
  2039. ASSERT_TRUE(ret);
  2040. EXPECT_EQ(200, res->status);
  2041. }
  2042. TEST_F(ServerTest, PercentEncoding) {
  2043. auto res = cli_.Get("/e%6edwith%");
  2044. ASSERT_TRUE(res);
  2045. EXPECT_EQ(200, res->status);
  2046. }
  2047. TEST_F(ServerTest, PercentEncodingUnicode) {
  2048. auto res = cli_.Get("/e%u006edwith%");
  2049. ASSERT_TRUE(res);
  2050. EXPECT_EQ(200, res->status);
  2051. }
  2052. TEST_F(ServerTest, InvalidPercentEncoding) {
  2053. auto res = cli_.Get("/%endwith%");
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(404, res->status);
  2056. }
  2057. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2058. auto res = cli_.Get("/%uendwith%");
  2059. ASSERT_TRUE(res);
  2060. EXPECT_EQ(404, res->status);
  2061. }
  2062. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2063. auto res = cli_.Get("/hello?aaa=bbb%");
  2064. ASSERT_TRUE(res);
  2065. EXPECT_EQ(404, res->status);
  2066. }
  2067. TEST_F(ServerTest, PlusSignEncoding) {
  2068. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2069. ASSERT_TRUE(res);
  2070. EXPECT_EQ(200, res->status);
  2071. EXPECT_EQ("a +b", res->body);
  2072. }
  2073. TEST_F(ServerTest, MultipartFormData) {
  2074. MultipartFormDataItems items = {
  2075. {"text1", "text default", "", ""},
  2076. {"text2", "aωb", "", ""},
  2077. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2078. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2079. {"file3", "", "", "application/octet-stream"},
  2080. {"file4", "", "", " application/json tmp-string "}};
  2081. auto res = cli_.Post("/multipart", items);
  2082. ASSERT_TRUE(res);
  2083. EXPECT_EQ(200, res->status);
  2084. }
  2085. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2086. auto res = cli_.Get("/hi");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(200, res->status);
  2089. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2090. EXPECT_EQ("Hello World!", res->body);
  2091. }
  2092. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2093. Request req;
  2094. req.method = "POST";
  2095. req.path = "/chunked";
  2096. std::string host_and_port;
  2097. host_and_port += HOST;
  2098. host_and_port += ":";
  2099. host_and_port += std::to_string(PORT);
  2100. req.headers.emplace("Host", host_and_port.c_str());
  2101. req.headers.emplace("Accept", "*/*");
  2102. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2103. req.headers.emplace("Content-Type", "text/plain");
  2104. req.headers.emplace("Content-Length", "0");
  2105. req.headers.emplace(
  2106. "Transfer-Encoding",
  2107. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2108. // Client does not chunk, so make a chunked body manually.
  2109. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2110. auto res = std::make_shared<Response>();
  2111. auto error = Error::Success;
  2112. auto ret = cli_.send(req, *res, error);
  2113. ASSERT_TRUE(ret);
  2114. EXPECT_EQ(200, res->status);
  2115. }
  2116. TEST_F(ServerTest, GetStreamed2) {
  2117. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(206, res->status);
  2120. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2121. EXPECT_EQ(std::string("ab"), res->body);
  2122. }
  2123. TEST_F(ServerTest, GetStreamed) {
  2124. auto res = cli_.Get("/streamed");
  2125. ASSERT_TRUE(res);
  2126. EXPECT_EQ(200, res->status);
  2127. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2128. EXPECT_EQ(std::string("aaabbb"), res->body);
  2129. }
  2130. TEST_F(ServerTest, GetStreamedWithRange1) {
  2131. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(206, res->status);
  2134. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2135. EXPECT_EQ(true, res->has_header("Content-Range"));
  2136. EXPECT_EQ(std::string("def"), res->body);
  2137. }
  2138. TEST_F(ServerTest, GetStreamedWithRange2) {
  2139. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2140. ASSERT_TRUE(res);
  2141. EXPECT_EQ(206, res->status);
  2142. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2143. EXPECT_EQ(true, res->has_header("Content-Range"));
  2144. EXPECT_EQ(std::string("bcdefg"), res->body);
  2145. }
  2146. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2147. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2148. ASSERT_TRUE(res);
  2149. EXPECT_EQ(206, res->status);
  2150. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2151. EXPECT_EQ(true, res->has_header("Content-Range"));
  2152. EXPECT_EQ(std::string("efg"), res->body);
  2153. }
  2154. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2155. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(206, res->status);
  2158. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2159. EXPECT_EQ(true, res->has_header("Content-Range"));
  2160. EXPECT_EQ(std::string("abcdefg"), res->body);
  2161. }
  2162. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2163. auto res = cli_.Get("/streamed-with-range",
  2164. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2165. "92233720368547758079223372036854775807"}});
  2166. ASSERT_TRUE(res);
  2167. EXPECT_EQ(416, res->status);
  2168. }
  2169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2170. auto res =
  2171. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2172. EXPECT_EQ(206, res->status);
  2173. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2174. EXPECT_EQ(true, res->has_header("Content-Range"));
  2175. EXPECT_EQ(std::string("abcdefg"), res->body);
  2176. }
  2177. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2178. auto res =
  2179. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2180. ASSERT_TRUE(res);
  2181. EXPECT_EQ(206, res->status);
  2182. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2183. EXPECT_EQ(false, res->has_header("Content-Range"));
  2184. EXPECT_EQ(269U, res->body.size());
  2185. }
  2186. TEST_F(ServerTest, GetStreamedEndless) {
  2187. uint64_t offset = 0;
  2188. auto res = cli_.Get("/streamed-cancel",
  2189. [&](const char * /*data*/, uint64_t data_length) {
  2190. if (offset < 100) {
  2191. offset += data_length;
  2192. return true;
  2193. }
  2194. return false;
  2195. });
  2196. ASSERT_TRUE(!res);
  2197. EXPECT_EQ(Error::Canceled, res.error());
  2198. }
  2199. TEST_F(ServerTest, ClientStop) {
  2200. std::vector<std::thread> threads;
  2201. for (auto i = 0; i < 3; i++) {
  2202. threads.emplace_back(thread([&]() {
  2203. auto res = cli_.Get("/streamed-cancel",
  2204. [&](const char *, uint64_t) { return true; });
  2205. ASSERT_TRUE(!res);
  2206. EXPECT_TRUE(res.error() == Error::Canceled ||
  2207. res.error() == Error::Read || res.error() == Error::Write);
  2208. }));
  2209. }
  2210. std::this_thread::sleep_for(std::chrono::seconds(2));
  2211. while (cli_.is_socket_open()) {
  2212. cli_.stop();
  2213. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2214. }
  2215. for (auto &t : threads) {
  2216. t.join();
  2217. }
  2218. }
  2219. TEST_F(ServerTest, GetWithRange1) {
  2220. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2221. ASSERT_TRUE(res);
  2222. EXPECT_EQ(206, res->status);
  2223. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2224. EXPECT_EQ(true, res->has_header("Content-Range"));
  2225. EXPECT_EQ(std::string("def"), res->body);
  2226. }
  2227. TEST_F(ServerTest, GetWithRange2) {
  2228. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(206, res->status);
  2231. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2232. EXPECT_EQ(true, res->has_header("Content-Range"));
  2233. EXPECT_EQ(std::string("bcdefg"), res->body);
  2234. }
  2235. TEST_F(ServerTest, GetWithRange3) {
  2236. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2237. ASSERT_TRUE(res);
  2238. EXPECT_EQ(206, res->status);
  2239. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2240. EXPECT_EQ(true, res->has_header("Content-Range"));
  2241. EXPECT_EQ(std::string("a"), res->body);
  2242. }
  2243. TEST_F(ServerTest, GetWithRange4) {
  2244. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2245. ASSERT_TRUE(res);
  2246. EXPECT_EQ(206, res->status);
  2247. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2248. EXPECT_EQ(true, res->has_header("Content-Range"));
  2249. EXPECT_EQ(std::string("fg"), res->body);
  2250. }
  2251. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2252. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2253. ASSERT_TRUE(res);
  2254. EXPECT_EQ(416, res->status);
  2255. }
  2256. TEST_F(ServerTest, GetWithRangeMultipart) {
  2257. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2258. ASSERT_TRUE(res);
  2259. EXPECT_EQ(206, res->status);
  2260. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2261. EXPECT_EQ(false, res->has_header("Content-Range"));
  2262. EXPECT_EQ(269U, res->body.size());
  2263. }
  2264. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2265. auto res =
  2266. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2267. ASSERT_TRUE(res);
  2268. EXPECT_EQ(416, res->status);
  2269. }
  2270. TEST_F(ServerTest, GetStreamedChunked) {
  2271. auto res = cli_.Get("/streamed-chunked");
  2272. ASSERT_TRUE(res);
  2273. EXPECT_EQ(200, res->status);
  2274. EXPECT_EQ(std::string("123456789"), res->body);
  2275. }
  2276. TEST_F(ServerTest, GetStreamedChunked2) {
  2277. auto res = cli_.Get("/streamed-chunked2");
  2278. ASSERT_TRUE(res);
  2279. EXPECT_EQ(200, res->status);
  2280. EXPECT_EQ(std::string("123456789"), res->body);
  2281. }
  2282. TEST_F(ServerTest, LargeChunkedPost) {
  2283. Request req;
  2284. req.method = "POST";
  2285. req.path = "/large-chunked";
  2286. std::string host_and_port;
  2287. host_and_port += HOST;
  2288. host_and_port += ":";
  2289. host_and_port += std::to_string(PORT);
  2290. req.headers.emplace("Host", host_and_port.c_str());
  2291. req.headers.emplace("Accept", "*/*");
  2292. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2293. req.headers.emplace("Content-Type", "text/plain");
  2294. req.headers.emplace("Content-Length", "0");
  2295. req.headers.emplace("Transfer-Encoding", "chunked");
  2296. std::string long_string(30 * 1024u, 'a');
  2297. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2298. // Attempt to make a large enough post to exceed OS buffers, to test that
  2299. // the server handles short reads if the full chunk data isn't available.
  2300. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2301. auto res = std::make_shared<Response>();
  2302. auto error = Error::Success;
  2303. auto ret = cli_.send(req, *res, error);
  2304. ASSERT_TRUE(ret);
  2305. EXPECT_EQ(200, res->status);
  2306. }
  2307. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2308. auto res = cli_.Get("/remote_addr");
  2309. ASSERT_TRUE(res);
  2310. EXPECT_EQ(200, res->status);
  2311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2312. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2313. }
  2314. TEST_F(ServerTest, HTTPResponseSplitting) {
  2315. auto res = cli_.Get("/http_response_splitting");
  2316. ASSERT_TRUE(res);
  2317. EXPECT_EQ(200, res->status);
  2318. }
  2319. TEST_F(ServerTest, SlowRequest) {
  2320. request_threads_.push_back(
  2321. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2322. request_threads_.push_back(
  2323. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2324. request_threads_.push_back(
  2325. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2326. }
  2327. #if 0
  2328. TEST_F(ServerTest, SlowPost) {
  2329. char buffer[64 * 1024];
  2330. memset(buffer, 0x42, sizeof(buffer));
  2331. auto res = cli_.Post(
  2332. "/slowpost", 64 * 1024 * 1024,
  2333. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2334. auto ret = sink.write(buffer, sizeof(buffer));
  2335. EXPECT_TRUE(ret);
  2336. return true;
  2337. },
  2338. "text/plain");
  2339. ASSERT_TRUE(res);
  2340. EXPECT_EQ(200, res->status);
  2341. }
  2342. TEST_F(ServerTest, SlowPostFail) {
  2343. char buffer[64 * 1024];
  2344. memset(buffer, 0x42, sizeof(buffer));
  2345. cli_.set_write_timeout(std::chrono::seconds(0));
  2346. auto res = cli_.Post(
  2347. "/slowpost", 64 * 1024 * 1024,
  2348. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2349. sink.write(buffer, sizeof(buffer));
  2350. return true;
  2351. },
  2352. "text/plain");
  2353. ASSERT_TRUE(!res);
  2354. EXPECT_EQ(Error::Write, res.error());
  2355. }
  2356. #endif
  2357. TEST_F(ServerTest, Put) {
  2358. auto res = cli_.Put("/put", "PUT", "text/plain");
  2359. ASSERT_TRUE(res);
  2360. EXPECT_EQ(200, res->status);
  2361. EXPECT_EQ("PUT", res->body);
  2362. }
  2363. TEST_F(ServerTest, PutWithContentProvider) {
  2364. auto res = cli_.Put(
  2365. "/put", 3,
  2366. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2367. EXPECT_TRUE(sink.is_writable());
  2368. sink.os << "PUT";
  2369. return true;
  2370. },
  2371. "text/plain");
  2372. ASSERT_TRUE(res);
  2373. EXPECT_EQ(200, res->status);
  2374. EXPECT_EQ("PUT", res->body);
  2375. }
  2376. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2377. auto res = cli_.Post(
  2378. "/post", 42,
  2379. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2380. return false;
  2381. },
  2382. "text/plain");
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2387. auto res = cli_.Put(
  2388. "/put",
  2389. [](size_t /*offset*/, DataSink &sink) {
  2390. EXPECT_TRUE(sink.is_writable());
  2391. sink.os << "PUT";
  2392. sink.done();
  2393. return true;
  2394. },
  2395. "text/plain");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(200, res->status);
  2398. EXPECT_EQ("PUT", res->body);
  2399. }
  2400. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2401. auto res = cli_.Post(
  2402. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2403. "text/plain");
  2404. ASSERT_TRUE(!res);
  2405. EXPECT_EQ(Error::Canceled, res.error());
  2406. }
  2407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2408. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2409. cli_.set_compress(true);
  2410. auto res = cli_.Put(
  2411. "/put", 3,
  2412. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2413. EXPECT_TRUE(sink.is_writable());
  2414. sink.os << "PUT";
  2415. return true;
  2416. },
  2417. "text/plain");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(200, res->status);
  2420. EXPECT_EQ("PUT", res->body);
  2421. }
  2422. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2423. cli_.set_compress(true);
  2424. auto res = cli_.Post(
  2425. "/post", 42,
  2426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2427. return false;
  2428. },
  2429. "text/plain");
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::Canceled, res.error());
  2432. }
  2433. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2434. cli_.set_compress(true);
  2435. auto res = cli_.Put(
  2436. "/put",
  2437. [](size_t /*offset*/, DataSink &sink) {
  2438. EXPECT_TRUE(sink.is_writable());
  2439. sink.os << "PUT";
  2440. sink.done();
  2441. return true;
  2442. },
  2443. "text/plain");
  2444. ASSERT_TRUE(res);
  2445. EXPECT_EQ(200, res->status);
  2446. EXPECT_EQ("PUT", res->body);
  2447. }
  2448. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2449. cli_.set_compress(true);
  2450. auto res = cli_.Post(
  2451. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2452. "text/plain");
  2453. ASSERT_TRUE(!res);
  2454. EXPECT_EQ(Error::Canceled, res.error());
  2455. }
  2456. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2457. cli_.set_compress(true);
  2458. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(200, res->status);
  2461. EXPECT_EQ(LARGE_DATA, res->body);
  2462. }
  2463. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2466. Client cli(s.c_str());
  2467. cli.enable_server_certificate_verification(false);
  2468. #else
  2469. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2470. Client cli(s.c_str());
  2471. #endif
  2472. cli.set_compress(true);
  2473. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(200, res->status);
  2476. EXPECT_EQ(LARGE_DATA, res->body);
  2477. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2478. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2479. }
  2480. TEST_F(ServerTest, PutContentWithDeflate) {
  2481. cli_.set_compress(false);
  2482. Headers headers;
  2483. headers.emplace("Content-Encoding", "deflate");
  2484. // PUT in deflate format:
  2485. auto res = cli_.Put("/put", headers,
  2486. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2487. ASSERT_TRUE(res);
  2488. EXPECT_EQ(200, res->status);
  2489. EXPECT_EQ("PUT", res->body);
  2490. }
  2491. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2492. Headers headers;
  2493. headers.emplace("Accept-Encoding", "gzip, deflate");
  2494. auto res = cli_.Get("/streamed-chunked", headers);
  2495. ASSERT_TRUE(res);
  2496. EXPECT_EQ(200, res->status);
  2497. EXPECT_EQ(std::string("123456789"), res->body);
  2498. }
  2499. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2500. Headers headers;
  2501. headers.emplace("Accept-Encoding", "gzip, deflate");
  2502. auto res = cli_.Get("/streamed-chunked2", headers);
  2503. ASSERT_TRUE(res);
  2504. EXPECT_EQ(200, res->status);
  2505. EXPECT_EQ(std::string("123456789"), res->body);
  2506. }
  2507. TEST(GzipDecompressor, ChunkedDecompression) {
  2508. std::string data;
  2509. for (size_t i = 0; i < 32 * 1024; ++i) {
  2510. data.push_back(static_cast<char>('a' + i % 26));
  2511. }
  2512. std::string compressed_data;
  2513. {
  2514. httplib::detail::gzip_compressor compressor;
  2515. bool result = compressor.compress(
  2516. data.data(), data.size(),
  2517. /*last=*/true, [&](const char *data, size_t size) {
  2518. compressed_data.insert(compressed_data.size(), data, size);
  2519. return true;
  2520. });
  2521. ASSERT_TRUE(result);
  2522. }
  2523. std::string decompressed_data;
  2524. {
  2525. httplib::detail::gzip_decompressor decompressor;
  2526. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2527. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2528. size_t chunk_size = 130;
  2529. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2530. chunk_begin += chunk_size) {
  2531. size_t current_chunk_size =
  2532. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2533. bool result = decompressor.decompress(
  2534. compressed_data.data() + chunk_begin, current_chunk_size,
  2535. [&](const char *data, size_t size) {
  2536. decompressed_data.insert(decompressed_data.size(), data, size);
  2537. return true;
  2538. });
  2539. ASSERT_TRUE(result);
  2540. }
  2541. }
  2542. ASSERT_EQ(data, decompressed_data);
  2543. }
  2544. #ifdef _WIN32
  2545. TEST(GzipDecompressor, LargeRandomData) {
  2546. // prepare large random data that is difficult to be compressed and is
  2547. // expected to have large size even when compressed
  2548. std::random_device seed_gen;
  2549. std::mt19937 random(seed_gen());
  2550. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2551. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2552. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2553. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2554. // compress data over 4GiB
  2555. std::string compressed_data;
  2556. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2557. httplib::detail::gzip_compressor compressor;
  2558. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2559. data.size() * sizeof(std::uint32_t), true,
  2560. [&](const char *data, size_t size) {
  2561. compressed_data.insert(
  2562. compressed_data.size(), data, size);
  2563. return true;
  2564. });
  2565. ASSERT_TRUE(result);
  2566. // FIXME: compressed data size is expected to be greater than 4GiB,
  2567. // but there is no guarantee
  2568. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2569. // decompress data over 4GiB
  2570. std::string decompressed_data;
  2571. decompressed_data.reserve(data_size);
  2572. httplib::detail::gzip_decompressor decompressor;
  2573. result = decompressor.decompress(
  2574. compressed_data.data(), compressed_data.size(),
  2575. [&](const char *data, size_t size) {
  2576. decompressed_data.insert(decompressed_data.size(), data, size);
  2577. return true;
  2578. });
  2579. ASSERT_TRUE(result);
  2580. // compare
  2581. ASSERT_EQ(data_size, decompressed_data.size());
  2582. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2583. 0);
  2584. }
  2585. #endif
  2586. #endif
  2587. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2588. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2589. Headers headers;
  2590. headers.emplace("Accept-Encoding", "br");
  2591. auto res = cli_.Get("/streamed-chunked", headers);
  2592. ASSERT_TRUE(res);
  2593. EXPECT_EQ(200, res->status);
  2594. EXPECT_EQ(std::string("123456789"), res->body);
  2595. }
  2596. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2597. Headers headers;
  2598. headers.emplace("Accept-Encoding", "br");
  2599. auto res = cli_.Get("/streamed-chunked2", headers);
  2600. ASSERT_TRUE(res);
  2601. EXPECT_EQ(200, res->status);
  2602. EXPECT_EQ(std::string("123456789"), res->body);
  2603. }
  2604. #endif
  2605. TEST_F(ServerTest, Patch) {
  2606. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2607. ASSERT_TRUE(res);
  2608. EXPECT_EQ(200, res->status);
  2609. EXPECT_EQ("PATCH", res->body);
  2610. }
  2611. TEST_F(ServerTest, Delete) {
  2612. auto res = cli_.Delete("/delete");
  2613. ASSERT_TRUE(res);
  2614. EXPECT_EQ(200, res->status);
  2615. EXPECT_EQ("DELETE", res->body);
  2616. }
  2617. TEST_F(ServerTest, DeleteContentReceiver) {
  2618. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2619. ASSERT_TRUE(res);
  2620. EXPECT_EQ(200, res->status);
  2621. EXPECT_EQ("content", res->body);
  2622. }
  2623. TEST_F(ServerTest, Options) {
  2624. auto res = cli_.Options("*");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(200, res->status);
  2627. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2628. EXPECT_TRUE(res->body.empty());
  2629. }
  2630. TEST_F(ServerTest, URL) {
  2631. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(200, res->status);
  2634. }
  2635. TEST_F(ServerTest, ArrayParam) {
  2636. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(200, res->status);
  2639. }
  2640. TEST_F(ServerTest, NoMultipleHeaders) {
  2641. Headers headers = {{"Content-Length", "5"}};
  2642. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2643. "text/plain");
  2644. ASSERT_TRUE(res);
  2645. EXPECT_EQ(200, res->status);
  2646. }
  2647. TEST_F(ServerTest, PostContentReceiver) {
  2648. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2649. ASSERT_TRUE(res);
  2650. ASSERT_EQ(200, res->status);
  2651. ASSERT_EQ("content", res->body);
  2652. }
  2653. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2654. MultipartFormDataItems items = {
  2655. {"text1", "text default", "", ""},
  2656. {"text2", "aωb", "", ""},
  2657. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2658. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2659. {"file3", "", "", "application/octet-stream"},
  2660. };
  2661. auto res = cli_.Post("/content_receiver", items);
  2662. ASSERT_TRUE(res);
  2663. EXPECT_EQ(200, res->status);
  2664. }
  2665. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2666. MultipartFormDataItems items = {
  2667. {"text1", "text default", "", ""},
  2668. {"text2", "aωb", "", ""},
  2669. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2670. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2671. {"file3", "", "", "application/octet-stream"},
  2672. };
  2673. auto boundary = std::string("+++++");
  2674. std::string body;
  2675. for (const auto &item : items) {
  2676. body += "--" + boundary + "\r\n";
  2677. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2678. if (!item.filename.empty()) {
  2679. body += "; filename=\"" + item.filename + "\"";
  2680. }
  2681. body += "\r\n";
  2682. if (!item.content_type.empty()) {
  2683. body += "Content-Type: " + item.content_type + "\r\n";
  2684. }
  2685. body += "\r\n";
  2686. body += item.content + "\r\n";
  2687. }
  2688. body += "--" + boundary + "--\r\n";
  2689. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2690. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2691. ASSERT_TRUE(res);
  2692. EXPECT_EQ(200, res->status);
  2693. }
  2694. TEST_F(ServerTest, PostContentReceiverGzip) {
  2695. cli_.set_compress(true);
  2696. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2697. ASSERT_TRUE(res);
  2698. ASSERT_EQ(200, res->status);
  2699. ASSERT_EQ("content", res->body);
  2700. }
  2701. TEST_F(ServerTest, PutContentReceiver) {
  2702. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2703. ASSERT_TRUE(res);
  2704. ASSERT_EQ(200, res->status);
  2705. ASSERT_EQ("content", res->body);
  2706. }
  2707. TEST_F(ServerTest, PatchContentReceiver) {
  2708. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2709. ASSERT_TRUE(res);
  2710. ASSERT_EQ(200, res->status);
  2711. ASSERT_EQ("content", res->body);
  2712. }
  2713. TEST_F(ServerTest, PostQueryStringAndBody) {
  2714. auto res =
  2715. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2716. ASSERT_TRUE(res);
  2717. ASSERT_EQ(200, res->status);
  2718. }
  2719. TEST_F(ServerTest, HTTP2Magic) {
  2720. Request req;
  2721. req.method = "PRI";
  2722. req.path = "*";
  2723. req.body = "SM";
  2724. auto res = std::make_shared<Response>();
  2725. auto error = Error::Success;
  2726. auto ret = cli_.send(req, *res, error);
  2727. ASSERT_TRUE(ret);
  2728. EXPECT_EQ(400, res->status);
  2729. }
  2730. TEST_F(ServerTest, KeepAlive) {
  2731. auto res = cli_.Get("/hi");
  2732. ASSERT_TRUE(res);
  2733. EXPECT_EQ(200, res->status);
  2734. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2735. EXPECT_EQ("Hello World!", res->body);
  2736. res = cli_.Get("/hi");
  2737. ASSERT_TRUE(res);
  2738. EXPECT_EQ(200, res->status);
  2739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2740. EXPECT_EQ("Hello World!", res->body);
  2741. res = cli_.Get("/hi");
  2742. ASSERT_TRUE(res);
  2743. EXPECT_EQ(200, res->status);
  2744. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2745. EXPECT_EQ("Hello World!", res->body);
  2746. res = cli_.Get("/not-exist");
  2747. ASSERT_TRUE(res);
  2748. EXPECT_EQ(404, res->status);
  2749. res = cli_.Post("/empty", "", "text/plain");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(200, res->status);
  2752. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2753. EXPECT_EQ("empty", res->body);
  2754. EXPECT_EQ("close", res->get_header_value("Connection"));
  2755. res = cli_.Post(
  2756. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2757. "text/plain");
  2758. ASSERT_TRUE(res);
  2759. EXPECT_EQ(200, res->status);
  2760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2761. EXPECT_EQ("empty", res->body);
  2762. cli_.set_keep_alive(false);
  2763. res = cli_.Get("/last-request");
  2764. ASSERT_TRUE(res);
  2765. EXPECT_EQ(200, res->status);
  2766. EXPECT_EQ("close", res->get_header_value("Connection"));
  2767. }
  2768. TEST_F(ServerTest, TooManyRedirect) {
  2769. cli_.set_follow_location(true);
  2770. auto res = cli_.Get("/redirect/0");
  2771. ASSERT_TRUE(!res);
  2772. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2773. }
  2774. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2775. TEST_F(ServerTest, Gzip) {
  2776. Headers headers;
  2777. headers.emplace("Accept-Encoding", "gzip, deflate");
  2778. auto res = cli_.Get("/compress", headers);
  2779. ASSERT_TRUE(res);
  2780. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2781. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2782. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2783. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2784. "7890123456789012345678901234567890",
  2785. res->body);
  2786. EXPECT_EQ(200, res->status);
  2787. }
  2788. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2789. auto res = cli_.Get("/compress");
  2790. ASSERT_TRUE(res);
  2791. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2792. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2793. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2794. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2795. "7890123456789012345678901234567890",
  2796. res->body);
  2797. EXPECT_EQ(200, res->status);
  2798. }
  2799. TEST_F(ServerTest, GzipWithContentReceiver) {
  2800. Headers headers;
  2801. headers.emplace("Accept-Encoding", "gzip, deflate");
  2802. std::string body;
  2803. auto res = cli_.Get("/compress", headers,
  2804. [&](const char *data, uint64_t data_length) {
  2805. EXPECT_EQ(100U, data_length);
  2806. body.append(data, data_length);
  2807. return true;
  2808. });
  2809. ASSERT_TRUE(res);
  2810. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2811. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2812. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2813. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2814. "7890123456789012345678901234567890",
  2815. body);
  2816. EXPECT_EQ(200, res->status);
  2817. }
  2818. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2819. Headers headers;
  2820. headers.emplace("Accept-Encoding", "gzip, deflate");
  2821. cli_.set_decompress(false);
  2822. auto res = cli_.Get("/compress", headers);
  2823. ASSERT_TRUE(res);
  2824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2826. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2827. EXPECT_EQ(33U, res->body.size());
  2828. EXPECT_EQ(200, res->status);
  2829. }
  2830. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2831. std::string body;
  2832. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2833. EXPECT_EQ(100U, data_length);
  2834. body.append(data, data_length);
  2835. return true;
  2836. });
  2837. ASSERT_TRUE(res);
  2838. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2839. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2840. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2841. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2842. "7890123456789012345678901234567890",
  2843. body);
  2844. EXPECT_EQ(200, res->status);
  2845. }
  2846. TEST_F(ServerTest, NoGzip) {
  2847. Headers headers;
  2848. headers.emplace("Accept-Encoding", "gzip, deflate");
  2849. auto res = cli_.Get("/nocompress", headers);
  2850. ASSERT_TRUE(res);
  2851. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2852. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2853. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2854. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2855. "7890123456789012345678901234567890",
  2856. res->body);
  2857. EXPECT_EQ(200, res->status);
  2858. }
  2859. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2860. Headers headers;
  2861. headers.emplace("Accept-Encoding", "gzip, deflate");
  2862. std::string body;
  2863. auto res = cli_.Get("/nocompress", headers,
  2864. [&](const char *data, uint64_t data_length) {
  2865. EXPECT_EQ(100U, data_length);
  2866. body.append(data, data_length);
  2867. return true;
  2868. });
  2869. ASSERT_TRUE(res);
  2870. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2871. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2872. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2873. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2874. "7890123456789012345678901234567890",
  2875. body);
  2876. EXPECT_EQ(200, res->status);
  2877. }
  2878. TEST_F(ServerTest, MultipartFormDataGzip) {
  2879. MultipartFormDataItems items = {
  2880. {"key1", "test", "", ""},
  2881. {"key2", "--abcdefg123", "", ""},
  2882. };
  2883. cli_.set_compress(true);
  2884. auto res = cli_.Post("/compress-multipart", items);
  2885. ASSERT_TRUE(res);
  2886. EXPECT_EQ(200, res->status);
  2887. }
  2888. #endif
  2889. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2890. TEST_F(ServerTest, Brotli) {
  2891. Headers headers;
  2892. headers.emplace("Accept-Encoding", "br");
  2893. auto res = cli_.Get("/compress", headers);
  2894. ASSERT_TRUE(res);
  2895. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2897. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2899. "7890123456789012345678901234567890",
  2900. res->body);
  2901. EXPECT_EQ(200, res->status);
  2902. }
  2903. #endif
  2904. // Sends a raw request to a server listening at HOST:PORT.
  2905. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2906. std::string *resp = nullptr) {
  2907. auto error = Error::Success;
  2908. auto client_sock = detail::create_client_socket(
  2909. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  2910. /*connection_timeout_sec=*/5, 0,
  2911. /*read_timeout_sec=*/5, 0,
  2912. /*write_timeout_sec=*/5, 0, std::string(), error);
  2913. if (client_sock == INVALID_SOCKET) { return false; }
  2914. auto ret = detail::process_client_socket(
  2915. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2916. if (req.size() !=
  2917. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2918. return false;
  2919. }
  2920. char buf[512];
  2921. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2922. while (line_reader.getline()) {
  2923. if (resp) { *resp += line_reader.ptr(); }
  2924. }
  2925. return true;
  2926. });
  2927. detail::close_socket(client_sock);
  2928. return ret;
  2929. }
  2930. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2931. Server svr;
  2932. std::string header_value;
  2933. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2934. header_value = req.get_header_value("foo");
  2935. res.set_content("ok", "text/plain");
  2936. });
  2937. thread t = thread([&] { svr.listen(HOST, PORT); });
  2938. while (!svr.is_running()) {
  2939. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2940. }
  2941. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2942. // like characters are not treated the same - use vertical tab and escape.
  2943. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2944. "foo: \t \v bar \x1B\t \r\n"
  2945. "Connection: close\r\n"
  2946. "\r\n";
  2947. ASSERT_TRUE(send_request(5, req));
  2948. svr.stop();
  2949. t.join();
  2950. EXPECT_EQ(header_value, "\v bar \x1B");
  2951. }
  2952. // Sends a raw request and verifies that there isn't a crash or exception.
  2953. static void test_raw_request(const std::string &req,
  2954. std::string *out = nullptr) {
  2955. Server svr;
  2956. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2957. res.set_content("ok", "text/plain");
  2958. });
  2959. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2960. res.set_content("ok", "text/plain");
  2961. });
  2962. // Server read timeout must be longer than the client read timeout for the
  2963. // bug to reproduce, probably to force the server to process a request
  2964. // without a trailing blank line.
  2965. const time_t client_read_timeout_sec = 1;
  2966. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  2967. bool listen_thread_ok = false;
  2968. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2969. while (!svr.is_running()) {
  2970. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2971. }
  2972. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2973. svr.stop();
  2974. t.join();
  2975. EXPECT_TRUE(listen_thread_ok);
  2976. }
  2977. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2978. // A certain header line causes an exception if the header property is parsed
  2979. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2980. test_raw_request(
  2981. "GET /hi HTTP/1.1\r\n"
  2982. " : "
  2983. " "
  2984. " ");
  2985. }
  2986. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2987. // A certain header line causes an exception if the header property *name* is
  2988. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2989. // greedy matcher and requires backtracking when there are a lot of ":"
  2990. // characters.
  2991. // This occurs with libc++ but not libstdc++.
  2992. test_raw_request(
  2993. "GET /hi HTTP/1.1\r\n"
  2994. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2995. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2996. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2997. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2998. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2999. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3000. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3001. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3002. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3003. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3004. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3005. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3006. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3007. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3008. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3009. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3010. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3011. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3012. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3013. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3014. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3015. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3016. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3017. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3018. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3019. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3020. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3021. "&&&%%%");
  3022. }
  3023. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  3024. // Make sure this doesn't crash the server.
  3025. // In a previous version of the header line regex, the "\r" rendered the line
  3026. // unparseable and the regex engine repeatedly backtracked, trying to look for
  3027. // a new position where the leading white space ended and the field value
  3028. // began.
  3029. // The crash occurs with libc++ but not libstdc++.
  3030. test_raw_request("GET /hi HTTP/1.1\r\n"
  3031. "a:" +
  3032. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3033. "\r\n"
  3034. "\r\n");
  3035. }
  3036. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3037. std::string out;
  3038. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3039. "Content-Type: text/plain\r\n"
  3040. "Transfer-Encoding: chunked\r\n"
  3041. "\r\n"
  3042. "nothex\r\n",
  3043. &out);
  3044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3045. }
  3046. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3047. std::string out;
  3048. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3049. "Content-Type: text/plain\r\n"
  3050. "Transfer-Encoding: chunked\r\n"
  3051. "\r\n"
  3052. "3\r\n"
  3053. "xyz\r\n"
  3054. "NaN\r\n",
  3055. &out);
  3056. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3057. }
  3058. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3059. std::string out;
  3060. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3061. "Content-Type: text/plain\r\n"
  3062. "Transfer-Encoding: chunked\r\n"
  3063. "\r\n"
  3064. // Length is too large for 64 bits.
  3065. "1ffffffffffffffff\r\n"
  3066. "xyz\r\n",
  3067. &out);
  3068. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3069. }
  3070. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3071. test_raw_request("GET /hi HTTP/1.1\r\n"
  3072. "Content-Type: text/plain\r\n\r");
  3073. }
  3074. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3075. std::string out;
  3076. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3077. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3078. }
  3079. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3080. Server svr;
  3081. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3082. res.set_header("Cache-Control", "no-cache");
  3083. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3084. DataSink &sink) {
  3085. char buffer[27];
  3086. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3087. auto ret = sink.write(buffer, size);
  3088. EXPECT_TRUE(ret);
  3089. std::this_thread::sleep_for(std::chrono::seconds(1));
  3090. return true;
  3091. });
  3092. });
  3093. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3094. while (!svr.is_running()) {
  3095. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3096. }
  3097. Client client(HOST, PORT);
  3098. const Headers headers = {{"Accept", "text/event-stream"}};
  3099. auto get_thread = std::thread([&client, &headers]() {
  3100. auto res = client.Get(
  3101. "/events", headers,
  3102. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3103. });
  3104. // Give GET time to get a few messages.
  3105. std::this_thread::sleep_for(std::chrono::seconds(2));
  3106. svr.stop();
  3107. listen_thread.join();
  3108. get_thread.join();
  3109. ASSERT_FALSE(svr.is_running());
  3110. }
  3111. TEST(StreamingTest, NoContentLengthStreaming) {
  3112. Server svr;
  3113. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3114. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3115. if (offset < 6) {
  3116. sink.os << (offset < 3 ? "a" : "b");
  3117. } else {
  3118. sink.done();
  3119. }
  3120. return true;
  3121. });
  3122. });
  3123. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3124. while (!svr.is_running()) {
  3125. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3126. }
  3127. Client client(HOST, PORT);
  3128. auto get_thread = std::thread([&client]() {
  3129. std::string s;
  3130. auto res =
  3131. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3132. s += std::string(data, len);
  3133. return true;
  3134. });
  3135. EXPECT_EQ("aaabbb", s);
  3136. });
  3137. // Give GET time to get a few messages.
  3138. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3139. svr.stop();
  3140. listen_thread.join();
  3141. get_thread.join();
  3142. ASSERT_FALSE(svr.is_running());
  3143. }
  3144. TEST(MountTest, Unmount) {
  3145. Server svr;
  3146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3147. while (!svr.is_running()) {
  3148. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3149. }
  3150. // Give GET time to get a few messages.
  3151. std::this_thread::sleep_for(std::chrono::seconds(1));
  3152. Client cli("localhost", PORT);
  3153. svr.set_mount_point("/mount2", "./www2");
  3154. auto res = cli.Get("/");
  3155. ASSERT_TRUE(res);
  3156. EXPECT_EQ(404, res->status);
  3157. res = cli.Get("/mount2/dir/test.html");
  3158. ASSERT_TRUE(res);
  3159. EXPECT_EQ(200, res->status);
  3160. svr.set_mount_point("/", "./www");
  3161. res = cli.Get("/dir/");
  3162. ASSERT_TRUE(res);
  3163. EXPECT_EQ(200, res->status);
  3164. svr.remove_mount_point("/");
  3165. res = cli.Get("/dir/");
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(404, res->status);
  3168. svr.remove_mount_point("/mount2");
  3169. res = cli.Get("/mount2/dir/test.html");
  3170. ASSERT_TRUE(res);
  3171. EXPECT_EQ(404, res->status);
  3172. svr.stop();
  3173. listen_thread.join();
  3174. ASSERT_FALSE(svr.is_running());
  3175. }
  3176. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3177. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3178. Server svr;
  3179. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  3180. throw std::runtime_error("exception...");
  3181. // res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3184. while (!svr.is_running()) {
  3185. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3186. }
  3187. // Give GET time to get a few messages.
  3188. std::this_thread::sleep_for(std::chrono::seconds(1));
  3189. Client cli("localhost", PORT);
  3190. auto res = cli.Get("/hi");
  3191. ASSERT_TRUE(res);
  3192. EXPECT_EQ(500, res->status);
  3193. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3194. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3195. svr.stop();
  3196. listen_thread.join();
  3197. ASSERT_FALSE(svr.is_running());
  3198. }
  3199. #endif
  3200. TEST(KeepAliveTest, ReadTimeout) {
  3201. Server svr;
  3202. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3203. std::this_thread::sleep_for(std::chrono::seconds(2));
  3204. res.set_content("a", "text/plain");
  3205. });
  3206. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3207. res.set_content("b", "text/plain");
  3208. });
  3209. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3210. while (!svr.is_running()) {
  3211. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3212. }
  3213. // Give GET time to get a few messages.
  3214. std::this_thread::sleep_for(std::chrono::seconds(1));
  3215. Client cli("localhost", PORT);
  3216. cli.set_keep_alive(true);
  3217. cli.set_read_timeout(std::chrono::seconds(1));
  3218. auto resa = cli.Get("/a");
  3219. ASSERT_TRUE(!resa);
  3220. EXPECT_EQ(Error::Read, resa.error());
  3221. auto resb = cli.Get("/b");
  3222. ASSERT_TRUE(resb);
  3223. EXPECT_EQ(200, resb->status);
  3224. EXPECT_EQ("b", resb->body);
  3225. svr.stop();
  3226. listen_thread.join();
  3227. ASSERT_FALSE(svr.is_running());
  3228. }
  3229. TEST(KeepAliveTest, Issue1041) {
  3230. const auto resourcePath = "/hi";
  3231. Server svr;
  3232. svr.set_keep_alive_timeout(3);
  3233. svr.Get(resourcePath, [](const httplib::Request &, httplib::Response &res) {
  3234. res.set_content("Hello World!", "text/plain");
  3235. });
  3236. auto a2 = std::async(std::launch::async, [&svr] { svr.listen(HOST, PORT); });
  3237. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3238. Client cli(HOST, PORT);
  3239. cli.set_keep_alive(true);
  3240. auto result = cli.Get(resourcePath);
  3241. ASSERT_TRUE(result);
  3242. EXPECT_EQ(200, result->status);
  3243. std::this_thread::sleep_for(std::chrono::seconds(5));
  3244. result = cli.Get(resourcePath);
  3245. ASSERT_TRUE(result);
  3246. EXPECT_EQ(200, result->status);
  3247. svr.stop();
  3248. a2.wait();
  3249. }
  3250. TEST(ClientProblemDetectionTest, ContentProvider) {
  3251. Server svr;
  3252. size_t content_length = 1024 * 1024;
  3253. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3254. res.set_content_provider(
  3255. content_length, "text/plain",
  3256. [&](size_t offset, size_t length, DataSink &sink) {
  3257. auto out_len = std::min(length, static_cast<size_t>(1024));
  3258. std::string out(out_len, '@');
  3259. sink.write(out.data(), out_len);
  3260. return offset < 4096;
  3261. },
  3262. [](bool success) { ASSERT_FALSE(success); });
  3263. });
  3264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3265. while (!svr.is_running()) {
  3266. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3267. }
  3268. // Give GET time to get a few messages.
  3269. std::this_thread::sleep_for(std::chrono::seconds(1));
  3270. Client cli("localhost", PORT);
  3271. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3272. return false;
  3273. });
  3274. ASSERT_FALSE(res);
  3275. svr.stop();
  3276. listen_thread.join();
  3277. ASSERT_FALSE(svr.is_running());
  3278. }
  3279. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3280. Server svr;
  3281. svr.set_error_handler([](Request const &, Response &res) -> void {
  3282. res.set_chunked_content_provider(
  3283. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3284. sink.os << "hello";
  3285. sink.os << "world";
  3286. sink.done();
  3287. return true;
  3288. });
  3289. });
  3290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3291. while (!svr.is_running()) {
  3292. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3293. }
  3294. // Give GET time to get a few messages.
  3295. std::this_thread::sleep_for(std::chrono::seconds(1));
  3296. Client cli("localhost", PORT);
  3297. auto res = cli.Get("/");
  3298. ASSERT_TRUE(res);
  3299. EXPECT_EQ(404, res->status);
  3300. EXPECT_EQ("helloworld", res->body);
  3301. svr.stop();
  3302. listen_thread.join();
  3303. ASSERT_FALSE(svr.is_running());
  3304. }
  3305. TEST(GetWithParametersTest, GetWithParameters) {
  3306. Server svr;
  3307. svr.Get("/", [&](const Request &req, Response &) {
  3308. EXPECT_EQ("world", req.get_param_value("hello"));
  3309. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3310. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3311. });
  3312. svr.Get("/params", [&](const Request &req, Response &) {
  3313. EXPECT_EQ("world", req.get_param_value("hello"));
  3314. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3315. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3316. });
  3317. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3318. EXPECT_EQ("resource-id", req.matches[1]);
  3319. EXPECT_EQ("foo", req.get_param_value("param1"));
  3320. EXPECT_EQ("bar", req.get_param_value("param2"));
  3321. });
  3322. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3323. while (!svr.is_running()) {
  3324. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3325. }
  3326. std::this_thread::sleep_for(std::chrono::seconds(1));
  3327. {
  3328. Client cli(HOST, PORT);
  3329. Params params;
  3330. params.emplace("hello", "world");
  3331. params.emplace("hello2", "world2");
  3332. params.emplace("hello3", "world3");
  3333. auto res = cli.Get("/", params, Headers{});
  3334. ASSERT_TRUE(res);
  3335. EXPECT_EQ(200, res->status);
  3336. }
  3337. {
  3338. Client cli(HOST, PORT);
  3339. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3340. ASSERT_TRUE(res);
  3341. EXPECT_EQ(200, res->status);
  3342. }
  3343. {
  3344. Client cli(HOST, PORT);
  3345. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3346. ASSERT_TRUE(res);
  3347. EXPECT_EQ(200, res->status);
  3348. }
  3349. svr.stop();
  3350. listen_thread.join();
  3351. ASSERT_FALSE(svr.is_running());
  3352. }
  3353. TEST(GetWithParametersTest, GetWithParameters2) {
  3354. Server svr;
  3355. svr.Get("/", [&](const Request &req, Response &res) {
  3356. auto text = req.get_param_value("hello");
  3357. res.set_content(text, "text/plain");
  3358. });
  3359. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3360. while (!svr.is_running()) {
  3361. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3362. }
  3363. std::this_thread::sleep_for(std::chrono::seconds(1));
  3364. Client cli("localhost", PORT);
  3365. Params params;
  3366. params.emplace("hello", "world");
  3367. std::string body;
  3368. auto res = cli.Get("/", params, Headers{},
  3369. [&](const char *data, size_t data_length) {
  3370. body.append(data, data_length);
  3371. return true;
  3372. });
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(200, res->status);
  3375. EXPECT_EQ("world", body);
  3376. svr.stop();
  3377. listen_thread.join();
  3378. ASSERT_FALSE(svr.is_running());
  3379. }
  3380. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3381. Client cli("httpbin.org");
  3382. cli.set_default_headers({make_range_header({{1, 10}})});
  3383. cli.set_connection_timeout(5);
  3384. {
  3385. auto res = cli.Get("/range/32");
  3386. ASSERT_TRUE(res);
  3387. EXPECT_EQ("bcdefghijk", res->body);
  3388. EXPECT_EQ(206, res->status);
  3389. }
  3390. {
  3391. auto res = cli.Get("/range/32");
  3392. ASSERT_TRUE(res);
  3393. EXPECT_EQ("bcdefghijk", res->body);
  3394. EXPECT_EQ(206, res->status);
  3395. }
  3396. }
  3397. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3398. Server svr;
  3399. svr.set_default_headers({{"Hello", "World"}});
  3400. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3401. res.set_content("ok", "text/plain");
  3402. });
  3403. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3404. while (!svr.is_running()) {
  3405. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3406. }
  3407. std::this_thread::sleep_for(std::chrono::seconds(1));
  3408. Client cli("localhost", PORT);
  3409. auto res = cli.Get("/");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(200, res->status);
  3412. EXPECT_EQ("ok", res->body);
  3413. EXPECT_EQ("World", res->get_header_value("Hello"));
  3414. svr.stop();
  3415. listen_thread.join();
  3416. ASSERT_FALSE(svr.is_running());
  3417. }
  3418. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3419. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3421. ASSERT_TRUE(svr.is_valid());
  3422. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3423. std::this_thread::sleep_for(std::chrono::seconds(2));
  3424. res.set_content("a", "text/plain");
  3425. });
  3426. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3427. res.set_content("b", "text/plain");
  3428. });
  3429. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3430. while (!svr.is_running()) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3432. }
  3433. // Give GET time to get a few messages.
  3434. std::this_thread::sleep_for(std::chrono::seconds(1));
  3435. SSLClient cli("localhost", PORT);
  3436. cli.enable_server_certificate_verification(false);
  3437. cli.set_keep_alive(true);
  3438. cli.set_read_timeout(std::chrono::seconds(1));
  3439. auto resa = cli.Get("/a");
  3440. ASSERT_TRUE(!resa);
  3441. EXPECT_EQ(Error::Read, resa.error());
  3442. auto resb = cli.Get("/b");
  3443. ASSERT_TRUE(resb);
  3444. EXPECT_EQ(200, resb->status);
  3445. EXPECT_EQ("b", resb->body);
  3446. svr.stop();
  3447. listen_thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. }
  3450. #endif
  3451. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3452. protected:
  3453. ServerTestWithAI_PASSIVE()
  3454. : cli_(HOST, PORT)
  3455. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3456. ,
  3457. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3458. #endif
  3459. {
  3460. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3461. cli_.enable_server_certificate_verification(false);
  3462. #endif
  3463. }
  3464. virtual void SetUp() {
  3465. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3466. res.set_content("Hello World!", "text/plain");
  3467. });
  3468. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  3469. while (!svr_.is_running()) {
  3470. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3471. }
  3472. }
  3473. virtual void TearDown() {
  3474. svr_.stop();
  3475. t_.join();
  3476. }
  3477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3478. SSLClient cli_;
  3479. SSLServer svr_;
  3480. #else
  3481. Client cli_;
  3482. Server svr_;
  3483. #endif
  3484. thread t_;
  3485. };
  3486. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3487. auto res = cli_.Get("/hi");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(200, res->status);
  3490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3491. EXPECT_EQ("Hello World!", res->body);
  3492. }
  3493. class ServerUpDownTest : public ::testing::Test {
  3494. protected:
  3495. ServerUpDownTest() : cli_(HOST, PORT) {}
  3496. virtual void SetUp() {
  3497. t_ = thread([&]() {
  3498. svr_.bind_to_any_port(HOST);
  3499. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3500. ASSERT_TRUE(svr_.listen_after_bind());
  3501. });
  3502. while (!svr_.is_running()) {
  3503. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3504. }
  3505. }
  3506. virtual void TearDown() {
  3507. svr_.stop();
  3508. t_.join();
  3509. }
  3510. Client cli_;
  3511. Server svr_;
  3512. thread t_;
  3513. };
  3514. TEST_F(ServerUpDownTest, QuickStartStop) {
  3515. // Should not crash, especially when run with
  3516. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3517. }
  3518. class PayloadMaxLengthTest : public ::testing::Test {
  3519. protected:
  3520. PayloadMaxLengthTest()
  3521. : cli_(HOST, PORT)
  3522. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3523. ,
  3524. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3525. #endif
  3526. {
  3527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3528. cli_.enable_server_certificate_verification(false);
  3529. #endif
  3530. }
  3531. virtual void SetUp() {
  3532. svr_.set_payload_max_length(8);
  3533. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3534. res.set_content("test", "text/plain");
  3535. });
  3536. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3537. while (!svr_.is_running()) {
  3538. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3539. }
  3540. }
  3541. virtual void TearDown() {
  3542. svr_.stop();
  3543. t_.join();
  3544. }
  3545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3546. SSLClient cli_;
  3547. SSLServer svr_;
  3548. #else
  3549. Client cli_;
  3550. Server svr_;
  3551. #endif
  3552. thread t_;
  3553. };
  3554. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3555. auto res = cli_.Post("/test", "123456789", "text/plain");
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(413, res->status);
  3558. res = cli_.Post("/test", "12345678", "text/plain");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(200, res->status);
  3561. }
  3562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3563. TEST(SSLClientTest, UpdateCAStore) {
  3564. httplib::SSLClient httplib_client("www.google.com");
  3565. auto ca_store_1 = X509_STORE_new();
  3566. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3567. nullptr);
  3568. httplib_client.set_ca_cert_store(ca_store_1);
  3569. auto ca_store_2 = X509_STORE_new();
  3570. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3571. nullptr);
  3572. httplib_client.set_ca_cert_store(ca_store_2);
  3573. }
  3574. TEST(SSLClientTest, ServerNameIndication_Online) {
  3575. SSLClient cli("httpbin.org", 443);
  3576. auto res = cli.Get("/get");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(200, res->status);
  3579. }
  3580. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3581. SSLClient cli("google.com");
  3582. auto res = cli.Get("/");
  3583. ASSERT_TRUE(res);
  3584. ASSERT_EQ(301, res->status);
  3585. }
  3586. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3587. SSLClient cli("google.com");
  3588. cli.enable_server_certificate_verification(true);
  3589. cli.set_ca_cert_path("hello");
  3590. auto res = cli.Get("/");
  3591. ASSERT_TRUE(!res);
  3592. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3593. }
  3594. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3595. SSLClient cli("google.com");
  3596. cli.set_ca_cert_path(CA_CERT_FILE);
  3597. auto res = cli.Get("/");
  3598. ASSERT_TRUE(res);
  3599. ASSERT_EQ(301, res->status);
  3600. }
  3601. TEST(SSLClientTest, ServerCertificateVerification4) {
  3602. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3603. ASSERT_TRUE(svr.is_valid());
  3604. svr.Get("/test", [&](const Request &, Response &res) {
  3605. res.set_content("test", "text/plain");
  3606. svr.stop();
  3607. ASSERT_TRUE(true);
  3608. });
  3609. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3610. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3611. SSLClient cli("127.0.0.1", PORT);
  3612. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3613. cli.enable_server_certificate_verification(true);
  3614. cli.set_connection_timeout(30);
  3615. auto res = cli.Get("/test");
  3616. ASSERT_TRUE(res);
  3617. ASSERT_EQ(200, res->status);
  3618. t.join();
  3619. }
  3620. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3621. SSLClient cli("www.youtube.com");
  3622. cli.set_ca_cert_path(CA_CERT_FILE);
  3623. cli.enable_server_certificate_verification(true);
  3624. cli.set_follow_location(true);
  3625. auto res = cli.Get("/");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(200, res->status);
  3628. }
  3629. TEST(SSLClientServerTest, ClientCertPresent) {
  3630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3631. CLIENT_CA_CERT_DIR);
  3632. ASSERT_TRUE(svr.is_valid());
  3633. svr.Get("/test", [&](const Request &req, Response &res) {
  3634. res.set_content("test", "text/plain");
  3635. svr.stop();
  3636. ASSERT_TRUE(true);
  3637. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3638. ASSERT_TRUE(peer_cert != nullptr);
  3639. auto subject_name = X509_get_subject_name(peer_cert);
  3640. ASSERT_TRUE(subject_name != nullptr);
  3641. std::string common_name;
  3642. {
  3643. char name[BUFSIZ];
  3644. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3645. name, sizeof(name));
  3646. common_name.assign(name, static_cast<size_t>(name_len));
  3647. }
  3648. EXPECT_EQ("Common Name", common_name);
  3649. X509_free(peer_cert);
  3650. });
  3651. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3652. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3654. cli.enable_server_certificate_verification(false);
  3655. cli.set_connection_timeout(30);
  3656. auto res = cli.Get("/test");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(200, res->status);
  3659. t.join();
  3660. }
  3661. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3662. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3663. X509 *server_cert;
  3664. EVP_PKEY *server_private_key;
  3665. X509_STORE *client_ca_cert_store;
  3666. X509 *client_cert;
  3667. EVP_PKEY *client_private_key;
  3668. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3669. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3670. fclose(f);
  3671. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3672. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3673. fclose(f);
  3674. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3675. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3676. client_ca_cert_store = X509_STORE_new();
  3677. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3678. X509_free(client_cert);
  3679. fclose(f);
  3680. f = fopen(CLIENT_CERT_FILE, "r+");
  3681. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3682. fclose(f);
  3683. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3684. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3685. fclose(f);
  3686. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3687. ASSERT_TRUE(svr.is_valid());
  3688. svr.Get("/test", [&](const Request &req, Response &res) {
  3689. res.set_content("test", "text/plain");
  3690. svr.stop();
  3691. ASSERT_TRUE(true);
  3692. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3693. ASSERT_TRUE(peer_cert != nullptr);
  3694. auto subject_name = X509_get_subject_name(peer_cert);
  3695. ASSERT_TRUE(subject_name != nullptr);
  3696. std::string common_name;
  3697. {
  3698. char name[BUFSIZ];
  3699. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3700. name, sizeof(name));
  3701. common_name.assign(name, static_cast<size_t>(name_len));
  3702. }
  3703. EXPECT_EQ("Common Name", common_name);
  3704. X509_free(peer_cert);
  3705. });
  3706. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3707. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3708. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3709. cli.enable_server_certificate_verification(false);
  3710. cli.set_connection_timeout(30);
  3711. auto res = cli.Get("/test");
  3712. ASSERT_TRUE(res);
  3713. ASSERT_EQ(200, res->status);
  3714. X509_free(server_cert);
  3715. EVP_PKEY_free(server_private_key);
  3716. X509_free(client_cert);
  3717. EVP_PKEY_free(client_private_key);
  3718. t.join();
  3719. }
  3720. #endif
  3721. TEST(SSLClientServerTest, ClientCertMissing) {
  3722. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3723. CLIENT_CA_CERT_DIR);
  3724. ASSERT_TRUE(svr.is_valid());
  3725. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3726. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3727. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3728. SSLClient cli(HOST, PORT);
  3729. auto res = cli.Get("/test");
  3730. cli.set_connection_timeout(30);
  3731. ASSERT_TRUE(!res);
  3732. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3733. svr.stop();
  3734. t.join();
  3735. }
  3736. TEST(SSLClientServerTest, TrustDirOptional) {
  3737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3738. ASSERT_TRUE(svr.is_valid());
  3739. svr.Get("/test", [&](const Request &, Response &res) {
  3740. res.set_content("test", "text/plain");
  3741. svr.stop();
  3742. });
  3743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3744. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3745. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3746. cli.enable_server_certificate_verification(false);
  3747. cli.set_connection_timeout(30);
  3748. auto res = cli.Get("/test");
  3749. ASSERT_TRUE(res);
  3750. ASSERT_EQ(200, res->status);
  3751. t.join();
  3752. }
  3753. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3754. class NoListenSSLServer : public SSLServer {
  3755. public:
  3756. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3757. const char *client_ca_cert_file_path,
  3758. const char *client_ca_cert_dir_path = nullptr)
  3759. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3760. client_ca_cert_dir_path),
  3761. stop_(false) {}
  3762. bool stop_;
  3763. private:
  3764. bool process_and_close_socket(socket_t /*sock*/) override {
  3765. // Don't create SSL context
  3766. while (!stop_) {
  3767. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3768. }
  3769. return true;
  3770. }
  3771. };
  3772. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3773. CLIENT_CA_CERT_FILE);
  3774. ASSERT_TRUE(svr.is_valid());
  3775. svr.Get("/test", [&](const Request &, Response &res) {
  3776. res.set_content("test", "text/plain");
  3777. });
  3778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3779. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3780. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3781. cli.enable_server_certificate_verification(false);
  3782. cli.set_connection_timeout(1);
  3783. auto res = cli.Get("/test");
  3784. ASSERT_TRUE(!res);
  3785. EXPECT_EQ(Error::SSLConnection, res.error());
  3786. svr.stop_ = true;
  3787. svr.stop();
  3788. t.join();
  3789. }
  3790. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  3791. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  3792. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  3793. SSL_CTX_set_options(&ssl_ctx,
  3794. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3795. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  3796. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  3797. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  3798. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  3799. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  3800. "ECDHE-DSS-AES128-SHA256:"
  3801. "ECDHE-RSA-AES256-SHA256:"
  3802. "ECDHE-DSS-AES256-SHA256:";
  3803. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  3804. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  3805. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  3806. SSL_FILETYPE_PEM) != 1) {
  3807. return false;
  3808. }
  3809. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  3810. CLIENT_CA_CERT_DIR);
  3811. SSL_CTX_set_verify(
  3812. &ssl_ctx,
  3813. SSL_VERIFY_PEER |
  3814. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3815. nullptr);
  3816. return true;
  3817. };
  3818. SSLServer svr(setup_ssl_ctx_callback);
  3819. ASSERT_TRUE(svr.is_valid());
  3820. svr.Get("/test", [&](const Request &req, Response &res) {
  3821. res.set_content("test", "text/plain");
  3822. svr.stop();
  3823. ASSERT_TRUE(true);
  3824. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3825. ASSERT_TRUE(peer_cert != nullptr);
  3826. auto subject_name = X509_get_subject_name(peer_cert);
  3827. ASSERT_TRUE(subject_name != nullptr);
  3828. std::string common_name;
  3829. {
  3830. char name[BUFSIZ];
  3831. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3832. name, sizeof(name));
  3833. common_name.assign(name, static_cast<size_t>(name_len));
  3834. }
  3835. EXPECT_EQ("Common Name", common_name);
  3836. X509_free(peer_cert);
  3837. });
  3838. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3839. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3840. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3841. cli.enable_server_certificate_verification(false);
  3842. cli.set_connection_timeout(30);
  3843. auto res = cli.Get("/test");
  3844. ASSERT_TRUE(res);
  3845. ASSERT_EQ(200, res->status);
  3846. t.join();
  3847. }
  3848. #endif
  3849. #ifdef _WIN32
  3850. TEST(CleanupTest, WSACleanup) {
  3851. int ret = WSACleanup();
  3852. ASSERT_EQ(0, ret);
  3853. }
  3854. #endif
  3855. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3856. TEST(NoSSLSupport, SimpleInterface) {
  3857. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3858. }
  3859. #endif
  3860. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3861. TEST(InvalidScheme, SimpleInterface) {
  3862. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3863. }
  3864. #endif
  3865. TEST(NoScheme, SimpleInterface) {
  3866. Client cli("yahoo.com:80");
  3867. ASSERT_TRUE(cli.is_valid());
  3868. }
  3869. TEST(SendAPI, SimpleInterface_Online) {
  3870. Client cli("http://yahoo.com");
  3871. Request req;
  3872. req.method = "GET";
  3873. req.path = "/";
  3874. auto res = cli.send(req);
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(301, res->status);
  3877. }
  3878. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3879. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  3880. Client cli("http://yahoo.com");
  3881. auto res = cli.Get("/");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(301, res->status);
  3884. cli.set_follow_location(true);
  3885. res = cli.Get("/");
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(200, res->status);
  3888. EXPECT_EQ("https://yahoo.com/", res->location);
  3889. }
  3890. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  3891. Client cli("https://yahoo.com");
  3892. auto res = cli.Get("/");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(301, res->status);
  3895. cli.set_follow_location(true);
  3896. res = cli.Get("/");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(200, res->status);
  3899. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3900. }
  3901. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  3902. Client cli("https://yahoo.com");
  3903. auto res = cli.Get("/");
  3904. ASSERT_TRUE(res);
  3905. ASSERT_FALSE(!res);
  3906. ASSERT_TRUE(res);
  3907. ASSERT_FALSE(res == nullptr);
  3908. ASSERT_TRUE(res != nullptr);
  3909. EXPECT_EQ(Error::Success, res.error());
  3910. EXPECT_EQ(301, res.value().status);
  3911. EXPECT_EQ(301, (*res).status);
  3912. EXPECT_EQ(301, res->status);
  3913. cli.set_follow_location(true);
  3914. res = cli.Get("/");
  3915. ASSERT_TRUE(res);
  3916. EXPECT_EQ(Error::Success, res.error());
  3917. EXPECT_EQ(200, res.value().status);
  3918. EXPECT_EQ(200, (*res).status);
  3919. EXPECT_EQ(200, res->status);
  3920. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3921. }
  3922. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3923. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  3924. Client cli("https://cdnjs.cloudflare.com");
  3925. auto res =
  3926. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(200, res->status);
  3929. EXPECT_EQ(287630U, res->body.size());
  3930. EXPECT_EQ("application/javascript; charset=utf-8",
  3931. res->get_header_value("Content-Type"));
  3932. }
  3933. #endif
  3934. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  3935. Client cli("https://nghttp2.org");
  3936. cli.set_follow_location(true);
  3937. auto res =
  3938. cli.Get("/httpbin/"
  3939. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(200, res->status);
  3942. }
  3943. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  3944. Client cli("https://nghttp2.org");
  3945. cli.set_follow_location(true);
  3946. Params params;
  3947. params.emplace("url", "http://www.google.com");
  3948. params.emplace("status_code", "302");
  3949. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(200, res->status);
  3952. }
  3953. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  3954. Client cli("https://nghttp2.org");
  3955. cli.set_follow_location(true);
  3956. Params params;
  3957. params.emplace("url", "http://www.google.com");
  3958. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(200, res->status);
  3961. }
  3962. TEST(HttpToHttpsRedirectTest, CertFile) {
  3963. Server svr;
  3964. ASSERT_TRUE(svr.is_valid());
  3965. svr.Get("/index", [&](const Request &, Response &res) {
  3966. res.set_redirect("https://127.0.0.1:1235/index");
  3967. svr.stop();
  3968. });
  3969. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3970. ASSERT_TRUE(ssl_svr.is_valid());
  3971. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  3972. res.set_content("test", "text/plain");
  3973. ssl_svr.stop();
  3974. });
  3975. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3976. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  3977. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3978. Client cli("127.0.0.1", PORT);
  3979. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3980. cli.enable_server_certificate_verification(true);
  3981. cli.set_follow_location(true);
  3982. cli.set_connection_timeout(30);
  3983. auto res = cli.Get("/index");
  3984. ASSERT_TRUE(res);
  3985. ASSERT_EQ(200, res->status);
  3986. t.join();
  3987. t2.join();
  3988. }
  3989. #endif