]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/beast/example/http/server/async/http_server_async.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / beast / example / http / server / async / http_server_async.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 server, asynchronous
13 //
14 //------------------------------------------------------------------------------
15
16 #include <boost/beast/core.hpp>
17 #include <boost/beast/http.hpp>
18 #include <boost/beast/version.hpp>
19 #include <boost/asio/bind_executor.hpp>
20 #include <boost/asio/ip/tcp.hpp>
21 #include <boost/asio/strand.hpp>
22 #include <boost/config.hpp>
23 #include <algorithm>
24 #include <cstdlib>
25 #include <functional>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <thread>
30 #include <vector>
31
32 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
33 namespace http = boost::beast::http; // from <boost/beast/http.hpp>
34
35 // Return a reasonable mime type based on the extension of a file.
36 boost::beast::string_view
37 mime_type(boost::beast::string_view path)
38 {
39 using boost::beast::iequals;
40 auto const ext = [&path]
41 {
42 auto const pos = path.rfind(".");
43 if(pos == boost::beast::string_view::npos)
44 return boost::beast::string_view{};
45 return path.substr(pos);
46 }();
47 if(iequals(ext, ".htm")) return "text/html";
48 if(iequals(ext, ".html")) return "text/html";
49 if(iequals(ext, ".php")) return "text/html";
50 if(iequals(ext, ".css")) return "text/css";
51 if(iequals(ext, ".txt")) return "text/plain";
52 if(iequals(ext, ".js")) return "application/javascript";
53 if(iequals(ext, ".json")) return "application/json";
54 if(iequals(ext, ".xml")) return "application/xml";
55 if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
56 if(iequals(ext, ".flv")) return "video/x-flv";
57 if(iequals(ext, ".png")) return "image/png";
58 if(iequals(ext, ".jpe")) return "image/jpeg";
59 if(iequals(ext, ".jpeg")) return "image/jpeg";
60 if(iequals(ext, ".jpg")) return "image/jpeg";
61 if(iequals(ext, ".gif")) return "image/gif";
62 if(iequals(ext, ".bmp")) return "image/bmp";
63 if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
64 if(iequals(ext, ".tiff")) return "image/tiff";
65 if(iequals(ext, ".tif")) return "image/tiff";
66 if(iequals(ext, ".svg")) return "image/svg+xml";
67 if(iequals(ext, ".svgz")) return "image/svg+xml";
68 return "application/text";
69 }
70
71 // Append an HTTP rel-path to a local filesystem path.
72 // The returned path is normalized for the platform.
73 std::string
74 path_cat(
75 boost::beast::string_view base,
76 boost::beast::string_view path)
77 {
78 if(base.empty())
79 return path.to_string();
80 std::string result = base.to_string();
81 #if BOOST_MSVC
82 char constexpr path_separator = '\\';
83 if(result.back() == path_separator)
84 result.resize(result.size() - 1);
85 result.append(path.data(), path.size());
86 for(auto& c : result)
87 if(c == '/')
88 c = path_separator;
89 #else
90 char constexpr path_separator = '/';
91 if(result.back() == path_separator)
92 result.resize(result.size() - 1);
93 result.append(path.data(), path.size());
94 #endif
95 return result;
96 }
97
98 // This function produces an HTTP response for the given
99 // request. The type of the response object depends on the
100 // contents of the request, so the interface requires the
101 // caller to pass a generic lambda for receiving the response.
102 template<
103 class Body, class Allocator,
104 class Send>
105 void
106 handle_request(
107 boost::beast::string_view doc_root,
108 http::request<Body, http::basic_fields<Allocator>>&& req,
109 Send&& send)
110 {
111 // Returns a bad request response
112 auto const bad_request =
113 [&req](boost::beast::string_view why)
114 {
115 http::response<http::string_body> res{http::status::bad_request, req.version()};
116 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
117 res.set(http::field::content_type, "text/html");
118 res.keep_alive(req.keep_alive());
119 res.body() = why.to_string();
120 res.prepare_payload();
121 return res;
122 };
123
124 // Returns a not found response
125 auto const not_found =
126 [&req](boost::beast::string_view target)
127 {
128 http::response<http::string_body> res{http::status::not_found, req.version()};
129 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
130 res.set(http::field::content_type, "text/html");
131 res.keep_alive(req.keep_alive());
132 res.body() = "The resource '" + target.to_string() + "' was not found.";
133 res.prepare_payload();
134 return res;
135 };
136
137 // Returns a server error response
138 auto const server_error =
139 [&req](boost::beast::string_view what)
140 {
141 http::response<http::string_body> res{http::status::internal_server_error, req.version()};
142 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
143 res.set(http::field::content_type, "text/html");
144 res.keep_alive(req.keep_alive());
145 res.body() = "An error occurred: '" + what.to_string() + "'";
146 res.prepare_payload();
147 return res;
148 };
149
150 // Make sure we can handle the method
151 if( req.method() != http::verb::get &&
152 req.method() != http::verb::head)
153 return send(bad_request("Unknown HTTP-method"));
154
155 // Request path must be absolute and not contain "..".
156 if( req.target().empty() ||
157 req.target()[0] != '/' ||
158 req.target().find("..") != boost::beast::string_view::npos)
159 return send(bad_request("Illegal request-target"));
160
161 // Build the path to the requested file
162 std::string path = path_cat(doc_root, req.target());
163 if(req.target().back() == '/')
164 path.append("index.html");
165
166 // Attempt to open the file
167 boost::beast::error_code ec;
168 http::file_body::value_type body;
169 body.open(path.c_str(), boost::beast::file_mode::scan, ec);
170
171 // Handle the case where the file doesn't exist
172 if(ec == boost::system::errc::no_such_file_or_directory)
173 return send(not_found(req.target()));
174
175 // Handle an unknown error
176 if(ec)
177 return send(server_error(ec.message()));
178
179 // Respond to HEAD request
180 if(req.method() == http::verb::head)
181 {
182 http::response<http::empty_body> res{http::status::ok, req.version()};
183 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
184 res.set(http::field::content_type, mime_type(path));
185 res.content_length(body.size());
186 res.keep_alive(req.keep_alive());
187 return send(std::move(res));
188 }
189
190 // Respond to GET request
191 http::response<http::file_body> res{
192 std::piecewise_construct,
193 std::make_tuple(std::move(body)),
194 std::make_tuple(http::status::ok, req.version())};
195 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
196 res.set(http::field::content_type, mime_type(path));
197 res.content_length(body.size());
198 res.keep_alive(req.keep_alive());
199 return send(std::move(res));
200 }
201
202 //------------------------------------------------------------------------------
203
204 // Report a failure
205 void
206 fail(boost::system::error_code ec, char const* what)
207 {
208 std::cerr << what << ": " << ec.message() << "\n";
209 }
210
211 // Handles an HTTP server connection
212 class session : public std::enable_shared_from_this<session>
213 {
214 // This is the C++11 equivalent of a generic lambda.
215 // The function object is used to send an HTTP message.
216 struct send_lambda
217 {
218 session& self_;
219
220 explicit
221 send_lambda(session& self)
222 : self_(self)
223 {
224 }
225
226 template<bool isRequest, class Body, class Fields>
227 void
228 operator()(http::message<isRequest, Body, Fields>&& msg) const
229 {
230 // The lifetime of the message has to extend
231 // for the duration of the async operation so
232 // we use a shared_ptr to manage it.
233 auto sp = std::make_shared<
234 http::message<isRequest, Body, Fields>>(std::move(msg));
235
236 // Store a type-erased version of the shared
237 // pointer in the class to keep it alive.
238 self_.res_ = sp;
239
240 // Write the response
241 http::async_write(
242 self_.socket_,
243 *sp,
244 boost::asio::bind_executor(
245 self_.strand_,
246 std::bind(
247 &session::on_write,
248 self_.shared_from_this(),
249 std::placeholders::_1,
250 std::placeholders::_2,
251 sp->need_eof())));
252 }
253 };
254
255 tcp::socket socket_;
256 boost::asio::strand<
257 boost::asio::io_context::executor_type> strand_;
258 boost::beast::flat_buffer buffer_;
259 std::string const& doc_root_;
260 http::request<http::string_body> req_;
261 std::shared_ptr<void> res_;
262 send_lambda lambda_;
263
264 public:
265 // Take ownership of the socket
266 explicit
267 session(
268 tcp::socket socket,
269 std::string const& doc_root)
270 : socket_(std::move(socket))
271 , strand_(socket_.get_executor())
272 , doc_root_(doc_root)
273 , lambda_(*this)
274 {
275 }
276
277 // Start the asynchronous operation
278 void
279 run()
280 {
281 do_read();
282 }
283
284 void
285 do_read()
286 {
287 // Read a request
288 http::async_read(socket_, buffer_, req_,
289 boost::asio::bind_executor(
290 strand_,
291 std::bind(
292 &session::on_read,
293 shared_from_this(),
294 std::placeholders::_1,
295 std::placeholders::_2)));
296 }
297
298 void
299 on_read(
300 boost::system::error_code ec,
301 std::size_t bytes_transferred)
302 {
303 boost::ignore_unused(bytes_transferred);
304
305 // This means they closed the connection
306 if(ec == http::error::end_of_stream)
307 return do_close();
308
309 if(ec)
310 return fail(ec, "read");
311
312 // Send the response
313 handle_request(doc_root_, std::move(req_), lambda_);
314 }
315
316 void
317 on_write(
318 boost::system::error_code ec,
319 std::size_t bytes_transferred,
320 bool close)
321 {
322 boost::ignore_unused(bytes_transferred);
323
324 if(ec)
325 return fail(ec, "write");
326
327 if(close)
328 {
329 // This means we should close the connection, usually because
330 // the response indicated the "Connection: close" semantic.
331 return do_close();
332 }
333
334 // We're done with the response so delete it
335 res_ = nullptr;
336
337 // Read another request
338 do_read();
339 }
340
341 void
342 do_close()
343 {
344 // Send a TCP shutdown
345 boost::system::error_code ec;
346 socket_.shutdown(tcp::socket::shutdown_send, ec);
347
348 // At this point the connection is closed gracefully
349 }
350 };
351
352 //------------------------------------------------------------------------------
353
354 // Accepts incoming connections and launches the sessions
355 class listener : public std::enable_shared_from_this<listener>
356 {
357 tcp::acceptor acceptor_;
358 tcp::socket socket_;
359 std::string const& doc_root_;
360
361 public:
362 listener(
363 boost::asio::io_context& ioc,
364 tcp::endpoint endpoint,
365 std::string const& doc_root)
366 : acceptor_(ioc)
367 , socket_(ioc)
368 , doc_root_(doc_root)
369 {
370 boost::system::error_code ec;
371
372 // Open the acceptor
373 acceptor_.open(endpoint.protocol(), ec);
374 if(ec)
375 {
376 fail(ec, "open");
377 return;
378 }
379
380 // Bind to the server address
381 acceptor_.bind(endpoint, ec);
382 if(ec)
383 {
384 fail(ec, "bind");
385 return;
386 }
387
388 // Start listening for connections
389 acceptor_.listen(
390 boost::asio::socket_base::max_listen_connections, ec);
391 if(ec)
392 {
393 fail(ec, "listen");
394 return;
395 }
396 }
397
398 // Start accepting incoming connections
399 void
400 run()
401 {
402 if(! acceptor_.is_open())
403 return;
404 do_accept();
405 }
406
407 void
408 do_accept()
409 {
410 acceptor_.async_accept(
411 socket_,
412 std::bind(
413 &listener::on_accept,
414 shared_from_this(),
415 std::placeholders::_1));
416 }
417
418 void
419 on_accept(boost::system::error_code ec)
420 {
421 if(ec)
422 {
423 fail(ec, "accept");
424 }
425 else
426 {
427 // Create the session and run it
428 std::make_shared<session>(
429 std::move(socket_),
430 doc_root_)->run();
431 }
432
433 // Accept another connection
434 do_accept();
435 }
436 };
437
438 //------------------------------------------------------------------------------
439
440 int main(int argc, char* argv[])
441 {
442 // Check command line arguments.
443 if (argc != 5)
444 {
445 std::cerr <<
446 "Usage: http-server-async <address> <port> <doc_root> <threads>\n" <<
447 "Example:\n" <<
448 " http-server-async 0.0.0.0 8080 . 1\n";
449 return EXIT_FAILURE;
450 }
451 auto const address = boost::asio::ip::make_address(argv[1]);
452 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
453 std::string const doc_root = argv[3];
454 auto const threads = std::max<int>(1, std::atoi(argv[4]));
455
456 // The io_context is required for all I/O
457 boost::asio::io_context ioc{threads};
458
459 // Create and launch a listening port
460 std::make_shared<listener>(
461 ioc,
462 tcp::endpoint{address, port},
463 doc_root)->run();
464
465 // Run the I/O service on the requested number of threads
466 std::vector<std::thread> v;
467 v.reserve(threads - 1);
468 for(auto i = threads - 1; i > 0; --i)
469 v.emplace_back(
470 [&ioc]
471 {
472 ioc.run();
473 });
474 ioc.run();
475
476 return EXIT_SUCCESS;
477 }