#include #include #include #include #include #include // Track C1 platform boundary: the fallback HTTP server (sockets, poll) and the loopback test // client in this translation unit require a POSIX host (Linux/macOS/BSD). Void::Net covers // only the server transport, so Windows stays unsupported until both sides are portable. #if defined(_WIN32) #error "registry/service/HttpServer.cpp requires a POSIX host" #endif #include #include #include #include #include #include #include #include #include namespace Void::Build::Registry { namespace { Void::Result::Error sys_err(int err, std::string msg) { return Void::System::make_system_error(Void::System::map_errno_to_system_code(err), std::move(msg), err); } std::string to_lower(std::string_view s) { return Void::Str::to_lower_ascii(s); } std::string trim(std::string_view s) { return std::string{Void::Str::trim_ascii(s)}; } std::string url_decode(std::string_view s) { return Void::Encoding::Url::decode(s, /*plus_as_space=*/true).value_or(std::string{s}); } std::string default_reason(std::uint16_t status) { switch (status) { case 200: return "OK"; case 201: return "Created"; case 204: return "No Content"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 409: return "Conflict"; case 413: return "Payload Too Large"; case 422: return "Unprocessable Entity"; case 500: return "Internal Server Error"; default: return "OK"; } } bool send_all(int fd, std::string_view data) { std::size_t off = 0; while (off < data.size()) { const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL); if (n < 0) { if (errno == EINTR) { continue; } return false; } off += static_cast(n); } return true; } void parse_query(std::string_view qs, std::map> &out) { std::size_t pos = 0; while (pos < qs.size()) { const auto amp = qs.find('&', pos); const auto pair = qs.substr(pos, amp == std::string_view::npos ? std::string_view::npos : amp - pos); if (!pair.empty()) { const auto eq = pair.find('='); if (eq == std::string_view::npos) { out[url_decode(pair)] = ""; } else { out[url_decode(pair.substr(0, eq))] = url_decode(pair.substr(eq + 1)); } } if (amp == std::string_view::npos) { break; } pos = amp + 1; } } void parse_cookies(std::string_view header_val, std::map> &out) { std::size_t pos = 0; while (pos < header_val.size()) { const auto semi = header_val.find(';', pos); const auto part = header_val.substr( pos, semi == std::string_view::npos ? std::string_view::npos : semi - pos); const auto eq = part.find('='); if (eq != std::string_view::npos) { out[trim(part.substr(0, eq))] = trim(part.substr(eq + 1)); } if (semi == std::string_view::npos) { break; } pos = semi + 1; } } // Default security headers applied to every response regardless of transport (Plan 16/17). void apply_default_security_headers(HttpResponse &resp) { resp.headers.emplace("X-Content-Type-Options", "nosniff"); resp.headers.emplace("X-Frame-Options", "DENY"); resp.headers.emplace("Referrer-Policy", "no-referrer"); resp.headers.emplace( "Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"); } } // namespace std::optional HttpRequest::header(std::string_view lower_name) const noexcept { const auto it = headers.find(lower_name); if (it == headers.end()) { return std::nullopt; } return it->second; } std::optional HttpRequest::cookie(std::string_view name) const noexcept { const auto it = cookies.find(name); if (it == cookies.end()) { return std::nullopt; } return it->second; } HttpResponse HttpResponse::json(std::uint16_t status, std::string payload) { HttpResponse res; res.status = status; res.reason = default_reason(status); res.headers["Content-Type"] = "application/json; charset=utf-8"; res.body = std::move(payload); return res; } HttpResponse HttpResponse::error_json(std::uint16_t status, std::string_view code, std::string_view message) { return json(status, "{\"error\":{\"code\":" + Util::json_quote(code) + ",\"message\":" + Util::json_quote(message) + "}}\n"); } HttpServer::~HttpServer() noexcept { stop(); } Void::Result::Result HttpServer::start(const HttpServerOptions &options, HttpHandler handler) { stop(); options_ = options; handler_ = std::move(handler); #if defined(VBS_HAS_VOID_NET) // Track E4: serve through Void::Net when it is enabled, adapting its request/response types // to this registry's transport-neutral handler. Void::Net::HttpServerOptions net_options; net_options.bind_host = options.bind_address; net_options.port = options.port; net_options.max_header_bytes = options.max_header_bytes; net_options.max_body_bytes = options.max_body_bytes; net_server_.emplace(net_options); auto bridge = [handler = handler_](const Void::Net::ServerRequest &request) -> Void::Net::RouteResult { HttpRequest bridged; switch (request.method) { case Void::Net::Method::Get: bridged.method = "GET"; break; case Void::Net::Method::Post: bridged.method = "POST"; break; case Void::Net::Method::Put: bridged.method = "PUT"; break; case Void::Net::Method::Delete: bridged.method = "DELETE"; break; case Void::Net::Method::Patch: bridged.method = "PATCH"; break; case Void::Net::Method::Head: bridged.method = "HEAD"; break; case Void::Net::Method::Options: bridged.method = "OPTIONS"; break; } bridged.path = request.path; bridged.raw_target = request.query.empty() ? request.path : request.path + "?" + request.query; if (!request.query.empty()) { parse_query(request.query, bridged.query); } for (const auto &header : request.headers) { const auto lower = to_lower(header.name); if (lower == "cookie") { parse_cookies(header.value, bridged.cookies); } bridged.headers[lower] = header.value; } bridged.body = request.body; // HEAD is routed exactly like GET; the body is dropped but Content-Length is preserved. const bool head_only = request.method == Void::Net::Method::Head; if (head_only) { bridged.method = "GET"; } HttpResponse response = handler(bridged); apply_default_security_headers(response); if (head_only) { response.headers["Content-Length"] = std::to_string(response.body.size()); response.body.clear(); } Void::Net::ServerResponse net_response; net_response.status = response.status; for (const auto &[name, value] : response.headers) { net_response.headers.push_back(Void::Net::Header{name, value}); } for (const auto &cookie : response.set_cookies) { net_response.headers.push_back(Void::Net::Header{"Set-Cookie", cookie}); } net_response.body = response.body; return net_response; }; for (const auto method : {Void::Net::Method::Get, Void::Net::Method::Post, Void::Net::Method::Put, Void::Net::Method::Delete, Void::Net::Method::Patch, Void::Net::Method::Head, Void::Net::Method::Options}) { if (auto added = net_server_->add_route(method, "/*path", bridge); !added) { return std::unexpected{added.error()}; } } if (auto started = net_server_->start(); !started) { return std::unexpected{started.error()}; } bound_port_ = net_server_->bound_port(); running_.store(true); return {}; #else const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { return std::unexpected{sys_err(errno, "HttpServer: socket() failed")}; } int opt = 1; (void)::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_port = htons(options.port); if (::inet_pton(AF_INET, options.bind_address.c_str(), &addr.sin_addr) != 1) { (void)::close(fd); return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::invalid_argument, std::format("HttpServer: invalid IPv4 bind address '{}'", options.bind_address))}; } if (::bind(fd, reinterpret_cast(&addr), sizeof(addr)) != 0) { const int err = errno; (void)::close(fd); return std::unexpected{sys_err(err, "HttpServer: bind() failed")}; } if (::listen(fd, 64) != 0) { const int err = errno; (void)::close(fd); return std::unexpected{sys_err(err, "HttpServer: listen() failed")}; } sockaddr_in actual{}; socklen_t len = sizeof(actual); if (::getsockname(fd, reinterpret_cast(&actual), &len) == 0) { bound_port_ = ntohs(actual.sin_port); } listen_fd_ = fd; running_.store(true); accept_thread_ = std::thread([this] { accept_loop(); }); return {}; #endif } void HttpServer::stop() noexcept { #if defined(VBS_HAS_VOID_NET) if (net_server_) { net_server_->shutdown(); net_server_.reset(); running_.store(false); bound_port_ = 0; return; } #endif running_.store(false); if (listen_fd_ >= 0) { (void)::shutdown(listen_fd_, SHUT_RDWR); (void)::close(listen_fd_); listen_fd_ = -1; } if (accept_thread_.joinable()) { accept_thread_.join(); } bound_port_ = 0; } void HttpServer::accept_loop() { while (running_.load()) { struct pollfd pfd{listen_fd_, POLLIN, 0}; const int ready = ::poll(&pfd, 1, 50); if (ready <= 0) { continue; } const int client_fd = ::accept4(listen_fd_, nullptr, nullptr, SOCK_CLOEXEC); if (client_fd < 0) { continue; } // Handle client connection with bounded read timeout. handle_client(client_fd); (void)::close(client_fd); } } void HttpServer::handle_client(int client_fd) { struct timeval tv{10, 0}; (void)::setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); (void)::setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); bool suppress_body = false; auto write_response = [&](HttpResponse resp) { if (resp.reason.empty()) { resp.reason = default_reason(resp.status); } apply_default_security_headers(resp); // HEAD keeps the headers of the equivalent GET (including Content-Length) but no body. resp.headers["Content-Length"] = std::to_string(resp.body.size()); resp.headers["Connection"] = "close"; std::string wire = std::format("HTTP/1.1 {} {}\r\n", resp.status, resp.reason); for (const auto &[k, v] : resp.headers) { wire += k + ": " + v + "\r\n"; } for (const auto &cookie : resp.set_cookies) { wire += "Set-Cookie: " + cookie + "\r\n"; } wire += "\r\n"; if (!suppress_body) { wire += resp.body; } (void)send_all(client_fd, wire); }; std::string raw; std::array buf{}; std::size_t header_end = std::string::npos; while (header_end == std::string::npos) { const ssize_t n = ::recv(client_fd, buf.data(), buf.size(), 0); if (n <= 0) { return; } raw.append(buf.data(), static_cast(n)); header_end = raw.find("\r\n\r\n"); if (header_end == std::string::npos && raw.size() > options_.max_header_bytes) { write_response(HttpResponse::error_json(431, "headers_too_large", "HTTP headers exceed maximum size")); return; } } const std::string_view header_block{raw.data(), header_end}; const auto first_crlf = header_block.find("\r\n"); const auto req_line = header_block.substr(0, first_crlf); const auto sp1 = req_line.find(' '); const auto sp2 = sp1 == std::string_view::npos ? std::string_view::npos : req_line.find(' ', sp1 + 1); if (sp1 == std::string_view::npos || sp2 == std::string_view::npos) { write_response(HttpResponse::error_json(400, "bad_request", "malformed HTTP request line")); return; } HttpRequest req; req.method = std::string{req_line.substr(0, sp1)}; req.raw_target = std::string{req_line.substr(sp1 + 1, sp2 - sp1 - 1)}; const auto qpos = req.raw_target.find('?'); if (qpos == std::string::npos) { req.path = req.raw_target; } else { req.path = req.raw_target.substr(0, qpos); parse_query(std::string_view{req.raw_target}.substr(qpos + 1), req.query); } if (first_crlf != std::string_view::npos) { std::size_t pos = first_crlf + 2; while (pos < header_block.size()) { const auto next = header_block.find("\r\n", pos); const auto line = header_block.substr( pos, next == std::string_view::npos ? std::string_view::npos : next - pos); const auto colon = line.find(':'); if (colon != std::string_view::npos) { const auto name = to_lower(trim(line.substr(0, colon))); const auto val = trim(line.substr(colon + 1)); req.headers[name] = val; if (name == "cookie") { parse_cookies(val, req.cookies); } } if (next == std::string_view::npos) { break; } pos = next + 2; } } std::size_t content_length = 0; if (const auto cl = req.header("content-length")) { try { content_length = static_cast(std::stoull(std::string{*cl})); } catch (...) { write_response(HttpResponse::error_json(400, "bad_content_length", "invalid Content-Length header")); return; } } if (content_length > options_.max_body_bytes) { write_response(HttpResponse::error_json(413, "payload_too_large", "request body exceeds configured limit")); return; } req.body = raw.substr(header_end + 4); while (req.body.size() < content_length) { const std::size_t want = std::min(buf.size(), content_length - req.body.size()); const ssize_t n = ::recv(client_fd, buf.data(), want, 0); if (n <= 0) { write_response( HttpResponse::error_json(400, "truncated_body", "truncated HTTP request body")); return; } req.body.append(buf.data(), static_cast(n)); } if (req.body.size() > content_length) { req.body.resize(content_length); } // HEAD is routed exactly like GET; only the body is suppressed when writing. if (req.method == "HEAD") { suppress_body = true; req.method = "GET"; } try { write_response(handler_(req)); } catch (const std::exception &ex) { write_response(HttpResponse::error_json(500, "internal_error", ex.what())); } } Void::Result::Result send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target, const std::map> &headers, std::string_view body) { const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { return std::unexpected{sys_err(errno, "send_loopback_http: socket() failed")}; } Void::System::OwnedFd guard{fd}; sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_port = htons(port); (void)::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr); if (::connect(fd, reinterpret_cast(&addr), sizeof(addr)) != 0) { return std::unexpected{sys_err(errno, "send_loopback_http: connect() failed")}; } std::string req = std::format("{} {} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n" "Content-Length: {}\r\n", method, target, port, body.size()); for (const auto &[k, v] : headers) { req += k + ": " + v + "\r\n"; } req += "\r\n"; req += body; if (!send_all(fd, req)) { return std::unexpected{sys_err(errno, "send_loopback_http: send() failed")}; } std::string raw; std::array buf{}; for (;;) { const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0); if (n > 0) { raw.append(buf.data(), static_cast(n)); } else if (n == 0) { break; } else if (errno != EINTR) { return std::unexpected{sys_err(errno, "send_loopback_http: recv() failed")}; } } const auto hdr_end = raw.find("\r\n\r\n"); if (hdr_end == std::string::npos) { return std::unexpected{Void::System::make_system_error( Void::System::SystemErrorCode::io_error, "malformed HTTP response")}; } HttpClientResponse resp; const std::string_view header_block{raw.data(), hdr_end}; const auto first_crlf = header_block.find("\r\n"); const auto status_line = header_block.substr(0, first_crlf); const auto sp1 = status_line.find(' '); if (sp1 != std::string_view::npos) { resp.status = static_cast(std::stoi(std::string{status_line.substr(sp1 + 1, 3)})); } if (first_crlf != std::string_view::npos) { std::size_t pos = first_crlf + 2; while (pos < header_block.size()) { const auto next = header_block.find("\r\n", pos); const auto line = header_block.substr( pos, next == std::string_view::npos ? std::string_view::npos : next - pos); const auto colon = line.find(':'); if (colon != std::string_view::npos) { const auto name = to_lower(trim(line.substr(0, colon))); const auto val = trim(line.substr(colon + 1)); if (name == "set-cookie") { resp.set_cookies.push_back(val); } else { resp.headers[name] = val; } } if (next == std::string_view::npos) { break; } pos = next + 2; } } resp.body = raw.substr(hdr_end + 4); return resp; } } // namespace Void::Build::Registry