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, asynchronous
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/dispatch.hpp>
23 #include <boost/asio/strand.hpp>
24 #include <boost/config.hpp>
34 namespace beast
= boost::beast
; // from <boost/beast.hpp>
35 namespace http
= beast::http
; // from <boost/beast/http.hpp>
36 namespace net
= boost::asio
; // from <boost/asio.hpp>
37 namespace ssl
= boost::asio::ssl
; // from <boost/asio/ssl.hpp>
38 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
40 // Return a reasonable mime type based on the extension of a file.
42 mime_type(beast::string_view path
)
45 auto const ext
= [&path
]
47 auto const pos
= path
.rfind(".");
48 if(pos
== beast::string_view::npos
)
49 return beast::string_view
{};
50 return path
.substr(pos
);
52 if(iequals(ext
, ".htm")) return "text/html";
53 if(iequals(ext
, ".html")) return "text/html";
54 if(iequals(ext
, ".php")) return "text/html";
55 if(iequals(ext
, ".css")) return "text/css";
56 if(iequals(ext
, ".txt")) return "text/plain";
57 if(iequals(ext
, ".js")) return "application/javascript";
58 if(iequals(ext
, ".json")) return "application/json";
59 if(iequals(ext
, ".xml")) return "application/xml";
60 if(iequals(ext
, ".swf")) return "application/x-shockwave-flash";
61 if(iequals(ext
, ".flv")) return "video/x-flv";
62 if(iequals(ext
, ".png")) return "image/png";
63 if(iequals(ext
, ".jpe")) return "image/jpeg";
64 if(iequals(ext
, ".jpeg")) return "image/jpeg";
65 if(iequals(ext
, ".jpg")) return "image/jpeg";
66 if(iequals(ext
, ".gif")) return "image/gif";
67 if(iequals(ext
, ".bmp")) return "image/bmp";
68 if(iequals(ext
, ".ico")) return "image/vnd.microsoft.icon";
69 if(iequals(ext
, ".tiff")) return "image/tiff";
70 if(iequals(ext
, ".tif")) return "image/tiff";
71 if(iequals(ext
, ".svg")) return "image/svg+xml";
72 if(iequals(ext
, ".svgz")) return "image/svg+xml";
73 return "application/text";
76 // Append an HTTP rel-path to a local filesystem path.
77 // The returned path is normalized for the platform.
80 beast::string_view base
,
81 beast::string_view path
)
84 return std::string(path
);
85 std::string
result(base
);
87 char constexpr path_separator
= '\\';
88 if(result
.back() == path_separator
)
89 result
.resize(result
.size() - 1);
90 result
.append(path
.data(), path
.size());
95 char constexpr path_separator
= '/';
96 if(result
.back() == path_separator
)
97 result
.resize(result
.size() - 1);
98 result
.append(path
.data(), path
.size());
103 // This function produces an HTTP response for the given
104 // request. The type of the response object depends on the
105 // contents of the request, so the interface requires the
106 // caller to pass a generic lambda for receiving the response.
108 class Body
, class Allocator
,
112 beast::string_view doc_root
,
113 http::request
<Body
, http::basic_fields
<Allocator
>>&& req
,
116 // Returns a bad request response
117 auto const bad_request
=
118 [&req
](beast::string_view why
)
120 http::response
<http::string_body
> res
{http::status::bad_request
, req
.version()};
121 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
122 res
.set(http::field::content_type
, "text/html");
123 res
.keep_alive(req
.keep_alive());
124 res
.body() = std::string(why
);
125 res
.prepare_payload();
129 // Returns a not found response
130 auto const not_found
=
131 [&req
](beast::string_view target
)
133 http::response
<http::string_body
> res
{http::status::not_found
, req
.version()};
134 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
135 res
.set(http::field::content_type
, "text/html");
136 res
.keep_alive(req
.keep_alive());
137 res
.body() = "The resource '" + std::string(target
) + "' was not found.";
138 res
.prepare_payload();
142 // Returns a server error response
143 auto const server_error
=
144 [&req
](beast::string_view what
)
146 http::response
<http::string_body
> res
{http::status::internal_server_error
, req
.version()};
147 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
148 res
.set(http::field::content_type
, "text/html");
149 res
.keep_alive(req
.keep_alive());
150 res
.body() = "An error occurred: '" + std::string(what
) + "'";
151 res
.prepare_payload();
155 // Make sure we can handle the method
156 if( req
.method() != http::verb::get
&&
157 req
.method() != http::verb::head
)
158 return send(bad_request("Unknown HTTP-method"));
160 // Request path must be absolute and not contain "..".
161 if( req
.target().empty() ||
162 req
.target()[0] != '/' ||
163 req
.target().find("..") != beast::string_view::npos
)
164 return send(bad_request("Illegal request-target"));
166 // Build the path to the requested file
167 std::string path
= path_cat(doc_root
, req
.target());
168 if(req
.target().back() == '/')
169 path
.append("index.html");
171 // Attempt to open the file
172 beast::error_code ec
;
173 http::file_body::value_type body
;
174 body
.open(path
.c_str(), beast::file_mode::scan
, ec
);
176 // Handle the case where the file doesn't exist
177 if(ec
== beast::errc::no_such_file_or_directory
)
178 return send(not_found(req
.target()));
180 // Handle an unknown error
182 return send(server_error(ec
.message()));
184 // Cache the size since we need it after the move
185 auto const size
= body
.size();
187 // Respond to HEAD request
188 if(req
.method() == http::verb::head
)
190 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
191 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
192 res
.set(http::field::content_type
, mime_type(path
));
193 res
.content_length(size
);
194 res
.keep_alive(req
.keep_alive());
195 return send(std::move(res
));
198 // Respond to GET request
199 http::response
<http::file_body
> res
{
200 std::piecewise_construct
,
201 std::make_tuple(std::move(body
)),
202 std::make_tuple(http::status::ok
, req
.version())};
203 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
204 res
.set(http::field::content_type
, mime_type(path
));
205 res
.content_length(size
);
206 res
.keep_alive(req
.keep_alive());
207 return send(std::move(res
));
210 //------------------------------------------------------------------------------
214 fail(beast::error_code ec
, char const* what
)
216 // ssl::error::stream_truncated, also known as an SSL "short read",
217 // indicates the peer closed the connection without performing the
218 // required closing handshake (for example, Google does this to
219 // improve performance). Generally this can be a security issue,
220 // but if your communication protocol is self-terminated (as
221 // it is with both HTTP and WebSocket) then you may simply
222 // ignore the lack of close_notify.
224 // https://github.com/boostorg/beast/issues/38
226 // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
228 // When a short read would cut off the end of an HTTP message,
229 // Beast returns the error beast::http::error::partial_message.
230 // Therefore, if we see a short read here, it has occurred
231 // after the message has been completed, so it is safe to ignore it.
233 if(ec
== net::ssl::error::stream_truncated
)
236 std::cerr
<< what
<< ": " << ec
.message() << "\n";
239 // Handles an HTTP server connection
240 class session
: public std::enable_shared_from_this
<session
>
242 // This is the C++11 equivalent of a generic lambda.
243 // The function object is used to send an HTTP message.
249 send_lambda(session
& self
)
254 template<bool isRequest
, class Body
, class Fields
>
256 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
258 // The lifetime of the message has to extend
259 // for the duration of the async operation so
260 // we use a shared_ptr to manage it.
261 auto sp
= std::make_shared
<
262 http::message
<isRequest
, Body
, Fields
>>(std::move(msg
));
264 // Store a type-erased version of the shared
265 // pointer in the class to keep it alive.
268 // Write the response
272 beast::bind_front_handler(
274 self_
.shared_from_this(),
279 beast::ssl_stream
<beast::tcp_stream
> stream_
;
280 beast::flat_buffer buffer_
;
281 std::shared_ptr
<std::string
const> doc_root_
;
282 http::request
<http::string_body
> req_
;
283 std::shared_ptr
<void> res_
;
287 // Take ownership of the socket
290 tcp::socket
&& socket
,
292 std::shared_ptr
<std::string
const> const& doc_root
)
293 : stream_(std::move(socket
), ctx
)
294 , doc_root_(doc_root
)
299 // Start the asynchronous operation
303 // We need to be executing within a strand to perform async operations
304 // on the I/O objects in this session. Although not strictly necessary
305 // for single-threaded contexts, this example code is written to be
306 // thread-safe by default.
308 stream_
.get_executor(),
309 beast::bind_front_handler(
311 shared_from_this()));
318 beast::get_lowest_layer(stream_
).expires_after(
319 std::chrono::seconds(30));
321 // Perform the SSL handshake
322 stream_
.async_handshake(
323 ssl::stream_base::server
,
324 beast::bind_front_handler(
325 &session::on_handshake
,
326 shared_from_this()));
330 on_handshake(beast::error_code ec
)
333 return fail(ec
, "handshake");
341 // Make the request empty before reading,
342 // otherwise the operation behavior is undefined.
346 beast::get_lowest_layer(stream_
).expires_after(std::chrono::seconds(30));
349 http::async_read(stream_
, buffer_
, req_
,
350 beast::bind_front_handler(
352 shared_from_this()));
357 beast::error_code ec
,
358 std::size_t bytes_transferred
)
360 boost::ignore_unused(bytes_transferred
);
362 // This means they closed the connection
363 if(ec
== http::error::end_of_stream
)
367 return fail(ec
, "read");
370 handle_request(*doc_root_
, std::move(req_
), lambda_
);
376 beast::error_code ec
,
377 std::size_t bytes_transferred
)
379 boost::ignore_unused(bytes_transferred
);
382 return fail(ec
, "write");
386 // This means we should close the connection, usually because
387 // the response indicated the "Connection: close" semantic.
391 // We're done with the response so delete it
394 // Read another request
402 beast::get_lowest_layer(stream_
).expires_after(std::chrono::seconds(30));
404 // Perform the SSL shutdown
405 stream_
.async_shutdown(
406 beast::bind_front_handler(
407 &session::on_shutdown
,
408 shared_from_this()));
412 on_shutdown(beast::error_code ec
)
415 return fail(ec
, "shutdown");
417 // At this point the connection is closed gracefully
421 //------------------------------------------------------------------------------
423 // Accepts incoming connections and launches the sessions
424 class listener
: public std::enable_shared_from_this
<listener
>
426 net::io_context
& ioc_
;
428 tcp::acceptor acceptor_
;
429 std::shared_ptr
<std::string
const> doc_root_
;
433 net::io_context
& ioc
,
435 tcp::endpoint endpoint
,
436 std::shared_ptr
<std::string
const> const& doc_root
)
440 , doc_root_(doc_root
)
442 beast::error_code ec
;
445 acceptor_
.open(endpoint
.protocol(), ec
);
452 // Allow address reuse
453 acceptor_
.set_option(net::socket_base::reuse_address(true), ec
);
456 fail(ec
, "set_option");
460 // Bind to the server address
461 acceptor_
.bind(endpoint
, ec
);
468 // Start listening for connections
470 net::socket_base::max_listen_connections
, ec
);
478 // Start accepting incoming connections
489 // The new connection gets its own strand
490 acceptor_
.async_accept(
491 net::make_strand(ioc_
),
492 beast::bind_front_handler(
493 &listener::on_accept
,
494 shared_from_this()));
498 on_accept(beast::error_code ec
, tcp::socket socket
)
506 // Create the session and run it
507 std::make_shared
<session
>(
513 // Accept another connection
518 //------------------------------------------------------------------------------
520 int main(int argc
, char* argv
[])
522 // Check command line arguments.
526 "Usage: http-server-async-ssl <address> <port> <doc_root> <threads>\n" <<
528 " http-server-async-ssl 0.0.0.0 8080 . 1\n";
531 auto const address
= net::ip::make_address(argv
[1]);
532 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
533 auto const doc_root
= std::make_shared
<std::string
>(argv
[3]);
534 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
536 // The io_context is required for all I/O
537 net::io_context ioc
{threads
};
539 // The SSL context is required, and holds certificates
540 ssl::context ctx
{ssl::context::tlsv12
};
542 // This holds the self-signed certificate used by the server
543 load_server_certificate(ctx
);
545 // Create and launch a listening port
546 std::make_shared
<listener
>(
549 tcp::endpoint
{address
, port
},
552 // Run the I/O service on the requested number of threads
553 std::vector
<std::thread
> v
;
554 v
.reserve(threads
- 1);
555 for(auto i
= threads
- 1; i
> 0; --i
)