test.cc 108 KB

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