test.cc 86 KB

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