test.cc 95 KB

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