#include #include #include #include #include #include #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; } } } // 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); 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 {}; } void HttpServer::stop() noexcept { 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)); auto write_response = [&](HttpResponse resp) { if (resp.reason.empty()) { resp.reason = default_reason(resp.status); } // Default security headers (Plan 16/17). 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'"); 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"; 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); } 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