test.cc 69 KB

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