http_server_async_ssl.cpp 17 KB

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