test.cc 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064
  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 =
  80. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  81. EXPECT_EQ(100ull, val);
  82. }
  83. TEST(GetHeaderValueTest, RegularValue) {
  84. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  85. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  86. EXPECT_STREQ("text/html", val);
  87. }
  88. TEST(GetHeaderValueTest, RegularValueInt) {
  89. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  90. auto val =
  91. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  92. EXPECT_EQ(100ull, val);
  93. }
  94. TEST(GetHeaderValueTest, Range) {
  95. {
  96. Headers headers = {make_range_header({{1, -1}})};
  97. auto val = detail::get_header_value(headers, "Range", 0, 0);
  98. EXPECT_STREQ("bytes=1-", val);
  99. }
  100. {
  101. Headers headers = {make_range_header({{-1, 1}})};
  102. auto val = detail::get_header_value(headers, "Range", 0, 0);
  103. EXPECT_STREQ("bytes=-1", val);
  104. }
  105. {
  106. Headers headers = {make_range_header({{1, 10}})};
  107. auto val = detail::get_header_value(headers, "Range", 0, 0);
  108. EXPECT_STREQ("bytes=1-10", val);
  109. }
  110. {
  111. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  112. auto val = detail::get_header_value(headers, "Range", 0, 0);
  113. EXPECT_STREQ("bytes=1-10, 100-", val);
  114. }
  115. {
  116. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  117. auto val = detail::get_header_value(headers, "Range", 0, 0);
  118. EXPECT_STREQ("bytes=1-10, 100-200", val);
  119. }
  120. {
  121. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  122. auto val = detail::get_header_value(headers, "Range", 0, 0);
  123. EXPECT_STREQ("bytes=0-0, -1", val);
  124. }
  125. }
  126. TEST(ParseHeaderValueTest, Range) {
  127. {
  128. Ranges ranges;
  129. auto ret = detail::parse_range_header("bytes=1-", ranges);
  130. EXPECT_TRUE(ret);
  131. EXPECT_EQ(1u, ranges.size());
  132. EXPECT_EQ(1u, ranges[0].first);
  133. EXPECT_EQ(-1, ranges[0].second);
  134. }
  135. {
  136. Ranges ranges;
  137. auto ret = detail::parse_range_header("bytes=-1", ranges);
  138. EXPECT_TRUE(ret);
  139. EXPECT_EQ(1u, ranges.size());
  140. EXPECT_EQ(-1, ranges[0].first);
  141. EXPECT_EQ(1u, ranges[0].second);
  142. }
  143. {
  144. Ranges ranges;
  145. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(1u, ranges.size());
  148. EXPECT_EQ(1u, ranges[0].first);
  149. EXPECT_EQ(10u, ranges[0].second);
  150. }
  151. {
  152. Ranges ranges;
  153. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  154. EXPECT_FALSE(ret);
  155. }
  156. {
  157. Ranges ranges;
  158. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  159. EXPECT_TRUE(ret);
  160. EXPECT_EQ(2u, ranges.size());
  161. EXPECT_EQ(1u, ranges[0].first);
  162. EXPECT_EQ(10u, ranges[0].second);
  163. EXPECT_EQ(100u, ranges[1].first);
  164. EXPECT_EQ(-1, ranges[1].second);
  165. }
  166. {
  167. Ranges ranges;
  168. auto ret =
  169. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  170. EXPECT_TRUE(ret);
  171. EXPECT_EQ(3u, ranges.size());
  172. EXPECT_EQ(1u, ranges[0].first);
  173. EXPECT_EQ(10u, ranges[0].second);
  174. EXPECT_EQ(100u, ranges[1].first);
  175. EXPECT_EQ(200u, ranges[1].second);
  176. EXPECT_EQ(300u, ranges[2].first);
  177. EXPECT_EQ(400u, ranges[2].second);
  178. }
  179. }
  180. TEST(BufferStreamTest, read) {
  181. detail::BufferStream strm1;
  182. Stream &strm = strm1;
  183. EXPECT_EQ(5, strm.write("hello"));
  184. char buf[512];
  185. EXPECT_EQ(2, strm.read(buf, 2));
  186. EXPECT_EQ('h', buf[0]);
  187. EXPECT_EQ('e', buf[1]);
  188. EXPECT_EQ(2, strm.read(buf, 2));
  189. EXPECT_EQ('l', buf[0]);
  190. EXPECT_EQ('l', buf[1]);
  191. EXPECT_EQ(1, strm.read(buf, 1));
  192. EXPECT_EQ('o', buf[0]);
  193. EXPECT_EQ(0, strm.read(buf, 1));
  194. }
  195. TEST(ChunkedEncodingTest, FromHTTPWatch) {
  196. auto host = "www.httpwatch.com";
  197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  198. auto port = 443;
  199. httplib::SSLClient cli(host, port);
  200. #else
  201. auto port = 80;
  202. httplib::Client cli(host, port);
  203. #endif
  204. cli.set_connection_timeout(2);
  205. auto res =
  206. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  207. ASSERT_TRUE(res != nullptr);
  208. std::string out;
  209. httplib::detail::read_file("./image.jpg", out);
  210. EXPECT_EQ(200, res->status);
  211. EXPECT_EQ(out, res->body);
  212. }
  213. TEST(ChunkedEncodingTest, WithContentReceiver) {
  214. auto host = "www.httpwatch.com";
  215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  216. auto port = 443;
  217. httplib::SSLClient cli(host, port);
  218. #else
  219. auto port = 80;
  220. httplib::Client cli(host, port);
  221. #endif
  222. cli.set_connection_timeout(2);
  223. std::string body;
  224. auto res =
  225. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  226. [&](const char *data, size_t data_length) {
  227. body.append(data, data_length);
  228. return true;
  229. });
  230. ASSERT_TRUE(res != nullptr);
  231. std::string out;
  232. httplib::detail::read_file("./image.jpg", out);
  233. EXPECT_EQ(200, res->status);
  234. EXPECT_EQ(out, body);
  235. }
  236. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  237. auto host = "www.httpwatch.com";
  238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  239. auto port = 443;
  240. httplib::SSLClient cli(host, port);
  241. #else
  242. auto port = 80;
  243. httplib::Client cli(host, port);
  244. #endif
  245. cli.set_connection_timeout(2);
  246. std::string body;
  247. auto res = cli.Get(
  248. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137", Headers(),
  249. [&](const Response &response) {
  250. EXPECT_EQ(200, response.status);
  251. return true;
  252. },
  253. [&](const char *data, size_t data_length) {
  254. body.append(data, data_length);
  255. return true;
  256. });
  257. ASSERT_TRUE(res != nullptr);
  258. std::string out;
  259. httplib::detail::read_file("./image.jpg", out);
  260. EXPECT_EQ(200, res->status);
  261. EXPECT_EQ(out, body);
  262. }
  263. TEST(RangeTest, FromHTTPBin) {
  264. auto host = "httpbin.org";
  265. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  266. auto port = 443;
  267. httplib::SSLClient cli(host, port);
  268. #else
  269. auto port = 80;
  270. httplib::Client cli(host, port);
  271. #endif
  272. cli.set_connection_timeout(5);
  273. {
  274. httplib::Headers headers;
  275. auto res = cli.Get("/range/32", headers);
  276. ASSERT_TRUE(res != nullptr);
  277. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  278. EXPECT_EQ(200, res->status);
  279. }
  280. {
  281. httplib::Headers headers = {httplib::make_range_header({{1, -1}})};
  282. auto res = cli.Get("/range/32", headers);
  283. ASSERT_TRUE(res != nullptr);
  284. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  285. EXPECT_EQ(206, res->status);
  286. }
  287. {
  288. httplib::Headers headers = {httplib::make_range_header({{1, 10}})};
  289. auto res = cli.Get("/range/32", headers);
  290. ASSERT_TRUE(res != nullptr);
  291. EXPECT_EQ("bcdefghijk", res->body);
  292. EXPECT_EQ(206, res->status);
  293. }
  294. {
  295. httplib::Headers headers = {httplib::make_range_header({{0, 31}})};
  296. auto res = cli.Get("/range/32", headers);
  297. ASSERT_TRUE(res != nullptr);
  298. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  299. EXPECT_EQ(200, res->status);
  300. }
  301. {
  302. httplib::Headers headers = {httplib::make_range_header({{0, -1}})};
  303. auto res = cli.Get("/range/32", headers);
  304. ASSERT_TRUE(res != nullptr);
  305. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  306. EXPECT_EQ(200, res->status);
  307. }
  308. {
  309. httplib::Headers headers = {httplib::make_range_header({{0, 32}})};
  310. auto res = cli.Get("/range/32", headers);
  311. ASSERT_TRUE(res != nullptr);
  312. EXPECT_EQ(416, res->status);
  313. }
  314. }
  315. TEST(ConnectionErrorTest, InvalidHost) {
  316. auto host = "-abcde.com";
  317. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  318. auto port = 443;
  319. httplib::SSLClient cli(host, port);
  320. #else
  321. auto port = 80;
  322. httplib::Client cli(host, port);
  323. #endif
  324. cli.set_connection_timeout(2);
  325. auto res = cli.Get("/");
  326. ASSERT_TRUE(res == nullptr);
  327. }
  328. TEST(ConnectionErrorTest, InvalidHost2) {
  329. auto host = "httpbin.org/";
  330. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  331. httplib::SSLClient cli(host);
  332. #else
  333. httplib::Client cli(host);
  334. #endif
  335. cli.set_connection_timeout(2);
  336. auto res = cli.Get("/");
  337. ASSERT_TRUE(res == nullptr);
  338. }
  339. TEST(ConnectionErrorTest, InvalidPort) {
  340. auto host = "localhost";
  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_connection_timeout(2);
  349. auto res = cli.Get("/");
  350. ASSERT_TRUE(res == nullptr);
  351. }
  352. TEST(ConnectionErrorTest, Timeout) {
  353. auto host = "google.com";
  354. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  355. auto port = 44380;
  356. httplib::SSLClient cli(host, port);
  357. #else
  358. auto port = 8080;
  359. httplib::Client cli(host, port);
  360. #endif
  361. cli.set_connection_timeout(2);
  362. auto res = cli.Get("/");
  363. ASSERT_TRUE(res == nullptr);
  364. }
  365. TEST(CancelTest, NoCancel) {
  366. auto host = "httpbin.org";
  367. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  368. auto port = 443;
  369. httplib::SSLClient cli(host, port);
  370. #else
  371. auto port = 80;
  372. httplib::Client cli(host, port);
  373. #endif
  374. cli.set_connection_timeout(5);
  375. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  376. ASSERT_TRUE(res != nullptr);
  377. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  378. EXPECT_EQ(200, res->status);
  379. }
  380. TEST(CancelTest, WithCancelSmallPayload) {
  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. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  390. cli.set_connection_timeout(5);
  391. ASSERT_TRUE(res == nullptr);
  392. }
  393. TEST(CancelTest, WithCancelLargePayload) {
  394. auto host = "httpbin.org";
  395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  396. auto port = 443;
  397. httplib::SSLClient cli(host, port);
  398. #else
  399. auto port = 80;
  400. httplib::Client cli(host, port);
  401. #endif
  402. cli.set_connection_timeout(5);
  403. uint32_t count = 0;
  404. httplib::Headers headers;
  405. auto res = cli.Get("/range/65536", headers,
  406. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  407. ASSERT_TRUE(res == nullptr);
  408. }
  409. TEST(BaseAuthTest, FromHTTPWatch) {
  410. auto host = "httpbin.org";
  411. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  412. auto port = 443;
  413. httplib::SSLClient cli(host, port);
  414. #else
  415. auto port = 80;
  416. httplib::Client cli(host, port);
  417. #endif
  418. {
  419. auto res = cli.Get("/basic-auth/hello/world");
  420. ASSERT_TRUE(res != nullptr);
  421. EXPECT_EQ(401, res->status);
  422. }
  423. {
  424. auto res =
  425. cli.Get("/basic-auth/hello/world",
  426. {httplib::make_basic_authentication_header("hello", "world")});
  427. ASSERT_TRUE(res != nullptr);
  428. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  429. res->body);
  430. EXPECT_EQ(200, res->status);
  431. }
  432. {
  433. cli.set_basic_auth("hello", "world");
  434. auto res = cli.Get("/basic-auth/hello/world");
  435. ASSERT_TRUE(res != nullptr);
  436. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  437. res->body);
  438. EXPECT_EQ(200, res->status);
  439. }
  440. {
  441. cli.set_basic_auth("hello", "bad");
  442. auto res = cli.Get("/basic-auth/hello/world");
  443. ASSERT_TRUE(res != nullptr);
  444. EXPECT_EQ(401, res->status);
  445. }
  446. {
  447. cli.set_basic_auth("bad", "world");
  448. auto res = cli.Get("/basic-auth/hello/world");
  449. ASSERT_TRUE(res != nullptr);
  450. EXPECT_EQ(401, res->status);
  451. }
  452. }
  453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  454. TEST(DigestAuthTest, FromHTTPWatch) {
  455. auto host = "httpbin.org";
  456. auto port = 443;
  457. httplib::SSLClient cli(host, port);
  458. {
  459. auto res = cli.Get("/digest-auth/auth/hello/world");
  460. ASSERT_TRUE(res != nullptr);
  461. EXPECT_EQ(401, res->status);
  462. }
  463. {
  464. std::vector<std::string> paths = {
  465. "/digest-auth/auth/hello/world/MD5",
  466. "/digest-auth/auth/hello/world/SHA-256",
  467. "/digest-auth/auth/hello/world/SHA-512",
  468. "/digest-auth/auth-int/hello/world/MD5",
  469. };
  470. cli.set_digest_auth("hello", "world");
  471. for (auto path : paths) {
  472. auto res = cli.Get(path.c_str());
  473. ASSERT_TRUE(res != nullptr);
  474. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  475. res->body);
  476. EXPECT_EQ(200, res->status);
  477. }
  478. cli.set_digest_auth("hello", "bad");
  479. for (auto path : paths) {
  480. auto res = cli.Get(path.c_str());
  481. ASSERT_TRUE(res != nullptr);
  482. EXPECT_EQ(401, res->status);
  483. }
  484. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  485. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  486. // cli.set_digest_auth("bad", "world");
  487. // for (auto path : paths) {
  488. // auto res = cli.Get(path.c_str());
  489. // ASSERT_TRUE(res != nullptr);
  490. // EXPECT_EQ(400, res->status);
  491. // }
  492. }
  493. }
  494. #endif
  495. #if 0
  496. TEST(AbsoluteRedirectTest, Redirect) {
  497. auto host = "httpbin.org";
  498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  499. httplib::SSLClient cli(host);
  500. #else
  501. httplib::Client cli(host);
  502. #endif
  503. cli.set_follow_location(true);
  504. auto res = cli.Get("/absolute-redirect/3");
  505. ASSERT_TRUE(res != nullptr);
  506. EXPECT_EQ(200, res->status);
  507. }
  508. TEST(RedirectTest, Redirect) {
  509. auto host = "httpbin.org";
  510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  511. httplib::SSLClient cli(host);
  512. #else
  513. httplib::Client cli(host);
  514. #endif
  515. cli.set_follow_location(true);
  516. auto res = cli.Get("/redirect/3");
  517. ASSERT_TRUE(res != nullptr);
  518. EXPECT_EQ(200, res->status);
  519. }
  520. TEST(RelativeRedirectTest, Redirect) {
  521. auto host = "httpbin.org";
  522. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  523. httplib::SSLClient cli(host);
  524. #else
  525. httplib::Client cli(host);
  526. #endif
  527. cli.set_follow_location(true);
  528. auto res = cli.Get("/relative-redirect/3");
  529. ASSERT_TRUE(res != nullptr);
  530. EXPECT_EQ(200, res->status);
  531. }
  532. TEST(TooManyRedirectTest, Redirect) {
  533. auto host = "httpbin.org";
  534. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  535. httplib::SSLClient cli(host);
  536. #else
  537. httplib::Client cli(host);
  538. #endif
  539. cli.set_follow_location(true);
  540. auto res = cli.Get("/redirect/21");
  541. ASSERT_TRUE(res == nullptr);
  542. }
  543. #endif
  544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  545. TEST(YahooRedirectTest, Redirect) {
  546. httplib::Client cli("yahoo.com");
  547. auto res = cli.Get("/");
  548. ASSERT_TRUE(res != nullptr);
  549. EXPECT_EQ(301, res->status);
  550. cli.set_follow_location(true);
  551. res = cli.Get("/");
  552. ASSERT_TRUE(res != nullptr);
  553. EXPECT_EQ(200, res->status);
  554. }
  555. #if 0
  556. TEST(HttpsToHttpRedirectTest, Redirect) {
  557. httplib::SSLClient cli("httpbin.org");
  558. cli.set_follow_location(true);
  559. auto res =
  560. cli.Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  561. ASSERT_TRUE(res != nullptr);
  562. EXPECT_EQ(200, res->status);
  563. }
  564. #endif
  565. TEST(RedirectToDifferentPort, Redirect) {
  566. Server svr8080;
  567. Server svr8081;
  568. svr8080.Get("/1", [&](const Request & /*req*/, Response &res) {
  569. res.set_redirect("http://localhost:8081/2");
  570. });
  571. svr8081.Get("/2", [&](const Request & /*req*/, Response &res) {
  572. res.set_content("Hello World!", "text/plain");
  573. });
  574. auto thread8080 = std::thread([&]() { svr8080.listen("localhost", 8080); });
  575. auto thread8081 = std::thread([&]() { svr8081.listen("localhost", 8081); });
  576. while (!svr8080.is_running() || !svr8081.is_running()) {
  577. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  578. }
  579. // Give GET time to get a few messages.
  580. std::this_thread::sleep_for(std::chrono::seconds(1));
  581. Client cli("localhost", 8080);
  582. cli.set_follow_location(true);
  583. auto res = cli.Get("/1");
  584. ASSERT_TRUE(res != nullptr);
  585. EXPECT_EQ(200, res->status);
  586. EXPECT_EQ("Hello World!", res->body);
  587. svr8080.stop();
  588. svr8081.stop();
  589. thread8080.join();
  590. thread8081.join();
  591. ASSERT_FALSE(svr8080.is_running());
  592. ASSERT_FALSE(svr8081.is_running());
  593. }
  594. TEST(UrlWithSpace, Redirect) {
  595. httplib::SSLClient cli("edge.forgecdn.net");
  596. cli.set_follow_location(true);
  597. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  598. ASSERT_TRUE(res != nullptr);
  599. EXPECT_EQ(200, res->status);
  600. EXPECT_EQ(18527, res->get_header_value<uint64_t>("Content-Length"));
  601. }
  602. #endif
  603. TEST(Server, BindDualStack) {
  604. Server svr;
  605. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  606. res.set_content("Hello World!", "text/plain");
  607. });
  608. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  609. // Give GET time to get a few messages.
  610. std::this_thread::sleep_for(std::chrono::seconds(1));
  611. {
  612. Client cli("127.0.0.1", PORT);
  613. auto res = cli.Get("/1");
  614. ASSERT_TRUE(res != nullptr);
  615. EXPECT_EQ(200, res->status);
  616. EXPECT_EQ("Hello World!", res->body);
  617. }
  618. {
  619. Client cli("::1", PORT);
  620. auto res = cli.Get("/1");
  621. ASSERT_TRUE(res != nullptr);
  622. EXPECT_EQ(200, res->status);
  623. EXPECT_EQ("Hello World!", res->body);
  624. }
  625. svr.stop();
  626. thread.join();
  627. ASSERT_FALSE(svr.is_running());
  628. }
  629. TEST(Server, BindAndListenSeparately) {
  630. Server svr;
  631. int port = svr.bind_to_any_port("0.0.0.0");
  632. ASSERT_TRUE(svr.is_valid());
  633. ASSERT_TRUE(port > 0);
  634. svr.stop();
  635. }
  636. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  637. TEST(SSLServer, BindAndListenSeparately) {
  638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  639. CLIENT_CA_CERT_DIR);
  640. int port = svr.bind_to_any_port("0.0.0.0");
  641. ASSERT_TRUE(svr.is_valid());
  642. ASSERT_TRUE(port > 0);
  643. svr.stop();
  644. }
  645. #endif
  646. class ServerTest : public ::testing::Test {
  647. protected:
  648. ServerTest()
  649. : cli_(HOST, PORT)
  650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  651. ,
  652. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  653. #endif
  654. {
  655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  656. cli_.enable_server_certificate_verification(false);
  657. #endif
  658. }
  659. virtual void SetUp() {
  660. svr_.set_mount_point("/", "./www");
  661. svr_.set_mount_point("/mount", "./www2");
  662. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  663. svr_.Get("/hi",
  664. [&](const Request & /*req*/, Response &res) {
  665. res.set_content("Hello World!", "text/plain");
  666. })
  667. .Get("/http_response_splitting",
  668. [&](const Request & /*req*/, Response &res) {
  669. res.set_header("a", "1\r\nSet-Cookie: a=1");
  670. EXPECT_EQ(0, res.headers.size());
  671. EXPECT_FALSE(res.has_header("a"));
  672. res.set_header("a", "1\nSet-Cookie: a=1");
  673. EXPECT_EQ(0, res.headers.size());
  674. EXPECT_FALSE(res.has_header("a"));
  675. res.set_header("a", "1\rSet-Cookie: a=1");
  676. EXPECT_EQ(0, res.headers.size());
  677. EXPECT_FALSE(res.has_header("a"));
  678. res.set_header("a\r\nb", "0");
  679. EXPECT_EQ(0, res.headers.size());
  680. EXPECT_FALSE(res.has_header("a"));
  681. res.set_header("a\rb", "0");
  682. EXPECT_EQ(0, res.headers.size());
  683. EXPECT_FALSE(res.has_header("a"));
  684. res.set_header("a\nb", "0");
  685. EXPECT_EQ(0, res.headers.size());
  686. EXPECT_FALSE(res.has_header("a"));
  687. res.set_redirect("1\r\nSet-Cookie: a=1");
  688. EXPECT_EQ(0, res.headers.size());
  689. EXPECT_FALSE(res.has_header("Location"));
  690. })
  691. .Get("/slow",
  692. [&](const Request & /*req*/, Response &res) {
  693. std::this_thread::sleep_for(std::chrono::seconds(2));
  694. res.set_content("slow", "text/plain");
  695. })
  696. .Post("/slowpost",
  697. [&](const Request & /*req*/, Response &res) {
  698. std::this_thread::sleep_for(std::chrono::seconds(2));
  699. res.set_content("slow", "text/plain");
  700. })
  701. .Get("/remote_addr",
  702. [&](const Request &req, Response &res) {
  703. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  704. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  705. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  706. EXPECT_EQ(req.remote_port,
  707. std::stoi(req.get_header_value("REMOTE_PORT")));
  708. res.set_content(remote_addr.c_str(), "text/plain");
  709. })
  710. .Get("/endwith%",
  711. [&](const Request & /*req*/, Response &res) {
  712. res.set_content("Hello World!", "text/plain");
  713. })
  714. .Get("/a\\+\\+b",
  715. [&](const Request &req, Response &res) {
  716. ASSERT_TRUE(req.has_param("a +b"));
  717. auto val = req.get_param_value("a +b");
  718. res.set_content(val, "text/plain");
  719. })
  720. .Get("/", [&](const Request & /*req*/,
  721. Response &res) { res.set_redirect("/hi"); })
  722. .Post("/1", [](const Request & /*req*/,
  723. Response &res) { res.set_redirect("/2", 303); })
  724. .Get("/2",
  725. [](const Request & /*req*/, Response &res) {
  726. res.set_content("redirected.", "text/plain");
  727. res.status = 200;
  728. })
  729. .Post("/person",
  730. [&](const Request &req, Response &res) {
  731. if (req.has_param("name") && req.has_param("note")) {
  732. persons_[req.get_param_value("name")] =
  733. req.get_param_value("note");
  734. } else {
  735. res.status = 400;
  736. }
  737. })
  738. .Put("/person",
  739. [&](const Request &req, Response &res) {
  740. if (req.has_param("name") && req.has_param("note")) {
  741. persons_[req.get_param_value("name")] =
  742. req.get_param_value("note");
  743. } else {
  744. res.status = 400;
  745. }
  746. })
  747. .Get("/person/(.*)",
  748. [&](const Request &req, Response &res) {
  749. string name = req.matches[1];
  750. if (persons_.find(name) != persons_.end()) {
  751. auto note = persons_[name];
  752. res.set_content(note, "text/plain");
  753. } else {
  754. res.status = 404;
  755. }
  756. })
  757. .Post("/x-www-form-urlencoded-json",
  758. [&](const Request &req, Response &res) {
  759. auto json = req.get_param_value("json");
  760. ASSERT_EQ(JSON_DATA, json);
  761. res.set_content(json, "appliation/json");
  762. res.status = 200;
  763. })
  764. .Get("/streamed-chunked",
  765. [&](const Request & /*req*/, Response &res) {
  766. res.set_chunked_content_provider(
  767. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  768. EXPECT_TRUE(sink.is_writable());
  769. sink.os << "123";
  770. sink.os << "456";
  771. sink.os << "789";
  772. sink.done();
  773. return true;
  774. });
  775. })
  776. .Get("/streamed-chunked2",
  777. [&](const Request & /*req*/, Response &res) {
  778. auto i = new int(0);
  779. res.set_chunked_content_provider(
  780. "text/plain",
  781. [i](size_t /*offset*/, DataSink &sink) {
  782. EXPECT_TRUE(sink.is_writable());
  783. switch (*i) {
  784. case 0: sink.os << "123"; break;
  785. case 1: sink.os << "456"; break;
  786. case 2: sink.os << "789"; break;
  787. case 3: sink.done(); break;
  788. }
  789. (*i)++;
  790. return true;
  791. },
  792. [i] { delete i; });
  793. })
  794. .Get("/streamed",
  795. [&](const Request & /*req*/, Response &res) {
  796. res.set_content_provider(
  797. 6, "text/plain",
  798. [](size_t offset, size_t /*length*/, DataSink &sink) {
  799. sink.os << (offset < 3 ? "a" : "b");
  800. return true;
  801. });
  802. })
  803. .Get("/streamed-with-range",
  804. [&](const Request & /*req*/, Response &res) {
  805. auto data = new std::string("abcdefg");
  806. res.set_content_provider(
  807. data->size(), "text/plain",
  808. [data](size_t offset, size_t length, DataSink &sink) {
  809. EXPECT_TRUE(sink.is_writable());
  810. size_t DATA_CHUNK_SIZE = 4;
  811. const auto &d = *data;
  812. auto out_len =
  813. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  814. sink.write(&d[static_cast<size_t>(offset)], out_len);
  815. return true;
  816. },
  817. [data] { delete data; });
  818. })
  819. .Get("/streamed-cancel",
  820. [&](const Request & /*req*/, Response &res) {
  821. res.set_content_provider(
  822. size_t(-1), "text/plain",
  823. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  824. EXPECT_TRUE(sink.is_writable());
  825. sink.os << "data_chunk";
  826. return true;
  827. });
  828. })
  829. .Get("/with-range",
  830. [&](const Request & /*req*/, Response &res) {
  831. res.set_content("abcdefg", "text/plain");
  832. })
  833. .Post("/chunked",
  834. [&](const Request &req, Response & /*res*/) {
  835. EXPECT_EQ(req.body, "dechunked post body");
  836. })
  837. .Post("/large-chunked",
  838. [&](const Request &req, Response & /*res*/) {
  839. std::string expected(6 * 30 * 1024u, 'a');
  840. EXPECT_EQ(req.body, expected);
  841. })
  842. .Post("/multipart",
  843. [&](const Request &req, Response & /*res*/) {
  844. EXPECT_EQ(5u, req.files.size());
  845. ASSERT_TRUE(!req.has_file("???"));
  846. ASSERT_TRUE(req.body.empty());
  847. {
  848. const auto &file = req.get_file_value("text1");
  849. EXPECT_TRUE(file.filename.empty());
  850. EXPECT_EQ("text default", file.content);
  851. }
  852. {
  853. const auto &file = req.get_file_value("text2");
  854. EXPECT_TRUE(file.filename.empty());
  855. EXPECT_EQ("aωb", file.content);
  856. }
  857. {
  858. const auto &file = req.get_file_value("file1");
  859. EXPECT_EQ("hello.txt", file.filename);
  860. EXPECT_EQ("text/plain", file.content_type);
  861. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  862. }
  863. {
  864. const auto &file = req.get_file_value("file3");
  865. EXPECT_TRUE(file.filename.empty());
  866. EXPECT_EQ("application/octet-stream", file.content_type);
  867. EXPECT_EQ(0u, file.content.size());
  868. }
  869. })
  870. .Post("/empty",
  871. [&](const Request &req, Response &res) {
  872. EXPECT_EQ(req.body, "");
  873. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  874. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  875. res.set_content("empty", "text/plain");
  876. })
  877. .Post("/empty-no-content-type",
  878. [&](const Request &req, Response &res) {
  879. EXPECT_EQ(req.body, "");
  880. EXPECT_FALSE(req.has_header("Content-Type"));
  881. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  882. res.set_content("empty-no-content-type", "text/plain");
  883. })
  884. .Put("/empty-no-content-type",
  885. [&](const Request &req, Response &res) {
  886. EXPECT_EQ(req.body, "");
  887. EXPECT_FALSE(req.has_header("Content-Type"));
  888. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  889. res.set_content("empty-no-content-type", "text/plain");
  890. })
  891. .Put("/put",
  892. [&](const Request &req, Response &res) {
  893. EXPECT_EQ(req.body, "PUT");
  894. res.set_content(req.body, "text/plain");
  895. })
  896. .Put("/put-large",
  897. [&](const Request &req, Response &res) {
  898. EXPECT_EQ(req.body, LARGE_DATA);
  899. res.set_content(req.body, "text/plain");
  900. })
  901. .Patch("/patch",
  902. [&](const Request &req, Response &res) {
  903. EXPECT_EQ(req.body, "PATCH");
  904. res.set_content(req.body, "text/plain");
  905. })
  906. .Delete("/delete",
  907. [&](const Request & /*req*/, Response &res) {
  908. res.set_content("DELETE", "text/plain");
  909. })
  910. .Delete("/delete-body",
  911. [&](const Request &req, Response &res) {
  912. EXPECT_EQ(req.body, "content");
  913. res.set_content(req.body, "text/plain");
  914. })
  915. .Options(R"(\*)",
  916. [&](const Request & /*req*/, Response &res) {
  917. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  918. })
  919. .Get("/request-target",
  920. [&](const Request &req, Response & /*res*/) {
  921. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  922. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  923. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  924. })
  925. .Get("/long-query-value",
  926. [&](const Request &req, Response & /*res*/) {
  927. EXPECT_EQ(LONG_QUERY_URL, req.target);
  928. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  929. })
  930. .Get("/array-param",
  931. [&](const Request &req, Response & /*res*/) {
  932. EXPECT_EQ(3u, req.get_param_value_count("array"));
  933. EXPECT_EQ("value1", req.get_param_value("array", 0));
  934. EXPECT_EQ("value2", req.get_param_value("array", 1));
  935. EXPECT_EQ("value3", req.get_param_value("array", 2));
  936. })
  937. .Post("/validate-no-multiple-headers",
  938. [&](const Request &req, Response & /*res*/) {
  939. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  940. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  941. })
  942. .Post("/content_receiver",
  943. [&](const Request &req, Response &res,
  944. const ContentReader &content_reader) {
  945. if (req.is_multipart_form_data()) {
  946. MultipartFormDataItems files;
  947. content_reader(
  948. [&](const MultipartFormData &file) {
  949. files.push_back(file);
  950. return true;
  951. },
  952. [&](const char *data, size_t data_length) {
  953. files.back().content.append(data, data_length);
  954. return true;
  955. });
  956. EXPECT_EQ(5u, files.size());
  957. {
  958. const auto &file = get_file_value(files, "text1");
  959. EXPECT_TRUE(file.filename.empty());
  960. EXPECT_EQ("text default", file.content);
  961. }
  962. {
  963. const auto &file = get_file_value(files, "text2");
  964. EXPECT_TRUE(file.filename.empty());
  965. EXPECT_EQ("aωb", file.content);
  966. }
  967. {
  968. const auto &file = get_file_value(files, "file1");
  969. EXPECT_EQ("hello.txt", file.filename);
  970. EXPECT_EQ("text/plain", file.content_type);
  971. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  972. }
  973. {
  974. const auto &file = get_file_value(files, "file3");
  975. EXPECT_TRUE(file.filename.empty());
  976. EXPECT_EQ("application/octet-stream", file.content_type);
  977. EXPECT_EQ(0u, file.content.size());
  978. }
  979. } else {
  980. std::string body;
  981. content_reader([&](const char *data, size_t data_length) {
  982. EXPECT_EQ(data_length, 7);
  983. body.append(data, data_length);
  984. return true;
  985. });
  986. EXPECT_EQ(body, "content");
  987. res.set_content(body, "text/plain");
  988. }
  989. })
  990. .Put("/content_receiver",
  991. [&](const Request & /*req*/, Response &res,
  992. const ContentReader &content_reader) {
  993. std::string body;
  994. content_reader([&](const char *data, size_t data_length) {
  995. body.append(data, data_length);
  996. return true;
  997. });
  998. EXPECT_EQ(body, "content");
  999. res.set_content(body, "text/plain");
  1000. })
  1001. .Patch("/content_receiver",
  1002. [&](const Request & /*req*/, Response &res,
  1003. const ContentReader &content_reader) {
  1004. std::string body;
  1005. content_reader([&](const char *data, size_t data_length) {
  1006. body.append(data, data_length);
  1007. return true;
  1008. });
  1009. EXPECT_EQ(body, "content");
  1010. res.set_content(body, "text/plain");
  1011. })
  1012. .Post("/query-string-and-body",
  1013. [&](const Request &req, Response & /*res*/) {
  1014. ASSERT_TRUE(req.has_param("key"));
  1015. EXPECT_EQ(req.get_param_value("key"), "value");
  1016. EXPECT_EQ(req.body, "content");
  1017. })
  1018. .Get("/last-request",
  1019. [&](const Request &req, Response & /*res*/) {
  1020. EXPECT_EQ("close", req.get_header_value("Connection"));
  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. std::vector<std::thread> threads;
  1560. for (auto i = 0; i < 3; i++) {
  1561. threads.emplace_back(thread([&]() {
  1562. auto res = cli_.Get("/streamed-cancel",
  1563. [&](const char *, uint64_t) { return true; });
  1564. ASSERT_TRUE(res == nullptr);
  1565. }));
  1566. }
  1567. std::this_thread::sleep_for(std::chrono::seconds(1));
  1568. while (cli_.is_socket_open()) {
  1569. cli_.stop();
  1570. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1571. }
  1572. for (auto &t : threads) {
  1573. t.join();
  1574. }
  1575. }
  1576. TEST_F(ServerTest, GetWithRange1) {
  1577. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1578. ASSERT_TRUE(res != nullptr);
  1579. EXPECT_EQ(206, res->status);
  1580. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1581. EXPECT_EQ(true, res->has_header("Content-Range"));
  1582. EXPECT_EQ(std::string("def"), res->body);
  1583. }
  1584. TEST_F(ServerTest, GetWithRange2) {
  1585. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1586. ASSERT_TRUE(res != nullptr);
  1587. EXPECT_EQ(206, res->status);
  1588. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1589. EXPECT_EQ(true, res->has_header("Content-Range"));
  1590. EXPECT_EQ(std::string("bcdefg"), res->body);
  1591. }
  1592. TEST_F(ServerTest, GetWithRange3) {
  1593. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1594. ASSERT_TRUE(res != nullptr);
  1595. EXPECT_EQ(206, res->status);
  1596. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1597. EXPECT_EQ(true, res->has_header("Content-Range"));
  1598. EXPECT_EQ(std::string("a"), res->body);
  1599. }
  1600. TEST_F(ServerTest, GetWithRange4) {
  1601. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1602. ASSERT_TRUE(res != nullptr);
  1603. EXPECT_EQ(206, res->status);
  1604. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1605. EXPECT_EQ(true, res->has_header("Content-Range"));
  1606. EXPECT_EQ(std::string("fg"), res->body);
  1607. }
  1608. TEST_F(ServerTest, GetWithRangeMultipart) {
  1609. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1610. ASSERT_TRUE(res != nullptr);
  1611. EXPECT_EQ(206, res->status);
  1612. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1613. EXPECT_EQ(false, res->has_header("Content-Range"));
  1614. EXPECT_EQ(269, res->body.size());
  1615. }
  1616. TEST_F(ServerTest, GetStreamedChunked) {
  1617. auto res = cli_.Get("/streamed-chunked");
  1618. ASSERT_TRUE(res != nullptr);
  1619. EXPECT_EQ(200, res->status);
  1620. EXPECT_EQ(std::string("123456789"), res->body);
  1621. }
  1622. TEST_F(ServerTest, GetStreamedChunked2) {
  1623. auto res = cli_.Get("/streamed-chunked2");
  1624. ASSERT_TRUE(res != nullptr);
  1625. EXPECT_EQ(200, res->status);
  1626. EXPECT_EQ(std::string("123456789"), res->body);
  1627. }
  1628. TEST_F(ServerTest, LargeChunkedPost) {
  1629. Request req;
  1630. req.method = "POST";
  1631. req.path = "/large-chunked";
  1632. std::string host_and_port;
  1633. host_and_port += HOST;
  1634. host_and_port += ":";
  1635. host_and_port += std::to_string(PORT);
  1636. req.headers.emplace("Host", host_and_port.c_str());
  1637. req.headers.emplace("Accept", "*/*");
  1638. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1639. req.headers.emplace("Content-Type", "text/plain");
  1640. req.headers.emplace("Content-Length", "0");
  1641. req.headers.emplace("Transfer-Encoding", "chunked");
  1642. std::string long_string(30 * 1024u, 'a');
  1643. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1644. // Attempt to make a large enough post to exceed OS buffers, to test that
  1645. // the server handles short reads if the full chunk data isn't available.
  1646. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1647. auto res = std::make_shared<Response>();
  1648. auto ret = cli_.send(req, *res);
  1649. ASSERT_TRUE(ret);
  1650. EXPECT_EQ(200, res->status);
  1651. }
  1652. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1653. auto res = cli_.Get("/remote_addr");
  1654. ASSERT_TRUE(res != nullptr);
  1655. EXPECT_EQ(200, res->status);
  1656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1657. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1658. }
  1659. TEST_F(ServerTest, HTTPResponseSplitting) {
  1660. auto res = cli_.Get("/http_response_splitting");
  1661. ASSERT_TRUE(res != nullptr);
  1662. EXPECT_EQ(200, res->status);
  1663. }
  1664. TEST_F(ServerTest, SlowRequest) {
  1665. request_threads_.push_back(
  1666. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1667. request_threads_.push_back(
  1668. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1669. request_threads_.push_back(
  1670. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1671. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1672. }
  1673. TEST_F(ServerTest, SlowPost) {
  1674. char buffer[64 * 1024];
  1675. memset(buffer, 0x42, sizeof(buffer));
  1676. auto res = cli_.Post(
  1677. "/slowpost", 64 * 1024 * 1024,
  1678. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1679. sink.write(buffer, sizeof(buffer));
  1680. return true;
  1681. },
  1682. "text/plain");
  1683. ASSERT_TRUE(res != nullptr);
  1684. EXPECT_EQ(200, res->status);
  1685. cli_.set_write_timeout(0, 0);
  1686. res = cli_.Post(
  1687. "/slowpost", 64 * 1024 * 1024,
  1688. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1689. sink.write(buffer, sizeof(buffer));
  1690. return true;
  1691. },
  1692. "text/plain");
  1693. ASSERT_FALSE(res != nullptr);
  1694. }
  1695. TEST_F(ServerTest, Put) {
  1696. auto res = cli_.Put("/put", "PUT", "text/plain");
  1697. ASSERT_TRUE(res != nullptr);
  1698. EXPECT_EQ(200, res->status);
  1699. EXPECT_EQ("PUT", res->body);
  1700. }
  1701. TEST_F(ServerTest, PutWithContentProvider) {
  1702. auto res = cli_.Put(
  1703. "/put", 3,
  1704. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1705. EXPECT_TRUE(sink.is_writable());
  1706. sink.os << "PUT";
  1707. return true;
  1708. },
  1709. "text/plain");
  1710. ASSERT_TRUE(res != nullptr);
  1711. EXPECT_EQ(200, res->status);
  1712. EXPECT_EQ("PUT", res->body);
  1713. }
  1714. TEST_F(ServerTest, PostWithContentProviderAbort) {
  1715. auto res = cli_.Post(
  1716. "/post", 42,
  1717. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1718. return false;
  1719. },
  1720. "text/plain");
  1721. ASSERT_TRUE(res == nullptr);
  1722. }
  1723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1724. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1725. cli_.set_compress(true);
  1726. auto res = cli_.Put(
  1727. "/put", 3,
  1728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1729. EXPECT_TRUE(sink.is_writable());
  1730. sink.os << "PUT";
  1731. return true;
  1732. },
  1733. "text/plain");
  1734. ASSERT_TRUE(res != nullptr);
  1735. EXPECT_EQ(200, res->status);
  1736. EXPECT_EQ("PUT", res->body);
  1737. }
  1738. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  1739. cli_.set_compress(true);
  1740. auto res = cli_.Post(
  1741. "/post", 42,
  1742. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1743. return false;
  1744. },
  1745. "text/plain");
  1746. ASSERT_TRUE(res == nullptr);
  1747. }
  1748. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1749. cli_.set_compress(true);
  1750. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  1751. ASSERT_TRUE(res != nullptr);
  1752. EXPECT_EQ(200, res->status);
  1753. EXPECT_EQ(LARGE_DATA, res->body);
  1754. }
  1755. TEST_F(ServerTest, PutContentWithDeflate) {
  1756. cli_.set_compress(false);
  1757. httplib::Headers headers;
  1758. headers.emplace("Content-Encoding", "deflate");
  1759. // PUT in deflate format:
  1760. auto res = cli_.Put("/put", headers,
  1761. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  1762. ASSERT_TRUE(res != nullptr);
  1763. EXPECT_EQ(200, res->status);
  1764. EXPECT_EQ("PUT", res->body);
  1765. }
  1766. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  1767. httplib::Headers headers;
  1768. headers.emplace("Accept-Encoding", "gzip, deflate");
  1769. auto res = cli_.Get("/streamed-chunked", headers);
  1770. ASSERT_TRUE(res != nullptr);
  1771. EXPECT_EQ(200, res->status);
  1772. EXPECT_EQ(std::string("123456789"), res->body);
  1773. }
  1774. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  1775. httplib::Headers headers;
  1776. headers.emplace("Accept-Encoding", "gzip, deflate");
  1777. auto res = cli_.Get("/streamed-chunked2", headers);
  1778. ASSERT_TRUE(res != nullptr);
  1779. EXPECT_EQ(200, res->status);
  1780. EXPECT_EQ(std::string("123456789"), res->body);
  1781. }
  1782. #endif
  1783. TEST_F(ServerTest, Patch) {
  1784. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1785. ASSERT_TRUE(res != nullptr);
  1786. EXPECT_EQ(200, res->status);
  1787. EXPECT_EQ("PATCH", res->body);
  1788. }
  1789. TEST_F(ServerTest, Delete) {
  1790. auto res = cli_.Delete("/delete");
  1791. ASSERT_TRUE(res != nullptr);
  1792. EXPECT_EQ(200, res->status);
  1793. EXPECT_EQ("DELETE", res->body);
  1794. }
  1795. TEST_F(ServerTest, DeleteContentReceiver) {
  1796. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  1797. ASSERT_TRUE(res != nullptr);
  1798. EXPECT_EQ(200, res->status);
  1799. EXPECT_EQ("content", res->body);
  1800. }
  1801. TEST_F(ServerTest, Options) {
  1802. auto res = cli_.Options("*");
  1803. ASSERT_TRUE(res != nullptr);
  1804. EXPECT_EQ(200, res->status);
  1805. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1806. EXPECT_TRUE(res->body.empty());
  1807. }
  1808. TEST_F(ServerTest, URL) {
  1809. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1810. ASSERT_TRUE(res != nullptr);
  1811. EXPECT_EQ(200, res->status);
  1812. }
  1813. TEST_F(ServerTest, ArrayParam) {
  1814. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  1815. ASSERT_TRUE(res != nullptr);
  1816. EXPECT_EQ(200, res->status);
  1817. }
  1818. TEST_F(ServerTest, NoMultipleHeaders) {
  1819. Headers headers = {{"Content-Length", "5"}};
  1820. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  1821. "text/plain");
  1822. ASSERT_TRUE(res != nullptr);
  1823. EXPECT_EQ(200, res->status);
  1824. }
  1825. TEST_F(ServerTest, PostContentReceiver) {
  1826. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1827. ASSERT_TRUE(res != nullptr);
  1828. ASSERT_EQ(200, res->status);
  1829. ASSERT_EQ("content", res->body);
  1830. }
  1831. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  1832. MultipartFormDataItems items = {
  1833. {"text1", "text default", "", ""},
  1834. {"text2", "aωb", "", ""},
  1835. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1836. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1837. {"file3", "", "", "application/octet-stream"},
  1838. };
  1839. auto res = cli_.Post("/content_receiver", items);
  1840. ASSERT_TRUE(res != nullptr);
  1841. EXPECT_EQ(200, res->status);
  1842. }
  1843. TEST_F(ServerTest, PostContentReceiverGzip) {
  1844. cli_.set_compress(true);
  1845. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  1846. ASSERT_TRUE(res != nullptr);
  1847. ASSERT_EQ(200, res->status);
  1848. ASSERT_EQ("content", res->body);
  1849. }
  1850. TEST_F(ServerTest, PutContentReceiver) {
  1851. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  1852. ASSERT_TRUE(res != nullptr);
  1853. ASSERT_EQ(200, res->status);
  1854. ASSERT_EQ("content", res->body);
  1855. }
  1856. TEST_F(ServerTest, PatchContentReceiver) {
  1857. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  1858. ASSERT_TRUE(res != nullptr);
  1859. ASSERT_EQ(200, res->status);
  1860. ASSERT_EQ("content", res->body);
  1861. }
  1862. TEST_F(ServerTest, PostQueryStringAndBody) {
  1863. auto res =
  1864. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  1865. ASSERT_TRUE(res != nullptr);
  1866. ASSERT_EQ(200, res->status);
  1867. }
  1868. TEST_F(ServerTest, HTTP2Magic) {
  1869. Request req;
  1870. req.method = "PRI";
  1871. req.path = "*";
  1872. req.body = "SM";
  1873. auto res = std::make_shared<Response>();
  1874. auto ret = cli_.send(req, *res);
  1875. ASSERT_TRUE(ret);
  1876. EXPECT_EQ(400, res->status);
  1877. }
  1878. TEST_F(ServerTest, KeepAlive) {
  1879. auto res = cli_.Get("/hi");
  1880. ASSERT_TRUE(res != nullptr);
  1881. EXPECT_EQ(200, res->status);
  1882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1883. EXPECT_EQ("Hello World!", res->body);
  1884. res = cli_.Get("/hi");
  1885. ASSERT_TRUE(res != nullptr);
  1886. EXPECT_EQ(200, res->status);
  1887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1888. EXPECT_EQ("Hello World!", res->body);
  1889. res = cli_.Get("/hi");
  1890. ASSERT_TRUE(res != nullptr);
  1891. EXPECT_EQ(200, res->status);
  1892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1893. EXPECT_EQ("Hello World!", res->body);
  1894. res = cli_.Get("/not-exist");
  1895. ASSERT_TRUE(res != nullptr);
  1896. EXPECT_EQ(404, res->status);
  1897. res = cli_.Post("/empty", "", "text/plain");
  1898. ASSERT_TRUE(res != nullptr);
  1899. EXPECT_EQ(200, res->status);
  1900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1901. EXPECT_EQ("empty", res->body);
  1902. EXPECT_EQ("close", res->get_header_value("Connection"));
  1903. res = cli_.Post(
  1904. "/empty", 0, [&](size_t, size_t, httplib::DataSink &) { return true; },
  1905. "text/plain");
  1906. ASSERT_TRUE(res != nullptr);
  1907. EXPECT_EQ(200, res->status);
  1908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1909. EXPECT_EQ("empty", res->body);
  1910. cli_.set_keep_alive(false);
  1911. res = cli_.Get("/last-request");
  1912. ASSERT_TRUE(res != nullptr);
  1913. EXPECT_EQ(200, res->status);
  1914. EXPECT_EQ("close", res->get_header_value("Connection"));
  1915. }
  1916. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1917. TEST_F(ServerTest, Gzip) {
  1918. Headers headers;
  1919. headers.emplace("Accept-Encoding", "gzip, deflate");
  1920. auto res = cli_.Get("/gzip", headers);
  1921. ASSERT_TRUE(res != nullptr);
  1922. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1923. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1924. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1925. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1926. "7890123456789012345678901234567890",
  1927. res->body);
  1928. EXPECT_EQ(200, res->status);
  1929. }
  1930. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  1931. Headers headers;
  1932. auto res = cli_.Get("/gzip", headers);
  1933. ASSERT_TRUE(res != nullptr);
  1934. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  1935. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1936. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1937. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1938. "7890123456789012345678901234567890",
  1939. res->body);
  1940. EXPECT_EQ(200, res->status);
  1941. }
  1942. TEST_F(ServerTest, GzipWithContentReceiver) {
  1943. Headers headers;
  1944. headers.emplace("Accept-Encoding", "gzip, deflate");
  1945. std::string body;
  1946. auto res =
  1947. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1948. EXPECT_EQ(data_length, 100);
  1949. body.append(data, data_length);
  1950. return true;
  1951. });
  1952. ASSERT_TRUE(res != nullptr);
  1953. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1955. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1956. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1957. "7890123456789012345678901234567890",
  1958. body);
  1959. EXPECT_EQ(200, res->status);
  1960. }
  1961. TEST_F(ServerTest, GzipWithoutDecompressing) {
  1962. Headers headers;
  1963. headers.emplace("Accept-Encoding", "gzip, deflate");
  1964. cli_.set_decompress(false);
  1965. auto res = cli_.Get("/gzip", headers);
  1966. ASSERT_TRUE(res != nullptr);
  1967. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  1968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1969. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  1970. EXPECT_EQ(33, res->body.size());
  1971. EXPECT_EQ(200, res->status);
  1972. }
  1973. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  1974. Headers headers;
  1975. std::string body;
  1976. auto res =
  1977. cli_.Get("/gzip", headers, [&](const char *data, uint64_t data_length) {
  1978. EXPECT_EQ(data_length, 100);
  1979. body.append(data, data_length);
  1980. return true;
  1981. });
  1982. ASSERT_TRUE(res != nullptr);
  1983. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  1984. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1985. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1986. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  1987. "7890123456789012345678901234567890",
  1988. body);
  1989. EXPECT_EQ(200, res->status);
  1990. }
  1991. TEST_F(ServerTest, NoGzip) {
  1992. Headers headers;
  1993. headers.emplace("Accept-Encoding", "gzip, deflate");
  1994. auto res = cli_.Get("/nogzip", headers);
  1995. ASSERT_TRUE(res != nullptr);
  1996. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  1997. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  1998. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  1999. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2000. "7890123456789012345678901234567890",
  2001. res->body);
  2002. EXPECT_EQ(200, res->status);
  2003. }
  2004. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2005. Headers headers;
  2006. headers.emplace("Accept-Encoding", "gzip, deflate");
  2007. std::string body;
  2008. auto res =
  2009. cli_.Get("/nogzip", headers, [&](const char *data, uint64_t data_length) {
  2010. EXPECT_EQ(data_length, 100);
  2011. body.append(data, data_length);
  2012. return true;
  2013. });
  2014. ASSERT_TRUE(res != nullptr);
  2015. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2016. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2017. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2018. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2019. "7890123456789012345678901234567890",
  2020. body);
  2021. EXPECT_EQ(200, res->status);
  2022. }
  2023. TEST_F(ServerTest, MultipartFormDataGzip) {
  2024. MultipartFormDataItems items = {
  2025. {"key1", "test", "", ""},
  2026. {"key2", "--abcdefg123", "", ""},
  2027. };
  2028. cli_.set_compress(true);
  2029. auto res = cli_.Post("/gzipmultipart", items);
  2030. ASSERT_TRUE(res != nullptr);
  2031. EXPECT_EQ(200, res->status);
  2032. }
  2033. #endif
  2034. // Sends a raw request to a server listening at HOST:PORT.
  2035. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2036. std::string *resp = nullptr) {
  2037. auto client_sock =
  2038. detail::create_client_socket(HOST, PORT, false, nullptr,
  2039. /*timeout_sec=*/5, 0, std::string());
  2040. if (client_sock == INVALID_SOCKET) { return false; }
  2041. auto ret = detail::process_client_socket(
  2042. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2043. if (req.size() !=
  2044. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2045. return false;
  2046. }
  2047. char buf[512];
  2048. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2049. while (line_reader.getline()) {
  2050. if (resp) { *resp += line_reader.ptr(); }
  2051. }
  2052. return true;
  2053. });
  2054. detail::close_socket(client_sock);
  2055. return ret;
  2056. }
  2057. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2058. Server svr;
  2059. std::string header_value;
  2060. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2061. header_value = req.get_header_value("foo");
  2062. res.set_content("ok", "text/plain");
  2063. });
  2064. thread t = thread([&] { svr.listen(HOST, PORT); });
  2065. while (!svr.is_running()) {
  2066. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2067. }
  2068. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2069. // like characters are not treated the same - use vertical tab and escape.
  2070. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2071. "foo: \t \v bar \e\t \r\n"
  2072. "Connection: close\r\n"
  2073. "\r\n";
  2074. ASSERT_TRUE(send_request(5, req));
  2075. svr.stop();
  2076. t.join();
  2077. EXPECT_EQ(header_value, "\v bar \e");
  2078. }
  2079. // Sends a raw request and verifies that there isn't a crash or exception.
  2080. static void test_raw_request(const std::string &req,
  2081. std::string *out = nullptr) {
  2082. Server svr;
  2083. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2084. res.set_content("ok", "text/plain");
  2085. });
  2086. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2087. res.set_content("ok", "text/plain");
  2088. });
  2089. // Server read timeout must be longer than the client read timeout for the
  2090. // bug to reproduce, probably to force the server to process a request
  2091. // without a trailing blank line.
  2092. const time_t client_read_timeout_sec = 1;
  2093. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  2094. bool listen_thread_ok = false;
  2095. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2096. while (!svr.is_running()) {
  2097. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2098. }
  2099. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2100. svr.stop();
  2101. t.join();
  2102. EXPECT_TRUE(listen_thread_ok);
  2103. }
  2104. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2105. // A certain header line causes an exception if the header property is parsed
  2106. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2107. test_raw_request(
  2108. "GET /hi HTTP/1.1\r\n"
  2109. " : "
  2110. " "
  2111. " ");
  2112. }
  2113. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2114. // A certain header line causes an exception if the header property *name* is
  2115. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2116. // greedy matcher and requires backtracking when there are a lot of ":"
  2117. // characters.
  2118. // This occurs with libc++ but not libstdc++.
  2119. test_raw_request(
  2120. "GET /hi HTTP/1.1\r\n"
  2121. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2122. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2123. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2124. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2125. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2126. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2127. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2128. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2129. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2130. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2131. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2132. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2133. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2134. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2135. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2136. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2137. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2138. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2139. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2140. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2141. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2142. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2143. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2144. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2145. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2146. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2147. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2148. "&&&%%%");
  2149. }
  2150. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2151. // Make sure this doesn't crash the server.
  2152. // In a previous version of the header line regex, the "\r" rendered the line
  2153. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2154. // a new position where the leading white space ended and the field value
  2155. // began.
  2156. // The crash occurs with libc++ but not libstdc++.
  2157. test_raw_request("GET /hi HTTP/1.1\r\n"
  2158. "a:" +
  2159. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2160. "\r\n"
  2161. "\r\n");
  2162. }
  2163. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2164. std::string out;
  2165. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2166. "Content-Type: text/plain\r\n"
  2167. "Transfer-Encoding: chunked\r\n"
  2168. "\r\n"
  2169. "nothex\r\n",
  2170. &out);
  2171. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2172. }
  2173. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2174. std::string out;
  2175. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2176. "Content-Type: text/plain\r\n"
  2177. "Transfer-Encoding: chunked\r\n"
  2178. "\r\n"
  2179. "3\r\n"
  2180. "xyz\r\n"
  2181. "NaN\r\n",
  2182. &out);
  2183. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2184. }
  2185. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2186. std::string out;
  2187. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2188. "Content-Type: text/plain\r\n"
  2189. "Transfer-Encoding: chunked\r\n"
  2190. "\r\n"
  2191. // Length is too large for 64 bits.
  2192. "1ffffffffffffffff\r\n"
  2193. "xyz\r\n",
  2194. &out);
  2195. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2196. }
  2197. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2198. test_raw_request("GET /hi HTTP/1.1\r\n"
  2199. "Content-Type: text/plain\r\n\r");
  2200. }
  2201. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2202. Server svr;
  2203. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2204. res.set_header("Cache-Control", "no-cache");
  2205. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2206. DataSink &sink) {
  2207. char buffer[27];
  2208. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2209. sink.write(buffer, size);
  2210. std::this_thread::sleep_for(std::chrono::seconds(1));
  2211. return true;
  2212. });
  2213. });
  2214. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2215. while (!svr.is_running()) {
  2216. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2217. }
  2218. Client client(HOST, PORT);
  2219. const Headers headers = {{"Accept", "text/event-stream"}};
  2220. auto get_thread = std::thread([&client, &headers]() {
  2221. std::shared_ptr<Response> res = client.Get(
  2222. "/events", headers,
  2223. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2224. });
  2225. // Give GET time to get a few messages.
  2226. std::this_thread::sleep_for(std::chrono::seconds(2));
  2227. svr.stop();
  2228. listen_thread.join();
  2229. get_thread.join();
  2230. ASSERT_FALSE(svr.is_running());
  2231. }
  2232. TEST(MountTest, Unmount) {
  2233. Server svr;
  2234. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2235. while (!svr.is_running()) {
  2236. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2237. }
  2238. // Give GET time to get a few messages.
  2239. std::this_thread::sleep_for(std::chrono::seconds(1));
  2240. Client cli("localhost", PORT);
  2241. svr.set_mount_point("/mount2", "./www2");
  2242. auto res = cli.Get("/");
  2243. ASSERT_TRUE(res != nullptr);
  2244. EXPECT_EQ(404, res->status);
  2245. res = cli.Get("/mount2/dir/test.html");
  2246. ASSERT_TRUE(res != nullptr);
  2247. EXPECT_EQ(200, res->status);
  2248. svr.set_mount_point("/", "./www");
  2249. res = cli.Get("/dir/");
  2250. ASSERT_TRUE(res != nullptr);
  2251. EXPECT_EQ(200, res->status);
  2252. svr.remove_mount_point("/");
  2253. res = cli.Get("/dir/");
  2254. ASSERT_TRUE(res != nullptr);
  2255. EXPECT_EQ(404, res->status);
  2256. svr.remove_mount_point("/mount2");
  2257. res = cli.Get("/mount2/dir/test.html");
  2258. ASSERT_TRUE(res != nullptr);
  2259. EXPECT_EQ(404, res->status);
  2260. svr.stop();
  2261. listen_thread.join();
  2262. ASSERT_FALSE(svr.is_running());
  2263. }
  2264. TEST(ExceptionTest, ThrowExceptionInHandler) {
  2265. Server svr;
  2266. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2267. throw std::runtime_error("exception...");
  2268. res.set_content("Hello World!", "text/plain");
  2269. });
  2270. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2271. while (!svr.is_running()) {
  2272. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2273. }
  2274. // Give GET time to get a few messages.
  2275. std::this_thread::sleep_for(std::chrono::seconds(1));
  2276. Client cli("localhost", PORT);
  2277. auto res = cli.Get("/hi");
  2278. ASSERT_TRUE(res != nullptr);
  2279. EXPECT_EQ(500, res->status);
  2280. ASSERT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2281. svr.stop();
  2282. listen_thread.join();
  2283. ASSERT_FALSE(svr.is_running());
  2284. }
  2285. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  2286. protected:
  2287. ServerTestWithAI_PASSIVE()
  2288. : cli_(HOST, PORT)
  2289. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2290. ,
  2291. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2292. #endif
  2293. {
  2294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2295. cli_.enable_server_certificate_verification(false);
  2296. #endif
  2297. }
  2298. virtual void SetUp() {
  2299. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2300. res.set_content("Hello World!", "text/plain");
  2301. });
  2302. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  2303. while (!svr_.is_running()) {
  2304. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2305. }
  2306. }
  2307. virtual void TearDown() {
  2308. svr_.stop();
  2309. t_.join();
  2310. }
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli_;
  2313. SSLServer svr_;
  2314. #else
  2315. Client cli_;
  2316. Server svr_;
  2317. #endif
  2318. thread t_;
  2319. };
  2320. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  2321. auto res = cli_.Get("/hi");
  2322. ASSERT_TRUE(res != nullptr);
  2323. EXPECT_EQ(200, res->status);
  2324. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2325. EXPECT_EQ("Hello World!", res->body);
  2326. }
  2327. class ServerUpDownTest : public ::testing::Test {
  2328. protected:
  2329. ServerUpDownTest() : cli_(HOST, PORT) {}
  2330. virtual void SetUp() {
  2331. t_ = thread([&]() {
  2332. svr_.bind_to_any_port(HOST);
  2333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2334. ASSERT_TRUE(svr_.listen_after_bind());
  2335. });
  2336. while (!svr_.is_running()) {
  2337. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2338. }
  2339. }
  2340. virtual void TearDown() {
  2341. svr_.stop();
  2342. t_.join();
  2343. }
  2344. Client cli_;
  2345. Server svr_;
  2346. thread t_;
  2347. };
  2348. TEST_F(ServerUpDownTest, QuickStartStop) {
  2349. // Should not crash, especially when run with
  2350. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  2351. }
  2352. class PayloadMaxLengthTest : public ::testing::Test {
  2353. protected:
  2354. PayloadMaxLengthTest()
  2355. : cli_(HOST, PORT)
  2356. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2357. ,
  2358. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2359. #endif
  2360. {
  2361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2362. cli_.enable_server_certificate_verification(false);
  2363. #endif
  2364. }
  2365. virtual void SetUp() {
  2366. svr_.set_payload_max_length(8);
  2367. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  2368. res.set_content("test", "text/plain");
  2369. });
  2370. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2371. while (!svr_.is_running()) {
  2372. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2373. }
  2374. }
  2375. virtual void TearDown() {
  2376. svr_.stop();
  2377. t_.join();
  2378. }
  2379. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2380. SSLClient cli_;
  2381. SSLServer svr_;
  2382. #else
  2383. Client cli_;
  2384. Server svr_;
  2385. #endif
  2386. thread t_;
  2387. };
  2388. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  2389. auto res = cli_.Post("/test", "123456789", "text/plain");
  2390. ASSERT_TRUE(res != nullptr);
  2391. EXPECT_EQ(413, res->status);
  2392. res = cli_.Post("/test", "12345678", "text/plain");
  2393. ASSERT_TRUE(res != nullptr);
  2394. EXPECT_EQ(200, res->status);
  2395. }
  2396. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2397. TEST(SSLClientTest, ServerNameIndication) {
  2398. SSLClient cli("httpbin.org", 443);
  2399. auto res = cli.Get("/get");
  2400. ASSERT_TRUE(res != nullptr);
  2401. ASSERT_EQ(200, res->status);
  2402. }
  2403. TEST(SSLClientTest, ServerCertificateVerification1) {
  2404. SSLClient cli("google.com");
  2405. auto res = cli.Get("/");
  2406. ASSERT_TRUE(res != nullptr);
  2407. ASSERT_EQ(301, res->status);
  2408. }
  2409. TEST(SSLClientTest, ServerCertificateVerification2) {
  2410. SSLClient cli("google.com");
  2411. cli.enable_server_certificate_verification(true);
  2412. cli.set_ca_cert_path("hello");
  2413. auto res = cli.Get("/");
  2414. ASSERT_TRUE(res == nullptr);
  2415. }
  2416. TEST(SSLClientTest, ServerCertificateVerification3) {
  2417. SSLClient cli("google.com");
  2418. cli.set_ca_cert_path(CA_CERT_FILE);
  2419. auto res = cli.Get("/");
  2420. ASSERT_TRUE(res != nullptr);
  2421. ASSERT_EQ(301, res->status);
  2422. }
  2423. TEST(SSLClientTest, WildcardHostNameMatch) {
  2424. SSLClient cli("www.youtube.com");
  2425. cli.set_ca_cert_path(CA_CERT_FILE);
  2426. cli.enable_server_certificate_verification(true);
  2427. auto res = cli.Get("/");
  2428. ASSERT_TRUE(res != nullptr);
  2429. ASSERT_EQ(200, res->status);
  2430. }
  2431. TEST(SSLClientServerTest, ClientCertPresent) {
  2432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2433. CLIENT_CA_CERT_DIR);
  2434. ASSERT_TRUE(svr.is_valid());
  2435. svr.Get("/test", [&](const Request &req, Response &res) {
  2436. res.set_content("test", "text/plain");
  2437. svr.stop();
  2438. ASSERT_TRUE(true);
  2439. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2440. ASSERT_TRUE(peer_cert != nullptr);
  2441. auto subject_name = X509_get_subject_name(peer_cert);
  2442. ASSERT_TRUE(subject_name != nullptr);
  2443. std::string common_name;
  2444. {
  2445. char name[BUFSIZ];
  2446. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2447. name, sizeof(name));
  2448. common_name.assign(name, static_cast<size_t>(name_len));
  2449. }
  2450. EXPECT_EQ("Common Name", common_name);
  2451. X509_free(peer_cert);
  2452. });
  2453. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2454. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2455. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2456. cli.enable_server_certificate_verification(false);
  2457. cli.set_connection_timeout(30);
  2458. auto res = cli.Get("/test");
  2459. ASSERT_TRUE(res != nullptr);
  2460. ASSERT_EQ(200, res->status);
  2461. t.join();
  2462. }
  2463. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  2464. X509 *server_cert;
  2465. EVP_PKEY *server_private_key;
  2466. X509_STORE *client_ca_cert_store;
  2467. X509 *client_cert;
  2468. EVP_PKEY *client_private_key;
  2469. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  2470. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2471. fclose(f);
  2472. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  2473. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2474. fclose(f);
  2475. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  2476. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2477. client_ca_cert_store = X509_STORE_new();
  2478. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  2479. X509_free(client_cert);
  2480. fclose(f);
  2481. f = fopen(CLIENT_CERT_FILE, "r+");
  2482. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2483. fclose(f);
  2484. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  2485. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2486. fclose(f);
  2487. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  2488. ASSERT_TRUE(svr.is_valid());
  2489. svr.Get("/test", [&](const Request &req, Response &res) {
  2490. res.set_content("test", "text/plain");
  2491. svr.stop();
  2492. ASSERT_TRUE(true);
  2493. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2494. ASSERT_TRUE(peer_cert != nullptr);
  2495. auto subject_name = X509_get_subject_name(peer_cert);
  2496. ASSERT_TRUE(subject_name != nullptr);
  2497. std::string common_name;
  2498. {
  2499. char name[BUFSIZ];
  2500. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2501. name, sizeof(name));
  2502. common_name.assign(name, static_cast<size_t>(name_len));
  2503. }
  2504. EXPECT_EQ("Common Name", common_name);
  2505. X509_free(peer_cert);
  2506. });
  2507. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2508. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2509. httplib::SSLClient cli(HOST, PORT, client_cert, client_private_key);
  2510. cli.enable_server_certificate_verification(false);
  2511. cli.set_connection_timeout(30);
  2512. auto res = cli.Get("/test");
  2513. ASSERT_TRUE(res != nullptr);
  2514. ASSERT_EQ(200, res->status);
  2515. X509_free(server_cert);
  2516. EVP_PKEY_free(server_private_key);
  2517. X509_free(client_cert);
  2518. EVP_PKEY_free(client_private_key);
  2519. t.join();
  2520. }
  2521. TEST(SSLClientServerTest, ClientCertMissing) {
  2522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2523. CLIENT_CA_CERT_DIR);
  2524. ASSERT_TRUE(svr.is_valid());
  2525. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  2526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2527. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2528. httplib::SSLClient cli(HOST, PORT);
  2529. auto res = cli.Get("/test");
  2530. cli.set_connection_timeout(30);
  2531. ASSERT_TRUE(res == nullptr);
  2532. svr.stop();
  2533. t.join();
  2534. }
  2535. TEST(SSLClientServerTest, TrustDirOptional) {
  2536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2537. ASSERT_TRUE(svr.is_valid());
  2538. svr.Get("/test", [&](const Request &, Response &res) {
  2539. res.set_content("test", "text/plain");
  2540. svr.stop();
  2541. });
  2542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2543. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2544. httplib::SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2545. cli.enable_server_certificate_verification(false);
  2546. cli.set_connection_timeout(30);
  2547. auto res = cli.Get("/test");
  2548. ASSERT_TRUE(res != nullptr);
  2549. ASSERT_EQ(200, res->status);
  2550. t.join();
  2551. }
  2552. #endif
  2553. #ifdef _WIN32
  2554. TEST(CleanupTest, WSACleanup) {
  2555. int ret = WSACleanup();
  2556. ASSERT_EQ(0, ret);
  2557. }
  2558. #endif
  2559. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2560. TEST(InvalidScheme, SimpleInterface) {
  2561. httplib::Client2 cli("scheme://yahoo.com");
  2562. ASSERT_FALSE(cli.is_valid());
  2563. }
  2564. TEST(NoScheme, SimpleInterface) {
  2565. httplib::Client2 cli("yahoo.com");
  2566. ASSERT_FALSE(cli.is_valid());
  2567. }
  2568. TEST(YahooRedirectTest2, SimpleInterface) {
  2569. httplib::Client2 cli("http://yahoo.com");
  2570. auto res = cli.Get("/");
  2571. ASSERT_TRUE(res != nullptr);
  2572. EXPECT_EQ(301, res->status);
  2573. cli.set_follow_location(true);
  2574. res = cli.Get("/");
  2575. ASSERT_TRUE(res != nullptr);
  2576. EXPECT_EQ(200, res->status);
  2577. }
  2578. TEST(YahooRedirectTest3, SimpleInterface) {
  2579. httplib::Client2 cli("https://yahoo.com");
  2580. auto res = cli.Get("/");
  2581. ASSERT_TRUE(res != nullptr);
  2582. EXPECT_EQ(301, res->status);
  2583. cli.set_follow_location(true);
  2584. res = cli.Get("/");
  2585. ASSERT_TRUE(res != nullptr);
  2586. EXPECT_EQ(200, res->status);
  2587. }
  2588. #if 0
  2589. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  2590. auto res =
  2591. httplib::Client2("https://httpbin.org")
  2592. .set_follow_location(true)
  2593. .Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  2594. ASSERT_TRUE(res != nullptr);
  2595. EXPECT_EQ(200, res->status);
  2596. }
  2597. #endif
  2598. #endif