test.cc 111 KB

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