fix correctness: IPv6 :: parsing, AF_INET6 on macOS, health check units,

DHT heap fallback
This commit is contained in:
2026-02-11 14:20:55 -03:00
parent e45bffbd8b
commit 137469c3e1
5 changed files with 190 additions and 49 deletions

View File

@@ -145,36 +145,42 @@ pub const Ipv6Address = struct {
} }
pub fn fromString(str: []const u8) Error!Ipv6Address { pub fn fromString(str: []const u8) Error!Ipv6Address {
var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 }; // Two-pass parsing for :: compression
var group_idx: usize = 0; // Pass 1: parse groups into front/back arrays around ::
var front: [8]u16 = [_]u16{0} ** 8;
var back: [8]u16 = [_]u16{0} ** 8;
var front_count: usize = 0;
var back_count: usize = 0;
var found_double_colon = false;
var current_val: u16 = 0; var current_val: u16 = 0;
var digit_count: usize = 0; var digit_count: usize = 0;
var i: usize = 0; var i: usize = 0;
// Handle leading ::
if (str.len >= 2 and str[0] == ':' and str[1] == ':') {
found_double_colon = true;
i = 2;
}
while (i < str.len) : (i += 1) { while (i < str.len) : (i += 1) {
const c = str[i]; const c = str[i];
if (c == ':') { if (c == ':') {
if (i + 1 < str.len and str[i + 1] == ':') { // Write current group
// Handle :: (compressed zeros) const target = if (found_double_colon) &back else &front;
if (group_idx > 0 and digit_count > 0) { const count = if (found_double_colon) &back_count else &front_count;
addr.bytes[group_idx * 2] = @intCast(current_val >> 8); if (count.* >= 8) return Error.AddressParseError;
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF); target[count.*] = current_val;
group_idx += 1; count.* += 1;
}
// Skip remaining groups for compressed zeros
i += 1;
current_val = 0;
digit_count = 0;
continue;
}
if (group_idx >= 8) return Error.AddressParseError;
addr.bytes[group_idx * 2] = @intCast(current_val >> 8);
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF);
group_idx += 1;
current_val = 0; current_val = 0;
digit_count = 0; digit_count = 0;
if (i + 1 < str.len and str[i + 1] == ':') {
if (found_double_colon) return Error.AddressParseError; // only one :: allowed
found_double_colon = true;
i += 1; // skip second colon
}
} else { } else {
const digit = switch (c) { const digit: u16 = switch (c) {
'0'...'9' => c - '0', '0'...'9' => c - '0',
'a'...'f' => c - 'a' + 10, 'a'...'f' => c - 'a' + 10,
'A'...'F' => c - 'A' + 10, 'A'...'F' => c - 'A' + 10,
@@ -186,10 +192,33 @@ pub const Ipv6Address = struct {
} }
} }
// Handle last group // Write final group
if (digit_count > 0 and group_idx < 8) { if (digit_count > 0) {
addr.bytes[group_idx * 2] = @intCast(current_val >> 8); const target = if (found_double_colon) &back else &front;
addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF); const count = if (found_double_colon) &back_count else &front_count;
if (count.* >= 8) return Error.AddressParseError;
target[count.*] = current_val;
count.* += 1;
}
// Assemble: front groups + zero padding + back groups
const total = front_count + back_count;
if (found_double_colon) {
if (total > 8) return Error.AddressParseError;
} else {
if (total != 8) return Error.AddressParseError;
}
var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 };
for (front[0..front_count], 0..) |val, g| {
addr.bytes[g * 2] = @intCast(val >> 8);
addr.bytes[g * 2 + 1] = @intCast(val & 0xFF);
}
const back_start = 8 - back_count;
for (back[0..back_count], 0..) |val, g| {
const idx = back_start + g;
addr.bytes[idx * 2] = @intCast(val >> 8);
addr.bytes[idx * 2 + 1] = @intCast(val & 0xFF);
} }
return addr; return addr;
@@ -627,9 +656,9 @@ pub const Address = struct {
/// Get address family constant for socket operations /// Get address family constant for socket operations
pub fn getSocketFamily(self: Address) u16 { pub fn getSocketFamily(self: Address) u16 {
return switch (self.family) { return switch (self.family) {
.ipv4 => 2, // AF_INET .ipv4 => posix.AF.INET,
.ipv6 => 10, // AF_INET6 .ipv6 => posix.AF.INET6,
.unix => 1, // AF_UNIX .unix => posix.AF.UNIX,
.custom => 0, .custom => 0,
}; };
} }

View File

@@ -432,12 +432,14 @@ pub const Connection = struct {
// This was the last reference // This was the last reference
return true; return true;
} }
// Safety check: underflow is an invariant violation (double-free) // Defensive check: detect double-free bugs without crashing.
// Dumps a stack trace pointing to the exact call site, then returns
// an error so the application can continue running.
if (old_count == 0) { if (old_count == 0) {
// fetchSub already wrapped the counter — this is unrecoverable corruption. _ = self.ref_count.fetchAdd(1, .acq_rel); // undo the wrapping fetchSub
// Panic immediately so the bug is caught in development rather than std.log.err("BUG: Connection ref count underflow (double-free). Stack trace:", .{});
// silently propagated through the call chain. std.debug.dumpCurrentStackTrace(@returnAddress());
@panic("Connection reference count underflow: double-free detected"); return Error.InternalError;
} }
return false; return false;
} }
@@ -734,7 +736,7 @@ pub const Connection = struct {
/// Thread-safe: uses socket_mutex to protect socket access /// Thread-safe: uses socket_mutex to protect socket access
pub fn checkHealth(self: *Connection) HealthCheckResult { pub fn checkHealth(self: *Connection) HealthCheckResult {
self.stats.recordHealthCheck(); self.stats.recordHealthCheck();
self.last_health_check = std.time.timestamp(); self.last_health_check = std.time.milliTimestamp();
// Acquire socket mutex to prevent race with connect/disconnect // Acquire socket mutex to prevent race with connect/disconnect
self.socket_mutex.lock(); self.socket_mutex.lock();
@@ -845,7 +847,7 @@ pub const Connection = struct {
/// Check if connection needs health check /// Check if connection needs health check
pub fn needsHealthCheck(self: *const Connection) bool { pub fn needsHealthCheck(self: *const Connection) bool {
const now = std.time.timestamp(); const now = std.time.milliTimestamp();
return (now - self.last_health_check) >= self.config.health_check_interval; return (now - self.last_health_check) >= self.config.health_check_interval;
} }

View File

@@ -21,6 +21,12 @@ const protocol = @import("protocol");
// Import P2P type from sibling module // Import P2P type from sibling module
const P2P = @import("p2p.zig").P2P; const P2P = @import("p2p.zig").P2P;
// SECURITY: Limits for DHT message deserialization to prevent DoS
/// Maximum number of nodes in a single DHT response (matches k_bucket_size)
const MAX_DHT_NODES_PER_RESPONSE: u32 = 20;
/// Maximum size of a DHT value in bytes (1 MB)
const MAX_DHT_VALUE_SIZE: u32 = 1024 * 1024;
// ========================================================================= // =========================================================================
// DHT (Distributed Hash Table) API // DHT (Distributed Hash Table) API
// ========================================================================= // =========================================================================
@@ -263,6 +269,23 @@ pub const DhtMsgType = enum(u8) {
find_value_response = 0x13, find_value_response = 0x13,
}; };
/// Compute the serialized size of a DHT message (for heap allocation when stack buffer is too small)
fn dhtMessageSize(msg: protocol.message.Message) ?usize {
const node_size = 32 + 46 + 1;
return switch (msg) {
.dht_find_node => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_store => |m| 1 + 8 + 32 + 32 + 4 + 4 + m.value.len + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_value => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)),
.dht_find_node_response => |m| 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_store_response => |m| 1 + 8 + 1 + 1 + @as(usize, @min(m.observed_addr_len, 18)),
.dht_find_value_response => |m| blk: {
const value_len = if (m.value) |v| v.len else 0;
break :blk 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18));
},
else => null,
};
}
/// Serialize a DHT message to simple binary format /// Serialize a DHT message to simple binary format
/// Format: [1 byte type][8 bytes request_id][32 bytes sender_id][payload...] /// Format: [1 byte type][8 bytes request_id][32 bytes sender_id][payload...]
/// Public for testing IP Reflection variable-length encoding /// Public for testing IP Reflection variable-length encoding
@@ -491,6 +514,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
offset += 4; offset += 4;
const value_len = std.mem.readInt(u32, data[offset..][0..4], .big); const value_len = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4; offset += 4;
// SECURITY: Reject excessive value sizes to prevent DoS
if (value_len > MAX_DHT_VALUE_SIZE) return null;
if (data.len < offset + value_len) return null; if (data.len < offset + value_len) return null;
// Allocate and copy value // Allocate and copy value
const value = allocator.dupe(u8, data[offset..][0..value_len]) catch return null; const value = allocator.dupe(u8, data[offset..][0..value_len]) catch return null;
@@ -559,8 +584,12 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
offset += 8; offset += 8;
const node_count = std.mem.readInt(u32, data[offset..][0..4], .big); const node_count = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4; offset += 4;
// SECURITY: Reject excessive node counts to prevent DoS
if (node_count > MAX_DHT_NODES_PER_RESPONSE) return null;
const node_size = 32 + 46 + 1; const node_size = 32 + 46 + 1;
if (data.len < offset + (node_count * node_size) + 1) return null; // SECURITY: Use checked multiplication to prevent integer overflow
const total_node_bytes = std.math.mul(usize, node_count, node_size) catch return null;
if (data.len < offset + total_node_bytes + 1) return null;
// Allocate nodes array // Allocate nodes array
const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null; const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null;
for (0..node_count) |i| { for (0..node_count) |i| {
@@ -625,6 +654,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
offset += 1; offset += 1;
const value_len = std.mem.readInt(u32, data[offset..][0..4], .big); const value_len = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4; offset += 4;
// SECURITY: Reject excessive value sizes to prevent DoS
if (value_len > MAX_DHT_VALUE_SIZE) return null;
if (data.len < offset + value_len + 4 + 1) return null; if (data.len < offset + value_len + 4 + 1) return null;
// Read value (may be empty) // Read value (may be empty)
const value: ?[]const u8 = if (value_len > 0) blk: { const value: ?[]const u8 = if (value_len > 0) blk: {
@@ -634,10 +665,26 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
offset += value_len; offset += value_len;
const node_count = std.mem.readInt(u32, data[offset..][0..4], .big); const node_count = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4; offset += 4;
// SECURITY: Reject excessive node counts to prevent DoS
if (node_count > MAX_DHT_NODES_PER_RESPONSE) {
if (value) |v| allocator.free(v);
return null;
}
const node_size = 32 + 46 + 1; const node_size = 32 + 46 + 1;
if (data.len < offset + (node_count * node_size) + 1) return null; // SECURITY: Use checked multiplication to prevent integer overflow
const total_node_bytes = std.math.mul(usize, node_count, node_size) catch {
if (value) |v| allocator.free(v);
return null;
};
if (data.len < offset + total_node_bytes + 1) {
if (value) |v| allocator.free(v);
return null;
}
// Allocate nodes array // Allocate nodes array
const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null; const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch {
if (value) |v| allocator.free(v);
return null;
};
for (0..node_count) |i| { for (0..node_count) |i| {
nodes[i] = .{ nodes[i] = .{
.node_id = data[offset..][0..32].*, .node_id = data[offset..][0..32].*,
@@ -713,8 +760,27 @@ pub fn sendDhtMessageImpl(p2p: *P2P, dht_node_id: [32]u8, msg: protocol.message.
}; };
// Use simple binary serialization (no HMAC - Noise transport provides security) // Use simple binary serialization (no HMAC - Noise transport provides security)
var buffer: [4096]u8 = undefined; // Use stack buffer for small messages, heap for large (e.g. dht_store with big values)
const len = serializeDhtMessage(msg, &buffer) orelse { var stack_buffer: [4096]u8 = undefined;
var heap_buffer: ?[]u8 = null;
defer if (heap_buffer) |hb| p2p.allocator.free(hb);
var buffer: []u8 = &stack_buffer;
// Try stack buffer first; if too small, compute needed size and heap-allocate
if (serializeDhtMessage(msg, buffer) == null) {
const needed = dhtMessageSize(msg) orelse {
std.log.warn("DHT: Failed to compute message size", .{});
return false;
};
heap_buffer = p2p.allocator.alloc(u8, needed) catch {
std.log.warn("DHT: Failed to allocate {d} bytes for message", .{needed});
return false;
};
buffer = heap_buffer.?;
}
const len = serializeDhtMessage(msg, buffer) orelse {
std.log.warn("DHT: Failed to serialize message", .{}); std.log.warn("DHT: Failed to serialize message", .{});
return false; return false;
}; };

View File

@@ -710,9 +710,18 @@ pub const MessageSerializer = struct {
fn getPayloadSize(self: *MessageSerializer, msg: message.Message) usize { fn getPayloadSize(self: *MessageSerializer, msg: message.Message) usize {
_ = self; _ = self;
return switch (msg) { return switch (msg) {
.discovery_hello => 2 + 4 + @sizeOf(message.NetworkAddress), .discovery_hello => |hello| blk: {
.discovery_response => 8 + 4 + @sizeOf(message.NetworkAddress), const base = 2 + 4 + @sizeOf(message.NetworkAddress);
.discovery_announce => 4 + @sizeOf(message.NetworkAddress), break :blk if (hello.isSigned()) base + 64 + 32 + 8 else base;
},
.discovery_response => |resp| blk: {
const base = 8 + 4 + @sizeOf(message.NetworkAddress);
break :blk if (resp.isSigned()) base + 64 + 32 + 8 else base;
},
.discovery_announce => |announce| blk: {
const base = 4 + @sizeOf(message.NetworkAddress) + 1; // +1 for TTL
break :blk if (announce.isSigned()) base + 64 + 32 + 8 else base;
},
.topology_query => 8 + 1, .topology_query => 8 + 1,
.topology_response => |resp| blk: { .topology_response => |resp| blk: {
// Safe addition with overflow check // Safe addition with overflow check
@@ -959,32 +968,67 @@ pub const MessageSerializer = struct {
switch (msg) { switch (msg) {
.discovery_hello => |hello| { .discovery_hello => |hello| {
// SECURITY: Safe bounds check with overflow protection // Base fields: version(2) + capabilities(4) + address
const required = safeAdd(safeAdd(2, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; const base = safeAdd(safeAdd(2, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength;
const sig_size: usize = if (hello.isSigned()) 64 + 32 + 8 else 0;
const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength;
try checkBounds(buffer, offset, required); try checkBounds(buffer, offset, required);
@memcpy(buffer[offset..offset + 2], std.mem.asBytes(&hello.version)); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&hello.version));
offset += 2; offset += 2;
@memcpy(buffer[offset..offset + 4], std.mem.asBytes(&hello.capabilities)); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&hello.capabilities));
offset += 4; offset += 4;
@memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&hello.address)); @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&hello.address));
offset += @sizeOf(message.NetworkAddress);
// Serialize signature fields if signed
if (hello.isSigned()) {
@memcpy(buffer[offset..][0..64], &hello.signature);
offset += 64;
@memcpy(buffer[offset..][0..32], &hello.signer_id);
offset += 32;
std.mem.writeInt(i64, buffer[offset..][0..8], hello.timestamp, .little);
}
}, },
.discovery_response => |resp| { .discovery_response => |resp| {
// SECURITY: Safe bounds check with overflow protection // Base fields: original_id(8) + capabilities(4) + address
const required = safeAdd(safeAdd(8, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; const base = safeAdd(safeAdd(8, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength;
const sig_size: usize = if (resp.isSigned()) 64 + 32 + 8 else 0;
const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength;
try checkBounds(buffer, offset, required); try checkBounds(buffer, offset, required);
@memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.original_id)); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.original_id));
offset += 8; offset += 8;
@memcpy(buffer[offset..offset + 4], std.mem.asBytes(&resp.capabilities)); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&resp.capabilities));
offset += 4; offset += 4;
@memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&resp.address)); @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&resp.address));
offset += @sizeOf(message.NetworkAddress);
// Serialize signature fields if signed
if (resp.isSigned()) {
@memcpy(buffer[offset..][0..64], &resp.signature);
offset += 64;
@memcpy(buffer[offset..][0..32], &resp.signer_id);
offset += 32;
std.mem.writeInt(i64, buffer[offset..][0..8], resp.timestamp, .little);
}
}, },
.discovery_announce => |announce| { .discovery_announce => |announce| {
// SECURITY: Safe bounds check with overflow protection // Base fields: capabilities(4) + address + ttl(1)
const required = safeAdd(4, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; const base = safeAdd(safeAdd(4, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength, 1) orelse return SerializationError.InvalidLength;
const sig_size: usize = if (announce.isSigned()) 64 + 32 + 8 else 0;
const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength;
try checkBounds(buffer, offset, required); try checkBounds(buffer, offset, required);
@memcpy(buffer[offset..offset + 4], std.mem.asBytes(&announce.capabilities)); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&announce.capabilities));
offset += 4; offset += 4;
@memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&announce.address)); @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&announce.address));
offset += @sizeOf(message.NetworkAddress);
buffer[offset] = announce.ttl;
offset += 1;
// Serialize signature fields if signed
if (announce.isSigned()) {
@memcpy(buffer[offset..][0..64], &announce.signature);
offset += 64;
@memcpy(buffer[offset..][0..32], &announce.signer_id);
offset += 32;
std.mem.writeInt(i64, buffer[offset..][0..8], announce.timestamp, .little);
}
}, },
.topology_query => |query| { .topology_query => |query| {
// SECURITY: Safe bounds check with overflow protection // SECURITY: Safe bounds check with overflow protection

View File

@@ -169,7 +169,7 @@ test "getPayloadSizePublic discovery_announce" {
var ser = MessageSerializer.initInsecureForTesting(allocator); var ser = MessageSerializer.initInsecureForTesting(allocator);
const addr = message.NetworkAddress{ .ip = [_]u8{0} ** 16, .port = 8080 }; const addr = message.NetworkAddress{ .ip = [_]u8{0} ** 16, .port = 8080 };
const msg = message.Message{ .discovery_announce = message.DiscoveryAnnounce.init(0, addr) }; const msg = message.Message{ .discovery_announce = message.DiscoveryAnnounce.init(0, addr) };
try testing.expectEqual(@as(usize, 4 + @sizeOf(message.NetworkAddress)), ser.getPayloadSizePublic(msg)); try testing.expectEqual(@as(usize, 4 + @sizeOf(message.NetworkAddress) + 1), ser.getPayloadSizePublic(msg)); // +1 for TTL
} }
test "getPayloadSizePublic topology_query" { test "getPayloadSizePublic topology_query" {