]>
Commit | Line | Data |
---|---|---|
b32b8144 FG |
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 | ||
11fdf7f2 TL |
177 | // Cache the size since we need it after the move |
178 | auto const size = body.size(); | |
179 | ||
b32b8144 FG |
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)); | |
11fdf7f2 | 186 | res.content_length(size); |
b32b8144 FG |
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)); | |
11fdf7f2 | 198 | res.content_length(size); |
b32b8144 FG |
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 | // This is the C++11 equivalent of a generic lambda. | |
213 | // The function object is used to send an HTTP message. | |
214 | template<class Stream> | |
215 | struct send_lambda | |
216 | { | |
217 | Stream& stream_; | |
218 | bool& close_; | |
219 | boost::system::error_code& ec_; | |
220 | boost::asio::yield_context yield_; | |
221 | ||
222 | explicit | |
223 | send_lambda( | |
224 | Stream& stream, | |
225 | bool& close, | |
226 | boost::system::error_code& ec, | |
227 | boost::asio::yield_context yield) | |
228 | : stream_(stream) | |
229 | , close_(close) | |
230 | , ec_(ec) | |
231 | , yield_(yield) | |
232 | { | |
233 | } | |
234 | ||
235 | template<bool isRequest, class Body, class Fields> | |
236 | void | |
237 | operator()(http::message<isRequest, Body, Fields>&& msg) const | |
238 | { | |
239 | // Determine if we should close the connection after | |
240 | close_ = msg.need_eof(); | |
241 | ||
242 | // We need the serializer here because the serializer requires | |
243 | // a non-const file_body, and the message oriented version of | |
244 | // http::write only works with const messages. | |
245 | http::serializer<isRequest, Body, Fields> sr{msg}; | |
246 | http::async_write(stream_, sr, yield_[ec_]); | |
247 | } | |
248 | }; | |
249 | ||
250 | // Handles an HTTP server connection | |
251 | void | |
252 | do_session( | |
253 | tcp::socket& socket, | |
254 | std::string const& doc_root, | |
255 | boost::asio::yield_context yield) | |
256 | { | |
257 | bool close = false; | |
258 | boost::system::error_code ec; | |
259 | ||
260 | // This buffer is required to persist across reads | |
261 | boost::beast::flat_buffer buffer; | |
262 | ||
263 | // This lambda is used to send messages | |
264 | send_lambda<tcp::socket> lambda{socket, close, ec, yield}; | |
265 | ||
266 | for(;;) | |
267 | { | |
268 | // Read a request | |
269 | http::request<http::string_body> req; | |
270 | http::async_read(socket, buffer, req, yield[ec]); | |
271 | if(ec == http::error::end_of_stream) | |
272 | break; | |
273 | if(ec) | |
274 | return fail(ec, "read"); | |
275 | ||
276 | // Send the response | |
277 | handle_request(doc_root, std::move(req), lambda); | |
278 | if(ec) | |
279 | return fail(ec, "write"); | |
280 | if(close) | |
281 | { | |
282 | // This means we should close the connection, usually because | |
283 | // the response indicated the "Connection: close" semantic. | |
284 | break; | |
285 | } | |
286 | } | |
287 | ||
288 | // Send a TCP shutdown | |
289 | socket.shutdown(tcp::socket::shutdown_send, ec); | |
290 | ||
291 | // At this point the connection is closed gracefully | |
292 | } | |
293 | ||
294 | //------------------------------------------------------------------------------ | |
295 | ||
296 | // Accepts incoming connections and launches the sessions | |
297 | void | |
298 | do_listen( | |
299 | boost::asio::io_context& ioc, | |
300 | tcp::endpoint endpoint, | |
301 | std::string const& doc_root, | |
302 | boost::asio::yield_context yield) | |
303 | { | |
304 | boost::system::error_code ec; | |
305 | ||
306 | // Open the acceptor | |
307 | tcp::acceptor acceptor(ioc); | |
308 | acceptor.open(endpoint.protocol(), ec); | |
309 | if(ec) | |
310 | return fail(ec, "open"); | |
311 | ||
11fdf7f2 TL |
312 | // Allow address reuse |
313 | acceptor.set_option(boost::asio::socket_base::reuse_address(true)); | |
314 | if(ec) | |
315 | return fail(ec, "set_option"); | |
316 | ||
b32b8144 FG |
317 | // Bind to the server address |
318 | acceptor.bind(endpoint, ec); | |
319 | if(ec) | |
320 | return fail(ec, "bind"); | |
321 | ||
322 | // Start listening for connections | |
323 | acceptor.listen(boost::asio::socket_base::max_listen_connections, ec); | |
324 | if(ec) | |
325 | return fail(ec, "listen"); | |
326 | ||
327 | for(;;) | |
328 | { | |
329 | tcp::socket socket(ioc); | |
330 | acceptor.async_accept(socket, yield[ec]); | |
331 | if(ec) | |
332 | fail(ec, "accept"); | |
333 | else | |
334 | boost::asio::spawn( | |
335 | acceptor.get_executor().context(), | |
336 | std::bind( | |
337 | &do_session, | |
338 | std::move(socket), | |
339 | doc_root, | |
340 | std::placeholders::_1)); | |
341 | } | |
342 | } | |
343 | ||
344 | int main(int argc, char* argv[]) | |
345 | { | |
346 | // Check command line arguments. | |
347 | if (argc != 5) | |
348 | { | |
349 | std::cerr << | |
350 | "Usage: http-server-coro <address> <port> <doc_root> <threads>\n" << | |
351 | "Example:\n" << | |
352 | " http-server-coro 0.0.0.0 8080 . 1\n"; | |
353 | return EXIT_FAILURE; | |
354 | } | |
355 | auto const address = boost::asio::ip::make_address(argv[1]); | |
356 | auto const port = static_cast<unsigned short>(std::atoi(argv[2])); | |
357 | std::string const doc_root = argv[3]; | |
358 | auto const threads = std::max<int>(1, std::atoi(argv[4])); | |
359 | ||
360 | // The io_context is required for all I/O | |
361 | boost::asio::io_context ioc{threads}; | |
362 | ||
363 | // Spawn a listening port | |
364 | boost::asio::spawn(ioc, | |
365 | std::bind( | |
366 | &do_listen, | |
367 | std::ref(ioc), | |
368 | tcp::endpoint{address, port}, | |
369 | doc_root, | |
370 | std::placeholders::_1)); | |
371 | ||
372 | // Run the I/O service on the requested number of threads | |
373 | std::vector<std::thread> v; | |
374 | v.reserve(threads - 1); | |
375 | for(auto i = threads - 1; i > 0; --i) | |
376 | v.emplace_back( | |
377 | [&ioc] | |
378 | { | |
379 | ioc.run(); | |
380 | }); | |
381 | ioc.run(); | |
382 | ||
383 | return EXIT_SUCCESS; | |
384 | } |