http_server_sync.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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, synchronous
  12. //
  13. //------------------------------------------------------------------------------
  14. #include <boost/beast/core.hpp>
  15. #include <boost/beast/http.hpp>
  16. #include <boost/beast/version.hpp>
  17. #include <boost/asio/ip/tcp.hpp>
  18. #include <boost/config.hpp>
  19. #include <cstdlib>
  20. #include <iostream>
  21. #include <memory>
  22. #include <string>
  23. #include <thread>
  24. namespace beast = boost::beast; // from <boost/beast.hpp>
  25. namespace http = beast::http; // from <boost/beast/http.hpp>
  26. namespace net = boost::asio; // from <boost/asio.hpp>
  27. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  28. //------------------------------------------------------------------------------
  29. // Return a reasonable mime type based on the extension of a file.
  30. beast::string_view
  31. mime_type(beast::string_view path)
  32. {
  33. using beast::iequals;
  34. auto const ext = [&path]
  35. {
  36. auto const pos = path.rfind(".");
  37. if(pos == beast::string_view::npos)
  38. return beast::string_view{};
  39. return path.substr(pos);
  40. }();
  41. if(iequals(ext, ".htm")) return "text/html";
  42. if(iequals(ext, ".html")) return "text/html";
  43. if(iequals(ext, ".php")) return "text/html";
  44. if(iequals(ext, ".css")) return "text/css";
  45. if(iequals(ext, ".txt")) return "text/plain";
  46. if(iequals(ext, ".js")) return "application/javascript";
  47. if(iequals(ext, ".json")) return "application/json";
  48. if(iequals(ext, ".xml")) return "application/xml";
  49. if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
  50. if(iequals(ext, ".flv")) return "video/x-flv";
  51. if(iequals(ext, ".png")) return "image/png";
  52. if(iequals(ext, ".jpe")) return "image/jpeg";
  53. if(iequals(ext, ".jpeg")) return "image/jpeg";
  54. if(iequals(ext, ".jpg")) return "image/jpeg";
  55. if(iequals(ext, ".gif")) return "image/gif";
  56. if(iequals(ext, ".bmp")) return "image/bmp";
  57. if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
  58. if(iequals(ext, ".tiff")) return "image/tiff";
  59. if(iequals(ext, ".tif")) return "image/tiff";
  60. if(iequals(ext, ".svg")) return "image/svg+xml";
  61. if(iequals(ext, ".svgz")) return "image/svg+xml";
  62. return "application/text";
  63. }
  64. // Append an HTTP rel-path to a local filesystem path.
  65. // The returned path is normalized for the platform.
  66. std::string
  67. path_cat(
  68. beast::string_view base,
  69. beast::string_view path)
  70. {
  71. if (base.empty())
  72. return std::string(path);
  73. std::string result(base);
  74. #ifdef BOOST_MSVC
  75. char constexpr path_separator = '\\';
  76. if(result.back() == path_separator)
  77. result.resize(result.size() - 1);
  78. result.append(path.data(), path.size());
  79. for(auto& c : result)
  80. if(c == '/')
  81. c = path_separator;
  82. #else
  83. char constexpr path_separator = '/';
  84. if(result.back() == path_separator)
  85. result.resize(result.size() - 1);
  86. result.append(path.data(), path.size());
  87. #endif
  88. return result;
  89. }
  90. // This function produces an HTTP response for the given
  91. // request. The type of the response object depends on the
  92. // contents of the request, so the interface requires the
  93. // caller to pass a generic lambda for receiving the response.
  94. template<
  95. class Body, class Allocator,
  96. class Send>
  97. void
  98. handle_request(
  99. beast::string_view doc_root,
  100. http::request<Body, http::basic_fields<Allocator>>&& req,
  101. Send&& send)
  102. {
  103. // Returns a bad request response
  104. auto const bad_request =
  105. [&req](beast::string_view why)
  106. {
  107. http::response<http::string_body> res{http::status::bad_request, req.version()};
  108. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  109. res.set(http::field::content_type, "text/html");
  110. res.keep_alive(req.keep_alive());
  111. res.body() = std::string(why);
  112. res.prepare_payload();
  113. return res;
  114. };
  115. // Returns a not found response
  116. auto const not_found =
  117. [&req](beast::string_view target)
  118. {
  119. http::response<http::string_body> res{http::status::not_found, req.version()};
  120. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  121. res.set(http::field::content_type, "text/html");
  122. res.keep_alive(req.keep_alive());
  123. res.body() = "The resource '" + std::string(target) + "' was not found.";
  124. res.prepare_payload();
  125. return res;
  126. };
  127. // Returns a server error response
  128. auto const server_error =
  129. [&req](beast::string_view what)
  130. {
  131. http::response<http::string_body> res{http::status::internal_server_error, req.version()};
  132. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  133. res.set(http::field::content_type, "text/html");
  134. res.keep_alive(req.keep_alive());
  135. res.body() = "An error occurred: '" + std::string(what) + "'";
  136. res.prepare_payload();
  137. return res;
  138. };
  139. // Make sure we can handle the method
  140. if( req.method() != http::verb::get &&
  141. req.method() != http::verb::head)
  142. return send(bad_request("Unknown HTTP-method"));
  143. // Request path must be absolute and not contain "..".
  144. if( req.target().empty() ||
  145. req.target()[0] != '/' ||
  146. req.target().find("..") != beast::string_view::npos)
  147. return send(bad_request("Illegal request-target"));
  148. // Build the path to the requested file
  149. std::string path = path_cat(doc_root, req.target());
  150. if(req.target().back() == '/')
  151. path.append("index.html");
  152. // Attempt to open the file
  153. beast::error_code ec;
  154. http::file_body::value_type body;
  155. body.open(path.c_str(), beast::file_mode::scan, ec);
  156. // Handle the case where the file doesn't exist
  157. if(ec == beast::errc::no_such_file_or_directory)
  158. return send(not_found(req.target()));
  159. // Handle an unknown error
  160. if(ec)
  161. return send(server_error(ec.message()));
  162. // Cache the size since we need it after the move
  163. auto const size = body.size();
  164. // Respond to HEAD request
  165. if(req.method() == http::verb::head)
  166. {
  167. http::response<http::empty_body> res{http::status::ok, req.version()};
  168. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  169. res.set(http::field::content_type, mime_type(path));
  170. res.content_length(size);
  171. res.keep_alive(req.keep_alive());
  172. return send(std::move(res));
  173. }
  174. // Respond to GET request
  175. http::response<http::file_body> res{
  176. std::piecewise_construct,
  177. std::make_tuple(std::move(body)),
  178. std::make_tuple(http::status::ok, req.version())};
  179. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  180. res.set(http::field::content_type, mime_type(path));
  181. res.content_length(size);
  182. res.keep_alive(req.keep_alive());
  183. return send(std::move(res));
  184. }
  185. //------------------------------------------------------------------------------
  186. // Report a failure
  187. void
  188. fail(beast::error_code ec, char const* what)
  189. {
  190. std::cerr << what << ": " << ec.message() << "\n";
  191. }
  192. // This is the C++11 equivalent of a generic lambda.
  193. // The function object is used to send an HTTP message.
  194. template<class Stream>
  195. struct send_lambda
  196. {
  197. Stream& stream_;
  198. bool& close_;
  199. beast::error_code& ec_;
  200. explicit
  201. send_lambda(
  202. Stream& stream,
  203. bool& close,
  204. beast::error_code& ec)
  205. : stream_(stream)
  206. , close_(close)
  207. , ec_(ec)
  208. {
  209. }
  210. template<bool isRequest, class Body, class Fields>
  211. void
  212. operator()(http::message<isRequest, Body, Fields>&& msg) const
  213. {
  214. // Determine if we should close the connection after
  215. close_ = msg.need_eof();
  216. // We need the serializer here because the serializer requires
  217. // a non-const file_body, and the message oriented version of
  218. // http::write only works with const messages.
  219. http::serializer<isRequest, Body, Fields> sr{msg};
  220. http::write(stream_, sr, ec_);
  221. }
  222. };
  223. // Handles an HTTP server connection
  224. void
  225. do_session(
  226. tcp::socket& socket,
  227. std::shared_ptr<std::string const> const& doc_root)
  228. {
  229. bool close = false;
  230. beast::error_code ec;
  231. // This buffer is required to persist across reads
  232. beast::flat_buffer buffer;
  233. // This lambda is used to send messages
  234. send_lambda<tcp::socket> lambda{socket, close, ec};
  235. for(;;)
  236. {
  237. // Read a request
  238. http::request<http::string_body> req;
  239. http::read(socket, buffer, req, ec);
  240. if(ec == http::error::end_of_stream)
  241. break;
  242. if(ec)
  243. return fail(ec, "read");
  244. // Send the response
  245. handle_request(*doc_root, std::move(req), lambda);
  246. if(ec)
  247. return fail(ec, "write");
  248. if(close)
  249. {
  250. // This means we should close the connection, usually because
  251. // the response indicated the "Connection: close" semantic.
  252. break;
  253. }
  254. }
  255. // Send a TCP shutdown
  256. socket.shutdown(tcp::socket::shutdown_send, ec);
  257. // At this point the connection is closed gracefully
  258. }
  259. //------------------------------------------------------------------------------
  260. int main(int argc, char* argv[])
  261. {
  262. try
  263. {
  264. // Check command line arguments.
  265. if (argc != 4)
  266. {
  267. std::cerr <<
  268. "Usage: http-server-sync <address> <port> <doc_root>\n" <<
  269. "Example:\n" <<
  270. " http-server-sync 0.0.0.0 8080 .\n";
  271. return EXIT_FAILURE;
  272. }
  273. auto const address = net::ip::make_address(argv[1]);
  274. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  275. auto const doc_root = std::make_shared<std::string>(argv[3]);
  276. // The io_context is required for all I/O
  277. net::io_context ioc{1};
  278. // The acceptor receives incoming connections
  279. tcp::acceptor acceptor{ioc, {address, port}};
  280. for(;;)
  281. {
  282. // This will receive the new connection
  283. tcp::socket socket{ioc};
  284. // Block until we get a connection
  285. acceptor.accept(socket);
  286. // Launch the session, transferring ownership of the socket
  287. std::thread{std::bind(
  288. &do_session,
  289. std::move(socket),
  290. doc_root)}.detach();
  291. }
  292. }
  293. catch (const std::exception& e)
  294. {
  295. std::cerr << "Error: " << e.what() << std::endl;
  296. return EXIT_FAILURE;
  297. }
  298. }