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