#include "response.h" #include "base64.h" #include "file.h" #include #include #include #include #include using namespace std::placeholders; namespace { class RequestContext { private: request_type& m_req; std::string m_host; std::string m_target; Server& m_server; const Path& m_path; public: RequestContext(request_type& req, Server& server) : m_req(req) , m_host(req["host"]) , m_target(req.target()) , m_server(server) , m_path(server.GetConfig().GetPath(server.GetSocket(), m_host, m_target)) { } const Path& GetPath() const {return m_path;} std::string GetPluginName() const {return m_path.params.at("plugin");} // can throw std::out_of_range std::string GetPluginPath() const {return m_path.requested;} std::string GetDocRoot() const {return m_path.params.at("target");} // can throw std::out_of_range std::string GetRelativePath() const { // can throw std::runtime_error if (!boost::starts_with(m_target, m_path.requested)) throw std::runtime_error("Mismatch of target ("s + m_target + ") and plugin path(" + m_path.requested + ")"s); if (m_target.size() > m_path.requested.size() && m_target[m_path.requested.size()] == '/') return m_target.substr(m_path.requested.size() + 1); else return m_target.substr(m_path.requested.size()); } std::string GetPluginParam(const std::string& key) const {return m_path.params.at(key);} // can throw std::out_of_range plugin_type GetPlugin() const {return m_server.GetPlugin(m_path.params.at("plugin"));}; // can throw std::out_of_range request_type& GetReq() const {return m_req;} std::string GetTarget() const {return m_target;} std::string GetHost() const {return m_host;} Server& GetServer() const {return m_server; } const Socket& GetSocket() const {return m_server.GetSocket(); } }; std::string extend_index_html(std::string path) { if (path.size() == 0 || path.back() == '/') path.append("index.html"); return path; } std::unordered_map> GetServerParamFunctions{ // following are the supported fields: {"version", [](Server& server) { return Server::VersionString; }}, {"address", [](Server& server) { return server.GetSocket().address; }}, {"port", [](Server& server) { return server.GetSocket().port; }}, }; std::string GetServerParam(const std::string& key, Server& server) { auto it = GetServerParamFunctions.find(key); if (it != GetServerParamFunctions.end()) return it->second(server); throw std::runtime_error("Unsupported server param: "s + key); } std::unordered_map> GetRequestParamFunctions{ // following are the supported fields: {"authorization", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::authorization]}; }}, {"body", [](RequestContext& req_ctx) { return req_ctx.GetReq().body(); }}, {"content_length", [](RequestContext& req_ctx) { return std::to_string(req_ctx.GetReq().body().size()); }}, {"content_type", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::content_type]}; }}, {"doc_root", [](RequestContext& req_ctx) { return req_ctx.GetDocRoot();}}, {"host", [](RequestContext& req_ctx) { return req_ctx.GetHost();}}, {"http_accept", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::accept]};}}, {"http_accept_charset", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::accept_charset]};}}, {"http_accept_encoding", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::accept_encoding]};}}, {"http_accept_language", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::accept_language]};}}, {"http_connection", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::connection]};}}, {"http_host", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::host]};}}, {"http_user_agent", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq()[http::field::user_agent]};}}, {"http_version", [](RequestContext& req_ctx) { unsigned version {req_ctx.GetReq().version()}; unsigned major{version / 10}; unsigned minor{version % 10}; return "HTTP/"s + std::to_string(major) + "."s + std::to_string(minor); }}, {"location", [](RequestContext& req_ctx) { return req_ctx.GetTarget(); }}, {"method", [](RequestContext& req_ctx) { return std::string{req_ctx.GetReq().method_string()};}}, {"rel_target", [](RequestContext& req_ctx) {return req_ctx.GetRelativePath();}}, {"target", [](RequestContext& req_ctx) {return req_ctx.GetTarget();}}, }; std::string GetRequestParam(const std::string& key, RequestContext& req_ctx) { // first, look up functions from GetRequestParamFunctions { auto it = GetRequestParamFunctions.find(key); if (it != GetRequestParamFunctions.end()) return it->second(req_ctx); } // second, look up plugin parameters { try { return req_ctx.GetPluginParam(key); } catch(const std::out_of_range& ex) { // not found }; } // third, look up req parameters // contains: host { try { return std::string{req_ctx.GetReq()[key]}; } catch(...) { // not found } } // otherwise: error throw std::runtime_error("Unsupported request param: "s + key); } void SetResponseHeader(const std::string& key, const std::string& value, response_type& res) { // following are the supported fields: if (key == "status") { // HTTP Status, e.g. "200" (OK) res.result(unsigned(stoul(value))); } else if (key == "server") { // Server name/version string res.set(http::field::server, value); } else if (key == "content_type") { // e.g. text/html res.set(http::field::content_type, value); } else if (key == "content_disposition") { // e.g. attachment; ... res.set(http::field::content_disposition, value); } else if (key == "location") { // e.g. 301 Moved Permanently: new Location res.set(http::field::location, value); } else throw std::runtime_error("Unsupported response field: "s + key); } // Return a reasonable mime type based on the extension of a file. beast::string_view mime_type(beast::string_view path) { using beast::iequals; auto const ext = [&path] { auto const pos = path.rfind("."); if (pos == beast::string_view::npos) return beast::string_view{}; 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"; } // Used to return errors by generating response page and HTTP status code response_type HttpStatus(std::string status, std::string message, response_type& res) { res.result(unsigned(stoul(status))); res.set(http::field::content_type, "text/html"); if (res.result_int() == 401) res.set(http::field::www_authenticate, "Basic realm=\"Webbox Login\""); res.body() = "

