test.cc 66 KB

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