test.cc 75 KB

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