http_server_async.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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, asynchronous
  12. //
  13. //------------------------------------------------------------------------------
  14. #include <boost/beast/core.hpp>
  15. #include <boost/beast/http.hpp>
  16. #include <boost/beast/version.hpp>
  17. #include <boost/asio/dispatch.hpp>
  18. #include <boost/asio/strand.hpp>
  19. #include <boost/config.hpp>
  20. #include <algorithm>
  21. #include <cstdlib>
  22. #include <functional>
  23. #include <iostream>
  24. #include <memory>
  25. #include <string>
  26. #include <thread>
  27. #include <vector>
  28. namespace beast = boost::beast; // from <boost/beast.hpp>
  29. namespace http = beast::http; // from <boost/beast/http.hpp>
  30. namespace net = boost::asio; // from <boost/asio.hpp>
  31. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  32. // Return a reasonable mime type based on the extension of a file.
  33. beast::string_view
  34. mime_type(beast::string_view path)
  35. {
  36. using beast::iequals;
  37. auto const ext = [&path]
  38. {
  39. auto const pos = path.rfind(".");
  40. if(pos == beast::string_view::npos)
  41. return beast::string_view{};
  42. return path.substr(pos);
  43. }();
  44. if(iequals(ext, ".htm")) return "text/html";
  45. if(iequals(ext, ".html")) return "text/html";
  46. if(iequals(ext, ".php")) return "text/html";
  47. if(iequals(ext, ".css")) return "text/css";
  48. if(iequals(ext, ".txt")) return "text/plain";
  49. if(iequals(ext, ".js")) return "application/javascript";
  50. if(iequals(ext, ".json")) return "application/json";
  51. if(iequals(ext, ".xml")) return "application/xml";
  52. if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
  53. if(iequals(ext, ".flv")) return "video/x-flv";
  54. if(iequals(ext, ".png")) return "image/png";
  55. if(iequals(ext, ".jpe")) return "image/jpeg";
  56. if(iequals(ext, ".jpeg")) return "image/jpeg";
  57. if(iequals(ext, ".jpg")) return "image/jpeg";
  58. if(iequals(ext, ".gif")) return "image/gif";
  59. if(iequals(ext, ".bmp")) return "image/bmp";
  60. if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
  61. if(iequals(ext, ".tiff")) return "image/tiff";
  62. if(iequals(ext, ".tif")) return "image/tiff";
  63. if(iequals(ext, ".svg")) return "image/svg+xml";
  64. if(iequals(ext, ".svgz")) return "image/svg+xml";
  65. return "application/text";
  66. }
  67. // Append an HTTP rel-path to a local filesystem path.
  68. // The returned path is normalized for the platform.
  69. std::string
  70. path_cat(
  71. beast::string_view base,
  72. beast::string_view path)
  73. {
  74. if(base.empty())
  75. return std::string(path);
  76. std::string result(base);
  77. #ifdef BOOST_MSVC
  78. char constexpr path_separator = '\\';
  79. if(result.back() == path_separator)
  80. result.resize(result.size() - 1);
  81. result.append(path.data(), path.size());
  82. for(auto& c : result)
  83. if(c == '/')
  84. c = path_separator;
  85. #else
  86. char constexpr path_separator = '/';
  87. if(result.back() == path_separator)
  88. result.resize(result.size() - 1);
  89. result.append(path.data(), path.size());
  90. #endif
  91. return result;
  92. }
  93. // This function produces an HTTP response for the given
  94. // request. The type of the response object depends on the
  95. // contents of the request, so the interface requires the
  96. // caller to pass a generic lambda for receiving the response.
  97. template<
  98. class Body, class Allocator,
  99. class Send>
  100. void
  101. handle_request(
  102. beast::string_view doc_root,
  103. http::request<Body, http::basic_fields<Allocator>>&& req,
  104. Send&& send)
  105. {
  106. // Returns a bad request response
  107. auto const bad_request =
  108. [&req](beast::string_view why)
  109. {
  110. http::response<http::string_body> res{http::status::bad_request, req.version()};
  111. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  112. res.set(http::field::content_type, "text/html");
  113. res.keep_alive(req.keep_alive());
  114. res.body() = std::string(why);
  115. res.prepare_payload();
  116. return res;
  117. };
  118. // Returns a not found response
  119. auto const not_found =
  120. [&req](beast::string_view target)
  121. {
  122. http::response<http::string_body> res{http::status::not_found, req.version()};
  123. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  124. res.set(http::field::content_type, "text/html");
  125. res.keep_alive(req.keep_alive());
  126. res.body() = "The resource '" + std::string(target) + "' was not found.";
  127. res.prepare_payload();
  128. return res;
  129. };
  130. // Returns a server error response
  131. auto const server_error =
  132. [&req](beast::string_view what)
  133. {
  134. http::response<http::string_body> res{http::status::internal_server_error, req.version()};
  135. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  136. res.set(http::field::content_type, "text/html");
  137. res.keep_alive(req.keep_alive());
  138. res.body() = "An error occurred: '" + std::string(what) + "'";
  139. res.prepare_payload();
  140. return res;
  141. };
  142. // Make sure we can handle the method
  143. if( req.method() != http::verb::get &&
  144. req.method() != http::verb::head)
  145. return send(bad_request("Unknown HTTP-method"));
  146. // Request path must be absolute and not contain "..".
  147. if( req.target().empty() ||
  148. req.target()[0] != '/' ||
  149. req.target().find("..") != beast::string_view::npos)
  150. return send(bad_request("Illegal request-target"));
  151. // Build the path to the requested file
  152. std::string path = path_cat(doc_root, req.target());
  153. if(req.target().back() == '/')
  154. path.append("index.html");
  155. // Attempt to open the file
  156. beast::error_code ec;
  157. http::file_body::value_type body;
  158. body.open(path.c_str(), beast::file_mode::scan, ec);
  159. // Handle the case where the file doesn't exist
  160. if(ec == beast::errc::no_such_file_or_directory)
  161. return send(not_found(req.target()));
  162. // Handle an unknown error
  163. if(ec)
  164. return send(server_error(ec.message()));
  165. // Cache the size since we need it after the move
  166. auto const size = body.size();
  167. // Respond to HEAD request
  168. if(req.method() == http::verb::head)
  169. {
  170. http::response<http::empty_body> res{http::status::ok, req.version()};
  171. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  172. res.set(http::field::content_type, mime_type(path));
  173. res.content_length(size);
  174. res.keep_alive(req.keep_alive());
  175. return send(std::move(res));
  176. }
  177. // Respond to GET request
  178. http::response<http::file_body> res{
  179. std::piecewise_construct,
  180. std::make_tuple(std::move(body)),
  181. std::make_tuple(http::status::ok, req.version())};
  182. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  183. res.set(http::field::content_type, mime_type(path));
  184. res.content_length(size);
  185. res.keep_alive(req.keep_alive());
  186. return send(std::move(res));
  187. }
  188. //------------------------------------------------------------------------------
  189. // Report a failure
  190. void
  191. fail(beast::error_code ec, char const* what)
  192. {
  193. std::cerr << what << ": " << ec.message() << "\n";
  194. }
  195. // Handles an HTTP server connection
  196. class session : public std::enable_shared_from_this<session>
  197. {
  198. // This is the C++11 equivalent of a generic lambda.
  199. // The function object is used to send an HTTP message.
  200. struct send_lambda
  201. {
  202. session& self_;
  203. explicit
  204. send_lambda(session& self)
  205. : self_(self)
  206. {
  207. }
  208. template<bool isRequest, class Body, class Fields>
  209. void
  210. operator()(http::message<isRequest, Body, Fields>&& msg) const
  211. {
  212. // The lifetime of the message has to extend
  213. // for the duration of the async operation so
  214. // we use a shared_ptr to manage it.
  215. auto sp = std::make_shared<
  216. http::message<isRequest, Body, Fields>>(std::move(msg));
  217. // Store a type-erased version of the shared
  218. // pointer in the class to keep it alive.
  219. self_.res_ = sp;
  220. // Write the response
  221. http::async_write(
  222. self_.stream_,
  223. *sp,
  224. beast::bind_front_handler(
  225. &session::on_write,
  226. self_.shared_from_this(),
  227. sp->need_eof()));
  228. }
  229. };
  230. beast::tcp_stream stream_;
  231. beast::flat_buffer buffer_;
  232. std::shared_ptr<std::string const> doc_root_;
  233. http::request<http::string_body> req_;
  234. std::shared_ptr<void> res_;
  235. send_lambda lambda_;
  236. public:
  237. // Take ownership of the stream
  238. session(
  239. tcp::socket&& socket,
  240. std::shared_ptr<std::string const> const& doc_root)
  241. : stream_(std::move(socket))
  242. , doc_root_(doc_root)
  243. , lambda_(*this)
  244. {
  245. }
  246. // Start the asynchronous operation
  247. void
  248. run()
  249. {
  250. // We need to be executing within a strand to perform async operations
  251. // on the I/O objects in this session. Although not strictly necessary
  252. // for single-threaded contexts, this example code is written to be
  253. // thread-safe by default.
  254. net::dispatch(stream_.get_executor(),
  255. beast::bind_front_handler(
  256. &session::do_read,
  257. shared_from_this()));
  258. }
  259. void
  260. do_read()
  261. {
  262. // Make the request empty before reading,
  263. // otherwise the operation behavior is undefined.
  264. req_ = {};
  265. // Set the timeout.
  266. stream_.expires_after(std::chrono::seconds(30));
  267. // Read a request
  268. http::async_read(stream_, buffer_, req_,
  269. beast::bind_front_handler(
  270. &session::on_read,
  271. shared_from_this()));
  272. }
  273. void
  274. on_read(
  275. beast::error_code ec,
  276. std::size_t bytes_transferred)
  277. {
  278. boost::ignore_unused(bytes_transferred);
  279. // This means they closed the connection
  280. if(ec == http::error::end_of_stream)
  281. return do_close();
  282. if(ec)
  283. return fail(ec, "read");
  284. // Send the response
  285. handle_request(*doc_root_, std::move(req_), lambda_);
  286. }
  287. void
  288. on_write(
  289. bool close,
  290. beast::error_code ec,
  291. std::size_t bytes_transferred)
  292. {
  293. boost::ignore_unused(bytes_transferred);
  294. if(ec)
  295. return fail(ec, "write");
  296. if(close)
  297. {
  298. // This means we should close the connection, usually because
  299. // the response indicated the "Connection: close" semantic.
  300. return do_close();
  301. }
  302. // We're done with the response so delete it
  303. res_ = nullptr;
  304. // Read another request
  305. do_read();
  306. }
  307. void
  308. do_close()
  309. {
  310. // Send a TCP shutdown
  311. beast::error_code ec;
  312. stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
  313. // At this point the connection is closed gracefully
  314. }
  315. };
  316. //------------------------------------------------------------------------------
  317. // Accepts incoming connections and launches the sessions
  318. class listener : public std::enable_shared_from_this<listener>
  319. {
  320. net::io_context& ioc_;
  321. tcp::acceptor acceptor_;
  322. std::shared_ptr<std::string const> doc_root_;
  323. public:
  324. listener(
  325. net::io_context& ioc,
  326. tcp::endpoint endpoint,
  327. std::shared_ptr<std::string const> const& doc_root)
  328. : ioc_(ioc)
  329. , acceptor_(net::make_strand(ioc))
  330. , doc_root_(doc_root)
  331. {
  332. beast::error_code ec;
  333. // Open the acceptor
  334. acceptor_.open(endpoint.protocol(), ec);
  335. if(ec)
  336. {
  337. fail(ec, "open");
  338. return;
  339. }
  340. // Allow address reuse
  341. acceptor_.set_option(net::socket_base::reuse_address(true), ec);
  342. if(ec)
  343. {
  344. fail(ec, "set_option");
  345. return;
  346. }
  347. // Bind to the server address
  348. acceptor_.bind(endpoint, ec);
  349. if(ec)
  350. {
  351. fail(ec, "bind");
  352. return;
  353. }
  354. // Start listening for connections
  355. acceptor_.listen(
  356. net::socket_base::max_listen_connections, ec);
  357. if(ec)
  358. {
  359. fail(ec, "listen");
  360. return;
  361. }
  362. }
  363. // Start accepting incoming connections
  364. void
  365. run()
  366. {
  367. do_accept();
  368. }
  369. private:
  370. void
  371. do_accept()
  372. {
  373. // The new connection gets its own strand
  374. acceptor_.async_accept(
  375. net::make_strand(ioc_),
  376. beast::bind_front_handler(
  377. &listener::on_accept,
  378. shared_from_this()));
  379. }
  380. void
  381. on_accept(beast::error_code ec, tcp::socket socket)
  382. {
  383. if(ec)
  384. {
  385. fail(ec, "accept");
  386. }
  387. else
  388. {
  389. // Create the session and run it
  390. std::make_shared<session>(
  391. std::move(socket),
  392. doc_root_)->run();
  393. }
  394. // Accept another connection
  395. do_accept();
  396. }
  397. };
  398. //------------------------------------------------------------------------------
  399. int main(int argc, char* argv[])
  400. {
  401. // Check command line arguments.
  402. if (argc != 5)
  403. {
  404. std::cerr <<
  405. "Usage: http-server-async <address> <port> <doc_root> <threads>\n" <<
  406. "Example:\n" <<
  407. " http-server-async 0.0.0.0 8080 . 1\n";
  408. return EXIT_FAILURE;
  409. }
  410. auto const address = net::ip::make_address(argv[1]);
  411. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  412. auto const doc_root = std::make_shared<std::string>(argv[3]);
  413. auto const threads = std::max<int>(1, std::atoi(argv[4]));
  414. // The io_context is required for all I/O
  415. net::io_context ioc{threads};
  416. // Create and launch a listening port
  417. std::make_shared<listener>(
  418. ioc,
  419. tcp::endpoint{address, port},
  420. doc_root)->run();
  421. // Run the I/O service on the requested number of threads
  422. std::vector<std::thread> v;
  423. v.reserve(threads - 1);
  424. for(auto i = threads - 1; i > 0; --i)
  425. v.emplace_back(
  426. [&ioc]
  427. {
  428. ioc.run();
  429. });
  430. ioc.run();
  431. return EXIT_SUCCESS;
  432. }