http_server_coro_ssl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 SSL server, coroutine
  12. //
  13. //------------------------------------------------------------------------------
  14. #include "example/common/server_certificate.hpp"
  15. #include <boost/beast/core.hpp>
  16. #include <boost/beast/http.hpp>
  17. #include <boost/beast/ssl.hpp>
  18. #include <boost/beast/version.hpp>
  19. #include <boost/asio/spawn.hpp>
  20. #include <boost/config.hpp>
  21. #include <algorithm>
  22. #include <cstdlib>
  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. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.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. // ssl::error::stream_truncated, also known as an SSL "short read",
  195. // indicates the peer closed the connection without performing the
  196. // required closing handshake (for example, Google does this to
  197. // improve performance). Generally this can be a security issue,
  198. // but if your communication protocol is self-terminated (as
  199. // it is with both HTTP and WebSocket) then you may simply
  200. // ignore the lack of close_notify.
  201. //
  202. // https://github.com/boostorg/beast/issues/38
  203. //
  204. // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
  205. //
  206. // When a short read would cut off the end of an HTTP message,
  207. // Beast returns the error beast::http::error::partial_message.
  208. // Therefore, if we see a short read here, it has occurred
  209. // after the message has been completed, so it is safe to ignore it.
  210. if(ec == net::ssl::error::stream_truncated)
  211. return;
  212. std::cerr << what << ": " << ec.message() << "\n";
  213. }
  214. // This is the C++11 equivalent of a generic lambda.
  215. // The function object is used to send an HTTP message.
  216. struct send_lambda
  217. {
  218. beast::ssl_stream<beast::tcp_stream>& stream_;
  219. bool& close_;
  220. beast::error_code& ec_;
  221. net::yield_context yield_;
  222. send_lambda(
  223. beast::ssl_stream<beast::tcp_stream>& stream,
  224. bool& close,
  225. beast::error_code& ec,
  226. net::yield_context yield)
  227. : stream_(stream)
  228. , close_(close)
  229. , ec_(ec)
  230. , yield_(yield)
  231. {
  232. }
  233. template<bool isRequest, class Body, class Fields>
  234. void
  235. operator()(http::message<isRequest, Body, Fields>&& msg) const
  236. {
  237. // Determine if we should close the connection after
  238. close_ = msg.need_eof();
  239. // We need the serializer here because the serializer requires
  240. // a non-const file_body, and the message oriented version of
  241. // http::write only works with const messages.
  242. http::serializer<isRequest, Body, Fields> sr{msg};
  243. http::async_write(stream_, sr, yield_[ec_]);
  244. }
  245. };
  246. // Handles an HTTP server connection
  247. void
  248. do_session(
  249. beast::ssl_stream<beast::tcp_stream>& stream,
  250. std::shared_ptr<std::string const> const& doc_root,
  251. net::yield_context yield)
  252. {
  253. bool close = false;
  254. beast::error_code ec;
  255. // Set the timeout.
  256. beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
  257. // Perform the SSL handshake
  258. stream.async_handshake(ssl::stream_base::server, yield[ec]);
  259. if(ec)
  260. return fail(ec, "handshake");
  261. // This buffer is required to persist across reads
  262. beast::flat_buffer buffer;
  263. // This lambda is used to send messages
  264. send_lambda lambda{stream, close, ec, yield};
  265. for(;;)
  266. {
  267. // Set the timeout.
  268. beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
  269. // Read a request
  270. http::request<http::string_body> req;
  271. http::async_read(stream, buffer, req, yield[ec]);
  272. if(ec == http::error::end_of_stream)
  273. break;
  274. if(ec)
  275. return fail(ec, "read");
  276. // Send the response
  277. handle_request(*doc_root, std::move(req), lambda);
  278. if(ec)
  279. return fail(ec, "write");
  280. if(close)
  281. {
  282. // This means we should close the connection, usually because
  283. // the response indicated the "Connection: close" semantic.
  284. break;
  285. }
  286. }
  287. // Set the timeout.
  288. beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
  289. // Perform the SSL shutdown
  290. stream.async_shutdown(yield[ec]);
  291. if(ec)
  292. return fail(ec, "shutdown");
  293. // At this point the connection is closed gracefully
  294. }
  295. //------------------------------------------------------------------------------
  296. // Accepts incoming connections and launches the sessions
  297. void
  298. do_listen(
  299. net::io_context& ioc,
  300. ssl::context& ctx,
  301. tcp::endpoint endpoint,
  302. std::shared_ptr<std::string const> const& doc_root,
  303. net::yield_context yield)
  304. {
  305. beast::error_code ec;
  306. // Open the acceptor
  307. tcp::acceptor acceptor(ioc);
  308. acceptor.open(endpoint.protocol(), ec);
  309. if(ec)
  310. return fail(ec, "open");
  311. // Allow address reuse
  312. acceptor.set_option(net::socket_base::reuse_address(true), ec);
  313. if(ec)
  314. return fail(ec, "set_option");
  315. // Bind to the server address
  316. acceptor.bind(endpoint, ec);
  317. if(ec)
  318. return fail(ec, "bind");
  319. // Start listening for connections
  320. acceptor.listen(net::socket_base::max_listen_connections, ec);
  321. if(ec)
  322. return fail(ec, "listen");
  323. for(;;)
  324. {
  325. tcp::socket socket(ioc);
  326. acceptor.async_accept(socket, yield[ec]);
  327. if(ec)
  328. fail(ec, "accept");
  329. else
  330. boost::asio::spawn(
  331. acceptor.get_executor(),
  332. std::bind(
  333. &do_session,
  334. beast::ssl_stream<beast::tcp_stream>(
  335. std::move(socket), ctx),
  336. doc_root,
  337. std::placeholders::_1));
  338. }
  339. }
  340. int main(int argc, char* argv[])
  341. {
  342. // Check command line arguments.
  343. if (argc != 5)
  344. {
  345. std::cerr <<
  346. "Usage: http-server-coro-ssl <address> <port> <doc_root> <threads>\n" <<
  347. "Example:\n" <<
  348. " http-server-coro-ssl 0.0.0.0 8080 . 1\n";
  349. return EXIT_FAILURE;
  350. }
  351. auto const address = net::ip::make_address(argv[1]);
  352. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  353. auto const doc_root = std::make_shared<std::string>(argv[3]);
  354. auto const threads = std::max<int>(1, std::atoi(argv[4]));
  355. // The io_context is required for all I/O
  356. net::io_context ioc{threads};
  357. // The SSL context is required, and holds certificates
  358. ssl::context ctx{ssl::context::tlsv12};
  359. // This holds the self-signed certificate used by the server
  360. load_server_certificate(ctx);
  361. // Spawn a listening port
  362. boost::asio::spawn(ioc,
  363. std::bind(
  364. &do_listen,
  365. std::ref(ioc),
  366. std::ref(ctx),
  367. tcp::endpoint{address, port},
  368. doc_root,
  369. std::placeholders::_1));
  370. // Run the I/O service on the requested number of threads
  371. std::vector<std::thread> v;
  372. v.reserve(threads - 1);
  373. for(auto i = threads - 1; i > 0; --i)
  374. v.emplace_back(
  375. [&ioc]
  376. {
  377. ioc.run();
  378. });
  379. ioc.run();
  380. return EXIT_SUCCESS;
  381. }