test.cc 101 KB

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