test.cc 68 KB

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