test.cc 88 KB

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