test.cc 91 KB

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