test.cc 72 KB

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