test.cc 76 KB

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