test.cc 98 KB

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