bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

View File

@@ -16,8 +16,8 @@ pub const RateLimiter = struct {
max_tokens: u64,
/// Token refill rate (tokens per second)
refill_rate: u64,
/// Last refill timestamp (nanoseconds)
last_refill: std.atomic.Value(i128),
/// Last refill timestamp (milliseconds) - using i64 for cross-platform atomic support
last_refill: std.atomic.Value(i64),
/// Mutex for non-atomic operations
mutex: std.Thread.Mutex = .{},
@@ -26,7 +26,7 @@ pub const RateLimiter = struct {
.tokens = std.atomic.Value(u64).init(config.burst_size),
.max_tokens = config.burst_size,
.refill_rate = config.tokens_per_second,
.last_refill = std.atomic.Value(i128).init(time.nanoTimestamp()),
.last_refill = std.atomic.Value(i64).init(time.milliTimestamp()),
};
}
@@ -79,14 +79,14 @@ pub const RateLimiter = struct {
/// Refill tokens based on elapsed time
fn refill(self: *RateLimiter) void {
const now = time.nanoTimestamp();
const now = time.milliTimestamp();
const last = self.last_refill.load(.acquire);
const elapsed_ns = now - last;
const elapsed_ms = now - last;
if (elapsed_ns <= 0) return;
if (elapsed_ms <= 0) return;
// Calculate tokens to add (using nanoseconds for precision)
const elapsed_seconds = @as(u64, @intCast(@divFloor(elapsed_ns, time.ns_per_s)));
// Calculate tokens to add (using milliseconds)
const elapsed_seconds = @as(u64, @intCast(@divFloor(elapsed_ms, time.ms_per_s)));
if (elapsed_seconds == 0) return;
const new_tokens = elapsed_seconds * self.refill_rate;

View File

@@ -838,13 +838,22 @@ pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
var stat: Statfs = undefined;
// Use extern fstatfs for both Linux and macOS
const fstatfs_impl = struct {
pub extern "c" fn fstatfs(fd: c_int, buf: *anyopaque) c_int;
// Use fstatfs - requires libc on Linux, always available on macOS
const result = if (builtin.os.tag == .macos or builtin.link_libc) blk: {
const fstatfs_impl = struct {
pub extern "c" fn fstatfs(fd: c_int, buf: *anyopaque) c_int;
};
break :blk fstatfs_impl.fstatfs(fd, &stat);
} else if (builtin.os.tag == .linux) blk: {
// Use Linux syscall directly when libc is not linked
const linux = std.os.linux;
const raw_result = linux.syscall2(.fstatfs, @as(usize, @bitCast(@as(isize, fd))), @intFromPtr(&stat));
break :blk if (raw_result == 0) @as(c_int, 0) else @as(c_int, -1);
} else blk: {
// Skip check on unsupported platforms
break :blk @as(c_int, -1);
};
const result = fstatfs_impl.fstatfs(fd, &stat);
if (result != 0) {
std.log.warn("Failed to get filesystem stats for {s}", .{dir_path});
return; // Allow operation to proceed
@@ -1104,13 +1113,8 @@ pub const FileWriter = struct {
if (builtin.os.tag == .linux) {
// FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size
const FALLOC_FL_KEEP_SIZE = 0x01;
const fd = file.handle;
const result = std.os.linux.syscall(.fallocate, .{
@as(usize, @intCast(fd)),
@as(usize, FALLOC_FL_KEEP_SIZE),
@as(usize, 0), // offset
@as(usize, @intCast(size)),
});
const fd: i32 = @intCast(file.handle);
const result = std.os.linux.fallocate(fd, FALLOC_FL_KEEP_SIZE, 0, @intCast(size));
if (result == 0) {
std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)});
return;

View File

@@ -16,8 +16,9 @@ pub const Defaults = struct {
/// Time to live for publications (seconds)
pub const publication_ttl: u32 = 300; // 5 minutes
/// Buffer time after seeing peer's publication (milliseconds)
pub const rendezvous_buffer_ms: i64 = 500;
/// Buffer time after publication timestamp for rendezvous (milliseconds)
/// Must be long enough for both peers to find each other's publications
pub const rendezvous_buffer_ms: i64 = 5000; // 5 seconds
/// Timeout waiting for peer's publication (milliseconds)
pub const discovery_timeout_ms: u64 = 30_000; // 30 seconds

View File

@@ -208,6 +208,12 @@ pub const MWP = struct {
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) {
// CRITICAL: Must call p2p.update() to process incoming network messages
// Without this, DHT responses are never received
self.p2p.update() catch |err| {
std.log.warn("MWP: p2p.update() failed: {}", .{err});
};
if (try self.findPeer(their_pubkey)) |publication| {
return publication;
}
@@ -249,6 +255,21 @@ pub const MWP = struct {
return self.attemptHolePunch(peer_publication.addresses, params, options);
}
/// Connect using an existing publication (for listeners who already published)
/// Use this when you've already published and found the peer's publication.
pub fn connectWithPublication(
self: *MWP,
our_publication: MeetingPublication,
peer_publication: MeetingPublication,
options: ConnectOptions,
) ConnectionResult {
// Compute rendezvous params from both publications
const params = computeRendezvousParamsFromPubs(our_publication, peer_publication, options.rendezvous_buffer_ms);
// Attempt hole punch
return self.attemptHolePunch(peer_publication.addresses, params, options);
}
fn computeRendezvousParamsFromPubs(our_pub: MeetingPublication, their_pub: MeetingPublication, buffer_ms: i64) RendezvousParams {
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
if (std.mem.lessThan(u8, &our_pub.nonce, &their_pub.nonce)) {
@@ -261,7 +282,11 @@ pub const MWP = struct {
var shared_randomness: [32]u8 = undefined;
hasher.final(&shared_randomness);
const rendezvous_time = std.time.milliTimestamp() + buffer_ms;
// CRITICAL: Rendezvous time must be the same for both peers
// Use the later publication timestamp plus buffer, so both peers agree
const later_timestamp = @max(our_pub.timestamp, their_pub.timestamp);
const rendezvous_time = later_timestamp + buffer_ms;
const port_offset = std.mem.readInt(u16, shared_randomness[0..2], .little);
const port_hint = 49152 + (port_offset % 16384);
@@ -297,6 +322,23 @@ pub const MWP = struct {
};
defer std.posix.close(fd);
// Enable address reuse so we can bind even if the port was recently used
const enable: c_int = 1;
_ = std.posix.setsockopt(fd, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, std.mem.asBytes(&enable)) catch {};
// Bind to our published address so we can receive on the right port
// This is critical for hole punching - we must send FROM the port we published
if (self.our_addresses.len > 0) {
const our_addr = self.our_addresses[0];
if (our_addr.addr_type == .ipv4) {
const bind_addr = std.net.Address.initIp4(our_addr.ip.v4, our_addr.port);
std.posix.bind(fd, &bind_addr.any, bind_addr.getOsSockLen()) catch |err| {
std.log.warn("MWP: Failed to bind to published address: {}", .{err});
// Continue anyway - might work with ephemeral port in some cases
};
}
}
// Set non-blocking
const flags = std.posix.fcntl(fd, std.posix.F.GETFL, 0) catch {
return .{ .hole_punch_failed = .all_addresses_failed };
@@ -321,12 +363,18 @@ pub const MWP = struct {
for (target_addresses) |addr| {
if (addr.addr_type == .ipv4) {
const sock_addr = std.net.Address.initIp4(addr.ip.v4, addr.port);
_ = std.posix.sendto(fd, &packet, 0, &sock_addr.any, sock_addr.getOsSockLen()) catch continue;
const sent = std.posix.sendto(fd, &packet, 0, &sock_addr.any, sock_addr.getOsSockLen()) catch |err| {
std.log.warn("MWP: sendto failed: {}", .{err});
continue;
};
std.log.info("MWP: Sent {d} bytes to {d}.{d}.{d}.{d}:{d}", .{
sent, addr.ip.v4[0], addr.ip.v4[1], addr.ip.v4[2], addr.ip.v4[3], addr.port,
});
}
}
// Wait for response
const deadline = std.time.milliTimestamp() + 2000; // 2 second timeout
// Wait for response - must be long enough for peer to find us and respond
const deadline = std.time.milliTimestamp() + 30000; // 30 second timeout for hole punch
var recv_buf: [256]u8 = undefined;
while (std.time.milliTimestamp() < deadline) {
@@ -338,19 +386,36 @@ pub const MWP = struct {
std.Thread.sleep(1 * std.time.ns_per_ms);
continue;
}
std.log.warn("MWP: recvfrom error: {}", .{err});
continue;
};
if (len < 124) continue;
std.log.info("MWP: Received {d} bytes", .{len});
if (len < 124) {
std.log.warn("MWP: Packet too small: {d} bytes (need 124)", .{len});
continue;
}
// Deserialize and verify packet
const recv_pkt = HolePunchPacket.deserialize(&recv_buf) catch continue;
const recv_pkt = HolePunchPacket.deserialize(&recv_buf) catch |err| {
std.log.warn("MWP: Failed to deserialize packet: {}", .{err});
continue;
};
// Verify connection ID
if (!std.mem.eql(u8, &recv_pkt.connection_id, &params.connection_id)) continue;
if (!std.mem.eql(u8, &recv_pkt.connection_id, &params.connection_id)) {
std.log.warn("MWP: Connection ID mismatch", .{});
continue;
}
// Verify signature
if (!recv_pkt.verify()) continue;
if (!recv_pkt.verify()) {
std.log.warn("MWP: Signature verification failed", .{});
continue;
}
std.log.info("MWP: Packet verified successfully!", .{});
// Extract remote address
const family = src_addr.family;

View File

@@ -414,6 +414,8 @@ pub const PendingResponse = struct {
query_type: QueryType,
sent_at: i64,
responded: bool = false,
/// Key being searched (for FIND_VALUE queries)
search_key: ?[32]u8 = null,
pub const QueryType = enum {
find_node,
@@ -583,6 +585,11 @@ pub const DhtCoordinator = struct {
/// SECURITY: Check rate limit for a peer
/// Returns error if rate limit exceeded
fn checkPeerRateLimit(self: *DhtCoordinator, peer_id: NodeId) DhtError!void {
// Skip rate limiting in development/insecure mode
if (!self.isSecureMode()) {
return;
}
const now = std.time.timestamp();
const now_ms = std.time.milliTimestamp();
@@ -626,6 +633,11 @@ pub const DhtCoordinator = struct {
/// SECURITY: Verify message authentication and apply TOFU
fn verifyMessageAuth(self: *DhtCoordinator, sender_id: NodeId, auth: ?SignedDhtMessage, msg_type: u8, payload: []const u8, request_id: u64) DhtError!void {
const auth_data = auth orelse {
// In development/insecure mode, allow unauthenticated messages
if (!self.isSecureMode()) {
std.log.debug("DHT: Processing unauthenticated message (insecure mode)", .{});
return;
}
std.log.err("DHT SECURITY: Message rejected - no authentication provided", .{});
return DhtError.MissingSignature;
};
@@ -1284,6 +1296,7 @@ pub const DhtCoordinator = struct {
.target = node_id,
.query_type = .find_value,
.sent_at = std.time.timestamp(),
.search_key = key,
});
sent_count += 1;
@@ -1305,14 +1318,22 @@ pub const DhtCoordinator = struct {
self.mutex.lock();
defer self.mutex.unlock();
// Mark the request as completed
// Get the search key from pending responses
var search_key: ?[32]u8 = null;
if (self.pending_responses.fetchRemove(response.request_id)) |pending| {
_ = pending;
search_key = pending.value.search_key;
}
// If value was found, store it locally and return
// If value was found, cache it locally for future findValue() calls
if (response.found) {
if (response.value) |value| {
// Cache locally if we know the key
if (search_key) |key| {
// Store unsigned since we're caching a remote response
self.storeLocalUnsigned(key, value, 300, self.local_id) catch |err| {
std.log.debug("DHT: Failed to cache FIND_VALUE result: {}", .{err});
};
}
// Return a copy of the value
return try self.allocator.dupe(u8, value);
}
@@ -1529,74 +1550,81 @@ pub const DhtCoordinator = struct {
}
// SECURITY: Verify value signature (proves publisher ownership)
const value_sig = msg.value_signature orelse {
std.log.err("DHT STORE rejected: no value signature provided", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature" };
// In development/insecure mode, allow storing without signatures
if (!self.isSecureMode()) {
// Development mode: store without signature verification
std.log.debug("DHT: Storing value in insecure mode (no signature verification)", .{});
try self.storeLocalUnsigned(msg.key, msg.value, msg.ttl, msg.sender_id);
} else {
const value_sig = msg.value_signature orelse {
std.log.err("DHT STORE rejected: no value signature provided", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing value signature",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing value signature",
.auth = auth,
};
};
// Get the sender's identity key (already verified via TOFU)
const identity_key = if (msg.auth) |auth_data| auth_data.identity_key else {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key" };
// Get the sender's identity key (already verified via TOFU)
const identity_key = if (msg.auth) |auth_data| auth_data.identity_key else {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing identity key",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing identity key",
.auth = auth,
};
};
// Verify value signature
const value_signing_data = DhtStore.createValueSigningData(self.allocator, msg.key, msg.value, msg.ttl) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" };
// Verify value signature
const value_signing_data = DhtStore.createValueSigningData(self.allocator, msg.key, msg.value, msg.ttl) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Internal error",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Internal error",
.auth = auth,
};
};
defer self.allocator.free(value_signing_data);
defer self.allocator.free(value_signing_data);
const sig = Ed25519.Signature.fromBytes(value_sig);
const pubkey = Ed25519.PublicKey.fromBytes(identity_key) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key" };
const sig = Ed25519.Signature.fromBytes(value_sig);
const pubkey = Ed25519.PublicKey.fromBytes(identity_key) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Invalid identity key",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Invalid identity key",
.auth = auth,
};
};
sig.verify(value_signing_data, pubkey) catch {
std.log.err("DHT STORE rejected: value signature verification failed", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature failed" };
sig.verify(value_signing_data, pubkey) catch {
std.log.err("DHT STORE rejected: value signature verification failed", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature failed" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Value signature verification failed",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Value signature verification failed",
.auth = auth,
};
};
// Store the value with signature for future verification
try self.storeLocalWithSignature(msg.key, msg.value, msg.ttl, msg.sender_id, value_sig, identity_key);
// Store the value with signature for future verification
try self.storeLocalWithSignature(msg.key, msg.value, msg.ttl, msg.sender_id, value_sig, identity_key);
}
// Sign and return success response
const auth = try self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{});
@@ -1648,6 +1676,45 @@ pub const DhtCoordinator = struct {
});
}
/// Store value locally without signature verification (for insecure/development mode)
fn storeLocalUnsigned(
self: *DhtCoordinator,
key: [32]u8,
value: []const u8,
ttl: u32,
publisher: NodeId,
) !void {
// Remove old value if it exists
const had_existing = if (self.storage.fetchRemove(key)) |old| blk: {
old.value.deinit(self.allocator);
break :blk true;
} else false;
// CRIT-7 FIX: Check storage limit for new entries
if (!had_existing) {
const max_storage = core.limits.global.dht.max_storage_entries;
if (self.storage.count() >= max_storage) {
std.log.warn("DHT: Storage limit reached ({d} entries), rejecting new entry", .{max_storage});
return DhtError.OutOfMemory;
}
}
// Store new value without signature (insecure mode)
const value_copy = try self.allocator.dupe(u8, value);
errdefer self.allocator.free(value_copy);
const now = std.time.timestamp();
try self.storage.put(key, .{
.data = value_copy,
.expires_at = now + @as(i64, @intCast(ttl)),
.publisher = publisher,
.publisher_signature = [_]u8{0} ** 64, // No signature in insecure mode
.publisher_identity = [_]u8{0} ** 32, // No identity in insecure mode
.key = key,
.original_ttl = ttl,
});
}
/// Handle incoming FIND_VALUE request
/// SECURITY: Verifies message signature and applies rate limiting
pub fn handleFindValue(self: *DhtCoordinator, msg: DhtFindValue) !DhtFindValueResponse {

View File

@@ -1166,12 +1166,27 @@ pub const NetworkManager = struct {
// Free the encrypted data, keep decrypted
self.allocator.free(msg_data);
// Create properly sized slice (plaintext is a slice into decrypt_buf)
const decrypted = self.allocator.alloc(u8, plaintext.len) catch {
// FIX: The sender includes a 4-byte length header in the plaintext (for
// non-encrypted framing compatibility). Strip it here since ReceiveBuffer
// already handles framing for the encrypted packet.
if (plaintext.len < 4) {
self.allocator.free(decrypt_buf);
continue;
}
const inner_len = std.mem.readInt(u32, plaintext[0..4], .big);
if (inner_len > plaintext.len - 4) {
std.log.warn("Decrypted message inner length mismatch: {} > {}", .{ inner_len, plaintext.len - 4 });
self.allocator.free(decrypt_buf);
continue;
}
const payload = plaintext[4 .. 4 + inner_len];
// Create properly sized slice
const decrypted = self.allocator.alloc(u8, payload.len) catch {
self.allocator.free(decrypt_buf);
continue;
};
@memcpy(decrypted, plaintext);
@memcpy(decrypted, payload);
self.allocator.free(decrypt_buf);
break :blk decrypted;

View File

@@ -58,6 +58,7 @@ pub const events = @import("p2p/events.zig");
pub const stats = @import("p2p/stats.zig");
pub const circuit_breaker = @import("p2p/circuit_breaker.zig");
pub const p2p_impl = @import("p2p/p2p.zig");
pub const dht = @import("p2p/dht.zig");
// Re-export main types
pub const P2P = p2p_impl.P2P;
@@ -68,6 +69,7 @@ pub const P2PStats = stats.P2PStats;
pub const CircuitBreaker = circuit_breaker.CircuitBreaker;
pub const EventCallback = events.EventCallback;
pub const UserContext = events.UserContext;
pub const ObservedAddress = p2p_impl.ObservedAddress; // IP Reflection / Bundled STUN
// Re-export configs
pub const NetworkConfig = config.NetworkConfig;

View File

@@ -100,17 +100,76 @@ pub fn dhtAddPeerImpl(p2p: *P2P, peer_id: [32]u8, address: Address) Error!void {
p2p.allocator.destroy(peer);
}
/// Helper: Get the observed address of a DHT peer for bidirectional IP reflection
/// Returns the peer's network address encoded for wire format (IPv4 = 6 bytes, IPv6 = 18 bytes)
fn getPeerObservedAddress(p2p: *P2P, dht_node_id: [32]u8) struct { addr: [18]u8, len: u8 } {
// Look up connection peer ID from DHT node ID
const connection_peer_id: PeerId = blk: {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
break :blk p2p.dht_node_to_peer.get(dht_node_id) orelse {
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
};
// Get the socket for this peer
const socket = p2p.getPeerSocket(connection_peer_id) orelse {
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
// Get the peer's address from the socket
const address = socket.getPeerAddress() catch {
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
// Encode the address: ip (4 or 16) + port (2)
var addr_buf: [18]u8 = [_]u8{0} ** 18;
var len: u8 = 0;
switch (address.family) {
.ipv4 => {
// IPv4: 4 bytes IP + 2 bytes port = 6 bytes
const ip_bytes = address.data.ipv4.bytes;
@memcpy(addr_buf[0..4], &ip_bytes);
std.mem.writeInt(u16, addr_buf[4..6], address.port, .big);
len = 6;
std.log.debug("Bidirectional IP Reflection: Including target's observed IPv4 {d}.{d}.{d}.{d}:{d} in request", .{
ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3], address.port,
});
},
.ipv6 => {
// IPv6: 16 bytes IP + 2 bytes port = 18 bytes
const ip_bytes = address.data.ipv6.bytes;
@memcpy(addr_buf[0..16], &ip_bytes);
std.mem.writeInt(u16, addr_buf[16..18], address.port, .big);
len = 18;
std.log.debug("Bidirectional IP Reflection: Including target's observed IPv6 (port {d}) in request", .{address.port});
},
else => {
// Unix sockets, custom addresses not supported for IP reflection
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
},
}
return .{ .addr = addr_buf, .len = len };
}
/// Create DHT network sender for DHT message propagation
pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
const DhtSendContext = struct {
fn sendFindNode(peer_id: network.dht.NodeId, msg: network.dht.DhtFindNode, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
// Bidirectional IP Reflection: Get the target's observed address to include in request
const target_observed = getPeerObservedAddress(p2p_ptr, peer_id);
const proto_msg = protocol.message.Message{
.dht_find_node = protocol.message.DhtFindNode{
.request_id = msg.request_id,
.target_id = msg.target_id,
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
},
};
@@ -120,6 +179,9 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
fn sendStore(peer_id: network.dht.NodeId, msg: network.dht.DhtStore, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
// Bidirectional IP Reflection: Get the target's observed address to include in request
const target_observed = getPeerObservedAddress(p2p_ptr, peer_id);
const proto_msg = protocol.message.Message{
.dht_store = protocol.message.DhtStore{
.request_id = msg.request_id,
@@ -127,6 +189,8 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
.value = msg.value,
.ttl = msg.ttl,
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
},
};
@@ -136,11 +200,16 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender {
fn sendFindValue(peer_id: network.dht.NodeId, msg: network.dht.DhtFindValue, ctx: ?*anyopaque) bool {
const p2p_ptr: *P2P = @ptrCast(@alignCast(ctx orelse return false));
// Bidirectional IP Reflection: Get the target's observed address to include in request
const target_observed = getPeerObservedAddress(p2p_ptr, peer_id);
const proto_msg = protocol.message.Message{
.dht_find_value = protocol.message.DhtFindValue{
.request_id = msg.request_id,
.key = msg.key,
.sender_id = msg.sender_id,
.target_observed_addr = target_observed.addr,
.target_observed_addr_len = target_observed.len,
},
};
@@ -172,12 +241,16 @@ pub const DhtMsgType = enum(u8) {
/// Serialize a DHT message to simple binary format
/// Format: [1 byte type][8 bytes request_id][32 bytes sender_id][payload...]
fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
/// Public for testing IP Reflection variable-length encoding
pub fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
var offset: usize = 0;
switch (msg) {
.dht_find_node => |m| {
if (buffer.len < 1 + 8 + 32 + 32) return null;
// Format: [type][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_node);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
@@ -186,11 +259,21 @@ fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
offset += 32;
@memcpy(buffer[offset..][0..32], &m.target_id);
offset += 32;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.target_observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
.dht_store => |m| {
// Format: [type][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
const value_len = m.value.len;
if (buffer.len < 1 + 8 + 32 + 32 + 4 + 4 + value_len) return null;
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 4 + 4 + value_len + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.store);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
@@ -205,10 +288,20 @@ fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
offset += 4;
@memcpy(buffer[offset..][0..value_len], m.value);
offset += value_len;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.target_observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
.dht_find_value => |m| {
if (buffer.len < 1 + 8 + 32 + 32) return null;
// Format: [type][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: include target's observed address in request
const addr_len: usize = @min(m.target_observed_addr_len, 18);
if (buffer.len < 1 + 8 + 32 + 32 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_value);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
@@ -217,12 +310,21 @@ fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
offset += 32;
@memcpy(buffer[offset..][0..32], &m.key);
offset += 32;
// Bidirectional IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.target_observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.target_observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
.dht_find_node_response => |m| {
// Format: [type][request_id][node_count][nodes...][observed_addr][observed_addr_len]
// Format: [type][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
const node_size = 32 + 46 + 1; // node_id + address + address_len
const required = 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 18 + 1;
const addr_len: usize = @min(m.observed_addr_len, 18);
const required = 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
if (buffer.len < required) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_node_response);
offset += 1;
@@ -238,34 +340,42 @@ fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: observed_addr
@memcpy(buffer[offset..][0..18], &m.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
.dht_store_response => |m| {
// Format: [type][request_id][success][observed_addr][observed_addr_len]
if (buffer.len < 1 + 8 + 1 + 18 + 1) return null;
// Format: [type][request_id][success][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
const addr_len: usize = @min(m.observed_addr_len, 18);
if (buffer.len < 1 + 8 + 1 + 1 + addr_len) return null;
buffer[offset] = @intFromEnum(DhtMsgType.store_response);
offset += 1;
std.mem.writeInt(u64, buffer[offset..][0..8], m.request_id, .big);
offset += 8;
buffer[offset] = if (m.success) 1 else 0;
offset += 1;
// IP Reflection: observed_addr
@memcpy(buffer[offset..][0..18], &m.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
.dht_find_value_response => |m| {
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr][observed_addr_len]
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes (saves 12 bytes for IPv4)
const node_size = 32 + 46 + 1;
const value_len = if (m.value) |v| v.len else 0;
const required = 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 18 + 1;
const addr_len: usize = @min(m.observed_addr_len, 18);
const required = 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + addr_len;
if (buffer.len < required) return null;
buffer[offset] = @intFromEnum(DhtMsgType.find_value_response);
offset += 1;
@@ -289,11 +399,13 @@ fn serializeDhtMessage(msg: protocol.message.Message, buffer: []u8) ?usize {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: observed_addr
@memcpy(buffer[offset..][0..18], &m.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = m.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..][0..addr_len], m.observed_addr[0..addr_len]);
offset += addr_len;
}
return offset;
},
else => return null,
@@ -310,21 +422,40 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
switch (msg_type) {
.find_node => {
if (data.len < 1 + 8 + 32 + 32) return null;
// Format: [type][request_id][sender_id][target_id][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const sender_id = data[offset..][0..32].*;
offset += 32;
const target_id = data[offset..][0..32].*;
offset += 32;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
target_observed_addr_len = data[offset];
offset += 1;
if (target_observed_addr_len > 0 and target_observed_addr_len <= 18) {
if (data.len >= offset + target_observed_addr_len) {
@memcpy(target_observed_addr[0..target_observed_addr_len], data[offset..][0..target_observed_addr_len]);
}
}
}
return protocol.message.Message{
.dht_find_node = .{
.request_id = request_id,
.sender_id = sender_id,
.target_id = target_id,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
},
};
},
.store => {
// Format: [type][request_id][sender_id][key][ttl][value_len][value][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 4 + 4) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
@@ -339,6 +470,19 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
if (data.len < offset + value_len) return null;
// Allocate and copy value
const value = allocator.dupe(u8, data[offset..][0..value_len]) catch return null;
offset += value_len;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
target_observed_addr_len = data[offset];
offset += 1;
if (target_observed_addr_len > 0 and target_observed_addr_len <= 18) {
if (data.len >= offset + target_observed_addr_len) {
@memcpy(target_observed_addr[0..target_observed_addr_len], data[offset..][0..target_observed_addr_len]);
}
}
}
return protocol.message.Message{
.dht_store = .{
.request_id = request_id,
@@ -346,33 +490,53 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
.key = key,
.ttl = ttl,
.value = value,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
},
};
},
.find_value => {
if (data.len < 1 + 8 + 32 + 32) return null;
// Format: [type][request_id][sender_id][key][target_observed_addr_len][target_observed_addr:len]
// Bidirectional IP Reflection: read target's observed address from request
if (data.len < 1 + 8 + 32 + 32 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const sender_id = data[offset..][0..32].*;
offset += 32;
const key = data[offset..][0..32].*;
offset += 32;
// Read target observed address (may be empty for backward compatibility)
var target_observed_addr: [18]u8 = [_]u8{0} ** 18;
var target_observed_addr_len: u8 = 0;
if (offset < data.len) {
target_observed_addr_len = data[offset];
offset += 1;
if (target_observed_addr_len > 0 and target_observed_addr_len <= 18) {
if (data.len >= offset + target_observed_addr_len) {
@memcpy(target_observed_addr[0..target_observed_addr_len], data[offset..][0..target_observed_addr_len]);
}
}
}
return protocol.message.Message{
.dht_find_value = .{
.request_id = request_id,
.sender_id = sender_id,
.key = key,
.target_observed_addr = target_observed_addr,
.target_observed_addr_len = target_observed_addr_len,
},
};
},
.find_node_response => {
// Format: [type][request_id][node_count][nodes...][observed_addr][observed_addr_len]
if (data.len < 1 + 8 + 4 + 18 + 1) return null;
// Format: [type][request_id][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 4 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const node_count = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4;
const node_size = 32 + 46 + 1;
if (data.len < offset + (node_count * node_size) + 19) return null;
if (data.len < offset + (node_count * node_size) + 1) return null;
// Allocate nodes array
const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null;
for (0..node_count) |i| {
@@ -383,10 +547,15 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
};
offset += node_size;
}
// IP Reflection: observed_addr
const observed_addr = data[offset..][0..18].*;
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
if (observed_addr_len > 0 and observed_addr_len <= 18) {
if (data.len < offset + observed_addr_len) return null;
@memcpy(observed_addr[0..observed_addr_len], data[offset..][0..observed_addr_len]);
offset += observed_addr_len;
}
return protocol.message.Message{
.dht_find_node_response = .{
.request_id = request_id,
@@ -397,16 +566,22 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
};
},
.store_response => {
// Format: [type][request_id][success][observed_addr][observed_addr_len]
if (data.len < 1 + 8 + 1 + 18 + 1) return null;
// Format: [type][request_id][success][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 1 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const success = data[offset] != 0;
offset += 1;
// IP Reflection: observed_addr
const observed_addr = data[offset..][0..18].*;
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
if (observed_addr_len > 0 and observed_addr_len <= 18) {
if (data.len < offset + observed_addr_len) return null;
@memcpy(observed_addr[0..observed_addr_len], data[offset..][0..observed_addr_len]);
offset += observed_addr_len;
}
return protocol.message.Message{
.dht_store_response = .{
.request_id = request_id,
@@ -417,15 +592,16 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
};
},
.find_value_response => {
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr][observed_addr_len]
if (data.len < 1 + 8 + 1 + 4 + 4 + 18 + 1) return null;
// Format: [type][request_id][found][value_len][value][node_count][nodes...][observed_addr_len][observed_addr:len]
// Variable-length IP Reflection: len first, then only len bytes
if (data.len < 1 + 8 + 1 + 4 + 4 + 1) return null;
const request_id = std.mem.readInt(u64, data[offset..][0..8], .big);
offset += 8;
const found = data[offset] != 0;
offset += 1;
const value_len = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4;
if (data.len < offset + value_len + 4 + 19) return null;
if (data.len < offset + value_len + 4 + 1) return null;
// Read value (may be empty)
const value: ?[]const u8 = if (value_len > 0) blk: {
const v = allocator.dupe(u8, data[offset..][0..value_len]) catch return null;
@@ -435,7 +611,7 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
const node_count = std.mem.readInt(u32, data[offset..][0..4], .big);
offset += 4;
const node_size = 32 + 46 + 1;
if (data.len < offset + (node_count * node_size) + 19) return null;
if (data.len < offset + (node_count * node_size) + 1) return null;
// Allocate nodes array
const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null;
for (0..node_count) |i| {
@@ -446,10 +622,15 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
};
offset += node_size;
}
// IP Reflection: observed_addr
const observed_addr = data[offset..][0..18].*;
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
const observed_addr_len = data[offset];
offset += 1;
var observed_addr: [18]u8 = [_]u8{0} ** 18;
if (observed_addr_len > 0 and observed_addr_len <= 18) {
if (data.len < offset + observed_addr_len) return null;
@memcpy(observed_addr[0..observed_addr_len], data[offset..][0..observed_addr_len]);
offset += observed_addr_len;
}
return protocol.message.Message{
.dht_find_value_response = .{
.request_id = request_id,
@@ -464,13 +645,45 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr
}
}
/// Free allocated memory from a deserialized DHT message
/// Only call this for messages created by deserializeDhtMessage
pub fn freeDhtMessage(allocator: std.mem.Allocator, msg: protocol.message.Message) void {
switch (msg) {
.dht_store => |store| {
// Free allocated value
if (store.value.len > 0) {
allocator.free(store.value);
}
},
.dht_find_value_response => |fvr| {
// Free allocated value
if (fvr.value) |v| {
allocator.free(v);
}
// Free allocated closest_nodes array
if (fvr.closest_nodes.len > 0) {
allocator.free(fvr.closest_nodes);
}
},
.dht_find_node_response => |fnr| {
// Free allocated closest_nodes array
if (fnr.closest_nodes.len > 0) {
allocator.free(fnr.closest_nodes);
}
},
else => {
// Other message types don't have allocated fields
},
}
}
/// Internal helper to send a DHT protocol message to a peer
pub fn sendDhtMessageImpl(p2p: *P2P, dht_node_id: [32]u8, msg: protocol.message.Message) bool {
const connection_peer_id: PeerId = blk: {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
break :blk p2p.dht_node_to_peer.get(dht_node_id) orelse {
std.log.warn("DHT: No connection peer ID found for node ID", .{});
std.log.debug("DHT: No peer mapping for node ID", .{});
return false;
};
};

View File

@@ -45,6 +45,7 @@ const P2P = p2p_module.P2P;
const handleDataResponseCallback = p2p_module.handleDataResponseCallback;
const registerNodeIdCallback = p2p_module.registerNodeIdCallback;
const sendDhtMessageCallback = p2p_module.sendDhtMessageCallback;
const addObservedAddressCallback = p2p_module.addObservedAddressCallback;
const P2PEvent = @import("events.zig").P2PEvent;
const P2PConfig = @import("config.zig").P2PConfig;
@@ -227,6 +228,11 @@ pub fn startImpl(p2p: *P2P) Error!void {
.send_fn = sendDhtMessageCallback,
.context = p2p,
});
// Wire the observed address callback for IP Reflection / Bundled STUN
ctx.setObservedAddressCallback(.{
.add_fn = addObservedAddressCallback,
.context = p2p,
});
}
}
@@ -234,6 +240,11 @@ pub fn startImpl(p2p: *P2P) Error!void {
p2p.peer_manager = p2p.allocator.create(network.peer.PeerManager) catch return Error.SystemError;
p2p.peer_manager.?.* = network.peer.PeerManager.init(p2p.allocator);
// Wire peer_manager to handler context for IP Reflection
if (p2p.handler_registry) |registry| {
registry.context.setP2PComponents(p2p.peer_manager, null, null, null);
}
// Initialize connection pool
const connection_config = core.connection.ConnectionConfig{
.connection_type = .tcp,

View File

@@ -277,6 +277,7 @@ fn handleDhtMessageImpl(p2p: *P2P, connection_peer_id: PeerId, payload: []const
std.log.warn("DHT: Failed to deserialize message (len={})", .{payload.len});
return;
};
defer dht.freeDhtMessage(p2p.allocator, msg);
// CRITICAL: Set the connection peer ID as source before processing
// This allows DHT handlers to auto-register the node_id -> peer_id mapping
@@ -287,8 +288,6 @@ fn handleDhtMessageImpl(p2p: *P2P, connection_peer_id: PeerId, payload: []const
registry.processMessage(msg) catch |err| {
std.log.warn("DHT: Failed to process message: {}", .{err});
};
std.log.debug("DHT: Processed message from peer", .{});
}
/// Callback for peer disconnection from NetworkManager

View File

@@ -98,6 +98,67 @@ pub const UserContext = events.UserContext;
pub const P2PStats = stats.P2PStats;
pub const CircuitBreaker = circuit_breaker.CircuitBreaker;
/// Observed address from DHT response (Bundled STUN / IP Reflection)
pub const ObservedAddress = struct {
/// The observed IP address (IPv4 or IPv6)
ip: union(enum) {
v4: [4]u8,
v6: [16]u8,
},
/// The observed port
port: u16,
/// Timestamp when this was observed
timestamp: i64,
/// Which peer observed this address
observer_id: [32]u8,
/// Create from raw DHT response bytes
pub fn fromDhtResponse(addr_bytes: [18]u8, addr_len: u8, observer: [32]u8) ?ObservedAddress {
if (addr_len == 0) return null;
var result: ObservedAddress = undefined;
result.timestamp = std.time.milliTimestamp();
result.observer_id = observer;
if (addr_len == 6) {
// IPv4: 4 bytes IP + 2 bytes port
result.ip = .{ .v4 = addr_bytes[0..4].* };
result.port = std.mem.readInt(u16, addr_bytes[4..6], .big);
} else if (addr_len == 18) {
// IPv6: 16 bytes IP + 2 bytes port
result.ip = .{ .v6 = addr_bytes[0..16].* };
result.port = std.mem.readInt(u16, addr_bytes[16..18], .big);
} else {
return null;
}
return result;
}
/// Check if this is a valid public address (not localhost/private)
pub fn isPublic(self: ObservedAddress) bool {
switch (self.ip) {
.v4 => |ip| {
// Skip localhost (127.x.x.x)
if (ip[0] == 127) return false;
// Skip private ranges
if (ip[0] == 10) return false; // 10.0.0.0/8
if (ip[0] == 172 and ip[1] >= 16 and ip[1] <= 31) return false; // 172.16.0.0/12
if (ip[0] == 192 and ip[1] == 168) return false; // 192.168.0.0/16
if (ip[0] == 0) return false; // 0.0.0.0
return true;
},
.v6 => |ip| {
// Skip loopback (::1)
if (std.mem.eql(u8, &ip, &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 })) return false;
// Skip link-local (fe80::/10)
if (ip[0] == 0xfe and (ip[1] & 0xc0) == 0x80) return false;
return true;
},
}
}
};
// Implementation modules
const lifecycle = @import("lifecycle.zig");
const connection = @import("connection.zig");
@@ -144,6 +205,17 @@ pub fn sendDhtMessageCallback(peer_id: [32]u8, msg: protocol.message.Message, co
return dht_module.sendDhtMessageImpl(p2p, peer_id, msg);
}
/// Callback to record observed addresses from DHT responses (IP Reflection / Bundled STUN).
/// Called by DHT response handlers when they receive our public IP from peers.
pub fn addObservedAddressCallback(observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8, context: ?*anyopaque) void {
const p2p: *P2P = @ptrCast(@alignCast(context orelse {
std.log.err("addObservedAddressCallback: null context", .{});
return;
}));
p2p.addObservedAddress(observed_addr, observed_addr_len, observer_id);
}
/// Callback to handle data responses during file downloads.
///
/// This function processes incoming DataResponse messages and writes
@@ -307,6 +379,11 @@ pub const P2P = struct {
dht_node_to_peer: std.AutoHashMap([32]u8, PeerId),
/// Mutex for dht_node_to_peer map
dht_node_to_peer_mutex: Mutex,
/// Observed public addresses from DHT responses (Bundled STUN / IP Reflection)
/// Stores our public IP:port as seen by DHT peers
observed_addresses: std.ArrayList(ObservedAddress),
/// Mutex for observed_addresses
observed_addresses_mutex: Mutex,
/// Statistics
stats: P2PStats,
/// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads)
@@ -383,6 +460,8 @@ pub const P2P = struct {
.connection_backoff = null,
.dht_node_to_peer = std.AutoHashMap([32]u8, PeerId).init(allocator),
.dht_node_to_peer_mutex = Mutex{},
.observed_addresses = .{},
.observed_addresses_mutex = Mutex{},
.stats = P2PStats{
.state = .Uninitialized,
.uptime_seconds = 0,
@@ -614,6 +693,7 @@ pub const P2P = struct {
p2p.allocator.destroy(rt);
}
p2p.dht_node_to_peer.deinit();
p2p.observed_addresses.deinit(p2p.allocator);
// Clean up network components
if (p2p.network_bridge) |bridge| {
@@ -829,6 +909,30 @@ pub const P2P = struct {
return messaging.emitEventImpl(p2p, event);
}
/// Process network I/O and internal state updates.
///
/// **CRITICAL**: This function MUST be called periodically in your application's
/// main loop. Without calling update(), the library will not:
/// - Receive incoming messages
/// - Accept new connections
/// - Process DHT queries/responses
/// - Handle file transfers
///
/// This poll-based design enables WASM compatibility and single-threaded operation.
///
/// ## Example
/// ```zig
/// while (running) {
/// try p2p.update(); // Process all pending I/O
/// // ... your application logic ...
/// std.Thread.sleep(10 * std.time.ns_per_ms);
/// }
/// ```
///
/// ## Recommended Call Frequency
/// - 10-100ms intervals for most applications
/// - More frequent for lower latency requirements
/// - Less frequent is OK for idle applications (but responses will be delayed)
pub fn update(p2p: *P2P) Error!void {
return messaging.updateImpl(p2p);
}
@@ -881,6 +985,47 @@ pub const P2P = struct {
return dht_ops.getDhtPeerCountImpl(p2p);
}
/// Get the number of active connections (connected peers)
pub fn getActiveConnectionCount(p2p: *P2P) u32 {
return p2p.stats.active_connections.load(.monotonic);
}
/// Get the number of DHT node ID mappings (peers we can route DHT messages to)
pub fn getDhtMappingCount(p2p: *P2P) usize {
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
return p2p.dht_node_to_peer.count();
}
/// Add all currently mapped DHT peers to the routing table.
/// This is useful when you want to be able to query peers that have connected to you
/// but haven't been explicitly added to your routing table via dhtAddPeer.
pub fn addMappedPeersToRoutingTable(p2p: *P2P) !usize {
var added: usize = 0;
// Collect node IDs and their connection peer IDs
p2p.dht_node_to_peer_mutex.lock();
defer p2p.dht_node_to_peer_mutex.unlock();
var iter = p2p.dht_node_to_peer.iterator();
while (iter.next()) |entry| {
const node_id = entry.key_ptr.*;
const connection_peer_id = entry.value_ptr.*;
// Get the socket for this connection peer
const socket = p2p.getPeerSocket(connection_peer_id) orelse continue;
// Get the peer's address from the socket (already in our Address type)
const address = socket.getPeerAddress() catch continue;
// Add to routing table
p2p.dhtAddPeer(node_id, address) catch continue;
added += 1;
}
return added;
}
pub fn dhtStore(p2p: *P2P, key: [32]u8, value: []const u8, ttl: u32) Error!void {
return dht_ops.dhtStoreImpl(p2p, key, value, ttl);
}
@@ -905,6 +1050,238 @@ pub const P2P = struct {
return dht_ops.dhtAddPeerImpl(p2p, peer_id, address);
}
// =========================================================================
// Bundled STUN / IP Reflection (Observed Address Management)
// =========================================================================
/// Store an observed address from a DHT response (called internally by DHT handlers)
pub fn addObservedAddress(p2p: *P2P, addr_bytes: [18]u8, addr_len: u8, observer_id: [32]u8) void {
const observed = ObservedAddress.fromDhtResponse(addr_bytes, addr_len, observer_id) orelse return;
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
// Check if we already have this address from this observer
for (p2p.observed_addresses.items) |*existing| {
const same_observer = std.mem.eql(u8, &existing.observer_id, &observer_id);
const same_addr = switch (observed.ip) {
.v4 => |ip| switch (existing.ip) {
.v4 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
.v6 => false,
},
.v6 => |ip| switch (existing.ip) {
.v6 => |eip| std.mem.eql(u8, &ip, &eip) and observed.port == existing.port,
.v4 => false,
},
};
if (same_observer or same_addr) {
// Update timestamp
existing.timestamp = observed.timestamp;
return;
}
}
// Add new observed address (limit to 10 entries to prevent unbounded growth)
if (p2p.observed_addresses.items.len >= 10) {
// Remove oldest entry
_ = p2p.observed_addresses.orderedRemove(0);
}
p2p.observed_addresses.append(p2p.allocator, observed) catch return;
// Log if this is a public address
if (observed.isPublic()) {
switch (observed.ip) {
.v4 => |ip| std.log.info("Bundled STUN: Discovered public address {d}.{d}.{d}.{d}:{d}", .{ ip[0], ip[1], ip[2], ip[3], observed.port }),
.v6 => std.log.info("Bundled STUN: Discovered public IPv6 address (port {d})", .{observed.port}),
}
}
}
/// Get the best observed public address (most recent, public, from multiple observers)
pub fn getObservedPublicAddress(p2p: *P2P) ?ObservedAddress {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
// Find most recent public address
var best: ?ObservedAddress = null;
for (p2p.observed_addresses.items) |addr| {
if (!addr.isPublic()) continue;
if (best == null or addr.timestamp > best.?.timestamp) {
best = addr;
}
}
return best;
}
/// Get all observed addresses (for MWP to include in publications)
pub fn getAllObservedAddresses(p2p: *P2P, allocator: Allocator) ![]ObservedAddress {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
return try allocator.dupe(ObservedAddress, p2p.observed_addresses.items);
}
/// Confidence level for observed address consensus
pub const AddressConfidence = enum {
/// No observers yet
none,
/// Single observer (trusted but unverified)
single_source,
/// Multiple observers agree
consensus,
/// Multiple observers disagree (using majority)
conflict,
};
/// Result of consensus address lookup
pub const ConsensusResult = struct {
address: ?ObservedAddress,
confidence: AddressConfidence,
/// Number of unique observers reporting this address
observer_count: u8,
/// Total number of unique observers
total_observers: u8,
};
/// Get the consensus observed address with confidence level
/// Returns the address that most unique observers agree on
pub fn getConsensusAddress(p2p: *P2P) ConsensusResult {
p2p.observed_addresses_mutex.lock();
defer p2p.observed_addresses_mutex.unlock();
if (p2p.observed_addresses.items.len == 0) {
return .{
.address = null,
.confidence = .none,
.observer_count = 0,
.total_observers = 0,
};
}
// Count unique observers and group addresses
// Key: (ip_hash, port) -> count of unique observers
var address_votes: [10]struct {
addr: ObservedAddress,
observers: [10][32]u8,
observer_count: u8,
} = undefined;
var num_addresses: usize = 0;
var total_unique_observers: u8 = 0;
var seen_observers: [10][32]u8 = undefined;
var num_seen_observers: usize = 0;
for (p2p.observed_addresses.items) |observed| {
// Track unique observers
var observer_seen = false;
for (seen_observers[0..num_seen_observers]) |seen| {
if (std.mem.eql(u8, &seen, &observed.observer_id)) {
observer_seen = true;
break;
}
}
if (!observer_seen and num_seen_observers < 10) {
seen_observers[num_seen_observers] = observed.observer_id;
num_seen_observers += 1;
total_unique_observers += 1;
}
// Find or create address entry
var found_idx: ?usize = null;
for (address_votes[0..num_addresses], 0..) |*entry, idx| {
if (addressesEqual(entry.addr, observed)) {
found_idx = idx;
break;
}
}
if (found_idx) |idx| {
// Check if this observer already voted for this address
var already_voted = false;
for (address_votes[idx].observers[0..address_votes[idx].observer_count]) |obs| {
if (std.mem.eql(u8, &obs, &observed.observer_id)) {
already_voted = true;
break;
}
}
if (!already_voted and address_votes[idx].observer_count < 10) {
address_votes[idx].observers[address_votes[idx].observer_count] = observed.observer_id;
address_votes[idx].observer_count += 1;
// Update to most recent timestamp
if (observed.timestamp > address_votes[idx].addr.timestamp) {
address_votes[idx].addr = observed;
}
}
} else if (num_addresses < 10) {
// New address
address_votes[num_addresses] = .{
.addr = observed,
.observers = undefined,
.observer_count = 1,
};
address_votes[num_addresses].observers[0] = observed.observer_id;
num_addresses += 1;
}
}
if (num_addresses == 0) {
return .{
.address = null,
.confidence = .none,
.observer_count = 0,
.total_observers = total_unique_observers,
};
}
// Find address with most votes
var best_idx: usize = 0;
var best_count: u8 = address_votes[0].observer_count;
for (address_votes[1..num_addresses], 1..) |entry, idx| {
if (entry.observer_count > best_count) {
best_count = entry.observer_count;
best_idx = idx;
}
}
const confidence: AddressConfidence = if (total_unique_observers == 1)
.single_source
else if (best_count == total_unique_observers)
.consensus
else
.conflict;
if (confidence == .consensus and total_unique_observers >= 2) {
std.log.info("IP Reflection: Consensus reached! {} observers agree on address", .{total_unique_observers});
} else if (confidence == .conflict) {
std.log.warn("IP Reflection: Conflict detected - {}/{} observers agree (using majority)", .{ best_count, total_unique_observers });
}
return .{
.address = address_votes[best_idx].addr,
.confidence = confidence,
.observer_count = best_count,
.total_observers = total_unique_observers,
};
}
/// Helper: Compare two observed addresses (ignoring timestamp and observer)
fn addressesEqual(a: ObservedAddress, b: ObservedAddress) bool {
if (a.port != b.port) return false;
return switch (a.ip) {
.v4 => |ip_a| switch (b.ip) {
.v4 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
.v6 => false,
},
.v6 => |ip_a| switch (b.ip) {
.v6 => |ip_b| std.mem.eql(u8, &ip_a, &ip_b),
.v4 => false,
},
};
}
// =========================================================================
// Small inline methods (just access fields)
// =========================================================================

View File

@@ -59,6 +59,22 @@ pub const DhtMessageSender = struct {
}
};
/// Observed address callback - called when we receive our public IP from DHT responses
/// This is the "Bundled STUN" / IP Reflection feature
pub const ObservedAddressCallback = struct {
/// Callback function to register an observed address
/// @param observed_addr: The 18-byte address buffer (IPv4: 6 bytes, IPv6: 18 bytes)
/// @param observed_addr_len: Length of the address (6 for IPv4, 18 for IPv6)
/// @param observer_id: The node ID of the peer that observed our address
/// @param context: User context (typically P2P instance)
add_fn: *const fn (observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8, context: ?*anyopaque) void,
context: ?*anyopaque,
pub fn add(self: ObservedAddressCallback, observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8) void {
self.add_fn(observed_addr, observed_addr_len, observer_id, self.context);
}
};
/// Handler limits for memory exhaustion protection
pub const HandlerLimits = struct {
pub const MAX_PENDING_MESSAGES: usize = 10000; // Max messages in async queue
@@ -169,6 +185,10 @@ pub const HandlerContext = struct {
// DHT message sender callback - for sending DHT messages in simple binary format
dht_message_sender: ?DhtMessageSender = null,
// Observed address callback - for IP Reflection / Bundled STUN
// Called when we receive our public IP from DHT responses
observed_address_callback: ?ObservedAddressCallback = null,
pub fn init(allocator: std.mem.Allocator, metrics: *HandlerMetrics) HandlerContext {
return .{
.allocator = allocator,
@@ -294,6 +314,29 @@ pub const HandlerContext = struct {
}
}
/// Set the observed address callback for IP Reflection / Bundled STUN
pub fn setObservedAddressCallback(self: *HandlerContext, callback: ObservedAddressCallback) void {
self.config_mutex.lock();
defer self.config_mutex.unlock();
self.observed_address_callback = callback;
}
/// Record an observed address from a DHT response (IP Reflection / Bundled STUN)
/// Called when we receive a DHT response that includes our observed public address
pub fn recordObservedAddress(self: *HandlerContext, observed_addr: [18]u8, observed_addr_len: u8, observer_id: [32]u8) void {
// Skip if no address was included (len=0)
if (observed_addr_len == 0) return;
self.config_mutex.lock();
const callback = self.observed_address_callback;
self.config_mutex.unlock();
if (callback) |cb| {
cb.add(observed_addr, observed_addr_len, observer_id);
std.log.debug("IP Reflection: Received observed address from {x} (len={})", .{ observer_id[0..8].*, observed_addr_len });
}
}
// MEM-M1 FIX: Type-safe getter methods for pointer casts.
// These methods encapsulate the unsafe pointer casts and provide
// proper error handling instead of undefined behavior on type mismatch.
@@ -357,13 +400,25 @@ pub const HandlerContext = struct {
/// Returns the peer's network address in wire format: IPv4 = 6 bytes, IPv6 = 18 bytes
pub fn getSourceObservedAddr(self: *const HandlerContext) struct { addr: [18]u8, len: u8 } {
const network = @import("network");
const source_id = self.source_peer_id orelse return .{ .addr = [_]u8{0} ** 18, .len = 0 };
const source_id = self.source_peer_id orelse {
std.log.debug("IP Reflection: No source_peer_id available", .{});
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
const pm = self.getPeerManager() catch return .{ .addr = [_]u8{0} ** 18, .len = 0 };
const peer_manager = pm orelse return .{ .addr = [_]u8{0} ** 18, .len = 0 };
const pm = self.getPeerManager() catch {
std.log.debug("IP Reflection: Failed to get peer manager", .{});
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
const peer_manager = pm orelse {
std.log.debug("IP Reflection: Peer manager is null", .{});
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
const peer_id = network.PeerId{ .bytes = source_id };
const peer_info = peer_manager.getPeerById(peer_id) orelse return .{ .addr = [_]u8{0} ** 18, .len = 0 };
const peer_info = peer_manager.getPeerById(peer_id) orelse {
std.log.debug("IP Reflection: Peer not found in peer manager (id={x})", .{source_id[0..8].*});
return .{ .addr = [_]u8{0} ** 18, .len = 0 };
};
// Serialize the address: type (1) + ip (4 or 16) + port (2)
var addr_buf: [18]u8 = [_]u8{0} ** 18;
@@ -376,6 +431,9 @@ pub const HandlerContext = struct {
@memcpy(addr_buf[0..4], &ip_bytes);
std.mem.writeInt(u16, addr_buf[4..6], peer_info.address.port, .big);
len = 6;
std.log.debug("IP Reflection: Responding with observed IPv4 {d}.{d}.{d}.{d}:{d}", .{
ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3], peer_info.address.port,
});
},
.ipv6 => {
// IPv6: 16 bytes IP + 2 bytes port = 18 bytes
@@ -383,8 +441,11 @@ pub const HandlerContext = struct {
@memcpy(addr_buf[0..16], &ip_bytes);
std.mem.writeInt(u16, addr_buf[16..18], peer_info.address.port, .big);
len = 18;
std.log.debug("IP Reflection: Responding with observed IPv6 (port {d})", .{peer_info.address.port});
},
else => {
std.log.debug("IP Reflection: Unknown address family", .{});
},
else => {},
}
return .{ .addr = addr_buf, .len = len };

View File

@@ -903,6 +903,13 @@ pub fn handleDhtFindNode(
// Auto-register the sender's DHT node ID mapping so we can respond
context.registerNodeId(msg.sender_id, source_id);
// Bidirectional IP Reflection: If the request contains our observed address, record it
// This allows the receiver (us) to learn our address from the sender's perspective
if (msg.target_observed_addr_len > 0) {
context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id);
std.log.debug("DHT FIND_NODE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len});
}
if (context.dht_coordinator) |dht_ptr| {
const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse {
std.log.err("DHT: Invalid dht_coordinator pointer", .{});
@@ -952,7 +959,7 @@ pub fn handleDhtFindNode(
},
};
if (!context.sendDhtMessage(source_id, response_msg)) {
if (!context.sendDhtMessage(msg.sender_id, response_msg)) {
context.metrics.recordMessageFailed();
return error.SendFailed;
}
@@ -1006,6 +1013,9 @@ pub fn handleDhtFindNodeResponse(
std.log.warn("DHT: Failed to process FIND_NODE response: {}", .{err});
};
// IP Reflection: Record observed address from response (Bundled STUN)
context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id);
context.metrics.recordMessageProcessed(0.0);
} else {
context.metrics.recordMessageFailed();
@@ -1026,6 +1036,13 @@ pub fn handleDhtStore(
// Auto-register the sender's DHT node ID mapping so we can respond
context.registerNodeId(msg.sender_id, source_id);
// Bidirectional IP Reflection: If the request contains our observed address, record it
// This allows the receiver (us) to learn our address from the sender's perspective
if (msg.target_observed_addr_len > 0) {
context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id);
std.log.debug("DHT STORE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len});
}
if (context.dht_coordinator) |dht_ptr| {
const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse {
context.metrics.recordMessageFailed();
@@ -1057,7 +1074,7 @@ pub fn handleDhtStore(
.observed_addr_len = observed.len,
},
};
_ = context.sendDhtMessage(source_id, fail_response);
_ = context.sendDhtMessage(msg.sender_id, fail_response);
context.metrics.recordMessageFailed();
return err;
};
@@ -1072,7 +1089,7 @@ pub fn handleDhtStore(
},
};
if (!context.sendDhtMessage(source_id, response_msg)) {
if (!context.sendDhtMessage(msg.sender_id, response_msg)) {
context.metrics.recordMessageFailed();
return error.SendFailed;
}
@@ -1089,6 +1106,11 @@ pub fn handleDhtStoreResponse(
msg: message.DhtStoreResponse,
context: *handler_mod.HandlerContext,
) !void {
const source_id = context.source_peer_id orelse {
context.metrics.recordMessageFailed();
return error.InvalidMessage;
};
if (context.dht_coordinator) |dht_ptr| {
const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse {
context.metrics.recordMessageFailed();
@@ -1101,6 +1123,10 @@ pub fn handleDhtStoreResponse(
};
dht.handleStoreResponse(dht_response);
// IP Reflection: Record observed address from response (Bundled STUN)
context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id);
context.metrics.recordMessageProcessed(0.0);
} else {
context.metrics.recordMessageFailed();
@@ -1122,6 +1148,13 @@ pub fn handleDhtFindValue(
// This enables bidirectional DHT communication without manual registration
context.registerNodeId(msg.sender_id, source_id);
// Bidirectional IP Reflection: If the request contains our observed address, record it
// This allows the receiver (us) to learn our address from the sender's perspective
if (msg.target_observed_addr_len > 0) {
context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id);
std.log.debug("DHT FIND_VALUE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len});
}
if (context.dht_coordinator) |dht_ptr| {
const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse {
context.metrics.recordMessageFailed();
@@ -1170,12 +1203,11 @@ pub fn handleDhtFindValue(
},
};
if (!context.sendDhtMessage(source_id, response_msg)) {
if (!context.sendDhtMessage(msg.sender_id, response_msg)) {
context.metrics.recordMessageFailed();
return error.SendFailed;
}
context.metrics.recordMessageProcessed(0.0);
std.log.debug("DHT: Sent FIND_VALUE response, found={}, observed_addr_len={}", .{ response.found, observed.len });
} else {
context.metrics.recordMessageFailed();
return error.InvalidState;
@@ -1187,6 +1219,11 @@ pub fn handleDhtFindValueResponse(
msg: message.DhtFindValueResponse,
context: *handler_mod.HandlerContext,
) !void {
const source_id = context.source_peer_id orelse {
context.metrics.recordMessageFailed();
return error.InvalidMessage;
};
if (context.dht_coordinator) |dht_ptr| {
const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse {
context.metrics.recordMessageFailed();
@@ -1215,9 +1252,17 @@ pub fn handleDhtFindValueResponse(
.closest_nodes = converted_nodes,
};
_ = dht.handleFindValueResponse(dht_response) catch |err| {
// handleFindValueResponse returns an optional allocated slice that must be freed
const found_value = dht.handleFindValueResponse(dht_response) catch |err| {
std.log.warn("DHT: Failed to process FIND_VALUE response: {}", .{err});
return;
};
if (found_value) |v| {
dht.allocator.free(v);
}
// IP Reflection: Record observed address from response (Bundled STUN)
context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id);
context.metrics.recordMessageProcessed(0.0);
} else {

View File

@@ -544,12 +544,28 @@ pub const DhtFindNode = struct {
request_id: u64,
target_id: NodeId,
sender_id: NodeId,
/// Bidirectional IP Reflection: The observed address of the TARGET (receiver)
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
pub fn init(target: NodeId, sender: NodeId) DhtFindNode {
return .{
.request_id = generateRequestId(),
.target_id = target,
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
};
}
pub fn initWithTargetObserved(target: NodeId, sender: NodeId, addr: [18]u8, addr_len: u8) DhtFindNode {
return .{
.request_id = generateRequestId(),
.target_id = target,
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
};
}
};
@@ -597,6 +613,10 @@ pub const DhtStore = struct {
value: []const u8,
ttl: u32,
sender_id: NodeId,
/// Bidirectional IP Reflection: The observed address of the TARGET (receiver)
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
pub fn init(key: [32]u8, value: []const u8, ttl: u32, sender: NodeId) DhtStore {
return .{
@@ -605,6 +625,20 @@ pub const DhtStore = struct {
.value = value,
.ttl = ttl,
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
};
}
pub fn initWithTargetObserved(key: [32]u8, value: []const u8, ttl: u32, sender: NodeId, addr: [18]u8, addr_len: u8) DhtStore {
return .{
.request_id = generateRequestId(),
.key = key,
.value = value,
.ttl = ttl,
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
};
}
};
@@ -643,12 +677,28 @@ pub const DhtFindValue = struct {
request_id: u64,
key: [32]u8,
sender_id: NodeId,
/// Bidirectional IP Reflection: The observed address of the TARGET (receiver)
/// This tells the receiver what their address looks like from our perspective
target_observed_addr: [18]u8 = [_]u8{0} ** 18,
target_observed_addr_len: u8 = 0,
pub fn init(key: [32]u8, sender: NodeId) DhtFindValue {
return .{
.request_id = generateRequestId(),
.key = key,
.sender_id = sender,
.target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0,
};
}
pub fn initWithTargetObserved(key: [32]u8, sender: NodeId, addr: [18]u8, addr_len: u8) DhtFindValue {
return .{
.request_id = generateRequestId(),
.key = key,
.sender_id = sender,
.target_observed_addr = addr,
.target_observed_addr_len = addr_len,
};
}
};

View File

@@ -31,6 +31,23 @@ const MessageEntry = struct {
nonce: u64,
};
/// Composite key for per-peer message tracking
/// This ensures message IDs are tracked per-peer to avoid collisions
/// when different peers use the same sequence numbers
const PeerMessageKey = struct {
peer_id_prefix: [8]u8, // First 8 bytes of peer ID for compact storage
msg_id: u64,
pub fn init(peer_id: [32]u8, msg_id: u64) PeerMessageKey {
var prefix: [8]u8 = undefined;
@memcpy(&prefix, peer_id[0..8]);
return .{
.peer_id_prefix = prefix,
.msg_id = msg_id,
};
}
};
/// Peer sequence tracking with sliding window
const PeerSequenceState = struct {
/// Last accepted sequence number
@@ -121,8 +138,9 @@ pub const MemoryError = error{
pub const ReplayProtector = struct {
allocator: std.mem.Allocator,
/// Track seen message IDs with their timestamps and nonces
seen_messages: std.AutoHashMap(u64, MessageEntry),
/// Track seen message IDs with their timestamps and nonces (per-peer)
/// Uses PeerMessageKey to avoid collisions when different peers use same sequence numbers
seen_messages: std.AutoHashMap(PeerMessageKey, MessageEntry),
/// Track per-peer sequence numbers
peer_sequences: std.AutoHashMap([32]u8, PeerSequenceState),
@@ -163,7 +181,7 @@ pub const ReplayProtector = struct {
pub fn init(allocator: std.mem.Allocator) ReplayProtector {
return .{
.allocator = allocator,
.seen_messages = std.AutoHashMap(u64, MessageEntry).init(allocator),
.seen_messages = std.AutoHashMap(PeerMessageKey, MessageEntry).init(allocator),
.peer_sequences = std.AutoHashMap([32]u8, PeerSequenceState).init(allocator),
.seen_nonces = std.AutoHashMap(u64, i64).init(allocator),
.max_clock_skew = 5, // HIGH-3: 5 seconds (reduced from 15s)
@@ -221,8 +239,8 @@ pub const ReplayProtector = struct {
// 1. Validate timestamp
try self.validateTimestamp(timestamp, current_time);
// 2. Check for duplicate message ID
if (try self.isReplay(msg_id, timestamp, nonce)) {
// 2. Check for duplicate message ID (per-peer to avoid collisions)
if (try self.isReplay(peer_id, msg_id, timestamp, nonce)) {
return ReplayError.DuplicateMessageId;
}
@@ -248,8 +266,9 @@ pub const ReplayProtector = struct {
try self.checkSequence(peer_id, sequence, current_time);
}
// 5. Record this message as seen
try self.seen_messages.put(msg_id, .{
// 5. Record this message as seen (per-peer key)
const key = PeerMessageKey.init(peer_id, msg_id);
try self.seen_messages.put(key, .{
.timestamp = timestamp,
.nonce = nonce,
});
@@ -279,10 +298,13 @@ pub const ReplayProtector = struct {
}
}
/// Check if message ID was seen before
fn isReplay(self: *ReplayProtector, msg_id: u64, timestamp: i64, nonce: u64) !bool {
if (self.seen_messages.get(msg_id)) |entry| {
// Found duplicate message ID
/// Check if message ID was seen before (per-peer)
/// Uses PeerMessageKey to ensure message IDs are tracked per-peer,
/// avoiding collisions when different peers use the same sequence numbers
fn isReplay(self: *ReplayProtector, peer_id: [32]u8, msg_id: u64, timestamp: i64, nonce: u64) !bool {
const key = PeerMessageKey.init(peer_id, msg_id);
if (self.seen_messages.get(key)) |entry| {
// Found duplicate message ID from this peer
// Additional check: if timestamp and nonce match, it's definitely a replay
if (entry.timestamp == timestamp and entry.nonce == nonce) {
return true;
@@ -352,9 +374,9 @@ pub const ReplayProtector = struct {
pub fn cleanup(self: *ReplayProtector, current_time: i64) void {
// This cleanup is called with mutex already held
// Clean up old message IDs
// Clean up old message IDs (now using PeerMessageKey)
var msg_it = self.seen_messages.iterator();
var to_remove_msgs = std.ArrayList(u64){};
var to_remove_msgs = std.ArrayList(PeerMessageKey){};
defer to_remove_msgs.deinit(self.allocator);
// SEC-M3 FIX: Limit pre-allocation to prevent memory DoS
@@ -381,8 +403,8 @@ pub const ReplayProtector = struct {
std.log.warn("Message ID cleanup encountered {} failures", .{msg_cleanup_failures});
}
for (to_remove_msgs.items) |msg_id| {
_ = self.seen_messages.remove(msg_id);
for (to_remove_msgs.items) |key| {
_ = self.seen_messages.remove(key);
}
// Clean up old nonces

View File

@@ -769,21 +769,29 @@ pub const MessageSerializer = struct {
// DHT messages - basic size calculations
.dht_find_node => 8 + 32 + 32, // request_id + target_id + sender_id
.dht_find_node_response => |resp| blk: {
// 8 (request_id) + array of NodeInfo (node_id + address + len) + observed_addr (18 + 1)
// 8 (request_id) + array of NodeInfo (node_id + address + len) + observed_addr (1 + len)
// Variable-length encoding: len byte + actual address bytes
const node_size = 32 + 46 + 1; // NodeInfo size
const nodes_size = resp.closest_nodes.len * node_size;
const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18));
const base = safeAdd(8, nodes_size) orelse std.math.maxInt(usize);
break :blk safeAdd(base, 19) orelse std.math.maxInt(usize); // + observed_addr
break :blk safeAdd(base, addr_overhead) orelse std.math.maxInt(usize);
},
.dht_store => |store| blk: {
// 8 + 32 + value.len + 4 + 32
const base = safeAdd(8 + 32, store.value.len) orelse std.math.maxInt(usize);
break :blk safeAdd(base, 4 + 32) orelse std.math.maxInt(usize);
},
.dht_store_response => 8 + 1 + 19, // request_id + success + observed_addr (18 + 1)
.dht_store_response => |resp| blk: {
// request_id + success + observed_addr (1 + len) - variable-length encoding
const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18));
break :blk 8 + 1 + addr_overhead;
},
.dht_find_value => 8 + 32 + 32, // request_id + key + sender_id
.dht_find_value_response => |resp| blk: {
const base = 8 + 1 + 19; // request_id + found + observed_addr
// request_id + found + observed_addr (1 + len) - variable-length encoding
const addr_overhead = 1 + @as(usize, @min(resp.observed_addr_len, 18));
const base = 8 + 1 + addr_overhead;
const value_size = if (resp.value) |v| v.len else 0;
const with_value = safeAdd(base, value_size) orelse std.math.maxInt(usize);
const node_size = 32 + 46 + 1;
@@ -1218,11 +1226,15 @@ pub const MessageSerializer = struct {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: Serialize observed_addr (bundled STUN)
try checkBounds(buffer, offset, 19);
@memcpy(buffer[offset..offset + 18], &resp.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
const addr_len: usize = @min(resp.observed_addr_len, 18);
try checkBounds(buffer, offset, 1 + addr_len);
buffer[offset] = resp.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]);
offset += addr_len;
}
},
.dht_store => |store| {
// SECURITY: Safe bounds check with overflow protection
@@ -1250,15 +1262,20 @@ pub const MessageSerializer = struct {
},
.dht_store_response => |resp| {
// SECURITY: Safe bounds check with overflow protection
try checkBounds(buffer, offset, 28); // 8 + 1 + 19 (observed_addr)
// Variable-length encoding: 8 + 1 + 1 + addr_len
const addr_len: usize = @min(resp.observed_addr_len, 18);
try checkBounds(buffer, offset, 8 + 1 + 1 + addr_len);
@memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.request_id));
offset += 8;
buffer[offset] = if (resp.success) 1 else 0;
offset += 1;
// IP Reflection: Serialize observed_addr (bundled STUN)
@memcpy(buffer[offset..offset + 18], &resp.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
buffer[offset] = resp.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]);
offset += addr_len;
}
},
.dht_find_value => |find| {
// SECURITY: Safe bounds check with overflow protection
@@ -1308,11 +1325,15 @@ pub const MessageSerializer = struct {
buffer[offset] = node.address_len;
offset += 1;
}
// IP Reflection: Serialize observed_addr (bundled STUN)
try checkBounds(buffer, offset, 19);
@memcpy(buffer[offset..offset + 18], &resp.observed_addr);
offset += 18;
// IP Reflection: variable-length encoding (len first, then data)
const addr_len: usize = @min(resp.observed_addr_len, 18);
try checkBounds(buffer, offset, 1 + addr_len);
buffer[offset] = resp.observed_addr_len;
offset += 1;
if (addr_len > 0) {
@memcpy(buffer[offset..offset + addr_len], resp.observed_addr[0..addr_len]);
offset += addr_len;
}
},
.app_data => |app| {
// SECURITY: Safe bounds check with overflow protection