http_server_coro.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. //
  2. // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/beast
  8. //
  9. //------------------------------------------------------------------------------
  10. //
  11. // Example: HTTP server, coroutine
  12. //
  13. //------------------------------------------------------------------------------
  14. #include <boost/beast/core.hpp>
  15. #include <boost/beast/http.hpp>
  16. #include <boost/beast/version.hpp>
  17. #include <boost/asio/ip/tcp.hpp>
  18. #include <boost/asio/spawn.hpp>
  19. #include <boost/config.hpp>
  20. #include <algorithm>
  21. #include <cstdlib>
  22. #include <iostream>
  23. #include <memory>
  24. #include <string>
  25. #include <thread>
  26. #include <vector>
  27. namespace beast = boost::beast; // from <boost/beast.hpp>
  28. namespace http = beast::http; // from <boost/beast/http.hpp>
  29. namespace net = boost::asio; // from <boost/asio.hpp>
  30. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  31. // Return a reasonable mime type based on the extension of a file.
  32. beast::string_view
  33. mime_type(beast::string_view path)
  34. {
  35. using beast::iequals;
  36. auto const ext = [&path]
  37. {
  38. auto const pos = path.rfind(".");
  39. if(pos == beast::string_view::npos)
  40. return beast::string_view{};
  41. return path.substr(pos);
  42. }();
  43. if(iequals(ext, ".htm")) return "text/html";
  44. if(iequals(ext, ".html")) return "text/html";
  45. if(iequals(ext, ".php")) return "text/html";
  46. if(iequals(ext, ".css")) return "text/css";
  47. if(iequals(ext, ".txt")) return "text/plain";
  48. if(iequals(ext, ".js")) return "application/javascript";
  49. if(iequals(ext, ".json")) return "application/json";
  50. if(iequals(ext, ".xml")) return "application/xml";
  51. if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
  52. if(iequals(ext, ".flv")) return "video/x-flv";
  53. if(iequals(ext, ".png")) return "image/png";
  54. if(iequals(ext, ".jpe")) return "image/jpeg";
  55. if(iequals(ext, ".jpeg")) return "image/jpeg";
  56. if(iequals(ext, ".jpg")) return "image/jpeg";
  57. if(iequals(ext, ".gif")) return "image/gif";
  58. if(iequals(ext, ".bmp")) return "image/bmp";
  59. if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
  60. if(iequals(ext, ".tiff")) return "image/tiff";
  61. if(iequals(ext, ".tif")) return "image/tiff";
  62. if(iequals(ext, ".svg")) return "image/svg+xml";
  63. if(iequals(ext, ".svgz")) return "image/svg+xml";
  64. return "application/text";
  65. }
  66. // Append an HTTP rel-path to a local filesystem path.
  67. // The returned path is normalized for the platform.
  68. std::string
  69. path_cat(
  70. beast::string_view base,
  71. beast::string_view path)
  72. {
  73. if(base.empty())
  74. return std::string(path);
  75. std::string result(base);
  76. #ifdef BOOST_MSVC
  77. char constexpr path_separator = '\\';
  78. if(result.back() == path_separator)
  79. result.resize(result.size() - 1);
  80. result.append(path.data(), path.size());
  81. for(auto& c : result)
  82. if(c == '/')
  83. c = path_separator;
  84. #else
  85. char constexpr path_separator = '/';
  86. if(result.back() == path_separator)
  87. result.resize(result.size() - 1);
  88. result.append(path.data(), path.size());
  89. #endif
  90. return result;
  91. }
  92. // This function produces an HTTP response for the given
  93. // request. The type of the response object depends on the
  94. // contents of the request, so the interface requires the
  95. // caller to pass a generic lambda for receiving the response.
  96. template<
  97. class Body, class Allocator,
  98. class Send>
  99. void
  100. handle_request(
  101. beast::string_view doc_root,
  102. http::request<Body, http::basic_fields<Allocator>>&& req,
  103. Send&& send)
  104. {
  105. // Returns a bad request response
  106. auto const bad_request =
  107. [&req](beast::string_view why)
  108. {
  109. http::response<http::string_body> res{http::status::bad_request, req.version()};
  110. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  111. res.set(http::field::content_type, "text/html");
  112. res.keep_alive(req.keep_alive());
  113. res.body() = std::string(why);
  114. res.prepare_payload();
  115. return res;
  116. };
  117. // Returns a not found response
  118. auto const not_found =
  119. [&req](beast::string_view target)
  120. {
  121. http::response<http::string_body> res{http::status::not_found, req.version()};
  122. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  123. res.set(http::field::content_type, "text/html");
  124. res.keep_alive(req.keep_alive());
  125. res.body() = "The resource '" + std::string(target) + "' was not found.";
  126. res.prepare_payload();
  127. return res;
  128. };
  129. // Returns a server error response
  130. auto const server_error =
  131. [&req](beast::string_view what)
  132. {
  133. http::response<http::string_body> res{http::status::internal_server_error, req.version()};
  134. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  135. res.set(http::field::content_type, "text/html");
  136. res.keep_alive(req.keep_alive());
  137. res.body() = "An error occurred: '" + std::string(what) + "'";
  138. res.prepare_payload();
  139. return res;
  140. };
  141. // Make sure we can handle the method
  142. if( req.method() != http::verb::get &&
  143. req.method() != http::verb::head)
  144. return send(bad_request("Unknown HTTP-method"));
  145. // Request path must be absolute and not contain "..".
  146. if( req.target().empty() ||
  147. req.target()[0] != '/' ||
  148. req.target().find("..") != beast::string_view::npos)
  149. return send(bad_request("Illegal request-target"));
  150. // Build the path to the requested file
  151. std::string path = path_cat(doc_root, req.target());
  152. if(req.target().back() == '/')
  153. path.append("index.html");
  154. // Attempt to open the file
  155. beast::error_code ec;
  156. http::file_body::value_type body;
  157. body.open(path.c_str(), beast::file_mode::scan, ec);
  158. // Handle the case where the file doesn't exist
  159. if(ec == beast::errc::no_such_file_or_directory)
  160. return send(not_found(req.target()));
  161. // Handle an unknown error
  162. if(ec)
  163. return send(server_error(ec.message()));
  164. // Cache the size since we need it after the move
  165. auto const size = body.size();
  166. // Respond to HEAD request
  167. if(req.method() == http::verb::head)
  168. {
  169. http::response<http::empty_body> res{http::status::ok, req.version()};
  170. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  171. res.set(http::field::content_type, mime_type(path));
  172. res.content_length(size);
  173. res.keep_alive(req.keep_alive());
  174. return send(std::move(res));
  175. }
  176. // Respond to GET request
  177. http::response<http::file_body> res{
  178. std::piecewise_construct,
  179. std::make_tuple(std::move(body)),
  180. std::make_tuple(http::status::ok, req.version())};
  181. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  182. res.set(http::field::content_type, mime_type(path));
  183. res.content_length(size);
  184. res.keep_alive(req.keep_alive());
  185. return send(std::move(res));
  186. }
  187. //------------------------------------------------------------------------------
  188. // Report a failure
  189. void
  190. fail(beast::error_code ec, char const* what)
  191. {
  192. std::cerr << what << ": " << ec.message() << "\n";
  193. }
  194. // This is the C++11 equivalent of a generic lambda.
  195. // The function object is used to send an HTTP message.
  196. struct send_lambda
  197. {
  198. beast::tcp_stream& stream_;
  199. bool& close_;
  200. beast::error_code& ec_;
  201. net::yield_context yield_;
  202. send_lambda(
  203. beast::tcp_stream& stream,
  204. bool& close,
  205. beast::error_code& ec,
  206. net::yield_context yield)
  207. : stream_(stream)
  208. , close_(close)
  209. , ec_(ec)
  210. , yield_(yield)
  211. {
  212. }
  213. template<bool isRequest, class Body, class Fields>
  214. void
  215. operator()(http::message<isRequest, Body, Fields>&& msg) const
  216. {
  217. // Determine if we should close the connection after
  218. close_ = msg.need_eof();
  219. // We need the serializer here because the serializer requires
  220. // a non-const file_body, and the message oriented version of
  221. // http::write only works with const messages.
  222. http::serializer<isRequest, Body, Fields> sr{msg};
  223. http::async_write(stream_, sr, yield_[ec_]);
  224. }
  225. };
  226. // Handles an HTTP server connection
  227. void
  228. do_session(
  229. beast::tcp_stream& stream,
  230. std::shared_ptr<std::string const> const& doc_root,
  231. net::yield_context yield)
  232. {
  233. bool close = false;
  234. beast::error_code ec;
  235. // This buffer is required to persist across reads
  236. beast::flat_buffer buffer;
  237. // This lambda is used to send messages
  238. send_lambda lambda{stream, close, ec, yield};
  239. for(;;)
  240. {
  241. // Set the timeout.
  242. stream.expires_after(std::chrono::seconds(30));
  243. // Read a request
  244. http::request<http::string_body> req;
  245. http::async_read(stream, buffer, req, yield[ec]);
  246. if(ec == http::error::end_of_stream)
  247. break;
  248. if(ec)
  249. return fail(ec, "read");
  250. // Send the response
  251. handle_request(*doc_root, std::move(req), lambda);
  252. if(ec)
  253. return fail(ec, "write");
  254. if(close)
  255. {
  256. // This means we should close the connection, usually because
  257. // the response indicated the "Connection: close" semantic.
  258. break;
  259. }
  260. }
  261. // Send a TCP shutdown
  262. stream.socket().shutdown(tcp::socket::shutdown_send, ec);
  263. // At this point the connection is closed gracefully
  264. }
  265. //------------------------------------------------------------------------------
  266. // Accepts incoming connections and launches the sessions
  267. void
  268. do_listen(
  269. net::io_context& ioc,
  270. tcp::endpoint endpoint,
  271. std::shared_ptr<std::string const> const& doc_root,
  272. net::yield_context yield)
  273. {
  274. beast::error_code ec;
  275. // Open the acceptor
  276. tcp::acceptor acceptor(ioc);
  277. acceptor.open(endpoint.protocol(), ec);
  278. if(ec)
  279. return fail(ec, "open");
  280. // Allow address reuse
  281. acceptor.set_option(net::socket_base::reuse_address(true), ec);
  282. if(ec)
  283. return fail(ec, "set_option");
  284. // Bind to the server address
  285. acceptor.bind(endpoint, ec);
  286. if(ec)
  287. return fail(ec, "bind");
  288. // Start listening for connections
  289. acceptor.listen(net::socket_base::max_listen_connections, ec);
  290. if(ec)
  291. return fail(ec, "listen");
  292. for(;;)
  293. {
  294. tcp::socket socket(ioc);
  295. acceptor.async_accept(socket, yield[ec]);
  296. if(ec)
  297. fail(ec, "accept");
  298. else
  299. boost::asio::spawn(
  300. acceptor.get_executor(),
  301. std::bind(
  302. &do_session,
  303. beast::tcp_stream(std::move(socket)),
  304. doc_root,
  305. std::placeholders::_1));
  306. }
  307. }
  308. int main(int argc, char* argv[])
  309. {
  310. // Check command line arguments.
  311. if (argc != 5)
  312. {
  313. std::cerr <<
  314. "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" <<
  315. "Example:\n" <<
  316. " http-server-coro 0.0.0.0 8080 . 1\n";
  317. return EXIT_FAILURE;
  318. }
  319. auto const address = net::ip::make_address(argv[1]);
  320. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  321. auto const doc_root = std::make_shared<std::string>(argv[3]);
  322. auto const threads = std::max<int>(1, std::atoi(argv[4]));
  323. // The io_context is required for all I/O
  324. net::io_context ioc{threads};
  325. // Spawn a listening port
  326. boost::asio::spawn(ioc,
  327. std::bind(
  328. &do_listen,
  329. std::ref(ioc),
  330. tcp::endpoint{address, port},
  331. doc_root,
  332. std::placeholders::_1));
  333. // Run the I/O service on the requested number of threads
  334. std::vector<std::thread> v;
  335. v.reserve(threads - 1);
  336. for(auto i = threads - 1; i > 0; --i)
  337. v.emplace_back(
  338. [&ioc]
  339. {
  340. ioc.run();
  341. });
  342. ioc.run();
  343. return EXIT_SUCCESS;
  344. }