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: Advanced server
14 //------------------------------------------------------------------------------
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/websocket.hpp>
19 #include <boost/beast/version.hpp>
20 #include <boost/asio/bind_executor.hpp>
21 #include <boost/asio/signal_set.hpp>
22 #include <boost/asio/strand.hpp>
23 #include <boost/make_unique.hpp>
24 #include <boost/optional.hpp>
34 namespace beast
= boost::beast
; // from <boost/beast.hpp>
35 namespace http
= beast::http
; // from <boost/beast/http.hpp>
36 namespace websocket
= beast::websocket
; // from <boost/beast/websocket.hpp>
37 namespace net
= boost::asio
; // from <boost/asio.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 std::cerr
<< what
<< ": " << ec
.message() << "\n";
219 // Echoes back all received WebSocket messages
220 class websocket_session
: public std::enable_shared_from_this
<websocket_session
>
222 websocket::stream
<beast::tcp_stream
> ws_
;
223 beast::flat_buffer buffer_
;
226 // Take ownership of the socket
228 websocket_session(tcp::socket
&& socket
)
229 : ws_(std::move(socket
))
233 // Start the asynchronous accept operation
234 template<class Body
, class Allocator
>
236 do_accept(http::request
<Body
, http::basic_fields
<Allocator
>> req
)
238 // Set suggested timeout settings for the websocket
240 websocket::stream_base::timeout::suggested(
241 beast::role_type::server
));
243 // Set a decorator to change the Server of the handshake
244 ws_
.set_option(websocket::stream_base::decorator(
245 [](websocket::response_type
& res
)
247 res
.set(http::field::server
,
248 std::string(BOOST_BEAST_VERSION_STRING
) +
252 // Accept the websocket handshake
255 beast::bind_front_handler(
256 &websocket_session::on_accept
,
257 shared_from_this()));
262 on_accept(beast::error_code ec
)
265 return fail(ec
, "accept");
274 // Read a message into our buffer
277 beast::bind_front_handler(
278 &websocket_session::on_read
,
279 shared_from_this()));
284 beast::error_code ec
,
285 std::size_t bytes_transferred
)
287 boost::ignore_unused(bytes_transferred
);
289 // This indicates that the websocket_session was closed
290 if(ec
== websocket::error::closed
)
297 ws_
.text(ws_
.got_text());
300 beast::bind_front_handler(
301 &websocket_session::on_write
,
302 shared_from_this()));
307 beast::error_code ec
,
308 std::size_t bytes_transferred
)
310 boost::ignore_unused(bytes_transferred
);
313 return fail(ec
, "write");
316 buffer_
.consume(buffer_
.size());
323 //------------------------------------------------------------------------------
325 // Handles an HTTP server connection
326 class http_session
: public std::enable_shared_from_this
<http_session
>
328 // This queue is used for HTTP pipelining.
333 // Maximum number of responses we will queue
337 // The type-erased, saved work item
340 virtual ~work() = default;
341 virtual void operator()() = 0;
345 std::vector
<std::unique_ptr
<work
>> items_
;
349 queue(http_session
& self
)
352 static_assert(limit
> 0, "queue limit must be positive");
353 items_
.reserve(limit
);
356 // Returns `true` if we have reached the queue limit
360 return items_
.size() >= limit
;
363 // Called when a message finishes sending
364 // Returns `true` if the caller should initiate a read
368 BOOST_ASSERT(! items_
.empty());
369 auto const was_full
= is_full();
370 items_
.erase(items_
.begin());
376 // Called by the HTTP handler to send a response.
377 template<bool isRequest
, class Body
, class Fields
>
379 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
)
381 // This holds a work item
382 struct work_impl
: work
385 http::message
<isRequest
, Body
, Fields
> msg_
;
389 http::message
<isRequest
, Body
, Fields
>&& msg
)
391 , msg_(std::move(msg
))
401 beast::bind_front_handler(
402 &http_session::on_write
,
403 self_
.shared_from_this(),
408 // Allocate and store the work
410 boost::make_unique
<work_impl
>(self_
, std::move(msg
)));
412 // If there was no previous work, start this one
413 if(items_
.size() == 1)
418 beast::tcp_stream stream_
;
419 beast::flat_buffer buffer_
;
420 std::shared_ptr
<std::string
const> doc_root_
;
423 // The parser is stored in an optional container so we can
424 // construct it from scratch it at the beginning of each new message.
425 boost::optional
<http::request_parser
<http::string_body
>> parser_
;
428 // Take ownership of the socket
430 tcp::socket
&& socket
,
431 std::shared_ptr
<std::string
const> const& doc_root
)
432 : stream_(std::move(socket
))
433 , doc_root_(doc_root
)
449 // Construct a new parser for each message
452 // Apply a reasonable limit to the allowed size
453 // of the body in bytes to prevent abuse.
454 parser_
->body_limit(10000);
457 stream_
.expires_after(std::chrono::seconds(30));
459 // Read a request using the parser-oriented interface
464 beast::bind_front_handler(
465 &http_session::on_read
,
466 shared_from_this()));
470 on_read(beast::error_code ec
, std::size_t bytes_transferred
)
472 boost::ignore_unused(bytes_transferred
);
474 // This means they closed the connection
475 if(ec
== http::error::end_of_stream
)
479 return fail(ec
, "read");
481 // See if it is a WebSocket Upgrade
482 if(websocket::is_upgrade(parser_
->get()))
484 // Create a websocket session, transferring ownership
485 // of both the socket and the HTTP request.
486 std::make_shared
<websocket_session
>(
487 stream_
.release_socket())->do_accept(parser_
->release());
492 handle_request(*doc_root_
, parser_
->release(), queue_
);
494 // If we aren't at the queue limit, try to pipeline another request
495 if(! queue_
.is_full())
500 on_write(bool close
, beast::error_code ec
, std::size_t bytes_transferred
)
502 boost::ignore_unused(bytes_transferred
);
505 return fail(ec
, "write");
509 // This means we should close the connection, usually because
510 // the response indicated the "Connection: close" semantic.
514 // Inform the queue that a write completed
515 if(queue_
.on_write())
517 // Read another request
525 // Send a TCP shutdown
526 beast::error_code ec
;
527 stream_
.socket().shutdown(tcp::socket::shutdown_send
, ec
);
529 // At this point the connection is closed gracefully
533 //------------------------------------------------------------------------------
535 // Accepts incoming connections and launches the sessions
536 class listener
: public std::enable_shared_from_this
<listener
>
538 net::io_context
& ioc_
;
539 tcp::acceptor acceptor_
;
540 std::shared_ptr
<std::string
const> doc_root_
;
544 net::io_context
& ioc
,
545 tcp::endpoint endpoint
,
546 std::shared_ptr
<std::string
const> const& doc_root
)
548 , acceptor_(net::make_strand(ioc
))
549 , doc_root_(doc_root
)
551 beast::error_code ec
;
554 acceptor_
.open(endpoint
.protocol(), ec
);
561 // Allow address reuse
562 acceptor_
.set_option(net::socket_base::reuse_address(true), ec
);
565 fail(ec
, "set_option");
569 // Bind to the server address
570 acceptor_
.bind(endpoint
, ec
);
577 // Start listening for connections
579 net::socket_base::max_listen_connections
, ec
);
587 // Start accepting incoming connections
598 // The new connection gets its own strand
599 acceptor_
.async_accept(
600 net::make_strand(ioc_
),
601 beast::bind_front_handler(
602 &listener::on_accept
,
603 shared_from_this()));
607 on_accept(beast::error_code ec
, tcp::socket socket
)
615 // Create the http session and run it
616 std::make_shared
<http_session
>(
621 // Accept another connection
626 //------------------------------------------------------------------------------
628 int main(int argc
, char* argv
[])
630 // Check command line arguments.
634 "Usage: advanced-server <address> <port> <doc_root> <threads>\n" <<
636 " advanced-server 0.0.0.0 8080 . 1\n";
639 auto const address
= net::ip::make_address(argv
[1]);
640 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
641 auto const doc_root
= std::make_shared
<std::string
>(argv
[3]);
642 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
644 // The io_context is required for all I/O
645 net::io_context ioc
{threads
};
647 // Create and launch a listening port
648 std::make_shared
<listener
>(
650 tcp::endpoint
{address
, port
},
653 // Capture SIGINT and SIGTERM to perform a clean shutdown
654 net::signal_set
signals(ioc
, SIGINT
, SIGTERM
);
656 [&](beast::error_code
const&, int)
658 // Stop the `io_context`. This will cause `run()`
659 // to return immediately, eventually destroying the
660 // `io_context` and all of the sockets in it.
664 // Run the I/O service on the requested number of threads
665 std::vector
<std::thread
> v
;
666 v
.reserve(threads
- 1);
667 for(auto i
= threads
- 1; i
> 0; --i
)
675 // (If we get here, it means we got a SIGINT or SIGTERM)
677 // Block until all the threads exit