test.cc 93 KB

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