test.cc 71 KB

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