test.cc 95 KB

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