http_server_stackless.cpp 15 KB

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