test.cc 101 KB

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