test.cc 100 KB

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