test.cc 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  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("0.0.0.0");
  540. ASSERT_TRUE(svr.is_valid());
  541. ASSERT_TRUE(port > 0);
  542. svr.stop();
  543. }
  544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  545. TEST(SSLServer, BindAndListenSeparately) {
  546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE, CLIENT_CA_CERT_DIR);
  547. int port = svr.bind_to_any_port("0.0.0.0");
  548. ASSERT_TRUE(svr.is_valid());
  549. ASSERT_TRUE(port > 0);
  550. svr.stop();
  551. }
  552. #endif
  553. class ServerTest : public ::testing::Test {
  554. protected:
  555. ServerTest()
  556. : cli_(HOST, PORT)
  557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  558. ,
  559. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  560. #endif
  561. {
  562. }
  563. virtual void SetUp() {
  564. svr_.set_mount_point("/", "./www");
  565. svr_.set_mount_point("/mount", "./www2");
  566. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  567. svr_.Get("/hi",
  568. [&](const Request & /*req*/, Response &res) {
  569. res.set_content("Hello World!", "text/plain");
  570. })
  571. .Get("/slow",
  572. [&](const Request & /*req*/, Response &res) {
  573. std::this_thread::sleep_for(std::chrono::seconds(2));
  574. res.set_content("slow", "text/plain");
  575. })
  576. .Get("/remote_addr",
  577. [&](const Request &req, Response &res) {
  578. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  579. res.set_content(remote_addr.c_str(), "text/plain");
  580. })
  581. .Get("/endwith%",
  582. [&](const Request & /*req*/, Response &res) {
  583. res.set_content("Hello World!", "text/plain");
  584. })
  585. .Get("/", [&](const Request & /*req*/,
  586. Response &res) { res.set_redirect("/hi"); })
  587. .Post("/person",
  588. [&](const Request &req, Response &res) {
  589. if (req.has_param("name") && req.has_param("note")) {
  590. persons_[req.get_param_value("name")] =
  591. req.get_param_value("note");
  592. } else {
  593. res.status = 400;
  594. }
  595. })
  596. .Put("/person",
  597. [&](const Request &req, Response &res) {
  598. if (req.has_param("name") && req.has_param("note")) {
  599. persons_[req.get_param_value("name")] =
  600. req.get_param_value("note");
  601. } else {
  602. res.status = 400;
  603. }
  604. })
  605. .Get("/person/(.*)",
  606. [&](const Request &req, Response &res) {
  607. string name = req.matches[1];
  608. if (persons_.find(name) != persons_.end()) {
  609. auto note = persons_[name];
  610. res.set_content(note, "text/plain");
  611. } else {
  612. res.status = 404;
  613. }
  614. })
  615. .Post("/x-www-form-urlencoded-json",
  616. [&](const Request &req, Response &res) {
  617. auto json = req.get_param_value("json");
  618. ASSERT_EQ(JSON_DATA, json);
  619. res.set_content(json, "appliation/json");
  620. res.status = 200;
  621. })
  622. .Get("/streamed-chunked",
  623. [&](const Request & /*req*/, Response &res) {
  624. res.set_chunked_content_provider(
  625. [](uint64_t /*offset*/, DataSink &sink) {
  626. ASSERT_TRUE(sink.is_writable());
  627. sink.write("123", 3);
  628. sink.write("456", 3);
  629. sink.write("789", 3);
  630. sink.done();
  631. });
  632. })
  633. .Get("/streamed-chunked2",
  634. [&](const Request & /*req*/, Response &res) {
  635. auto i = new int(0);
  636. res.set_chunked_content_provider(
  637. [i](uint64_t /*offset*/, DataSink &sink) {
  638. ASSERT_TRUE(sink.is_writable());
  639. switch (*i) {
  640. case 0: sink.write("123", 3); break;
  641. case 1: sink.write("456", 3); break;
  642. case 2: sink.write("789", 3); break;
  643. case 3: sink.done(); break;
  644. }
  645. (*i)++;
  646. },
  647. [i] { delete i; });
  648. })
  649. .Get("/streamed",
  650. [&](const Request & /*req*/, Response &res) {
  651. res.set_content_provider(
  652. 6, [](uint64_t offset, uint64_t /*length*/, DataSink &sink) {
  653. sink.write(offset < 3 ? "a" : "b", 1);
  654. });
  655. })
  656. .Get("/streamed-with-range",
  657. [&](const Request & /*req*/, Response &res) {
  658. auto data = new std::string("abcdefg");
  659. res.set_content_provider(
  660. data->size(),
  661. [data](uint64_t offset, uint64_t length, DataSink &sink) {
  662. ASSERT_TRUE(sink.is_writable());
  663. size_t DATA_CHUNK_SIZE = 4;
  664. const auto &d = *data;
  665. auto out_len =
  666. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  667. sink.write(&d[static_cast<size_t>(offset)], out_len);
  668. },
  669. [data] { delete data; });
  670. })
  671. .Get("/streamed-cancel",
  672. [&](const Request & /*req*/, Response &res) {
  673. res.set_content_provider(size_t(-1), [](uint64_t /*offset*/,
  674. uint64_t /*length*/,
  675. DataSink &sink) {
  676. ASSERT_TRUE(sink.is_writable());
  677. std::string data = "data_chunk";
  678. sink.write(data.data(), data.size());
  679. });
  680. })
  681. .Get("/with-range",
  682. [&](const Request & /*req*/, Response &res) {
  683. res.set_content("abcdefg", "text/plain");
  684. })
  685. .Post("/chunked",
  686. [&](const Request &req, Response & /*res*/) {
  687. EXPECT_EQ(req.body, "dechunked post body");
  688. })
  689. .Post("/large-chunked",
  690. [&](const Request &req, Response & /*res*/) {
  691. std::string expected(6 * 30 * 1024u, 'a');
  692. EXPECT_EQ(req.body, expected);
  693. })
  694. .Post("/multipart",
  695. [&](const Request &req, Response & /*res*/) {
  696. EXPECT_EQ(5u, req.files.size());
  697. ASSERT_TRUE(!req.has_file("???"));
  698. {
  699. const auto &file = req.get_file_value("text1");
  700. EXPECT_EQ("", file.filename);
  701. EXPECT_EQ("text default", file.content);
  702. }
  703. {
  704. const auto &file = req.get_file_value("text2");
  705. EXPECT_EQ("", file.filename);
  706. EXPECT_EQ("aωb", file.content);
  707. }
  708. {
  709. const auto &file = req.get_file_value("file1");
  710. EXPECT_EQ("hello.txt", file.filename);
  711. EXPECT_EQ("text/plain", file.content_type);
  712. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  713. }
  714. {
  715. const auto &file = req.get_file_value("file3");
  716. EXPECT_EQ("", file.filename);
  717. EXPECT_EQ("application/octet-stream", file.content_type);
  718. EXPECT_EQ(0u, file.content.size());
  719. }
  720. })
  721. .Post("/empty",
  722. [&](const Request &req, Response &res) {
  723. EXPECT_EQ(req.body, "");
  724. res.set_content("empty", "text/plain");
  725. })
  726. .Put("/put",
  727. [&](const Request &req, Response &res) {
  728. EXPECT_EQ(req.body, "PUT");
  729. res.set_content(req.body, "text/plain");
  730. })
  731. .Put("/put-large",
  732. [&](const Request &req, Response &res) {
  733. EXPECT_EQ(req.body, LARGE_DATA);
  734. res.set_content(req.body, "text/plain");
  735. })
  736. .Patch("/patch",
  737. [&](const Request &req, Response &res) {
  738. EXPECT_EQ(req.body, "PATCH");
  739. res.set_content(req.body, "text/plain");
  740. })
  741. .Delete("/delete",
  742. [&](const Request & /*req*/, Response &res) {
  743. res.set_content("DELETE", "text/plain");
  744. })
  745. .Options(R"(\*)",
  746. [&](const Request & /*req*/, Response &res) {
  747. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  748. })
  749. .Get("/request-target",
  750. [&](const Request &req, Response & /*res*/) {
  751. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  752. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  753. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  754. })
  755. .Get("/long-query-value",
  756. [&](const Request &req, Response & /*res*/) {
  757. EXPECT_EQ(LONG_QUERY_URL, req.target);
  758. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  759. })
  760. .Get("/array-param",
  761. [&](const Request &req, Response & /*res*/) {
  762. EXPECT_EQ(3u, req.get_param_value_count("array"));
  763. EXPECT_EQ("value1", req.get_param_value("array", 0));
  764. EXPECT_EQ("value2", req.get_param_value("array", 1));
  765. EXPECT_EQ("value3", req.get_param_value("array", 2));
  766. })
  767. .Post("/validate-no-multiple-headers",
  768. [&](const Request &req, Response & /*res*/) {
  769. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  770. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  771. })
  772. .Post("/content_receiver",
  773. [&](const Request &req, Response &res,
  774. const ContentReader &content_reader) {
  775. if (req.is_multipart_form_data()) {
  776. MultipartFormDataItems files;
  777. content_reader(
  778. [&](const MultipartFormData &file) {
  779. files.push_back(file);
  780. return true;
  781. },
  782. [&](const char *data, size_t data_length) {
  783. files.back().content.append(data, data_length);
  784. return true;
  785. });
  786. EXPECT_EQ(5u, files.size());
  787. {
  788. const auto &file = get_file_value(files, "text1");
  789. EXPECT_EQ("", file.filename);
  790. EXPECT_EQ("text default", file.content);
  791. }
  792. {
  793. const auto &file = get_file_value(files, "text2");
  794. EXPECT_EQ("", file.filename);
  795. EXPECT_EQ("aωb", file.content);
  796. }
  797. {
  798. const auto &file = get_file_value(files, "file1");
  799. EXPECT_EQ("hello.txt", file.filename);
  800. EXPECT_EQ("text/plain", file.content_type);
  801. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  802. }
  803. {
  804. const auto &file = get_file_value(files, "file3");
  805. EXPECT_EQ("", file.filename);
  806. EXPECT_EQ("application/octet-stream", file.content_type);
  807. EXPECT_EQ(0u, file.content.size());
  808. }
  809. } else {
  810. std::string body;
  811. content_reader([&](const char *data, size_t data_length) {
  812. EXPECT_EQ(data_length, 7);
  813. body.append(data, data_length);
  814. return true;
  815. });
  816. EXPECT_EQ(body, "content");
  817. res.set_content(body, "text/plain");
  818. }
  819. })
  820. .Put("/content_receiver",
  821. [&](const Request & /*req*/, Response &res,
  822. const ContentReader &content_reader) {
  823. std::string body;
  824. content_reader([&](const char *data, size_t data_length) {
  825. body.append(data, data_length);
  826. return true;
  827. });
  828. EXPECT_EQ(body, "content");
  829. res.set_content(body, "text/plain");
  830. })
  831. .Patch("/content_receiver",
  832. [&](const Request & /*req*/, Response &res,
  833. const ContentReader &content_reader) {
  834. std::string body;
  835. content_reader([&](const char *data, size_t data_length) {
  836. body.append(data, data_length);
  837. return true;
  838. });
  839. EXPECT_EQ(body, "content");
  840. res.set_content(body, "text/plain");
  841. })
  842. .Post("/query-string-and-body",
  843. [&](const Request &req, Response & /*res*/) {
  844. ASSERT_TRUE(req.has_param("key"));
  845. EXPECT_EQ(req.get_param_value("key"), "value");
  846. EXPECT_EQ(req.body, "content");
  847. })
  848. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  849. .Get("/gzip",
  850. [&](const Request & /*req*/, Response &res) {
  851. res.set_content(
  852. "12345678901234567890123456789012345678901234567890123456789"
  853. "01234567890123456789012345678901234567890",
  854. "text/plain");
  855. })
  856. .Get("/nogzip",
  857. [&](const Request & /*req*/, Response &res) {
  858. res.set_content(
  859. "12345678901234567890123456789012345678901234567890123456789"
  860. "01234567890123456789012345678901234567890",
  861. "application/octet-stream");
  862. })
  863. .Post("/gzipmultipart",
  864. [&](const Request &req, Response & /*res*/) {
  865. EXPECT_EQ(2u, req.files.size());
  866. ASSERT_TRUE(!req.has_file("???"));
  867. {
  868. const auto &file = req.get_file_value("key1");
  869. EXPECT_EQ("", file.filename);
  870. EXPECT_EQ("test", file.content);
  871. }
  872. {
  873. const auto &file = req.get_file_value("key2");
  874. EXPECT_EQ("", file.filename);
  875. EXPECT_EQ("--abcdefg123", file.content);
  876. }
  877. })
  878. #endif
  879. ;
  880. persons_["john"] = "programmer";
  881. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  882. while (!svr_.is_running()) {
  883. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  884. }
  885. }
  886. virtual void TearDown() {
  887. svr_.stop();
  888. for (auto &t : request_threads_) {
  889. t.join();
  890. }
  891. t_.join();
  892. }
  893. map<string, string> persons_;
  894. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  895. SSLClient cli_;
  896. SSLServer svr_;
  897. #else
  898. Client cli_;
  899. Server svr_;
  900. #endif
  901. thread t_;
  902. std::vector<thread> request_threads_;
  903. };
  904. TEST_F(ServerTest, GetMethod200) {
  905. auto res = cli_.Get("/hi");
  906. ASSERT_TRUE(res != nullptr);
  907. EXPECT_EQ("HTTP/1.1", res->version);
  908. EXPECT_EQ(200, res->status);
  909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  910. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  911. EXPECT_EQ("Hello World!", res->body);
  912. }
  913. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  914. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  915. ASSERT_TRUE(res != nullptr);
  916. EXPECT_EQ("HTTP/1.1", res->version);
  917. EXPECT_EQ(200, res->status);
  918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  919. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  920. EXPECT_EQ("Hello World!", res->body);
  921. }
  922. TEST_F(ServerTest, GetMethod302) {
  923. auto res = cli_.Get("/");
  924. ASSERT_TRUE(res != nullptr);
  925. EXPECT_EQ(302, res->status);
  926. EXPECT_EQ("/hi", res->get_header_value("Location"));
  927. }
  928. TEST_F(ServerTest, GetMethod404) {
  929. auto res = cli_.Get("/invalid");
  930. ASSERT_TRUE(res != nullptr);
  931. EXPECT_EQ(404, res->status);
  932. }
  933. TEST_F(ServerTest, HeadMethod200) {
  934. auto res = cli_.Head("/hi");
  935. ASSERT_TRUE(res != nullptr);
  936. EXPECT_EQ(200, res->status);
  937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  938. EXPECT_EQ("", res->body);
  939. }
  940. TEST_F(ServerTest, HeadMethod200Static) {
  941. auto res = cli_.Head("/mount/dir/index.html");
  942. ASSERT_TRUE(res != nullptr);
  943. EXPECT_EQ(200, res->status);
  944. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  945. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  946. EXPECT_EQ("", res->body);
  947. }
  948. TEST_F(ServerTest, HeadMethod404) {
  949. auto res = cli_.Head("/invalid");
  950. ASSERT_TRUE(res != nullptr);
  951. EXPECT_EQ(404, res->status);
  952. EXPECT_EQ("", res->body);
  953. }
  954. TEST_F(ServerTest, GetMethodPersonJohn) {
  955. auto res = cli_.Get("/person/john");
  956. ASSERT_TRUE(res != nullptr);
  957. EXPECT_EQ(200, res->status);
  958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  959. EXPECT_EQ("programmer", res->body);
  960. }
  961. TEST_F(ServerTest, PostMethod1) {
  962. auto res = cli_.Get("/person/john1");
  963. ASSERT_TRUE(res != nullptr);
  964. ASSERT_EQ(404, res->status);
  965. res = cli_.Post("/person", "name=john1&note=coder",
  966. "application/x-www-form-urlencoded");
  967. ASSERT_TRUE(res != nullptr);
  968. ASSERT_EQ(200, res->status);
  969. res = cli_.Get("/person/john1");
  970. ASSERT_TRUE(res != nullptr);
  971. ASSERT_EQ(200, res->status);
  972. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  973. ASSERT_EQ("coder", res->body);
  974. }
  975. TEST_F(ServerTest, PostMethod2) {
  976. auto res = cli_.Get("/person/john2");
  977. ASSERT_TRUE(res != nullptr);
  978. ASSERT_EQ(404, res->status);
  979. Params params;
  980. params.emplace("name", "john2");
  981. params.emplace("note", "coder");
  982. res = cli_.Post("/person", params);
  983. ASSERT_TRUE(res != nullptr);
  984. ASSERT_EQ(200, res->status);
  985. res = cli_.Get("/person/john2");
  986. ASSERT_TRUE(res != nullptr);
  987. ASSERT_EQ(200, res->status);
  988. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  989. ASSERT_EQ("coder", res->body);
  990. }
  991. TEST_F(ServerTest, PutMethod3) {
  992. auto res = cli_.Get("/person/john3");
  993. ASSERT_TRUE(res != nullptr);
  994. ASSERT_EQ(404, res->status);
  995. Params params;
  996. params.emplace("name", "john3");
  997. params.emplace("note", "coder");
  998. res = cli_.Put("/person", params);
  999. ASSERT_TRUE(res != nullptr);
  1000. ASSERT_EQ(200, res->status);
  1001. res = cli_.Get("/person/john3");
  1002. ASSERT_TRUE(res != nullptr);
  1003. ASSERT_EQ(200, res->status);
  1004. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1005. ASSERT_EQ("coder", res->body);
  1006. }
  1007. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1008. Params params;
  1009. params.emplace("json", JSON_DATA);
  1010. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1011. ASSERT_TRUE(res != nullptr);
  1012. ASSERT_EQ(200, res->status);
  1013. ASSERT_EQ(JSON_DATA, res->body);
  1014. }
  1015. TEST_F(ServerTest, PostEmptyContent) {
  1016. auto res = cli_.Post("/empty", "", "text/plain");
  1017. ASSERT_TRUE(res != nullptr);
  1018. ASSERT_EQ(200, res->status);
  1019. ASSERT_EQ("empty", res->body);
  1020. }
  1021. TEST_F(ServerTest, GetMethodDir) {
  1022. auto res = cli_.Get("/dir/");
  1023. ASSERT_TRUE(res != nullptr);
  1024. EXPECT_EQ(200, res->status);
  1025. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1026. auto body = R"(<html>
  1027. <head>
  1028. </head>
  1029. <body>
  1030. <a href="/dir/test.html">Test</a>
  1031. <a href="/hi">hi</a>
  1032. </body>
  1033. </html>
  1034. )";
  1035. EXPECT_EQ(body, res->body);
  1036. }
  1037. TEST_F(ServerTest, GetMethodDirTest) {
  1038. auto res = cli_.Get("/dir/test.html");
  1039. ASSERT_TRUE(res != nullptr);
  1040. EXPECT_EQ(200, res->status);
  1041. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1042. EXPECT_EQ("test.html", res->body);
  1043. }
  1044. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1045. auto res = cli_.Get("/dir/../dir/test.html");
  1046. ASSERT_TRUE(res != nullptr);
  1047. EXPECT_EQ(200, res->status);
  1048. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1049. EXPECT_EQ("test.html", res->body);
  1050. }
  1051. TEST_F(ServerTest, GetMethodInvalidPath) {
  1052. auto res = cli_.Get("/dir/../test.html");
  1053. ASSERT_TRUE(res != nullptr);
  1054. EXPECT_EQ(404, res->status);
  1055. }
  1056. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1057. auto res = cli_.Get("/../www/dir/test.html");
  1058. ASSERT_TRUE(res != nullptr);
  1059. EXPECT_EQ(404, res->status);
  1060. }
  1061. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1062. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1063. ASSERT_TRUE(res != nullptr);
  1064. EXPECT_EQ(404, res->status);
  1065. }
  1066. TEST_F(ServerTest, GetMethodDirMountTest) {
  1067. auto res = cli_.Get("/mount/dir/test.html");
  1068. ASSERT_TRUE(res != nullptr);
  1069. EXPECT_EQ(200, res->status);
  1070. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1071. EXPECT_EQ("test.html", res->body);
  1072. }
  1073. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1074. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1075. ASSERT_TRUE(res != nullptr);
  1076. EXPECT_EQ(200, res->status);
  1077. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1078. EXPECT_EQ("test.html", res->body);
  1079. }
  1080. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1081. auto res = cli_.Get("/mount/dir/../test.html");
  1082. ASSERT_TRUE(res != nullptr);
  1083. EXPECT_EQ(404, res->status);
  1084. }
  1085. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1086. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1087. ASSERT_TRUE(res != nullptr);
  1088. EXPECT_EQ(404, res->status);
  1089. }
  1090. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1091. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1092. ASSERT_TRUE(res != nullptr);
  1093. EXPECT_EQ(404, res->status);
  1094. }
  1095. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1096. auto res = cli_.Get("/dir/test.abcde");
  1097. ASSERT_TRUE(res != nullptr);
  1098. EXPECT_EQ(200, res->status);
  1099. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1100. EXPECT_EQ("abcde", res->body);
  1101. }
  1102. TEST_F(ServerTest, InvalidBaseDirMount) {
  1103. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1104. }
  1105. TEST_F(ServerTest, EmptyRequest) {
  1106. auto res = cli_.Get("");
  1107. ASSERT_TRUE(res == nullptr);
  1108. }
  1109. TEST_F(ServerTest, LongRequest) {
  1110. std::string request;
  1111. for (size_t i = 0; i < 545; i++) {
  1112. request += "/TooLongRequest";
  1113. }
  1114. request += "OK";
  1115. auto res = cli_.Get(request.c_str());
  1116. ASSERT_TRUE(res != nullptr);
  1117. EXPECT_EQ(404, res->status);
  1118. }
  1119. TEST_F(ServerTest, TooLongRequest) {
  1120. std::string request;
  1121. for (size_t i = 0; i < 545; i++) {
  1122. request += "/TooLongRequest";
  1123. }
  1124. request += "_NG";
  1125. auto res = cli_.Get(request.c_str());
  1126. ASSERT_TRUE(res != nullptr);
  1127. EXPECT_EQ(414, res->status);
  1128. }
  1129. TEST_F(ServerTest, LongHeader) {
  1130. Request req;
  1131. req.method = "GET";
  1132. req.path = "/hi";
  1133. std::string host_and_port;
  1134. host_and_port += HOST;
  1135. host_and_port += ":";
  1136. host_and_port += std::to_string(PORT);
  1137. req.headers.emplace("Host", host_and_port.c_str());
  1138. req.headers.emplace("Accept", "*/*");
  1139. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1140. req.headers.emplace(
  1141. "Header-Name",
  1142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1170. "@@@@@@@@@@@@@@@@");
  1171. auto res = std::make_shared<Response>();
  1172. auto ret = cli_.send(req, *res);
  1173. ASSERT_TRUE(ret);
  1174. EXPECT_EQ(200, res->status);
  1175. }
  1176. TEST_F(ServerTest, LongQueryValue) {
  1177. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1178. ASSERT_TRUE(res != nullptr);
  1179. EXPECT_EQ(414, res->status);
  1180. }
  1181. TEST_F(ServerTest, TooLongHeader) {
  1182. Request req;
  1183. req.method = "GET";
  1184. req.path = "/hi";
  1185. std::string host_and_port;
  1186. host_and_port += HOST;
  1187. host_and_port += ":";
  1188. host_and_port += std::to_string(PORT);
  1189. req.headers.emplace("Host", host_and_port.c_str());
  1190. req.headers.emplace("Accept", "*/*");
  1191. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1192. req.headers.emplace(
  1193. "Header-Name",
  1194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1222. "@@@@@@@@@@@@@@@@@");
  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, PercentEncoding) {
  1229. auto res = cli_.Get("/e%6edwith%");
  1230. ASSERT_TRUE(res != nullptr);
  1231. EXPECT_EQ(200, res->status);
  1232. }
  1233. TEST_F(ServerTest, PercentEncodingUnicode) {
  1234. auto res = cli_.Get("/e%u006edwith%");
  1235. ASSERT_TRUE(res != nullptr);
  1236. EXPECT_EQ(200, res->status);
  1237. }
  1238. TEST_F(ServerTest, InvalidPercentEncoding) {
  1239. auto res = cli_.Get("/%endwith%");
  1240. ASSERT_TRUE(res != nullptr);
  1241. EXPECT_EQ(404, res->status);
  1242. }
  1243. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1244. auto res = cli_.Get("/%uendwith%");
  1245. ASSERT_TRUE(res != nullptr);
  1246. EXPECT_EQ(404, res->status);
  1247. }
  1248. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1249. auto res = cli_.Get("/hello?aaa=bbb%");
  1250. ASSERT_TRUE(res != nullptr);
  1251. EXPECT_EQ(404, res->status);
  1252. }
  1253. TEST_F(ServerTest, MultipartFormData) {
  1254. MultipartFormDataItems items = {
  1255. {"text1", "text default", "", ""},
  1256. {"text2", "aωb", "", ""},
  1257. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1258. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1259. {"file3", "", "", "application/octet-stream"},
  1260. };
  1261. auto res = cli_.Post("/multipart", items);
  1262. ASSERT_TRUE(res != nullptr);
  1263. EXPECT_EQ(200, res->status);
  1264. }
  1265. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1266. auto res = cli_.Get("/hi");
  1267. ASSERT_TRUE(res != nullptr);
  1268. EXPECT_EQ(200, res->status);
  1269. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1270. EXPECT_EQ("Hello World!", res->body);
  1271. }
  1272. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1273. Request req;
  1274. req.method = "POST";
  1275. req.path = "/chunked";
  1276. std::string host_and_port;
  1277. host_and_port += HOST;
  1278. host_and_port += ":";
  1279. host_and_port += std::to_string(PORT);
  1280. req.headers.emplace("Host", host_and_port.c_str());
  1281. req.headers.emplace("Accept", "*/*");
  1282. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1283. req.headers.emplace("Content-Type", "text/plain");
  1284. req.headers.emplace("Content-Length", "0");
  1285. req.headers.emplace(
  1286. "Transfer-Encoding",
  1287. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1288. // Client does not chunk, so make a chunked body manually.
  1289. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1290. auto res = std::make_shared<Response>();
  1291. auto ret = cli_.send(req, *res);
  1292. ASSERT_TRUE(ret);
  1293. EXPECT_EQ(200, res->status);
  1294. }
  1295. TEST_F(ServerTest, GetStreamed2) {
  1296. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1297. ASSERT_TRUE(res != nullptr);
  1298. EXPECT_EQ(206, res->status);
  1299. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1300. EXPECT_EQ(std::string("ab"), res->body);
  1301. }
  1302. TEST_F(ServerTest, GetStreamed) {
  1303. auto res = cli_.Get("/streamed");
  1304. ASSERT_TRUE(res != nullptr);
  1305. EXPECT_EQ(200, res->status);
  1306. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1307. EXPECT_EQ(std::string("aaabbb"), res->body);
  1308. }
  1309. TEST_F(ServerTest, GetStreamedWithRange1) {
  1310. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1311. ASSERT_TRUE(res != nullptr);
  1312. EXPECT_EQ(206, res->status);
  1313. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1314. EXPECT_EQ(true, res->has_header("Content-Range"));
  1315. EXPECT_EQ(std::string("def"), res->body);
  1316. }
  1317. TEST_F(ServerTest, GetStreamedWithRange2) {
  1318. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1319. ASSERT_TRUE(res != nullptr);
  1320. EXPECT_EQ(206, res->status);
  1321. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1322. EXPECT_EQ(true, res->has_header("Content-Range"));
  1323. EXPECT_EQ(std::string("bcdefg"), res->body);
  1324. }
  1325. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1326. auto res =
  1327. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1328. ASSERT_TRUE(res != nullptr);
  1329. EXPECT_EQ(206, res->status);
  1330. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1331. EXPECT_EQ(false, res->has_header("Content-Range"));
  1332. EXPECT_EQ(269, res->body.size());
  1333. }
  1334. TEST_F(ServerTest, GetStreamedEndless) {
  1335. uint64_t offset = 0;
  1336. auto res = cli_.Get("/streamed-cancel",
  1337. [&](const char * /*data*/, uint64_t data_length) {
  1338. if (offset < 100) {
  1339. offset += data_length;
  1340. return true;
  1341. }
  1342. return false;
  1343. });
  1344. ASSERT_TRUE(res == nullptr);
  1345. }
  1346. TEST_F(ServerTest, GetWithRange1) {
  1347. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1348. ASSERT_TRUE(res != nullptr);
  1349. EXPECT_EQ(206, res->status);
  1350. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1351. EXPECT_EQ(true, res->has_header("Content-Range"));
  1352. EXPECT_EQ(std::string("def"), res->body);
  1353. }
  1354. TEST_F(ServerTest, GetWithRange2) {
  1355. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1356. ASSERT_TRUE(res != nullptr);
  1357. EXPECT_EQ(206, res->status);
  1358. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1359. EXPECT_EQ(true, res->has_header("Content-Range"));
  1360. EXPECT_EQ(std::string("bcdefg"), res->body);
  1361. }
  1362. TEST_F(ServerTest, GetWithRange3) {
  1363. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1364. ASSERT_TRUE(res != nullptr);
  1365. EXPECT_EQ(206, res->status);
  1366. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1367. EXPECT_EQ(true, res->has_header("Content-Range"));
  1368. EXPECT_EQ(std::string("a"), res->body);
  1369. }
  1370. TEST_F(ServerTest, GetWithRange4) {
  1371. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1372. ASSERT_TRUE(res != nullptr);
  1373. EXPECT_EQ(206, res->status);
  1374. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1375. EXPECT_EQ(true, res->has_header("Content-Range"));
  1376. EXPECT_EQ(std::string("fg"), res->body);
  1377. }
  1378. TEST_F(ServerTest, GetWithRangeMultipart) {
  1379. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1380. ASSERT_TRUE(res != nullptr);
  1381. EXPECT_EQ(206, res->status);
  1382. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1383. EXPECT_EQ(false, res->has_header("Content-Range"));
  1384. EXPECT_EQ(269, res->body.size());
  1385. }
  1386. TEST_F(ServerTest, GetStreamedChunked) {
  1387. auto res = cli_.Get("/streamed-chunked");
  1388. ASSERT_TRUE(res != nullptr);
  1389. EXPECT_EQ(200, res->status);
  1390. EXPECT_EQ(std::string("123456789"), res->body);
  1391. }
  1392. TEST_F(ServerTest, GetStreamedChunked2) {
  1393. auto res = cli_.Get("/streamed-chunked2");
  1394. ASSERT_TRUE(res != nullptr);
  1395. EXPECT_EQ(200, res->status);
  1396. EXPECT_EQ(std::string("123456789"), res->body);
  1397. }
  1398. TEST_F(ServerTest, LargeChunkedPost) {
  1399. Request req;
  1400. req.method = "POST";
  1401. req.path = "/large-chunked";
  1402. std::string host_and_port;
  1403. host_and_port += HOST;
  1404. host_and_port += ":";
  1405. host_and_port += std::to_string(PORT);
  1406. req.headers.emplace("Host", host_and_port.c_str());
  1407. req.headers.emplace("Accept", "*/*");
  1408. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1409. req.headers.emplace("Content-Type", "text/plain");
  1410. req.headers.emplace("Content-Length", "0");
  1411. req.headers.emplace("Transfer-Encoding", "chunked");
  1412. std::string long_string(30 * 1024u, 'a');
  1413. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1414. // Attempt to make a large enough post to exceed OS buffers, to test that
  1415. // the server handles short reads if the full chunk data isn't available.
  1416. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1417. auto res = std::make_shared<Response>();
  1418. auto ret = cli_.send(req, *res);
  1419. ASSERT_TRUE(ret);
  1420. EXPECT_EQ(200, res->status);
  1421. }
  1422. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1423. auto res = cli_.Get("/remote_addr");
  1424. ASSERT_TRUE(res != nullptr);
  1425. EXPECT_EQ(200, res->status);
  1426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1427. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1428. }
  1429. TEST_F(ServerTest, SlowRequest) {
  1430. request_threads_.push_back(
  1431. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1432. request_threads_.push_back(
  1433. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1434. request_threads_.push_back(
  1435. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1436. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1437. }
  1438. TEST_F(ServerTest, Put) {
  1439. auto res = cli_.Put("/put", "PUT", "text/plain");
  1440. ASSERT_TRUE(res != nullptr);
  1441. EXPECT_EQ(200, res->status);
  1442. EXPECT_EQ("PUT", res->body);
  1443. }
  1444. TEST_F(ServerTest, PutWithContentProvider) {
  1445. auto res = cli_.Put(
  1446. "/put", 3,
  1447. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1448. ASSERT_TRUE(sink.is_writable());
  1449. sink.write("PUT", 3);
  1450. },
  1451. "text/plain");
  1452. ASSERT_TRUE(res != nullptr);
  1453. EXPECT_EQ(200, res->status);
  1454. EXPECT_EQ("PUT", res->body);
  1455. }
  1456. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1457. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1458. cli_.set_compress(true);
  1459. auto res = cli_.Put(
  1460. "/put", 3,
  1461. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1462. ASSERT_TRUE(sink.is_writable());
  1463. sink.write("PUT", 3);
  1464. },
  1465. "text/plain");
  1466. ASSERT_TRUE(res != nullptr);
  1467. EXPECT_EQ(200, res->status);
  1468. EXPECT_EQ("PUT", res->body);
  1469. }
  1470. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1471. cli_.set_compress(true);
  1472. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  1473. ASSERT_TRUE(res != nullptr);
  1474. EXPECT_EQ(200, res->status);
  1475. EXPECT_EQ(LARGE_DATA, res->body);
  1476. }
  1477. TEST_F(ServerTest, PutContentWithDeflate) {
  1478. cli_.set_compress(false);
  1479. httplib::Headers headers;
  1480. headers.emplace("Content-Encoding", "deflate");
  1481. // PUT in deflate format:
  1482. auto res = cli_.Put("/put", headers, "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  1483. ASSERT_TRUE(res != nullptr);
  1484. EXPECT_EQ(200, res->status);
  1485. EXPECT_EQ("PUT", res->body);
  1486. }
  1487. #endif
  1488. TEST_F(ServerTest, Patch) {
  1489. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1490. ASSERT_TRUE(res != nullptr);
  1491. EXPECT_EQ(200, res->status);
  1492. EXPECT_EQ("PATCH", res->body);
  1493. }
  1494. TEST_F(ServerTest, Delete) {
  1495. auto res = cli_.Delete("/delete");
  1496. ASSERT_TRUE(res != nullptr);
  1497. EXPECT_EQ(200, res->status);
  1498. EXPECT_EQ("DELETE", res->body);
  1499. }
  1500. TEST_F(ServerTest, Options) {
  1501. auto res = cli_.Options("*");
  1502. ASSERT_TRUE(res != nullptr);
  1503. EXPECT_EQ(200, res->status);
  1504. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1505. EXPECT_TRUE(res->body.empty());
  1506. }
  1507. TEST_F(ServerTest, URL) {
  1508. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1509. ASSERT_TRUE(res != nullptr);
  1510. EXPECT_EQ(200, res->status);
  1511. }
  1512. TEST_F(ServerTest, ArrayParam) {
  1513. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  1514. ASSERT_TRUE(res != nullptr);
  1515. EXPECT_EQ(200, res->status);
  1516. }
  1517. TEST_F(ServerTest, NoMultipleHeaders) {
  1518. Headers headers = {{"Content-Length", "5"}};
  1519. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  1520. "text/plain");
  1521. ASSERT_TRUE(res != nullptr);
  1522. EXPECT_EQ(200, res->status);
  1523. }
  1524. TEST_F(ServerTest, PostContentReceiver) {
  1525. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1526. ASSERT_TRUE(res != nullptr);
  1527. ASSERT_EQ(200, res->status);
  1528. ASSERT_EQ("content", res->body);
  1529. }
  1530. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  1531. MultipartFormDataItems items = {
  1532. {"text1", "text default", "", ""},
  1533. {"text2", "aωb", "", ""},
  1534. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1535. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1536. {"file3", "", "", "application/octet-stream"},
  1537. };
  1538. auto res = cli_.Post("/content_receiver", items);
  1539. ASSERT_TRUE(res != nullptr);
  1540. EXPECT_EQ(200, res->status);
  1541. }
  1542. TEST_F(ServerTest, PostContentReceiverGzip) {
  1543. cli_.set_compress(true);
  1544. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1545. ASSERT_TRUE(res != nullptr);
  1546. ASSERT_EQ(200, res->status);
  1547. ASSERT_EQ("content", res->body);
  1548. }
  1549. TEST_F(ServerTest, PutContentReceiver) {
  1550. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  1551. ASSERT_TRUE(res != nullptr);
  1552. ASSERT_EQ(200, res->status);
  1553. ASSERT_EQ("content", res->body);
  1554. }
  1555. TEST_F(ServerTest, PatchContentReceiver) {
  1556. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  1557. ASSERT_TRUE(res != nullptr);
  1558. ASSERT_EQ(200, res->status);
  1559. ASSERT_EQ("content", res->body);
  1560. }
  1561. TEST_F(ServerTest, PostQueryStringAndBody) {
  1562. auto res =
  1563. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  1564. ASSERT_TRUE(res != nullptr);
  1565. ASSERT_EQ(200, res->status);
  1566. }
  1567. TEST_F(ServerTest, HTTP2Magic) {
  1568. Request req;
  1569. req.method = "PRI";
  1570. req.path = "*";
  1571. req.body = "SM";
  1572. auto res = std::make_shared<Response>();
  1573. auto ret = cli_.send(req, *res);
  1574. ASSERT_TRUE(ret);
  1575. EXPECT_EQ(400, res->status);
  1576. }
  1577. TEST_F(ServerTest, KeepAlive) {
  1578. cli_.set_keep_alive_max_count(4);
  1579. std::vector<Request> requests;
  1580. Get(requests, "/hi");
  1581. Get(requests, "/hi");
  1582. Get(requests, "/hi");
  1583. Get(requests, "/not-exist");
  1584. Post(requests, "/empty", "", "text/plain");
  1585. std::vector<Response> responses;
  1586. auto ret = cli_.send(requests, responses);
  1587. ASSERT_TRUE(ret == true);
  1588. ASSERT_TRUE(requests.size() == responses.size());
  1589. for (int i = 0; i < 3; i++) {
  1590. auto &res = responses[i];
  1591. EXPECT_EQ(200, res.status);
  1592. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1593. EXPECT_EQ("Hello World!", res.body);
  1594. }
  1595. {
  1596. auto &res = responses[3];
  1597. EXPECT_EQ(404, res.status);
  1598. }
  1599. {
  1600. auto &res = responses[4];
  1601. EXPECT_EQ(200, res.status);
  1602. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1603. EXPECT_EQ("empty", res.body);
  1604. }
  1605. }
  1606. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1607. TEST_F(ServerTest, Gzip) {
  1608. Headers headers;
  1609. headers.emplace("Accept-Encoding", "gzip, deflate");
  1610. auto res = cli_.Get("/gzip", headers);
  1611. ASSERT_TRUE(res != nullptr);
  1612. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1613. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1614. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1615. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1616. "7890123456789012345678901234567890",
  1617. res->body);
  1618. EXPECT_EQ(200, res->status);
  1619. }
  1620. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  1621. Headers headers;
  1622. auto res = cli_.Get("/gzip", headers);
  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. res->body);
  1630. EXPECT_EQ(200, res->status);
  1631. }
  1632. TEST_F(ServerTest, GzipWithContentReceiver) {
  1633. Headers headers;
  1634. headers.emplace("Accept-Encoding", "gzip, deflate");
  1635. std::string body;
  1636. auto res =
  1637. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1638. EXPECT_EQ(data_length, 100);
  1639. body.append(data, data_length);
  1640. return true;
  1641. });
  1642. ASSERT_TRUE(res != nullptr);
  1643. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1645. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1647. "7890123456789012345678901234567890",
  1648. body);
  1649. EXPECT_EQ(200, res->status);
  1650. }
  1651. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  1652. Headers headers;
  1653. std::string body;
  1654. auto res =
  1655. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1656. EXPECT_EQ(data_length, 100);
  1657. body.append(data, data_length);
  1658. return true;
  1659. });
  1660. ASSERT_TRUE(res != nullptr);
  1661. EXPECT_EQ("", res->get_header_value("Content-Encoding"));
  1662. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1663. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1664. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1665. "7890123456789012345678901234567890",
  1666. body);
  1667. EXPECT_EQ(200, res->status);
  1668. }
  1669. TEST_F(ServerTest, NoGzip) {
  1670. Headers headers;
  1671. headers.emplace("Accept-Encoding", "gzip, deflate");
  1672. auto res = cli_.Get("/nogzip", headers);
  1673. ASSERT_TRUE(res != nullptr);
  1674. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1675. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1676. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1677. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1678. "7890123456789012345678901234567890",
  1679. res->body);
  1680. EXPECT_EQ(200, res->status);
  1681. }
  1682. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  1683. Headers headers;
  1684. headers.emplace("Accept-Encoding", "gzip, deflate");
  1685. std::string body;
  1686. auto res =
  1687. cli_.Get("/nogzip", headers, [&](const char *data, uint64_t data_length) {
  1688. EXPECT_EQ(data_length, 100);
  1689. body.append(data, data_length);
  1690. return true;
  1691. });
  1692. ASSERT_TRUE(res != nullptr);
  1693. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1694. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1695. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1696. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1697. "7890123456789012345678901234567890",
  1698. body);
  1699. EXPECT_EQ(200, res->status);
  1700. }
  1701. TEST_F(ServerTest, MultipartFormDataGzip) {
  1702. MultipartFormDataItems items = {
  1703. {"key1", "test", "", ""},
  1704. {"key2", "--abcdefg123", "", ""},
  1705. };
  1706. cli_.set_compress(true);
  1707. auto res = cli_.Post("/gzipmultipart", items);
  1708. ASSERT_TRUE(res != nullptr);
  1709. EXPECT_EQ(200, res->status);
  1710. }
  1711. #endif
  1712. // Sends a raw request to a server listening at HOST:PORT.
  1713. static bool send_request(time_t read_timeout_sec, const std::string &req) {
  1714. auto client_sock = detail::create_client_socket(HOST, PORT, /*timeout_sec=*/5,
  1715. std::string());
  1716. if (client_sock == INVALID_SOCKET) { return false; }
  1717. return detail::process_and_close_socket(
  1718. true, client_sock, 1, read_timeout_sec, 0,
  1719. [&](Stream &strm, bool /*last_connection*/, bool &
  1720. /*connection_close*/) -> bool {
  1721. if (req.size() !=
  1722. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  1723. return false;
  1724. }
  1725. char buf[512];
  1726. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  1727. while (line_reader.getline()) {}
  1728. return true;
  1729. });
  1730. }
  1731. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  1732. Server svr;
  1733. std::string header_value;
  1734. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  1735. header_value = req.get_header_value("foo");
  1736. res.set_content("ok", "text/plain");
  1737. });
  1738. thread t = thread([&] { svr.listen(HOST, PORT); });
  1739. while (!svr.is_running()) {
  1740. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1741. }
  1742. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  1743. // like characters are not treated the same - use vertical tab and escape.
  1744. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  1745. "foo: \t \v bar \e\t \r\n"
  1746. "Connection: close\r\n"
  1747. "\r\n";
  1748. ASSERT_TRUE(send_request(5, req));
  1749. svr.stop();
  1750. t.join();
  1751. EXPECT_EQ(header_value, "\v bar \e");
  1752. }
  1753. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  1754. Server svr;
  1755. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1756. res.set_content("ok", "text/plain");
  1757. });
  1758. // Server read timeout must be longer than the client read timeout for the
  1759. // bug to reproduce, probably to force the server to process a request
  1760. // without a trailing blank line.
  1761. const time_t client_read_timeout_sec = 1;
  1762. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  1763. bool listen_thread_ok = false;
  1764. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  1765. while (!svr.is_running()) {
  1766. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1767. }
  1768. // A certain header line causes an exception if the header property is parsed
  1769. // naively with a single regex. This occurs with libc++ but not libstdc++.
  1770. const std::string req =
  1771. "GET /hi HTTP/1.1\r\n"
  1772. " : "
  1773. " ";
  1774. ASSERT_TRUE(send_request(client_read_timeout_sec, req));
  1775. svr.stop();
  1776. t.join();
  1777. EXPECT_TRUE(listen_thread_ok);
  1778. }
  1779. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  1780. Server svr;
  1781. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  1782. res.set_header("Content-Type", "text/event-stream");
  1783. res.set_header("Cache-Control", "no-cache");
  1784. res.set_chunked_content_provider([](size_t offset, const DataSink &sink) {
  1785. char buffer[27];
  1786. int size = sprintf(buffer, "data:%ld\n\n", offset);
  1787. sink.write(buffer, size);
  1788. std::this_thread::sleep_for(std::chrono::seconds(1));
  1789. });
  1790. });
  1791. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1792. while (!svr.is_running()) {
  1793. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1794. }
  1795. Client client(HOST, PORT);
  1796. const Headers headers = {{"Accept", "text/event-stream"},
  1797. {"Connection", "Keep-Alive"}};
  1798. auto get_thread = std::thread([&client, &headers]() {
  1799. std::shared_ptr<Response> res = client.Get(
  1800. "/events", headers,
  1801. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  1802. });
  1803. // Give GET time to get a few messages.
  1804. std::this_thread::sleep_for(std::chrono::seconds(2));
  1805. svr.stop();
  1806. listen_thread.join();
  1807. get_thread.join();
  1808. ASSERT_FALSE(svr.is_running());
  1809. }
  1810. TEST(MountTest, Unmount) {
  1811. Server svr;
  1812. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1813. while (!svr.is_running()) {
  1814. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1815. }
  1816. // Give GET time to get a few messages.
  1817. std::this_thread::sleep_for(std::chrono::seconds(1));
  1818. Client cli("localhost", PORT);
  1819. svr.set_mount_point("/mount2", "./www2");
  1820. auto res = cli.Get("/");
  1821. ASSERT_TRUE(res != nullptr);
  1822. EXPECT_EQ(404, res->status);
  1823. res = cli.Get("/mount2/dir/test.html");
  1824. ASSERT_TRUE(res != nullptr);
  1825. EXPECT_EQ(200, res->status);
  1826. svr.set_mount_point("/", "./www");
  1827. res = cli.Get("/dir/");
  1828. ASSERT_TRUE(res != nullptr);
  1829. EXPECT_EQ(200, res->status);
  1830. svr.remove_mount_point("/");
  1831. res = cli.Get("/dir/");
  1832. ASSERT_TRUE(res != nullptr);
  1833. EXPECT_EQ(404, res->status);
  1834. svr.remove_mount_point("/mount2");
  1835. res = cli.Get("/mount2/dir/test.html");
  1836. ASSERT_TRUE(res != nullptr);
  1837. EXPECT_EQ(404, res->status);
  1838. svr.stop();
  1839. listen_thread.join();
  1840. ASSERT_FALSE(svr.is_running());
  1841. }
  1842. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  1843. protected:
  1844. ServerTestWithAI_PASSIVE()
  1845. : cli_(HOST, PORT)
  1846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1847. ,
  1848. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1849. #endif
  1850. {
  1851. }
  1852. virtual void SetUp() {
  1853. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1854. res.set_content("Hello World!", "text/plain");
  1855. });
  1856. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  1857. while (!svr_.is_running()) {
  1858. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1859. }
  1860. }
  1861. virtual void TearDown() {
  1862. svr_.stop();
  1863. t_.join();
  1864. }
  1865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1866. SSLClient cli_;
  1867. SSLServer svr_;
  1868. #else
  1869. Client cli_;
  1870. Server svr_;
  1871. #endif
  1872. thread t_;
  1873. };
  1874. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  1875. auto res = cli_.Get("/hi");
  1876. ASSERT_TRUE(res != nullptr);
  1877. EXPECT_EQ(200, res->status);
  1878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1879. EXPECT_EQ("Hello World!", res->body);
  1880. }
  1881. class ServerUpDownTest : public ::testing::Test {
  1882. protected:
  1883. ServerUpDownTest() : cli_(HOST, PORT) {}
  1884. virtual void SetUp() {
  1885. t_ = thread([&]() {
  1886. svr_.bind_to_any_port(HOST);
  1887. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  1888. ASSERT_TRUE(svr_.listen_after_bind());
  1889. });
  1890. while (!svr_.is_running()) {
  1891. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1892. }
  1893. }
  1894. virtual void TearDown() {
  1895. svr_.stop();
  1896. t_.join();
  1897. }
  1898. Client cli_;
  1899. Server svr_;
  1900. thread t_;
  1901. };
  1902. TEST_F(ServerUpDownTest, QuickStartStop) {
  1903. // Should not crash, especially when run with
  1904. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  1905. }
  1906. class PayloadMaxLengthTest : public ::testing::Test {
  1907. protected:
  1908. PayloadMaxLengthTest()
  1909. : cli_(HOST, PORT)
  1910. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1911. ,
  1912. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1913. #endif
  1914. {
  1915. }
  1916. virtual void SetUp() {
  1917. svr_.set_payload_max_length(8);
  1918. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  1919. res.set_content("test", "text/plain");
  1920. });
  1921. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1922. while (!svr_.is_running()) {
  1923. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1924. }
  1925. }
  1926. virtual void TearDown() {
  1927. svr_.stop();
  1928. t_.join();
  1929. }
  1930. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1931. SSLClient cli_;
  1932. SSLServer svr_;
  1933. #else
  1934. Client cli_;
  1935. Server svr_;
  1936. #endif
  1937. thread t_;
  1938. };
  1939. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  1940. auto res = cli_.Post("/test", "123456789", "text/plain");
  1941. ASSERT_TRUE(res != nullptr);
  1942. EXPECT_EQ(413, res->status);
  1943. res = cli_.Post("/test", "12345678", "text/plain");
  1944. ASSERT_TRUE(res != nullptr);
  1945. EXPECT_EQ(200, res->status);
  1946. }
  1947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1948. TEST(SSLClientTest, ServerNameIndication) {
  1949. SSLClient cli("httpbin.org", 443);
  1950. auto res = cli.Get("/get");
  1951. ASSERT_TRUE(res != nullptr);
  1952. ASSERT_EQ(200, res->status);
  1953. }
  1954. TEST(SSLClientTest, ServerCertificateVerification) {
  1955. SSLClient cli("google.com");
  1956. auto res = cli.Get("/");
  1957. ASSERT_TRUE(res != nullptr);
  1958. ASSERT_EQ(301, res->status);
  1959. cli.enable_server_certificate_verification(true);
  1960. res = cli.Get("/");
  1961. ASSERT_TRUE(res == nullptr);
  1962. cli.set_ca_cert_path(CA_CERT_FILE);
  1963. res = cli.Get("/");
  1964. ASSERT_TRUE(res != nullptr);
  1965. ASSERT_EQ(301, res->status);
  1966. }
  1967. TEST(SSLClientTest, WildcardHostNameMatch) {
  1968. SSLClient cli("www.youtube.com");
  1969. cli.set_ca_cert_path(CA_CERT_FILE);
  1970. cli.enable_server_certificate_verification(true);
  1971. auto res = cli.Get("/");
  1972. ASSERT_TRUE(res != nullptr);
  1973. ASSERT_EQ(200, res->status);
  1974. }
  1975. TEST(SSLClientServerTest, ClientCertPresent) {
  1976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1977. CLIENT_CA_CERT_DIR);
  1978. ASSERT_TRUE(svr.is_valid());
  1979. svr.Get("/test", [&](const Request &req, Response &res) {
  1980. res.set_content("test", "text/plain");
  1981. svr.stop();
  1982. ASSERT_TRUE(true);
  1983. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  1984. ASSERT_TRUE(peer_cert != nullptr);
  1985. auto subject_name = X509_get_subject_name(peer_cert);
  1986. ASSERT_TRUE(subject_name != nullptr);
  1987. std::string common_name;
  1988. {
  1989. char name[BUFSIZ];
  1990. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  1991. name, sizeof(name));
  1992. common_name.assign(name, name_len);
  1993. }
  1994. EXPECT_EQ("Common Name", common_name);
  1995. X509_free(peer_cert);
  1996. });
  1997. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  1998. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1999. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2000. auto res = cli.Get("/test");
  2001. cli.set_timeout_sec(30);
  2002. ASSERT_TRUE(res != nullptr);
  2003. ASSERT_EQ(200, res->status);
  2004. t.join();
  2005. }
  2006. TEST(SSLClientServerTest, ClientCertMissing) {
  2007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2008. CLIENT_CA_CERT_DIR);
  2009. ASSERT_TRUE(svr.is_valid());
  2010. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  2011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2012. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2013. httplib::SSLClient cli(HOST, PORT);
  2014. auto res = cli.Get("/test");
  2015. cli.set_timeout_sec(30);
  2016. ASSERT_TRUE(res == nullptr);
  2017. svr.stop();
  2018. t.join();
  2019. }
  2020. TEST(SSLClientServerTest, TrustDirOptional) {
  2021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2022. ASSERT_TRUE(svr.is_valid());
  2023. svr.Get("/test", [&](const Request &, Response &res) {
  2024. res.set_content("test", "text/plain");
  2025. svr.stop();
  2026. });
  2027. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2028. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2029. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2030. auto res = cli.Get("/test");
  2031. cli.set_timeout_sec(30);
  2032. ASSERT_TRUE(res != nullptr);
  2033. ASSERT_EQ(200, res->status);
  2034. t.join();
  2035. }
  2036. /* Cannot test this case as there is no external access to SSL object to check
  2037. SSL_get_peer_certificate() == NULL TEST(SSLClientServerTest,
  2038. ClientCAPathRequired) { SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  2039. nullptr, CLIENT_CA_CERT_DIR);
  2040. }
  2041. */
  2042. #endif
  2043. #ifdef _WIN32
  2044. TEST(CleanupTest, WSACleanup) {
  2045. int ret = WSACleanup();
  2046. ASSERT_EQ(0, ret);
  2047. }
  2048. #endif