test.cc 64 KB

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