#include "evo/server/ops_http.hpp" #include #include #include #include #include #include namespace evo::server { namespace { using Clock = std::chrono::steady_clock; const char* reason(int status) { switch (status) { case 200: return "OK"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 403: return "Forbidden"; case 404: return "Not Found"; case 429: return "Too Many Requests"; case 405: return "Method Not Allowed"; case 431: return "Request Header Fields Too Large"; case 503: return "Service Unavailable"; default: return "Internal Server Error"; } } std::string encode(const OpsResponse& r) { std::string out = "HTTP/1.1 " + std::to_string(r.status) + " " + reason(r.status) + "\r\nContent-Type: " + r.content_type + "\r\nContent-Length: " + std::to_string(r.body.size()) + "\r\nCache-Control: no-store\r\nConnection: close\r\n"; if (r.status == 405) out += "Allow: GET, POST\r\n"; if (r.status == 401) out += "WWW-Authenticate: Bearer\r\n"; out += r.headers; return out + "\r\n" + r.body; } bool printable(std::string_view s) { for (const char ch : s) if (ch <= ' ' || ch > '~') return false; return true; } } // namespace std::expected, OpsError> OpsServer::listen(std::string_view address, std::size_t response_limit) { if (response_limit == 0 || response_limit > max_configurable_response_bytes) return std::unexpected{OpsError::address}; const auto colon = address.rfind(':'); if (colon == std::string_view::npos || colon + 1 >= address.size()) return std::unexpected{OpsError::address}; unsigned port{}; const auto digits = address.substr(colon + 1); const auto [end, error] = std::from_chars(digits.data(), digits.data() + digits.size(), port); if (error != std::errc{} || end != digits.data() + digits.size() || port > 65535) return std::unexpected{OpsError::address}; auto host = std::string(address.substr(0, colon)); sockaddr_storage storage{}; socklen_t length{}; int family{}; if (host.size() >= 2 && host.front() == '[' && host.back() == ']') { host = host.substr(1, host.size() - 2); auto* v6 = reinterpret_cast(&storage); if (inet_pton(AF_INET6, host.c_str(), &v6->sin6_addr) != 1) return std::unexpected{OpsError::address}; v6->sin6_family = AF_INET6; v6->sin6_port = htons(static_cast(port)); family = AF_INET6; length = sizeof(sockaddr_in6); } else { auto* v4 = reinterpret_cast(&storage); if (inet_pton(AF_INET, host.c_str(), &v4->sin_addr) != 1) return std::unexpected{OpsError::address}; v4->sin_family = AF_INET; v4->sin_port = htons(static_cast(port)); family = AF_INET; length = sizeof(sockaddr_in); } const int fd = ::socket(family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0); if (fd < 0) return std::unexpected{OpsError::socket}; const int on = 1; ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on); if (::bind(fd, reinterpret_cast(&storage), length) != 0 || ::listen(fd, 16) != 0) { ::close(fd); return std::unexpected{OpsError::socket}; } sockaddr_storage bound{}; socklen_t bound_length = sizeof bound; ::getsockname(fd, reinterpret_cast(&bound), &bound_length); const auto actual = family == AF_INET6 ? ntohs(reinterpret_cast(&bound)->sin6_port) : ntohs(reinterpret_cast(&bound)->sin_port); return std::unique_ptr(new OpsServer(fd, actual, response_limit)); } OpsServer::~OpsServer() { for (auto& c : connections_) ::close(c.fd); ::close(fd_); } void OpsServer::respond(Connection& c, const OpsHandler& handler) { OpsResponse response; const auto line_end = c.in.find("\r\n"); const std::string_view line = std::string_view(c.in).substr(0, line_end); const auto first = line.find(' '); const auto second = first == std::string_view::npos ? first : line.find(' ', first + 1); if (second == std::string_view::npos || line.substr(second + 1).rfind("HTTP/1.", 0) != 0) { response = {400, "bad request\n"}; } else { const auto method = line.substr(0, first); const auto path = line.substr(first + 1, second - first - 1); if (method != "GET") response = {405, "method not allowed\n"}; else if (path.empty() || path.front() != '/' || path.size() > 256 || !printable(path)) response = {400, "bad request\n"}; else response = handler(path); } if (response.body.size() > response_limit_) response = {500, "response too large\n"}; c.out = encode(response); } void OpsServer::respond_api(Connection& c, const ApiHandler& handler) { OpsResponse response; const std::string_view request = c.in; const auto line_end = request.find("\r\n"); const auto line = request.substr(0, line_end); const auto first = line.find(' '); const auto second = first == std::string_view::npos ? first : line.find(' ', first + 1); if (second == std::string_view::npos || line.substr(second + 1).rfind("HTTP/1.", 0) != 0) { c.out = encode({400, "bad request\n"}); return; } const auto method = line.substr(0, first); const auto path = line.substr(first + 1, second - first - 1); std::string_view authorization; bool has_body = false; // Header lines up to the blank line; names are case-insensitive. auto at = line_end + 2; while (at < request.size()) { const auto end = request.find("\r\n", at); if (end == std::string_view::npos || end == at) break; const auto header = request.substr(at, end - at); const auto colon = header.find(':'); if (colon != std::string_view::npos) { std::string name(header.substr(0, colon)); for (auto& ch : name) ch = static_cast(ch >= 'A' && ch <= 'Z' ? ch - 'A' + 'a' : ch); auto value = header.substr(colon + 1); while (!value.empty() && value.front() == ' ') value.remove_prefix(1); if (name == "authorization") authorization = value; else if ((name == "content-length" && value != "0") || name == "transfer-encoding") has_body = true; } at = end + 2; } if (method != "GET" && method != "POST") response = {405, "method not allowed\n"}; else if (path.empty() || path.front() != '/' || path.size() > 256 || !printable(path) || has_body) response = {400, "bad request\n"}; else response = handler({method, path, authorization}); if (response.body.size() > response_limit_) response = {500, "response too large\n"}; c.out = encode(response); } void OpsServer::serve(const OpsHandler& handler) { serve_with(max_request_bytes, [&](Connection& c) { respond(c, handler); }); } void OpsServer::serve_api(const ApiHandler& handler) { serve_with(max_api_request_bytes, [&](Connection& c) { respond_api(c, handler); }); } template void OpsServer::serve_with(std::size_t request_limit, const Answer& answer) { const auto accepted_at = Clock::now(); for (std::size_t attempt = 0; attempt < max_accepts_per_serve; ++attempt) { const int fd = ::accept4(fd_, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC); if (fd < 0) break; // EAGAIN: nothing pending (other errors: retried next call). if (connections_.size() >= max_connections) { ::close(fd); // Bounded: excess connections are refused, never queued. ++refused_; continue; } connections_.push_back({fd, {}, {}, 0, accepted_at + connection_deadline}); } const auto now = Clock::now(); // Deadlines are judged after the bounded accept work. for (auto it = connections_.begin(); it != connections_.end();) { auto& c = *it; bool done = false; // Read before expiring: a complete request that waited behind a bounded host // step is still answered; only incomplete or unsent work expires. if (c.out.empty()) { char chunk[1024]; const auto n = ::recv(c.fd, chunk, sizeof chunk, 0); if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { done = true; } else if (n > 0) { c.in.append(chunk, static_cast(n)); if (c.in.size() > request_limit) c.out = encode({431, "request too large\n"}); else if (c.in.find("\r\n\r\n") != std::string::npos) answer(c); } } if (!done && !c.out.empty()) { const auto n = ::send(c.fd, c.out.data() + c.sent, c.out.size() - c.sent, MSG_NOSIGNAL); if (n > 0) c.sent += static_cast(n); done = c.sent == c.out.size() || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR); } // Slow client: an incomplete request expires at the deadline; a response the // client will not take gets one more deadline, then is dropped. if (!done && now > c.deadline && (c.out.empty() || now > c.deadline + connection_deadline)) done = true; if (done) { ::close(c.fd); it = connections_.erase(it); } else { ++it; } } } } // namespace evo::server