test.cc 64 KB

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