test.cc 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557
  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("/http_response_splitting",
  582. [&](const Request & /*req*/, Response &res) {
  583. res.set_header("a", "1\r\nSet-Cookie: a=1");
  584. EXPECT_EQ(0, res.headers.size());
  585. EXPECT_FALSE(res.has_header("a"));
  586. res.set_header("a", "1\nSet-Cookie: a=1");
  587. EXPECT_EQ(0, res.headers.size());
  588. EXPECT_FALSE(res.has_header("a"));
  589. res.set_header("a", "1\rSet-Cookie: a=1");
  590. EXPECT_EQ(0, res.headers.size());
  591. EXPECT_FALSE(res.has_header("a"));
  592. res.set_header("a\r\nb", "0");
  593. EXPECT_EQ(0, res.headers.size());
  594. EXPECT_FALSE(res.has_header("a"));
  595. res.set_header("a\rb", "0");
  596. EXPECT_EQ(0, res.headers.size());
  597. EXPECT_FALSE(res.has_header("a"));
  598. res.set_header("a\nb", "0");
  599. EXPECT_EQ(0, res.headers.size());
  600. EXPECT_FALSE(res.has_header("a"));
  601. res.set_redirect("1\r\nSet-Cookie: a=1");
  602. EXPECT_EQ(0, res.headers.size());
  603. EXPECT_FALSE(res.has_header("Location"));
  604. })
  605. .Get("/slow",
  606. [&](const Request & /*req*/, Response &res) {
  607. std::this_thread::sleep_for(std::chrono::seconds(2));
  608. res.set_content("slow", "text/plain");
  609. })
  610. .Get("/remote_addr",
  611. [&](const Request &req, Response &res) {
  612. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  613. res.set_content(remote_addr.c_str(), "text/plain");
  614. })
  615. .Get("/endwith%",
  616. [&](const Request & /*req*/, Response &res) {
  617. res.set_content("Hello World!", "text/plain");
  618. })
  619. .Get("/a\\+\\+b",
  620. [&](const Request &req, Response &res) {
  621. ASSERT_TRUE(req.has_param("a +b"));
  622. auto val = req.get_param_value("a +b");
  623. res.set_content(val, "text/plain");
  624. })
  625. .Get("/", [&](const Request & /*req*/,
  626. Response &res) { res.set_redirect("/hi"); })
  627. .Post("/person",
  628. [&](const Request &req, Response &res) {
  629. if (req.has_param("name") && req.has_param("note")) {
  630. persons_[req.get_param_value("name")] =
  631. req.get_param_value("note");
  632. } else {
  633. res.status = 400;
  634. }
  635. })
  636. .Put("/person",
  637. [&](const Request &req, Response &res) {
  638. if (req.has_param("name") && req.has_param("note")) {
  639. persons_[req.get_param_value("name")] =
  640. req.get_param_value("note");
  641. } else {
  642. res.status = 400;
  643. }
  644. })
  645. .Get("/person/(.*)",
  646. [&](const Request &req, Response &res) {
  647. string name = req.matches[1];
  648. if (persons_.find(name) != persons_.end()) {
  649. auto note = persons_[name];
  650. res.set_content(note, "text/plain");
  651. } else {
  652. res.status = 404;
  653. }
  654. })
  655. .Post("/x-www-form-urlencoded-json",
  656. [&](const Request &req, Response &res) {
  657. auto json = req.get_param_value("json");
  658. ASSERT_EQ(JSON_DATA, json);
  659. res.set_content(json, "appliation/json");
  660. res.status = 200;
  661. })
  662. .Get("/streamed-chunked",
  663. [&](const Request & /*req*/, Response &res) {
  664. res.set_chunked_content_provider(
  665. [](uint64_t /*offset*/, DataSink &sink) {
  666. ASSERT_TRUE(sink.is_writable());
  667. sink.write("123", 3);
  668. sink.write("456", 3);
  669. sink.write("789", 3);
  670. sink.done();
  671. });
  672. })
  673. .Get("/streamed-chunked2",
  674. [&](const Request & /*req*/, Response &res) {
  675. auto i = new int(0);
  676. res.set_chunked_content_provider(
  677. [i](uint64_t /*offset*/, DataSink &sink) {
  678. ASSERT_TRUE(sink.is_writable());
  679. switch (*i) {
  680. case 0: sink.write("123", 3); break;
  681. case 1: sink.write("456", 3); break;
  682. case 2: sink.write("789", 3); break;
  683. case 3: sink.done(); break;
  684. }
  685. (*i)++;
  686. },
  687. [i] { delete i; });
  688. })
  689. .Get("/streamed",
  690. [&](const Request & /*req*/, Response &res) {
  691. res.set_content_provider(
  692. 6, [](uint64_t offset, uint64_t /*length*/, DataSink &sink) {
  693. sink.write(offset < 3 ? "a" : "b", 1);
  694. });
  695. })
  696. .Get("/streamed-with-range",
  697. [&](const Request & /*req*/, Response &res) {
  698. auto data = new std::string("abcdefg");
  699. res.set_content_provider(
  700. data->size(),
  701. [data](uint64_t offset, uint64_t length, DataSink &sink) {
  702. ASSERT_TRUE(sink.is_writable());
  703. size_t DATA_CHUNK_SIZE = 4;
  704. const auto &d = *data;
  705. auto out_len =
  706. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  707. sink.write(&d[static_cast<size_t>(offset)], out_len);
  708. },
  709. [data] { delete data; });
  710. })
  711. .Get("/streamed-cancel",
  712. [&](const Request & /*req*/, Response &res) {
  713. res.set_content_provider(size_t(-1), [](uint64_t /*offset*/,
  714. uint64_t /*length*/,
  715. DataSink &sink) {
  716. ASSERT_TRUE(sink.is_writable());
  717. std::string data = "data_chunk";
  718. sink.write(data.data(), data.size());
  719. });
  720. })
  721. .Get("/with-range",
  722. [&](const Request & /*req*/, Response &res) {
  723. res.set_content("abcdefg", "text/plain");
  724. })
  725. .Post("/chunked",
  726. [&](const Request &req, Response & /*res*/) {
  727. EXPECT_EQ(req.body, "dechunked post body");
  728. })
  729. .Post("/large-chunked",
  730. [&](const Request &req, Response & /*res*/) {
  731. std::string expected(6 * 30 * 1024u, 'a');
  732. EXPECT_EQ(req.body, expected);
  733. })
  734. .Post("/multipart",
  735. [&](const Request &req, Response & /*res*/) {
  736. EXPECT_EQ(5u, req.files.size());
  737. ASSERT_TRUE(!req.has_file("???"));
  738. ASSERT_TRUE(req.body.empty());
  739. {
  740. const auto &file = req.get_file_value("text1");
  741. EXPECT_EQ("", file.filename);
  742. EXPECT_EQ("text default", file.content);
  743. }
  744. {
  745. const auto &file = req.get_file_value("text2");
  746. EXPECT_EQ("", file.filename);
  747. EXPECT_EQ("aωb", file.content);
  748. }
  749. {
  750. const auto &file = req.get_file_value("file1");
  751. EXPECT_EQ("hello.txt", file.filename);
  752. EXPECT_EQ("text/plain", file.content_type);
  753. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  754. }
  755. {
  756. const auto &file = req.get_file_value("file3");
  757. EXPECT_EQ("", file.filename);
  758. EXPECT_EQ("application/octet-stream", file.content_type);
  759. EXPECT_EQ(0u, file.content.size());
  760. }
  761. })
  762. .Post("/empty",
  763. [&](const Request &req, Response &res) {
  764. EXPECT_EQ(req.body, "");
  765. res.set_content("empty", "text/plain");
  766. })
  767. .Put("/put",
  768. [&](const Request &req, Response &res) {
  769. EXPECT_EQ(req.body, "PUT");
  770. res.set_content(req.body, "text/plain");
  771. })
  772. .Put("/put-large",
  773. [&](const Request &req, Response &res) {
  774. EXPECT_EQ(req.body, LARGE_DATA);
  775. res.set_content(req.body, "text/plain");
  776. })
  777. .Patch("/patch",
  778. [&](const Request &req, Response &res) {
  779. EXPECT_EQ(req.body, "PATCH");
  780. res.set_content(req.body, "text/plain");
  781. })
  782. .Delete("/delete",
  783. [&](const Request & /*req*/, Response &res) {
  784. res.set_content("DELETE", "text/plain");
  785. })
  786. .Delete("/delete-body",
  787. [&](const Request &req, Response &res) {
  788. EXPECT_EQ(req.body, "content");
  789. res.set_content(req.body, "text/plain");
  790. })
  791. .Options(R"(\*)",
  792. [&](const Request & /*req*/, Response &res) {
  793. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  794. })
  795. .Get("/request-target",
  796. [&](const Request &req, Response & /*res*/) {
  797. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  798. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  799. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  800. })
  801. .Get("/long-query-value",
  802. [&](const Request &req, Response & /*res*/) {
  803. EXPECT_EQ(LONG_QUERY_URL, req.target);
  804. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  805. })
  806. .Get("/array-param",
  807. [&](const Request &req, Response & /*res*/) {
  808. EXPECT_EQ(3u, req.get_param_value_count("array"));
  809. EXPECT_EQ("value1", req.get_param_value("array", 0));
  810. EXPECT_EQ("value2", req.get_param_value("array", 1));
  811. EXPECT_EQ("value3", req.get_param_value("array", 2));
  812. })
  813. .Post("/validate-no-multiple-headers",
  814. [&](const Request &req, Response & /*res*/) {
  815. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  816. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  817. })
  818. .Post("/content_receiver",
  819. [&](const Request &req, Response &res,
  820. const ContentReader &content_reader) {
  821. if (req.is_multipart_form_data()) {
  822. MultipartFormDataItems files;
  823. content_reader(
  824. [&](const MultipartFormData &file) {
  825. files.push_back(file);
  826. return true;
  827. },
  828. [&](const char *data, size_t data_length) {
  829. files.back().content.append(data, data_length);
  830. return true;
  831. });
  832. EXPECT_EQ(5u, files.size());
  833. {
  834. const auto &file = get_file_value(files, "text1");
  835. EXPECT_EQ("", file.filename);
  836. EXPECT_EQ("text default", file.content);
  837. }
  838. {
  839. const auto &file = get_file_value(files, "text2");
  840. EXPECT_EQ("", file.filename);
  841. EXPECT_EQ("aωb", file.content);
  842. }
  843. {
  844. const auto &file = get_file_value(files, "file1");
  845. EXPECT_EQ("hello.txt", file.filename);
  846. EXPECT_EQ("text/plain", file.content_type);
  847. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  848. }
  849. {
  850. const auto &file = get_file_value(files, "file3");
  851. EXPECT_EQ("", file.filename);
  852. EXPECT_EQ("application/octet-stream", file.content_type);
  853. EXPECT_EQ(0u, file.content.size());
  854. }
  855. } else {
  856. std::string body;
  857. content_reader([&](const char *data, size_t data_length) {
  858. EXPECT_EQ(data_length, 7);
  859. body.append(data, data_length);
  860. return true;
  861. });
  862. EXPECT_EQ(body, "content");
  863. res.set_content(body, "text/plain");
  864. }
  865. })
  866. .Put("/content_receiver",
  867. [&](const Request & /*req*/, Response &res,
  868. const ContentReader &content_reader) {
  869. std::string body;
  870. content_reader([&](const char *data, size_t data_length) {
  871. body.append(data, data_length);
  872. return true;
  873. });
  874. EXPECT_EQ(body, "content");
  875. res.set_content(body, "text/plain");
  876. })
  877. .Patch("/content_receiver",
  878. [&](const Request & /*req*/, Response &res,
  879. const ContentReader &content_reader) {
  880. std::string body;
  881. content_reader([&](const char *data, size_t data_length) {
  882. body.append(data, data_length);
  883. return true;
  884. });
  885. EXPECT_EQ(body, "content");
  886. res.set_content(body, "text/plain");
  887. })
  888. .Post("/query-string-and-body",
  889. [&](const Request &req, Response & /*res*/) {
  890. ASSERT_TRUE(req.has_param("key"));
  891. EXPECT_EQ(req.get_param_value("key"), "value");
  892. EXPECT_EQ(req.body, "content");
  893. })
  894. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  895. .Get("/gzip",
  896. [&](const Request & /*req*/, Response &res) {
  897. res.set_content(
  898. "12345678901234567890123456789012345678901234567890123456789"
  899. "01234567890123456789012345678901234567890",
  900. "text/plain");
  901. })
  902. .Get("/nogzip",
  903. [&](const Request & /*req*/, Response &res) {
  904. res.set_content(
  905. "12345678901234567890123456789012345678901234567890123456789"
  906. "01234567890123456789012345678901234567890",
  907. "application/octet-stream");
  908. })
  909. .Post("/gzipmultipart",
  910. [&](const Request &req, Response & /*res*/) {
  911. EXPECT_EQ(2u, req.files.size());
  912. ASSERT_TRUE(!req.has_file("???"));
  913. {
  914. const auto &file = req.get_file_value("key1");
  915. EXPECT_EQ("", file.filename);
  916. EXPECT_EQ("test", file.content);
  917. }
  918. {
  919. const auto &file = req.get_file_value("key2");
  920. EXPECT_EQ("", file.filename);
  921. EXPECT_EQ("--abcdefg123", file.content);
  922. }
  923. })
  924. #endif
  925. ;
  926. persons_["john"] = "programmer";
  927. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  928. while (!svr_.is_running()) {
  929. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  930. }
  931. }
  932. virtual void TearDown() {
  933. svr_.stop();
  934. for (auto &t : request_threads_) {
  935. t.join();
  936. }
  937. t_.join();
  938. }
  939. map<string, string> persons_;
  940. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  941. SSLClient cli_;
  942. SSLServer svr_;
  943. #else
  944. Client cli_;
  945. Server svr_;
  946. #endif
  947. thread t_;
  948. std::vector<thread> request_threads_;
  949. };
  950. TEST_F(ServerTest, GetMethod200) {
  951. auto res = cli_.Get("/hi");
  952. ASSERT_TRUE(res != nullptr);
  953. EXPECT_EQ("HTTP/1.1", res->version);
  954. EXPECT_EQ(200, res->status);
  955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  956. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  957. EXPECT_EQ("Hello World!", res->body);
  958. }
  959. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  960. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  961. ASSERT_TRUE(res != nullptr);
  962. EXPECT_EQ("HTTP/1.1", res->version);
  963. EXPECT_EQ(200, res->status);
  964. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  965. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  966. EXPECT_EQ("Hello World!", res->body);
  967. }
  968. TEST_F(ServerTest, GetMethod302) {
  969. auto res = cli_.Get("/");
  970. ASSERT_TRUE(res != nullptr);
  971. EXPECT_EQ(302, res->status);
  972. EXPECT_EQ("/hi", res->get_header_value("Location"));
  973. }
  974. TEST_F(ServerTest, GetMethod404) {
  975. auto res = cli_.Get("/invalid");
  976. ASSERT_TRUE(res != nullptr);
  977. EXPECT_EQ(404, res->status);
  978. }
  979. TEST_F(ServerTest, HeadMethod200) {
  980. auto res = cli_.Head("/hi");
  981. ASSERT_TRUE(res != nullptr);
  982. EXPECT_EQ(200, res->status);
  983. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  984. EXPECT_EQ("", res->body);
  985. }
  986. TEST_F(ServerTest, HeadMethod200Static) {
  987. auto res = cli_.Head("/mount/dir/index.html");
  988. ASSERT_TRUE(res != nullptr);
  989. EXPECT_EQ(200, res->status);
  990. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  991. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  992. EXPECT_EQ("", res->body);
  993. }
  994. TEST_F(ServerTest, HeadMethod404) {
  995. auto res = cli_.Head("/invalid");
  996. ASSERT_TRUE(res != nullptr);
  997. EXPECT_EQ(404, res->status);
  998. EXPECT_EQ("", res->body);
  999. }
  1000. TEST_F(ServerTest, GetMethodPersonJohn) {
  1001. auto res = cli_.Get("/person/john");
  1002. ASSERT_TRUE(res != nullptr);
  1003. EXPECT_EQ(200, res->status);
  1004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1005. EXPECT_EQ("programmer", res->body);
  1006. }
  1007. TEST_F(ServerTest, PostMethod1) {
  1008. auto res = cli_.Get("/person/john1");
  1009. ASSERT_TRUE(res != nullptr);
  1010. ASSERT_EQ(404, res->status);
  1011. res = cli_.Post("/person", "name=john1&note=coder",
  1012. "application/x-www-form-urlencoded");
  1013. ASSERT_TRUE(res != nullptr);
  1014. ASSERT_EQ(200, res->status);
  1015. res = cli_.Get("/person/john1");
  1016. ASSERT_TRUE(res != nullptr);
  1017. ASSERT_EQ(200, res->status);
  1018. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1019. ASSERT_EQ("coder", res->body);
  1020. }
  1021. TEST_F(ServerTest, PostMethod2) {
  1022. auto res = cli_.Get("/person/john2");
  1023. ASSERT_TRUE(res != nullptr);
  1024. ASSERT_EQ(404, res->status);
  1025. Params params;
  1026. params.emplace("name", "john2");
  1027. params.emplace("note", "coder");
  1028. res = cli_.Post("/person", params);
  1029. ASSERT_TRUE(res != nullptr);
  1030. ASSERT_EQ(200, res->status);
  1031. res = cli_.Get("/person/john2");
  1032. ASSERT_TRUE(res != nullptr);
  1033. ASSERT_EQ(200, res->status);
  1034. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1035. ASSERT_EQ("coder", res->body);
  1036. }
  1037. TEST_F(ServerTest, PutMethod3) {
  1038. auto res = cli_.Get("/person/john3");
  1039. ASSERT_TRUE(res != nullptr);
  1040. ASSERT_EQ(404, res->status);
  1041. Params params;
  1042. params.emplace("name", "john3");
  1043. params.emplace("note", "coder");
  1044. res = cli_.Put("/person", params);
  1045. ASSERT_TRUE(res != nullptr);
  1046. ASSERT_EQ(200, res->status);
  1047. res = cli_.Get("/person/john3");
  1048. ASSERT_TRUE(res != nullptr);
  1049. ASSERT_EQ(200, res->status);
  1050. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1051. ASSERT_EQ("coder", res->body);
  1052. }
  1053. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1054. Params params;
  1055. params.emplace("json", JSON_DATA);
  1056. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1057. ASSERT_TRUE(res != nullptr);
  1058. ASSERT_EQ(200, res->status);
  1059. ASSERT_EQ(JSON_DATA, res->body);
  1060. }
  1061. TEST_F(ServerTest, PostEmptyContent) {
  1062. auto res = cli_.Post("/empty", "", "text/plain");
  1063. ASSERT_TRUE(res != nullptr);
  1064. ASSERT_EQ(200, res->status);
  1065. ASSERT_EQ("empty", res->body);
  1066. }
  1067. TEST_F(ServerTest, GetMethodDir) {
  1068. auto res = cli_.Get("/dir/");
  1069. ASSERT_TRUE(res != nullptr);
  1070. EXPECT_EQ(200, res->status);
  1071. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1072. auto body = R"(<html>
  1073. <head>
  1074. </head>
  1075. <body>
  1076. <a href="/dir/test.html">Test</a>
  1077. <a href="/hi">hi</a>
  1078. </body>
  1079. </html>
  1080. )";
  1081. EXPECT_EQ(body, res->body);
  1082. }
  1083. TEST_F(ServerTest, GetMethodDirTest) {
  1084. auto res = cli_.Get("/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, GetMethodDirTestWithDoubleDots) {
  1091. auto res = cli_.Get("/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, GetMethodInvalidPath) {
  1098. auto res = cli_.Get("/dir/../test.html");
  1099. ASSERT_TRUE(res != nullptr);
  1100. EXPECT_EQ(404, res->status);
  1101. }
  1102. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1103. auto res = cli_.Get("/../www/dir/test.html");
  1104. ASSERT_TRUE(res != nullptr);
  1105. EXPECT_EQ(404, res->status);
  1106. }
  1107. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1108. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1109. ASSERT_TRUE(res != nullptr);
  1110. EXPECT_EQ(404, res->status);
  1111. }
  1112. TEST_F(ServerTest, GetMethodDirMountTest) {
  1113. auto res = cli_.Get("/mount/dir/test.html");
  1114. ASSERT_TRUE(res != nullptr);
  1115. EXPECT_EQ(200, res->status);
  1116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1117. EXPECT_EQ("test.html", res->body);
  1118. }
  1119. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1120. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1121. ASSERT_TRUE(res != nullptr);
  1122. EXPECT_EQ(200, res->status);
  1123. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1124. EXPECT_EQ("test.html", res->body);
  1125. }
  1126. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1127. auto res = cli_.Get("/mount/dir/../test.html");
  1128. ASSERT_TRUE(res != nullptr);
  1129. EXPECT_EQ(404, res->status);
  1130. }
  1131. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1132. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1133. ASSERT_TRUE(res != nullptr);
  1134. EXPECT_EQ(404, res->status);
  1135. }
  1136. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1137. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1138. ASSERT_TRUE(res != nullptr);
  1139. EXPECT_EQ(404, res->status);
  1140. }
  1141. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1142. auto res = cli_.Get("/dir/test.abcde");
  1143. ASSERT_TRUE(res != nullptr);
  1144. EXPECT_EQ(200, res->status);
  1145. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1146. EXPECT_EQ("abcde", res->body);
  1147. }
  1148. TEST_F(ServerTest, InvalidBaseDirMount) {
  1149. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1150. }
  1151. TEST_F(ServerTest, EmptyRequest) {
  1152. auto res = cli_.Get("");
  1153. ASSERT_TRUE(res == nullptr);
  1154. }
  1155. TEST_F(ServerTest, LongRequest) {
  1156. std::string request;
  1157. for (size_t i = 0; i < 545; i++) {
  1158. request += "/TooLongRequest";
  1159. }
  1160. request += "OK";
  1161. auto res = cli_.Get(request.c_str());
  1162. ASSERT_TRUE(res != nullptr);
  1163. EXPECT_EQ(404, res->status);
  1164. }
  1165. TEST_F(ServerTest, TooLongRequest) {
  1166. std::string request;
  1167. for (size_t i = 0; i < 545; i++) {
  1168. request += "/TooLongRequest";
  1169. }
  1170. request += "_NG";
  1171. auto res = cli_.Get(request.c_str());
  1172. ASSERT_TRUE(res != nullptr);
  1173. EXPECT_EQ(414, res->status);
  1174. }
  1175. TEST_F(ServerTest, LongHeader) {
  1176. Request req;
  1177. req.method = "GET";
  1178. req.path = "/hi";
  1179. std::string host_and_port;
  1180. host_and_port += HOST;
  1181. host_and_port += ":";
  1182. host_and_port += std::to_string(PORT);
  1183. req.headers.emplace("Host", host_and_port.c_str());
  1184. req.headers.emplace("Accept", "*/*");
  1185. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1186. req.headers.emplace(
  1187. "Header-Name",
  1188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1216. "@@@@@@@@@@@@@@@@");
  1217. auto res = std::make_shared<Response>();
  1218. auto ret = cli_.send(req, *res);
  1219. ASSERT_TRUE(ret);
  1220. EXPECT_EQ(200, res->status);
  1221. }
  1222. TEST_F(ServerTest, LongQueryValue) {
  1223. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1224. ASSERT_TRUE(res != nullptr);
  1225. EXPECT_EQ(414, res->status);
  1226. }
  1227. TEST_F(ServerTest, TooLongHeader) {
  1228. Request req;
  1229. req.method = "GET";
  1230. req.path = "/hi";
  1231. std::string host_and_port;
  1232. host_and_port += HOST;
  1233. host_and_port += ":";
  1234. host_and_port += std::to_string(PORT);
  1235. req.headers.emplace("Host", host_and_port.c_str());
  1236. req.headers.emplace("Accept", "*/*");
  1237. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1238. req.headers.emplace(
  1239. "Header-Name",
  1240. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1241. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1242. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1244. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1245. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1246. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1268. "@@@@@@@@@@@@@@@@@");
  1269. auto res = std::make_shared<Response>();
  1270. auto ret = cli_.send(req, *res);
  1271. ASSERT_TRUE(ret);
  1272. EXPECT_EQ(200, res->status);
  1273. }
  1274. TEST_F(ServerTest, PercentEncoding) {
  1275. auto res = cli_.Get("/e%6edwith%");
  1276. ASSERT_TRUE(res != nullptr);
  1277. EXPECT_EQ(200, res->status);
  1278. }
  1279. TEST_F(ServerTest, PercentEncodingUnicode) {
  1280. auto res = cli_.Get("/e%u006edwith%");
  1281. ASSERT_TRUE(res != nullptr);
  1282. EXPECT_EQ(200, res->status);
  1283. }
  1284. TEST_F(ServerTest, InvalidPercentEncoding) {
  1285. auto res = cli_.Get("/%endwith%");
  1286. ASSERT_TRUE(res != nullptr);
  1287. EXPECT_EQ(404, res->status);
  1288. }
  1289. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1290. auto res = cli_.Get("/%uendwith%");
  1291. ASSERT_TRUE(res != nullptr);
  1292. EXPECT_EQ(404, res->status);
  1293. }
  1294. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1295. auto res = cli_.Get("/hello?aaa=bbb%");
  1296. ASSERT_TRUE(res != nullptr);
  1297. EXPECT_EQ(404, res->status);
  1298. }
  1299. TEST_F(ServerTest, PlusSignEncoding) {
  1300. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1301. ASSERT_TRUE(res != nullptr);
  1302. EXPECT_EQ(200, res->status);
  1303. EXPECT_EQ("a +b", res->body);
  1304. }
  1305. TEST_F(ServerTest, MultipartFormData) {
  1306. MultipartFormDataItems items = {
  1307. {"text1", "text default", "", ""},
  1308. {"text2", "aωb", "", ""},
  1309. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1310. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1311. {"file3", "", "", "application/octet-stream"},
  1312. };
  1313. auto res = cli_.Post("/multipart", items);
  1314. ASSERT_TRUE(res != nullptr);
  1315. EXPECT_EQ(200, res->status);
  1316. }
  1317. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1318. auto res = cli_.Get("/hi");
  1319. ASSERT_TRUE(res != nullptr);
  1320. EXPECT_EQ(200, res->status);
  1321. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1322. EXPECT_EQ("Hello World!", res->body);
  1323. }
  1324. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1325. Request req;
  1326. req.method = "POST";
  1327. req.path = "/chunked";
  1328. std::string host_and_port;
  1329. host_and_port += HOST;
  1330. host_and_port += ":";
  1331. host_and_port += std::to_string(PORT);
  1332. req.headers.emplace("Host", host_and_port.c_str());
  1333. req.headers.emplace("Accept", "*/*");
  1334. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1335. req.headers.emplace("Content-Type", "text/plain");
  1336. req.headers.emplace("Content-Length", "0");
  1337. req.headers.emplace(
  1338. "Transfer-Encoding",
  1339. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1340. // Client does not chunk, so make a chunked body manually.
  1341. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1342. auto res = std::make_shared<Response>();
  1343. auto ret = cli_.send(req, *res);
  1344. ASSERT_TRUE(ret);
  1345. EXPECT_EQ(200, res->status);
  1346. }
  1347. TEST_F(ServerTest, GetStreamed2) {
  1348. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1349. ASSERT_TRUE(res != nullptr);
  1350. EXPECT_EQ(206, res->status);
  1351. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1352. EXPECT_EQ(std::string("ab"), res->body);
  1353. }
  1354. TEST_F(ServerTest, GetStreamed) {
  1355. auto res = cli_.Get("/streamed");
  1356. ASSERT_TRUE(res != nullptr);
  1357. EXPECT_EQ(200, res->status);
  1358. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1359. EXPECT_EQ(std::string("aaabbb"), res->body);
  1360. }
  1361. TEST_F(ServerTest, GetStreamedWithRange1) {
  1362. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1363. ASSERT_TRUE(res != nullptr);
  1364. EXPECT_EQ(206, res->status);
  1365. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1366. EXPECT_EQ(true, res->has_header("Content-Range"));
  1367. EXPECT_EQ(std::string("def"), res->body);
  1368. }
  1369. TEST_F(ServerTest, GetStreamedWithRange2) {
  1370. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1371. ASSERT_TRUE(res != nullptr);
  1372. EXPECT_EQ(206, res->status);
  1373. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1374. EXPECT_EQ(true, res->has_header("Content-Range"));
  1375. EXPECT_EQ(std::string("bcdefg"), res->body);
  1376. }
  1377. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1378. auto res =
  1379. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1380. ASSERT_TRUE(res != nullptr);
  1381. EXPECT_EQ(206, res->status);
  1382. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1383. EXPECT_EQ(false, res->has_header("Content-Range"));
  1384. EXPECT_EQ(269, res->body.size());
  1385. }
  1386. TEST_F(ServerTest, GetStreamedEndless) {
  1387. uint64_t offset = 0;
  1388. auto res = cli_.Get("/streamed-cancel",
  1389. [&](const char * /*data*/, uint64_t data_length) {
  1390. if (offset < 100) {
  1391. offset += data_length;
  1392. return true;
  1393. }
  1394. return false;
  1395. });
  1396. ASSERT_TRUE(res == nullptr);
  1397. }
  1398. TEST_F(ServerTest, GetWithRange1) {
  1399. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1400. ASSERT_TRUE(res != nullptr);
  1401. EXPECT_EQ(206, res->status);
  1402. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1403. EXPECT_EQ(true, res->has_header("Content-Range"));
  1404. EXPECT_EQ(std::string("def"), res->body);
  1405. }
  1406. TEST_F(ServerTest, GetWithRange2) {
  1407. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1408. ASSERT_TRUE(res != nullptr);
  1409. EXPECT_EQ(206, res->status);
  1410. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1411. EXPECT_EQ(true, res->has_header("Content-Range"));
  1412. EXPECT_EQ(std::string("bcdefg"), res->body);
  1413. }
  1414. TEST_F(ServerTest, GetWithRange3) {
  1415. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1416. ASSERT_TRUE(res != nullptr);
  1417. EXPECT_EQ(206, res->status);
  1418. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1419. EXPECT_EQ(true, res->has_header("Content-Range"));
  1420. EXPECT_EQ(std::string("a"), res->body);
  1421. }
  1422. TEST_F(ServerTest, GetWithRange4) {
  1423. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1424. ASSERT_TRUE(res != nullptr);
  1425. EXPECT_EQ(206, res->status);
  1426. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1427. EXPECT_EQ(true, res->has_header("Content-Range"));
  1428. EXPECT_EQ(std::string("fg"), res->body);
  1429. }
  1430. TEST_F(ServerTest, GetWithRangeMultipart) {
  1431. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1432. ASSERT_TRUE(res != nullptr);
  1433. EXPECT_EQ(206, res->status);
  1434. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1435. EXPECT_EQ(false, res->has_header("Content-Range"));
  1436. EXPECT_EQ(269, res->body.size());
  1437. }
  1438. TEST_F(ServerTest, GetStreamedChunked) {
  1439. auto res = cli_.Get("/streamed-chunked");
  1440. ASSERT_TRUE(res != nullptr);
  1441. EXPECT_EQ(200, res->status);
  1442. EXPECT_EQ(std::string("123456789"), res->body);
  1443. }
  1444. TEST_F(ServerTest, GetStreamedChunked2) {
  1445. auto res = cli_.Get("/streamed-chunked2");
  1446. ASSERT_TRUE(res != nullptr);
  1447. EXPECT_EQ(200, res->status);
  1448. EXPECT_EQ(std::string("123456789"), res->body);
  1449. }
  1450. TEST_F(ServerTest, LargeChunkedPost) {
  1451. Request req;
  1452. req.method = "POST";
  1453. req.path = "/large-chunked";
  1454. std::string host_and_port;
  1455. host_and_port += HOST;
  1456. host_and_port += ":";
  1457. host_and_port += std::to_string(PORT);
  1458. req.headers.emplace("Host", host_and_port.c_str());
  1459. req.headers.emplace("Accept", "*/*");
  1460. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1461. req.headers.emplace("Content-Type", "text/plain");
  1462. req.headers.emplace("Content-Length", "0");
  1463. req.headers.emplace("Transfer-Encoding", "chunked");
  1464. std::string long_string(30 * 1024u, 'a');
  1465. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1466. // Attempt to make a large enough post to exceed OS buffers, to test that
  1467. // the server handles short reads if the full chunk data isn't available.
  1468. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1469. auto res = std::make_shared<Response>();
  1470. auto ret = cli_.send(req, *res);
  1471. ASSERT_TRUE(ret);
  1472. EXPECT_EQ(200, res->status);
  1473. }
  1474. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1475. auto res = cli_.Get("/remote_addr");
  1476. ASSERT_TRUE(res != nullptr);
  1477. EXPECT_EQ(200, res->status);
  1478. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1479. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1480. }
  1481. TEST_F(ServerTest, HTTPResponseSplitting) {
  1482. auto res = cli_.Get("/http_response_splitting");
  1483. ASSERT_TRUE(res != nullptr);
  1484. EXPECT_EQ(200, res->status);
  1485. }
  1486. TEST_F(ServerTest, SlowRequest) {
  1487. request_threads_.push_back(
  1488. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1489. request_threads_.push_back(
  1490. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1491. request_threads_.push_back(
  1492. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1493. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1494. }
  1495. TEST_F(ServerTest, Put) {
  1496. auto res = cli_.Put("/put", "PUT", "text/plain");
  1497. ASSERT_TRUE(res != nullptr);
  1498. EXPECT_EQ(200, res->status);
  1499. EXPECT_EQ("PUT", res->body);
  1500. }
  1501. TEST_F(ServerTest, PutWithContentProvider) {
  1502. auto res = cli_.Put(
  1503. "/put", 3,
  1504. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1505. ASSERT_TRUE(sink.is_writable());
  1506. sink.write("PUT", 3);
  1507. },
  1508. "text/plain");
  1509. ASSERT_TRUE(res != nullptr);
  1510. EXPECT_EQ(200, res->status);
  1511. EXPECT_EQ("PUT", res->body);
  1512. }
  1513. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1514. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1515. cli_.set_compress(true);
  1516. auto res = cli_.Put(
  1517. "/put", 3,
  1518. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1519. ASSERT_TRUE(sink.is_writable());
  1520. sink.write("PUT", 3);
  1521. },
  1522. "text/plain");
  1523. ASSERT_TRUE(res != nullptr);
  1524. EXPECT_EQ(200, res->status);
  1525. EXPECT_EQ("PUT", res->body);
  1526. }
  1527. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1528. cli_.set_compress(true);
  1529. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  1530. ASSERT_TRUE(res != nullptr);
  1531. EXPECT_EQ(200, res->status);
  1532. EXPECT_EQ(LARGE_DATA, res->body);
  1533. }
  1534. TEST_F(ServerTest, PutContentWithDeflate) {
  1535. cli_.set_compress(false);
  1536. httplib::Headers headers;
  1537. headers.emplace("Content-Encoding", "deflate");
  1538. // PUT in deflate format:
  1539. auto res = cli_.Put("/put", headers,
  1540. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  1541. ASSERT_TRUE(res != nullptr);
  1542. EXPECT_EQ(200, res->status);
  1543. EXPECT_EQ("PUT", res->body);
  1544. }
  1545. #endif
  1546. TEST_F(ServerTest, Patch) {
  1547. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1548. ASSERT_TRUE(res != nullptr);
  1549. EXPECT_EQ(200, res->status);
  1550. EXPECT_EQ("PATCH", res->body);
  1551. }
  1552. TEST_F(ServerTest, Delete) {
  1553. auto res = cli_.Delete("/delete");
  1554. ASSERT_TRUE(res != nullptr);
  1555. EXPECT_EQ(200, res->status);
  1556. EXPECT_EQ("DELETE", res->body);
  1557. }
  1558. TEST_F(ServerTest, DeleteContentReceiver) {
  1559. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  1560. ASSERT_TRUE(res != nullptr);
  1561. EXPECT_EQ(200, res->status);
  1562. EXPECT_EQ("content", res->body);
  1563. }
  1564. TEST_F(ServerTest, Options) {
  1565. auto res = cli_.Options("*");
  1566. ASSERT_TRUE(res != nullptr);
  1567. EXPECT_EQ(200, res->status);
  1568. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1569. EXPECT_TRUE(res->body.empty());
  1570. }
  1571. TEST_F(ServerTest, URL) {
  1572. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1573. ASSERT_TRUE(res != nullptr);
  1574. EXPECT_EQ(200, res->status);
  1575. }
  1576. TEST_F(ServerTest, ArrayParam) {
  1577. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  1578. ASSERT_TRUE(res != nullptr);
  1579. EXPECT_EQ(200, res->status);
  1580. }
  1581. TEST_F(ServerTest, NoMultipleHeaders) {
  1582. Headers headers = {{"Content-Length", "5"}};
  1583. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  1584. "text/plain");
  1585. ASSERT_TRUE(res != nullptr);
  1586. EXPECT_EQ(200, res->status);
  1587. }
  1588. TEST_F(ServerTest, PostContentReceiver) {
  1589. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1590. ASSERT_TRUE(res != nullptr);
  1591. ASSERT_EQ(200, res->status);
  1592. ASSERT_EQ("content", res->body);
  1593. }
  1594. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  1595. MultipartFormDataItems items = {
  1596. {"text1", "text default", "", ""},
  1597. {"text2", "aωb", "", ""},
  1598. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1599. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1600. {"file3", "", "", "application/octet-stream"},
  1601. };
  1602. auto res = cli_.Post("/content_receiver", items);
  1603. ASSERT_TRUE(res != nullptr);
  1604. EXPECT_EQ(200, res->status);
  1605. }
  1606. TEST_F(ServerTest, PostContentReceiverGzip) {
  1607. cli_.set_compress(true);
  1608. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1609. ASSERT_TRUE(res != nullptr);
  1610. ASSERT_EQ(200, res->status);
  1611. ASSERT_EQ("content", res->body);
  1612. }
  1613. TEST_F(ServerTest, PutContentReceiver) {
  1614. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  1615. ASSERT_TRUE(res != nullptr);
  1616. ASSERT_EQ(200, res->status);
  1617. ASSERT_EQ("content", res->body);
  1618. }
  1619. TEST_F(ServerTest, PatchContentReceiver) {
  1620. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  1621. ASSERT_TRUE(res != nullptr);
  1622. ASSERT_EQ(200, res->status);
  1623. ASSERT_EQ("content", res->body);
  1624. }
  1625. TEST_F(ServerTest, PostQueryStringAndBody) {
  1626. auto res =
  1627. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  1628. ASSERT_TRUE(res != nullptr);
  1629. ASSERT_EQ(200, res->status);
  1630. }
  1631. TEST_F(ServerTest, HTTP2Magic) {
  1632. Request req;
  1633. req.method = "PRI";
  1634. req.path = "*";
  1635. req.body = "SM";
  1636. auto res = std::make_shared<Response>();
  1637. auto ret = cli_.send(req, *res);
  1638. ASSERT_TRUE(ret);
  1639. EXPECT_EQ(400, res->status);
  1640. }
  1641. TEST_F(ServerTest, KeepAlive) {
  1642. cli_.set_keep_alive_max_count(4);
  1643. std::vector<Request> requests;
  1644. Get(requests, "/hi");
  1645. Get(requests, "/hi");
  1646. Get(requests, "/hi");
  1647. Get(requests, "/not-exist");
  1648. Post(requests, "/empty", "", "text/plain");
  1649. std::vector<Response> responses;
  1650. auto ret = cli_.send(requests, responses);
  1651. ASSERT_TRUE(ret == true);
  1652. ASSERT_TRUE(requests.size() == responses.size());
  1653. for (size_t i = 0; i < 3; i++) {
  1654. auto &res = responses[i];
  1655. EXPECT_EQ(200, res.status);
  1656. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1657. EXPECT_EQ("Hello World!", res.body);
  1658. }
  1659. {
  1660. auto &res = responses[3];
  1661. EXPECT_EQ(404, res.status);
  1662. }
  1663. {
  1664. auto &res = responses[4];
  1665. EXPECT_EQ(200, res.status);
  1666. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1667. EXPECT_EQ("empty", res.body);
  1668. }
  1669. }
  1670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1671. TEST_F(ServerTest, Gzip) {
  1672. Headers headers;
  1673. headers.emplace("Accept-Encoding", "gzip, deflate");
  1674. auto res = cli_.Get("/gzip", headers);
  1675. ASSERT_TRUE(res != nullptr);
  1676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1678. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1679. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1680. "7890123456789012345678901234567890",
  1681. res->body);
  1682. EXPECT_EQ(200, res->status);
  1683. }
  1684. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  1685. Headers headers;
  1686. auto res = cli_.Get("/gzip", headers);
  1687. ASSERT_TRUE(res != nullptr);
  1688. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1690. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1691. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1692. "7890123456789012345678901234567890",
  1693. res->body);
  1694. EXPECT_EQ(200, res->status);
  1695. }
  1696. TEST_F(ServerTest, GzipWithContentReceiver) {
  1697. Headers headers;
  1698. headers.emplace("Accept-Encoding", "gzip, deflate");
  1699. std::string body;
  1700. auto res =
  1701. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1702. EXPECT_EQ(data_length, 100);
  1703. body.append(data, data_length);
  1704. return true;
  1705. });
  1706. ASSERT_TRUE(res != nullptr);
  1707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1708. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1709. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1710. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1711. "7890123456789012345678901234567890",
  1712. body);
  1713. EXPECT_EQ(200, res->status);
  1714. }
  1715. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  1716. Headers headers;
  1717. std::string body;
  1718. auto res =
  1719. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1720. EXPECT_EQ(data_length, 100);
  1721. body.append(data, data_length);
  1722. return true;
  1723. });
  1724. ASSERT_TRUE(res != nullptr);
  1725. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1726. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1727. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1728. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1729. "7890123456789012345678901234567890",
  1730. body);
  1731. EXPECT_EQ(200, res->status);
  1732. }
  1733. TEST_F(ServerTest, NoGzip) {
  1734. Headers headers;
  1735. headers.emplace("Accept-Encoding", "gzip, deflate");
  1736. auto res = cli_.Get("/nogzip", headers);
  1737. ASSERT_TRUE(res != nullptr);
  1738. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1739. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1740. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1741. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1742. "7890123456789012345678901234567890",
  1743. res->body);
  1744. EXPECT_EQ(200, res->status);
  1745. }
  1746. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  1747. Headers headers;
  1748. headers.emplace("Accept-Encoding", "gzip, deflate");
  1749. std::string body;
  1750. auto res =
  1751. cli_.Get("/nogzip", headers, [&](const char *data, uint64_t data_length) {
  1752. EXPECT_EQ(data_length, 100);
  1753. body.append(data, data_length);
  1754. return true;
  1755. });
  1756. ASSERT_TRUE(res != nullptr);
  1757. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1758. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1759. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1760. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1761. "7890123456789012345678901234567890",
  1762. body);
  1763. EXPECT_EQ(200, res->status);
  1764. }
  1765. TEST_F(ServerTest, MultipartFormDataGzip) {
  1766. MultipartFormDataItems items = {
  1767. {"key1", "test", "", ""},
  1768. {"key2", "--abcdefg123", "", ""},
  1769. };
  1770. cli_.set_compress(true);
  1771. auto res = cli_.Post("/gzipmultipart", items);
  1772. ASSERT_TRUE(res != nullptr);
  1773. EXPECT_EQ(200, res->status);
  1774. }
  1775. #endif
  1776. // Sends a raw request to a server listening at HOST:PORT.
  1777. static bool send_request(time_t read_timeout_sec, const std::string &req) {
  1778. auto client_sock = detail::create_client_socket(HOST, PORT, /*timeout_sec=*/5,
  1779. std::string());
  1780. if (client_sock == INVALID_SOCKET) { return false; }
  1781. return detail::process_and_close_socket(
  1782. true, client_sock, 1, read_timeout_sec, 0,
  1783. [&](Stream &strm, bool /*last_connection*/, bool &
  1784. /*connection_close*/) -> bool {
  1785. if (req.size() !=
  1786. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  1787. return false;
  1788. }
  1789. char buf[512];
  1790. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  1791. while (line_reader.getline()) {}
  1792. return true;
  1793. });
  1794. }
  1795. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  1796. Server svr;
  1797. std::string header_value;
  1798. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  1799. header_value = req.get_header_value("foo");
  1800. res.set_content("ok", "text/plain");
  1801. });
  1802. thread t = thread([&] { svr.listen(HOST, PORT); });
  1803. while (!svr.is_running()) {
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1805. }
  1806. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  1807. // like characters are not treated the same - use vertical tab and escape.
  1808. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  1809. "foo: \t \v bar \e\t \r\n"
  1810. "Connection: close\r\n"
  1811. "\r\n";
  1812. ASSERT_TRUE(send_request(5, req));
  1813. svr.stop();
  1814. t.join();
  1815. EXPECT_EQ(header_value, "\v bar \e");
  1816. }
  1817. // Sends a raw request and verifies that there isn't a crash or exception.
  1818. static void test_raw_request(const std::string &req) {
  1819. Server svr;
  1820. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1821. res.set_content("ok", "text/plain");
  1822. });
  1823. // Server read timeout must be longer than the client read timeout for the
  1824. // bug to reproduce, probably to force the server to process a request
  1825. // without a trailing blank line.
  1826. const time_t client_read_timeout_sec = 1;
  1827. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  1828. bool listen_thread_ok = false;
  1829. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  1830. while (!svr.is_running()) {
  1831. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1832. }
  1833. ASSERT_TRUE(send_request(client_read_timeout_sec, req));
  1834. svr.stop();
  1835. t.join();
  1836. EXPECT_TRUE(listen_thread_ok);
  1837. }
  1838. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  1839. // A certain header line causes an exception if the header property is parsed
  1840. // naively with a single regex. This occurs with libc++ but not libstdc++.
  1841. test_raw_request(
  1842. "GET /hi HTTP/1.1\r\n"
  1843. " : "
  1844. " "
  1845. );
  1846. }
  1847. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  1848. // A certain header line causes an exception if the header property *name* is
  1849. // parsed with a regular expression starting with "(.+?):" - this is a non-
  1850. // greedy matcher and requires backtracking when there are a lot of ":"
  1851. // characters.
  1852. // This occurs with libc++ but not libstdc++.
  1853. test_raw_request(
  1854. "GET /hi HTTP/1.1\r\n"
  1855. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  1856. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  1857. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  1858. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  1859. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  1860. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  1861. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  1862. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  1863. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  1864. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  1865. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  1866. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  1867. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  1868. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  1869. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  1870. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  1871. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  1872. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  1873. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  1874. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  1875. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  1876. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  1877. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  1878. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  1879. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  1880. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  1881. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  1882. "&&&%%%");
  1883. }
  1884. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  1885. Server svr;
  1886. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  1887. res.set_header("Content-Type", "text/event-stream");
  1888. res.set_header("Cache-Control", "no-cache");
  1889. res.set_chunked_content_provider([](size_t offset, const DataSink &sink) {
  1890. char buffer[27];
  1891. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  1892. sink.write(buffer, size);
  1893. std::this_thread::sleep_for(std::chrono::seconds(1));
  1894. });
  1895. });
  1896. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1897. while (!svr.is_running()) {
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1899. }
  1900. Client client(HOST, PORT);
  1901. const Headers headers = {{"Accept", "text/event-stream"},
  1902. {"Connection", "Keep-Alive"}};
  1903. auto get_thread = std::thread([&client, &headers]() {
  1904. std::shared_ptr<Response> res = client.Get(
  1905. "/events", headers,
  1906. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  1907. });
  1908. // Give GET time to get a few messages.
  1909. std::this_thread::sleep_for(std::chrono::seconds(2));
  1910. svr.stop();
  1911. listen_thread.join();
  1912. get_thread.join();
  1913. ASSERT_FALSE(svr.is_running());
  1914. }
  1915. TEST(MountTest, Unmount) {
  1916. Server svr;
  1917. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1918. while (!svr.is_running()) {
  1919. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1920. }
  1921. // Give GET time to get a few messages.
  1922. std::this_thread::sleep_for(std::chrono::seconds(1));
  1923. Client cli("localhost", PORT);
  1924. svr.set_mount_point("/mount2", "./www2");
  1925. auto res = cli.Get("/");
  1926. ASSERT_TRUE(res != nullptr);
  1927. EXPECT_EQ(404, res->status);
  1928. res = cli.Get("/mount2/dir/test.html");
  1929. ASSERT_TRUE(res != nullptr);
  1930. EXPECT_EQ(200, res->status);
  1931. svr.set_mount_point("/", "./www");
  1932. res = cli.Get("/dir/");
  1933. ASSERT_TRUE(res != nullptr);
  1934. EXPECT_EQ(200, res->status);
  1935. svr.remove_mount_point("/");
  1936. res = cli.Get("/dir/");
  1937. ASSERT_TRUE(res != nullptr);
  1938. EXPECT_EQ(404, res->status);
  1939. svr.remove_mount_point("/mount2");
  1940. res = cli.Get("/mount2/dir/test.html");
  1941. ASSERT_TRUE(res != nullptr);
  1942. EXPECT_EQ(404, res->status);
  1943. svr.stop();
  1944. listen_thread.join();
  1945. ASSERT_FALSE(svr.is_running());
  1946. }
  1947. TEST(ExceptionTest, ThrowExceptionInHandler) {
  1948. Server svr;
  1949. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1950. throw std::runtime_error("exception...");
  1951. res.set_content("Hello World!", "text/plain");
  1952. });
  1953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1954. while (!svr.is_running()) {
  1955. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1956. }
  1957. // Give GET time to get a few messages.
  1958. std::this_thread::sleep_for(std::chrono::seconds(1));
  1959. Client cli("localhost", PORT);
  1960. auto res = cli.Get("/hi");
  1961. ASSERT_TRUE(res != nullptr);
  1962. EXPECT_EQ(500, res->status);
  1963. ASSERT_FALSE(res->has_header("EXCEPTION_WHAT"));
  1964. svr.stop();
  1965. listen_thread.join();
  1966. ASSERT_FALSE(svr.is_running());
  1967. }
  1968. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  1969. protected:
  1970. ServerTestWithAI_PASSIVE()
  1971. : cli_(HOST, PORT)
  1972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1973. ,
  1974. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1975. #endif
  1976. {
  1977. }
  1978. virtual void SetUp() {
  1979. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1980. res.set_content("Hello World!", "text/plain");
  1981. });
  1982. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  1983. while (!svr_.is_running()) {
  1984. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1985. }
  1986. }
  1987. virtual void TearDown() {
  1988. svr_.stop();
  1989. t_.join();
  1990. }
  1991. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1992. SSLClient cli_;
  1993. SSLServer svr_;
  1994. #else
  1995. Client cli_;
  1996. Server svr_;
  1997. #endif
  1998. thread t_;
  1999. };
  2000. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  2001. auto res = cli_.Get("/hi");
  2002. ASSERT_TRUE(res != nullptr);
  2003. EXPECT_EQ(200, res->status);
  2004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2005. EXPECT_EQ("Hello World!", res->body);
  2006. }
  2007. class ServerUpDownTest : public ::testing::Test {
  2008. protected:
  2009. ServerUpDownTest() : cli_(HOST, PORT) {}
  2010. virtual void SetUp() {
  2011. t_ = thread([&]() {
  2012. svr_.bind_to_any_port(HOST);
  2013. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2014. ASSERT_TRUE(svr_.listen_after_bind());
  2015. });
  2016. while (!svr_.is_running()) {
  2017. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2018. }
  2019. }
  2020. virtual void TearDown() {
  2021. svr_.stop();
  2022. t_.join();
  2023. }
  2024. Client cli_;
  2025. Server svr_;
  2026. thread t_;
  2027. };
  2028. TEST_F(ServerUpDownTest, QuickStartStop) {
  2029. // Should not crash, especially when run with
  2030. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  2031. }
  2032. class PayloadMaxLengthTest : public ::testing::Test {
  2033. protected:
  2034. PayloadMaxLengthTest()
  2035. : cli_(HOST, PORT)
  2036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2037. ,
  2038. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2039. #endif
  2040. {
  2041. }
  2042. virtual void SetUp() {
  2043. svr_.set_payload_max_length(8);
  2044. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  2045. res.set_content("test", "text/plain");
  2046. });
  2047. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2048. while (!svr_.is_running()) {
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2050. }
  2051. }
  2052. virtual void TearDown() {
  2053. svr_.stop();
  2054. t_.join();
  2055. }
  2056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2057. SSLClient cli_;
  2058. SSLServer svr_;
  2059. #else
  2060. Client cli_;
  2061. Server svr_;
  2062. #endif
  2063. thread t_;
  2064. };
  2065. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  2066. auto res = cli_.Post("/test", "123456789", "text/plain");
  2067. ASSERT_TRUE(res != nullptr);
  2068. EXPECT_EQ(413, res->status);
  2069. res = cli_.Post("/test", "12345678", "text/plain");
  2070. ASSERT_TRUE(res != nullptr);
  2071. EXPECT_EQ(200, res->status);
  2072. }
  2073. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2074. TEST(SSLClientTest, ServerNameIndication) {
  2075. SSLClient cli("httpbin.org", 443);
  2076. auto res = cli.Get("/get");
  2077. ASSERT_TRUE(res != nullptr);
  2078. ASSERT_EQ(200, res->status);
  2079. }
  2080. TEST(SSLClientTest, ServerCertificateVerification) {
  2081. SSLClient cli("google.com");
  2082. auto res = cli.Get("/");
  2083. ASSERT_TRUE(res != nullptr);
  2084. ASSERT_EQ(301, res->status);
  2085. cli.enable_server_certificate_verification(true);
  2086. res = cli.Get("/");
  2087. ASSERT_TRUE(res == nullptr);
  2088. cli.set_ca_cert_path(CA_CERT_FILE);
  2089. res = cli.Get("/");
  2090. ASSERT_TRUE(res != nullptr);
  2091. ASSERT_EQ(301, res->status);
  2092. }
  2093. TEST(SSLClientTest, WildcardHostNameMatch) {
  2094. SSLClient cli("www.youtube.com");
  2095. cli.set_ca_cert_path(CA_CERT_FILE);
  2096. cli.enable_server_certificate_verification(true);
  2097. auto res = cli.Get("/");
  2098. ASSERT_TRUE(res != nullptr);
  2099. ASSERT_EQ(200, res->status);
  2100. }
  2101. TEST(SSLClientServerTest, ClientCertPresent) {
  2102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2103. CLIENT_CA_CERT_DIR);
  2104. ASSERT_TRUE(svr.is_valid());
  2105. svr.Get("/test", [&](const Request &req, Response &res) {
  2106. res.set_content("test", "text/plain");
  2107. svr.stop();
  2108. ASSERT_TRUE(true);
  2109. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2110. ASSERT_TRUE(peer_cert != nullptr);
  2111. auto subject_name = X509_get_subject_name(peer_cert);
  2112. ASSERT_TRUE(subject_name != nullptr);
  2113. std::string common_name;
  2114. {
  2115. char name[BUFSIZ];
  2116. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2117. name, sizeof(name));
  2118. common_name.assign(name, static_cast<size_t>(name_len));
  2119. }
  2120. EXPECT_EQ("Common Name", common_name);
  2121. X509_free(peer_cert);
  2122. });
  2123. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2124. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2125. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2126. auto res = cli.Get("/test");
  2127. cli.set_timeout_sec(30);
  2128. ASSERT_TRUE(res != nullptr);
  2129. ASSERT_EQ(200, res->status);
  2130. t.join();
  2131. }
  2132. TEST(SSLClientServerTest, ClientCertMissing) {
  2133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2134. CLIENT_CA_CERT_DIR);
  2135. ASSERT_TRUE(svr.is_valid());
  2136. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  2137. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2138. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2139. httplib::SSLClient cli(HOST, PORT);
  2140. auto res = cli.Get("/test");
  2141. cli.set_timeout_sec(30);
  2142. ASSERT_TRUE(res == nullptr);
  2143. svr.stop();
  2144. t.join();
  2145. }
  2146. TEST(SSLClientServerTest, TrustDirOptional) {
  2147. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2148. ASSERT_TRUE(svr.is_valid());
  2149. svr.Get("/test", [&](const Request &, Response &res) {
  2150. res.set_content("test", "text/plain");
  2151. svr.stop();
  2152. });
  2153. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2154. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2155. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2156. auto res = cli.Get("/test");
  2157. cli.set_timeout_sec(30);
  2158. ASSERT_TRUE(res != nullptr);
  2159. ASSERT_EQ(200, res->status);
  2160. t.join();
  2161. }
  2162. /* Cannot test this case as there is no external access to SSL object to check
  2163. SSL_get_peer_certificate() == NULL TEST(SSLClientServerTest,
  2164. ClientCAPathRequired) { SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  2165. nullptr, CLIENT_CA_CERT_DIR);
  2166. }
  2167. */
  2168. #endif
  2169. #ifdef _WIN32
  2170. TEST(CleanupTest, WSACleanup) {
  2171. int ret = WSACleanup();
  2172. ASSERT_EQ(0, ret);
  2173. }
  2174. #endif