Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / beast / example / http / server / async-ssl / http_server_async_ssl.cpp
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, asynchronous
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/dispatch.hpp>
23 #include <boost/asio/strand.hpp>
24 #include <boost/config.hpp>
25 #include <algorithm>
26 #include <cstdlib>
27 #include <functional>
28 #include <iostream>
29 #include <memory>
30 #include <string>
31 #include <thread>
32 #include <vector>
33
34 namespace beast = boost::beast;         // from <boost/beast.hpp>
35 namespace http = beast::http;           // from <boost/beast/http.hpp>
36 namespace net = boost::asio;            // from <boost/asio.hpp>
37 namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
38 using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
39
40 // Return a reasonable mime type based on the extension of a file.
41 beast::string_view
42 mime_type(beast::string_view path)
43 {
44     using beast::iequals;
45     auto const ext = [&path]
46     {
47         auto const pos = path.rfind(".");
48         if(pos == beast::string_view::npos)
49             return beast::string_view{};
50         return path.substr(pos);
51     }();
52     if(iequals(ext, ".htm"))  return "text/html";
53     if(iequals(ext, ".html")) return "text/html";
54     if(iequals(ext, ".php"))  return "text/html";
55     if(iequals(ext, ".css"))  return "text/css";
56     if(iequals(ext, ".txt"))  return "text/plain";
57     if(iequals(ext, ".js"))   return "application/javascript";
58     if(iequals(ext, ".json")) return "application/json";
59     if(iequals(ext, ".xml"))  return "application/xml";
60     if(iequals(ext, ".swf"))  return "application/x-shockwave-flash";
61     if(iequals(ext, ".flv"))  return "video/x-flv";
62     if(iequals(ext, ".png"))  return "image/png";
63     if(iequals(ext, ".jpe"))  return "image/jpeg";
64     if(iequals(ext, ".jpeg")) return "image/jpeg";
65     if(iequals(ext, ".jpg"))  return "image/jpeg";
66     if(iequals(ext, ".gif"))  return "image/gif";
67     if(iequals(ext, ".bmp"))  return "image/bmp";
68     if(iequals(ext, ".ico"))  return "image/vnd.microsoft.icon";
69     if(iequals(ext, ".tiff")) return "image/tiff";
70     if(iequals(ext, ".tif"))  return "image/tiff";
71     if(iequals(ext, ".svg"))  return "image/svg+xml";
72     if(iequals(ext, ".svgz")) return "image/svg+xml";
73     return "application/text";
74 }
75
76 // Append an HTTP rel-path to a local filesystem path.
77 // The returned path is normalized for the platform.
78 std::string
79 path_cat(
80     beast::string_view base,
81     beast::string_view path)
82 {
83     if(base.empty())
84         return std::string(path);
85     std::string result(base);
86 #ifdef BOOST_MSVC
87     char constexpr path_separator = '\\';
88     if(result.back() == path_separator)
89         result.resize(result.size() - 1);
90     result.append(path.data(), path.size());
91     for(auto& c : result)
92         if(c == '/')
93             c = path_separator;
94 #else
95     char constexpr path_separator = '/';
96     if(result.back() == path_separator)
97         result.resize(result.size() - 1);
98     result.append(path.data(), path.size());
99 #endif
100     return result;
101 }
102
103 // This function produces an HTTP response for the given
104 // request. The type of the response object depends on the
105 // contents of the request, so the interface requires the
106 // caller to pass a generic lambda for receiving the response.
107 template<
108     class Body, class Allocator,
109     class Send>
110 void
111 handle_request(
112     beast::string_view doc_root,
113     http::request<Body, http::basic_fields<Allocator>>&& req,
114     Send&& send)
115 {
116     // Returns a bad request response
117     auto const bad_request =
118     [&req](beast::string_view why)
119     {
120         http::response<http::string_body> res{http::status::bad_request, req.version()};
121         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
122         res.set(http::field::content_type, "text/html");
123         res.keep_alive(req.keep_alive());
124         res.body() = std::string(why);
125         res.prepare_payload();
126         return res;
127     };
128
129     // Returns a not found response
130     auto const not_found =
131     [&req](beast::string_view target)
132     {
133         http::response<http::string_body> res{http::status::not_found, req.version()};
134         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
135         res.set(http::field::content_type, "text/html");
136         res.keep_alive(req.keep_alive());
137         res.body() = "The resource '" + std::string(target) + "' was not found.";
138         res.prepare_payload();
139         return res;
140     };
141
142     // Returns a server error response
143     auto const server_error =
144     [&req](beast::string_view what)
145     {
146         http::response<http::string_body> res{http::status::internal_server_error, req.version()};
147         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
148         res.set(http::field::content_type, "text/html");
149         res.keep_alive(req.keep_alive());
150         res.body() = "An error occurred: '" + std::string(what) + "'";
151         res.prepare_payload();
152         return res;
153     };
154
155     // Make sure we can handle the method
156     if( req.method() != http::verb::get &&
157         req.method() != http::verb::head)
158         return send(bad_request("Unknown HTTP-method"));
159
160     // Request path must be absolute and not contain "..".
161     if( req.target().empty() ||
162         req.target()[0] != '/' ||
163         req.target().find("..") != beast::string_view::npos)
164         return send(bad_request("Illegal request-target"));
165
166     // Build the path to the requested file
167     std::string path = path_cat(doc_root, req.target());
168     if(req.target().back() == '/')
169         path.append("index.html");
170
171     // Attempt to open the file
172     beast::error_code ec;
173     http::file_body::value_type body;
174     body.open(path.c_str(), beast::file_mode::scan, ec);
175
176     // Handle the case where the file doesn't exist
177     if(ec == beast::errc::no_such_file_or_directory)
178         return send(not_found(req.target()));
179
180     // Handle an unknown error
181     if(ec)
182         return send(server_error(ec.message()));
183
184     // Cache the size since we need it after the move
185     auto const size = body.size();
186
187     // Respond to HEAD request
188     if(req.method() == http::verb::head)
189     {
190         http::response<http::empty_body> res{http::status::ok, req.version()};
191         res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
192         res.set(http::field::content_type, mime_type(path));
193         res.content_length(size);
194         res.keep_alive(req.keep_alive());
195         return send(std::move(res));
196     }
197
198     // Respond to GET request
199     http::response<http::file_body> res{
200         std::piecewise_construct,
201         std::make_tuple(std::move(body)),
202         std::make_tuple(http::status::ok, req.version())};
203     res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
204     res.set(http::field::content_type, mime_type(path));
205     res.content_length(size);
206     res.keep_alive(req.keep_alive());
207     return send(std::move(res));
208 }
209
210 //------------------------------------------------------------------------------
211
212 // Report a failure
213 void
214 fail(beast::error_code ec, char const* what)
215 {
216     // ssl::error::stream_truncated, also known as an SSL "short read",
217     // indicates the peer closed the connection without performing the
218     // required closing handshake (for example, Google does this to
219     // improve performance). Generally this can be a security issue,
220     // but if your communication protocol is self-terminated (as
221     // it is with both HTTP and WebSocket) then you may simply
222     // ignore the lack of close_notify.
223     //
224     // https://github.com/boostorg/beast/issues/38
225     //
226     // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
227     //
228     // When a short read would cut off the end of an HTTP message,
229     // Beast returns the error beast::http::error::partial_message.
230     // Therefore, if we see a short read here, it has occurred
231     // after the message has been completed, so it is safe to ignore it.
232
233     if(ec == net::ssl::error::stream_truncated)
234         return;
235
236     std::cerr << what << ": " << ec.message() << "\n";
237 }
238
239 // Handles an HTTP server connection
240 class session : public std::enable_shared_from_this<session>
241 {
242     // This is the C++11 equivalent of a generic lambda.
243     // The function object is used to send an HTTP message.
244     struct send_lambda
245     {
246         session& self_;
247
248         explicit
249         send_lambda(session& self)
250             : self_(self)
251         {
252         }
253
254         template<bool isRequest, class Body, class Fields>
255         void
256         operator()(http::message<isRequest, Body, Fields>&& msg) const
257         {
258             // The lifetime of the message has to extend
259             // for the duration of the async operation so
260             // we use a shared_ptr to manage it.
261             auto sp = std::make_shared<
262                 http::message<isRequest, Body, Fields>>(std::move(msg));
263
264             // Store a type-erased version of the shared
265             // pointer in the class to keep it alive.
266             self_.res_ = sp;
267
268             // Write the response
269             http::async_write(
270                 self_.stream_,
271                 *sp,
272                 beast::bind_front_handler(
273                     &session::on_write,
274                     self_.shared_from_this(),
275                     sp->need_eof()));
276         }
277     };
278
279     beast::ssl_stream<beast::tcp_stream> stream_;
280     beast::flat_buffer buffer_;
281     std::shared_ptr<std::string const> doc_root_;
282     http::request<http::string_body> req_;
283     std::shared_ptr<void> res_;
284     send_lambda lambda_;
285
286 public:
287     // Take ownership of the socket
288     explicit
289     session(
290         tcp::socket&& socket,
291         ssl::context& ctx,
292         std::shared_ptr<std::string const> const& doc_root)
293         : stream_(std::move(socket), ctx)
294         , doc_root_(doc_root)
295         , lambda_(*this)
296     {
297     }
298
299     // Start the asynchronous operation
300     void
301     run()
302     {
303         // We need to be executing within a strand to perform async operations
304         // on the I/O objects in this session. Although not strictly necessary
305         // for single-threaded contexts, this example code is written to be
306         // thread-safe by default.
307         net::dispatch(
308             stream_.get_executor(),
309             beast::bind_front_handler(
310                 &session::on_run,
311                 shared_from_this()));
312     }
313
314     void
315     on_run()
316     {
317         // Set the timeout.
318         beast::get_lowest_layer(stream_).expires_after(
319             std::chrono::seconds(30));
320
321         // Perform the SSL handshake
322         stream_.async_handshake(
323             ssl::stream_base::server,
324             beast::bind_front_handler(
325                 &session::on_handshake,
326                 shared_from_this()));
327     }
328
329     void
330     on_handshake(beast::error_code ec)
331     {
332         if(ec)
333             return fail(ec, "handshake");
334
335         do_read();
336     }
337
338     void
339     do_read()
340     {
341         // Make the request empty before reading,
342         // otherwise the operation behavior is undefined.
343         req_ = {};
344
345         // Set the timeout.
346         beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
347
348         // Read a request
349         http::async_read(stream_, buffer_, req_,
350             beast::bind_front_handler(
351                 &session::on_read,
352                 shared_from_this()));
353     }
354
355     void
356     on_read(
357         beast::error_code ec,
358         std::size_t bytes_transferred)
359     {
360         boost::ignore_unused(bytes_transferred);
361
362         // This means they closed the connection
363         if(ec == http::error::end_of_stream)
364             return do_close();
365
366         if(ec)
367             return fail(ec, "read");
368
369         // Send the response
370         handle_request(*doc_root_, std::move(req_), lambda_);
371     }
372
373     void
374     on_write(
375         bool close,
376         beast::error_code ec,
377         std::size_t bytes_transferred)
378     {
379         boost::ignore_unused(bytes_transferred);
380
381         if(ec)
382             return fail(ec, "write");
383
384         if(close)
385         {
386             // This means we should close the connection, usually because
387             // the response indicated the "Connection: close" semantic.
388             return do_close();
389         }
390
391         // We're done with the response so delete it
392         res_ = nullptr;
393
394         // Read another request
395         do_read();
396     }
397
398     void
399     do_close()
400     {
401         // Set the timeout.
402         beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
403
404         // Perform the SSL shutdown
405         stream_.async_shutdown(
406             beast::bind_front_handler(
407                 &session::on_shutdown,
408                 shared_from_this()));
409     }
410
411     void
412     on_shutdown(beast::error_code ec)
413     {
414         if(ec)
415             return fail(ec, "shutdown");
416
417         // At this point the connection is closed gracefully
418     }
419 };
420
421 //------------------------------------------------------------------------------
422
423 // Accepts incoming connections and launches the sessions
424 class listener : public std::enable_shared_from_this<listener>
425 {
426     net::io_context& ioc_;
427     ssl::context& ctx_;
428     tcp::acceptor acceptor_;
429     std::shared_ptr<std::string const> doc_root_;
430
431 public:
432     listener(
433         net::io_context& ioc,
434         ssl::context& ctx,
435         tcp::endpoint endpoint,
436         std::shared_ptr<std::string const> const& doc_root)
437         : ioc_(ioc)
438         , ctx_(ctx)
439         , acceptor_(ioc)
440         , doc_root_(doc_root)
441     {
442         beast::error_code ec;
443
444         // Open the acceptor
445         acceptor_.open(endpoint.protocol(), ec);
446         if(ec)
447         {
448             fail(ec, "open");
449             return;
450         }
451
452         // Allow address reuse
453         acceptor_.set_option(net::socket_base::reuse_address(true), ec);
454         if(ec)
455         {
456             fail(ec, "set_option");
457             return;
458         }
459
460         // Bind to the server address
461         acceptor_.bind(endpoint, ec);
462         if(ec)
463         {
464             fail(ec, "bind");
465             return;
466         }
467
468         // Start listening for connections
469         acceptor_.listen(
470             net::socket_base::max_listen_connections, ec);
471         if(ec)
472         {
473             fail(ec, "listen");
474             return;
475         }
476     }
477
478     // Start accepting incoming connections
479     void
480     run()
481     {
482         do_accept();
483     }
484
485 private:
486     void
487     do_accept()
488     {
489         // The new connection gets its own strand
490         acceptor_.async_accept(
491             net::make_strand(ioc_),
492             beast::bind_front_handler(
493                 &listener::on_accept,
494                 shared_from_this()));
495     }
496
497     void
498     on_accept(beast::error_code ec, tcp::socket socket)
499     {
500         if(ec)
501         {
502             fail(ec, "accept");
503         }
504         else
505         {
506             // Create the session and run it
507             std::make_shared<session>(
508                 std::move(socket),
509                 ctx_,
510                 doc_root_)->run();
511         }
512
513         // Accept another connection
514         do_accept();
515     }
516 };
517
518 //------------------------------------------------------------------------------
519
520 int main(int argc, char* argv[])
521 {
522     // Check command line arguments.
523     if (argc != 5)
524     {
525         std::cerr <<
526             "Usage: http-server-async-ssl <address> <port> <doc_root> <threads>\n" <<
527             "Example:\n" <<
528             "    http-server-async-ssl 0.0.0.0 8080 . 1\n";
529         return EXIT_FAILURE;
530     }
531     auto const address = net::ip::make_address(argv[1]);
532     auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
533     auto const doc_root = std::make_shared<std::string>(argv[3]);
534     auto const threads = std::max<int>(1, std::atoi(argv[4]));
535
536     // The io_context is required for all I/O
537     net::io_context ioc{threads};
538
539     // The SSL context is required, and holds certificates
540     ssl::context ctx{ssl::context::tlsv12};
541
542     // This holds the self-signed certificate used by the server
543     load_server_certificate(ctx);
544
545     // Create and launch a listening port
546     std::make_shared<listener>(
547         ioc,
548         ctx,
549         tcp::endpoint{address, port},
550         doc_root)->run();
551
552     // Run the I/O service on the requested number of threads
553     std::vector<std::thread> v;
554     v.reserve(threads - 1);
555     for(auto i = threads - 1; i > 0; --i)
556         v.emplace_back(
557         [&ioc]
558         {
559             ioc.run();
560         });
561     ioc.run();
562
563     return EXIT_SUCCESS;
564 }