test.cc 91 KB

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