2 // Copyright (c) 2016-2017 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 server, asynchronous
14 //------------------------------------------------------------------------------
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/version.hpp>
19 #include <boost/asio/bind_executor.hpp>
20 #include <boost/asio/ip/tcp.hpp>
21 #include <boost/asio/strand.hpp>
22 #include <boost/config.hpp>
32 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
33 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
35 // Return a reasonable mime type based on the extension of a file.
36 boost::beast::string_view
37 mime_type(boost::beast::string_view path
)
39 using boost::beast::iequals
;
40 auto const ext
= [&path
]
42 auto const pos
= path
.rfind(".");
43 if(pos
== boost::beast::string_view::npos
)
44 return boost::beast::string_view
{};
45 return path
.substr(pos
);
47 if(iequals(ext
, ".htm")) return "text/html";
48 if(iequals(ext
, ".html")) return "text/html";
49 if(iequals(ext
, ".php")) return "text/html";
50 if(iequals(ext
, ".css")) return "text/css";
51 if(iequals(ext
, ".txt")) return "text/plain";
52 if(iequals(ext
, ".js")) return "application/javascript";
53 if(iequals(ext
, ".json")) return "application/json";
54 if(iequals(ext
, ".xml")) return "application/xml";
55 if(iequals(ext
, ".swf")) return "application/x-shockwave-flash";
56 if(iequals(ext
, ".flv")) return "video/x-flv";
57 if(iequals(ext
, ".png")) return "image/png";
58 if(iequals(ext
, ".jpe")) return "image/jpeg";
59 if(iequals(ext
, ".jpeg")) return "image/jpeg";
60 if(iequals(ext
, ".jpg")) return "image/jpeg";
61 if(iequals(ext
, ".gif")) return "image/gif";
62 if(iequals(ext
, ".bmp")) return "image/bmp";
63 if(iequals(ext
, ".ico")) return "image/vnd.microsoft.icon";
64 if(iequals(ext
, ".tiff")) return "image/tiff";
65 if(iequals(ext
, ".tif")) return "image/tiff";
66 if(iequals(ext
, ".svg")) return "image/svg+xml";
67 if(iequals(ext
, ".svgz")) return "image/svg+xml";
68 return "application/text";
71 // Append an HTTP rel-path to a local filesystem path.
72 // The returned path is normalized for the platform.
75 boost::beast::string_view base
,
76 boost::beast::string_view path
)
79 return path
.to_string();
80 std::string result
= base
.to_string();
82 char constexpr path_separator
= '\\';
83 if(result
.back() == path_separator
)
84 result
.resize(result
.size() - 1);
85 result
.append(path
.data(), path
.size());
90 char constexpr path_separator
= '/';
91 if(result
.back() == path_separator
)
92 result
.resize(result
.size() - 1);
93 result
.append(path
.data(), path
.size());
98 // This function produces an HTTP response for the given
99 // request. The type of the response object depends on the
100 // contents of the request, so the interface requires the
101 // caller to pass a generic lambda for receiving the response.
103 class Body
, class Allocator
,
107 boost::beast::string_view doc_root
,
108 http::request
<Body
, http::basic_fields
<Allocator
>>&& req
,
111 // Returns a bad request response
112 auto const bad_request
=
113 [&req
](boost::beast::string_view why
)
115 http::response
<http::string_body
> res
{http::status::bad_request
, req
.version()};
116 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
117 res
.set(http::field::content_type
, "text/html");
118 res
.keep_alive(req
.keep_alive());
119 res
.body() = why
.to_string();
120 res
.prepare_payload();
124 // Returns a not found response
125 auto const not_found
=
126 [&req
](boost::beast::string_view target
)
128 http::response
<http::string_body
> res
{http::status::not_found
, req
.version()};
129 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
130 res
.set(http::field::content_type
, "text/html");
131 res
.keep_alive(req
.keep_alive());
132 res
.body() = "The resource '" + target
.to_string() + "' was not found.";
133 res
.prepare_payload();
137 // Returns a server error response
138 auto const server_error
=
139 [&req
](boost::beast::string_view what
)
141 http::response
<http::string_body
> res
{http::status::internal_server_error
, req
.version()};
142 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
143 res
.set(http::field::content_type
, "text/html");
144 res
.keep_alive(req
.keep_alive());
145 res
.body() = "An error occurred: '" + what
.to_string() + "'";
146 res
.prepare_payload();
150 // Make sure we can handle the method
151 if( req
.method() != http::verb::get
&&
152 req
.method() != http::verb::head
)
153 return send(bad_request("Unknown HTTP-method"));
155 // Request path must be absolute and not contain "..".
156 if( req
.target().empty() ||
157 req
.target()[0] != '/' ||
158 req
.target().find("..") != boost::beast::string_view::npos
)
159 return send(bad_request("Illegal request-target"));
161 // Build the path to the requested file
162 std::string path
= path_cat(doc_root
, req
.target());
163 if(req
.target().back() == '/')
164 path
.append("index.html");
166 // Attempt to open the file
167 boost::beast::error_code ec
;
168 http::file_body::value_type body
;
169 body
.open(path
.c_str(), boost::beast::file_mode::scan
, ec
);
171 // Handle the case where the file doesn't exist
172 if(ec
== boost::system::errc::no_such_file_or_directory
)
173 return send(not_found(req
.target()));
175 // Handle an unknown error
177 return send(server_error(ec
.message()));
179 // Respond to HEAD request
180 if(req
.method() == http::verb::head
)
182 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
183 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
184 res
.set(http::field::content_type
, mime_type(path
));
185 res
.content_length(body
.size());
186 res
.keep_alive(req
.keep_alive());
187 return send(std::move(res
));
190 // Respond to GET request
191 http::response
<http::file_body
> res
{
192 std::piecewise_construct
,
193 std::make_tuple(std::move(body
)),
194 std::make_tuple(http::status::ok
, req
.version())};
195 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
196 res
.set(http::field::content_type
, mime_type(path
));
197 res
.content_length(body
.size());
198 res
.keep_alive(req
.keep_alive());
199 return send(std::move(res
));
202 //------------------------------------------------------------------------------
206 fail(boost::system::error_code ec
, char const* what
)
208 std::cerr
<< what
<< ": " << ec
.message() << "\n";
211 // Handles an HTTP server connection
212 class session
: public std::enable_shared_from_this
<session
>
214 // This is the C++11 equivalent of a generic lambda.
215 // The function object is used to send an HTTP message.
221 send_lambda(session
& self
)
226 template<bool isRequest
, class Body
, class Fields
>
228 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
230 // The lifetime of the message has to extend
231 // for the duration of the async operation so
232 // we use a shared_ptr to manage it.
233 auto sp
= std::make_shared
<
234 http::message
<isRequest
, Body
, Fields
>>(std::move(msg
));
236 // Store a type-erased version of the shared
237 // pointer in the class to keep it alive.
240 // Write the response
244 boost::asio::bind_executor(
248 self_
.shared_from_this(),
249 std::placeholders::_1
,
250 std::placeholders::_2
,
257 boost::asio::io_context::executor_type
> strand_
;
258 boost::beast::flat_buffer buffer_
;
259 std::string
const& doc_root_
;
260 http::request
<http::string_body
> req_
;
261 std::shared_ptr
<void> res_
;
265 // Take ownership of the socket
269 std::string
const& doc_root
)
270 : socket_(std::move(socket
))
271 , strand_(socket_
.get_executor())
272 , doc_root_(doc_root
)
277 // Start the asynchronous operation
288 http::async_read(socket_
, buffer_
, req_
,
289 boost::asio::bind_executor(
294 std::placeholders::_1
,
295 std::placeholders::_2
)));
300 boost::system::error_code ec
,
301 std::size_t bytes_transferred
)
303 boost::ignore_unused(bytes_transferred
);
305 // This means they closed the connection
306 if(ec
== http::error::end_of_stream
)
310 return fail(ec
, "read");
313 handle_request(doc_root_
, std::move(req_
), lambda_
);
318 boost::system::error_code ec
,
319 std::size_t bytes_transferred
,
322 boost::ignore_unused(bytes_transferred
);
325 return fail(ec
, "write");
329 // This means we should close the connection, usually because
330 // the response indicated the "Connection: close" semantic.
334 // We're done with the response so delete it
337 // Read another request
344 // Send a TCP shutdown
345 boost::system::error_code ec
;
346 socket_
.shutdown(tcp::socket::shutdown_send
, ec
);
348 // At this point the connection is closed gracefully
352 //------------------------------------------------------------------------------
354 // Accepts incoming connections and launches the sessions
355 class listener
: public std::enable_shared_from_this
<listener
>
357 tcp::acceptor acceptor_
;
359 std::string
const& doc_root_
;
363 boost::asio::io_context
& ioc
,
364 tcp::endpoint endpoint
,
365 std::string
const& doc_root
)
368 , doc_root_(doc_root
)
370 boost::system::error_code ec
;
373 acceptor_
.open(endpoint
.protocol(), ec
);
380 // Bind to the server address
381 acceptor_
.bind(endpoint
, ec
);
388 // Start listening for connections
390 boost::asio::socket_base::max_listen_connections
, ec
);
398 // Start accepting incoming connections
402 if(! acceptor_
.is_open())
410 acceptor_
.async_accept(
413 &listener::on_accept
,
415 std::placeholders::_1
));
419 on_accept(boost::system::error_code ec
)
427 // Create the session and run it
428 std::make_shared
<session
>(
433 // Accept another connection
438 //------------------------------------------------------------------------------
440 int main(int argc
, char* argv
[])
442 // Check command line arguments.
446 "Usage: http-server-async <address> <port> <doc_root> <threads>\n" <<
448 " http-server-async 0.0.0.0 8080 . 1\n";
451 auto const address
= boost::asio::ip::make_address(argv
[1]);
452 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
453 std::string
const doc_root
= argv
[3];
454 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
456 // The io_context is required for all I/O
457 boost::asio::io_context ioc
{threads
};
459 // Create and launch a listening port
460 std::make_shared
<listener
>(
462 tcp::endpoint
{address
, port
},
465 // Run the I/O service on the requested number of threads
466 std::vector
<std::thread
> v
;
467 v
.reserve(threads
- 1);
468 for(auto i
= threads
- 1; i
> 0; --i
)