test.cc 64 KB

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