2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
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)
7 // Official repository: https://github.com/boostorg/beast
10 //------------------------------------------------------------------------------
12 // Example: HTTP SSL server, stackless coroutine
14 //------------------------------------------------------------------------------
16 #include "example/common/server_certificate.hpp"
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/http.hpp>
20 #include <boost/beast/ssl.hpp>
21 #include <boost/beast/version.hpp>
22 #include <boost/asio/coroutine.hpp>
23 #include <boost/asio/dispatch.hpp>
24 #include <boost/asio/strand.hpp>
25 #include <boost/config.hpp>
35 namespace beast = boost::beast; // from <boost/beast.hpp>
36 namespace http = beast::http; // from <boost/beast/http.hpp>
37 namespace net = boost::asio; // from <boost/asio.hpp>
38 namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
39 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
41 // Return a reasonable mime type based on the extension of a file.
43 mime_type(beast::string_view path)
46 auto const ext = [&path]
48 auto const pos = path.rfind(".");
49 if(pos == beast::string_view::npos)
50 return beast::string_view{};
51 return path.substr(pos);
53 if(iequals(ext, ".htm")) return "text/html";
54 if(iequals(ext, ".html")) return "text/html";
55 if(iequals(ext, ".php")) return "text/html";
56 if(iequals(ext, ".css")) return "text/css";
57 if(iequals(ext, ".txt")) return "text/plain";
58 if(iequals(ext, ".js")) return "application/javascript";
59 if(iequals(ext, ".json")) return "application/json";
60 if(iequals(ext, ".xml")) return "application/xml";
61 if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
62 if(iequals(ext, ".flv")) return "video/x-flv";
63 if(iequals(ext, ".png")) return "image/png";
64 if(iequals(ext, ".jpe")) return "image/jpeg";
65 if(iequals(ext, ".jpeg")) return "image/jpeg";
66 if(iequals(ext, ".jpg")) return "image/jpeg";
67 if(iequals(ext, ".gif")) return "image/gif";
68 if(iequals(ext, ".bmp")) return "image/bmp";
69 if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
70 if(iequals(ext, ".tiff")) return "image/tiff";
71 if(iequals(ext, ".tif")) return "image/tiff";
72 if(iequals(ext, ".svg")) return "image/svg+xml";
73 if(iequals(ext, ".svgz")) return "image/svg+xml";
74 return "application/text";
77 // Append an HTTP rel-path to a local filesystem path.
78 // The returned path is normalized for the platform.
81 beast::string_view base,
82 beast::string_view path)
85 return std::string(path);
86 std::string result(base);
88 char constexpr path_separator = '\\';
89 if(result.back() == path_separator)
90 result.resize(result.size() - 1);
91 result.append(path.data(), path.size());
96 char constexpr path_separator = '/';
97 if(result.back() == path_separator)
98 result.resize(result.size() - 1);
99 result.append(path.data(), path.size());
104 // This function produces an HTTP response for the given
105 // request. The type of the response object depends on the
106 // contents of the request, so the interface requires the
107 // caller to pass a generic lambda for receiving the response.
109 class Body, class Allocator,
113 beast::string_view doc_root,
114 http::request<Body, http::basic_fields<Allocator>>&& req,
117 // Returns a bad request response
118 auto const bad_request =
119 [&req](beast::string_view why)
121 http::response<http::string_body> res{http::status::bad_request, req.version()};
122 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
123 res.set(http::field::content_type, "text/html");
124 res.keep_alive(req.keep_alive());
125 res.body() = std::string(why);
126 res.prepare_payload();
130 // Returns a not found response
131 auto const not_found =
132 [&req](beast::string_view target)
134 http::response<http::string_body> res{http::status::not_found, 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() = "The resource '" + std::string(target) + "' was not found.";
139 res.prepare_payload();
143 // Returns a server error response
144 auto const server_error =
145 [&req](beast::string_view what)
147 http::response<http::string_body> res{http::status::internal_server_error, req.version()};
148 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
149 res.set(http::field::content_type, "text/html");
150 res.keep_alive(req.keep_alive());
151 res.body() = "An error occurred: '" + std::string(what) + "'";
152 res.prepare_payload();
156 // Make sure we can handle the method
157 if( req.method() != http::verb::get &&
158 req.method() != http::verb::head)
159 return send(bad_request("Unknown HTTP-method"));
161 // Request path must be absolute and not contain "..".
162 if( req.target().empty() ||
163 req.target()[0] != '/' ||
164 req.target().find("..") != beast::string_view::npos)
165 return send(bad_request("Illegal request-target"));
167 // Build the path to the requested file
168 std::string path = path_cat(doc_root, req.target());
169 if(req.target().back() == '/')
170 path.append("index.html");
172 // Attempt to open the file
173 beast::error_code ec;
174 http::file_body::value_type body;
175 body.open(path.c_str(), beast::file_mode::scan, ec);
177 // Handle the case where the file doesn't exist
178 if(ec == beast::errc::no_such_file_or_directory)
179 return send(not_found(req.target()));
181 // Handle an unknown error
183 return send(server_error(ec.message()));
185 // Cache the size since we need it after the move
186 auto const size = body.size();
188 // Respond to HEAD request
189 if(req.method() == http::verb::head)
191 http::response<http::empty_body> res{http::status::ok, req.version()};
192 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
193 res.set(http::field::content_type, mime_type(path));
194 res.content_length(size);
195 res.keep_alive(req.keep_alive());
196 return send(std::move(res));
199 // Respond to GET request
200 http::response<http::file_body> res{
201 std::piecewise_construct,
202 std::make_tuple(std::move(body)),
203 std::make_tuple(http::status::ok, req.version())};
204 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
205 res.set(http::field::content_type, mime_type(path));
206 res.content_length(size);
207 res.keep_alive(req.keep_alive());
208 return send(std::move(res));
211 //------------------------------------------------------------------------------
215 fail(beast::error_code ec, char const* what)
217 // ssl::error::stream_truncated, also known as an SSL "short read",
218 // indicates the peer closed the connection without performing the
219 // required closing handshake (for example, Google does this to
220 // improve performance). Generally this can be a security issue,
221 // but if your communication protocol is self-terminated (as
222 // it is with both HTTP and WebSocket) then you may simply
223 // ignore the lack of close_notify.
225 // https://github.com/boostorg/beast/issues/38
227 // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
229 // When a short read would cut off the end of an HTTP message,
230 // Beast returns the error beast::http::error::partial_message.
231 // Therefore, if we see a short read here, it has occurred
232 // after the message has been completed, so it is safe to ignore it.
234 if(ec == net::ssl::error::stream_truncated)
237 std::cerr << what << ": " << ec.message() << "\n";
240 // Handles an HTTP server connection
242 : public boost::asio::coroutine
243 , public std::enable_shared_from_this<session>
245 // This is the C++11 equivalent of a generic lambda.
246 // The function object is used to send an HTTP message.
252 send_lambda(session& self)
257 template<bool isRequest, class Body, class Fields>
259 operator()(http::message<isRequest, Body, Fields>&& msg) const
261 // The lifetime of the message has to extend
262 // for the duration of the async operation so
263 // we use a shared_ptr to manage it.
264 auto sp = std::make_shared<
265 http::message<isRequest, Body, Fields>>(std::move(msg));
267 // Store a type-erased version of the shared
268 // pointer in the class to keep it alive.
271 // Write the response
277 self_.shared_from_this(),
278 std::placeholders::_1,
279 std::placeholders::_2,
284 beast::ssl_stream<beast::tcp_stream> stream_;
285 beast::flat_buffer buffer_;
286 std::shared_ptr<std::string const> doc_root_;
287 http::request<http::string_body> req_;
288 std::shared_ptr<void> res_;
292 // Take ownership of the socket
295 tcp::socket&& socket,
297 std::shared_ptr<std::string const> const& doc_root)
298 : stream_(std::move(socket), ctx)
299 , doc_root_(doc_root)
304 // Start the asynchronous operation
308 // We need to be executing within a strand to perform async operations
309 // on the I/O objects in this session.Although not strictly necessary
310 // for single-threaded contexts, this example code is written to be
311 // thread-safe by default.
312 net::dispatch(stream_.get_executor(),
313 beast::bind_front_handler(&session::loop,
320 #include <boost/asio/yield.hpp>
324 beast::error_code ec,
325 std::size_t bytes_transferred,
328 boost::ignore_unused(bytes_transferred);
332 beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
334 // Perform the SSL handshake
335 yield stream_.async_handshake(
336 ssl::stream_base::server,
340 std::placeholders::_1,
344 return fail(ec, "handshake");
349 beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
351 // Make the request empty before reading,
352 // otherwise the operation behavior is undefined.
356 yield http::async_read(stream_, buffer_, req_,
360 std::placeholders::_1,
361 std::placeholders::_2,
363 if(ec == http::error::end_of_stream)
365 // The remote host closed the connection
369 return fail(ec, "read");
372 yield handle_request(*doc_root_, std::move(req_), lambda_);
374 return fail(ec, "write");
377 // This means we should close the connection, usually because
378 // the response indicated the "Connection: close" semantic.
382 // We're done with the response so delete it
387 beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
389 // Perform the SSL shutdown
390 yield stream_.async_shutdown(
394 std::placeholders::_1,
398 return fail(ec, "shutdown");
400 // At this point the connection is closed gracefully
404 #include <boost/asio/unyield.hpp>
407 //------------------------------------------------------------------------------
409 // Accepts incoming connections and launches the sessions
411 : public boost::asio::coroutine
412 , public std::enable_shared_from_this<listener>
414 net::io_context& ioc_;
416 tcp::acceptor acceptor_;
418 std::shared_ptr<std::string const> doc_root_;
422 net::io_context& ioc,
424 tcp::endpoint endpoint,
425 std::shared_ptr<std::string const> const& doc_root)
428 , acceptor_(net::make_strand(ioc))
429 , socket_(net::make_strand(ioc))
430 , doc_root_(doc_root)
432 beast::error_code ec;
435 acceptor_.open(endpoint.protocol(), ec);
442 // Allow address reuse
443 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
446 fail(ec, "set_option");
450 // Bind to the server address
451 acceptor_.bind(endpoint, ec);
458 // Start listening for connections
460 net::socket_base::max_listen_connections, ec);
468 // Start accepting incoming connections
477 #include <boost/asio/yield.hpp>
480 loop(beast::error_code ec = {})
486 yield acceptor_.async_accept(
491 std::placeholders::_1));
498 // Create the session and run it
499 std::make_shared<session>(
505 // Make sure each session gets its own strand
506 socket_ = tcp::socket(net::make_strand(ioc_));
511 #include <boost/asio/unyield.hpp>
514 //------------------------------------------------------------------------------
516 int main(int argc, char* argv[])
518 // Check command line arguments.
522 "Usage: http-server-stackless-ssl <address> <port> <doc_root> <threads>\n" <<
524 " http-server-stackless-ssl 0.0.0.0 8080 . 1\n";
527 auto const address = net::ip::make_address(argv[1]);
528 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
529 auto const doc_root = std::make_shared<std::string>(argv[3]);
530 auto const threads = std::max<int>(1, std::atoi(argv[4]));
532 // The io_context is required for all I/O
533 net::io_context ioc{threads};
535 // The SSL context is required, and holds certificates
536 ssl::context ctx{ssl::context::tlsv12};
538 // This holds the self-signed certificate used by the server
539 load_server_certificate(ctx);
541 // Create and launch a listening port
542 std::make_shared<listener>(
545 tcp::endpoint{address, port},
548 // Run the I/O service on the requested number of threads
549 std::vector<std::thread> v;
550 v.reserve(threads - 1);
551 for(auto i = threads - 1; i > 0; --i)