test.cc 89 KB

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