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, coroutine
14 //------------------------------------------------------------------------------
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/version.hpp>
19 #include <boost/asio/ip/tcp.hpp>
20 #include <boost/asio/spawn.hpp>
21 #include <boost/config.hpp>
30 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
31 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
33 // Return a reasonable mime type based on the extension of a file.
34 boost::beast::string_view
35 mime_type(boost::beast::string_view path
)
37 using boost::beast::iequals
;
38 auto const ext
= [&path
]
40 auto const pos
= path
.rfind(".");
41 if(pos
== boost::beast::string_view::npos
)
42 return boost::beast::string_view
{};
43 return path
.substr(pos
);
45 if(iequals(ext
, ".htm")) return "text/html";
46 if(iequals(ext
, ".html")) return "text/html";
47 if(iequals(ext
, ".php")) return "text/html";
48 if(iequals(ext
, ".css")) return "text/css";
49 if(iequals(ext
, ".txt")) return "text/plain";
50 if(iequals(ext
, ".js")) return "application/javascript";
51 if(iequals(ext
, ".json")) return "application/json";
52 if(iequals(ext
, ".xml")) return "application/xml";
53 if(iequals(ext
, ".swf")) return "application/x-shockwave-flash";
54 if(iequals(ext
, ".flv")) return "video/x-flv";
55 if(iequals(ext
, ".png")) return "image/png";
56 if(iequals(ext
, ".jpe")) return "image/jpeg";
57 if(iequals(ext
, ".jpeg")) return "image/jpeg";
58 if(iequals(ext
, ".jpg")) return "image/jpeg";
59 if(iequals(ext
, ".gif")) return "image/gif";
60 if(iequals(ext
, ".bmp")) return "image/bmp";
61 if(iequals(ext
, ".ico")) return "image/vnd.microsoft.icon";
62 if(iequals(ext
, ".tiff")) return "image/tiff";
63 if(iequals(ext
, ".tif")) return "image/tiff";
64 if(iequals(ext
, ".svg")) return "image/svg+xml";
65 if(iequals(ext
, ".svgz")) return "image/svg+xml";
66 return "application/text";
69 // Append an HTTP rel-path to a local filesystem path.
70 // The returned path is normalized for the platform.
73 boost::beast::string_view base
,
74 boost::beast::string_view path
)
77 return path
.to_string();
78 std::string result
= base
.to_string();
80 char constexpr path_separator
= '\\';
81 if(result
.back() == path_separator
)
82 result
.resize(result
.size() - 1);
83 result
.append(path
.data(), path
.size());
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 // This function produces an HTTP response for the given
97 // request. The type of the response object depends on the
98 // contents of the request, so the interface requires the
99 // caller to pass a generic lambda for receiving the response.
101 class Body
, class Allocator
,
105 boost::beast::string_view doc_root
,
106 http::request
<Body
, http::basic_fields
<Allocator
>>&& req
,
109 // Returns a bad request response
110 auto const bad_request
=
111 [&req
](boost::beast::string_view why
)
113 http::response
<http::string_body
> res
{http::status::bad_request
, req
.version()};
114 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
115 res
.set(http::field::content_type
, "text/html");
116 res
.keep_alive(req
.keep_alive());
117 res
.body() = why
.to_string();
118 res
.prepare_payload();
122 // Returns a not found response
123 auto const not_found
=
124 [&req
](boost::beast::string_view target
)
126 http::response
<http::string_body
> res
{http::status::not_found
, req
.version()};
127 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
128 res
.set(http::field::content_type
, "text/html");
129 res
.keep_alive(req
.keep_alive());
130 res
.body() = "The resource '" + target
.to_string() + "' was not found.";
131 res
.prepare_payload();
135 // Returns a server error response
136 auto const server_error
=
137 [&req
](boost::beast::string_view what
)
139 http::response
<http::string_body
> res
{http::status::internal_server_error
, req
.version()};
140 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
141 res
.set(http::field::content_type
, "text/html");
142 res
.keep_alive(req
.keep_alive());
143 res
.body() = "An error occurred: '" + what
.to_string() + "'";
144 res
.prepare_payload();
148 // Make sure we can handle the method
149 if( req
.method() != http::verb::get
&&
150 req
.method() != http::verb::head
)
151 return send(bad_request("Unknown HTTP-method"));
153 // Request path must be absolute and not contain "..".
154 if( req
.target().empty() ||
155 req
.target()[0] != '/' ||
156 req
.target().find("..") != boost::beast::string_view::npos
)
157 return send(bad_request("Illegal request-target"));
159 // Build the path to the requested file
160 std::string path
= path_cat(doc_root
, req
.target());
161 if(req
.target().back() == '/')
162 path
.append("index.html");
164 // Attempt to open the file
165 boost::beast::error_code ec
;
166 http::file_body::value_type body
;
167 body
.open(path
.c_str(), boost::beast::file_mode::scan
, ec
);
169 // Handle the case where the file doesn't exist
170 if(ec
== boost::system::errc::no_such_file_or_directory
)
171 return send(not_found(req
.target()));
173 // Handle an unknown error
175 return send(server_error(ec
.message()));
177 // Cache the size since we need it after the move
178 auto const size
= body
.size();
180 // Respond to HEAD request
181 if(req
.method() == http::verb::head
)
183 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
184 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
185 res
.set(http::field::content_type
, mime_type(path
));
186 res
.content_length(size
);
187 res
.keep_alive(req
.keep_alive());
188 return send(std::move(res
));
191 // Respond to GET request
192 http::response
<http::file_body
> res
{
193 std::piecewise_construct
,
194 std::make_tuple(std::move(body
)),
195 std::make_tuple(http::status::ok
, req
.version())};
196 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
197 res
.set(http::field::content_type
, mime_type(path
));
198 res
.content_length(size
);
199 res
.keep_alive(req
.keep_alive());
200 return send(std::move(res
));
203 //------------------------------------------------------------------------------
207 fail(boost::system::error_code ec
, char const* what
)
209 std::cerr
<< what
<< ": " << ec
.message() << "\n";
212 // This is the C++11 equivalent of a generic lambda.
213 // The function object is used to send an HTTP message.
214 template<class Stream
>
219 boost::system::error_code
& ec_
;
220 boost::asio::yield_context yield_
;
226 boost::system::error_code
& ec
,
227 boost::asio::yield_context yield
)
235 template<bool isRequest
, class Body
, class Fields
>
237 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
239 // Determine if we should close the connection after
240 close_
= msg
.need_eof();
242 // We need the serializer here because the serializer requires
243 // a non-const file_body, and the message oriented version of
244 // http::write only works with const messages.
245 http::serializer
<isRequest
, Body
, Fields
> sr
{msg
};
246 http::async_write(stream_
, sr
, yield_
[ec_
]);
250 // Handles an HTTP server connection
254 std::string
const& doc_root
,
255 boost::asio::yield_context yield
)
258 boost::system::error_code ec
;
260 // This buffer is required to persist across reads
261 boost::beast::flat_buffer buffer
;
263 // This lambda is used to send messages
264 send_lambda
<tcp::socket
> lambda
{socket
, close
, ec
, yield
};
269 http::request
<http::string_body
> req
;
270 http::async_read(socket
, buffer
, req
, yield
[ec
]);
271 if(ec
== http::error::end_of_stream
)
274 return fail(ec
, "read");
277 handle_request(doc_root
, std::move(req
), lambda
);
279 return fail(ec
, "write");
282 // This means we should close the connection, usually because
283 // the response indicated the "Connection: close" semantic.
288 // Send a TCP shutdown
289 socket
.shutdown(tcp::socket::shutdown_send
, ec
);
291 // At this point the connection is closed gracefully
294 //------------------------------------------------------------------------------
296 // Accepts incoming connections and launches the sessions
299 boost::asio::io_context
& ioc
,
300 tcp::endpoint endpoint
,
301 std::string
const& doc_root
,
302 boost::asio::yield_context yield
)
304 boost::system::error_code ec
;
307 tcp::acceptor
acceptor(ioc
);
308 acceptor
.open(endpoint
.protocol(), ec
);
310 return fail(ec
, "open");
312 // Allow address reuse
313 acceptor
.set_option(boost::asio::socket_base::reuse_address(true));
315 return fail(ec
, "set_option");
317 // Bind to the server address
318 acceptor
.bind(endpoint
, ec
);
320 return fail(ec
, "bind");
322 // Start listening for connections
323 acceptor
.listen(boost::asio::socket_base::max_listen_connections
, ec
);
325 return fail(ec
, "listen");
329 tcp::socket
socket(ioc
);
330 acceptor
.async_accept(socket
, yield
[ec
]);
335 acceptor
.get_executor().context(),
340 std::placeholders::_1
));
344 int main(int argc
, char* argv
[])
346 // Check command line arguments.
350 "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" <<
352 " http-server-coro 0.0.0.0 8080 . 1\n";
355 auto const address
= boost::asio::ip::make_address(argv
[1]);
356 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
357 std::string
const doc_root
= argv
[3];
358 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
360 // The io_context is required for all I/O
361 boost::asio::io_context ioc
{threads
};
363 // Spawn a listening port
364 boost::asio::spawn(ioc
,
368 tcp::endpoint
{address
, port
},
370 std::placeholders::_1
));
372 // Run the I/O service on the requested number of threads
373 std::vector
<std::thread
> v
;
374 v
.reserve(threads
- 1);
375 for(auto i
= threads
- 1; i
> 0; --i
)