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