test.cc 105 KB

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