test.cc 70 KB

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