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, stackless coroutine
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/coroutine.hpp>
21 #include <boost/asio/ip/tcp.hpp>
22 #include <boost/asio/strand.hpp>
23 #include <boost/config.hpp>
33 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
34 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
36 // Return a reasonable mime type based on the extension of a file.
37 boost::beast::string_view
38 mime_type(boost::beast::string_view path
)
40 using boost::beast::iequals
;
41 auto const ext
= [&path
]
43 auto const pos
= path
.rfind(".");
44 if(pos
== boost::beast::string_view::npos
)
45 return boost::beast::string_view
{};
46 return path
.substr(pos
);
48 if(iequals(ext
, ".htm")) return "text/html";
49 if(iequals(ext
, ".html")) return "text/html";
50 if(iequals(ext
, ".php")) return "text/html";
51 if(iequals(ext
, ".css")) return "text/css";
52 if(iequals(ext
, ".txt")) return "text/plain";
53 if(iequals(ext
, ".js")) return "application/javascript";
54 if(iequals(ext
, ".json")) return "application/json";
55 if(iequals(ext
, ".xml")) return "application/xml";
56 if(iequals(ext
, ".swf")) return "application/x-shockwave-flash";
57 if(iequals(ext
, ".flv")) return "video/x-flv";
58 if(iequals(ext
, ".png")) return "image/png";
59 if(iequals(ext
, ".jpe")) return "image/jpeg";
60 if(iequals(ext
, ".jpeg")) return "image/jpeg";
61 if(iequals(ext
, ".jpg")) return "image/jpeg";
62 if(iequals(ext
, ".gif")) return "image/gif";
63 if(iequals(ext
, ".bmp")) return "image/bmp";
64 if(iequals(ext
, ".ico")) return "image/vnd.microsoft.icon";
65 if(iequals(ext
, ".tiff")) return "image/tiff";
66 if(iequals(ext
, ".tif")) return "image/tiff";
67 if(iequals(ext
, ".svg")) return "image/svg+xml";
68 if(iequals(ext
, ".svgz")) return "image/svg+xml";
69 return "application/text";
72 // Append an HTTP rel-path to a local filesystem path.
73 // The returned path is normalized for the platform.
76 boost::beast::string_view base
,
77 boost::beast::string_view path
)
80 return path
.to_string();
81 std::string result
= base
.to_string();
83 char constexpr path_separator
= '\\';
84 if(result
.back() == path_separator
)
85 result
.resize(result
.size() - 1);
86 result
.append(path
.data(), path
.size());
91 char constexpr path_separator
= '/';
92 if(result
.back() == path_separator
)
93 result
.resize(result
.size() - 1);
94 result
.append(path
.data(), path
.size());
99 // This function produces an HTTP response for the given
100 // request. The type of the response object depends on the
101 // contents of the request, so the interface requires the
102 // caller to pass a generic lambda for receiving the response.
104 class Body
, class Allocator
,
108 boost::beast::string_view doc_root
,
109 http::request
<Body
, http::basic_fields
<Allocator
>>&& req
,
112 // Returns a bad request response
113 auto const bad_request
=
114 [&req
](boost::beast::string_view why
)
116 http::response
<http::string_body
> res
{http::status::bad_request
, req
.version()};
117 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
118 res
.set(http::field::content_type
, "text/html");
119 res
.keep_alive(req
.keep_alive());
120 res
.body() = why
.to_string();
121 res
.prepare_payload();
125 // Returns a not found response
126 auto const not_found
=
127 [&req
](boost::beast::string_view target
)
129 http::response
<http::string_body
> res
{http::status::not_found
, req
.version()};
130 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
131 res
.set(http::field::content_type
, "text/html");
132 res
.keep_alive(req
.keep_alive());
133 res
.body() = "The resource '" + target
.to_string() + "' was not found.";
134 res
.prepare_payload();
138 // Returns a server error response
139 auto const server_error
=
140 [&req
](boost::beast::string_view what
)
142 http::response
<http::string_body
> res
{http::status::internal_server_error
, req
.version()};
143 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
144 res
.set(http::field::content_type
, "text/html");
145 res
.keep_alive(req
.keep_alive());
146 res
.body() = "An error occurred: '" + what
.to_string() + "'";
147 res
.prepare_payload();
151 // Make sure we can handle the method
152 if( req
.method() != http::verb::get
&&
153 req
.method() != http::verb::head
)
154 return send(bad_request("Unknown HTTP-method"));
156 // Request path must be absolute and not contain "..".
157 if( req
.target().empty() ||
158 req
.target()[0] != '/' ||
159 req
.target().find("..") != boost::beast::string_view::npos
)
160 return send(bad_request("Illegal request-target"));
162 // Build the path to the requested file
163 std::string path
= path_cat(doc_root
, req
.target());
164 if(req
.target().back() == '/')
165 path
.append("index.html");
167 // Attempt to open the file
168 boost::beast::error_code ec
;
169 http::file_body::value_type body
;
170 body
.open(path
.c_str(), boost::beast::file_mode::scan
, ec
);
172 // Handle the case where the file doesn't exist
173 if(ec
== boost::system::errc::no_such_file_or_directory
)
174 return send(not_found(req
.target()));
176 // Handle an unknown error
178 return send(server_error(ec
.message()));
180 // Cache the size since we need it after the move
181 auto const size
= body
.size();
183 // Respond to HEAD request
184 if(req
.method() == http::verb::head
)
186 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
187 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
188 res
.set(http::field::content_type
, mime_type(path
));
189 res
.content_length(size
);
190 res
.keep_alive(req
.keep_alive());
191 return send(std::move(res
));
194 // Respond to GET request
195 http::response
<http::file_body
> res
{
196 std::piecewise_construct
,
197 std::make_tuple(std::move(body
)),
198 std::make_tuple(http::status::ok
, req
.version())};
199 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
200 res
.set(http::field::content_type
, mime_type(path
));
201 res
.content_length(size
);
202 res
.keep_alive(req
.keep_alive());
203 return send(std::move(res
));
206 //------------------------------------------------------------------------------
210 fail(boost::system::error_code ec
, char const* what
)
212 std::cerr
<< what
<< ": " << ec
.message() << "\n";
215 // Handles an HTTP server connection
217 : public boost::asio::coroutine
218 , public std::enable_shared_from_this
<session
>
220 // This is the C++11 equivalent of a generic lambda.
221 // The function object is used to send an HTTP message.
225 std::shared_ptr
<void> res_
;
228 send_lambda(session
& self
)
233 template<bool isRequest
, class Body
, class Fields
>
235 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
237 // The lifetime of the message has to extend
238 // for the duration of the async operation so
239 // we use a shared_ptr to manage it.
240 auto sp
= std::make_shared
<
241 http::message
<isRequest
, Body
, Fields
>>(std::move(msg
));
243 // Store a type-erased version of the shared
244 // pointer in the class to keep it alive.
247 // Write the response
251 boost::asio::bind_executor(
255 self_
.shared_from_this(),
256 std::placeholders::_1
,
257 std::placeholders::_2
,
264 boost::asio::io_context::executor_type
> strand_
;
265 boost::beast::flat_buffer buffer_
;
266 std::string
const& doc_root_
;
267 http::request
<http::string_body
> req_
;
268 std::shared_ptr
<void> res_
;
272 // Take ownership of the socket
276 std::string
const& doc_root
)
277 : socket_(std::move(socket
))
278 , strand_(socket_
.get_executor())
279 , doc_root_(doc_root
)
284 // Start the asynchronous operation
291 #include <boost/asio/yield.hpp>
294 boost::system::error_code ec
,
295 std::size_t bytes_transferred
,
298 boost::ignore_unused(bytes_transferred
);
303 // Make the request empty before reading,
304 // otherwise the operation behavior is undefined.
308 yield
http::async_read(socket_
, buffer_
, req_
,
309 boost::asio::bind_executor(
314 std::placeholders::_1
,
315 std::placeholders::_2
,
317 if(ec
== http::error::end_of_stream
)
319 // The remote host closed the connection
323 return fail(ec
, "read");
326 yield
handle_request(doc_root_
, std::move(req_
), lambda_
);
328 return fail(ec
, "write");
331 // This means we should close the connection, usually because
332 // the response indicated the "Connection: close" semantic.
336 // We're done with the response so delete it
340 // Send a TCP shutdown
341 socket_
.shutdown(tcp::socket::shutdown_send
, ec
);
343 // At this point the connection is closed gracefully
346 #include <boost/asio/unyield.hpp>
349 //------------------------------------------------------------------------------
351 // Accepts incoming connections and launches the sessions
353 : public boost::asio::coroutine
354 , public std::enable_shared_from_this
<listener
>
356 tcp::acceptor acceptor_
;
358 std::string
const& doc_root_
;
362 boost::asio::io_context
& ioc
,
363 tcp::endpoint endpoint
,
364 std::string
const& doc_root
)
367 , doc_root_(doc_root
)
369 boost::system::error_code ec
;
372 acceptor_
.open(endpoint
.protocol(), ec
);
379 // Allow address reuse
380 acceptor_
.set_option(boost::asio::socket_base::reuse_address(true));
383 fail(ec
, "set_option");
387 // Bind to the server address
388 acceptor_
.bind(endpoint
, ec
);
395 // Start listening for connections
396 acceptor_
.listen(boost::asio::socket_base::max_listen_connections
, ec
);
404 // Start accepting incoming connections
408 if(! acceptor_
.is_open())
413 #include <boost/asio/yield.hpp>
415 loop(boost::system::error_code ec
= {})
421 yield acceptor_
.async_accept(
426 std::placeholders::_1
));
433 // Create the session and run it
434 std::make_shared
<session
>(
441 #include <boost/asio/unyield.hpp>
444 //------------------------------------------------------------------------------
446 int main(int argc
, char* argv
[])
448 // Check command line arguments.
452 "Usage: http-server-stackless <address> <port> <doc_root> <threads>\n" <<
454 " http-server-stackless 0.0.0.0 8080 . 1\n";
457 auto const address
= boost::asio::ip::make_address(argv
[1]);
458 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
459 std::string
const doc_root
= argv
[3];
460 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
462 // The io_context is required for all I/O
463 boost::asio::io_context ioc
{threads
};
465 // Create and launch a listening port
466 std::make_shared
<listener
>(
468 tcp::endpoint
{address
, port
},
471 // Run the I/O service on the requested number of threads
472 std::vector
<std::thread
> v
;
473 v
.reserve(threads
- 1);
474 for(auto i
= threads
- 1; i
> 0; --i
)