• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
3 //
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)
6 //
7 // Official repository: https://github.com/boostorg/beast
8 //
9 
10 //------------------------------------------------------------------------------
11 //
12 // Example: HTTP SSL server, coroutine
13 //
14 //------------------------------------------------------------------------------
15 
16 #include "example/common/server_certificate.hpp"
17 
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/http.hpp>
20 #include <boost/beast/ssl.hpp>
21 #include <boost/beast/version.hpp>
22 #include <boost/asio/spawn.hpp>
23 #include <boost/config.hpp>
24 #include <algorithm>
25 #include <cstdlib>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <thread>
30 #include <vector>
31 
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 namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
36 using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
37 
38 // Return a reasonable mime type based on the extension of a file.
39 beast::string_view
mime_type(beast::string_view path)40 mime_type(beast::string_view path)
41 {
42     using beast::iequals;
43     auto const ext = [&path]
44     {
45         auto const pos = path.rfind(".");
46         if(pos == beast::string_view::npos)
47             return beast::string_view{};
48         return path.substr(pos);
49     }();
50     if(iequals(ext, ".htm"))  return "text/html";
51     if(iequals(ext, ".html")) return "text/html";
52     if(iequals(ext, ".php"))  return "text/html";
53     if(iequals(ext, ".css"))  return "text/css";
54     if(iequals(ext, ".txt"))  return "text/plain";
55     if(iequals(ext, ".js"))   return "application/javascript";
56     if(iequals(ext, ".json")) return "application/json";
57     if(iequals(ext, ".xml"))  return "application/xml";
58     if(iequals(ext, ".swf"))  return "application/x-shockwave-flash";
59     if(iequals(ext, ".flv"))  return "video/x-flv";
60     if(iequals(ext, ".png"))  return "image/png";
61     if(iequals(ext, ".jpe"))  return "image/jpeg";
62     if(iequals(ext, ".jpeg")) return "image/jpeg";
63     if(iequals(ext, ".jpg"))  return "image/jpeg";
64     if(iequals(ext, ".gif"))  return "image/gif";
65     if(iequals(ext, ".bmp"))  return "image/bmp";
66     if(iequals(ext, ".ico"))  return "image/vnd.microsoft.icon";
67     if(iequals(ext, ".tiff")) return "image/tiff";
68     if(iequals(ext, ".tif"))  return "image/tiff";
69     if(iequals(ext, ".svg"))  return "image/svg+xml";
70     if(iequals(ext, ".svgz")) return "image/svg+xml";
71     return "application/text";
72 }
73 
74 // Append an HTTP rel-path to a local filesystem path.
75 // The returned path is normalized for the platform.
76 std::string
path_cat(beast::string_view base,beast::string_view path)77 path_cat(
78     beast::string_view base,
79     beast::string_view path)
80 {
81     if(base.empty())
82         return std::string(path);
83     std::string result(base);
84 #ifdef BOOST_MSVC
85     char constexpr path_separator = '\\';
86     if(result.back() == path_separator)
87         result.resize(result.size() - 1);
88     result.append(path.data(), path.size());
89     for(auto& c : result)
90         if(c == '/')
91             c = path_separator;
92 #else
93     char constexpr path_separator = '/';
94     if(result.back() == path_separator)
95         result.resize(result.size() - 1);
96     result.append(path.data(), path.size());
97 #endif
98     return result;
99 }
100 
101 // This function produces an HTTP response for the given
102 // request. The type of the response object depends on the
103 // contents of the request, so the interface requires the
104 // caller to pass a generic lambda for receiving the response.
105 template<
106     class Body, class Allocator,
107     class Send>
108 void
handle_request(beast::string_view doc_root,http::request<Body,http::basic_fields<Allocator>> && req,Send && send)109 handle_request(
110     beast::string_view doc_root,
111     http::request<Body, http::basic_fields<Allocator>>&& req,
112     Send&& send)
113 {
114     // Returns a bad request response
115     auto const bad_request =
116     [&req](beast::string_view why)
117     {
118         http::response<http::string_body> res{http::status::bad_request, req.version()};
119         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
120         res.set(http::field::content_type, "text/html");
121         res.keep_alive(req.keep_alive());
122         res.body() = std::string(why);
123         res.prepare_payload();
124         return res;
125     };
126 
127     // Returns a not found response
128     auto const not_found =
129     [&req](beast::string_view target)
130     {
131         http::response<http::string_body> res{http::status::not_found, req.version()};
132         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
133         res.set(http::field::content_type, "text/html");
134         res.keep_alive(req.keep_alive());
135         res.body() = "The resource '" + std::string(target) + "' was not found.";
136         res.prepare_payload();
137         return res;
138     };
139 
140     // Returns a server error response
141     auto const server_error =
142     [&req](beast::string_view what)
143     {
144         http::response<http::string_body> res{http::status::internal_server_error, req.version()};
145         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
146         res.set(http::field::content_type, "text/html");
147         res.keep_alive(req.keep_alive());
148         res.body() = "An error occurred: '" + std::string(what) + "'";
149         res.prepare_payload();
150         return res;
151     };
152 
153     // Make sure we can handle the method
154     if( req.method() != http::verb::get &&
155         req.method() != http::verb::head)
156         return send(bad_request("Unknown HTTP-method"));
157 
158     // Request path must be absolute and not contain "..".
159     if( req.target().empty() ||
160         req.target()[0] != '/' ||
161         req.target().find("..") != beast::string_view::npos)
162         return send(bad_request("Illegal request-target"));
163 
164     // Build the path to the requested file
165     std::string path = path_cat(doc_root, req.target());
166     if(req.target().back() == '/')
167         path.append("index.html");
168 
169     // Attempt to open the file
170     beast::error_code ec;
171     http::file_body::value_type body;
172     body.open(path.c_str(), beast::file_mode::scan, ec);
173 
174     // Handle the case where the file doesn't exist
175     if(ec == beast::errc::no_such_file_or_directory)
176         return send(not_found(req.target()));
177 
178     // Handle an unknown error
179     if(ec)
180         return send(server_error(ec.message()));
181 
182     // Cache the size since we need it after the move
183     auto const size = body.size();
184 
185     // Respond to HEAD request
186     if(req.method() == http::verb::head)
187     {
188         http::response<http::empty_body> res{http::status::ok, req.version()};
189         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
190         res.set(http::field::content_type, mime_type(path));
191         res.content_length(size);
192         res.keep_alive(req.keep_alive());
193         return send(std::move(res));
194     }
195 
196     // Respond to GET request
197     http::response<http::file_body> res{
198         std::piecewise_construct,
199         std::make_tuple(std::move(body)),
200         std::make_tuple(http::status::ok, req.version())};
201     res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
202     res.set(http::field::content_type, mime_type(path));
203     res.content_length(size);
204     res.keep_alive(req.keep_alive());
205     return send(std::move(res));
206 }
207 
208 //------------------------------------------------------------------------------
209 
210 // Report a failure
211 void
fail(beast::error_code ec,char const * what)212 fail(beast::error_code ec, char const* what)
213 {
214     // ssl::error::stream_truncated, also known as an SSL "short read",
215     // indicates the peer closed the connection without performing the
216     // required closing handshake (for example, Google does this to
217     // improve performance). Generally this can be a security issue,
218     // but if your communication protocol is self-terminated (as
219     // it is with both HTTP and WebSocket) then you may simply
220     // ignore the lack of close_notify.
221     //
222     // https://github.com/boostorg/beast/issues/38
223     //
224     // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
225     //
226     // When a short read would cut off the end of an HTTP message,
227     // Beast returns the error beast::http::error::partial_message.
228     // Therefore, if we see a short read here, it has occurred
229     // after the message has been completed, so it is safe to ignore it.
230 
231     if(ec == net::ssl::error::stream_truncated)
232         return;
233 
234     std::cerr << what << ": " << ec.message() << "\n";
235 }
236 
237 // This is the C++11 equivalent of a generic lambda.
238 // The function object is used to send an HTTP message.
239 struct send_lambda
240 {
241     beast::ssl_stream<beast::tcp_stream>& stream_;
242     bool& close_;
243     beast::error_code& ec_;
244     net::yield_context yield_;
245 
send_lambdasend_lambda246     send_lambda(
247         beast::ssl_stream<beast::tcp_stream>& stream,
248         bool& close,
249         beast::error_code& ec,
250         net::yield_context yield)
251         : stream_(stream)
252         , close_(close)
253         , ec_(ec)
254         , yield_(yield)
255     {
256     }
257 
258     template<bool isRequest, class Body, class Fields>
259     void
operator ()send_lambda260     operator()(http::message<isRequest, Body, Fields>&& msg) const
261     {
262         // Determine if we should close the connection after
263         close_ = msg.need_eof();
264 
265         // We need the serializer here because the serializer requires
266         // a non-const file_body, and the message oriented version of
267         // http::write only works with const messages.
268         http::serializer<isRequest, Body, Fields> sr{msg};
269         http::async_write(stream_, sr, yield_[ec_]);
270     }
271 };
272 
273 // Handles an HTTP server connection
274 void
do_session(beast::ssl_stream<beast::tcp_stream> & stream,std::shared_ptr<std::string const> const & doc_root,net::yield_context yield)275 do_session(
276     beast::ssl_stream<beast::tcp_stream>& stream,
277     std::shared_ptr<std::string const> const& doc_root,
278     net::yield_context yield)
279 {
280     bool close = false;
281     beast::error_code ec;
282 
283     // Set the timeout.
284     beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
285 
286     // Perform the SSL handshake
287     stream.async_handshake(ssl::stream_base::server, yield[ec]);
288     if(ec)
289         return fail(ec, "handshake");
290 
291     // This buffer is required to persist across reads
292     beast::flat_buffer buffer;
293 
294     // This lambda is used to send messages
295     send_lambda lambda{stream, close, ec, yield};
296 
297     for(;;)
298     {
299         // Set the timeout.
300         beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
301 
302         // Read a request
303         http::request<http::string_body> req;
304         http::async_read(stream, buffer, req, yield[ec]);
305         if(ec == http::error::end_of_stream)
306             break;
307         if(ec)
308             return fail(ec, "read");
309 
310         // Send the response
311         handle_request(*doc_root, std::move(req), lambda);
312         if(ec)
313             return fail(ec, "write");
314         if(close)
315         {
316             // This means we should close the connection, usually because
317             // the response indicated the "Connection: close" semantic.
318             break;
319         }
320     }
321 
322     // Set the timeout.
323     beast::get_lowest_layer(stream).expires_after(std::chrono::seconds(30));
324 
325     // Perform the SSL shutdown
326     stream.async_shutdown(yield[ec]);
327     if(ec)
328         return fail(ec, "shutdown");
329 
330     // At this point the connection is closed gracefully
331 }
332 
333 //------------------------------------------------------------------------------
334 
335 // Accepts incoming connections and launches the sessions
336 void
do_listen(net::io_context & ioc,ssl::context & ctx,tcp::endpoint endpoint,std::shared_ptr<std::string const> const & doc_root,net::yield_context yield)337 do_listen(
338     net::io_context& ioc,
339     ssl::context& ctx,
340     tcp::endpoint endpoint,
341     std::shared_ptr<std::string const> const& doc_root,
342     net::yield_context yield)
343 {
344     beast::error_code ec;
345 
346     // Open the acceptor
347     tcp::acceptor acceptor(ioc);
348     acceptor.open(endpoint.protocol(), ec);
349     if(ec)
350         return fail(ec, "open");
351 
352     // Allow address reuse
353     acceptor.set_option(net::socket_base::reuse_address(true), ec);
354     if(ec)
355         return fail(ec, "set_option");
356 
357     // Bind to the server address
358     acceptor.bind(endpoint, ec);
359     if(ec)
360         return fail(ec, "bind");
361 
362     // Start listening for connections
363     acceptor.listen(net::socket_base::max_listen_connections, ec);
364     if(ec)
365         return fail(ec, "listen");
366 
367     for(;;)
368     {
369         tcp::socket socket(ioc);
370         acceptor.async_accept(socket, yield[ec]);
371         if(ec)
372             fail(ec, "accept");
373         else
374             boost::asio::spawn(
375                 acceptor.get_executor(),
376                 std::bind(
377                     &do_session,
378                     beast::ssl_stream<beast::tcp_stream>(
379                         std::move(socket), ctx),
380                     doc_root,
381                     std::placeholders::_1));
382     }
383 }
384 
main(int argc,char * argv[])385 int main(int argc, char* argv[])
386 {
387     // Check command line arguments.
388     if (argc != 5)
389     {
390         std::cerr <<
391             "Usage: http-server-coro-ssl <address> <port> <doc_root> <threads>\n" <<
392             "Example:\n" <<
393             "    http-server-coro-ssl 0.0.0.0 8080 . 1\n";
394         return EXIT_FAILURE;
395     }
396     auto const address = net::ip::make_address(argv[1]);
397     auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
398     auto const doc_root = std::make_shared<std::string>(argv[3]);
399     auto const threads = std::max<int>(1, std::atoi(argv[4]));
400 
401     // The io_context is required for all I/O
402     net::io_context ioc{threads};
403 
404     // The SSL context is required, and holds certificates
405     ssl::context ctx{ssl::context::tlsv12};
406 
407     // This holds the self-signed certificate used by the server
408     load_server_certificate(ctx);
409 
410     // Spawn a listening port
411     boost::asio::spawn(ioc,
412         std::bind(
413             &do_listen,
414             std::ref(ioc),
415             std::ref(ctx),
416             tcp::endpoint{address, port},
417             doc_root,
418             std::placeholders::_1));
419 
420     // Run the I/O service on the requested number of threads
421     std::vector<std::thread> v;
422     v.reserve(threads - 1);
423     for(auto i = threads - 1; i > 0; --i)
424         v.emplace_back(
425         [&ioc]
426         {
427             ioc.run();
428         });
429     ioc.run();
430 
431     return EXIT_SUCCESS;
432 }
433