test.cc 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522
  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. if (!request_threads_.empty()) {
  1155. std::this_thread::sleep_for(std::chrono::seconds(1));
  1156. for (auto &t : request_threads_) {
  1157. t.join();
  1158. }
  1159. }
  1160. t_.join();
  1161. }
  1162. map<string, string> persons_;
  1163. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1164. SSLClient cli_;
  1165. SSLServer svr_;
  1166. #else
  1167. Client cli_;
  1168. Server svr_;
  1169. #endif
  1170. thread t_;
  1171. std::vector<thread> request_threads_;
  1172. };
  1173. TEST_F(ServerTest, GetMethod200) {
  1174. auto res = cli_.Get("/hi");
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("HTTP/1.1", res->version);
  1177. EXPECT_EQ(200, res->status);
  1178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1179. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1180. EXPECT_EQ("Hello World!", res->body);
  1181. }
  1182. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1183. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1184. ASSERT_TRUE(res);
  1185. EXPECT_EQ("HTTP/1.1", res->version);
  1186. EXPECT_EQ(200, res->status);
  1187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1188. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1189. EXPECT_EQ("Hello World!", res->body);
  1190. }
  1191. TEST_F(ServerTest, GetMethod302) {
  1192. auto res = cli_.Get("/");
  1193. ASSERT_TRUE(res);
  1194. EXPECT_EQ(302, res->status);
  1195. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1196. }
  1197. TEST_F(ServerTest, GetMethod302Redirect) {
  1198. cli_.set_follow_location(true);
  1199. auto res = cli_.Get("/");
  1200. ASSERT_TRUE(res);
  1201. EXPECT_EQ(200, res->status);
  1202. EXPECT_EQ("Hello World!", res->body);
  1203. }
  1204. TEST_F(ServerTest, GetMethod404) {
  1205. auto res = cli_.Get("/invalid");
  1206. ASSERT_TRUE(res);
  1207. EXPECT_EQ(404, res->status);
  1208. }
  1209. TEST_F(ServerTest, HeadMethod200) {
  1210. auto res = cli_.Head("/hi");
  1211. ASSERT_TRUE(res);
  1212. EXPECT_EQ(200, res->status);
  1213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1214. EXPECT_TRUE(res->body.empty());
  1215. }
  1216. TEST_F(ServerTest, HeadMethod200Static) {
  1217. auto res = cli_.Head("/mount/dir/index.html");
  1218. ASSERT_TRUE(res);
  1219. EXPECT_EQ(200, res->status);
  1220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1221. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1222. EXPECT_TRUE(res->body.empty());
  1223. }
  1224. TEST_F(ServerTest, HeadMethod404) {
  1225. auto res = cli_.Head("/invalid");
  1226. ASSERT_TRUE(res);
  1227. EXPECT_EQ(404, res->status);
  1228. EXPECT_TRUE(res->body.empty());
  1229. }
  1230. TEST_F(ServerTest, GetMethodPersonJohn) {
  1231. auto res = cli_.Get("/person/john");
  1232. ASSERT_TRUE(res);
  1233. EXPECT_EQ(200, res->status);
  1234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1235. EXPECT_EQ("programmer", res->body);
  1236. }
  1237. TEST_F(ServerTest, PostMethod1) {
  1238. auto res = cli_.Get("/person/john1");
  1239. ASSERT_TRUE(res);
  1240. ASSERT_EQ(404, res->status);
  1241. res = cli_.Post("/person", "name=john1&note=coder",
  1242. "application/x-www-form-urlencoded");
  1243. ASSERT_TRUE(res);
  1244. ASSERT_EQ(200, res->status);
  1245. res = cli_.Get("/person/john1");
  1246. ASSERT_TRUE(res);
  1247. ASSERT_EQ(200, res->status);
  1248. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1249. ASSERT_EQ("coder", res->body);
  1250. }
  1251. TEST_F(ServerTest, PostMethod2) {
  1252. auto res = cli_.Get("/person/john2");
  1253. ASSERT_TRUE(res);
  1254. ASSERT_EQ(404, res->status);
  1255. Params params;
  1256. params.emplace("name", "john2");
  1257. params.emplace("note", "coder");
  1258. res = cli_.Post("/person", params);
  1259. ASSERT_TRUE(res);
  1260. ASSERT_EQ(200, res->status);
  1261. res = cli_.Get("/person/john2");
  1262. ASSERT_TRUE(res);
  1263. ASSERT_EQ(200, res->status);
  1264. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1265. ASSERT_EQ("coder", res->body);
  1266. }
  1267. TEST_F(ServerTest, PutMethod3) {
  1268. auto res = cli_.Get("/person/john3");
  1269. ASSERT_TRUE(res);
  1270. ASSERT_EQ(404, res->status);
  1271. Params params;
  1272. params.emplace("name", "john3");
  1273. params.emplace("note", "coder");
  1274. res = cli_.Put("/person", params);
  1275. ASSERT_TRUE(res);
  1276. ASSERT_EQ(200, res->status);
  1277. res = cli_.Get("/person/john3");
  1278. ASSERT_TRUE(res);
  1279. ASSERT_EQ(200, res->status);
  1280. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1281. ASSERT_EQ("coder", res->body);
  1282. }
  1283. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1284. Params params;
  1285. params.emplace("json", JSON_DATA);
  1286. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1287. ASSERT_TRUE(res);
  1288. ASSERT_EQ(200, res->status);
  1289. ASSERT_EQ(JSON_DATA, res->body);
  1290. }
  1291. TEST_F(ServerTest, PostEmptyContent) {
  1292. auto res = cli_.Post("/empty", "", "text/plain");
  1293. ASSERT_TRUE(res);
  1294. ASSERT_EQ(200, res->status);
  1295. ASSERT_EQ("empty", res->body);
  1296. }
  1297. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1298. auto res = cli_.Post("/empty-no-content-type");
  1299. ASSERT_TRUE(res);
  1300. ASSERT_EQ(200, res->status);
  1301. ASSERT_EQ("empty-no-content-type", res->body);
  1302. }
  1303. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1304. auto res = cli_.Put("/empty-no-content-type");
  1305. ASSERT_TRUE(res);
  1306. ASSERT_EQ(200, res->status);
  1307. ASSERT_EQ("empty-no-content-type", res->body);
  1308. }
  1309. TEST_F(ServerTest, GetMethodDir) {
  1310. auto res = cli_.Get("/dir/");
  1311. ASSERT_TRUE(res);
  1312. EXPECT_EQ(200, res->status);
  1313. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1314. auto body = R"(<html>
  1315. <head>
  1316. </head>
  1317. <body>
  1318. <a href="/dir/test.html">Test</a>
  1319. <a href="/hi">hi</a>
  1320. </body>
  1321. </html>
  1322. )";
  1323. EXPECT_EQ(body, res->body);
  1324. }
  1325. TEST_F(ServerTest, GetMethodDirTest) {
  1326. auto res = cli_.Get("/dir/test.html");
  1327. ASSERT_TRUE(res);
  1328. EXPECT_EQ(200, res->status);
  1329. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1330. EXPECT_EQ("test.html", res->body);
  1331. }
  1332. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1333. auto res = cli_.Get("/dir/../dir/test.html");
  1334. ASSERT_TRUE(res);
  1335. EXPECT_EQ(200, res->status);
  1336. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1337. EXPECT_EQ("test.html", res->body);
  1338. }
  1339. TEST_F(ServerTest, GetMethodInvalidPath) {
  1340. auto res = cli_.Get("/dir/../test.html");
  1341. ASSERT_TRUE(res);
  1342. EXPECT_EQ(404, res->status);
  1343. }
  1344. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1345. auto res = cli_.Get("/../www/dir/test.html");
  1346. ASSERT_TRUE(res);
  1347. EXPECT_EQ(404, res->status);
  1348. }
  1349. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1350. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1351. ASSERT_TRUE(res);
  1352. EXPECT_EQ(404, res->status);
  1353. }
  1354. TEST_F(ServerTest, GetMethodDirMountTest) {
  1355. auto res = cli_.Get("/mount/dir/test.html");
  1356. ASSERT_TRUE(res);
  1357. EXPECT_EQ(200, res->status);
  1358. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1359. EXPECT_EQ("test.html", res->body);
  1360. }
  1361. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1362. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1363. ASSERT_TRUE(res);
  1364. EXPECT_EQ(200, res->status);
  1365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1366. EXPECT_EQ("test.html", res->body);
  1367. }
  1368. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1369. auto res = cli_.Get("/mount/dir/../test.html");
  1370. ASSERT_TRUE(res);
  1371. EXPECT_EQ(404, res->status);
  1372. }
  1373. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1374. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1375. ASSERT_TRUE(res);
  1376. EXPECT_EQ(404, res->status);
  1377. }
  1378. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1379. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1380. ASSERT_TRUE(res);
  1381. EXPECT_EQ(404, res->status);
  1382. }
  1383. TEST_F(ServerTest, PostMethod303) {
  1384. auto res = cli_.Post("/1", "body", "text/plain");
  1385. ASSERT_TRUE(res);
  1386. EXPECT_EQ(303, res->status);
  1387. EXPECT_EQ("/2", res->get_header_value("Location"));
  1388. }
  1389. TEST_F(ServerTest, PostMethod303Redirect) {
  1390. cli_.set_follow_location(true);
  1391. auto res = cli_.Post("/1", "body", "text/plain");
  1392. ASSERT_TRUE(res);
  1393. EXPECT_EQ(200, res->status);
  1394. EXPECT_EQ("redirected.", res->body);
  1395. }
  1396. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1397. auto res = cli_.Get("/dir/test.abcde");
  1398. ASSERT_TRUE(res);
  1399. EXPECT_EQ(200, res->status);
  1400. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1401. EXPECT_EQ("abcde", res->body);
  1402. }
  1403. TEST_F(ServerTest, InvalidBaseDirMount) {
  1404. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1405. }
  1406. TEST_F(ServerTest, EmptyRequest) {
  1407. auto res = cli_.Get("");
  1408. ASSERT_TRUE(!res);
  1409. EXPECT_EQ(Error::Connection, res.error());
  1410. }
  1411. TEST_F(ServerTest, LongRequest) {
  1412. std::string request;
  1413. for (size_t i = 0; i < 545; i++) {
  1414. request += "/TooLongRequest";
  1415. }
  1416. request += "OK";
  1417. auto res = cli_.Get(request.c_str());
  1418. ASSERT_TRUE(res);
  1419. EXPECT_EQ(404, res->status);
  1420. }
  1421. TEST_F(ServerTest, TooLongRequest) {
  1422. std::string request;
  1423. for (size_t i = 0; i < 545; i++) {
  1424. request += "/TooLongRequest";
  1425. }
  1426. request += "_NG";
  1427. auto res = cli_.Get(request.c_str());
  1428. ASSERT_TRUE(res);
  1429. EXPECT_EQ(414, res->status);
  1430. }
  1431. TEST_F(ServerTest, LongHeader) {
  1432. Request req;
  1433. req.method = "GET";
  1434. req.path = "/hi";
  1435. std::string host_and_port;
  1436. host_and_port += HOST;
  1437. host_and_port += ":";
  1438. host_and_port += std::to_string(PORT);
  1439. req.headers.emplace("Host", host_and_port.c_str());
  1440. req.headers.emplace("Accept", "*/*");
  1441. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1442. req.headers.emplace(
  1443. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1472. "@@@@@@@@@@@@@@@@");
  1473. auto res = std::make_shared<Response>();
  1474. auto ret = cli_.send(req, *res);
  1475. ASSERT_TRUE(ret);
  1476. EXPECT_EQ(200, res->status);
  1477. }
  1478. TEST_F(ServerTest, LongQueryValue) {
  1479. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1480. ASSERT_TRUE(res);
  1481. EXPECT_EQ(414, res->status);
  1482. }
  1483. TEST_F(ServerTest, TooLongHeader) {
  1484. Request req;
  1485. req.method = "GET";
  1486. req.path = "/hi";
  1487. std::string host_and_port;
  1488. host_and_port += HOST;
  1489. host_and_port += ":";
  1490. host_and_port += std::to_string(PORT);
  1491. req.headers.emplace("Host", host_and_port.c_str());
  1492. req.headers.emplace("Accept", "*/*");
  1493. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1494. req.headers.emplace(
  1495. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1524. "@@@@@@@@@@@@@@@@@");
  1525. auto res = std::make_shared<Response>();
  1526. auto ret = cli_.send(req, *res);
  1527. ASSERT_TRUE(ret);
  1528. EXPECT_EQ(200, res->status);
  1529. }
  1530. TEST_F(ServerTest, PercentEncoding) {
  1531. auto res = cli_.Get("/e%6edwith%");
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ(200, res->status);
  1534. }
  1535. TEST_F(ServerTest, PercentEncodingUnicode) {
  1536. auto res = cli_.Get("/e%u006edwith%");
  1537. ASSERT_TRUE(res);
  1538. EXPECT_EQ(200, res->status);
  1539. }
  1540. TEST_F(ServerTest, InvalidPercentEncoding) {
  1541. auto res = cli_.Get("/%endwith%");
  1542. ASSERT_TRUE(res);
  1543. EXPECT_EQ(404, res->status);
  1544. }
  1545. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1546. auto res = cli_.Get("/%uendwith%");
  1547. ASSERT_TRUE(res);
  1548. EXPECT_EQ(404, res->status);
  1549. }
  1550. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1551. auto res = cli_.Get("/hello?aaa=bbb%");
  1552. ASSERT_TRUE(res);
  1553. EXPECT_EQ(404, res->status);
  1554. }
  1555. TEST_F(ServerTest, PlusSignEncoding) {
  1556. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1557. ASSERT_TRUE(res);
  1558. EXPECT_EQ(200, res->status);
  1559. EXPECT_EQ("a +b", res->body);
  1560. }
  1561. TEST_F(ServerTest, MultipartFormData) {
  1562. MultipartFormDataItems items = {
  1563. {"text1", "text default", "", ""},
  1564. {"text2", "aωb", "", ""},
  1565. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1566. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1567. {"file3", "", "", "application/octet-stream"},
  1568. {"file4", "", "", " application/json tmp-string "}};
  1569. auto res = cli_.Post("/multipart", items);
  1570. ASSERT_TRUE(res);
  1571. EXPECT_EQ(200, res->status);
  1572. }
  1573. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1574. auto res = cli_.Get("/hi");
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ(200, res->status);
  1577. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1578. EXPECT_EQ("Hello World!", res->body);
  1579. }
  1580. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1581. Request req;
  1582. req.method = "POST";
  1583. req.path = "/chunked";
  1584. std::string host_and_port;
  1585. host_and_port += HOST;
  1586. host_and_port += ":";
  1587. host_and_port += std::to_string(PORT);
  1588. req.headers.emplace("Host", host_and_port.c_str());
  1589. req.headers.emplace("Accept", "*/*");
  1590. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1591. req.headers.emplace("Content-Type", "text/plain");
  1592. req.headers.emplace("Content-Length", "0");
  1593. req.headers.emplace(
  1594. "Transfer-Encoding",
  1595. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1596. // Client does not chunk, so make a chunked body manually.
  1597. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1598. auto res = std::make_shared<Response>();
  1599. auto ret = cli_.send(req, *res);
  1600. ASSERT_TRUE(ret);
  1601. EXPECT_EQ(200, res->status);
  1602. }
  1603. TEST_F(ServerTest, GetStreamed2) {
  1604. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  1605. ASSERT_TRUE(res);
  1606. EXPECT_EQ(206, res->status);
  1607. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1608. EXPECT_EQ(std::string("ab"), res->body);
  1609. }
  1610. TEST_F(ServerTest, GetStreamed) {
  1611. auto res = cli_.Get("/streamed");
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(200, res->status);
  1614. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1615. EXPECT_EQ(std::string("aaabbb"), res->body);
  1616. }
  1617. TEST_F(ServerTest, GetStreamedWithRange1) {
  1618. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  1619. ASSERT_TRUE(res);
  1620. EXPECT_EQ(206, res->status);
  1621. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1622. EXPECT_EQ(true, res->has_header("Content-Range"));
  1623. EXPECT_EQ(std::string("def"), res->body);
  1624. }
  1625. TEST_F(ServerTest, GetStreamedWithRange2) {
  1626. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ(206, res->status);
  1629. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1630. EXPECT_EQ(true, res->has_header("Content-Range"));
  1631. EXPECT_EQ(std::string("bcdefg"), res->body);
  1632. }
  1633. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  1634. auto res = cli_.Get("/streamed-with-range", {
  1635. {"Range", "bytes=-3"}
  1636. });
  1637. ASSERT_TRUE(res);
  1638. EXPECT_EQ(206, res->status);
  1639. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1640. EXPECT_EQ(true, res->has_header("Content-Range"));
  1641. EXPECT_EQ(std::string("efg"), res->body);
  1642. }
  1643. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  1644. auto res = cli_.Get("/streamed-with-range", {
  1645. {"Range", "bytes=-9999"}
  1646. });
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ(206, res->status);
  1649. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  1650. EXPECT_EQ(true, res->has_header("Content-Range"));
  1651. EXPECT_EQ(std::string("abcdefg"), res->body);
  1652. }
  1653. TEST_F(ServerTest, GetStreamedWithRangeError) {
  1654. auto res = cli_.Get("/streamed-with-range", {
  1655. {"Range", "bytes=92233720368547758079223372036854775806-92233720368547758079223372036854775807"}
  1656. });
  1657. ASSERT_TRUE(res);
  1658. EXPECT_EQ(416, res->status);
  1659. }
  1660. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  1661. auto res =
  1662. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(206, res->status);
  1665. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1666. EXPECT_EQ(false, res->has_header("Content-Range"));
  1667. EXPECT_EQ(269, res->body.size());
  1668. }
  1669. TEST_F(ServerTest, GetStreamedEndless) {
  1670. uint64_t offset = 0;
  1671. auto res = cli_.Get("/streamed-cancel",
  1672. [&](const char * /*data*/, uint64_t data_length) {
  1673. if (offset < 100) {
  1674. offset += data_length;
  1675. return true;
  1676. }
  1677. return false;
  1678. });
  1679. ASSERT_TRUE(!res);
  1680. EXPECT_EQ(Error::Canceled, res.error());
  1681. }
  1682. TEST_F(ServerTest, ClientStop) {
  1683. std::vector<std::thread> threads;
  1684. for (auto i = 0; i < 3; i++) {
  1685. threads.emplace_back(thread([&]() {
  1686. auto res = cli_.Get("/streamed-cancel",
  1687. [&](const char *, uint64_t) { return true; });
  1688. ASSERT_TRUE(!res);
  1689. EXPECT_TRUE(res.error() == Error::Canceled || res.error() == Error::Read);
  1690. }));
  1691. }
  1692. std::this_thread::sleep_for(std::chrono::seconds(1));
  1693. while (cli_.is_socket_open()) {
  1694. cli_.stop();
  1695. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1696. }
  1697. for (auto &t : threads) {
  1698. t.join();
  1699. }
  1700. }
  1701. TEST_F(ServerTest, GetWithRange1) {
  1702. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  1703. ASSERT_TRUE(res);
  1704. EXPECT_EQ(206, res->status);
  1705. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  1706. EXPECT_EQ(true, res->has_header("Content-Range"));
  1707. EXPECT_EQ(std::string("def"), res->body);
  1708. }
  1709. TEST_F(ServerTest, GetWithRange2) {
  1710. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  1711. ASSERT_TRUE(res);
  1712. EXPECT_EQ(206, res->status);
  1713. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  1714. EXPECT_EQ(true, res->has_header("Content-Range"));
  1715. EXPECT_EQ(std::string("bcdefg"), res->body);
  1716. }
  1717. TEST_F(ServerTest, GetWithRange3) {
  1718. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ(206, res->status);
  1721. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  1722. EXPECT_EQ(true, res->has_header("Content-Range"));
  1723. EXPECT_EQ(std::string("a"), res->body);
  1724. }
  1725. TEST_F(ServerTest, GetWithRange4) {
  1726. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(206, res->status);
  1729. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1730. EXPECT_EQ(true, res->has_header("Content-Range"));
  1731. EXPECT_EQ(std::string("fg"), res->body);
  1732. }
  1733. TEST_F(ServerTest, GetWithRangeMultipart) {
  1734. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  1735. ASSERT_TRUE(res);
  1736. EXPECT_EQ(206, res->status);
  1737. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  1738. EXPECT_EQ(false, res->has_header("Content-Range"));
  1739. EXPECT_EQ(269, res->body.size());
  1740. }
  1741. TEST_F(ServerTest, GetStreamedChunked) {
  1742. auto res = cli_.Get("/streamed-chunked");
  1743. ASSERT_TRUE(res);
  1744. EXPECT_EQ(200, res->status);
  1745. EXPECT_EQ(std::string("123456789"), res->body);
  1746. }
  1747. TEST_F(ServerTest, GetStreamedChunked2) {
  1748. auto res = cli_.Get("/streamed-chunked2");
  1749. ASSERT_TRUE(res);
  1750. EXPECT_EQ(200, res->status);
  1751. EXPECT_EQ(std::string("123456789"), res->body);
  1752. }
  1753. TEST_F(ServerTest, LargeChunkedPost) {
  1754. Request req;
  1755. req.method = "POST";
  1756. req.path = "/large-chunked";
  1757. std::string host_and_port;
  1758. host_and_port += HOST;
  1759. host_and_port += ":";
  1760. host_and_port += std::to_string(PORT);
  1761. req.headers.emplace("Host", host_and_port.c_str());
  1762. req.headers.emplace("Accept", "*/*");
  1763. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1764. req.headers.emplace("Content-Type", "text/plain");
  1765. req.headers.emplace("Content-Length", "0");
  1766. req.headers.emplace("Transfer-Encoding", "chunked");
  1767. std::string long_string(30 * 1024u, 'a');
  1768. std::string chunk = "7800\r\n" + long_string + "\r\n";
  1769. // Attempt to make a large enough post to exceed OS buffers, to test that
  1770. // the server handles short reads if the full chunk data isn't available.
  1771. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  1772. auto res = std::make_shared<Response>();
  1773. auto ret = cli_.send(req, *res);
  1774. ASSERT_TRUE(ret);
  1775. EXPECT_EQ(200, res->status);
  1776. }
  1777. TEST_F(ServerTest, GetMethodRemoteAddr) {
  1778. auto res = cli_.Get("/remote_addr");
  1779. ASSERT_TRUE(res);
  1780. EXPECT_EQ(200, res->status);
  1781. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1782. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  1783. }
  1784. TEST_F(ServerTest, HTTPResponseSplitting) {
  1785. auto res = cli_.Get("/http_response_splitting");
  1786. ASSERT_TRUE(res);
  1787. EXPECT_EQ(200, res->status);
  1788. }
  1789. TEST_F(ServerTest, SlowRequest) {
  1790. request_threads_.push_back(
  1791. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1792. request_threads_.push_back(
  1793. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1794. request_threads_.push_back(
  1795. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  1796. }
  1797. TEST_F(ServerTest, SlowPost) {
  1798. char buffer[64 * 1024];
  1799. memset(buffer, 0x42, sizeof(buffer));
  1800. auto res = cli_.Post(
  1801. "/slowpost", 64 * 1024 * 1024,
  1802. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1803. sink.write(buffer, sizeof(buffer));
  1804. return true;
  1805. },
  1806. "text/plain");
  1807. ASSERT_TRUE(res);
  1808. EXPECT_EQ(200, res->status);
  1809. }
  1810. TEST_F(ServerTest, SlowPostFail) {
  1811. char buffer[64 * 1024];
  1812. memset(buffer, 0x42, sizeof(buffer));
  1813. cli_.set_write_timeout(0, 0);
  1814. auto res = cli_.Post(
  1815. "/slowpost", 64 * 1024 * 1024,
  1816. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1817. sink.write(buffer, sizeof(buffer));
  1818. return true;
  1819. },
  1820. "text/plain");
  1821. ASSERT_TRUE(!res);
  1822. EXPECT_EQ(Error::Write, res.error());
  1823. }
  1824. TEST_F(ServerTest, Put) {
  1825. auto res = cli_.Put("/put", "PUT", "text/plain");
  1826. ASSERT_TRUE(res);
  1827. EXPECT_EQ(200, res->status);
  1828. EXPECT_EQ("PUT", res->body);
  1829. }
  1830. TEST_F(ServerTest, PutWithContentProvider) {
  1831. auto res = cli_.Put(
  1832. "/put", 3,
  1833. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1834. EXPECT_TRUE(sink.is_writable());
  1835. sink.os << "PUT";
  1836. return true;
  1837. },
  1838. "text/plain");
  1839. ASSERT_TRUE(res);
  1840. EXPECT_EQ(200, res->status);
  1841. EXPECT_EQ("PUT", res->body);
  1842. }
  1843. TEST_F(ServerTest, PostWithContentProviderAbort) {
  1844. auto res = cli_.Post(
  1845. "/post", 42,
  1846. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1847. return false;
  1848. },
  1849. "text/plain");
  1850. ASSERT_TRUE(!res);
  1851. EXPECT_EQ(Error::Canceled, res.error());
  1852. }
  1853. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1854. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  1855. cli_.set_compress(true);
  1856. auto res = cli_.Put(
  1857. "/put", 3,
  1858. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1859. EXPECT_TRUE(sink.is_writable());
  1860. sink.os << "PUT";
  1861. return true;
  1862. },
  1863. "text/plain");
  1864. ASSERT_TRUE(res);
  1865. EXPECT_EQ(200, res->status);
  1866. EXPECT_EQ("PUT", res->body);
  1867. }
  1868. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  1869. cli_.set_compress(true);
  1870. auto res = cli_.Post(
  1871. "/post", 42,
  1872. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  1873. return false;
  1874. },
  1875. "text/plain");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Canceled, res.error());
  1878. }
  1879. TEST_F(ServerTest, PutLargeFileWithGzip) {
  1880. cli_.set_compress(true);
  1881. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  1882. ASSERT_TRUE(res);
  1883. EXPECT_EQ(200, res->status);
  1884. EXPECT_EQ(LARGE_DATA, res->body);
  1885. }
  1886. TEST_F(ServerTest, PutContentWithDeflate) {
  1887. cli_.set_compress(false);
  1888. Headers headers;
  1889. headers.emplace("Content-Encoding", "deflate");
  1890. // PUT in deflate format:
  1891. auto res = cli_.Put("/put", headers,
  1892. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  1893. ASSERT_TRUE(res);
  1894. EXPECT_EQ(200, res->status);
  1895. EXPECT_EQ("PUT", res->body);
  1896. }
  1897. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  1898. Headers headers;
  1899. headers.emplace("Accept-Encoding", "gzip, deflate");
  1900. auto res = cli_.Get("/streamed-chunked", headers);
  1901. ASSERT_TRUE(res);
  1902. EXPECT_EQ(200, res->status);
  1903. EXPECT_EQ(std::string("123456789"), res->body);
  1904. }
  1905. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  1906. Headers headers;
  1907. headers.emplace("Accept-Encoding", "gzip, deflate");
  1908. auto res = cli_.Get("/streamed-chunked2", headers);
  1909. ASSERT_TRUE(res);
  1910. EXPECT_EQ(200, res->status);
  1911. EXPECT_EQ(std::string("123456789"), res->body);
  1912. }
  1913. TEST(GzipDecompressor, ChunkedDecompression) {
  1914. std::string data;
  1915. for (size_t i = 0; i < 32 * 1024; ++i) {
  1916. data.push_back(static_cast<char>('a' + i % 26));
  1917. }
  1918. std::string compressed_data;
  1919. {
  1920. httplib::detail::gzip_compressor compressor;
  1921. bool result = compressor.compress(
  1922. data.data(), data.size(),
  1923. /*last=*/true, [&](const char *data, size_t size) {
  1924. compressed_data.insert(compressed_data.size(), data, size);
  1925. return true;
  1926. });
  1927. ASSERT_TRUE(result);
  1928. }
  1929. std::string decompressed_data;
  1930. {
  1931. httplib::detail::gzip_decompressor decompressor;
  1932. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  1933. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  1934. size_t chunk_size = 130;
  1935. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  1936. chunk_begin += chunk_size) {
  1937. size_t current_chunk_size =
  1938. std::min(compressed_data.size() - chunk_begin, chunk_size);
  1939. bool result = decompressor.decompress(
  1940. compressed_data.data() + chunk_begin, current_chunk_size,
  1941. [&](const char *data, size_t size) {
  1942. decompressed_data.insert(decompressed_data.size(), data, size);
  1943. return true;
  1944. });
  1945. ASSERT_TRUE(result);
  1946. }
  1947. }
  1948. ASSERT_EQ(data, decompressed_data);
  1949. }
  1950. #endif
  1951. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1952. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  1953. Headers headers;
  1954. headers.emplace("Accept-Encoding", "brotli");
  1955. auto res = cli_.Get("/streamed-chunked", headers);
  1956. ASSERT_TRUE(res);
  1957. EXPECT_EQ(200, res->status);
  1958. EXPECT_EQ(std::string("123456789"), res->body);
  1959. }
  1960. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  1961. Headers headers;
  1962. headers.emplace("Accept-Encoding", "brotli");
  1963. auto res = cli_.Get("/streamed-chunked2", headers);
  1964. ASSERT_TRUE(res);
  1965. EXPECT_EQ(200, res->status);
  1966. EXPECT_EQ(std::string("123456789"), res->body);
  1967. }
  1968. #endif
  1969. TEST_F(ServerTest, Patch) {
  1970. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(200, res->status);
  1973. EXPECT_EQ("PATCH", res->body);
  1974. }
  1975. TEST_F(ServerTest, Delete) {
  1976. auto res = cli_.Delete("/delete");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(200, res->status);
  1979. EXPECT_EQ("DELETE", res->body);
  1980. }
  1981. TEST_F(ServerTest, DeleteContentReceiver) {
  1982. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(200, res->status);
  1985. EXPECT_EQ("content", res->body);
  1986. }
  1987. TEST_F(ServerTest, Options) {
  1988. auto res = cli_.Options("*");
  1989. ASSERT_TRUE(res);
  1990. EXPECT_EQ(200, res->status);
  1991. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  1992. EXPECT_TRUE(res->body.empty());
  1993. }
  1994. TEST_F(ServerTest, URL) {
  1995. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(200, res->status);
  1998. }
  1999. TEST_F(ServerTest, ArrayParam) {
  2000. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(200, res->status);
  2003. }
  2004. TEST_F(ServerTest, NoMultipleHeaders) {
  2005. Headers headers = {{"Content-Length", "5"}};
  2006. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2007. "text/plain");
  2008. ASSERT_TRUE(res);
  2009. EXPECT_EQ(200, res->status);
  2010. }
  2011. TEST_F(ServerTest, PostContentReceiver) {
  2012. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2013. ASSERT_TRUE(res);
  2014. ASSERT_EQ(200, res->status);
  2015. ASSERT_EQ("content", res->body);
  2016. }
  2017. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2018. MultipartFormDataItems items = {
  2019. {"text1", "text default", "", ""},
  2020. {"text2", "aωb", "", ""},
  2021. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2022. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2023. {"file3", "", "", "application/octet-stream"},
  2024. };
  2025. auto res = cli_.Post("/content_receiver", items);
  2026. ASSERT_TRUE(res);
  2027. EXPECT_EQ(200, res->status);
  2028. }
  2029. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2030. MultipartFormDataItems items = {
  2031. {"text1", "text default", "", ""},
  2032. {"text2", "aωb", "", ""},
  2033. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2034. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2035. {"file3", "", "", "application/octet-stream"},
  2036. };
  2037. auto boundary = std::string("+++++");
  2038. std::string body;
  2039. for (const auto &item : items) {
  2040. body += "--" + boundary + "\r\n";
  2041. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2042. if (!item.filename.empty()) {
  2043. body += "; filename=\"" + item.filename + "\"";
  2044. }
  2045. body += "\r\n";
  2046. if (!item.content_type.empty()) {
  2047. body += "Content-Type: " + item.content_type + "\r\n";
  2048. }
  2049. body += "\r\n";
  2050. body += item.content + "\r\n";
  2051. }
  2052. body += "--" + boundary + "--\r\n";
  2053. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2054. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(200, res->status);
  2057. }
  2058. TEST_F(ServerTest, PostContentReceiverGzip) {
  2059. cli_.set_compress(true);
  2060. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2061. ASSERT_TRUE(res);
  2062. ASSERT_EQ(200, res->status);
  2063. ASSERT_EQ("content", res->body);
  2064. }
  2065. TEST_F(ServerTest, PutContentReceiver) {
  2066. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2067. ASSERT_TRUE(res);
  2068. ASSERT_EQ(200, res->status);
  2069. ASSERT_EQ("content", res->body);
  2070. }
  2071. TEST_F(ServerTest, PatchContentReceiver) {
  2072. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2073. ASSERT_TRUE(res);
  2074. ASSERT_EQ(200, res->status);
  2075. ASSERT_EQ("content", res->body);
  2076. }
  2077. TEST_F(ServerTest, PostQueryStringAndBody) {
  2078. auto res =
  2079. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2080. ASSERT_TRUE(res);
  2081. ASSERT_EQ(200, res->status);
  2082. }
  2083. TEST_F(ServerTest, HTTP2Magic) {
  2084. Request req;
  2085. req.method = "PRI";
  2086. req.path = "*";
  2087. req.body = "SM";
  2088. auto res = std::make_shared<Response>();
  2089. auto ret = cli_.send(req, *res);
  2090. ASSERT_TRUE(ret);
  2091. EXPECT_EQ(400, res->status);
  2092. }
  2093. TEST_F(ServerTest, KeepAlive) {
  2094. auto res = cli_.Get("/hi");
  2095. ASSERT_TRUE(res);
  2096. EXPECT_EQ(200, res->status);
  2097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2098. EXPECT_EQ("Hello World!", res->body);
  2099. res = cli_.Get("/hi");
  2100. ASSERT_TRUE(res);
  2101. EXPECT_EQ(200, res->status);
  2102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2103. EXPECT_EQ("Hello World!", res->body);
  2104. res = cli_.Get("/hi");
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(200, res->status);
  2107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2108. EXPECT_EQ("Hello World!", res->body);
  2109. res = cli_.Get("/not-exist");
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(404, res->status);
  2112. res = cli_.Post("/empty", "", "text/plain");
  2113. ASSERT_TRUE(res);
  2114. EXPECT_EQ(200, res->status);
  2115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2116. EXPECT_EQ("empty", res->body);
  2117. EXPECT_EQ("close", res->get_header_value("Connection"));
  2118. res = cli_.Post(
  2119. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2120. "text/plain");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(200, res->status);
  2123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2124. EXPECT_EQ("empty", res->body);
  2125. cli_.set_keep_alive(false);
  2126. res = cli_.Get("/last-request");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(200, res->status);
  2129. EXPECT_EQ("close", res->get_header_value("Connection"));
  2130. }
  2131. TEST_F(ServerTest, TooManyRedirect) {
  2132. cli_.set_follow_location(true);
  2133. auto res = cli_.Get("/redirect/0");
  2134. ASSERT_TRUE(!res);
  2135. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2136. }
  2137. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2138. TEST_F(ServerTest, Gzip) {
  2139. Headers headers;
  2140. headers.emplace("Accept-Encoding", "gzip, deflate");
  2141. auto res = cli_.Get("/compress", headers);
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2144. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2145. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2146. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2147. "7890123456789012345678901234567890",
  2148. res->body);
  2149. EXPECT_EQ(200, res->status);
  2150. }
  2151. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2152. auto res = cli_.Get("/compress");
  2153. ASSERT_TRUE(res);
  2154. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2155. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2156. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2157. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2158. "7890123456789012345678901234567890",
  2159. res->body);
  2160. EXPECT_EQ(200, res->status);
  2161. }
  2162. TEST_F(ServerTest, GzipWithContentReceiver) {
  2163. Headers headers;
  2164. headers.emplace("Accept-Encoding", "gzip, deflate");
  2165. std::string body;
  2166. auto res = cli_.Get("/compress", headers,
  2167. [&](const char *data, uint64_t data_length) {
  2168. EXPECT_EQ(data_length, 100);
  2169. body.append(data, data_length);
  2170. return true;
  2171. });
  2172. ASSERT_TRUE(res);
  2173. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2175. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2177. "7890123456789012345678901234567890",
  2178. body);
  2179. EXPECT_EQ(200, res->status);
  2180. }
  2181. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2182. Headers headers;
  2183. headers.emplace("Accept-Encoding", "gzip, deflate");
  2184. cli_.set_decompress(false);
  2185. auto res = cli_.Get("/compress", headers);
  2186. ASSERT_TRUE(res);
  2187. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2189. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2190. EXPECT_EQ(33, res->body.size());
  2191. EXPECT_EQ(200, res->status);
  2192. }
  2193. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2194. std::string body;
  2195. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2196. EXPECT_EQ(data_length, 100);
  2197. body.append(data, data_length);
  2198. return true;
  2199. });
  2200. ASSERT_TRUE(res);
  2201. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2203. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2204. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2205. "7890123456789012345678901234567890",
  2206. body);
  2207. EXPECT_EQ(200, res->status);
  2208. }
  2209. TEST_F(ServerTest, NoGzip) {
  2210. Headers headers;
  2211. headers.emplace("Accept-Encoding", "gzip, deflate");
  2212. auto res = cli_.Get("/nocompress", headers);
  2213. ASSERT_TRUE(res);
  2214. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2215. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2216. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2217. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2218. "7890123456789012345678901234567890",
  2219. res->body);
  2220. EXPECT_EQ(200, res->status);
  2221. }
  2222. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2223. Headers headers;
  2224. headers.emplace("Accept-Encoding", "gzip, deflate");
  2225. std::string body;
  2226. auto res = cli_.Get("/nocompress", headers,
  2227. [&](const char *data, uint64_t data_length) {
  2228. EXPECT_EQ(data_length, 100);
  2229. body.append(data, data_length);
  2230. return true;
  2231. });
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2234. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2235. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2237. "7890123456789012345678901234567890",
  2238. body);
  2239. EXPECT_EQ(200, res->status);
  2240. }
  2241. TEST_F(ServerTest, MultipartFormDataGzip) {
  2242. MultipartFormDataItems items = {
  2243. {"key1", "test", "", ""},
  2244. {"key2", "--abcdefg123", "", ""},
  2245. };
  2246. cli_.set_compress(true);
  2247. auto res = cli_.Post("/compress-multipart", items);
  2248. ASSERT_TRUE(res);
  2249. EXPECT_EQ(200, res->status);
  2250. }
  2251. #endif
  2252. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2253. TEST_F(ServerTest, Brotli) {
  2254. Headers headers;
  2255. headers.emplace("Accept-Encoding", "br");
  2256. auto res = cli_.Get("/compress", headers);
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ("brotli", res->get_header_value("Content-Encoding"));
  2259. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2260. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2261. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2262. "7890123456789012345678901234567890",
  2263. res->body);
  2264. EXPECT_EQ(200, res->status);
  2265. }
  2266. #endif
  2267. // Sends a raw request to a server listening at HOST:PORT.
  2268. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2269. std::string *resp = nullptr) {
  2270. Error error = Error::Success;
  2271. auto client_sock =
  2272. detail::create_client_socket(HOST, PORT, false, nullptr,
  2273. /*timeout_sec=*/5, 0, std::string(), error);
  2274. if (client_sock == INVALID_SOCKET) { return false; }
  2275. auto ret = detail::process_client_socket(
  2276. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2277. if (req.size() !=
  2278. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2279. return false;
  2280. }
  2281. char buf[512];
  2282. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2283. while (line_reader.getline()) {
  2284. if (resp) { *resp += line_reader.ptr(); }
  2285. }
  2286. return true;
  2287. });
  2288. detail::close_socket(client_sock);
  2289. return ret;
  2290. }
  2291. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2292. Server svr;
  2293. std::string header_value;
  2294. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2295. header_value = req.get_header_value("foo");
  2296. res.set_content("ok", "text/plain");
  2297. });
  2298. thread t = thread([&] { svr.listen(HOST, PORT); });
  2299. while (!svr.is_running()) {
  2300. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2301. }
  2302. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2303. // like characters are not treated the same - use vertical tab and escape.
  2304. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2305. "foo: \t \v bar \e\t \r\n"
  2306. "Connection: close\r\n"
  2307. "\r\n";
  2308. ASSERT_TRUE(send_request(5, req));
  2309. svr.stop();
  2310. t.join();
  2311. EXPECT_EQ(header_value, "\v bar \e");
  2312. }
  2313. // Sends a raw request and verifies that there isn't a crash or exception.
  2314. static void test_raw_request(const std::string &req,
  2315. std::string *out = nullptr) {
  2316. Server svr;
  2317. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2318. res.set_content("ok", "text/plain");
  2319. });
  2320. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2321. res.set_content("ok", "text/plain");
  2322. });
  2323. // Server read timeout must be longer than the client read timeout for the
  2324. // bug to reproduce, probably to force the server to process a request
  2325. // without a trailing blank line.
  2326. const time_t client_read_timeout_sec = 1;
  2327. svr.set_read_timeout(client_read_timeout_sec + 1, 0);
  2328. bool listen_thread_ok = false;
  2329. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2330. while (!svr.is_running()) {
  2331. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2332. }
  2333. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2334. svr.stop();
  2335. t.join();
  2336. EXPECT_TRUE(listen_thread_ok);
  2337. }
  2338. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2339. // A certain header line causes an exception if the header property is parsed
  2340. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2341. test_raw_request(
  2342. "GET /hi HTTP/1.1\r\n"
  2343. " : "
  2344. " "
  2345. " ");
  2346. }
  2347. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2348. // A certain header line causes an exception if the header property *name* is
  2349. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2350. // greedy matcher and requires backtracking when there are a lot of ":"
  2351. // characters.
  2352. // This occurs with libc++ but not libstdc++.
  2353. test_raw_request(
  2354. "GET /hi HTTP/1.1\r\n"
  2355. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2356. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2357. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2358. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2359. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2360. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2361. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2362. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2363. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2364. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2365. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2366. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2367. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2368. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2369. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2370. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2371. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2372. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2373. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2374. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2375. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2376. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2377. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2378. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2379. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2380. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2381. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2382. "&&&%%%");
  2383. }
  2384. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2385. // Make sure this doesn't crash the server.
  2386. // In a previous version of the header line regex, the "\r" rendered the line
  2387. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2388. // a new position where the leading white space ended and the field value
  2389. // began.
  2390. // The crash occurs with libc++ but not libstdc++.
  2391. test_raw_request("GET /hi HTTP/1.1\r\n"
  2392. "a:" +
  2393. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2394. "\r\n"
  2395. "\r\n");
  2396. }
  2397. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2398. std::string out;
  2399. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2400. "Content-Type: text/plain\r\n"
  2401. "Transfer-Encoding: chunked\r\n"
  2402. "\r\n"
  2403. "nothex\r\n",
  2404. &out);
  2405. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2406. }
  2407. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2408. std::string out;
  2409. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2410. "Content-Type: text/plain\r\n"
  2411. "Transfer-Encoding: chunked\r\n"
  2412. "\r\n"
  2413. "3\r\n"
  2414. "xyz\r\n"
  2415. "NaN\r\n",
  2416. &out);
  2417. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2418. }
  2419. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2420. std::string out;
  2421. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2422. "Content-Type: text/plain\r\n"
  2423. "Transfer-Encoding: chunked\r\n"
  2424. "\r\n"
  2425. // Length is too large for 64 bits.
  2426. "1ffffffffffffffff\r\n"
  2427. "xyz\r\n",
  2428. &out);
  2429. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2430. }
  2431. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2432. test_raw_request("GET /hi HTTP/1.1\r\n"
  2433. "Content-Type: text/plain\r\n\r");
  2434. }
  2435. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2436. Server svr;
  2437. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2438. res.set_header("Cache-Control", "no-cache");
  2439. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2440. DataSink &sink) {
  2441. char buffer[27];
  2442. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2443. sink.write(buffer, size);
  2444. std::this_thread::sleep_for(std::chrono::seconds(1));
  2445. return true;
  2446. });
  2447. });
  2448. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2449. while (!svr.is_running()) {
  2450. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2451. }
  2452. Client client(HOST, PORT);
  2453. const Headers headers = {{"Accept", "text/event-stream"}};
  2454. auto get_thread = std::thread([&client, &headers]() {
  2455. auto res = client.Get(
  2456. "/events", headers,
  2457. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2458. });
  2459. // Give GET time to get a few messages.
  2460. std::this_thread::sleep_for(std::chrono::seconds(2));
  2461. svr.stop();
  2462. listen_thread.join();
  2463. get_thread.join();
  2464. ASSERT_FALSE(svr.is_running());
  2465. }
  2466. TEST(StreamingTest, NoContentLengthStreaming) {
  2467. Server svr;
  2468. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  2469. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  2470. if (offset < 6) {
  2471. sink.os << (offset < 3 ? "a" : "b");
  2472. } else {
  2473. sink.done();
  2474. }
  2475. return true;
  2476. });
  2477. });
  2478. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2479. while (!svr.is_running()) {
  2480. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2481. }
  2482. Client client(HOST, PORT);
  2483. auto get_thread = std::thread([&client]() {
  2484. auto res = client.Get("/stream", [](const char *data, size_t len) -> bool {
  2485. EXPECT_EQ("aaabbb", std::string(data, len));
  2486. return true;
  2487. });
  2488. });
  2489. // Give GET time to get a few messages.
  2490. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2491. svr.stop();
  2492. listen_thread.join();
  2493. get_thread.join();
  2494. ASSERT_FALSE(svr.is_running());
  2495. }
  2496. TEST(MountTest, Unmount) {
  2497. Server svr;
  2498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2499. while (!svr.is_running()) {
  2500. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2501. }
  2502. // Give GET time to get a few messages.
  2503. std::this_thread::sleep_for(std::chrono::seconds(1));
  2504. Client cli("localhost", PORT);
  2505. svr.set_mount_point("/mount2", "./www2");
  2506. auto res = cli.Get("/");
  2507. ASSERT_TRUE(res);
  2508. EXPECT_EQ(404, res->status);
  2509. res = cli.Get("/mount2/dir/test.html");
  2510. ASSERT_TRUE(res);
  2511. EXPECT_EQ(200, res->status);
  2512. svr.set_mount_point("/", "./www");
  2513. res = cli.Get("/dir/");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(200, res->status);
  2516. svr.remove_mount_point("/");
  2517. res = cli.Get("/dir/");
  2518. ASSERT_TRUE(res);
  2519. EXPECT_EQ(404, res->status);
  2520. svr.remove_mount_point("/mount2");
  2521. res = cli.Get("/mount2/dir/test.html");
  2522. ASSERT_TRUE(res);
  2523. EXPECT_EQ(404, res->status);
  2524. svr.stop();
  2525. listen_thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. }
  2528. TEST(ExceptionTest, ThrowExceptionInHandler) {
  2529. Server svr;
  2530. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2531. throw std::runtime_error("exception...");
  2532. res.set_content("Hello World!", "text/plain");
  2533. });
  2534. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2535. while (!svr.is_running()) {
  2536. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2537. }
  2538. // Give GET time to get a few messages.
  2539. std::this_thread::sleep_for(std::chrono::seconds(1));
  2540. Client cli("localhost", PORT);
  2541. auto res = cli.Get("/hi");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(500, res->status);
  2544. ASSERT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2545. svr.stop();
  2546. listen_thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. }
  2549. TEST(KeepAliveTest, ReadTimeout) {
  2550. Server svr;
  2551. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2552. std::this_thread::sleep_for(std::chrono::seconds(2));
  2553. res.set_content("a", "text/plain");
  2554. });
  2555. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2556. res.set_content("b", "text/plain");
  2557. });
  2558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2559. while (!svr.is_running()) {
  2560. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2561. }
  2562. // Give GET time to get a few messages.
  2563. std::this_thread::sleep_for(std::chrono::seconds(1));
  2564. Client cli("localhost", PORT);
  2565. cli.set_keep_alive(true);
  2566. cli.set_read_timeout(1);
  2567. auto resa = cli.Get("/a");
  2568. ASSERT_TRUE(!resa);
  2569. EXPECT_EQ(Error::Read, resa.error());
  2570. auto resb = cli.Get("/b");
  2571. ASSERT_TRUE(resb);
  2572. EXPECT_EQ(200, resb->status);
  2573. EXPECT_EQ("b", resb->body);
  2574. svr.stop();
  2575. listen_thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. }
  2578. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2579. TEST(KeepAliveTest, ReadTimeoutSSL) {
  2580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2581. ASSERT_TRUE(svr.is_valid());
  2582. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  2583. std::this_thread::sleep_for(std::chrono::seconds(2));
  2584. res.set_content("a", "text/plain");
  2585. });
  2586. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  2587. res.set_content("b", "text/plain");
  2588. });
  2589. auto listen_thread = std::thread([&svr]() {
  2590. svr.listen("localhost", PORT);
  2591. });
  2592. while (!svr.is_running()) {
  2593. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2594. }
  2595. // Give GET time to get a few messages.
  2596. std::this_thread::sleep_for(std::chrono::seconds(1));
  2597. SSLClient cli("localhost", PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. cli.set_keep_alive(true);
  2600. cli.set_read_timeout(1);
  2601. auto resa = cli.Get("/a");
  2602. ASSERT_TRUE(!resa);
  2603. EXPECT_EQ(Error::Read, resa.error());
  2604. auto resb = cli.Get("/b");
  2605. ASSERT_TRUE(resb);
  2606. EXPECT_EQ(200, resb->status);
  2607. EXPECT_EQ("b", resb->body);
  2608. svr.stop();
  2609. listen_thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. }
  2612. #endif
  2613. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  2614. protected:
  2615. ServerTestWithAI_PASSIVE()
  2616. : cli_(HOST, PORT)
  2617. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2618. ,
  2619. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2620. #endif
  2621. {
  2622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2623. cli_.enable_server_certificate_verification(false);
  2624. #endif
  2625. }
  2626. virtual void SetUp() {
  2627. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2628. res.set_content("Hello World!", "text/plain");
  2629. });
  2630. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  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(ServerTestWithAI_PASSIVE, GetMethod200) {
  2649. auto res = cli_.Get("/hi");
  2650. ASSERT_TRUE(res);
  2651. EXPECT_EQ(200, res->status);
  2652. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2653. EXPECT_EQ("Hello World!", res->body);
  2654. }
  2655. class ServerUpDownTest : public ::testing::Test {
  2656. protected:
  2657. ServerUpDownTest() : cli_(HOST, PORT) {}
  2658. virtual void SetUp() {
  2659. t_ = thread([&]() {
  2660. svr_.bind_to_any_port(HOST);
  2661. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2662. ASSERT_TRUE(svr_.listen_after_bind());
  2663. });
  2664. while (!svr_.is_running()) {
  2665. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2666. }
  2667. }
  2668. virtual void TearDown() {
  2669. svr_.stop();
  2670. t_.join();
  2671. }
  2672. Client cli_;
  2673. Server svr_;
  2674. thread t_;
  2675. };
  2676. TEST_F(ServerUpDownTest, QuickStartStop) {
  2677. // Should not crash, especially when run with
  2678. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  2679. }
  2680. class PayloadMaxLengthTest : public ::testing::Test {
  2681. protected:
  2682. PayloadMaxLengthTest()
  2683. : cli_(HOST, PORT)
  2684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2685. ,
  2686. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2687. #endif
  2688. {
  2689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2690. cli_.enable_server_certificate_verification(false);
  2691. #endif
  2692. }
  2693. virtual void SetUp() {
  2694. svr_.set_payload_max_length(8);
  2695. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  2696. res.set_content("test", "text/plain");
  2697. });
  2698. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2699. while (!svr_.is_running()) {
  2700. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2701. }
  2702. }
  2703. virtual void TearDown() {
  2704. svr_.stop();
  2705. t_.join();
  2706. }
  2707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2708. SSLClient cli_;
  2709. SSLServer svr_;
  2710. #else
  2711. Client cli_;
  2712. Server svr_;
  2713. #endif
  2714. thread t_;
  2715. };
  2716. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  2717. auto res = cli_.Post("/test", "123456789", "text/plain");
  2718. ASSERT_TRUE(res);
  2719. EXPECT_EQ(413, res->status);
  2720. res = cli_.Post("/test", "12345678", "text/plain");
  2721. ASSERT_TRUE(res);
  2722. EXPECT_EQ(200, res->status);
  2723. }
  2724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2725. TEST(SSLClientTest, UpdateCAStore) {
  2726. httplib::SSLClient httplib_client("www.google.com");
  2727. auto ca_store_1 = X509_STORE_new();
  2728. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  2729. nullptr);
  2730. httplib_client.set_ca_cert_store(ca_store_1);
  2731. auto ca_store_2 = X509_STORE_new();
  2732. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  2733. nullptr);
  2734. httplib_client.set_ca_cert_store(ca_store_2);
  2735. }
  2736. TEST(SSLClientTest, ServerNameIndication) {
  2737. SSLClient cli("httpbin.org", 443);
  2738. auto res = cli.Get("/get");
  2739. ASSERT_TRUE(res);
  2740. ASSERT_EQ(200, res->status);
  2741. }
  2742. TEST(SSLClientTest, ServerCertificateVerification1) {
  2743. SSLClient cli("google.com");
  2744. auto res = cli.Get("/");
  2745. ASSERT_TRUE(res);
  2746. ASSERT_EQ(301, res->status);
  2747. }
  2748. TEST(SSLClientTest, ServerCertificateVerification2) {
  2749. SSLClient cli("google.com");
  2750. cli.enable_server_certificate_verification(true);
  2751. cli.set_ca_cert_path("hello");
  2752. auto res = cli.Get("/");
  2753. ASSERT_TRUE(!res);
  2754. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  2755. }
  2756. TEST(SSLClientTest, ServerCertificateVerification3) {
  2757. SSLClient cli("google.com");
  2758. cli.set_ca_cert_path(CA_CERT_FILE);
  2759. auto res = cli.Get("/");
  2760. ASSERT_TRUE(res);
  2761. ASSERT_EQ(301, res->status);
  2762. }
  2763. TEST(SSLClientTest, WildcardHostNameMatch) {
  2764. SSLClient cli("www.youtube.com");
  2765. cli.set_ca_cert_path(CA_CERT_FILE);
  2766. cli.enable_server_certificate_verification(true);
  2767. auto res = cli.Get("/");
  2768. ASSERT_TRUE(res);
  2769. ASSERT_EQ(200, res->status);
  2770. }
  2771. TEST(SSLClientServerTest, ClientCertPresent) {
  2772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2773. CLIENT_CA_CERT_DIR);
  2774. ASSERT_TRUE(svr.is_valid());
  2775. svr.Get("/test", [&](const Request &req, Response &res) {
  2776. res.set_content("test", "text/plain");
  2777. svr.stop();
  2778. ASSERT_TRUE(true);
  2779. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2780. ASSERT_TRUE(peer_cert != nullptr);
  2781. auto subject_name = X509_get_subject_name(peer_cert);
  2782. ASSERT_TRUE(subject_name != nullptr);
  2783. std::string common_name;
  2784. {
  2785. char name[BUFSIZ];
  2786. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2787. name, sizeof(name));
  2788. common_name.assign(name, static_cast<size_t>(name_len));
  2789. }
  2790. EXPECT_EQ("Common Name", common_name);
  2791. X509_free(peer_cert);
  2792. });
  2793. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2794. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2795. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2796. cli.enable_server_certificate_verification(false);
  2797. cli.set_connection_timeout(30);
  2798. auto res = cli.Get("/test");
  2799. ASSERT_TRUE(res);
  2800. ASSERT_EQ(200, res->status);
  2801. t.join();
  2802. }
  2803. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  2804. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  2805. X509 *server_cert;
  2806. EVP_PKEY *server_private_key;
  2807. X509_STORE *client_ca_cert_store;
  2808. X509 *client_cert;
  2809. EVP_PKEY *client_private_key;
  2810. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  2811. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2812. fclose(f);
  2813. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  2814. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2815. fclose(f);
  2816. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  2817. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2818. client_ca_cert_store = X509_STORE_new();
  2819. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  2820. X509_free(client_cert);
  2821. fclose(f);
  2822. f = fopen(CLIENT_CERT_FILE, "r+");
  2823. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  2824. fclose(f);
  2825. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  2826. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  2827. fclose(f);
  2828. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  2829. ASSERT_TRUE(svr.is_valid());
  2830. svr.Get("/test", [&](const Request &req, Response &res) {
  2831. res.set_content("test", "text/plain");
  2832. svr.stop();
  2833. ASSERT_TRUE(true);
  2834. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  2835. ASSERT_TRUE(peer_cert != nullptr);
  2836. auto subject_name = X509_get_subject_name(peer_cert);
  2837. ASSERT_TRUE(subject_name != nullptr);
  2838. std::string common_name;
  2839. {
  2840. char name[BUFSIZ];
  2841. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2842. name, sizeof(name));
  2843. common_name.assign(name, static_cast<size_t>(name_len));
  2844. }
  2845. EXPECT_EQ("Common Name", common_name);
  2846. X509_free(peer_cert);
  2847. });
  2848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2849. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2850. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  2851. cli.enable_server_certificate_verification(false);
  2852. cli.set_connection_timeout(30);
  2853. auto res = cli.Get("/test");
  2854. ASSERT_TRUE(res);
  2855. ASSERT_EQ(200, res->status);
  2856. X509_free(server_cert);
  2857. EVP_PKEY_free(server_private_key);
  2858. X509_free(client_cert);
  2859. EVP_PKEY_free(client_private_key);
  2860. t.join();
  2861. }
  2862. #endif
  2863. TEST(SSLClientServerTest, ClientCertMissing) {
  2864. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2865. CLIENT_CA_CERT_DIR);
  2866. ASSERT_TRUE(svr.is_valid());
  2867. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  2868. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2869. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2870. SSLClient cli(HOST, PORT);
  2871. auto res = cli.Get("/test");
  2872. cli.set_connection_timeout(30);
  2873. ASSERT_TRUE(!res);
  2874. EXPECT_EQ(Error::SSLServerVerification, res.error());
  2875. svr.stop();
  2876. t.join();
  2877. }
  2878. TEST(SSLClientServerTest, TrustDirOptional) {
  2879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2880. ASSERT_TRUE(svr.is_valid());
  2881. svr.Get("/test", [&](const Request &, Response &res) {
  2882. res.set_content("test", "text/plain");
  2883. svr.stop();
  2884. });
  2885. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2886. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2887. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2888. cli.enable_server_certificate_verification(false);
  2889. cli.set_connection_timeout(30);
  2890. auto res = cli.Get("/test");
  2891. ASSERT_TRUE(res);
  2892. ASSERT_EQ(200, res->status);
  2893. t.join();
  2894. }
  2895. #endif
  2896. #ifdef _WIN32
  2897. TEST(CleanupTest, WSACleanup) {
  2898. int ret = WSACleanup();
  2899. ASSERT_EQ(0, ret);
  2900. }
  2901. #endif
  2902. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  2903. TEST(NoSSLSupport, SimpleInterface) {
  2904. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  2905. }
  2906. #endif
  2907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2908. TEST(InvalidScheme, SimpleInterface) {
  2909. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  2910. }
  2911. TEST(NoScheme, SimpleInterface) {
  2912. Client cli("yahoo.com:80");
  2913. ASSERT_TRUE(cli.is_valid());
  2914. }
  2915. TEST(YahooRedirectTest2, SimpleInterface) {
  2916. Client cli("http://yahoo.com");
  2917. auto res = cli.Get("/");
  2918. ASSERT_TRUE(res);
  2919. EXPECT_EQ(301, res->status);
  2920. cli.set_follow_location(true);
  2921. res = cli.Get("/");
  2922. ASSERT_TRUE(res);
  2923. EXPECT_EQ(200, res->status);
  2924. }
  2925. TEST(YahooRedirectTest3, SimpleInterface) {
  2926. Client cli("https://yahoo.com");
  2927. auto res = cli.Get("/");
  2928. ASSERT_TRUE(res);
  2929. EXPECT_EQ(301, res->status);
  2930. cli.set_follow_location(true);
  2931. res = cli.Get("/");
  2932. ASSERT_TRUE(res);
  2933. EXPECT_EQ(200, res->status);
  2934. }
  2935. TEST(YahooRedirectTest3, NewResultInterface) {
  2936. Client cli("https://yahoo.com");
  2937. auto res = cli.Get("/");
  2938. ASSERT_TRUE(res);
  2939. ASSERT_FALSE(!res);
  2940. ASSERT_TRUE(res);
  2941. ASSERT_FALSE(res == nullptr);
  2942. ASSERT_TRUE(res != nullptr);
  2943. EXPECT_EQ(Error::Success, res.error());
  2944. EXPECT_EQ(301, res.value().status);
  2945. EXPECT_EQ(301, (*res).status);
  2946. EXPECT_EQ(301, res->status);
  2947. cli.set_follow_location(true);
  2948. res = cli.Get("/");
  2949. ASSERT_TRUE(res);
  2950. EXPECT_EQ(Error::Success, res.error());
  2951. EXPECT_EQ(200, res.value().status);
  2952. EXPECT_EQ(200, (*res).status);
  2953. EXPECT_EQ(200, res->status);
  2954. }
  2955. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2956. TEST(DecodeWithChunkedEncoding, BrotliEncoding) {
  2957. Client cli("https://cdnjs.cloudflare.com");
  2958. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  2959. {{"Accept-Encoding", "brotli"}});
  2960. ASSERT_TRUE(res);
  2961. EXPECT_EQ(200, res->status);
  2962. EXPECT_EQ(287630, res->body.size());
  2963. EXPECT_EQ("application/javascript; charset=utf-8",
  2964. res->get_header_value("Content-Type"));
  2965. }
  2966. #endif
  2967. #if 0
  2968. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  2969. auto res =
  2970. Client("https://httpbin.org")
  2971. .set_follow_location(true)
  2972. .Get("/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  2973. ASSERT_TRUE(res);
  2974. EXPECT_EQ(200, res->status);
  2975. }
  2976. #endif
  2977. #endif