test.cc 86 KB

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