test.cc 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  1. #include <httplib.h>
  2. #include <gtest/gtest.h>
  3. #include <chrono>
  4. #include <future>
  5. #include <thread>
  6. #define SERVER_CERT_FILE "./cert.pem"
  7. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  8. #define CA_CERT_FILE "./ca-bundle.crt"
  9. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  10. #define CLIENT_CA_CERT_DIR "."
  11. #define CLIENT_CERT_FILE "./client.cert.pem"
  12. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  13. using namespace std;
  14. using namespace httplib;
  15. const char *HOST = "localhost";
  16. const int PORT = 1234;
  17. const string LONG_QUERY_VALUE = string(25000, '@');
  18. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  19. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  20. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  21. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  22. const char *key) {
  23. auto it = std::find_if(
  24. files.begin(), files.end(),
  25. [&](const MultipartFormData &file) { return file.name == key; });
  26. if (it != files.end()) { return *it; }
  27. throw std::runtime_error("invalid mulitpart form data name error");
  28. }
  29. #ifdef _WIN32
  30. TEST(StartupTest, WSAStartup) {
  31. WSADATA wsaData;
  32. int ret = WSAStartup(0x0002, &wsaData);
  33. ASSERT_EQ(0, ret);
  34. }
  35. #endif
  36. TEST(SplitTest, ParseQueryString) {
  37. string s = "key1=val1&key2=val2&key3=val3";
  38. Params dic;
  39. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  40. [&](const char *b, const char *e) {
  41. string key, val;
  42. detail::split(b, e, '=', [&](const char *b, const char *e) {
  43. if (key.empty()) {
  44. key.assign(b, e);
  45. } else {
  46. val.assign(b, e);
  47. }
  48. });
  49. dic.emplace(key, val);
  50. });
  51. EXPECT_EQ("val1", dic.find("key1")->second);
  52. EXPECT_EQ("val2", dic.find("key2")->second);
  53. EXPECT_EQ("val3", dic.find("key3")->second);
  54. }
  55. TEST(ParseQueryTest, ParseQueryString) {
  56. string s = "key1=val1&key2=val2&key3=val3";
  57. Params dic;
  58. detail::parse_query_text(s, dic);
  59. EXPECT_EQ("val1", dic.find("key1")->second);
  60. EXPECT_EQ("val2", dic.find("key2")->second);
  61. EXPECT_EQ("val3", dic.find("key3")->second);
  62. }
  63. TEST(GetHeaderValueTest, DefaultValue) {
  64. Headers headers = {{"Dummy", "Dummy"}};
  65. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  66. EXPECT_STREQ("text/plain", val);
  67. }
  68. TEST(GetHeaderValueTest, DefaultValueInt) {
  69. Headers headers = {{"Dummy", "Dummy"}};
  70. auto val = detail::get_header_value_uint64(headers, "Content-Length", 100);
  71. EXPECT_EQ(100ull, val);
  72. }
  73. TEST(GetHeaderValueTest, RegularValue) {
  74. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  75. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  76. EXPECT_STREQ("text/html", val);
  77. }
  78. TEST(GetHeaderValueTest, RegularValueInt) {
  79. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  80. auto val = detail::get_header_value_uint64(headers, "Content-Length", 0);
  81. EXPECT_EQ(100ull, val);
  82. }
  83. TEST(GetHeaderValueTest, Range) {
  84. {
  85. Headers headers = {make_range_header({{1, -1}})};
  86. auto val = detail::get_header_value(headers, "Range", 0, 0);
  87. EXPECT_STREQ("bytes=1-", val);
  88. }
  89. {
  90. Headers headers = {make_range_header({{-1, 1}})};
  91. auto val = detail::get_header_value(headers, "Range", 0, 0);
  92. EXPECT_STREQ("bytes=-1", val);
  93. }
  94. {
  95. Headers headers = {make_range_header({{1, 10}})};
  96. auto val = detail::get_header_value(headers, "Range", 0, 0);
  97. EXPECT_STREQ("bytes=1-10", val);
  98. }
  99. {
  100. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  101. auto val = detail::get_header_value(headers, "Range", 0, 0);
  102. EXPECT_STREQ("bytes=1-10, 100-", val);
  103. }
  104. {
  105. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  106. auto val = detail::get_header_value(headers, "Range", 0, 0);
  107. EXPECT_STREQ("bytes=1-10, 100-200", val);
  108. }
  109. {
  110. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  111. auto val = detail::get_header_value(headers, "Range", 0, 0);
  112. EXPECT_STREQ("bytes=0-0, -1", val);
  113. }
  114. }
  115. TEST(ParseHeaderValueTest, Range) {
  116. {
  117. Ranges ranges;
  118. auto ret = detail::parse_range_header("bytes=1-", ranges);
  119. EXPECT_TRUE(ret);
  120. EXPECT_EQ(1u, ranges.size());
  121. EXPECT_EQ(1u, ranges[0].first);
  122. EXPECT_EQ(-1, ranges[0].second);
  123. }
  124. {
  125. Ranges ranges;
  126. auto ret = detail::parse_range_header("bytes=-1", ranges);
  127. EXPECT_TRUE(ret);
  128. EXPECT_EQ(1u, ranges.size());
  129. EXPECT_EQ(-1, ranges[0].first);
  130. EXPECT_EQ(1u, ranges[0].second);
  131. }
  132. {
  133. Ranges ranges;
  134. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  135. EXPECT_TRUE(ret);
  136. EXPECT_EQ(1u, ranges.size());
  137. EXPECT_EQ(1u, ranges[0].first);
  138. EXPECT_EQ(10u, ranges[0].second);
  139. }
  140. {
  141. Ranges ranges;
  142. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  143. EXPECT_FALSE(ret);
  144. }
  145. {
  146. Ranges ranges;
  147. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  148. EXPECT_TRUE(ret);
  149. EXPECT_EQ(2u, ranges.size());
  150. EXPECT_EQ(1u, ranges[0].first);
  151. EXPECT_EQ(10u, ranges[0].second);
  152. EXPECT_EQ(100u, ranges[1].first);
  153. EXPECT_EQ(-1, ranges[1].second);
  154. }
  155. {
  156. Ranges ranges;
  157. auto ret =
  158. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  159. EXPECT_TRUE(ret);
  160. EXPECT_EQ(3u, ranges.size());
  161. EXPECT_EQ(1u, ranges[0].first);
  162. EXPECT_EQ(10u, ranges[0].second);
  163. EXPECT_EQ(100u, ranges[1].first);
  164. EXPECT_EQ(200u, ranges[1].second);
  165. EXPECT_EQ(300u, ranges[2].first);
  166. EXPECT_EQ(400u, ranges[2].second);
  167. }
  168. }
  169. TEST(BufferStreamTest, read) {
  170. detail::BufferStream strm1;
  171. Stream& strm = strm1;
  172. EXPECT_EQ(5, strm.write("hello"));
  173. char buf[512];
  174. EXPECT_EQ(2, strm.read(buf, 2));
  175. EXPECT_EQ('h', buf[0]);
  176. EXPECT_EQ('e', buf[1]);
  177. EXPECT_EQ(2, strm.read(buf, 2));
  178. EXPECT_EQ('l', buf[0]);
  179. EXPECT_EQ('l', buf[1]);
  180. EXPECT_EQ(1, strm.read(buf, 1));
  181. EXPECT_EQ('o', buf[0]);
  182. EXPECT_EQ(0, strm.read(buf, 1));
  183. }
  184. TEST(ChunkedEncodingTest, FromHTTPWatch) {
  185. auto host = "www.httpwatch.com";
  186. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  187. auto port = 443;
  188. httplib::SSLClient cli(host, port);
  189. #else
  190. auto port = 80;
  191. httplib::Client cli(host, port);
  192. #endif
  193. cli.set_timeout_sec(2);
  194. auto res =
  195. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  196. ASSERT_TRUE(res != nullptr);
  197. std::string out;
  198. httplib::detail::read_file("./image.jpg", out);
  199. EXPECT_EQ(200, res->status);
  200. EXPECT_EQ(out, res->body);
  201. }
  202. TEST(ChunkedEncodingTest, WithContentReceiver) {
  203. auto host = "www.httpwatch.com";
  204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  205. auto port = 443;
  206. httplib::SSLClient cli(host, port);
  207. #else
  208. auto port = 80;
  209. httplib::Client cli(host, port);
  210. #endif
  211. cli.set_timeout_sec(2);
  212. std::string body;
  213. auto res =
  214. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  215. [&](const char *data, size_t data_length) {
  216. body.append(data, data_length);
  217. return true;
  218. });
  219. ASSERT_TRUE(res != nullptr);
  220. std::string out;
  221. httplib::detail::read_file("./image.jpg", out);
  222. EXPECT_EQ(200, res->status);
  223. EXPECT_EQ(out, body);
  224. }
  225. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  226. auto host = "www.httpwatch.com";
  227. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  228. auto port = 443;
  229. httplib::SSLClient cli(host, port);
  230. #else
  231. auto port = 80;
  232. httplib::Client cli(host, port);
  233. #endif
  234. cli.set_timeout_sec(2);
  235. std::string body;
  236. auto res = cli.Get(
  237. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137", Headers(),
  238. [&](const Response &response) {
  239. EXPECT_EQ(200, response.status);
  240. return true;
  241. },
  242. [&](const char *data, size_t data_length) {
  243. body.append(data, data_length);
  244. return true;
  245. });
  246. ASSERT_TRUE(res != nullptr);
  247. std::string out;
  248. httplib::detail::read_file("./image.jpg", out);
  249. EXPECT_EQ(200, res->status);
  250. EXPECT_EQ(out, body);
  251. }
  252. TEST(RangeTest, FromHTTPBin) {
  253. auto host = "httpbin.org";
  254. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  255. auto port = 443;
  256. httplib::SSLClient cli(host, port);
  257. #else
  258. auto port = 80;
  259. httplib::Client cli(host, port);
  260. #endif
  261. cli.set_timeout_sec(5);
  262. {
  263. httplib::Headers headers;
  264. auto res = cli.Get("/range/32", headers);
  265. ASSERT_TRUE(res != nullptr);
  266. EXPECT_EQ(res->body, "abcdefghijklmnopqrstuvwxyzabcdef");
  267. EXPECT_EQ(200, res->status);
  268. }
  269. {
  270. httplib::Headers headers = {httplib::make_range_header({{1, -1}})};
  271. auto res = cli.Get("/range/32", headers);
  272. ASSERT_TRUE(res != nullptr);
  273. EXPECT_EQ(res->body, "bcdefghijklmnopqrstuvwxyzabcdef");
  274. EXPECT_EQ(206, res->status);
  275. }
  276. {
  277. httplib::Headers headers = {httplib::make_range_header({{1, 10}})};
  278. auto res = cli.Get("/range/32", headers);
  279. ASSERT_TRUE(res != nullptr);
  280. EXPECT_EQ(res->body, "bcdefghijk");
  281. EXPECT_EQ(206, res->status);
  282. }
  283. {
  284. httplib::Headers headers = {httplib::make_range_header({{0, 31}})};
  285. auto res = cli.Get("/range/32", headers);
  286. ASSERT_TRUE(res != nullptr);
  287. EXPECT_EQ(res->body, "abcdefghijklmnopqrstuvwxyzabcdef");
  288. EXPECT_EQ(200, res->status);
  289. }
  290. {
  291. httplib::Headers headers = {httplib::make_range_header({{0, -1}})};
  292. auto res = cli.Get("/range/32", headers);
  293. ASSERT_TRUE(res != nullptr);
  294. EXPECT_EQ(res->body, "abcdefghijklmnopqrstuvwxyzabcdef");
  295. EXPECT_EQ(200, res->status);
  296. }
  297. {
  298. httplib::Headers headers = {httplib::make_range_header({{0, 32}})};
  299. auto res = cli.Get("/range/32", headers);
  300. ASSERT_TRUE(res != nullptr);
  301. EXPECT_EQ(416, res->status);
  302. }
  303. }
  304. TEST(ConnectionErrorTest, InvalidHost) {
  305. auto host = "-abcde.com";
  306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  307. auto port = 443;
  308. httplib::SSLClient cli(host, port);
  309. #else
  310. auto port = 80;
  311. httplib::Client cli(host, port);
  312. #endif
  313. cli.set_timeout_sec(2);
  314. auto res = cli.Get("/");
  315. ASSERT_TRUE(res == nullptr);
  316. }
  317. TEST(ConnectionErrorTest, InvalidPort) {
  318. auto host = "localhost";
  319. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  320. auto port = 44380;
  321. httplib::SSLClient cli(host, port);
  322. #else
  323. auto port = 8080;
  324. httplib::Client cli(host, port);
  325. #endif
  326. cli.set_timeout_sec(2);
  327. auto res = cli.Get("/");
  328. ASSERT_TRUE(res == nullptr);
  329. }
  330. TEST(ConnectionErrorTest, Timeout) {
  331. auto host = "google.com";
  332. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  333. auto port = 44380;
  334. httplib::SSLClient cli(host, port);
  335. #else
  336. auto port = 8080;
  337. httplib::Client cli(host, port);
  338. #endif
  339. cli.set_timeout_sec(2);
  340. auto res = cli.Get("/");
  341. ASSERT_TRUE(res == nullptr);
  342. }
  343. TEST(CancelTest, NoCancel) {
  344. auto host = "httpbin.org";
  345. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  346. auto port = 443;
  347. httplib::SSLClient cli(host, port);
  348. #else
  349. auto port = 80;
  350. httplib::Client cli(host, port);
  351. #endif
  352. cli.set_timeout_sec(5);
  353. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  354. ASSERT_TRUE(res != nullptr);
  355. EXPECT_EQ(res->body, "abcdefghijklmnopqrstuvwxyzabcdef");
  356. EXPECT_EQ(200, res->status);
  357. }
  358. TEST(CancelTest, WithCancelSmallPayload) {
  359. auto host = "httpbin.org";
  360. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  361. auto port = 443;
  362. httplib::SSLClient cli(host, port);
  363. #else
  364. auto port = 80;
  365. httplib::Client cli(host, port);
  366. #endif
  367. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  368. cli.set_timeout_sec(5);
  369. ASSERT_TRUE(res == nullptr);
  370. }
  371. TEST(CancelTest, WithCancelLargePayload) {
  372. auto host = "httpbin.org";
  373. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  374. auto port = 443;
  375. httplib::SSLClient cli(host, port);
  376. #else
  377. auto port = 80;
  378. httplib::Client cli(host, port);
  379. #endif
  380. cli.set_timeout_sec(5);
  381. uint32_t count = 0;
  382. httplib::Headers headers;
  383. auto res = cli.Get("/range/65536", headers,
  384. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  385. ASSERT_TRUE(res == nullptr);
  386. }
  387. TEST(BaseAuthTest, FromHTTPWatch) {
  388. auto host = "httpbin.org";
  389. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  390. auto port = 443;
  391. httplib::SSLClient cli(host, port);
  392. #else
  393. auto port = 80;
  394. httplib::Client cli(host, port);
  395. #endif
  396. {
  397. auto res = cli.Get("/basic-auth/hello/world");
  398. ASSERT_TRUE(res != nullptr);
  399. EXPECT_EQ(401, res->status);
  400. }
  401. {
  402. auto res =
  403. cli.Get("/basic-auth/hello/world",
  404. {httplib::make_basic_authentication_header("hello", "world")});
  405. ASSERT_TRUE(res != nullptr);
  406. EXPECT_EQ(res->body,
  407. "{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n");
  408. EXPECT_EQ(200, res->status);
  409. }
  410. {
  411. cli.set_basic_auth("hello", "world");
  412. auto res = cli.Get("/basic-auth/hello/world");
  413. ASSERT_TRUE(res != nullptr);
  414. EXPECT_EQ(res->body,
  415. "{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n");
  416. EXPECT_EQ(200, res->status);
  417. }
  418. {
  419. cli.set_basic_auth("hello", "bad");
  420. auto res = cli.Get("/basic-auth/hello/world");
  421. ASSERT_TRUE(res != nullptr);
  422. EXPECT_EQ(401, res->status);
  423. }
  424. {
  425. cli.set_basic_auth("bad", "world");
  426. auto res = cli.Get("/basic-auth/hello/world");
  427. ASSERT_TRUE(res != nullptr);
  428. EXPECT_EQ(401, res->status);
  429. }
  430. }
  431. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  432. TEST(DigestAuthTest, FromHTTPWatch) {
  433. auto host = "httpbin.org";
  434. auto port = 443;
  435. httplib::SSLClient cli(host, port);
  436. {
  437. auto res = cli.Get("/digest-auth/auth/hello/world");
  438. ASSERT_TRUE(res != nullptr);
  439. EXPECT_EQ(401, res->status);
  440. }
  441. {
  442. std::vector<std::string> paths = {
  443. "/digest-auth/auth/hello/world/MD5",
  444. "/digest-auth/auth/hello/world/SHA-256",
  445. "/digest-auth/auth/hello/world/SHA-512",
  446. "/digest-auth/auth-int/hello/world/MD5",
  447. };
  448. cli.set_digest_auth("hello", "world");
  449. for (auto path : paths) {
  450. auto res = cli.Get(path.c_str());
  451. ASSERT_TRUE(res != nullptr);
  452. EXPECT_EQ(res->body,
  453. "{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n");
  454. EXPECT_EQ(200, res->status);
  455. }
  456. cli.set_digest_auth("hello", "bad");
  457. for (auto path : paths) {
  458. auto res = cli.Get(path.c_str());
  459. ASSERT_TRUE(res != nullptr);
  460. EXPECT_EQ(400, res->status);
  461. }
  462. cli.set_digest_auth("bad", "world");
  463. for (auto path : paths) {
  464. auto res = cli.Get(path.c_str());
  465. ASSERT_TRUE(res != nullptr);
  466. EXPECT_EQ(400, res->status);
  467. }
  468. }
  469. }
  470. #endif
  471. TEST(AbsoluteRedirectTest, Redirect) {
  472. auto host = "httpbin.org";
  473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  474. httplib::SSLClient cli(host);
  475. #else
  476. httplib::Client cli(host);
  477. #endif
  478. cli.set_follow_location(true);
  479. auto res = cli.Get("/absolute-redirect/3");
  480. ASSERT_TRUE(res != nullptr);
  481. EXPECT_EQ(200, res->status);
  482. }
  483. TEST(RedirectTest, Redirect) {
  484. auto host = "httpbin.org";
  485. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  486. httplib::SSLClient cli(host);
  487. #else
  488. httplib::Client cli(host);
  489. #endif
  490. cli.set_follow_location(true);
  491. auto res = cli.Get("/redirect/3");
  492. ASSERT_TRUE(res != nullptr);
  493. EXPECT_EQ(200, res->status);
  494. }
  495. TEST(RelativeRedirectTest, Redirect) {
  496. auto host = "httpbin.org";
  497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  498. httplib::SSLClient cli(host);
  499. #else
  500. httplib::Client cli(host);
  501. #endif
  502. cli.set_follow_location(true);
  503. auto res = cli.Get("/relative-redirect/3");
  504. ASSERT_TRUE(res != nullptr);
  505. EXPECT_EQ(200, res->status);
  506. }
  507. TEST(TooManyRedirectTest, Redirect) {
  508. auto host = "httpbin.org";
  509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  510. httplib::SSLClient cli(host);
  511. #else
  512. httplib::Client cli(host);
  513. #endif
  514. cli.set_follow_location(true);
  515. auto res = cli.Get("/redirect/21");
  516. ASSERT_TRUE(res == nullptr);
  517. }
  518. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  519. TEST(YahooRedirectTest, Redirect) {
  520. httplib::Client cli("yahoo.com");
  521. auto res = cli.Get("/");
  522. ASSERT_TRUE(res != nullptr);
  523. EXPECT_EQ(301, res->status);
  524. cli.set_follow_location(true);
  525. res = cli.Get("/");
  526. ASSERT_TRUE(res != nullptr);
  527. EXPECT_EQ(200, res->status);
  528. }
  529. TEST(HttpsToHttpRedirectTest, Redirect) {
  530. httplib::SSLClient cli("httpbin.org");
  531. cli.set_follow_location(true);
  532. auto res =
  533. cli.Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  534. ASSERT_TRUE(res != nullptr);
  535. }
  536. #endif
  537. TEST(Server, BindAndListenSeparately) {
  538. Server svr;
  539. int port = svr.bind_to_any_port("localhost");
  540. ASSERT_TRUE(port > 0);
  541. svr.stop();
  542. }
  543. class ServerTest : public ::testing::Test {
  544. protected:
  545. ServerTest()
  546. : cli_(HOST, PORT)
  547. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  548. ,
  549. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  550. #endif
  551. {
  552. }
  553. virtual void SetUp() {
  554. svr_.set_mount_point("./www", "/");
  555. svr_.set_mount_point("./www2", "/mount");
  556. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  557. svr_.Get("/hi",
  558. [&](const Request & /*req*/, Response &res) {
  559. res.set_content("Hello World!", "text/plain");
  560. })
  561. .Get("/slow",
  562. [&](const Request & /*req*/, Response &res) {
  563. std::this_thread::sleep_for(std::chrono::seconds(2));
  564. res.set_content("slow", "text/plain");
  565. })
  566. .Get("/remote_addr",
  567. [&](const Request &req, Response &res) {
  568. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  569. res.set_content(remote_addr.c_str(), "text/plain");
  570. })
  571. .Get("/endwith%",
  572. [&](const Request & /*req*/, Response &res) {
  573. res.set_content("Hello World!", "text/plain");
  574. })
  575. .Get("/", [&](const Request & /*req*/,
  576. Response &res) { res.set_redirect("/hi"); })
  577. .Post("/person",
  578. [&](const Request &req, Response &res) {
  579. if (req.has_param("name") && req.has_param("note")) {
  580. persons_[req.get_param_value("name")] =
  581. req.get_param_value("note");
  582. } else {
  583. res.status = 400;
  584. }
  585. })
  586. .Put("/person",
  587. [&](const Request &req, Response &res) {
  588. if (req.has_param("name") && req.has_param("note")) {
  589. persons_[req.get_param_value("name")] =
  590. req.get_param_value("note");
  591. } else {
  592. res.status = 400;
  593. }
  594. })
  595. .Get("/person/(.*)",
  596. [&](const Request &req, Response &res) {
  597. string name = req.matches[1];
  598. if (persons_.find(name) != persons_.end()) {
  599. auto note = persons_[name];
  600. res.set_content(note, "text/plain");
  601. } else {
  602. res.status = 404;
  603. }
  604. })
  605. .Post("/x-www-form-urlencoded-json",
  606. [&](const Request &req, Response &res) {
  607. auto json = req.get_param_value("json");
  608. ASSERT_EQ(JSON_DATA, json);
  609. res.set_content(json, "appliation/json");
  610. res.status = 200;
  611. })
  612. .Get("/streamed-chunked",
  613. [&](const Request & /*req*/, Response &res) {
  614. res.set_chunked_content_provider(
  615. [](uint64_t /*offset*/, DataSink &sink) {
  616. ASSERT_TRUE(sink.is_writable());
  617. sink.write("123", 3);
  618. sink.write("456", 3);
  619. sink.write("789", 3);
  620. sink.done();
  621. });
  622. })
  623. .Get("/streamed-chunked2",
  624. [&](const Request & /*req*/, Response &res) {
  625. auto i = new int(0);
  626. res.set_chunked_content_provider(
  627. [i](uint64_t /*offset*/, DataSink &sink) {
  628. ASSERT_TRUE(sink.is_writable());
  629. switch (*i) {
  630. case 0: sink.write("123", 3); break;
  631. case 1: sink.write("456", 3); break;
  632. case 2: sink.write("789", 3); break;
  633. case 3: sink.done(); break;
  634. }
  635. (*i)++;
  636. },
  637. [i] { delete i; });
  638. })
  639. .Get("/streamed",
  640. [&](const Request & /*req*/, Response &res) {
  641. res.set_content_provider(
  642. 6, [](uint64_t offset, uint64_t /*length*/, DataSink &sink) {
  643. sink.write(offset < 3 ? "a" : "b", 1);
  644. });
  645. })
  646. .Get("/streamed-with-range",
  647. [&](const Request & /*req*/, Response &res) {
  648. auto data = new std::string("abcdefg");
  649. res.set_content_provider(
  650. data->size(),
  651. [data](uint64_t offset, uint64_t length, DataSink &sink) {
  652. ASSERT_TRUE(sink.is_writable());
  653. size_t DATA_CHUNK_SIZE = 4;
  654. const auto &d = *data;
  655. auto out_len =
  656. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  657. sink.write(&d[static_cast<size_t>(offset)], out_len);
  658. },
  659. [data] { delete data; });
  660. })
  661. .Get("/streamed-cancel",
  662. [&](const Request & /*req*/, Response &res) {
  663. res.set_content_provider(size_t(-1), [](uint64_t /*offset*/,
  664. uint64_t /*length*/,
  665. DataSink &sink) {
  666. ASSERT_TRUE(sink.is_writable());
  667. std::string data = "data_chunk";
  668. sink.write(data.data(), data.size());
  669. });
  670. })
  671. .Get("/with-range",
  672. [&](const Request & /*req*/, Response &res) {
  673. res.set_content("abcdefg", "text/plain");
  674. })
  675. .Post("/chunked",
  676. [&](const Request &req, Response & /*res*/) {
  677. EXPECT_EQ(req.body, "dechunked post body");
  678. })
  679. .Post("/large-chunked",
  680. [&](const Request &req, Response & /*res*/) {
  681. std::string expected(6 * 30 * 1024u, 'a');
  682. EXPECT_EQ(req.body, expected);
  683. })
  684. .Post("/multipart",
  685. [&](const Request &req, Response & /*res*/) {
  686. EXPECT_EQ(5u, req.files.size());
  687. ASSERT_TRUE(!req.has_file("???"));
  688. {
  689. const auto &file = req.get_file_value("text1");
  690. EXPECT_EQ("", file.filename);
  691. EXPECT_EQ("text default", file.content);
  692. }
  693. {
  694. const auto &file = req.get_file_value("text2");
  695. EXPECT_EQ("", file.filename);
  696. EXPECT_EQ("aωb", file.content);
  697. }
  698. {
  699. const auto &file = req.get_file_value("file1");
  700. EXPECT_EQ("hello.txt", file.filename);
  701. EXPECT_EQ("text/plain", file.content_type);
  702. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  703. }
  704. {
  705. const auto &file = req.get_file_value("file3");
  706. EXPECT_EQ("", file.filename);
  707. EXPECT_EQ("application/octet-stream", file.content_type);
  708. EXPECT_EQ(0u, file.content.size());
  709. }
  710. })
  711. .Post("/empty",
  712. [&](const Request &req, Response &res) {
  713. EXPECT_EQ(req.body, "");
  714. res.set_content("empty", "text/plain");
  715. })
  716. .Put("/put",
  717. [&](const Request &req, Response &res) {
  718. EXPECT_EQ(req.body, "PUT");
  719. res.set_content(req.body, "text/plain");
  720. })
  721. .Put("/put-large",
  722. [&](const Request &req, Response &res) {
  723. EXPECT_EQ(req.body, LARGE_DATA);
  724. res.set_content(req.body, "text/plain");
  725. })
  726. .Patch("/patch",
  727. [&](const Request &req, Response &res) {
  728. EXPECT_EQ(req.body, "PATCH");
  729. res.set_content(req.body, "text/plain");
  730. })
  731. .Delete("/delete",
  732. [&](const Request & /*req*/, Response &res) {
  733. res.set_content("DELETE", "text/plain");
  734. })
  735. .Options(R"(\*)",
  736. [&](const Request & /*req*/, Response &res) {
  737. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  738. })
  739. .Get("/request-target",
  740. [&](const Request &req, Response & /*res*/) {
  741. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  742. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  743. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  744. })
  745. .Get("/long-query-value",
  746. [&](const Request &req, Response & /*res*/) {
  747. EXPECT_EQ(LONG_QUERY_URL, req.target);
  748. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  749. })
  750. .Get("/array-param",
  751. [&](const Request &req, Response & /*res*/) {
  752. EXPECT_EQ(3u, req.get_param_value_count("array"));
  753. EXPECT_EQ("value1", req.get_param_value("array", 0));
  754. EXPECT_EQ("value2", req.get_param_value("array", 1));
  755. EXPECT_EQ("value3", req.get_param_value("array", 2));
  756. })
  757. .Post("/validate-no-multiple-headers",
  758. [&](const Request &req, Response & /*res*/) {
  759. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  760. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  761. })
  762. .Post("/content_receiver",
  763. [&](const Request &req, Response &res,
  764. const ContentReader &content_reader) {
  765. if (req.is_multipart_form_data()) {
  766. MultipartFormDataItems files;
  767. content_reader(
  768. [&](const MultipartFormData &file) {
  769. files.push_back(file);
  770. return true;
  771. },
  772. [&](const char *data, size_t data_length) {
  773. files.back().content.append(data, data_length);
  774. return true;
  775. });
  776. EXPECT_EQ(5u, files.size());
  777. {
  778. const auto &file = get_file_value(files, "text1");
  779. EXPECT_EQ("", file.filename);
  780. EXPECT_EQ("text default", file.content);
  781. }
  782. {
  783. const auto &file = get_file_value(files, "text2");
  784. EXPECT_EQ("", file.filename);
  785. EXPECT_EQ("aωb", file.content);
  786. }
  787. {
  788. const auto &file = get_file_value(files, "file1");
  789. EXPECT_EQ("hello.txt", file.filename);
  790. EXPECT_EQ("text/plain", file.content_type);
  791. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  792. }
  793. {
  794. const auto &file = get_file_value(files, "file3");
  795. EXPECT_EQ("", file.filename);
  796. EXPECT_EQ("application/octet-stream", file.content_type);
  797. EXPECT_EQ(0u, file.content.size());
  798. }
  799. } else {
  800. std::string body;
  801. content_reader([&](const char *data, size_t data_length) {
  802. EXPECT_EQ(data_length, 7);
  803. body.append(data, data_length);
  804. return true;
  805. });
  806. EXPECT_EQ(body, "content");
  807. res.set_content(body, "text/plain");
  808. }
  809. })
  810. .Put("/content_receiver",
  811. [&](const Request & /*req*/, Response &res,
  812. const ContentReader &content_reader) {
  813. std::string body;
  814. content_reader([&](const char *data, size_t data_length) {
  815. body.append(data, data_length);
  816. return true;
  817. });
  818. EXPECT_EQ(body, "content");
  819. res.set_content(body, "text/plain");
  820. })
  821. .Patch("/content_receiver",
  822. [&](const Request & /*req*/, Response &res,
  823. const ContentReader &content_reader) {
  824. std::string body;
  825. content_reader([&](const char *data, size_t data_length) {
  826. body.append(data, data_length);
  827. return true;
  828. });
  829. EXPECT_EQ(body, "content");
  830. res.set_content(body, "text/plain");
  831. })
  832. .Post("/query-string-and-body",
  833. [&](const Request &req, Response & /*res*/) {
  834. ASSERT_TRUE(req.has_param("key"));
  835. EXPECT_EQ(req.get_param_value("key"), "value");
  836. EXPECT_EQ(req.body, "content");
  837. })
  838. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  839. .Get("/gzip",
  840. [&](const Request & /*req*/, Response &res) {
  841. res.set_content(
  842. "12345678901234567890123456789012345678901234567890123456789"
  843. "01234567890123456789012345678901234567890",
  844. "text/plain");
  845. })
  846. .Get("/nogzip",
  847. [&](const Request & /*req*/, Response &res) {
  848. res.set_content(
  849. "12345678901234567890123456789012345678901234567890123456789"
  850. "01234567890123456789012345678901234567890",
  851. "application/octet-stream");
  852. })
  853. .Post("/gzipmultipart",
  854. [&](const Request &req, Response & /*res*/) {
  855. EXPECT_EQ(2u, req.files.size());
  856. ASSERT_TRUE(!req.has_file("???"));
  857. {
  858. const auto &file = req.get_file_value("key1");
  859. EXPECT_EQ("", file.filename);
  860. EXPECT_EQ("test", file.content);
  861. }
  862. {
  863. const auto &file = req.get_file_value("key2");
  864. EXPECT_EQ("", file.filename);
  865. EXPECT_EQ("--abcdefg123", file.content);
  866. }
  867. })
  868. #endif
  869. ;
  870. persons_["john"] = "programmer";
  871. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  872. while (!svr_.is_running()) {
  873. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  874. }
  875. }
  876. virtual void TearDown() {
  877. svr_.stop();
  878. for (auto &t : request_threads_) {
  879. t.join();
  880. }
  881. t_.join();
  882. }
  883. map<string, string> persons_;
  884. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  885. SSLClient cli_;
  886. SSLServer svr_;
  887. #else
  888. Client cli_;
  889. Server svr_;
  890. #endif
  891. thread t_;
  892. std::vector<thread> request_threads_;
  893. };
  894. TEST_F(ServerTest, GetMethod200) {
  895. auto res = cli_.Get("/hi");
  896. ASSERT_TRUE(res != nullptr);
  897. EXPECT_EQ("HTTP/1.1", res->version);
  898. EXPECT_EQ(200, res->status);
  899. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  900. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  901. EXPECT_EQ("Hello World!", res->body);
  902. }
  903. TEST_F(ServerTest, GetMethod302) {
  904. auto res = cli_.Get("/");
  905. ASSERT_TRUE(res != nullptr);
  906. EXPECT_EQ(302, res->status);
  907. EXPECT_EQ("/hi", res->get_header_value("Location"));
  908. }
  909. TEST_F(ServerTest, GetMethod404) {
  910. auto res = cli_.Get("/invalid");
  911. ASSERT_TRUE(res != nullptr);
  912. EXPECT_EQ(404, res->status);
  913. }
  914. TEST_F(ServerTest, HeadMethod200) {
  915. auto res = cli_.Head("/hi");
  916. ASSERT_TRUE(res != nullptr);
  917. EXPECT_EQ(200, res->status);
  918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  919. EXPECT_EQ("", res->body);
  920. }
  921. TEST_F(ServerTest, HeadMethod200Static) {
  922. auto res = cli_.Head("/mount/dir/index.html");
  923. ASSERT_TRUE(res != nullptr);
  924. EXPECT_EQ(200, res->status);
  925. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  926. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  927. EXPECT_EQ("", res->body);
  928. }
  929. TEST_F(ServerTest, HeadMethod404) {
  930. auto res = cli_.Head("/invalid");
  931. ASSERT_TRUE(res != nullptr);
  932. EXPECT_EQ(404, res->status);
  933. EXPECT_EQ("", res->body);
  934. }
  935. TEST_F(ServerTest, GetMethodPersonJohn) {
  936. auto res = cli_.Get("/person/john");
  937. ASSERT_TRUE(res != nullptr);
  938. EXPECT_EQ(200, res->status);
  939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  940. EXPECT_EQ("programmer", res->body);
  941. }
  942. TEST_F(ServerTest, PostMethod1) {
  943. auto res = cli_.Get("/person/john1");
  944. ASSERT_TRUE(res != nullptr);
  945. ASSERT_EQ(404, res->status);
  946. res = cli_.Post("/person", "name=john1&note=coder",
  947. "application/x-www-form-urlencoded");
  948. ASSERT_TRUE(res != nullptr);
  949. ASSERT_EQ(200, res->status);
  950. res = cli_.Get("/person/john1");
  951. ASSERT_TRUE(res != nullptr);
  952. ASSERT_EQ(200, res->status);
  953. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  954. ASSERT_EQ("coder", res->body);
  955. }
  956. TEST_F(ServerTest, PostMethod2) {
  957. auto res = cli_.Get("/person/john2");
  958. ASSERT_TRUE(res != nullptr);
  959. ASSERT_EQ(404, res->status);
  960. Params params;
  961. params.emplace("name", "john2");
  962. params.emplace("note", "coder");
  963. res = cli_.Post("/person", params);
  964. ASSERT_TRUE(res != nullptr);
  965. ASSERT_EQ(200, res->status);
  966. res = cli_.Get("/person/john2");
  967. ASSERT_TRUE(res != nullptr);
  968. ASSERT_EQ(200, res->status);
  969. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  970. ASSERT_EQ("coder", res->body);
  971. }
  972. TEST_F(ServerTest, PutMethod3) {
  973. auto res = cli_.Get("/person/john3");
  974. ASSERT_TRUE(res != nullptr);
  975. ASSERT_EQ(404, res->status);
  976. Params params;
  977. params.emplace("name", "john3");
  978. params.emplace("note", "coder");
  979. res = cli_.Put("/person", params);
  980. ASSERT_TRUE(res != nullptr);
  981. ASSERT_EQ(200, res->status);
  982. res = cli_.Get("/person/john3");
  983. ASSERT_TRUE(res != nullptr);
  984. ASSERT_EQ(200, res->status);
  985. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  986. ASSERT_EQ("coder", res->body);
  987. }
  988. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  989. Params params;
  990. params.emplace("json", JSON_DATA);
  991. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  992. ASSERT_TRUE(res != nullptr);
  993. ASSERT_EQ(200, res->status);
  994. ASSERT_EQ(JSON_DATA, res->body);
  995. }
  996. TEST_F(ServerTest, PostEmptyContent) {
  997. auto res = cli_.Post("/empty", "", "text/plain");
  998. ASSERT_TRUE(res != nullptr);
  999. ASSERT_EQ(200, res->status);
  1000. ASSERT_EQ("empty", res->body);
  1001. }
  1002. TEST_F(ServerTest, GetMethodDir) {
  1003. auto res = cli_.Get("/dir/");
  1004. ASSERT_TRUE(res != nullptr);
  1005. EXPECT_EQ(200, res->status);
  1006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1007. auto body = R"(<html>
  1008. <head>
  1009. </head>
  1010. <body>
  1011. <a href="/dir/test.html">Test</a>
  1012. <a href="/hi">hi</a>
  1013. </body>
  1014. </html>
  1015. )";
  1016. EXPECT_EQ(body, res->body);
  1017. }
  1018. TEST_F(ServerTest, GetMethodDirTest) {
  1019. auto res = cli_.Get("/dir/test.html");
  1020. ASSERT_TRUE(res != nullptr);
  1021. EXPECT_EQ(200, res->status);
  1022. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1023. EXPECT_EQ("test.html", res->body);
  1024. }
  1025. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1026. auto res = cli_.Get("/dir/../dir/test.html");
  1027. ASSERT_TRUE(res != nullptr);
  1028. EXPECT_EQ(200, res->status);
  1029. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1030. EXPECT_EQ("test.html", res->body);
  1031. }
  1032. TEST_F(ServerTest, GetMethodInvalidPath) {
  1033. auto res = cli_.Get("/dir/../test.html");
  1034. ASSERT_TRUE(res != nullptr);
  1035. EXPECT_EQ(404, res->status);
  1036. }
  1037. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1038. auto res = cli_.Get("/../www/dir/test.html");
  1039. ASSERT_TRUE(res != nullptr);
  1040. EXPECT_EQ(404, res->status);
  1041. }
  1042. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1043. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1044. ASSERT_TRUE(res != nullptr);
  1045. EXPECT_EQ(404, res->status);
  1046. }
  1047. TEST_F(ServerTest, GetMethodDirMountTest) {
  1048. auto res = cli_.Get("/mount/dir/test.html");
  1049. ASSERT_TRUE(res != nullptr);
  1050. EXPECT_EQ(200, res->status);
  1051. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1052. EXPECT_EQ("test.html", res->body);
  1053. }
  1054. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1055. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1056. ASSERT_TRUE(res != nullptr);
  1057. EXPECT_EQ(200, res->status);
  1058. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1059. EXPECT_EQ("test.html", res->body);
  1060. }
  1061. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1062. auto res = cli_.Get("/mount/dir/../test.html");
  1063. ASSERT_TRUE(res != nullptr);
  1064. EXPECT_EQ(404, res->status);
  1065. }
  1066. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1067. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1068. ASSERT_TRUE(res != nullptr);
  1069. EXPECT_EQ(404, res->status);
  1070. }
  1071. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1072. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1073. ASSERT_TRUE(res != nullptr);
  1074. EXPECT_EQ(404, res->status);
  1075. }
  1076. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1077. auto res = cli_.Get("/dir/test.abcde");
  1078. ASSERT_TRUE(res != nullptr);
  1079. EXPECT_EQ(200, res->status);
  1080. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1081. EXPECT_EQ("abcde", res->body);
  1082. }
  1083. TEST_F(ServerTest, InvalidBaseDirMount) {
  1084. EXPECT_EQ(false, svr_.set_mount_point("./www3", "invalid_mount_point"));
  1085. }
  1086. TEST_F(ServerTest, EmptyRequest) {
  1087. auto res = cli_.Get("");
  1088. ASSERT_TRUE(res == nullptr);
  1089. }
  1090. TEST_F(ServerTest, LongRequest) {
  1091. std::string request;
  1092. for (size_t i = 0; i < 545; i++) {
  1093. request += "/TooLongRequest";
  1094. }
  1095. request += "OK";
  1096. auto res = cli_.Get(request.c_str());
  1097. ASSERT_TRUE(res != nullptr);
  1098. EXPECT_EQ(404, res->status);
  1099. }
  1100. TEST_F(ServerTest, TooLongRequest) {
  1101. std::string request;
  1102. for (size_t i = 0; i < 545; i++) {
  1103. request += "/TooLongRequest";
  1104. }
  1105. request += "_NG";
  1106. auto res = cli_.Get(request.c_str());
  1107. ASSERT_TRUE(res != nullptr);
  1108. EXPECT_EQ(414, res->status);
  1109. }
  1110. TEST_F(ServerTest, LongHeader) {
  1111. Request req;
  1112. req.method = "GET";
  1113. req.path = "/hi";
  1114. std::string host_and_port;
  1115. host_and_port += HOST;
  1116. host_and_port += ":";
  1117. host_and_port += std::to_string(PORT);
  1118. req.headers.emplace("Host", host_and_port.c_str());
  1119. req.headers.emplace("Accept", "*/*");
  1120. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1121. req.headers.emplace(
  1122. "Header-Name",
  1123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1151. "@@@@@@@@@@@@@@@@");
  1152. auto res = std::make_shared<Response>();
  1153. auto ret = cli_.send(req, *res);
  1154. ASSERT_TRUE(ret);
  1155. EXPECT_EQ(200, res->status);
  1156. }
  1157. TEST_F(ServerTest, LongQueryValue) {
  1158. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1159. ASSERT_TRUE(res != nullptr);
  1160. EXPECT_EQ(414, res->status);
  1161. }
  1162. TEST_F(ServerTest, TooLongHeader) {
  1163. Request req;
  1164. req.method = "GET";
  1165. req.path = "/hi";
  1166. std::string host_and_port;
  1167. host_and_port += HOST;
  1168. host_and_port += ":";
  1169. host_and_port += std::to_string(PORT);
  1170. req.headers.emplace("Host", host_and_port.c_str());
  1171. req.headers.emplace("Accept", "*/*");
  1172. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1173. req.headers.emplace(
  1174. "Header-Name",
  1175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1203. "@@@@@@@@@@@@@@@@@");
  1204. auto res = std::make_shared<Response>();
  1205. auto ret = cli_.send(req, *res);
  1206. ASSERT_TRUE(ret);
  1207. EXPECT_EQ(200, res->status);
  1208. }
  1209. TEST_F(ServerTest, PercentEncoding) {
  1210. auto res = cli_.Get("/e%6edwith%");
  1211. ASSERT_TRUE(res != nullptr);
  1212. EXPECT_EQ(200, res->status);
  1213. }
  1214. TEST_F(ServerTest, PercentEncodingUnicode) {
  1215. auto res = cli_.Get("/e%u006edwith%");
  1216. ASSERT_TRUE(res != nullptr);
  1217. EXPECT_EQ(200, res->status);
  1218. }
  1219. TEST_F(ServerTest, InvalidPercentEncoding) {
  1220. auto res = cli_.Get("/%endwith%");
  1221. ASSERT_TRUE(res != nullptr);
  1222. EXPECT_EQ(404, res->status);
  1223. }
  1224. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1225. auto res = cli_.Get("/%uendwith%");
  1226. ASSERT_TRUE(res != nullptr);
  1227. EXPECT_EQ(404, res->status);
  1228. }
  1229. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1230. auto res = cli_.Get("/hello?aaa=bbb%");
  1231. ASSERT_TRUE(res != nullptr);
  1232. EXPECT_EQ(404, res->status);
  1233. }
  1234. TEST_F(ServerTest, MultipartFormData) {
  1235. MultipartFormDataItems items = {
  1236. {"text1", "text default", "", ""},
  1237. {"text2", "aωb", "", ""},
  1238. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1239. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1240. {"file3", "", "", "application/octet-stream"},
  1241. };
  1242. auto res = cli_.Post("/multipart", items);
  1243. ASSERT_TRUE(res != nullptr);
  1244. EXPECT_EQ(200, res->status);
  1245. }
  1246. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1247. auto res = cli_.Get("/hi");
  1248. ASSERT_TRUE(res != nullptr);
  1249. EXPECT_EQ(200, res->status);
  1250. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1251. EXPECT_EQ("Hello World!", res->body);
  1252. }
  1253. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1254. Request req;
  1255. req.method = "POST";
  1256. req.path = "/chunked";
  1257. std::string host_and_port;
  1258. host_and_port += HOST;
  1259. host_and_port += ":";
  1260. host_and_port += std::to_string(PORT);
  1261. req.headers.emplace("Host", host_and_port.c_str());
  1262. req.headers.emplace("Accept", "*/*");
  1263. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1264. req.headers.emplace("Content-Type", "text/plain");
  1265. req.headers.emplace("Content-Length", "0");
  1266. req.headers.emplace(
  1267. "Transfer-Encoding",
  1268. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1269. // Client does not chunk, so make a chunked body manually.
  1270. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1271. auto res = std::make_shared<Response>();
  1272. auto ret = cli_.send(req, *res);
  1273. ASSERT_TRUE(ret);
  1274. EXPECT_EQ(200, res->status);
  1275. }
  1276. TEST_F(ServerTest, GetStreamed2) {
  1277. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1278. ASSERT_TRUE(res != nullptr);
  1279. EXPECT_EQ(206, res->status);
  1280. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1281. EXPECT_EQ(std::string("ab"), res->body);
  1282. }
  1283. TEST_F(ServerTest, GetStreamed) {
  1284. auto res = cli_.Get("/streamed");
  1285. ASSERT_TRUE(res != nullptr);
  1286. EXPECT_EQ(200, res->status);
  1287. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1288. EXPECT_EQ(std::string("aaabbb"), res->body);
  1289. }
  1290. TEST_F(ServerTest, GetStreamedWithRange1) {
  1291. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1292. ASSERT_TRUE(res != nullptr);
  1293. EXPECT_EQ(206, res->status);
  1294. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1295. EXPECT_EQ(true, res->has_header("Content-Range"));
  1296. EXPECT_EQ(std::string("def"), res->body);
  1297. }
  1298. TEST_F(ServerTest, GetStreamedWithRange2) {
  1299. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1300. ASSERT_TRUE(res != nullptr);
  1301. EXPECT_EQ(206, res->status);
  1302. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1303. EXPECT_EQ(true, res->has_header("Content-Range"));
  1304. EXPECT_EQ(std::string("bcdefg"), res->body);
  1305. }
  1306. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1307. auto res =
  1308. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1309. ASSERT_TRUE(res != nullptr);
  1310. EXPECT_EQ(206, res->status);
  1311. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1312. EXPECT_EQ(false, res->has_header("Content-Range"));
  1313. EXPECT_EQ(269, res->body.size());
  1314. }
  1315. TEST_F(ServerTest, GetStreamedEndless) {
  1316. uint64_t offset = 0;
  1317. auto res = cli_.Get("/streamed-cancel",
  1318. [&](const char * /*data*/, uint64_t data_length) {
  1319. if (offset < 100) {
  1320. offset += data_length;
  1321. return true;
  1322. }
  1323. return false;
  1324. });
  1325. ASSERT_TRUE(res == nullptr);
  1326. }
  1327. TEST_F(ServerTest, GetWithRange1) {
  1328. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1329. ASSERT_TRUE(res != nullptr);
  1330. EXPECT_EQ(206, res->status);
  1331. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1332. EXPECT_EQ(true, res->has_header("Content-Range"));
  1333. EXPECT_EQ(std::string("def"), res->body);
  1334. }
  1335. TEST_F(ServerTest, GetWithRange2) {
  1336. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1337. ASSERT_TRUE(res != nullptr);
  1338. EXPECT_EQ(206, res->status);
  1339. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1340. EXPECT_EQ(true, res->has_header("Content-Range"));
  1341. EXPECT_EQ(std::string("bcdefg"), res->body);
  1342. }
  1343. TEST_F(ServerTest, GetWithRange3) {
  1344. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1345. ASSERT_TRUE(res != nullptr);
  1346. EXPECT_EQ(206, res->status);
  1347. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1348. EXPECT_EQ(true, res->has_header("Content-Range"));
  1349. EXPECT_EQ(std::string("a"), res->body);
  1350. }
  1351. TEST_F(ServerTest, GetWithRange4) {
  1352. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1353. ASSERT_TRUE(res != nullptr);
  1354. EXPECT_EQ(206, res->status);
  1355. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1356. EXPECT_EQ(true, res->has_header("Content-Range"));
  1357. EXPECT_EQ(std::string("fg"), res->body);
  1358. }
  1359. TEST_F(ServerTest, GetWithRangeMultipart) {
  1360. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1361. ASSERT_TRUE(res != nullptr);
  1362. EXPECT_EQ(206, res->status);
  1363. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1364. EXPECT_EQ(false, res->has_header("Content-Range"));
  1365. EXPECT_EQ(269, res->body.size());
  1366. }
  1367. TEST_F(ServerTest, GetStreamedChunked) {
  1368. auto res = cli_.Get("/streamed-chunked");
  1369. ASSERT_TRUE(res != nullptr);
  1370. EXPECT_EQ(200, res->status);
  1371. EXPECT_EQ(std::string("123456789"), res->body);
  1372. }
  1373. TEST_F(ServerTest, GetStreamedChunked2) {
  1374. auto res = cli_.Get("/streamed-chunked2");
  1375. ASSERT_TRUE(res != nullptr);
  1376. EXPECT_EQ(200, res->status);
  1377. EXPECT_EQ(std::string("123456789"), res->body);
  1378. }
  1379. TEST_F(ServerTest, LargeChunkedPost) {
  1380. Request req;
  1381. req.method = "POST";
  1382. req.path = "/large-chunked";
  1383. std::string host_and_port;
  1384. host_and_port += HOST;
  1385. host_and_port += ":";
  1386. host_and_port += std::to_string(PORT);
  1387. req.headers.emplace("Host", host_and_port.c_str());
  1388. req.headers.emplace("Accept", "*/*");
  1389. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1390. req.headers.emplace("Content-Type", "text/plain");
  1391. req.headers.emplace("Content-Length", "0");
  1392. req.headers.emplace("Transfer-Encoding", "chunked");
  1393. std::string long_string(30 * 1024u, 'a');
  1394. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1395. // Attempt to make a large enough post to exceed OS buffers, to test that
  1396. // the server handles short reads if the full chunk data isn't available.
  1397. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1398. auto res = std::make_shared<Response>();
  1399. auto ret = cli_.send(req, *res);
  1400. ASSERT_TRUE(ret);
  1401. EXPECT_EQ(200, res->status);
  1402. }
  1403. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1404. auto res = cli_.Get("/remote_addr");
  1405. ASSERT_TRUE(res != nullptr);
  1406. EXPECT_EQ(200, res->status);
  1407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1408. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1409. }
  1410. TEST_F(ServerTest, SlowRequest) {
  1411. request_threads_.push_back(
  1412. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1413. request_threads_.push_back(
  1414. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1415. request_threads_.push_back(
  1416. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1417. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1418. }
  1419. TEST_F(ServerTest, Put) {
  1420. auto res = cli_.Put("/put", "PUT", "text/plain");
  1421. ASSERT_TRUE(res != nullptr);
  1422. EXPECT_EQ(200, res->status);
  1423. EXPECT_EQ("PUT", res->body);
  1424. }
  1425. TEST_F(ServerTest, PutWithContentProvider) {
  1426. auto res = cli_.Put(
  1427. "/put", 3,
  1428. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1429. ASSERT_TRUE(sink.is_writable());
  1430. sink.write("PUT", 3);
  1431. },
  1432. "text/plain");
  1433. ASSERT_TRUE(res != nullptr);
  1434. EXPECT_EQ(200, res->status);
  1435. EXPECT_EQ("PUT", res->body);
  1436. }
  1437. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1438. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1439. cli_.set_compress(true);
  1440. auto res = cli_.Put(
  1441. "/put", 3,
  1442. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1443. ASSERT_TRUE(sink.is_writable());
  1444. sink.write("PUT", 3);
  1445. },
  1446. "text/plain");
  1447. ASSERT_TRUE(res != nullptr);
  1448. EXPECT_EQ(200, res->status);
  1449. EXPECT_EQ("PUT", res->body);
  1450. }
  1451. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1452. cli_.set_compress(true);
  1453. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  1454. ASSERT_TRUE(res != nullptr);
  1455. EXPECT_EQ(200, res->status);
  1456. EXPECT_EQ(LARGE_DATA, res->body);
  1457. }
  1458. #endif
  1459. TEST_F(ServerTest, Patch) {
  1460. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1461. ASSERT_TRUE(res != nullptr);
  1462. EXPECT_EQ(200, res->status);
  1463. EXPECT_EQ("PATCH", res->body);
  1464. }
  1465. TEST_F(ServerTest, Delete) {
  1466. auto res = cli_.Delete("/delete");
  1467. ASSERT_TRUE(res != nullptr);
  1468. EXPECT_EQ(200, res->status);
  1469. EXPECT_EQ("DELETE", res->body);
  1470. }
  1471. TEST_F(ServerTest, Options) {
  1472. auto res = cli_.Options("*");
  1473. ASSERT_TRUE(res != nullptr);
  1474. EXPECT_EQ(200, res->status);
  1475. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1476. EXPECT_TRUE(res->body.empty());
  1477. }
  1478. TEST_F(ServerTest, URL) {
  1479. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1480. ASSERT_TRUE(res != nullptr);
  1481. EXPECT_EQ(200, res->status);
  1482. }
  1483. TEST_F(ServerTest, ArrayParam) {
  1484. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  1485. ASSERT_TRUE(res != nullptr);
  1486. EXPECT_EQ(200, res->status);
  1487. }
  1488. TEST_F(ServerTest, NoMultipleHeaders) {
  1489. Headers headers = {{"Content-Length", "5"}};
  1490. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  1491. "text/plain");
  1492. ASSERT_TRUE(res != nullptr);
  1493. EXPECT_EQ(200, res->status);
  1494. }
  1495. TEST_F(ServerTest, PostContentReceiver) {
  1496. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1497. ASSERT_TRUE(res != nullptr);
  1498. ASSERT_EQ(200, res->status);
  1499. ASSERT_EQ("content", res->body);
  1500. }
  1501. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  1502. MultipartFormDataItems items = {
  1503. {"text1", "text default", "", ""},
  1504. {"text2", "aωb", "", ""},
  1505. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1506. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1507. {"file3", "", "", "application/octet-stream"},
  1508. };
  1509. auto res = cli_.Post("/content_receiver", items);
  1510. ASSERT_TRUE(res != nullptr);
  1511. EXPECT_EQ(200, res->status);
  1512. }
  1513. TEST_F(ServerTest, PostContentReceiverGzip) {
  1514. cli_.set_compress(true);
  1515. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1516. ASSERT_TRUE(res != nullptr);
  1517. ASSERT_EQ(200, res->status);
  1518. ASSERT_EQ("content", res->body);
  1519. }
  1520. TEST_F(ServerTest, PutContentReceiver) {
  1521. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  1522. ASSERT_TRUE(res != nullptr);
  1523. ASSERT_EQ(200, res->status);
  1524. ASSERT_EQ("content", res->body);
  1525. }
  1526. TEST_F(ServerTest, PatchContentReceiver) {
  1527. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  1528. ASSERT_TRUE(res != nullptr);
  1529. ASSERT_EQ(200, res->status);
  1530. ASSERT_EQ("content", res->body);
  1531. }
  1532. TEST_F(ServerTest, PostQueryStringAndBody) {
  1533. auto res =
  1534. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  1535. ASSERT_TRUE(res != nullptr);
  1536. ASSERT_EQ(200, res->status);
  1537. }
  1538. TEST_F(ServerTest, HTTP2Magic) {
  1539. Request req;
  1540. req.method = "PRI";
  1541. req.path = "*";
  1542. req.body = "SM";
  1543. auto res = std::make_shared<Response>();
  1544. auto ret = cli_.send(req, *res);
  1545. ASSERT_TRUE(ret);
  1546. EXPECT_EQ(400, res->status);
  1547. }
  1548. TEST_F(ServerTest, KeepAlive) {
  1549. cli_.set_keep_alive_max_count(4);
  1550. std::vector<Request> requests;
  1551. Get(requests, "/hi");
  1552. Get(requests, "/hi");
  1553. Get(requests, "/hi");
  1554. Get(requests, "/not-exist");
  1555. Post(requests, "/empty", "", "text/plain");
  1556. std::vector<Response> responses;
  1557. auto ret = cli_.send(requests, responses);
  1558. ASSERT_TRUE(ret == true);
  1559. ASSERT_TRUE(requests.size() == responses.size());
  1560. for (int i = 0; i < 3; i++) {
  1561. auto &res = responses[i];
  1562. EXPECT_EQ(200, res.status);
  1563. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1564. EXPECT_EQ("Hello World!", res.body);
  1565. }
  1566. {
  1567. auto &res = responses[3];
  1568. EXPECT_EQ(404, res.status);
  1569. }
  1570. {
  1571. auto &res = responses[4];
  1572. EXPECT_EQ(200, res.status);
  1573. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1574. EXPECT_EQ("empty", res.body);
  1575. }
  1576. }
  1577. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1578. TEST_F(ServerTest, Gzip) {
  1579. Headers headers;
  1580. headers.emplace("Accept-Encoding", "gzip, deflate");
  1581. auto res = cli_.Get("/gzip", headers);
  1582. ASSERT_TRUE(res != nullptr);
  1583. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1584. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1585. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1586. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1587. "7890123456789012345678901234567890",
  1588. res->body);
  1589. EXPECT_EQ(200, res->status);
  1590. }
  1591. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  1592. Headers headers;
  1593. auto res = cli_.Get("/gzip", headers);
  1594. ASSERT_TRUE(res != nullptr);
  1595. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1597. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1599. "7890123456789012345678901234567890",
  1600. res->body);
  1601. EXPECT_EQ(200, res->status);
  1602. }
  1603. TEST_F(ServerTest, GzipWithContentReceiver) {
  1604. Headers headers;
  1605. headers.emplace("Accept-Encoding", "gzip, deflate");
  1606. std::string body;
  1607. auto res =
  1608. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1609. EXPECT_EQ(data_length, 100);
  1610. body.append(data, data_length);
  1611. return true;
  1612. });
  1613. ASSERT_TRUE(res != nullptr);
  1614. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1615. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1616. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1617. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1618. "7890123456789012345678901234567890",
  1619. body);
  1620. EXPECT_EQ(200, res->status);
  1621. }
  1622. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  1623. Headers headers;
  1624. std::string body;
  1625. auto res =
  1626. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1627. EXPECT_EQ(data_length, 100);
  1628. body.append(data, data_length);
  1629. return true;
  1630. });
  1631. ASSERT_TRUE(res != nullptr);
  1632. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1634. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1635. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1636. "7890123456789012345678901234567890",
  1637. body);
  1638. EXPECT_EQ(200, res->status);
  1639. }
  1640. TEST_F(ServerTest, NoGzip) {
  1641. Headers headers;
  1642. headers.emplace("Accept-Encoding", "gzip, deflate");
  1643. auto res = cli_.Get("/nogzip", headers);
  1644. ASSERT_TRUE(res != nullptr);
  1645. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1646. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1647. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1648. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1649. "7890123456789012345678901234567890",
  1650. res->body);
  1651. EXPECT_EQ(200, res->status);
  1652. }
  1653. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  1654. Headers headers;
  1655. headers.emplace("Accept-Encoding", "gzip, deflate");
  1656. std::string body;
  1657. auto res =
  1658. cli_.Get("/nogzip", headers, [&](const char *data, uint64_t data_length) {
  1659. EXPECT_EQ(data_length, 100);
  1660. body.append(data, data_length);
  1661. return true;
  1662. });
  1663. ASSERT_TRUE(res != nullptr);
  1664. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1665. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1666. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1667. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1668. "7890123456789012345678901234567890",
  1669. body);
  1670. EXPECT_EQ(200, res->status);
  1671. }
  1672. TEST_F(ServerTest, MultipartFormDataGzip) {
  1673. MultipartFormDataItems items = {
  1674. {"key1", "test", "", ""},
  1675. {"key2", "--abcdefg123", "", ""},
  1676. };
  1677. cli_.set_compress(true);
  1678. auto res = cli_.Post("/gzipmultipart", items);
  1679. ASSERT_TRUE(res != nullptr);
  1680. EXPECT_EQ(200, res->status);
  1681. }
  1682. #endif
  1683. // Sends a raw request to a server listening at HOST:PORT.
  1684. static bool send_request(time_t read_timeout_sec, const std::string &req) {
  1685. auto client_sock = detail::create_client_socket(HOST, PORT, /*timeout_sec=*/5,
  1686. std::string());
  1687. if (client_sock == INVALID_SOCKET) { return false; }
  1688. return detail::process_and_close_socket(
  1689. true, client_sock, 1, read_timeout_sec, 0,
  1690. [&](Stream &strm, bool /*last_connection*/, bool &
  1691. /*connection_close*/) -> bool {
  1692. if (req.size() !=
  1693. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  1694. return false;
  1695. }
  1696. char buf[512];
  1697. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  1698. while (line_reader.getline()) {}
  1699. return true;
  1700. });
  1701. }
  1702. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  1703. Server svr;
  1704. std::string header_value;
  1705. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  1706. header_value = req.get_header_value("foo");
  1707. res.set_content("ok", "text/plain");
  1708. });
  1709. thread t = thread([&] { svr.listen(HOST, PORT); });
  1710. while (!svr.is_running()) {
  1711. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1712. }
  1713. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  1714. // like characters are not treated the same - use vertical tab and escape.
  1715. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  1716. "foo: \t \v bar \e\t \r\n"
  1717. "Connection: close\r\n"
  1718. "\r\n";
  1719. ASSERT_TRUE(send_request(5, req));
  1720. svr.stop();
  1721. t.join();
  1722. EXPECT_EQ(header_value, "\v bar \e");
  1723. }
  1724. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  1725. Server svr;
  1726. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1727. res.set_content("ok", "text/plain");
  1728. });
  1729. // Server read timeout must be longer than the client read timeout for the
  1730. // bug to reproduce, probably to force the server to process a request
  1731. // without a trailing blank line.
  1732. const time_t client_read_timeout_sec = 1;
  1733. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  1734. bool listen_thread_ok = false;
  1735. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  1736. while (!svr.is_running()) {
  1737. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1738. }
  1739. // A certain header line causes an exception if the header property is parsed
  1740. // naively with a single regex. This occurs with libc++ but not libstdc++.
  1741. const std::string req =
  1742. "GET /hi HTTP/1.1\r\n"
  1743. " : "
  1744. " ";
  1745. ASSERT_TRUE(send_request(client_read_timeout_sec, req));
  1746. svr.stop();
  1747. t.join();
  1748. EXPECT_TRUE(listen_thread_ok);
  1749. }
  1750. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  1751. Server svr;
  1752. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  1753. res.set_header("Content-Type", "text/event-stream");
  1754. res.set_header("Cache-Control", "no-cache");
  1755. res.set_chunked_content_provider([](size_t offset, const DataSink &sink) {
  1756. char buffer[27];
  1757. int size = sprintf(buffer, "data:%ld\n\n", offset);
  1758. sink.write(buffer, size);
  1759. std::this_thread::sleep_for(std::chrono::seconds(1));
  1760. });
  1761. });
  1762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1763. while (!svr.is_running()) {
  1764. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1765. }
  1766. Client client(HOST, PORT);
  1767. const Headers headers = {{"Accept", "text/event-stream"},
  1768. {"Connection", "Keep-Alive"}};
  1769. auto get_thread = std::thread([&client, &headers]() {
  1770. std::shared_ptr<Response> res = client.Get(
  1771. "/events", headers,
  1772. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  1773. });
  1774. // Give GET time to get a few messages.
  1775. std::this_thread::sleep_for(std::chrono::seconds(2));
  1776. svr.stop();
  1777. listen_thread.join();
  1778. get_thread.join();
  1779. ASSERT_FALSE(svr.is_running());
  1780. }
  1781. TEST(MountTest, Unmount) {
  1782. Server svr;
  1783. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1784. while (!svr.is_running()) {
  1785. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1786. }
  1787. // Give GET time to get a few messages.
  1788. std::this_thread::sleep_for(std::chrono::seconds(1));
  1789. Client cli("localhost", PORT);
  1790. svr.set_mount_point("./www2", "/mount2");
  1791. auto res = cli.Get("/");
  1792. ASSERT_TRUE(res != nullptr);
  1793. EXPECT_EQ(404, res->status);
  1794. res = cli.Get("/mount2/dir/test.html");
  1795. ASSERT_TRUE(res != nullptr);
  1796. EXPECT_EQ(200, res->status);
  1797. svr.set_mount_point("./www", "/");
  1798. res = cli.Get("/dir/");
  1799. ASSERT_TRUE(res != nullptr);
  1800. EXPECT_EQ(200, res->status);
  1801. svr.remove_mount_point("/");
  1802. res = cli.Get("/dir/");
  1803. ASSERT_TRUE(res != nullptr);
  1804. EXPECT_EQ(404, res->status);
  1805. svr.remove_mount_point("/mount2");
  1806. res = cli.Get("/mount2/dir/test.html");
  1807. ASSERT_TRUE(res != nullptr);
  1808. EXPECT_EQ(404, res->status);
  1809. svr.stop();
  1810. listen_thread.join();
  1811. ASSERT_FALSE(svr.is_running());
  1812. }
  1813. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  1814. protected:
  1815. ServerTestWithAI_PASSIVE()
  1816. : cli_(HOST, PORT)
  1817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1818. ,
  1819. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1820. #endif
  1821. {
  1822. }
  1823. virtual void SetUp() {
  1824. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1825. res.set_content("Hello World!", "text/plain");
  1826. });
  1827. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  1828. while (!svr_.is_running()) {
  1829. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1830. }
  1831. }
  1832. virtual void TearDown() {
  1833. svr_.stop();
  1834. t_.join();
  1835. }
  1836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1837. SSLClient cli_;
  1838. SSLServer svr_;
  1839. #else
  1840. Client cli_;
  1841. Server svr_;
  1842. #endif
  1843. thread t_;
  1844. };
  1845. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  1846. auto res = cli_.Get("/hi");
  1847. ASSERT_TRUE(res != nullptr);
  1848. EXPECT_EQ(200, res->status);
  1849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1850. EXPECT_EQ("Hello World!", res->body);
  1851. }
  1852. class ServerUpDownTest : public ::testing::Test {
  1853. protected:
  1854. ServerUpDownTest() : cli_(HOST, PORT) {}
  1855. virtual void SetUp() {
  1856. t_ = thread([&]() {
  1857. svr_.bind_to_any_port(HOST);
  1858. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  1859. ASSERT_TRUE(svr_.listen_after_bind());
  1860. });
  1861. while (!svr_.is_running()) {
  1862. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1863. }
  1864. }
  1865. virtual void TearDown() {
  1866. svr_.stop();
  1867. t_.join();
  1868. }
  1869. Client cli_;
  1870. Server svr_;
  1871. thread t_;
  1872. };
  1873. TEST_F(ServerUpDownTest, QuickStartStop) {
  1874. // Should not crash, especially when run with
  1875. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  1876. }
  1877. class PayloadMaxLengthTest : public ::testing::Test {
  1878. protected:
  1879. PayloadMaxLengthTest()
  1880. : cli_(HOST, PORT)
  1881. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1882. ,
  1883. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1884. #endif
  1885. {
  1886. }
  1887. virtual void SetUp() {
  1888. svr_.set_payload_max_length(8);
  1889. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  1890. res.set_content("test", "text/plain");
  1891. });
  1892. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1893. while (!svr_.is_running()) {
  1894. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1895. }
  1896. }
  1897. virtual void TearDown() {
  1898. svr_.stop();
  1899. t_.join();
  1900. }
  1901. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1902. SSLClient cli_;
  1903. SSLServer svr_;
  1904. #else
  1905. Client cli_;
  1906. Server svr_;
  1907. #endif
  1908. thread t_;
  1909. };
  1910. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  1911. auto res = cli_.Post("/test", "123456789", "text/plain");
  1912. ASSERT_TRUE(res != nullptr);
  1913. EXPECT_EQ(413, res->status);
  1914. res = cli_.Post("/test", "12345678", "text/plain");
  1915. ASSERT_TRUE(res != nullptr);
  1916. EXPECT_EQ(200, res->status);
  1917. }
  1918. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1919. TEST(SSLClientTest, ServerNameIndication) {
  1920. SSLClient cli("httpbin.org", 443);
  1921. auto res = cli.Get("/get");
  1922. ASSERT_TRUE(res != nullptr);
  1923. ASSERT_EQ(200, res->status);
  1924. }
  1925. TEST(SSLClientTest, ServerCertificateVerification) {
  1926. SSLClient cli("google.com");
  1927. auto res = cli.Get("/");
  1928. ASSERT_TRUE(res != nullptr);
  1929. ASSERT_EQ(301, res->status);
  1930. cli.enable_server_certificate_verification(true);
  1931. res = cli.Get("/");
  1932. ASSERT_TRUE(res == nullptr);
  1933. cli.set_ca_cert_path(CA_CERT_FILE);
  1934. res = cli.Get("/");
  1935. ASSERT_TRUE(res != nullptr);
  1936. ASSERT_EQ(301, res->status);
  1937. }
  1938. TEST(SSLClientTest, WildcardHostNameMatch) {
  1939. SSLClient cli("www.youtube.com");
  1940. cli.set_ca_cert_path(CA_CERT_FILE);
  1941. cli.enable_server_certificate_verification(true);
  1942. auto res = cli.Get("/");
  1943. ASSERT_TRUE(res != nullptr);
  1944. ASSERT_EQ(200, res->status);
  1945. }
  1946. TEST(SSLClientServerTest, ClientCertPresent) {
  1947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1948. CLIENT_CA_CERT_DIR);
  1949. ASSERT_TRUE(svr.is_valid());
  1950. svr.Get("/test", [&](const Request &req, Response &res) {
  1951. res.set_content("test", "text/plain");
  1952. svr.stop();
  1953. ASSERT_TRUE(true);
  1954. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  1955. ASSERT_TRUE(peer_cert != nullptr);
  1956. auto subject_name = X509_get_subject_name(peer_cert);
  1957. ASSERT_TRUE(subject_name != nullptr);
  1958. std::string common_name;
  1959. {
  1960. char name[BUFSIZ];
  1961. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  1962. name, sizeof(name));
  1963. common_name.assign(name, name_len);
  1964. }
  1965. EXPECT_EQ("Common Name", common_name);
  1966. X509_free(peer_cert);
  1967. });
  1968. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1969. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1970. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  1971. auto res = cli.Get("/test");
  1972. cli.set_timeout_sec(30);
  1973. ASSERT_TRUE(res != nullptr);
  1974. ASSERT_EQ(200, res->status);
  1975. t.join();
  1976. }
  1977. TEST(SSLClientServerTest, ClientCertMissing) {
  1978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1979. CLIENT_CA_CERT_DIR);
  1980. ASSERT_TRUE(svr.is_valid());
  1981. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  1982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1983. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1984. httplib::SSLClient cli(HOST, PORT);
  1985. auto res = cli.Get("/test");
  1986. cli.set_timeout_sec(30);
  1987. ASSERT_TRUE(res == nullptr);
  1988. svr.stop();
  1989. t.join();
  1990. }
  1991. TEST(SSLClientServerTest, TrustDirOptional) {
  1992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1993. ASSERT_TRUE(svr.is_valid());
  1994. svr.Get("/test", [&](const Request &, Response &res) {
  1995. res.set_content("test", "text/plain");
  1996. svr.stop();
  1997. });
  1998. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1999. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2000. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2001. auto res = cli.Get("/test");
  2002. cli.set_timeout_sec(30);
  2003. ASSERT_TRUE(res != nullptr);
  2004. ASSERT_EQ(200, res->status);
  2005. t.join();
  2006. }
  2007. /* Cannot test this case as there is no external access to SSL object to check
  2008. SSL_get_peer_certificate() == NULL TEST(SSLClientServerTest,
  2009. ClientCAPathRequired) { SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  2010. nullptr, CLIENT_CA_CERT_DIR);
  2011. }
  2012. */
  2013. #endif
  2014. #ifdef _WIN32
  2015. TEST(CleanupTest, WSACleanup) {
  2016. int ret = WSACleanup();
  2017. ASSERT_EQ(0, ret);
  2018. }
  2019. #endif