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 SSL server, coroutine
14 //------------------------------------------------------------------------------
16 #include "example/common/server_certificate.hpp"
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/http.hpp>
20 #include <boost/beast/version.hpp>
21 #include <boost/asio/ip/tcp.hpp>
22 #include <boost/asio/spawn.hpp>
23 #include <boost/asio/ssl/stream.hpp>
24 #include <boost/config.hpp>
33 using tcp
= boost::asio::ip::tcp
; // from <boost/asio/ip/tcp.hpp>
34 namespace ssl
= boost::asio::ssl
; // from <boost/asio/ssl.hpp>
35 namespace http
= boost::beast::http
; // from <boost/beast/http.hpp>
37 // Return a reasonable mime type based on the extension of a file.
38 boost::beast::string_view
39 mime_type(boost::beast::string_view path
)
41 using boost::beast::iequals
;
42 auto const ext
= [&path
]
44 auto const pos
= path
.rfind(".");
45 if(pos
== boost::beast::string_view::npos
)
46 return boost::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 boost::beast::string_view base
,
78 boost::beast::string_view path
)
81 return path
.to_string();
82 std::string result
= base
.to_string();
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 boost::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
](boost::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() = why
.to_string();
122 res
.prepare_payload();
126 // Returns a not found response
127 auto const not_found
=
128 [&req
](boost::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 '" + target
.to_string() + "' was not found.";
135 res
.prepare_payload();
139 // Returns a server error response
140 auto const server_error
=
141 [&req
](boost::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: '" + what
.to_string() + "'";
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("..") != boost::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 boost::beast::error_code ec
;
170 http::file_body::value_type body
;
171 body
.open(path
.c_str(), boost::beast::file_mode::scan
, ec
);
173 // Handle the case where the file doesn't exist
174 if(ec
== boost::system::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 // Respond to HEAD request
182 if(req
.method() == http::verb::head
)
184 http::response
<http::empty_body
> res
{http::status::ok
, req
.version()};
185 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
186 res
.set(http::field::content_type
, mime_type(path
));
187 res
.content_length(body
.size());
188 res
.keep_alive(req
.keep_alive());
189 return send(std::move(res
));
192 // Respond to GET request
193 http::response
<http::file_body
> res
{
194 std::piecewise_construct
,
195 std::make_tuple(std::move(body
)),
196 std::make_tuple(http::status::ok
, req
.version())};
197 res
.set(http::field::server
, BOOST_BEAST_VERSION_STRING
);
198 res
.set(http::field::content_type
, mime_type(path
));
199 res
.content_length(body
.size());
200 res
.keep_alive(req
.keep_alive());
201 return send(std::move(res
));
204 //------------------------------------------------------------------------------
208 fail(boost::system::error_code ec
, char const* what
)
210 std::cerr
<< what
<< ": " << ec
.message() << "\n";
213 // This is the C++11 equivalent of a generic lambda.
214 // The function object is used to send an HTTP message.
215 template<class Stream
>
220 boost::system::error_code
& ec_
;
221 boost::asio::yield_context yield_
;
227 boost::system::error_code
& ec
,
228 boost::asio::yield_context yield
)
236 template<bool isRequest
, class Body
, class Fields
>
238 operator()(http::message
<isRequest
, Body
, Fields
>&& msg
) const
240 // Determine if we should close the connection after
241 close_
= msg
.need_eof();
243 // We need the serializer here because the serializer requires
244 // a non-const file_body, and the message oriented version of
245 // http::write only works with const messages.
246 http::serializer
<isRequest
, Body
, Fields
> sr
{msg
};
247 http::async_write(stream_
, sr
, yield_
[ec_
]);
251 // Handles an HTTP server connection
256 std::string
const& doc_root
,
257 boost::asio::yield_context yield
)
260 boost::system::error_code ec
;
262 // Construct the stream around the socket
263 ssl::stream
<tcp::socket
&> stream
{socket
, ctx
};
265 // Perform the SSL handshake
266 stream
.async_handshake(ssl::stream_base::server
, yield
[ec
]);
268 return fail(ec
, "handshake");
270 // This buffer is required to persist across reads
271 boost::beast::flat_buffer buffer
;
273 // This lambda is used to send messages
274 send_lambda
<ssl::stream
<tcp::socket
&>> lambda
{stream
, close
, ec
, yield
};
279 http::request
<http::string_body
> req
;
280 http::async_read(stream
, buffer
, req
, yield
[ec
]);
281 if(ec
== http::error::end_of_stream
)
284 return fail(ec
, "read");
287 handle_request(doc_root
, std::move(req
), lambda
);
289 return fail(ec
, "write");
292 // This means we should close the connection, usually because
293 // the response indicated the "Connection: close" semantic.
298 // Perform the SSL shutdown
299 stream
.async_shutdown(yield
[ec
]);
301 return fail(ec
, "shutdown");
303 // At this point the connection is closed gracefully
306 //------------------------------------------------------------------------------
308 // Accepts incoming connections and launches the sessions
311 boost::asio::io_context
& ioc
,
313 tcp::endpoint endpoint
,
314 std::string
const& doc_root
,
315 boost::asio::yield_context yield
)
317 boost::system::error_code ec
;
320 tcp::acceptor
acceptor(ioc
);
321 acceptor
.open(endpoint
.protocol(), ec
);
323 return fail(ec
, "open");
325 // Bind to the server address
326 acceptor
.bind(endpoint
, ec
);
328 return fail(ec
, "bind");
330 // Start listening for connections
331 acceptor
.listen(boost::asio::socket_base::max_listen_connections
, ec
);
333 return fail(ec
, "listen");
337 tcp::socket
socket(ioc
);
338 acceptor
.async_accept(socket
, yield
[ec
]);
343 acceptor
.get_executor().context(),
349 std::placeholders::_1
));
353 int main(int argc
, char* argv
[])
355 // Check command line arguments.
359 "Usage: http-server-coro-ssl <address> <port> <doc_root> <threads>\n" <<
361 " http-server-coro-ssl 0.0.0.0 8080 . 1\n";
364 auto const address
= boost::asio::ip::make_address(argv
[1]);
365 auto const port
= static_cast<unsigned short>(std::atoi(argv
[2]));
366 std::string
const doc_root
= argv
[3];
367 auto const threads
= std::max
<int>(1, std::atoi(argv
[4]));
369 // The io_context is required for all I/O
370 boost::asio::io_context ioc
{threads
};
372 // The SSL context is required, and holds certificates
373 ssl::context ctx
{ssl::context::sslv23
};
375 // This holds the self-signed certificate used by the server
376 load_server_certificate(ctx
);
378 // Spawn a listening port
379 boost::asio::spawn(ioc
,
384 tcp::endpoint
{address
, port
},
386 std::placeholders::_1
));
388 // Run the I/O service on the requested number of threads
389 std::vector
<std::thread
> v
;
390 v
.reserve(threads
- 1);
391 for(auto i
= threads
- 1; i
> 0; --i
)