test.cc 105 KB

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