]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/beast/example/http/server/coro/http_server_coro.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / beast / example / http / server / coro / http_server_coro.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, 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/ip/tcp.hpp>
20 #include <boost/asio/spawn.hpp>
21 #include <boost/config.hpp>
22 #include <algorithm>
23 #include <cstdlib>
24 #include <iostream>
25 #include <memory>
26 #include <string>
27 #include <thread>
28 #include <vector>
29
30 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
31 namespace http = boost::beast::http; // from <boost/beast/http.hpp>
32
33 // Return a reasonable mime type based on the extension of a file.
34 boost::beast::string_view
35 mime_type(boost::beast::string_view path)
36 {
37 using boost::beast::iequals;
38 auto const ext = [&path]
39 {
40 auto const pos = path.rfind(".");
41 if(pos == boost::beast::string_view::npos)
42 return boost::beast::string_view{};
43 return path.substr(pos);
44 }();
45 if(iequals(ext, ".htm")) return "text/html";
46 if(iequals(ext, ".html")) return "text/html";
47 if(iequals(ext, ".php")) return "text/html";
48 if(iequals(ext, ".css")) return "text/css";
49 if(iequals(ext, ".txt")) return "text/plain";
50 if(iequals(ext, ".js")) return "application/javascript";
51 if(iequals(ext, ".json")) return "application/json";
52 if(iequals(ext, ".xml")) return "application/xml";
53 if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
54 if(iequals(ext, ".flv")) return "video/x-flv";
55 if(iequals(ext, ".png")) return "image/png";
56 if(iequals(ext, ".jpe")) return "image/jpeg";
57 if(iequals(ext, ".jpeg")) return "image/jpeg";
58 if(iequals(ext, ".jpg")) return "image/jpeg";
59 if(iequals(ext, ".gif")) return "image/gif";
60 if(iequals(ext, ".bmp")) return "image/bmp";
61 if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
62 if(iequals(ext, ".tiff")) return "image/tiff";
63 if(iequals(ext, ".tif")) return "image/tiff";
64 if(iequals(ext, ".svg")) return "image/svg+xml";
65 if(iequals(ext, ".svgz")) return "image/svg+xml";
66 return "application/text";
67 }
68
69 // Append an HTTP rel-path to a local filesystem path.
70 // The returned path is normalized for the platform.
71 std::string
72 path_cat(
73 boost::beast::string_view base,
74 boost::beast::string_view path)
75 {
76 if(base.empty())
77 return path.to_string();
78 std::string result = base.to_string();
79 #if BOOST_MSVC
80 char constexpr path_separator = '\\';
81 if(result.back() == path_separator)
82 result.resize(result.size() - 1);
83 result.append(path.data(), path.size());
84 for(auto& c : result)
85 if(c == '/')
86 c = path_separator;
87 #else
88 char constexpr path_separator = '/';
89 if(result.back() == path_separator)
90 result.resize(result.size() - 1);
91 result.append(path.data(), path.size());
92 #endif
93 return result;
94 }
95
96 // This function produces an HTTP response for the given
97 // request. The type of the response object depends on the
98 // contents of the request, so the interface requires the
99 // caller to pass a generic lambda for receiving the response.
100 template<
101 class Body, class Allocator,
102 class Send>
103 void
104 handle_request(
105 boost::beast::string_view doc_root,
106 http::request<Body, http::basic_fields<Allocator>>&& req,
107 Send&& send)
108 {
109 // Returns a bad request response
110 auto const bad_request =
111 [&req](boost::beast::string_view why)
112 {
113 http::response<http::string_body> res{http::status::bad_request, req.version()};
114 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
115 res.set(http::field::content_type, "text/html");
116 res.keep_alive(req.keep_alive());
117 res.body() = why.to_string();
118 res.prepare_payload();
119 return res;
120 };
121
122 // Returns a not found response
123 auto const not_found =
124 [&req](boost::beast::string_view target)
125 {
126 http::response<http::string_body> res{http::status::not_found, req.version()};
127 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
128 res.set(http::field::content_type, "text/html");
129 res.keep_alive(req.keep_alive());
130 res.body() = "The resource '" + target.to_string() + "' was not found.";
131 res.prepare_payload();
132 return res;
133 };
134
135 // Returns a server error response
136 auto const server_error =
137 [&req](boost::beast::string_view what)
138 {
139 http::response<http::string_body> res{http::status::internal_server_error, req.version()};
140 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
141 res.set(http::field::content_type, "text/html");
142 res.keep_alive(req.keep_alive());
143 res.body() = "An error occurred: '" + what.to_string() + "'";
144 res.prepare_payload();
145 return res;
146 };
147
148 // Make sure we can handle the method
149 if( req.method() != http::verb::get &&
150 req.method() != http::verb::head)
151 return send(bad_request("Unknown HTTP-method"));
152
153 // Request path must be absolute and not contain "..".
154 if( req.target().empty() ||
155 req.target()[0] != '/' ||
156 req.target().find("..") != boost::beast::string_view::npos)
157 return send(bad_request("Illegal request-target"));
158
159 // Build the path to the requested file
160 std::string path = path_cat(doc_root, req.target());
161 if(req.target().back() == '/')
162 path.append("index.html");
163
164 // Attempt to open the file
165 boost::beast::error_code ec;
166 http::file_body::value_type body;
167 body.open(path.c_str(), boost::beast::file_mode::scan, ec);
168
169 // Handle the case where the file doesn't exist
170 if(ec == boost::system::errc::no_such_file_or_directory)
171 return send(not_found(req.target()));
172
173 // Handle an unknown error
174 if(ec)
175 return send(server_error(ec.message()));
176
177 // Respond to HEAD request
178 if(req.method() == http::verb::head)
179 {
180 http::response<http::empty_body> res{http::status::ok, req.version()};
181 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
182 res.set(http::field::content_type, mime_type(path));
183 res.content_length(body.size());
184 res.keep_alive(req.keep_alive());
185 return send(std::move(res));
186 }
187
188 // Respond to GET request
189 http::response<http::file_body> res{
190 std::piecewise_construct,
191 std::make_tuple(std::move(body)),
192 std::make_tuple(http::status::ok, req.version())};
193 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
194 res.set(http::field::content_type, mime_type(path));
195 res.content_length(body.size());
196 res.keep_alive(req.keep_alive());
197 return send(std::move(res));
198 }
199
200 //------------------------------------------------------------------------------
201
202 // Report a failure
203 void
204 fail(boost::system::error_code ec, char const* what)
205 {
206 std::cerr << what << ": " << ec.message() << "\n";
207 }
208
209 // This is the C++11 equivalent of a generic lambda.
210 // The function object is used to send an HTTP message.
211 template<class Stream>
212 struct send_lambda
213 {
214 Stream& stream_;
215 bool& close_;
216 boost::system::error_code& ec_;
217 boost::asio::yield_context yield_;
218
219 explicit
220 send_lambda(
221 Stream& stream,
222 bool& close,
223 boost::system::error_code& ec,
224 boost::asio::yield_context yield)
225 : stream_(stream)
226 , close_(close)
227 , ec_(ec)
228 , yield_(yield)
229 {
230 }
231
232 template<bool isRequest, class Body, class Fields>
233 void
234 operator()(http::message<isRequest, Body, Fields>&& msg) const
235 {
236 // Determine if we should close the connection after
237 close_ = msg.need_eof();
238
239 // We need the serializer here because the serializer requires
240 // a non-const file_body, and the message oriented version of
241 // http::write only works with const messages.
242 http::serializer<isRequest, Body, Fields> sr{msg};
243 http::async_write(stream_, sr, yield_[ec_]);
244 }
245 };
246
247 // Handles an HTTP server connection
248 void
249 do_session(
250 tcp::socket& socket,
251 std::string const& doc_root,
252 boost::asio::yield_context yield)
253 {
254 bool close = false;
255 boost::system::error_code ec;
256
257 // This buffer is required to persist across reads
258 boost::beast::flat_buffer buffer;
259
260 // This lambda is used to send messages
261 send_lambda<tcp::socket> lambda{socket, close, ec, yield};
262
263 for(;;)
264 {
265 // Read a request
266 http::request<http::string_body> req;
267 http::async_read(socket, buffer, req, yield[ec]);
268 if(ec == http::error::end_of_stream)
269 break;
270 if(ec)
271 return fail(ec, "read");
272
273 // Send the response
274 handle_request(doc_root, std::move(req), lambda);
275 if(ec)
276 return fail(ec, "write");
277 if(close)
278 {
279 // This means we should close the connection, usually because
280 // the response indicated the "Connection: close" semantic.
281 break;
282 }
283 }
284
285 // Send a TCP shutdown
286 socket.shutdown(tcp::socket::shutdown_send, ec);
287
288 // At this point the connection is closed gracefully
289 }
290
291 //------------------------------------------------------------------------------
292
293 // Accepts incoming connections and launches the sessions
294 void
295 do_listen(
296 boost::asio::io_context& ioc,
297 tcp::endpoint endpoint,
298 std::string const& doc_root,
299 boost::asio::yield_context yield)
300 {
301 boost::system::error_code ec;
302
303 // Open the acceptor
304 tcp::acceptor acceptor(ioc);
305 acceptor.open(endpoint.protocol(), ec);
306 if(ec)
307 return fail(ec, "open");
308
309 // Bind to the server address
310 acceptor.bind(endpoint, ec);
311 if(ec)
312 return fail(ec, "bind");
313
314 // Start listening for connections
315 acceptor.listen(boost::asio::socket_base::max_listen_connections, ec);
316 if(ec)
317 return fail(ec, "listen");
318
319 for(;;)
320 {
321 tcp::socket socket(ioc);
322 acceptor.async_accept(socket, yield[ec]);
323 if(ec)
324 fail(ec, "accept");
325 else
326 boost::asio::spawn(
327 acceptor.get_executor().context(),
328 std::bind(
329 &do_session,
330 std::move(socket),
331 doc_root,
332 std::placeholders::_1));
333 }
334 }
335
336 int main(int argc, char* argv[])
337 {
338 // Check command line arguments.
339 if (argc != 5)
340 {
341 std::cerr <<
342 "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" <<
343 "Example:\n" <<
344 " http-server-coro 0.0.0.0 8080 . 1\n";
345 return EXIT_FAILURE;
346 }
347 auto const address = boost::asio::ip::make_address(argv[1]);
348 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
349 std::string const doc_root = argv[3];
350 auto const threads = std::max<int>(1, std::atoi(argv[4]));
351
352 // The io_context is required for all I/O
353 boost::asio::io_context ioc{threads};
354
355 // Spawn a listening port
356 boost::asio::spawn(ioc,
357 std::bind(
358 &do_listen,
359 std::ref(ioc),
360 tcp::endpoint{address, port},
361 doc_root,
362 std::placeholders::_1));
363
364 // Run the I/O service on the requested number of threads
365 std::vector<std::thread> v;
366 v.reserve(threads - 1);
367 for(auto i = threads - 1; i > 0; --i)
368 v.emplace_back(
369 [&ioc]
370 {
371 ioc.run();
372 });
373 ioc.run();
374
375 return EXIT_SUCCESS;
376 }