Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef HTTP_SERVER_H
- #define HTTP_SERVER_H
- #include <boost/beast/core.hpp>
- #include <boost/beast/http.hpp>
- #include <boost/beast/version.hpp>
- #include <boost/asio/bind_executor.hpp>
- #include <boost/asio/ip/tcp.hpp>
- #include <boost/asio/strand.hpp>
- #include <boost/config.hpp>
- #include <algorithm>
- #include <nlohmann/json.hpp>
- #include <cstdlib>
- #include <functional>
- #include <iostream>
- #include <memory>
- #include <string>
- #include <thread>
- #include <vector>
- using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
- namespace http = boost::beast::http; // from <boost/beast/http.hpp>
- // Return a reasonable mime type based on the extension of a file.
- boost::beast::string_view mime_type(boost::beast::string_view path);
- // Append an HTTP rel-path to a local filesystem path.
- // The returned path is normalized for the platform.
- std::string path_cat(boost::beast::string_view base, boost::beast::string_view path);
- // This class represents a cache for storing results from the
- // currency exchange API used by openexchangerates.org
- template<typename Query_Data_T, typename Query_Response_T>
- class cache_storage
- {
- public:
- cache_storage()
- : m_cache{}
- {
- }
- const Query_Response_T &query(Query_Data_T query_data)
- {
- }
- private:
- std::unordered_map<Query_Data_T, std::pair<std::chrono::time_point<std::chrono::system_clock>, Query_Response_T>> m_cache;
- };
- // This function produces an HTTP response for the given
- // request. The type of the response object depends on the
- // contents of the request, so the interface requires the
- // caller to pass a generic lambda for receiving the response.
- template<class Body, class Allocator, class Send>
- void handle_request(boost::beast::string_view doc_root, http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send)
- {
- // Returns a bad request response
- const auto bad_request =
- [&req](boost::beast::string_view why)
- {
- http::response<http::string_body> res{ http::status::bad_request, req.version() };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, "text/html");
- res.keep_alive(req.keep_alive());
- res.body() = why.to_string();
- res.prepare_payload();
- return res;
- };
- // Returns a not found response
- const auto not_found =
- [&req](boost::beast::string_view target)
- {
- http::response<http::string_body> res{ http::status::not_found, req.version() };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, "text/html");
- res.keep_alive(req.keep_alive());
- res.body() = "The resource '" + target.to_string() + "' was not found.";
- res.prepare_payload();
- return res;
- };
- // Returns a server error response
- const auto server_error = [&req](boost::beast::string_view what)
- {
- http::response<http::string_body> res{ http::status::internal_server_error, req.version() };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, "text/html");
- res.keep_alive(req.keep_alive());
- res.body() = "An error occurred: '" + what.to_string() + "'";
- res.prepare_payload();
- return res;
- };
- // Make sure we can handle the method
- if (req.method() != http::verb::get &&
- req.method() != http::verb::head &&
- req.method() != http::verb::post)
- {
- return send(bad_request("Unknown HTTP-method"));
- }
- // Request path must be absolute and not contain "..".
- if (req.target().empty() ||
- req.target()[0] != '/' ||
- req.target().find("..") != boost::beast::string_view::npos)
- {
- return send(bad_request("Illegal request-target"));
- }
- // Build the path to the requested file
- std::string path = path_cat(doc_root, req.target());
- if (req.target().back() == '/')
- {
- path.append("index.html");
- }
- // In case of POST request, check the path URI
- else if (req.target().front() == '/' && req.target().size() > 1)
- {
- using boost::beast::iequals;
- const auto ext = [&path]
- {
- auto pos = path.rfind(".");
- if (pos == boost::beast::string_view::npos)
- {
- return boost::beast::string_view{};
- }
- pos = path.find(" ");
- if (pos != boost::beast::string_view::npos)
- {
- return boost::beast::string_view{};
- }
- return boost::beast::string_view(path.substr(pos));
- }();
- if (!iequals(ext, ".cgi") && !iequals(ext, ".exe"))
- {
- return send(bad_request("Illegal request-target"));
- }
- }
- // Attempt to open the file
- boost::beast::error_code ec;
- http::file_body::value_type body;
- body.open(path.c_str(), boost::beast::file_mode::scan, ec);
- // Handle the case where the file doesn't exist
- if (ec == boost::system::errc::no_such_file_or_directory)
- {
- return send(not_found(req.target()));
- }
- // Handle an unknown error
- if (ec)
- {
- return send(server_error(ec.message()));
- }
- // Respond to HEAD request
- if (req.method() == http::verb::head)
- {
- http::response<http::empty_body> res{ http::status::ok, req.version() };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, mime_type(path));
- res.content_length(body.size());
- res.keep_alive(req.keep_alive());
- return send(std::move(res));
- }
- // Respond to GET request
- else if (req.method() == http::verb::get)
- {
- http::response<http::file_body> res{
- std::piecewise_construct,
- std::make_tuple(std::move(body)),
- std::make_tuple(http::status::ok, req.version()) };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, mime_type(path));
- res.content_length(body.size());
- res.keep_alive(req.keep_alive());
- return send(std::move(res));
- }
- // Respond to POST request
- else if (req.method() == http::verb::post)
- {
- boost::beast::string_view content_type = req[http::field::content_type];
- if (content_type != "multipart/form-data" && content_type != "application/x-www-form-urlencoded")
- {
- return send(bad_request("Bad request"));
- }
- http::response<http::file_body> res{
- std::piecewise_construct,
- std::make_tuple(std::move(body)),
- std::make_tuple(http::status::ok, req.version()) };
- res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
- res.set(http::field::content_type, mime_type(path));
- res.content_length(body.size());
- res.keep_alive(req.keep_alive());
- return send(std::move(res));
- }
- return send(bad_request("Bad request"));
- }
- //------------------------------------------------------------------------------
- // Report a failure
- void fail(boost::system::error_code ec, const char *what);
- // Handles an HTTP server connection
- class session : public std::enable_shared_from_this<session>
- {
- // This is the C++11 equivalent of a generic lambda.
- // The function object is used to send an HTTP message.
- struct send_lambda
- {
- session& self_;
- explicit send_lambda(session& self)
- : self_{ self }
- {
- }
- template<bool isRequest, class Body, class Fields>
- void operator()(http::message<isRequest, Body, Fields>&& msg) const
- {
- // The lifetime of the message has to extend
- // for the duration of the async operation so
- // we use a shared_ptr to manage it.
- auto sp = std::make_shared<http::message<isRequest, Body, Fields>>(std::move(msg));
- // Store a type-erased version of the shared
- // pointer in the class to keep it alive.
- self_.res_ = sp;
- // Write the response
- http::async_write(self_.socket_, *sp, boost::asio::bind_executor(self_.strand_, std::bind(&session::on_write,
- self_.shared_from_this(), std::placeholders::_1, std::placeholders::_2, sp->need_eof())));
- }
- };
- tcp::socket socket_;
- boost::asio::strand<boost::asio::io_context::executor_type> strand_;
- boost::beast::flat_buffer buffer_;
- std::string const& doc_root_;
- http::request<http::string_body> req_;
- std::shared_ptr<void> res_;
- send_lambda lambda_;
- public:
- // Take ownership of the socket
- explicit session(tcp::socket socket, const std::string &doc_root)
- : socket_{ std::move(socket) }
- , strand_{ socket_.get_executor() }
- , doc_root_{ doc_root }
- , lambda_{ *this }
- {
- }
- // Start the asynchronous operation
- void run()
- {
- do_read();
- }
- void do_read()
- {
- // Read a request
- http::async_read(socket_, buffer_, req_, boost::asio::bind_executor(strand_, std::bind(&session::on_read, shared_from_this(),
- std::placeholders::_1, std::placeholders::_2)));
- }
- void on_read(boost::system::error_code ec, std::size_t bytes_transferred);
- void on_write(boost::system::error_code ec, std::size_t bytes_transferred, bool close);
- void do_close()
- {
- // Send a TCP shutdown
- boost::system::error_code ec;
- socket_.shutdown(tcp::socket::shutdown_send, ec);
- // At this point the connection is closed gracefully
- }
- };
- //------------------------------------------------------------------------------
- // Accepts incoming connections and launches the sessions
- class listener : public std::enable_shared_from_this<listener>
- {
- tcp::acceptor acceptor_;
- tcp::socket socket_;
- const std::string &doc_root_;
- public:
- listener(boost::asio::io_context& ioc, tcp::endpoint endpoint, const std::string &doc_root);
- // Start accepting incoming connections
- void run()
- {
- if (!acceptor_.is_open())
- {
- return;
- }
- do_accept();
- }
- void do_accept()
- {
- acceptor_.async_accept(socket_, std::bind(&listener::on_accept, shared_from_this(), std::placeholders::_1));
- }
- void on_accept(boost::system::error_code ec);
- };
- #endif
Add Comment
Please, Sign In to add comment