Files
boost_beast/example/http/server/sync/http_server_sync.cpp
T

302 lines
9.6 KiB
C++
Raw Normal View History

2017-08-04 19:55:28 -07:00
//
2019-02-21 07:00:31 -08:00
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
2017-08-04 19:55:28 -07:00
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
//------------------------------------------------------------------------------
//
// Example: HTTP server, synchronous
//
//------------------------------------------------------------------------------
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/config.hpp>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
2018-11-30 14:58:38 -08:00
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
2017-08-04 19:55:28 -07:00
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
//------------------------------------------------------------------------------
// Return a reasonable mime type based on the extension of a file.
2018-11-30 14:58:38 -08:00
beast::string_view
mime_type(beast::string_view path)
2017-08-04 19:55:28 -07:00
{
2018-11-30 14:58:38 -08:00
using beast::iequals;
2017-08-04 19:55:28 -07:00
auto const ext = [&path]
{
auto const pos = path.rfind(".");
2018-11-30 14:58:38 -08:00
if(pos == beast::string_view::npos)
return beast::string_view{};
2017-08-04 19:55:28 -07:00
return path.substr(pos);
}();
if(iequals(ext, ".htm")) return "text/html";
if(iequals(ext, ".html")) return "text/html";
if(iequals(ext, ".php")) return "text/html";
if(iequals(ext, ".css")) return "text/css";
if(iequals(ext, ".txt")) return "text/plain";
if(iequals(ext, ".js")) return "application/javascript";
if(iequals(ext, ".json")) return "application/json";
if(iequals(ext, ".xml")) return "application/xml";
if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
if(iequals(ext, ".flv")) return "video/x-flv";
if(iequals(ext, ".png")) return "image/png";
if(iequals(ext, ".jpe")) return "image/jpeg";
if(iequals(ext, ".jpeg")) return "image/jpeg";
if(iequals(ext, ".jpg")) return "image/jpeg";
if(iequals(ext, ".gif")) return "image/gif";
if(iequals(ext, ".bmp")) return "image/bmp";
if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
if(iequals(ext, ".tiff")) return "image/tiff";
if(iequals(ext, ".tif")) return "image/tiff";
if(iequals(ext, ".svg")) return "image/svg+xml";
if(iequals(ext, ".svgz")) return "image/svg+xml";
return "application/text";
}
// Append an HTTP rel-path to a local filesystem path.
// The returned path is normalized for the platform.
std::string
path_cat(
2018-11-30 14:58:38 -08:00
beast::string_view base,
beast::string_view path)
2017-08-04 19:55:28 -07:00
{
2019-02-07 23:47:05 +01:00
if (base.empty())
return std::string(path);
std::string result(base);
2019-03-29 20:41:39 -07:00
#ifdef BOOST_MSVC
2017-08-04 19:55:28 -07:00
char constexpr path_separator = '\\';
if(result.back() == path_separator)
result.resize(result.size() - 1);
result.append(path.data(), path.size());
for(auto& c : result)
if(c == '/')
c = path_separator;
#else
char constexpr path_separator = '/';
if(result.back() == path_separator)
result.resize(result.size() - 1);
result.append(path.data(), path.size());
#endif
return result;
}
2022-05-20 17:05:18 -07:00
// Return a response for the given request.
//
// The concrete type of the response message (which depends on the
// request), is type-erased in message_generator.
template <class Body, class Allocator>
http::message_generator
2017-08-04 19:55:28 -07:00
handle_request(
2018-11-30 14:58:38 -08:00
beast::string_view doc_root,
2022-05-20 17:05:18 -07:00
http::request<Body, http::basic_fields<Allocator>>&& req)
2017-08-04 19:55:28 -07:00
{
// Returns a bad request response
auto const bad_request =
2018-11-30 14:58:38 -08:00
[&req](beast::string_view why)
2017-08-04 19:55:28 -07:00
{
http::response<http::string_body> res{http::status::bad_request, req.version()};
2017-08-04 19:55:28 -07:00
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
2019-02-07 23:47:05 +01:00
res.body() = std::string(why);
2017-08-04 19:55:28 -07:00
res.prepare_payload();
return res;
};
// Returns a not found response
auto const not_found =
2018-11-30 14:58:38 -08:00
[&req](beast::string_view target)
2017-08-04 19:55:28 -07:00
{
http::response<http::string_body> res{http::status::not_found, req.version()};
2017-08-04 19:55:28 -07:00
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
2019-02-07 23:47:05 +01:00
res.body() = "The resource '" + std::string(target) + "' was not found.";
2017-08-04 19:55:28 -07:00
res.prepare_payload();
return res;
};
// Returns a server error response
auto const server_error =
2018-11-30 14:58:38 -08:00
[&req](beast::string_view what)
2017-08-04 19:55:28 -07:00
{
http::response<http::string_body> res{http::status::internal_server_error, req.version()};
2017-08-04 19:55:28 -07:00
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
2019-02-07 23:47:05 +01:00
res.body() = "An error occurred: '" + std::string(what) + "'";
2017-08-04 19:55:28 -07:00
res.prepare_payload();
return res;
};
// Make sure we can handle the method
if( req.method() != http::verb::get &&
req.method() != http::verb::head)
2022-05-20 17:05:18 -07:00
return bad_request("Unknown HTTP-method");
2017-08-04 19:55:28 -07:00
// Request path must be absolute and not contain "..".
if( req.target().empty() ||
req.target()[0] != '/' ||
2018-11-30 14:58:38 -08:00
req.target().find("..") != beast::string_view::npos)
2022-05-20 17:05:18 -07:00
return bad_request("Illegal request-target");
2017-08-04 19:55:28 -07:00
// Build the path to the requested file
std::string path = path_cat(doc_root, req.target());
if(req.target().back() == '/')
path.append("index.html");
// Attempt to open the file
2018-11-30 14:58:38 -08:00
beast::error_code ec;
2017-08-04 19:55:28 -07:00
http::file_body::value_type body;
2018-11-30 14:58:38 -08:00
body.open(path.c_str(), beast::file_mode::scan, ec);
2017-08-04 19:55:28 -07:00
// Handle the case where the file doesn't exist
2018-11-30 14:58:38 -08:00
if(ec == beast::errc::no_such_file_or_directory)
2022-05-20 17:05:18 -07:00
return not_found(req.target());
2017-08-04 19:55:28 -07:00
// Handle an unknown error
if(ec)
2022-05-20 17:05:18 -07:00
return server_error(ec.message());
2017-08-04 19:55:28 -07:00
// Cache the size since we need it after the move
auto const size = body.size();
2017-08-04 19:55:28 -07:00
// Respond to HEAD request
if(req.method() == http::verb::head)
{
http::response<http::empty_body> res{http::status::ok, req.version()};
2017-08-04 19:55:28 -07:00
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
2017-08-04 19:55:28 -07:00
res.keep_alive(req.keep_alive());
2022-05-20 17:05:18 -07:00
return res;
2017-08-04 19:55:28 -07:00
}
2017-08-08 17:38:48 -07:00
// Respond to GET request
2017-08-04 19:55:28 -07:00
http::response<http::file_body> res{
std::piecewise_construct,
std::make_tuple(std::move(body)),
std::make_tuple(http::status::ok, req.version())};
2017-08-04 19:55:28 -07:00
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
2017-08-04 19:55:28 -07:00
res.keep_alive(req.keep_alive());
2022-05-20 17:05:18 -07:00
return res;
2017-08-04 19:55:28 -07:00
}
//------------------------------------------------------------------------------
// Report a failure
void
2018-11-30 14:58:38 -08:00
fail(beast::error_code ec, char const* what)
2017-08-04 19:55:28 -07:00
{
std::cerr << what << ": " << ec.message() << "\n";
}
// Handles an HTTP server connection
void
do_session(
2024-05-29 20:06:23 +00:00
tcp::socket socket,
std::shared_ptr<std::string const> const& doc_root)
2017-08-04 19:55:28 -07:00
{
2018-11-30 14:58:38 -08:00
beast::error_code ec;
2017-08-04 19:55:28 -07:00
// This buffer is required to persist across reads
2018-11-30 14:58:38 -08:00
beast::flat_buffer buffer;
2017-08-04 19:55:28 -07:00
for(;;)
{
// Read a request
http::request<http::string_body> req;
http::read(socket, buffer, req, ec);
if(ec == http::error::end_of_stream)
break;
if(ec)
return fail(ec, "read");
2022-05-20 17:05:18 -07:00
// Handle request
http::message_generator msg =
handle_request(*doc_root, std::move(req));
// Determine if we should close the connection
bool keep_alive = msg.keep_alive();
2017-08-04 19:55:28 -07:00
// Send the response
2022-05-20 17:05:18 -07:00
beast::write(socket, std::move(msg), ec);
if(ec)
return fail(ec, "write");
2022-05-20 17:05:18 -07:00
if(! keep_alive)
2017-08-04 19:55:28 -07:00
{
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
break;
}
}
// Send a TCP shutdown
socket.shutdown(tcp::socket::shutdown_send, ec);
// At this point the connection is closed gracefully
}
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 4)
{
std::cerr <<
"Usage: http-server-sync <address> <port> <doc_root>\n" <<
"Example:\n" <<
" http-server-sync 0.0.0.0 8080 .\n";
return EXIT_FAILURE;
}
2018-11-30 14:58:38 -08:00
auto const address = net::ip::make_address(argv[1]);
2017-08-04 19:55:28 -07:00
auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
auto const doc_root = std::make_shared<std::string>(argv[3]);
2017-08-04 19:55:28 -07:00
2017-09-07 07:39:52 -07:00
// The io_context is required for all I/O
2018-11-30 14:58:38 -08:00
net::io_context ioc{1};
2017-08-04 19:55:28 -07:00
// The acceptor receives incoming connections
2017-09-07 07:39:52 -07:00
tcp::acceptor acceptor{ioc, {address, port}};
2017-08-04 19:55:28 -07:00
for(;;)
{
// This will receive the new connection
2017-09-07 07:39:52 -07:00
tcp::socket socket{ioc};
2017-08-04 19:55:28 -07:00
// Block until we get a connection
acceptor.accept(socket);
// Launch the session, transferring ownership of the socket
2024-05-29 20:06:23 +00:00
std::thread{
do_session,
2017-08-04 19:55:28 -07:00
std::move(socket),
2024-05-29 20:06:23 +00:00
doc_root}.detach();
2017-08-04 19:55:28 -07:00
}
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
}