test.cc 68 KB

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