test.cc 69 KB

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