test.cc 73 KB

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