http_server_stackless_ssl.cpp 17 KB

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