test.cc 98 KB

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