]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/beast/example/http/server/coro-ssl/http_server_coro_ssl.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / beast / example / http / server / coro-ssl / http_server_coro_ssl.cpp
1 //
2 // Copyright (c) 2016-2017 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/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>
25 #include <algorithm>
26 #include <cstdlib>
27 #include <iostream>
28 #include <memory>
29 #include <string>
30 #include <thread>
31 #include <vector>
32
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>
36
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)
40 {
41 using boost::beast::iequals;
42 auto const ext = [&path]
43 {
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);
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
76 path_cat(
77 boost::beast::string_view base,
78 boost::beast::string_view path)
79 {
80 if(base.empty())
81 return path.to_string();
82 std::string result = base.to_string();
83 #if 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
108 handle_request(
109 boost::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](boost::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() = why.to_string();
122 res.prepare_payload();
123 return res;
124 };
125
126 // Returns a not found response
127 auto const not_found =
128 [&req](boost::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 '" + target.to_string() + "' 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](boost::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: '" + what.to_string() + "'";
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("..") != boost::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 boost::beast::error_code ec;
170 http::file_body::value_type body;
171 body.open(path.c_str(), boost::beast::file_mode::scan, ec);
172
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()));
176
177 // Handle an unknown error
178 if(ec)
179 return send(server_error(ec.message()));
180
181 // Respond to HEAD request
182 if(req.method() == http::verb::head)
183 {
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));
190 }
191
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));
202 }
203
204 //------------------------------------------------------------------------------
205
206 // Report a failure
207 void
208 fail(boost::system::error_code ec, char const* what)
209 {
210 std::cerr << what << ": " << ec.message() << "\n";
211 }
212
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>
216 struct send_lambda
217 {
218 Stream& stream_;
219 bool& close_;
220 boost::system::error_code& ec_;
221 boost::asio::yield_context yield_;
222
223 explicit
224 send_lambda(
225 Stream& stream,
226 bool& close,
227 boost::system::error_code& ec,
228 boost::asio::yield_context yield)
229 : stream_(stream)
230 , close_(close)
231 , ec_(ec)
232 , yield_(yield)
233 {
234 }
235
236 template<bool isRequest, class Body, class Fields>
237 void
238 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::async_write(stream_, sr, yield_[ec_]);
248 }
249 };
250
251 // Handles an HTTP server connection
252 void
253 do_session(
254 tcp::socket& socket,
255 ssl::context& ctx,
256 std::string const& doc_root,
257 boost::asio::yield_context yield)
258 {
259 bool close = false;
260 boost::system::error_code ec;
261
262 // Construct the stream around the socket
263 ssl::stream<tcp::socket&> stream{socket, ctx};
264
265 // Perform the SSL handshake
266 stream.async_handshake(ssl::stream_base::server, yield[ec]);
267 if(ec)
268 return fail(ec, "handshake");
269
270 // This buffer is required to persist across reads
271 boost::beast::flat_buffer buffer;
272
273 // This lambda is used to send messages
274 send_lambda<ssl::stream<tcp::socket&>> lambda{stream, close, ec, yield};
275
276 for(;;)
277 {
278 // Read a request
279 http::request<http::string_body> req;
280 http::async_read(stream, buffer, req, yield[ec]);
281 if(ec == http::error::end_of_stream)
282 break;
283 if(ec)
284 return fail(ec, "read");
285
286 // Send the response
287 handle_request(doc_root, std::move(req), lambda);
288 if(ec)
289 return fail(ec, "write");
290 if(close)
291 {
292 // This means we should close the connection, usually because
293 // the response indicated the "Connection: close" semantic.
294 break;
295 }
296 }
297
298 // Perform the SSL shutdown
299 stream.async_shutdown(yield[ec]);
300 if(ec)
301 return fail(ec, "shutdown");
302
303 // At this point the connection is closed gracefully
304 }
305
306 //------------------------------------------------------------------------------
307
308 // Accepts incoming connections and launches the sessions
309 void
310 do_listen(
311 boost::asio::io_context& ioc,
312 ssl::context& ctx,
313 tcp::endpoint endpoint,
314 std::string const& doc_root,
315 boost::asio::yield_context yield)
316 {
317 boost::system::error_code ec;
318
319 // Open the acceptor
320 tcp::acceptor acceptor(ioc);
321 acceptor.open(endpoint.protocol(), ec);
322 if(ec)
323 return fail(ec, "open");
324
325 // Bind to the server address
326 acceptor.bind(endpoint, ec);
327 if(ec)
328 return fail(ec, "bind");
329
330 // Start listening for connections
331 acceptor.listen(boost::asio::socket_base::max_listen_connections, ec);
332 if(ec)
333 return fail(ec, "listen");
334
335 for(;;)
336 {
337 tcp::socket socket(ioc);
338 acceptor.async_accept(socket, yield[ec]);
339 if(ec)
340 fail(ec, "accept");
341 else
342 boost::asio::spawn(
343 acceptor.get_executor().context(),
344 std::bind(
345 &do_session,
346 std::move(socket),
347 std::ref(ctx),
348 doc_root,
349 std::placeholders::_1));
350 }
351 }
352
353 int main(int argc, char* argv[])
354 {
355 // Check command line arguments.
356 if (argc != 5)
357 {
358 std::cerr <<
359 "Usage: http-server-coro-ssl <address> <port> <doc_root> <threads>\n" <<
360 "Example:\n" <<
361 " http-server-coro-ssl 0.0.0.0 8080 . 1\n";
362 return EXIT_FAILURE;
363 }
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]));
368
369 // The io_context is required for all I/O
370 boost::asio::io_context ioc{threads};
371
372 // The SSL context is required, and holds certificates
373 ssl::context ctx{ssl::context::sslv23};
374
375 // This holds the self-signed certificate used by the server
376 load_server_certificate(ctx);
377
378 // Spawn a listening port
379 boost::asio::spawn(ioc,
380 std::bind(
381 &do_listen,
382 std::ref(ioc),
383 std::ref(ctx),
384 tcp::endpoint{address, port},
385 doc_root,
386 std::placeholders::_1));
387
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)
392 v.emplace_back(
393 [&ioc]
394 {
395 ioc.run();
396 });
397 ioc.run();
398
399 return EXIT_SUCCESS;
400 }