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, synchronous
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/config.hpp>
21 #include <cstdlib>
22 #include <iostream>
23 #include <memory>
24 #include <string>
25 #include <thread>
26
27 namespace beast = boost::beast; // from <boost/beast.hpp>
28 namespace http = beast::http; // from <boost/beast/http.hpp>
29 namespace net = boost::asio; // from <boost/asio.hpp>
30 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
31
32 //------------------------------------------------------------------------------
33
34 // Return a reasonable mime type based on the extension of a file.
35 beast::string_view
mime_type(beast::string_view path)36 mime_type(beast::string_view path)
37 {
38 using beast::iequals;
39 auto const ext = [&path]
40 {
41 auto const pos = path.rfind(".");
42 if(pos == beast::string_view::npos)
43 return beast::string_view{};
44 return path.substr(pos);
45 }();
46 if(iequals(ext, ".htm")) return "text/html";
47 if(iequals(ext, ".html")) return "text/html";
48 if(iequals(ext, ".php")) return "text/html";
49 if(iequals(ext, ".css")) return "text/css";
50 if(iequals(ext, ".txt")) return "text/plain";
51 if(iequals(ext, ".js")) return "application/javascript";
52 if(iequals(ext, ".json")) return "application/json";
53 if(iequals(ext, ".xml")) return "application/xml";
54 if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
55 if(iequals(ext, ".flv")) return "video/x-flv";
56 if(iequals(ext, ".png")) return "image/png";
57 if(iequals(ext, ".jpe")) return "image/jpeg";
58 if(iequals(ext, ".jpeg")) return "image/jpeg";
59 if(iequals(ext, ".jpg")) return "image/jpeg";
60 if(iequals(ext, ".gif")) return "image/gif";
61 if(iequals(ext, ".bmp")) return "image/bmp";
62 if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
63 if(iequals(ext, ".tiff")) return "image/tiff";
64 if(iequals(ext, ".tif")) return "image/tiff";
65 if(iequals(ext, ".svg")) return "image/svg+xml";
66 if(iequals(ext, ".svgz")) return "image/svg+xml";
67 return "application/text";
68 }
69
70 // Append an HTTP rel-path to a local filesystem path.
71 // The returned path is normalized for the platform.
72 std::string
path_cat(beast::string_view base,beast::string_view path)73 path_cat(
74 beast::string_view base,
75 beast::string_view path)
76 {
77 if (base.empty())
78 return std::string(path);
79 std::string result(base);
80 #ifdef BOOST_MSVC
81 char constexpr path_separator = '\\';
82 if(result.back() == path_separator)
83 result.resize(result.size() - 1);
84 result.append(path.data(), path.size());
85 for(auto& c : result)
86 if(c == '/')
87 c = path_separator;
88 #else
89 char constexpr path_separator = '/';
90 if(result.back() == path_separator)
91 result.resize(result.size() - 1);
92 result.append(path.data(), path.size());
93 #endif
94 return result;
95 }
96
97 // This function produces an HTTP response for the given
98 // request. The type of the response object depends on the
99 // contents of the request, so the interface requires the
100 // caller to pass a generic lambda for receiving the response.
101 template<
102 class Body, class Allocator,
103 class Send>
104 void
handle_request(beast::string_view doc_root,http::request<Body,http::basic_fields<Allocator>> && req,Send && send)105 handle_request(
106 beast::string_view doc_root,
107 http::request<Body, http::basic_fields<Allocator>>&& req,
108 Send&& send)
109 {
110 // Returns a bad request response
111 auto const bad_request =
112 [&req](beast::string_view why)
113 {
114 http::response<http::string_body> res{http::status::bad_request, req.version()};
115 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
116 res.set(http::field::content_type, "text/html");
117 res.keep_alive(req.keep_alive());
118 res.body() = std::string(why);
119 res.prepare_payload();
120 return res;
121 };
122
123 // Returns a not found response
124 auto const not_found =
125 [&req](beast::string_view target)
126 {
127 http::response<http::string_body> res{http::status::not_found, req.version()};
128 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
129 res.set(http::field::content_type, "text/html");
130 res.keep_alive(req.keep_alive());
131 res.body() = "The resource '" + std::string(target) + "' was not found.";
132 res.prepare_payload();
133 return res;
134 };
135
136 // Returns a server error response
137 auto const server_error =
138 [&req](beast::string_view what)
139 {
140 http::response<http::string_body> res{http::status::internal_server_error, req.version()};
141 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
142 res.set(http::field::content_type, "text/html");
143 res.keep_alive(req.keep_alive());
144 res.body() = "An error occurred: '" + std::string(what) + "'";
145 res.prepare_payload();
146 return res;
147 };
148
149 // Make sure we can handle the method
150 if( req.method() != http::verb::get &&
151 req.method() != http::verb::head)
152 return send(bad_request("Unknown HTTP-method"));
153
154 // Request path must be absolute and not contain "..".
155 if( req.target().empty() ||
156 req.target()[0] != '/' ||
157 req.target().find("..") != beast::string_view::npos)
158 return send(bad_request("Illegal request-target"));
159
160 // Build the path to the requested file
161 std::string path = path_cat(doc_root, req.target());
162 if(req.target().back() == '/')
163 path.append("index.html");
164
165 // Attempt to open the file
166 beast::error_code ec;
167 http::file_body::value_type body;
168 body.open(path.c_str(), beast::file_mode::scan, ec);
169
170 // Handle the case where the file doesn't exist
171 if(ec == beast::errc::no_such_file_or_directory)
172 return send(not_found(req.target()));
173
174 // Handle an unknown error
175 if(ec)
176 return send(server_error(ec.message()));
177
178 // Cache the size since we need it after the move
179 auto const size = body.size();
180
181 // Respond to HEAD request
182 if(req.method() == http::verb::head)
183 {
184 http::response<http::empty_body> res{http::status::ok, req.version()};
185 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
186 res.set(http::field::content_type, mime_type(path));
187 res.content_length(size);
188 res.keep_alive(req.keep_alive());
189 return send(std::move(res));
190 }
191
192 // Respond to GET request
193 http::response<http::file_body> res{
194 std::piecewise_construct,
195 std::make_tuple(std::move(body)),
196 std::make_tuple(http::status::ok, req.version())};
197 res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
198 res.set(http::field::content_type, mime_type(path));
199 res.content_length(size);
200 res.keep_alive(req.keep_alive());
201 return send(std::move(res));
202 }
203
204 //------------------------------------------------------------------------------
205
206 // Report a failure
207 void
fail(beast::error_code ec,char const * what)208 fail(beast::error_code ec, char const* what)
209 {
210 std::cerr << what << ": " << ec.message() << "\n";
211 }
212
213 // This is the C++11 equivalent of a generic lambda.
214 // The function object is used to send an HTTP message.
215 template<class Stream>
216 struct send_lambda
217 {
218 Stream& stream_;
219 bool& close_;
220 beast::error_code& ec_;
221
222 explicit
send_lambdasend_lambda223 send_lambda(
224 Stream& stream,
225 bool& close,
226 beast::error_code& ec)
227 : stream_(stream)
228 , close_(close)
229 , ec_(ec)
230 {
231 }
232
233 template<bool isRequest, class Body, class Fields>
234 void
operator ()send_lambda235 operator()(http::message<isRequest, Body, Fields>&& msg) const
236 {
237 // Determine if we should close the connection after
238 close_ = msg.need_eof();
239
240 // We need the serializer here because the serializer requires
241 // a non-const file_body, and the message oriented version of
242 // http::write only works with const messages.
243 http::serializer<isRequest, Body, Fields> sr{msg};
244 http::write(stream_, sr, ec_);
245 }
246 };
247
248 // Handles an HTTP server connection
249 void
do_session(tcp::socket & socket,std::shared_ptr<std::string const> const & doc_root)250 do_session(
251 tcp::socket& socket,
252 std::shared_ptr<std::string const> const& doc_root)
253 {
254 bool close = false;
255 beast::error_code ec;
256
257 // This buffer is required to persist across reads
258 beast::flat_buffer buffer;
259
260 // This lambda is used to send messages
261 send_lambda<tcp::socket> lambda{socket, close, ec};
262
263 for(;;)
264 {
265 // Read a request
266 http::request<http::string_body> req;
267 http::read(socket, buffer, req, 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
main(int argc,char * argv[])293 int main(int argc, char* argv[])
294 {
295 try
296 {
297 // Check command line arguments.
298 if (argc != 4)
299 {
300 std::cerr <<
301 "Usage: http-server-sync <address> <port> <doc_root>\n" <<
302 "Example:\n" <<
303 " http-server-sync 0.0.0.0 8080 .\n";
304 return EXIT_FAILURE;
305 }
306 auto const address = net::ip::make_address(argv[1]);
307 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
308 auto const doc_root = std::make_shared<std::string>(argv[3]);
309
310 // The io_context is required for all I/O
311 net::io_context ioc{1};
312
313 // The acceptor receives incoming connections
314 tcp::acceptor acceptor{ioc, {address, port}};
315 for(;;)
316 {
317 // This will receive the new connection
318 tcp::socket socket{ioc};
319
320 // Block until we get a connection
321 acceptor.accept(socket);
322
323 // Launch the session, transferring ownership of the socket
324 std::thread{std::bind(
325 &do_session,
326 std::move(socket),
327 doc_root)}.detach();
328 }
329 }
330 catch (const std::exception& e)
331 {
332 std::cerr << "Error: " << e.what() << std::endl;
333 return EXIT_FAILURE;
334 }
335 }
336