http_server_sync_ssl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, synchronous
  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/ip/tcp.hpp>
  20. #include <boost/asio/ssl/stream.hpp>
  21. #include <boost/config.hpp>
  22. #include <cstdlib>
  23. #include <iostream>
  24. #include <memory>
  25. #include <string>
  26. #include <thread>
  27. namespace beast = boost::beast; // from <boost/beast.hpp>
  28. namespace http = beast::http; // from <boost/beast/http.hpp>
  29. namespace net = boost::asio; // from <boost/asio.hpp>
  30. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.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. // This is the C++11 equivalent of a generic lambda.
  196. // The function object is used to send an HTTP message.
  197. template<class Stream>
  198. struct send_lambda
  199. {
  200. Stream& stream_;
  201. bool& close_;
  202. beast::error_code& ec_;
  203. explicit
  204. send_lambda(
  205. Stream& stream,
  206. bool& close,
  207. beast::error_code& ec)
  208. : stream_(stream)
  209. , close_(close)
  210. , ec_(ec)
  211. {
  212. }
  213. template<bool isRequest, class Body, class Fields>
  214. void
  215. operator()(http::message<isRequest, Body, Fields>&& msg) const
  216. {
  217. // Determine if we should close the connection after
  218. close_ = msg.need_eof();
  219. // We need the serializer here because the serializer requires
  220. // a non-const file_body, and the message oriented version of
  221. // http::write only works with const messages.
  222. http::serializer<isRequest, Body, Fields> sr{msg};
  223. http::write(stream_, sr, ec_);
  224. }
  225. };
  226. // Handles an HTTP server connection
  227. void
  228. do_session(
  229. tcp::socket& socket,
  230. ssl::context& ctx,
  231. std::shared_ptr<std::string const> const& doc_root)
  232. {
  233. bool close = false;
  234. beast::error_code ec;
  235. // Construct the stream around the socket
  236. beast::ssl_stream<tcp::socket&> stream{socket, ctx};
  237. // Perform the SSL handshake
  238. stream.handshake(ssl::stream_base::server, ec);
  239. if(ec)
  240. return fail(ec, "handshake");
  241. // This buffer is required to persist across reads
  242. beast::flat_buffer buffer;
  243. // This lambda is used to send messages
  244. send_lambda<beast::ssl_stream<tcp::socket&>> lambda{stream, close, ec};
  245. for(;;)
  246. {
  247. // Read a request
  248. http::request<http::string_body> req;
  249. http::read(stream, buffer, req, ec);
  250. if(ec == http::error::end_of_stream)
  251. break;
  252. if(ec)
  253. return fail(ec, "read");
  254. // Send the response
  255. handle_request(*doc_root, std::move(req), lambda);
  256. if(ec)
  257. return fail(ec, "write");
  258. if(close)
  259. {
  260. // This means we should close the connection, usually because
  261. // the response indicated the "Connection: close" semantic.
  262. break;
  263. }
  264. }
  265. // Perform the SSL shutdown
  266. stream.shutdown(ec);
  267. if(ec)
  268. return fail(ec, "shutdown");
  269. // At this point the connection is closed gracefully
  270. }
  271. //------------------------------------------------------------------------------
  272. int main(int argc, char* argv[])
  273. {
  274. try
  275. {
  276. // Check command line arguments.
  277. if (argc != 4)
  278. {
  279. std::cerr <<
  280. "Usage: http-server-sync-ssl <address> <port> <doc_root>\n" <<
  281. "Example:\n" <<
  282. " http-server-sync-ssl 0.0.0.0 8080 .\n";
  283. return EXIT_FAILURE;
  284. }
  285. auto const address = net::ip::make_address(argv[1]);
  286. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  287. auto const doc_root = std::make_shared<std::string>(argv[3]);
  288. // The io_context is required for all I/O
  289. net::io_context ioc{1};
  290. // The SSL context is required, and holds certificates
  291. ssl::context ctx{ssl::context::tlsv12};
  292. // This holds the self-signed certificate used by the server
  293. load_server_certificate(ctx);
  294. // The acceptor receives incoming connections
  295. tcp::acceptor acceptor{ioc, {address, port}};
  296. for(;;)
  297. {
  298. // This will receive the new connection
  299. tcp::socket socket{ioc};
  300. // Block until we get a connection
  301. acceptor.accept(socket);
  302. // Launch the session, transferring ownership of the socket
  303. std::thread{std::bind(
  304. &do_session,
  305. std::move(socket),
  306. std::ref(ctx),
  307. doc_root)}.detach();
  308. }
  309. }
  310. catch (const std::exception& e)
  311. {
  312. std::cerr << "Error: " << e.what() << std::endl;
  313. return EXIT_FAILURE;
  314. }
  315. }