test.cc 89 KB

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