"s + Server::VersionString + " Error

"s + status + " "s + message + "

"s; res.prepare_payload(); return res; } } // anonymous namespace response_type generate_response(request_type& req, Server& server) { response_type res{http::status::ok, req.version()}; res.set(http::field::server, Server::VersionString); res.set(http::field::content_type, mime_type(extend_index_html(std::string(req.target())))); res.keep_alive(req.keep_alive()); try { RequestContext req_ctx{req, server}; // can throw std::out_of_range auto& auth{req_ctx.GetPath().auth}; if (auth.size() != 0) { std::string authorization{req[http::field::authorization]}; if (authorization.substr(0, 6) != "Basic "s) return HttpStatus("401", "Bad Authorization Type", res); authorization = authorization.substr(6); authorization = decode64(authorization); size_t pos {authorization.find(':')}; if (pos == authorization.npos) return HttpStatus("401", "Bad Authorization Encoding", res); std::string login{authorization.substr(0, pos)}; std::string password{authorization.substr(pos + 1)}; auto it {auth.find(login)}; if (it == auth.end()) return HttpStatus("401", "Bad Authorization", res); if (it->second != password) return HttpStatus("401", "Bad Authorization", res); // should be same message as previous one to prevent login guessing } plugin_type plugin{req_ctx.GetPlugin()}; auto GetServerParamFunction {std::function(std::bind(GetServerParam, _1, std::ref(server)))}; auto GetRequestParamFunction {std::function(std::bind(GetRequestParam, _1, std::ref(req_ctx)))}; auto SetResponseHeaderFunction{std::function(std::bind(SetResponseHeader, _1, _2, std::ref(res)))}; std::string res_data { plugin->generate_page(GetServerParamFunction, GetRequestParamFunction, SetResponseHeaderFunction)}; if (req.method() == http::verb::head) { res.content_length(res_data.size()); } else { res.body() = res_data; res.prepare_payload(); } return res; } catch(const std::out_of_range& ex) { return HttpStatus("400", "Bad request: Host "s + std::string{req["host"]} + ":"s + std::string{req.target()} + " unknown"s, res); } catch(const std::exception& ex) { return HttpStatus("400", "Bad request: "s + std::string{ex.what()}, res); } }