test.cc 61 KB

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