test.cc 93 KB

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