test.cc 89 KB

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