test.cc 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  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. TEST(AbsoluteRedirectTest, Redirect) {
  398. auto host = "httpbin.org";
  399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  400. httplib::SSLClient cli(host);
  401. #else
  402. httplib::Client cli(host);
  403. #endif
  404. cli.follow_location(true);
  405. auto res = cli.Get("/absolute-redirect/3");
  406. ASSERT_TRUE(res != nullptr);
  407. EXPECT_EQ(200, res->status);
  408. }
  409. TEST(RedirectTest, Redirect) {
  410. auto host = "httpbin.org";
  411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  412. httplib::SSLClient cli(host);
  413. #else
  414. httplib::Client cli(host);
  415. #endif
  416. cli.follow_location(true);
  417. auto res = cli.Get("/redirect/3");
  418. ASSERT_TRUE(res != nullptr);
  419. EXPECT_EQ(200, res->status);
  420. }
  421. TEST(RelativeRedirectTest, Redirect) {
  422. auto host = "httpbin.org";
  423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  424. httplib::SSLClient cli(host);
  425. #else
  426. httplib::Client cli(host);
  427. #endif
  428. cli.follow_location(true);
  429. auto res = cli.Get("/relative-redirect/3");
  430. ASSERT_TRUE(res != nullptr);
  431. EXPECT_EQ(200, res->status);
  432. }
  433. TEST(TooManyRedirectTest, Redirect) {
  434. auto host = "httpbin.org";
  435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  436. httplib::SSLClient cli(host);
  437. #else
  438. httplib::Client cli(host);
  439. #endif
  440. cli.follow_location(true);
  441. auto res = cli.Get("/redirect/21");
  442. ASSERT_TRUE(res == nullptr);
  443. }
  444. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  445. TEST(YahooRedirectTest, Redirect) {
  446. httplib::Client cli("yahoo.com");
  447. auto res = cli.Get("/");
  448. ASSERT_TRUE(res != nullptr);
  449. EXPECT_EQ(301, res->status);
  450. cli.follow_location(true);
  451. res = cli.Get("/");
  452. ASSERT_TRUE(res != nullptr);
  453. EXPECT_EQ(200, res->status);
  454. }
  455. TEST(HttpsToHttpRedirectTest, Redirect) {
  456. httplib::SSLClient cli("httpbin.org");
  457. cli.follow_location(true);
  458. auto res =
  459. cli.Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  460. ASSERT_TRUE(res != nullptr);
  461. }
  462. #endif
  463. TEST(Server, BindAndListenSeparately) {
  464. Server svr;
  465. int port = svr.bind_to_any_port("localhost");
  466. ASSERT_TRUE(port > 0);
  467. svr.stop();
  468. }
  469. class ServerTest : public ::testing::Test {
  470. protected:
  471. ServerTest()
  472. : cli_(HOST, PORT)
  473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  474. ,
  475. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  476. #endif
  477. {
  478. }
  479. virtual void SetUp() {
  480. svr_.set_base_dir("./www");
  481. svr_.set_base_dir("./www2", "/mount");
  482. svr_.Get("/hi",
  483. [&](const Request & /*req*/, Response &res) {
  484. res.set_content("Hello World!", "text/plain");
  485. })
  486. .Get("/slow",
  487. [&](const Request & /*req*/, Response &res) {
  488. msleep(2000);
  489. res.set_content("slow", "text/plain");
  490. })
  491. .Get("/remote_addr",
  492. [&](const Request &req, Response &res) {
  493. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  494. res.set_content(remote_addr.c_str(), "text/plain");
  495. })
  496. .Get("/endwith%",
  497. [&](const Request & /*req*/, Response &res) {
  498. res.set_content("Hello World!", "text/plain");
  499. })
  500. .Get("/", [&](const Request & /*req*/,
  501. Response &res) { res.set_redirect("/hi"); })
  502. .Post("/person",
  503. [&](const Request &req, Response &res) {
  504. if (req.has_param("name") && req.has_param("note")) {
  505. persons_[req.get_param_value("name")] =
  506. req.get_param_value("note");
  507. } else {
  508. res.status = 400;
  509. }
  510. })
  511. .Get("/person/(.*)",
  512. [&](const Request &req, Response &res) {
  513. string name = req.matches[1];
  514. if (persons_.find(name) != persons_.end()) {
  515. auto note = persons_[name];
  516. res.set_content(note, "text/plain");
  517. } else {
  518. res.status = 404;
  519. }
  520. })
  521. .Post("/x-www-form-urlencoded-json",
  522. [&](const Request &req, Response &res) {
  523. auto json = req.get_param_value("json");
  524. ASSERT_EQ(JSON_DATA, json);
  525. res.set_content(json, "appliation/json");
  526. res.status = 200;
  527. })
  528. .Get("/streamed-chunked",
  529. [&](const Request & /*req*/, Response &res) {
  530. res.set_chunked_content_provider(
  531. [](uint64_t /*offset*/, DataSink sink, Done done) {
  532. sink("123", 3);
  533. sink("456", 3);
  534. sink("789", 3);
  535. done();
  536. });
  537. })
  538. .Get("/streamed",
  539. [&](const Request & /*req*/, Response &res) {
  540. res.set_content_provider(
  541. 6, [](uint64_t offset, uint64_t /*length*/, DataSink sink) {
  542. sink(offset < 3 ? "a" : "b", 1);
  543. });
  544. })
  545. .Get("/streamed-with-range",
  546. [&](const Request & /*req*/, Response &res) {
  547. auto data = new std::string("abcdefg");
  548. res.set_content_provider(
  549. data->size(),
  550. [data](uint64_t offset, uint64_t length, DataSink sink) {
  551. size_t DATA_CHUNK_SIZE = 4;
  552. const auto &d = *data;
  553. auto out_len =
  554. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  555. sink(&d[static_cast<size_t>(offset)], out_len);
  556. },
  557. [data] { delete data; });
  558. })
  559. .Get("/streamed-cancel",
  560. [&](const Request & /*req*/, Response &res) {
  561. res.set_content_provider(
  562. size_t(-1),
  563. [](uint64_t /*offset*/, uint64_t /*length*/, DataSink sink) {
  564. std::string data = "data_chunk";
  565. sink(data.data(), data.size());
  566. });
  567. })
  568. .Get("/with-range",
  569. [&](const Request & /*req*/, Response &res) {
  570. res.set_content("abcdefg", "text/plain");
  571. })
  572. .Post("/chunked",
  573. [&](const Request &req, Response & /*res*/) {
  574. EXPECT_EQ(req.body, "dechunked post body");
  575. })
  576. .Post("/large-chunked",
  577. [&](const Request &req, Response & /*res*/) {
  578. std::string expected(6 * 30 * 1024u, 'a');
  579. EXPECT_EQ(req.body, expected);
  580. })
  581. .Post("/multipart",
  582. [&](const Request &req, Response & /*res*/) {
  583. EXPECT_EQ(5u, req.files.size());
  584. ASSERT_TRUE(!req.has_file("???"));
  585. {
  586. const auto &file = req.get_file_value("text1");
  587. EXPECT_EQ("", file.filename);
  588. EXPECT_EQ("text default", file.content);
  589. }
  590. {
  591. const auto &file = req.get_file_value("text2");
  592. EXPECT_EQ("", file.filename);
  593. EXPECT_EQ("aωb", file.content);
  594. }
  595. {
  596. const auto &file = req.get_file_value("file1");
  597. EXPECT_EQ("hello.txt", file.filename);
  598. EXPECT_EQ("text/plain", file.content_type);
  599. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  600. }
  601. {
  602. const auto &file = req.get_file_value("file3");
  603. EXPECT_EQ("", file.filename);
  604. EXPECT_EQ("application/octet-stream", file.content_type);
  605. EXPECT_EQ(0u, file.content.size());
  606. }
  607. })
  608. .Post("/empty",
  609. [&](const Request &req, Response &res) {
  610. EXPECT_EQ(req.body, "");
  611. res.set_content("empty", "text/plain");
  612. })
  613. .Put("/put",
  614. [&](const Request &req, Response &res) {
  615. EXPECT_EQ(req.body, "PUT");
  616. res.set_content(req.body, "text/plain");
  617. })
  618. .Put("/put-large",
  619. [&](const Request &req, Response &res) {
  620. EXPECT_EQ(req.body, LARGE_DATA);
  621. res.set_content(req.body, "text/plain");
  622. })
  623. .Patch("/patch",
  624. [&](const Request &req, Response &res) {
  625. EXPECT_EQ(req.body, "PATCH");
  626. res.set_content(req.body, "text/plain");
  627. })
  628. .Delete("/delete",
  629. [&](const Request & /*req*/, Response &res) {
  630. res.set_content("DELETE", "text/plain");
  631. })
  632. .Options(R"(\*)",
  633. [&](const Request & /*req*/, Response &res) {
  634. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  635. })
  636. .Get("/request-target",
  637. [&](const Request &req, Response & /*res*/) {
  638. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  639. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  640. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  641. })
  642. .Get("/long-query-value",
  643. [&](const Request &req, Response & /*res*/) {
  644. EXPECT_EQ(LONG_QUERY_URL, req.target);
  645. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  646. })
  647. .Get("/array-param",
  648. [&](const Request &req, Response & /*res*/) {
  649. EXPECT_EQ(3u, req.get_param_value_count("array"));
  650. EXPECT_EQ("value1", req.get_param_value("array", 0));
  651. EXPECT_EQ("value2", req.get_param_value("array", 1));
  652. EXPECT_EQ("value3", req.get_param_value("array", 2));
  653. })
  654. .Post("/validate-no-multiple-headers",
  655. [&](const Request &req, Response & /*res*/) {
  656. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  657. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  658. })
  659. .Post("/content_receiver",
  660. [&](const Request & req, Response &res, const ContentReader &content_reader) {
  661. if (req.is_multipart_form_data()) {
  662. MultipartFiles files;
  663. content_reader(
  664. [&](const std::string &name, const MultipartFile &file) {
  665. files.emplace(name, file);
  666. return true;
  667. },
  668. [&](const std::string &name, const char *data, size_t data_length) {
  669. auto &file = files.find(name)->second;
  670. file.content.append(data, data_length);
  671. return true;
  672. });
  673. EXPECT_EQ(5u, files.size());
  674. {
  675. const auto &file = get_file_value(files, "text1");
  676. EXPECT_EQ("", file.filename);
  677. EXPECT_EQ("text default", file.content);
  678. }
  679. {
  680. const auto &file = get_file_value(files, "text2");
  681. EXPECT_EQ("", file.filename);
  682. EXPECT_EQ("aωb", file.content);
  683. }
  684. {
  685. const auto &file = get_file_value(files, "file1");
  686. EXPECT_EQ("hello.txt", file.filename);
  687. EXPECT_EQ("text/plain", file.content_type);
  688. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  689. }
  690. {
  691. const auto &file = get_file_value(files, "file3");
  692. EXPECT_EQ("", file.filename);
  693. EXPECT_EQ("application/octet-stream", file.content_type);
  694. EXPECT_EQ(0u, file.content.size());
  695. }
  696. } else {
  697. std::string body;
  698. content_reader([&](const char *data, size_t data_length) {
  699. EXPECT_EQ(data_length, 7);
  700. body.append(data, data_length);
  701. return true;
  702. });
  703. EXPECT_EQ(body, "content");
  704. res.set_content(body, "text/plain");
  705. }
  706. })
  707. .Put("/content_receiver",
  708. [&](const Request & /*req*/, Response &res,
  709. const ContentReader &content_reader) {
  710. std::string body;
  711. content_reader([&](const char *data, size_t data_length) {
  712. body.append(data, data_length);
  713. return true;
  714. });
  715. EXPECT_EQ(body, "content");
  716. res.set_content(body, "text/plain");
  717. })
  718. .Patch("/content_receiver",
  719. [&](const Request & /*req*/, Response &res,
  720. const ContentReader &content_reader) {
  721. std::string body;
  722. content_reader([&](const char *data, size_t data_length) {
  723. body.append(data, data_length);
  724. return true;
  725. });
  726. EXPECT_EQ(body, "content");
  727. res.set_content(body, "text/plain");
  728. })
  729. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  730. .Get("/gzip",
  731. [&](const Request & /*req*/, Response &res) {
  732. res.set_content(
  733. "12345678901234567890123456789012345678901234567890123456789"
  734. "01234567890123456789012345678901234567890",
  735. "text/plain");
  736. })
  737. .Get("/nogzip",
  738. [&](const Request & /*req*/, Response &res) {
  739. res.set_content(
  740. "12345678901234567890123456789012345678901234567890123456789"
  741. "01234567890123456789012345678901234567890",
  742. "application/octet-stream");
  743. })
  744. .Post("/gzipmultipart",
  745. [&](const Request &req, Response & /*res*/) {
  746. EXPECT_EQ(2u, req.files.size());
  747. ASSERT_TRUE(!req.has_file("???"));
  748. {
  749. const auto &file = req.get_file_value("key1");
  750. EXPECT_EQ("", file.filename);
  751. EXPECT_EQ("test", file.content);
  752. }
  753. {
  754. const auto &file = req.get_file_value("key2");
  755. EXPECT_EQ("", file.filename);
  756. EXPECT_EQ("--abcdefg123", file.content);
  757. }
  758. })
  759. #endif
  760. ;
  761. persons_["john"] = "programmer";
  762. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  763. while (!svr_.is_running()) {
  764. msleep(1);
  765. }
  766. }
  767. virtual void TearDown() {
  768. svr_.stop();
  769. for (auto &t : request_threads_) {
  770. t.join();
  771. }
  772. t_.join();
  773. }
  774. map<string, string> persons_;
  775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  776. SSLClient cli_;
  777. SSLServer svr_;
  778. #else
  779. Client cli_;
  780. Server svr_;
  781. #endif
  782. thread t_;
  783. std::vector<thread> request_threads_;
  784. };
  785. TEST_F(ServerTest, GetMethod200) {
  786. auto res = cli_.Get("/hi");
  787. ASSERT_TRUE(res != nullptr);
  788. EXPECT_EQ("HTTP/1.1", res->version);
  789. EXPECT_EQ(200, res->status);
  790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  791. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  792. EXPECT_EQ("Hello World!", res->body);
  793. }
  794. TEST_F(ServerTest, GetMethod302) {
  795. auto res = cli_.Get("/");
  796. ASSERT_TRUE(res != nullptr);
  797. EXPECT_EQ(302, res->status);
  798. EXPECT_EQ("/hi", res->get_header_value("Location"));
  799. }
  800. TEST_F(ServerTest, GetMethod404) {
  801. auto res = cli_.Get("/invalid");
  802. ASSERT_TRUE(res != nullptr);
  803. EXPECT_EQ(404, res->status);
  804. }
  805. TEST_F(ServerTest, HeadMethod200) {
  806. auto res = cli_.Head("/hi");
  807. ASSERT_TRUE(res != nullptr);
  808. EXPECT_EQ(200, res->status);
  809. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  810. EXPECT_EQ("", res->body);
  811. }
  812. TEST_F(ServerTest, HeadMethod404) {
  813. auto res = cli_.Head("/invalid");
  814. ASSERT_TRUE(res != nullptr);
  815. EXPECT_EQ(404, res->status);
  816. EXPECT_EQ("", res->body);
  817. }
  818. TEST_F(ServerTest, GetMethodPersonJohn) {
  819. auto res = cli_.Get("/person/john");
  820. ASSERT_TRUE(res != nullptr);
  821. EXPECT_EQ(200, res->status);
  822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  823. EXPECT_EQ("programmer", res->body);
  824. }
  825. TEST_F(ServerTest, PostMethod1) {
  826. auto res = cli_.Get("/person/john1");
  827. ASSERT_TRUE(res != nullptr);
  828. ASSERT_EQ(404, res->status);
  829. res = cli_.Post("/person", "name=john1&note=coder",
  830. "application/x-www-form-urlencoded");
  831. ASSERT_TRUE(res != nullptr);
  832. ASSERT_EQ(200, res->status);
  833. res = cli_.Get("/person/john1");
  834. ASSERT_TRUE(res != nullptr);
  835. ASSERT_EQ(200, res->status);
  836. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  837. ASSERT_EQ("coder", res->body);
  838. }
  839. TEST_F(ServerTest, PostMethod2) {
  840. auto res = cli_.Get("/person/john2");
  841. ASSERT_TRUE(res != nullptr);
  842. ASSERT_EQ(404, res->status);
  843. Params params;
  844. params.emplace("name", "john2");
  845. params.emplace("note", "coder");
  846. res = cli_.Post("/person", params);
  847. ASSERT_TRUE(res != nullptr);
  848. ASSERT_EQ(200, res->status);
  849. res = cli_.Get("/person/john2");
  850. ASSERT_TRUE(res != nullptr);
  851. ASSERT_EQ(200, res->status);
  852. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  853. ASSERT_EQ("coder", res->body);
  854. }
  855. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  856. Params params;
  857. params.emplace("json", JSON_DATA);
  858. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  859. ASSERT_TRUE(res != nullptr);
  860. ASSERT_EQ(200, res->status);
  861. ASSERT_EQ(JSON_DATA, res->body);
  862. }
  863. TEST_F(ServerTest, PostEmptyContent) {
  864. auto res = cli_.Post("/empty", "", "text/plain");
  865. ASSERT_TRUE(res != nullptr);
  866. ASSERT_EQ(200, res->status);
  867. ASSERT_EQ("empty", res->body);
  868. }
  869. TEST_F(ServerTest, GetMethodDir) {
  870. auto res = cli_.Get("/dir/");
  871. ASSERT_TRUE(res != nullptr);
  872. EXPECT_EQ(200, res->status);
  873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  874. auto body = R"(<html>
  875. <head>
  876. </head>
  877. <body>
  878. <a href="/dir/test.html">Test</a>
  879. <a href="/hi">hi</a>
  880. </body>
  881. </html>
  882. )";
  883. EXPECT_EQ(body, res->body);
  884. }
  885. TEST_F(ServerTest, GetMethodDirTest) {
  886. auto res = cli_.Get("/dir/test.html");
  887. ASSERT_TRUE(res != nullptr);
  888. EXPECT_EQ(200, res->status);
  889. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  890. EXPECT_EQ("test.html", res->body);
  891. }
  892. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  893. auto res = cli_.Get("/dir/../dir/test.html");
  894. ASSERT_TRUE(res != nullptr);
  895. EXPECT_EQ(200, res->status);
  896. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  897. EXPECT_EQ("test.html", res->body);
  898. }
  899. TEST_F(ServerTest, GetMethodInvalidPath) {
  900. auto res = cli_.Get("/dir/../test.html");
  901. ASSERT_TRUE(res != nullptr);
  902. EXPECT_EQ(404, res->status);
  903. }
  904. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  905. auto res = cli_.Get("/../www/dir/test.html");
  906. ASSERT_TRUE(res != nullptr);
  907. EXPECT_EQ(404, res->status);
  908. }
  909. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  910. auto res = cli_.Get("/dir/../../www/dir/test.html");
  911. ASSERT_TRUE(res != nullptr);
  912. EXPECT_EQ(404, res->status);
  913. }
  914. TEST_F(ServerTest, GetMethodDirMountTest) {
  915. auto res = cli_.Get("/mount/dir/test.html");
  916. ASSERT_TRUE(res != nullptr);
  917. EXPECT_EQ(200, res->status);
  918. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  919. EXPECT_EQ("test.html", res->body);
  920. }
  921. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  922. auto res = cli_.Get("/mount/dir/../dir/test.html");
  923. ASSERT_TRUE(res != nullptr);
  924. EXPECT_EQ(200, res->status);
  925. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  926. EXPECT_EQ("test.html", res->body);
  927. }
  928. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  929. auto res = cli_.Get("/mount/dir/../test.html");
  930. ASSERT_TRUE(res != nullptr);
  931. EXPECT_EQ(404, res->status);
  932. }
  933. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  934. auto res = cli_.Get("/mount/../www2/dir/test.html");
  935. ASSERT_TRUE(res != nullptr);
  936. EXPECT_EQ(404, res->status);
  937. }
  938. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  939. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  940. ASSERT_TRUE(res != nullptr);
  941. EXPECT_EQ(404, res->status);
  942. }
  943. TEST_F(ServerTest, InvalidBaseDirMount) {
  944. EXPECT_EQ(false, svr_.set_base_dir("./www3", "invalid_mount_point"));
  945. }
  946. TEST_F(ServerTest, EmptyRequest) {
  947. auto res = cli_.Get("");
  948. ASSERT_TRUE(res == nullptr);
  949. }
  950. TEST_F(ServerTest, LongRequest) {
  951. std::string request;
  952. for (size_t i = 0; i < 545; i++) {
  953. request += "/TooLongRequest";
  954. }
  955. request += "OK";
  956. auto res = cli_.Get(request.c_str());
  957. ASSERT_TRUE(res != nullptr);
  958. EXPECT_EQ(404, res->status);
  959. }
  960. TEST_F(ServerTest, TooLongRequest) {
  961. std::string request;
  962. for (size_t i = 0; i < 545; i++) {
  963. request += "/TooLongRequest";
  964. }
  965. request += "_NG";
  966. auto res = cli_.Get(request.c_str());
  967. ASSERT_TRUE(res != nullptr);
  968. EXPECT_EQ(414, res->status);
  969. }
  970. TEST_F(ServerTest, LongHeader) {
  971. Request req;
  972. req.method = "GET";
  973. req.path = "/hi";
  974. std::string host_and_port;
  975. host_and_port += HOST;
  976. host_and_port += ":";
  977. host_and_port += std::to_string(PORT);
  978. req.headers.emplace("Host", host_and_port.c_str());
  979. req.headers.emplace("Accept", "*/*");
  980. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  981. req.headers.emplace(
  982. "Header-Name",
  983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1011. "@@@@@@@@@@@@@@@@");
  1012. auto res = std::make_shared<Response>();
  1013. auto ret = cli_.send(req, *res);
  1014. ASSERT_TRUE(ret);
  1015. EXPECT_EQ(200, res->status);
  1016. }
  1017. TEST_F(ServerTest, LongQueryValue) {
  1018. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1019. ASSERT_TRUE(res != nullptr);
  1020. EXPECT_EQ(414, res->status);
  1021. }
  1022. TEST_F(ServerTest, TooLongHeader) {
  1023. Request req;
  1024. req.method = "GET";
  1025. req.path = "/hi";
  1026. std::string host_and_port;
  1027. host_and_port += HOST;
  1028. host_and_port += ":";
  1029. host_and_port += std::to_string(PORT);
  1030. req.headers.emplace("Host", host_and_port.c_str());
  1031. req.headers.emplace("Accept", "*/*");
  1032. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1033. req.headers.emplace(
  1034. "Header-Name",
  1035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1063. "@@@@@@@@@@@@@@@@@");
  1064. auto res = std::make_shared<Response>();
  1065. auto ret = cli_.send(req, *res);
  1066. ASSERT_TRUE(ret);
  1067. EXPECT_EQ(200, res->status);
  1068. }
  1069. TEST_F(ServerTest, PercentEncoding) {
  1070. auto res = cli_.Get("/e%6edwith%");
  1071. ASSERT_TRUE(res != nullptr);
  1072. EXPECT_EQ(200, res->status);
  1073. }
  1074. TEST_F(ServerTest, PercentEncodingUnicode) {
  1075. auto res = cli_.Get("/e%u006edwith%");
  1076. ASSERT_TRUE(res != nullptr);
  1077. EXPECT_EQ(200, res->status);
  1078. }
  1079. TEST_F(ServerTest, InvalidPercentEncoding) {
  1080. auto res = cli_.Get("/%endwith%");
  1081. ASSERT_TRUE(res != nullptr);
  1082. EXPECT_EQ(404, res->status);
  1083. }
  1084. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1085. auto res = cli_.Get("/%uendwith%");
  1086. ASSERT_TRUE(res != nullptr);
  1087. EXPECT_EQ(404, res->status);
  1088. }
  1089. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1090. auto res = cli_.Get("/hello?aaa=bbb%");
  1091. ASSERT_TRUE(res != nullptr);
  1092. EXPECT_EQ(404, res->status);
  1093. }
  1094. TEST_F(ServerTest, MultipartFormData) {
  1095. MultipartFormDataItems items = {
  1096. {"text1", "text default", "", ""},
  1097. {"text2", "aωb", "", ""},
  1098. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1099. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1100. {"file3", "", "", "application/octet-stream"},
  1101. };
  1102. auto res = cli_.Post("/multipart", items);
  1103. ASSERT_TRUE(res != nullptr);
  1104. EXPECT_EQ(200, res->status);
  1105. }
  1106. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1107. auto res = cli_.Get("/hi");
  1108. ASSERT_TRUE(res != nullptr);
  1109. EXPECT_EQ(200, res->status);
  1110. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1111. EXPECT_EQ("Hello World!", res->body);
  1112. }
  1113. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1114. Request req;
  1115. req.method = "POST";
  1116. req.path = "/chunked";
  1117. std::string host_and_port;
  1118. host_and_port += HOST;
  1119. host_and_port += ":";
  1120. host_and_port += std::to_string(PORT);
  1121. req.headers.emplace("Host", host_and_port.c_str());
  1122. req.headers.emplace("Accept", "*/*");
  1123. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1124. req.headers.emplace("Content-Type", "text/plain");
  1125. req.headers.emplace("Content-Length", "0");
  1126. req.headers.emplace(
  1127. "Transfer-Encoding",
  1128. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1129. // Client does not chunk, so make a chunked body manually.
  1130. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1131. auto res = std::make_shared<Response>();
  1132. auto ret = cli_.send(req, *res);
  1133. ASSERT_TRUE(ret);
  1134. EXPECT_EQ(200, res->status);
  1135. }
  1136. TEST_F(ServerTest, GetStreamed2) {
  1137. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1138. ASSERT_TRUE(res != nullptr);
  1139. EXPECT_EQ(206, res->status);
  1140. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1141. EXPECT_EQ(std::string("ab"), res->body);
  1142. }
  1143. TEST_F(ServerTest, GetStreamed) {
  1144. auto res = cli_.Get("/streamed");
  1145. ASSERT_TRUE(res != nullptr);
  1146. EXPECT_EQ(200, res->status);
  1147. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1148. EXPECT_EQ(std::string("aaabbb"), res->body);
  1149. }
  1150. TEST_F(ServerTest, GetStreamedWithRange1) {
  1151. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1152. ASSERT_TRUE(res != nullptr);
  1153. EXPECT_EQ(206, res->status);
  1154. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1155. EXPECT_EQ(true, res->has_header("Content-Range"));
  1156. EXPECT_EQ(std::string("def"), res->body);
  1157. }
  1158. TEST_F(ServerTest, GetStreamedWithRange2) {
  1159. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1160. ASSERT_TRUE(res != nullptr);
  1161. EXPECT_EQ(206, res->status);
  1162. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1163. EXPECT_EQ(true, res->has_header("Content-Range"));
  1164. EXPECT_EQ(std::string("bcdefg"), res->body);
  1165. }
  1166. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1167. auto res =
  1168. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1169. ASSERT_TRUE(res != nullptr);
  1170. EXPECT_EQ(206, res->status);
  1171. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1172. EXPECT_EQ(false, res->has_header("Content-Range"));
  1173. EXPECT_EQ(269, res->body.size());
  1174. }
  1175. TEST_F(ServerTest, GetStreamedEndless) {
  1176. size_t offset = 0;
  1177. auto res = cli_.Get("/streamed-cancel",
  1178. [&](const char * /*data*/, uint64_t data_length) {
  1179. if (offset < 100) {
  1180. offset += data_length;
  1181. return true;
  1182. }
  1183. return false;
  1184. });
  1185. ASSERT_TRUE(res == nullptr);
  1186. }
  1187. TEST_F(ServerTest, GetWithRange1) {
  1188. auto res = cli_.Get("/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, GetWithRange2) {
  1196. auto res = cli_.Get("/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, GetWithRange3) {
  1204. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1205. ASSERT_TRUE(res != nullptr);
  1206. EXPECT_EQ(206, res->status);
  1207. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1208. EXPECT_EQ(true, res->has_header("Content-Range"));
  1209. EXPECT_EQ(std::string("a"), res->body);
  1210. }
  1211. TEST_F(ServerTest, GetWithRange4) {
  1212. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1213. ASSERT_TRUE(res != nullptr);
  1214. EXPECT_EQ(206, res->status);
  1215. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1216. EXPECT_EQ(true, res->has_header("Content-Range"));
  1217. EXPECT_EQ(std::string("fg"), res->body);
  1218. }
  1219. TEST_F(ServerTest, GetWithRangeMultipart) {
  1220. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1221. ASSERT_TRUE(res != nullptr);
  1222. EXPECT_EQ(206, res->status);
  1223. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1224. EXPECT_EQ(false, res->has_header("Content-Range"));
  1225. EXPECT_EQ(269, res->body.size());
  1226. }
  1227. TEST_F(ServerTest, GetStreamedChunked) {
  1228. auto res = cli_.Get("/streamed-chunked");
  1229. ASSERT_TRUE(res != nullptr);
  1230. EXPECT_EQ(200, res->status);
  1231. EXPECT_EQ(std::string("123456789"), res->body);
  1232. }
  1233. TEST_F(ServerTest, LargeChunkedPost) {
  1234. Request req;
  1235. req.method = "POST";
  1236. req.path = "/large-chunked";
  1237. std::string host_and_port;
  1238. host_and_port += HOST;
  1239. host_and_port += ":";
  1240. host_and_port += std::to_string(PORT);
  1241. req.headers.emplace("Host", host_and_port.c_str());
  1242. req.headers.emplace("Accept", "*/*");
  1243. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1244. req.headers.emplace("Content-Type", "text/plain");
  1245. req.headers.emplace("Content-Length", "0");
  1246. req.headers.emplace("Transfer-Encoding", "chunked");
  1247. std::string long_string(30 * 1024u, 'a');
  1248. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1249. // Attempt to make a large enough post to exceed OS buffers, to test that
  1250. // the server handles short reads if the full chunk data isn't available.
  1251. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1252. auto res = std::make_shared<Response>();
  1253. auto ret = cli_.send(req, *res);
  1254. ASSERT_TRUE(ret);
  1255. EXPECT_EQ(200, res->status);
  1256. }
  1257. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1258. auto res = cli_.Get("/remote_addr");
  1259. ASSERT_TRUE(res != nullptr);
  1260. EXPECT_EQ(200, res->status);
  1261. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1262. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1263. }
  1264. TEST_F(ServerTest, SlowRequest) {
  1265. request_threads_.push_back(
  1266. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1267. request_threads_.push_back(
  1268. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1269. request_threads_.push_back(
  1270. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1271. msleep(100);
  1272. }
  1273. TEST_F(ServerTest, Put) {
  1274. auto res = cli_.Put("/put", "PUT", "text/plain");
  1275. ASSERT_TRUE(res != nullptr);
  1276. EXPECT_EQ(200, res->status);
  1277. EXPECT_EQ("PUT", res->body);
  1278. }
  1279. TEST_F(ServerTest, PutWithContentProvider) {
  1280. auto res = cli_.Put(
  1281. "/put", 3,
  1282. [](size_t /*offset*/, size_t /*length*/, DataSink sink) {
  1283. sink("PUT", 3);
  1284. },
  1285. "text/plain");
  1286. ASSERT_TRUE(res != nullptr);
  1287. EXPECT_EQ(200, res->status);
  1288. EXPECT_EQ("PUT", res->body);
  1289. }
  1290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1291. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1292. auto res = cli_.Put(
  1293. "/put", 3,
  1294. [](size_t /*offset*/, size_t /*length*/, DataSink sink) {
  1295. sink("PUT", 3);
  1296. },
  1297. "text/plain", true);
  1298. ASSERT_TRUE(res != nullptr);
  1299. EXPECT_EQ(200, res->status);
  1300. EXPECT_EQ("PUT", res->body);
  1301. }
  1302. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1303. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain", true);
  1304. ASSERT_TRUE(res != nullptr);
  1305. EXPECT_EQ(200, res->status);
  1306. EXPECT_EQ(LARGE_DATA, res->body);
  1307. }
  1308. #endif
  1309. TEST_F(ServerTest, Patch) {
  1310. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1311. ASSERT_TRUE(res != nullptr);
  1312. EXPECT_EQ(200, res->status);
  1313. EXPECT_EQ("PATCH", res->body);
  1314. }
  1315. TEST_F(ServerTest, Delete) {
  1316. auto res = cli_.Delete("/delete");
  1317. ASSERT_TRUE(res != nullptr);
  1318. EXPECT_EQ(200, res->status);
  1319. EXPECT_EQ("DELETE", res->body);
  1320. }
  1321. TEST_F(ServerTest, Options) {
  1322. auto res = cli_.Options("*");
  1323. ASSERT_TRUE(res != nullptr);
  1324. EXPECT_EQ(200, res->status);
  1325. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1326. EXPECT_TRUE(res->body.empty());
  1327. }
  1328. TEST_F(ServerTest, URL) {
  1329. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1330. ASSERT_TRUE(res != nullptr);
  1331. EXPECT_EQ(200, res->status);
  1332. }
  1333. TEST_F(ServerTest, ArrayParam) {
  1334. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  1335. ASSERT_TRUE(res != nullptr);
  1336. EXPECT_EQ(200, res->status);
  1337. }
  1338. TEST_F(ServerTest, NoMultipleHeaders) {
  1339. Headers headers = {{"Content-Length", "5"}};
  1340. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  1341. "text/plain");
  1342. ASSERT_TRUE(res != nullptr);
  1343. EXPECT_EQ(200, res->status);
  1344. }
  1345. TEST_F(ServerTest, PostContentReceiver) {
  1346. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1347. ASSERT_TRUE(res != nullptr);
  1348. ASSERT_EQ(200, res->status);
  1349. ASSERT_EQ("content", res->body);
  1350. }
  1351. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  1352. MultipartFormDataItems items = {
  1353. {"text1", "text default", "", ""},
  1354. {"text2", "aωb", "", ""},
  1355. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1356. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1357. {"file3", "", "", "application/octet-stream"},
  1358. };
  1359. auto res = cli_.Post("/content_receiver", items);
  1360. ASSERT_TRUE(res != nullptr);
  1361. EXPECT_EQ(200, res->status);
  1362. }
  1363. TEST_F(ServerTest, PostContentReceiverGzip) {
  1364. auto res = cli_.Post("/content_receiver", "content", "text/plain", true);
  1365. ASSERT_TRUE(res != nullptr);
  1366. ASSERT_EQ(200, res->status);
  1367. ASSERT_EQ("content", res->body);
  1368. }
  1369. TEST_F(ServerTest, PutContentReceiver) {
  1370. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  1371. ASSERT_TRUE(res != nullptr);
  1372. ASSERT_EQ(200, res->status);
  1373. ASSERT_EQ("content", res->body);
  1374. }
  1375. TEST_F(ServerTest, PatchContentReceiver) {
  1376. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  1377. ASSERT_TRUE(res != nullptr);
  1378. ASSERT_EQ(200, res->status);
  1379. ASSERT_EQ("content", res->body);
  1380. }
  1381. TEST_F(ServerTest, HTTP2Magic) {
  1382. Request req;
  1383. req.method = "PRI";
  1384. req.path = "*";
  1385. req.body = "SM";
  1386. auto res = std::make_shared<Response>();
  1387. auto ret = cli_.send(req, *res);
  1388. ASSERT_TRUE(ret);
  1389. EXPECT_EQ(400, res->status);
  1390. }
  1391. TEST_F(ServerTest, KeepAlive) {
  1392. cli_.set_keep_alive_max_count(4);
  1393. std::vector<Request> requests;
  1394. Get(requests, "/hi");
  1395. Get(requests, "/hi");
  1396. Get(requests, "/hi");
  1397. Get(requests, "/not-exist");
  1398. Post(requests, "/empty", "", "text/plain");
  1399. std::vector<Response> responses;
  1400. auto ret = cli_.send(requests, responses);
  1401. ASSERT_TRUE(ret == true);
  1402. ASSERT_TRUE(requests.size() == responses.size());
  1403. for (int i = 0; i < 3; i++) {
  1404. auto &res = responses[i];
  1405. EXPECT_EQ(200, res.status);
  1406. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1407. EXPECT_EQ("Hello World!", res.body);
  1408. }
  1409. {
  1410. auto &res = responses[3];
  1411. EXPECT_EQ(404, res.status);
  1412. }
  1413. {
  1414. auto &res = responses[4];
  1415. EXPECT_EQ(200, res.status);
  1416. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1417. EXPECT_EQ("empty", res.body);
  1418. }
  1419. }
  1420. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1421. TEST_F(ServerTest, Gzip) {
  1422. Headers headers;
  1423. headers.emplace("Accept-Encoding", "gzip, deflate");
  1424. auto res = cli_.Get("/gzip", headers);
  1425. ASSERT_TRUE(res != nullptr);
  1426. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1428. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1430. "7890123456789012345678901234567890",
  1431. res->body);
  1432. EXPECT_EQ(200, res->status);
  1433. }
  1434. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  1435. Headers headers;
  1436. auto res = cli_.Get("/gzip", headers);
  1437. ASSERT_TRUE(res != nullptr);
  1438. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1439. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1440. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1441. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1442. "7890123456789012345678901234567890",
  1443. res->body);
  1444. EXPECT_EQ(200, res->status);
  1445. }
  1446. TEST_F(ServerTest, GzipWithContentReceiver) {
  1447. Headers headers;
  1448. headers.emplace("Accept-Encoding", "gzip, deflate");
  1449. std::string body;
  1450. auto res =
  1451. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1452. EXPECT_EQ(data_length, 100);
  1453. body.append(data, data_length);
  1454. return true;
  1455. });
  1456. ASSERT_TRUE(res != nullptr);
  1457. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1459. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1460. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1461. "7890123456789012345678901234567890",
  1462. body);
  1463. EXPECT_EQ(200, res->status);
  1464. }
  1465. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  1466. Headers headers;
  1467. std::string body;
  1468. auto res =
  1469. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1470. EXPECT_EQ(data_length, 100);
  1471. body.append(data, data_length);
  1472. return true;
  1473. });
  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. body);
  1481. EXPECT_EQ(200, res->status);
  1482. }
  1483. TEST_F(ServerTest, NoGzip) {
  1484. Headers headers;
  1485. headers.emplace("Accept-Encoding", "gzip, deflate");
  1486. auto res = cli_.Get("/nogzip", headers);
  1487. ASSERT_TRUE(res != nullptr);
  1488. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1490. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1491. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1492. "7890123456789012345678901234567890",
  1493. res->body);
  1494. EXPECT_EQ(200, res->status);
  1495. }
  1496. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  1497. Headers headers;
  1498. headers.emplace("Accept-Encoding", "gzip, deflate");
  1499. std::string body;
  1500. auto res =
  1501. cli_.Get("/nogzip", headers, [&](const char *data, uint64_t data_length) {
  1502. EXPECT_EQ(data_length, 100);
  1503. body.append(data, data_length);
  1504. return true;
  1505. });
  1506. ASSERT_TRUE(res != nullptr);
  1507. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1508. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1509. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1510. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1511. "7890123456789012345678901234567890",
  1512. body);
  1513. EXPECT_EQ(200, res->status);
  1514. }
  1515. TEST_F(ServerTest, MultipartFormDataGzip) {
  1516. MultipartFormDataItems items = {
  1517. {"key1", "test", "", ""},
  1518. {"key2", "--abcdefg123", "", ""},
  1519. };
  1520. auto res = cli_.Post("/gzipmultipart", items, true);
  1521. ASSERT_TRUE(res != nullptr);
  1522. EXPECT_EQ(200, res->status);
  1523. }
  1524. #endif
  1525. // Sends a raw request to a server listening at HOST:PORT.
  1526. static bool send_request(time_t read_timeout_sec, const std::string& req) {
  1527. auto client_sock =
  1528. detail::create_client_socket(HOST, PORT, /*timeout_sec=*/5);
  1529. if (client_sock == INVALID_SOCKET) { return false; }
  1530. return detail::process_and_close_socket(
  1531. true, client_sock, 1, read_timeout_sec, 0,
  1532. [&](Stream& strm, bool /*last_connection*/,
  1533. bool &/*connection_close*/) -> bool {
  1534. if (req.size() !=
  1535. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  1536. return false;
  1537. }
  1538. char buf[512];
  1539. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  1540. while (line_reader.getline()) {}
  1541. return true;
  1542. });
  1543. }
  1544. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  1545. Server svr;
  1546. std::string header_value;
  1547. svr.Get("/validate-ws-in-headers",
  1548. [&](const Request &req, Response &res) {
  1549. header_value = req.get_header_value("foo");
  1550. res.set_content("ok", "text/plain");
  1551. });
  1552. thread t = thread([&] { svr.listen(HOST, PORT); });
  1553. while (!svr.is_running()) {
  1554. msleep(1);
  1555. }
  1556. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  1557. // like characters are not treated the same - use vertical tab and escape.
  1558. const std::string req =
  1559. "GET /validate-ws-in-headers HTTP/1.1\r\n"
  1560. "foo: \t \v bar \e\t \r\n"
  1561. "Connection: close\r\n"
  1562. "\r\n";
  1563. ASSERT_TRUE(send_request(5, req));
  1564. svr.stop();
  1565. t.join();
  1566. EXPECT_EQ(header_value, "\v bar \e");
  1567. }
  1568. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  1569. Server svr;
  1570. svr.Get("/hi",
  1571. [&](const Request & /*req*/, Response &res) {
  1572. res.set_content("ok", "text/plain");
  1573. });
  1574. // Server read timeout must be longer than the client read timeout for the
  1575. // bug to reproduce, probably to force the server to process a request
  1576. // without a trailing blank line.
  1577. const time_t client_read_timeout_sec = 1;
  1578. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  1579. bool listen_thread_ok = false;
  1580. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  1581. while (!svr.is_running()) {
  1582. msleep(1);
  1583. }
  1584. // A certain header line causes an exception if the header property is parsed
  1585. // naively with a single regex. This occurs with libc++ but not libstdc++.
  1586. const std::string req =
  1587. "GET /hi HTTP/1.1\r\n"
  1588. " : "
  1589. " ";
  1590. ASSERT_TRUE(send_request(client_read_timeout_sec, req));
  1591. svr.stop();
  1592. t.join();
  1593. EXPECT_TRUE(listen_thread_ok);
  1594. }
  1595. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  1596. protected:
  1597. ServerTestWithAI_PASSIVE()
  1598. : cli_(HOST, PORT)
  1599. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1600. ,
  1601. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1602. #endif
  1603. {
  1604. }
  1605. virtual void SetUp() {
  1606. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1607. res.set_content("Hello World!", "text/plain");
  1608. });
  1609. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  1610. while (!svr_.is_running()) {
  1611. msleep(1);
  1612. }
  1613. }
  1614. virtual void TearDown() {
  1615. svr_.stop();
  1616. t_.join();
  1617. }
  1618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1619. SSLClient cli_;
  1620. SSLServer svr_;
  1621. #else
  1622. Client cli_;
  1623. Server svr_;
  1624. #endif
  1625. thread t_;
  1626. };
  1627. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  1628. auto res = cli_.Get("/hi");
  1629. ASSERT_TRUE(res != nullptr);
  1630. EXPECT_EQ(200, res->status);
  1631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1632. EXPECT_EQ("Hello World!", res->body);
  1633. }
  1634. class ServerUpDownTest : public ::testing::Test {
  1635. protected:
  1636. ServerUpDownTest() : cli_(HOST, PORT) {}
  1637. virtual void SetUp() {
  1638. t_ = thread([&]() {
  1639. svr_.bind_to_any_port(HOST);
  1640. msleep(500);
  1641. ASSERT_TRUE(svr_.listen_after_bind());
  1642. });
  1643. while (!svr_.is_running()) {
  1644. msleep(1);
  1645. }
  1646. }
  1647. virtual void TearDown() {
  1648. svr_.stop();
  1649. t_.join();
  1650. }
  1651. Client cli_;
  1652. Server svr_;
  1653. thread t_;
  1654. };
  1655. TEST_F(ServerUpDownTest, QuickStartStop) {
  1656. // Should not crash, especially when run with
  1657. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  1658. }
  1659. class PayloadMaxLengthTest : public ::testing::Test {
  1660. protected:
  1661. PayloadMaxLengthTest()
  1662. : cli_(HOST, PORT)
  1663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1664. ,
  1665. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1666. #endif
  1667. {
  1668. }
  1669. virtual void SetUp() {
  1670. svr_.set_payload_max_length(8);
  1671. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  1672. res.set_content("test", "text/plain");
  1673. });
  1674. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1675. while (!svr_.is_running()) {
  1676. msleep(1);
  1677. }
  1678. }
  1679. virtual void TearDown() {
  1680. svr_.stop();
  1681. t_.join();
  1682. }
  1683. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1684. SSLClient cli_;
  1685. SSLServer svr_;
  1686. #else
  1687. Client cli_;
  1688. Server svr_;
  1689. #endif
  1690. thread t_;
  1691. };
  1692. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  1693. auto res = cli_.Post("/test", "123456789", "text/plain");
  1694. ASSERT_TRUE(res != nullptr);
  1695. EXPECT_EQ(413, res->status);
  1696. res = cli_.Post("/test", "12345678", "text/plain");
  1697. ASSERT_TRUE(res != nullptr);
  1698. EXPECT_EQ(200, res->status);
  1699. }
  1700. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1701. TEST(SSLClientTest, ServerNameIndication) {
  1702. SSLClient cli("httpbin.org", 443);
  1703. auto res = cli.Get("/get");
  1704. ASSERT_TRUE(res != nullptr);
  1705. ASSERT_EQ(200, res->status);
  1706. }
  1707. TEST(SSLClientTest, ServerCertificateVerification) {
  1708. SSLClient cli("google.com");
  1709. auto res = cli.Get("/");
  1710. ASSERT_TRUE(res != nullptr);
  1711. ASSERT_EQ(301, res->status);
  1712. cli.enable_server_certificate_verification(true);
  1713. res = cli.Get("/");
  1714. ASSERT_TRUE(res == nullptr);
  1715. cli.set_ca_cert_path(CA_CERT_FILE);
  1716. res = cli.Get("/");
  1717. ASSERT_TRUE(res != nullptr);
  1718. ASSERT_EQ(301, res->status);
  1719. }
  1720. TEST(SSLClientTest, WildcardHostNameMatch) {
  1721. SSLClient cli("www.youtube.com");
  1722. cli.set_ca_cert_path(CA_CERT_FILE);
  1723. cli.enable_server_certificate_verification(true);
  1724. auto res = cli.Get("/");
  1725. ASSERT_TRUE(res != nullptr);
  1726. ASSERT_EQ(200, res->status);
  1727. }
  1728. TEST(SSLClientServerTest, ClientCertPresent) {
  1729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1730. CLIENT_CA_CERT_DIR);
  1731. ASSERT_TRUE(svr.is_valid());
  1732. svr.Get("/test", [&](const Request &req, Response &res) {
  1733. res.set_content("test", "text/plain");
  1734. svr.stop();
  1735. ASSERT_TRUE(true);
  1736. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  1737. ASSERT_TRUE(peer_cert != nullptr);
  1738. auto subject_name = X509_get_subject_name(peer_cert);
  1739. ASSERT_TRUE(subject_name != nullptr);
  1740. std::string common_name;
  1741. {
  1742. char name[BUFSIZ];
  1743. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  1744. name, sizeof(name));
  1745. common_name.assign(name, name_len);
  1746. }
  1747. EXPECT_EQ("Common Name", common_name);
  1748. X509_free(peer_cert);
  1749. });
  1750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1751. msleep(1);
  1752. httplib::SSLClient cli(HOST, PORT, 30, CLIENT_CERT_FILE,
  1753. CLIENT_PRIVATE_KEY_FILE);
  1754. auto res = cli.Get("/test");
  1755. ASSERT_TRUE(res != nullptr);
  1756. ASSERT_EQ(200, res->status);
  1757. t.join();
  1758. }
  1759. TEST(SSLClientServerTest, ClientCertMissing) {
  1760. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1761. CLIENT_CA_CERT_DIR);
  1762. ASSERT_TRUE(svr.is_valid());
  1763. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  1764. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1765. msleep(1);
  1766. httplib::SSLClient cli(HOST, PORT, 30);
  1767. auto res = cli.Get("/test");
  1768. ASSERT_TRUE(res == nullptr);
  1769. svr.stop();
  1770. t.join();
  1771. }
  1772. TEST(SSLClientServerTest, TrustDirOptional) {
  1773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1774. ASSERT_TRUE(svr.is_valid());
  1775. svr.Get("/test", [&](const Request &, Response &res) {
  1776. res.set_content("test", "text/plain");
  1777. svr.stop();
  1778. });
  1779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1780. msleep(1);
  1781. httplib::SSLClient cli(HOST, PORT, 30, CLIENT_CERT_FILE,
  1782. CLIENT_PRIVATE_KEY_FILE);
  1783. auto res = cli.Get("/test");
  1784. ASSERT_TRUE(res != nullptr);
  1785. ASSERT_EQ(200, res->status);
  1786. t.join();
  1787. }
  1788. /* Cannot test this case as there is no external access to SSL object to check
  1789. SSL_get_peer_certificate() == NULL TEST(SSLClientServerTest,
  1790. ClientCAPathRequired) { SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  1791. nullptr, CLIENT_CA_CERT_DIR);
  1792. }
  1793. */
  1794. #endif
  1795. #ifdef _WIN32
  1796. TEST(CleanupTest, WSACleanup) {
  1797. int ret = WSACleanup();
  1798. ASSERT_EQ(0, ret);
  1799. }
  1800. #endif