• 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, synchronous
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/ip/tcp.hpp>
23 #include <boost/asio/ssl/stream.hpp>
24 #include <boost/config.hpp>
25 #include <cstdlib>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <thread>
30 
31 namespace beast = boost::beast;         // from <boost/beast.hpp>
32 namespace http = beast::http;           // from <boost/beast/http.hpp>
33 namespace net = boost::asio;            // from <boost/asio.hpp>
34 namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
35 using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
36 
37 // Return a reasonable mime type based on the extension of a file.
38 beast::string_view
mime_type(beast::string_view path)39 mime_type(beast::string_view path)
40 {
41     using beast::iequals;
42     auto const ext = [&path]
43     {
44         auto const pos = path.rfind(".");
45         if(pos == beast::string_view::npos)
46             return beast::string_view{};
47         return path.substr(pos);
48     }();
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";
71 }
72 
73 // Append an HTTP rel-path to a local filesystem path.
74 // The returned path is normalized for the platform.
75 std::string
path_cat(beast::string_view base,beast::string_view path)76 path_cat(
77     beast::string_view base,
78     beast::string_view path)
79 {
80     if(base.empty())
81         return std::string(path);
82     std::string result(base);
83 #ifdef BOOST_MSVC
84     char constexpr path_separator = '\\';
85     if(result.back() == path_separator)
86         result.resize(result.size() - 1);
87     result.append(path.data(), path.size());
88     for(auto& c : result)
89         if(c == '/')
90             c = path_separator;
91 #else
92     char constexpr path_separator = '/';
93     if(result.back() == path_separator)
94         result.resize(result.size() - 1);
95     result.append(path.data(), path.size());
96 #endif
97     return result;
98 }
99 
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.
104 template<
105     class Body, class Allocator,
106     class Send>
107 void
handle_request(beast::string_view doc_root,http::request<Body,http::basic_fields<Allocator>> && req,Send && send)108 handle_request(
109     beast::string_view doc_root,
110     http::request<Body, http::basic_fields<Allocator>>&& req,
111     Send&& send)
112 {
113     // Returns a bad request response
114     auto const bad_request =
115     [&req](beast::string_view why)
116     {
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();
123         return res;
124     };
125 
126     // Returns a not found response
127     auto const not_found =
128     [&req](beast::string_view target)
129     {
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();
136         return res;
137     };
138 
139     // Returns a server error response
140     auto const server_error =
141     [&req](beast::string_view what)
142     {
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();
149         return res;
150     };
151 
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"));
156 
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"));
162 
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");
167 
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);
172 
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()));
176 
177     // Handle an unknown error
178     if(ec)
179         return send(server_error(ec.message()));
180 
181     // Cache the size since we need it after the move
182     auto const size = body.size();
183 
184     // Respond to HEAD request
185     if(req.method() == http::verb::head)
186     {
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));
193     }
194 
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));
205 }
206 
207 //------------------------------------------------------------------------------
208 
209 // Report a failure
210 void
fail(beast::error_code ec,char const * what)211 fail(beast::error_code ec, char const* what)
212 {
213     std::cerr << what << ": " << ec.message() << "\n";
214 }
215 
216 // This is the C++11 equivalent of a generic lambda.
217 // The function object is used to send an HTTP message.
218 template<class Stream>
219 struct send_lambda
220 {
221     Stream& stream_;
222     bool& close_;
223     beast::error_code& ec_;
224 
225     explicit
send_lambdasend_lambda226     send_lambda(
227         Stream& stream,
228         bool& close,
229         beast::error_code& ec)
230         : stream_(stream)
231         , close_(close)
232         , ec_(ec)
233     {
234     }
235 
236     template<bool isRequest, class Body, class Fields>
237     void
operator ()send_lambda238     operator()(http::message<isRequest, Body, Fields>&& msg) const
239     {
240         // Determine if we should close the connection after
241         close_ = msg.need_eof();
242 
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::write(stream_, sr, ec_);
248     }
249 };
250 
251 // Handles an HTTP server connection
252 void
do_session(tcp::socket & socket,ssl::context & ctx,std::shared_ptr<std::string const> const & doc_root)253 do_session(
254     tcp::socket& socket,
255     ssl::context& ctx,
256     std::shared_ptr<std::string const> const& doc_root)
257 {
258     bool close = false;
259     beast::error_code ec;
260 
261     // Construct the stream around the socket
262     beast::ssl_stream<tcp::socket&> stream{socket, ctx};
263 
264     // Perform the SSL handshake
265     stream.handshake(ssl::stream_base::server, ec);
266     if(ec)
267         return fail(ec, "handshake");
268 
269     // This buffer is required to persist across reads
270     beast::flat_buffer buffer;
271 
272     // This lambda is used to send messages
273     send_lambda<beast::ssl_stream<tcp::socket&>> lambda{stream, close, ec};
274 
275     for(;;)
276     {
277         // Read a request
278         http::request<http::string_body> req;
279         http::read(stream, buffer, req, ec);
280         if(ec == http::error::end_of_stream)
281             break;
282         if(ec)
283             return fail(ec, "read");
284 
285         // Send the response
286         handle_request(*doc_root, std::move(req), lambda);
287         if(ec)
288             return fail(ec, "write");
289         if(close)
290         {
291             // This means we should close the connection, usually because
292             // the response indicated the "Connection: close" semantic.
293             break;
294         }
295     }
296 
297     // Perform the SSL shutdown
298     stream.shutdown(ec);
299     if(ec)
300         return fail(ec, "shutdown");
301 
302     // At this point the connection is closed gracefully
303 }
304 
305 //------------------------------------------------------------------------------
306 
main(int argc,char * argv[])307 int main(int argc, char* argv[])
308 {
309     try
310     {
311         // Check command line arguments.
312         if (argc != 4)
313         {
314             std::cerr <<
315                 "Usage: http-server-sync-ssl <address> <port> <doc_root>\n" <<
316                 "Example:\n" <<
317                 "    http-server-sync-ssl 0.0.0.0 8080 .\n";
318             return EXIT_FAILURE;
319         }
320         auto const address = net::ip::make_address(argv[1]);
321         auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
322         auto const doc_root = std::make_shared<std::string>(argv[3]);
323 
324         // The io_context is required for all I/O
325         net::io_context ioc{1};
326 
327         // The SSL context is required, and holds certificates
328         ssl::context ctx{ssl::context::tlsv12};
329 
330         // This holds the self-signed certificate used by the server
331         load_server_certificate(ctx);
332 
333         // The acceptor receives incoming connections
334         tcp::acceptor acceptor{ioc, {address, port}};
335         for(;;)
336         {
337             // This will receive the new connection
338             tcp::socket socket{ioc};
339 
340             // Block until we get a connection
341             acceptor.accept(socket);
342 
343             // Launch the session, transferring ownership of the socket
344             std::thread{std::bind(
345                 &do_session,
346                 std::move(socket),
347                 std::ref(ctx),
348                 doc_root)}.detach();
349         }
350     }
351     catch (const std::exception& e)
352     {
353         std::cerr << "Error: " << e.what() << std::endl;
354         return EXIT_FAILURE;
355     }
356 }
357