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 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/coroutine.hpp>
20 #include <boost/asio/dispatch.hpp>
21 #include <boost/asio/strand.hpp>
22 #include <boost/config.hpp>
32 namespace beast = boost::beast; // from <boost/beast.hpp>
33 namespace http = beast::http; // from <boost/beast/http.hpp>
34 namespace net = boost::asio; // from <boost/asio.hpp>
35 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
37 // Return a reasonable mime type based on the extension of a file.
39 mime_type(beast::string_view path)
42 auto const ext = [&path]
44 auto const pos = path.rfind(".");
45 if(pos == beast::string_view::npos)
46 return beast::string_view{};
47 return path.substr(pos);
49 if(iequals(ext, ".htm")) return "text/html";
50 if(iequals(ext, ".html")) return "text/html";
51 if(iequals(ext, ".php")) return "text/html";
52 if(iequals(ext, ".css")) return "text/css";
53 if(iequals(ext, ".txt")) return "text/plain";
54 if(iequals(ext, ".js")) return "application/javascript";
55 if(iequals(ext, ".json")) return "application/json";
56 if(iequals(ext, ".xml")) return "application/xml";
57 if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
58 if(iequals(ext, ".flv")) return "video/x-flv";
59 if(iequals(ext, ".png")) return "image/png";
60 if(iequals(ext, ".jpe")) return "image/jpeg";
61 if(iequals(ext, ".jpeg")) return "image/jpeg";
62 if(iequals(ext, ".jpg")) return "image/jpeg";
63 if(iequals(ext, ".gif")) return "image/gif";
64 if(iequals(ext, ".bmp")) return "image/bmp";
65 if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
66 if(iequals(ext, ".tiff")) return "image/tiff";
67 if(iequals(ext, ".tif")) return "image/tiff";
68 if(iequals(ext, ".svg")) return "image/svg+xml";
69 if(iequals(ext, ".svgz")) return "image/svg+xml";
70 return "application/text";
73 // Append an HTTP rel-path to a local filesystem path.
74 // The returned path is normalized for the platform.
77 beast::string_view base,
78 beast::string_view path)
81 return std::string(path);
82 std::string result(base);
84 char constexpr path_separator = '\\';
85 if(result.back() == path_separator)
86 result.resize(result.size() - 1);
87 result.append(path.data(), path.size());
92 char constexpr path_separator = '/';
93 if(result.back() == path_separator)
94 result.resize(result.size() - 1);
95 result.append(path.data(), path.size());
100 // This function produces an HTTP response for the given
101 // request. The type of the response object depends on the
102 // contents of the request, so the interface requires the
103 // caller to pass a generic lambda for receiving the response.
105 class Body, class Allocator,
109 beast::string_view doc_root,
110 http::request<Body, http::basic_fields<Allocator>>&& req,
113 // Returns a bad request response
114 auto const bad_request =
115 [&req](beast::string_view why)
117 http::response<http::string_body> res{http::status::bad_request, req.version()};
118 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
119 res.set(http::field::content_type, "text/html");
120 res.keep_alive(req.keep_alive());
121 res.body() = std::string(why);
122 res.prepare_payload();
126 // Returns a not found response
127 auto const not_found =
128 [&req](beast::string_view target)
130 http::response<http::string_body> res{http::status::not_found, req.version()};
131 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
132 res.set(http::field::content_type, "text/html");
133 res.keep_alive(req.keep_alive());
134 res.body() = "The resource '" + std::string(target) + "' was not found.";
135 res.prepare_payload();
139 // Returns a server error response
140 auto const server_error =
141 [&req](beast::string_view what)
143 http::response<http::string_body> res{http::status::internal_server_error, req.version()};
144 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
145 res.set(http::field::content_type, "text/html");
146 res.keep_alive(req.keep_alive());
147 res.body() = "An error occurred: '" + std::string(what) + "'";
148 res.prepare_payload();
152 // Make sure we can handle the method
153 if( req.method() != http::verb::get &&
154 req.method() != http::verb::head)
155 return send(bad_request("Unknown HTTP-method"));
157 // Request path must be absolute and not contain "..".
158 if( req.target().empty() ||
159 req.target()[0] != '/' ||
160 req.target().find("..") != beast::string_view::npos)
161 return send(bad_request("Illegal request-target"));
163 // Build the path to the requested file
164 std::string path = path_cat(doc_root, req.target());
165 if(req.target().back() == '/')
166 path.append("index.html");
168 // Attempt to open the file
169 beast::error_code ec;
170 http::file_body::value_type body;
171 body.open(path.c_str(), beast::file_mode::scan, ec);
173 // Handle the case where the file doesn't exist
174 if(ec == beast::errc::no_such_file_or_directory)
175 return send(not_found(req.target()));
177 // Handle an unknown error
179 return send(server_error(ec.message()));
181 // Cache the size since we need it after the move
182 auto const size = body.size();
184 // Respond to HEAD request
185 if(req.method() == http::verb::head)
187 http::response<http::empty_body> res{http::status::ok, req.version()};
188 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
189 res.set(http::field::content_type, mime_type(path));
190 res.content_length(size);
191 res.keep_alive(req.keep_alive());
192 return send(std::move(res));
195 // Respond to GET request
196 http::response<http::file_body> res{
197 std::piecewise_construct,
198 std::make_tuple(std::move(body)),
199 std::make_tuple(http::status::ok, req.version())};
200 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
201 res.set(http::field::content_type, mime_type(path));
202 res.content_length(size);
203 res.keep_alive(req.keep_alive());
204 return send(std::move(res));
207 //------------------------------------------------------------------------------
211 fail(beast::error_code ec, char const* what)
213 std::cerr << what << ": " << ec.message() << "\n";
216 // Handles an HTTP server connection
218 : public boost::asio::coroutine
219 , public std::enable_shared_from_this<session>
221 // This is the C++11 equivalent of a generic lambda.
222 // The function object is used to send an HTTP message.
226 std::shared_ptr<void> res_;
229 send_lambda(session& self)
234 template<bool isRequest, class Body, class Fields>
236 operator()(http::message<isRequest, Body, Fields>&& msg) const
238 // The lifetime of the message has to extend
239 // for the duration of the async operation so
240 // we use a shared_ptr to manage it.
241 auto sp = std::make_shared<
242 http::message<isRequest, Body, Fields>>(std::move(msg));
244 // Store a type-erased version of the shared
245 // pointer in the class to keep it alive.
248 // Write the response
252 beast::bind_front_handler(
254 self_.shared_from_this(),
259 beast::tcp_stream stream_;
260 beast::flat_buffer buffer_;
261 std::shared_ptr<std::string const> doc_root_;
262 http::request<http::string_body> req_;
263 std::shared_ptr<void> res_;
267 // Take ownership of the socket
270 tcp::socket&& socket,
271 std::shared_ptr<std::string const> const& doc_root)
272 : stream_(std::move(socket))
273 , doc_root_(doc_root)
278 // Start the asynchronous operation
282 // We need to be executing within a strand to perform async operations
283 // on the I/O objects in this session. Although not strictly necessary
284 // for single-threaded contexts, this example code is written to be
285 // thread-safe by default.
286 net::dispatch(stream_.get_executor(),
287 beast::bind_front_handler(&session::loop,
294 #include <boost/asio/yield.hpp>
299 beast::error_code ec,
300 std::size_t bytes_transferred)
302 boost::ignore_unused(bytes_transferred);
307 // Make the request empty before reading,
308 // otherwise the operation behavior is undefined.
312 stream_.expires_after(std::chrono::seconds(30));
315 yield http::async_read(stream_, buffer_, req_,
316 beast::bind_front_handler(
320 if(ec == http::error::end_of_stream)
322 // The remote host closed the connection
326 return fail(ec, "read");
329 yield handle_request(*doc_root_, std::move(req_), lambda_);
331 return fail(ec, "write");
334 // This means we should close the connection, usually because
335 // the response indicated the "Connection: close" semantic.
339 // We're done with the response so delete it
343 // Send a TCP shutdown
344 stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
346 // At this point the connection is closed gracefully
350 #include <boost/asio/unyield.hpp>
353 //------------------------------------------------------------------------------
355 // Accepts incoming connections and launches the sessions
357 : public boost::asio::coroutine
358 , public std::enable_shared_from_this<listener>
360 net::io_context& ioc_;
361 tcp::acceptor acceptor_;
363 std::shared_ptr<std::string const> doc_root_;
367 net::io_context& ioc,
368 tcp::endpoint endpoint,
369 std::shared_ptr<std::string const> const& doc_root)
371 , acceptor_(net::make_strand(ioc))
372 , socket_(net::make_strand(ioc))
373 , doc_root_(doc_root)
375 beast::error_code ec;
378 acceptor_.open(endpoint.protocol(), ec);
385 // Allow address reuse
386 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
389 fail(ec, "set_option");
393 // Bind to the server address
394 acceptor_.bind(endpoint, ec);
401 // Start listening for connections
402 acceptor_.listen(net::socket_base::max_listen_connections, ec);
410 // Start accepting incoming connections
419 #include <boost/asio/yield.hpp>
422 loop(beast::error_code ec = {})
428 yield acceptor_.async_accept(
430 beast::bind_front_handler(
432 shared_from_this()));
439 // Create the session and run it
440 std::make_shared<session>(
445 // Make sure each session gets its own strand
446 socket_ = tcp::socket(net::make_strand(ioc_));
451 #include <boost/asio/unyield.hpp>
454 //------------------------------------------------------------------------------
456 int main(int argc, char* argv[])
458 // Check command line arguments.
462 "Usage: http-server-stackless <address> <port> <doc_root> <threads>\n" <<
464 " http-server-stackless 0.0.0.0 8080 . 1\n";
467 auto const address = net::ip::make_address(argv[1]);
468 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
469 auto const doc_root = std::make_shared<std::string>(argv[3]);
470 auto const threads = std::max<int>(1, std::atoi(argv[4]));
472 // The io_context is required for all I/O
473 net::io_context ioc{threads};
475 // Create and launch a listening port
476 std::make_shared<listener>(
478 tcp::endpoint{address, port},
481 // Run the I/O service on the requested number of threads
482 std::vector<std::thread> v;
483 v.reserve(threads - 1);
484 for(auto i = threads - 1; i > 0; --i)