test.cc 92 KB

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