]> git.proxmox.com Git - ceph.git/blame - ceph/src/boost/libs/beast/example/http/server/async-ssl/http_server_async_ssl.cpp
update ceph source to reef 18.1.2
[ceph.git] / ceph / src / boost / libs / beast / example / http / server / async-ssl / http_server_async_ssl.cpp
CommitLineData
b32b8144 1//
92f5a8d4 2// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
b32b8144
FG
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>
92f5a8d4 20#include <boost/beast/ssl.hpp>
b32b8144 21#include <boost/beast/version.hpp>
92f5a8d4 22#include <boost/asio/dispatch.hpp>
b32b8144
FG
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
92f5a8d4
TL
34namespace beast = boost::beast; // from <boost/beast.hpp>
35namespace http = beast::http; // from <boost/beast/http.hpp>
36namespace net = boost::asio; // from <boost/asio.hpp>
b32b8144 37namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
92f5a8d4 38using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
b32b8144
FG
39
40// Return a reasonable mime type based on the extension of a file.
92f5a8d4
TL
41beast::string_view
42mime_type(beast::string_view path)
b32b8144 43{
92f5a8d4 44 using beast::iequals;
b32b8144
FG
45 auto const ext = [&path]
46 {
47 auto const pos = path.rfind(".");
92f5a8d4
TL
48 if(pos == beast::string_view::npos)
49 return beast::string_view{};
b32b8144
FG
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.
78std::string
79path_cat(
92f5a8d4
TL
80 beast::string_view base,
81 beast::string_view path)
b32b8144
FG
82{
83 if(base.empty())
92f5a8d4
TL
84 return std::string(path);
85 std::string result(base);
86#ifdef BOOST_MSVC
b32b8144
FG
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.
107template<
108 class Body, class Allocator,
109 class Send>
110void
111handle_request(
92f5a8d4 112 beast::string_view doc_root,
b32b8144
FG
113 http::request<Body, http::basic_fields<Allocator>>&& req,
114 Send&& send)
115{
116 // Returns a bad request response
117 auto const bad_request =
92f5a8d4 118 [&req](beast::string_view why)
b32b8144
FG
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());
92f5a8d4 124 res.body() = std::string(why);
b32b8144
FG
125 res.prepare_payload();
126 return res;
127 };
128
129 // Returns a not found response
130 auto const not_found =
92f5a8d4 131 [&req](beast::string_view target)
b32b8144
FG
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());
92f5a8d4 137 res.body() = "The resource '" + std::string(target) + "' was not found.";
b32b8144
FG
138 res.prepare_payload();
139 return res;
140 };
141
142 // Returns a server error response
143 auto const server_error =
92f5a8d4 144 [&req](beast::string_view what)
b32b8144
FG
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());
92f5a8d4 150 res.body() = "An error occurred: '" + std::string(what) + "'";
b32b8144
FG
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] != '/' ||
92f5a8d4 163 req.target().find("..") != beast::string_view::npos)
b32b8144
FG
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
92f5a8d4 172 beast::error_code ec;
b32b8144 173 http::file_body::value_type body;
92f5a8d4 174 body.open(path.c_str(), beast::file_mode::scan, ec);
b32b8144
FG
175
176 // Handle the case where the file doesn't exist
92f5a8d4 177 if(ec == beast::errc::no_such_file_or_directory)
b32b8144
FG
178 return send(not_found(req.target()));
179
180 // Handle an unknown error
181 if(ec)
182 return send(server_error(ec.message()));
183
11fdf7f2
TL
184 // Cache the size since we need it after the move
185 auto const size = body.size();
186
b32b8144
FG
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));
11fdf7f2 193 res.content_length(size);
b32b8144
FG
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));
11fdf7f2 205 res.content_length(size);
b32b8144
FG
206 res.keep_alive(req.keep_alive());
207 return send(std::move(res));
208}
209
210//------------------------------------------------------------------------------
211
212// Report a failure
213void
92f5a8d4 214fail(beast::error_code ec, char const* what)
b32b8144 215{
92f5a8d4
TL
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
b32b8144
FG
236 std::cerr << what << ": " << ec.message() << "\n";
237}
238
239// Handles an HTTP server connection
240class 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,
92f5a8d4
TL
272 beast::bind_front_handler(
273 &session::on_write,
274 self_.shared_from_this(),
275 sp->need_eof()));
b32b8144
FG
276 }
277 };
278
92f5a8d4
TL
279 beast::ssl_stream<beast::tcp_stream> stream_;
280 beast::flat_buffer buffer_;
281 std::shared_ptr<std::string const> doc_root_;
b32b8144
FG
282 http::request<http::string_body> req_;
283 std::shared_ptr<void> res_;
284 send_lambda lambda_;
285
286public:
287 // Take ownership of the socket
288 explicit
289 session(
92f5a8d4 290 tcp::socket&& socket,
b32b8144 291 ssl::context& ctx,
92f5a8d4
TL
292 std::shared_ptr<std::string const> const& doc_root)
293 : stream_(std::move(socket), ctx)
b32b8144
FG
294 , doc_root_(doc_root)
295 , lambda_(*this)
296 {
297 }
298
299 // Start the asynchronous operation
300 void
301 run()
302 {
92f5a8d4
TL
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
b32b8144
FG
321 // Perform the SSL handshake
322 stream_.async_handshake(
323 ssl::stream_base::server,
92f5a8d4
TL
324 beast::bind_front_handler(
325 &session::on_handshake,
326 shared_from_this()));
b32b8144
FG
327 }
328
329 void
92f5a8d4 330 on_handshake(beast::error_code ec)
b32b8144
FG
331 {
332 if(ec)
333 return fail(ec, "handshake");
334
335 do_read();
336 }
337
338 void
339 do_read()
340 {
11fdf7f2
TL
341 // Make the request empty before reading,
342 // otherwise the operation behavior is undefined.
343 req_ = {};
344
92f5a8d4
TL
345 // Set the timeout.
346 beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
347
b32b8144
FG
348 // Read a request
349 http::async_read(stream_, buffer_, req_,
92f5a8d4
TL
350 beast::bind_front_handler(
351 &session::on_read,
352 shared_from_this()));
b32b8144
FG
353 }
354
355 void
356 on_read(
92f5a8d4 357 beast::error_code ec,
b32b8144
FG
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
92f5a8d4 370 handle_request(*doc_root_, std::move(req_), lambda_);
b32b8144
FG
371 }
372
373 void
374 on_write(
92f5a8d4
TL
375 bool close,
376 beast::error_code ec,
377 std::size_t bytes_transferred)
b32b8144
FG
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 {
92f5a8d4
TL
401 // Set the timeout.
402 beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
403
b32b8144
FG
404 // Perform the SSL shutdown
405 stream_.async_shutdown(
92f5a8d4
TL
406 beast::bind_front_handler(
407 &session::on_shutdown,
408 shared_from_this()));
b32b8144
FG
409 }
410
411 void
92f5a8d4 412 on_shutdown(beast::error_code ec)
b32b8144
FG
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
424class listener : public std::enable_shared_from_this<listener>
425{
92f5a8d4 426 net::io_context& ioc_;
b32b8144
FG
427 ssl::context& ctx_;
428 tcp::acceptor acceptor_;
92f5a8d4 429 std::shared_ptr<std::string const> doc_root_;
b32b8144
FG
430
431public:
432 listener(
92f5a8d4 433 net::io_context& ioc,
b32b8144
FG
434 ssl::context& ctx,
435 tcp::endpoint endpoint,
92f5a8d4
TL
436 std::shared_ptr<std::string const> const& doc_root)
437 : ioc_(ioc)
438 , ctx_(ctx)
b32b8144 439 , acceptor_(ioc)
b32b8144
FG
440 , doc_root_(doc_root)
441 {
92f5a8d4 442 beast::error_code ec;
b32b8144
FG
443
444 // Open the acceptor
445 acceptor_.open(endpoint.protocol(), ec);
446 if(ec)
447 {
448 fail(ec, "open");
449 return;
450 }
451
11fdf7f2 452 // Allow address reuse
92f5a8d4 453 acceptor_.set_option(net::socket_base::reuse_address(true), ec);
11fdf7f2
TL
454 if(ec)
455 {
456 fail(ec, "set_option");
457 return;
458 }
459
b32b8144
FG
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(
92f5a8d4 470 net::socket_base::max_listen_connections, ec);
b32b8144
FG
471 if(ec)
472 {
473 fail(ec, "listen");
474 return;
475 }
476 }
477
478 // Start accepting incoming connections
479 void
480 run()
481 {
b32b8144
FG
482 do_accept();
483 }
484
92f5a8d4 485private:
b32b8144
FG
486 void
487 do_accept()
488 {
92f5a8d4 489 // The new connection gets its own strand
b32b8144 490 acceptor_.async_accept(
92f5a8d4
TL
491 net::make_strand(ioc_),
492 beast::bind_front_handler(
b32b8144 493 &listener::on_accept,
92f5a8d4 494 shared_from_this()));
b32b8144
FG
495 }
496
497 void
92f5a8d4 498 on_accept(beast::error_code ec, tcp::socket socket)
b32b8144
FG
499 {
500 if(ec)
501 {
502 fail(ec, "accept");
1e59de90 503 return; // To avoid infinite loop
b32b8144
FG
504 }
505 else
506 {
507 // Create the session and run it
508 std::make_shared<session>(
92f5a8d4 509 std::move(socket),
b32b8144
FG
510 ctx_,
511 doc_root_)->run();
512 }
513
514 // Accept another connection
515 do_accept();
516 }
517};
518
519//------------------------------------------------------------------------------
520
521int main(int argc, char* argv[])
522{
523 // Check command line arguments.
524 if (argc != 5)
525 {
526 std::cerr <<
527 "Usage: http-server-async-ssl <address> <port> <doc_root> <threads>\n" <<
528 "Example:\n" <<
529 " http-server-async-ssl 0.0.0.0 8080 . 1\n";
530 return EXIT_FAILURE;
531 }
92f5a8d4 532 auto const address = net::ip::make_address(argv[1]);
b32b8144 533 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
92f5a8d4 534 auto const doc_root = std::make_shared<std::string>(argv[3]);
b32b8144
FG
535 auto const threads = std::max<int>(1, std::atoi(argv[4]));
536
537 // The io_context is required for all I/O
92f5a8d4 538 net::io_context ioc{threads};
b32b8144
FG
539
540 // The SSL context is required, and holds certificates
92f5a8d4 541 ssl::context ctx{ssl::context::tlsv12};
b32b8144
FG
542
543 // This holds the self-signed certificate used by the server
544 load_server_certificate(ctx);
545
546 // Create and launch a listening port
547 std::make_shared<listener>(
548 ioc,
549 ctx,
550 tcp::endpoint{address, port},
551 doc_root)->run();
552
553 // Run the I/O service on the requested number of threads
554 std::vector<std::thread> v;
555 v.reserve(threads - 1);
556 for(auto i = threads - 1; i > 0; --i)
557 v.emplace_back(
558 [&ioc]
559 {
560 ioc.run();
561 });
562 ioc.run();
563
564 return EXIT_SUCCESS;
565}