Net: expose peer/client addresses and trusted-proxy policy on ServerRequest (#57)

This commit is contained in:
faumaray committed 2026-12-04 10:04:14 +03:00
1 parent b3c1246291
commit 55a1399e01
4 files changed
+317

No files matched your search

+203
View File
@@ -74,6 +74,199 @@ namespace Void::Net
return s;
}
struct IpAddress {
int family{0};
std::array<std::byte, 16> bytes{};
auto operator<=>(const IpAddress&) const = default;
};
/// Parses a numeric IPv4/IPv6 literal. IPv4-mapped IPv6 addresses are
/// normalized to IPv4 so a dual-stack listener matches IPv4 CIDRs.
[[nodiscard]] std::optional<IpAddress>
parse_ip(std::string_view text) noexcept
{
if (text.empty() || text.size() >= INET6_ADDRSTRLEN + 8) {
return std::nullopt;
}
std::string owned{text};
IpAddress out;
in_addr v4{};
if (::inet_pton(AF_INET, owned.c_str(), &v4) == 1) {
out.family = AF_INET;
std::memcpy(out.bytes.data(), &v4, sizeof(v4));
return out;
}
in6_addr v6{};
if (::inet_pton(AF_INET6, owned.c_str(), &v6) != 1) {
return std::nullopt;
}
constexpr std::array<std::byte, 12> mapped_prefix{
std::byte{0}, std::byte{0}, std::byte{0}, std::byte{0},
std::byte{0}, std::byte{0}, std::byte{0}, std::byte{0},
std::byte{0}, std::byte{0}, std::byte{0xff}, std::byte{0xff}};
if (std::memcmp(v6.s6_addr, mapped_prefix.data(),
mapped_prefix.size()) == 0) {
out.family = AF_INET;
std::memcpy(out.bytes.data(), v6.s6_addr + 12, 4);
return out;
}
out.family = AF_INET6;
std::memcpy(out.bytes.data(), &v6, sizeof(v6));
return out;
}
struct TrustedRange {
IpAddress network;
int prefix{0};
};
[[nodiscard]] std::optional<TrustedRange>
parse_trusted_range(std::string_view text)
{
const std::size_t slash = text.find('/');
const auto parsed = parse_ip(text.substr(0, slash));
if (!parsed.has_value()) {
return std::nullopt;
}
const int max_prefix = parsed->family == AF_INET ? 32 : 128;
int prefix = max_prefix;
if (slash != std::string_view::npos) {
const std::string_view suffix = text.substr(slash + 1);
int value = 0;
const auto [ptr, ec] =
std::from_chars(suffix.data(), suffix.data() + suffix.size(),
value);
if (ec != std::errc{} || ptr != suffix.data() + suffix.size() ||
value < 0 || value > max_prefix) {
return std::nullopt;
}
prefix = value;
}
return TrustedRange{*parsed, prefix};
}
[[nodiscard]] bool ip_in_range(const IpAddress& address,
const TrustedRange& range) noexcept
{
if (address.family != range.network.family) {
return false;
}
const int full_bytes = range.prefix / 8;
const int remaining_bits = range.prefix % 8;
if (full_bytes > 0 &&
std::memcmp(address.bytes.data(), range.network.bytes.data(),
static_cast<std::size_t>(full_bytes)) != 0) {
return false;
}
if (remaining_bits == 0) {
return true;
}
const auto mask = static_cast<unsigned char>(
0xFFu << (8 - remaining_bits));
const auto a = static_cast<unsigned char>(
address.bytes[static_cast<std::size_t>(full_bytes)]);
const auto b = static_cast<unsigned char>(
range.network.bytes[static_cast<std::size_t>(full_bytes)]);
return (a & mask) == (b & mask);
}
/// True when `address` matches any configured trusted-proxy entry.
/// Unparsable configuration entries are ignored (fail closed).
[[nodiscard]] bool
is_trusted_proxy(std::string_view address,
const std::vector<std::string>& trusted) noexcept
{
if (trusted.empty() || address.empty()) {
return false;
}
const auto parsed = parse_ip(address);
if (!parsed.has_value()) {
return false;
}
for (const auto& entry : trusted) {
const auto range = parse_trusted_range(entry);
if (range.has_value() && ip_in_range(*parsed, *range)) {
return true;
}
}
return false;
}
[[nodiscard]] PeerInfo peer_info_of(int fd) noexcept
{
PeerInfo info;
sockaddr_storage ss{};
socklen_t length = sizeof(ss);
if (::getpeername(fd, reinterpret_cast<sockaddr*>(&ss), &length) != 0) {
return info;
}
std::array<char, INET6_ADDRSTRLEN> buffer{};
if (ss.ss_family == AF_INET) {
const auto* v4 = reinterpret_cast<const sockaddr_in*>(&ss);
info.port = ntohs(v4->sin_port);
if (::inet_ntop(AF_INET, &v4->sin_addr, buffer.data(),
buffer.size()) != nullptr) {
info.address = buffer.data();
}
} else if (ss.ss_family == AF_INET6) {
const auto* v6 = reinterpret_cast<const sockaddr_in6*>(&ss);
info.port = ntohs(v6->sin6_port);
if (::inet_ntop(AF_INET6, &v6->sin6_addr, buffer.data(),
buffer.size()) != nullptr) {
info.address = buffer.data();
}
}
return info;
}
/// Resolves the effective client from the immediate peer and the
/// X-Forwarded-For chain. The header is only consulted when the peer is a
/// configured trusted proxy; malformed hops invalidate the whole chain.
[[nodiscard]] PeerInfo
resolve_client(const PeerInfo& peer,
const std::vector<Header>& headers,
const std::vector<std::string>& trusted)
{
PeerInfo client = peer;
if (!is_trusted_proxy(peer.address, trusted)) {
return client;
}
std::string chain;
for (const auto& header : headers) {
if (equal_ascii_ci(header.name, "X-Forwarded-For")) {
if (!chain.empty()) {
chain += ',';
}
chain += header.value;
}
}
if (chain.empty()) {
return client;
}
std::vector<std::string> hops;
std::string_view rest = chain;
while (true) {
const std::size_t comma = rest.find(',');
const std::string_view token = trim_ows(rest.substr(0, comma));
if (token.empty() || !parse_ip(token).has_value()) {
return client;
}
hops.emplace_back(token);
if (comma == std::string_view::npos) {
break;
}
rest.remove_prefix(comma + 1);
}
std::size_t index = hops.size();
while (index > 0 && is_trusted_proxy(hops[index - 1], trusted)) {
--index;
}
client.address = hops[index == 0 ? 0 : index - 1];
client.port = 0;
return client;
}
[[nodiscard]] std::optional<Method>
parse_method(std::string_view token) noexcept
{
@@ -2009,6 +2202,7 @@ namespace Void::Net
OwnedFd fd_guard{raw_fd};
std::string rx_buf;
std::size_t rx_off = 0;
const PeerInfo peer = peer_info_of(fd_guard.get());
while (!stopping.load(std::memory_order_acquire)) {
// 1. Read request headers up to \r\n\r\n.
@@ -2208,6 +2402,9 @@ namespace Void::Net
ws_req.path = std::string{raw_path};
ws_req.headers = std::move(headers);
ws_req.query = std::string{raw_query};
ws_req.peer = peer;
ws_req.client = resolve_client(
peer, ws_req.headers, options.trusted_proxies);
auto hs = validate_websocket_upgrade_request(
ws_req, ws_match->options);
if (!hs.has_value()) {
@@ -2373,6 +2570,9 @@ namespace Void::Net
req.headers = std::move(headers);
req.parameters = std::move(streaming_match->second);
req.query = std::string{raw_query};
req.peer = peer;
req.client = resolve_client(
peer, req.headers, options.trusted_proxies);
auto route_res =
streaming_match->first(req, body_reader);
@@ -2443,6 +2643,9 @@ namespace Void::Net
req.headers = std::move(headers);
req.body = std::move(body_str);
req.query = std::string{raw_query};
req.peer = peer;
req.client = resolve_client(
peer, req.headers, options.trusted_proxies);
auto dispatched = router->dispatch(req);
if (!dispatched.has_value()) {