feat: refactor core+network+protocol: use platform abstractions,

transport vtable
This commit is contained in:
2026-02-19 11:32:30 -03:00
parent 63e5ac59ce
commit b466979bc7
33 changed files with 884 additions and 624 deletions

View File

@@ -13,6 +13,7 @@ pub const rate_limiter = @import("core/rate_limiter.zig");
pub const limits = @import("core/limits.zig"); pub const limits = @import("core/limits.zig");
pub const tracking_allocator = @import("core/tracking_allocator.zig"); pub const tracking_allocator = @import("core/tracking_allocator.zig");
pub const log = @import("core/log.zig"); pub const log = @import("core/log.zig");
pub const transport = @import("core/transport.zig");
// Re-export commonly used types // Re-export commonly used types
pub const Error = errors.Error; pub const Error = errors.Error;
@@ -31,6 +32,12 @@ pub const MockSocket = socket.MockSocket;
pub const MockSocketConfig = socket.MockSocketConfig; pub const MockSocketConfig = socket.MockSocketConfig;
pub const ReceiveFromResult = socket.ReceiveFromResult; pub const ReceiveFromResult = socket.ReceiveFromResult;
// Transport abstraction
pub const Transport = transport.Transport;
pub const TransportFactory = transport.TransportFactory;
pub const TransportState = transport.TransportState;
pub const TransportMode = transport.TransportMode;
pub const Connection = connection.Connection; pub const Connection = connection.Connection;
pub const ConnectionState = connection.ConnectionState; pub const ConnectionState = connection.ConnectionState;
pub const ConnectionConfig = connection.ConnectionConfig; pub const ConnectionConfig = connection.ConnectionConfig;
@@ -74,4 +81,5 @@ test {
_ = limits; _ = limits;
_ = tracking_allocator; _ = tracking_allocator;
_ = log; _ = log;
_ = transport;
} }

View File

@@ -12,8 +12,11 @@ const posix = std.posix;
const mem = std.mem; const mem = std.mem;
const fmt = std.fmt; const fmt = std.fmt;
const builtin = @import("builtin"); const builtin = @import("builtin");
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error; const Error = @import("error.zig").Error;
const platform_time = @import("platform").time;
/// Address family types /// Address family types
pub const AddressFamily = enum(u8) { pub const AddressFamily = enum(u8) {
@@ -825,7 +828,7 @@ pub const MAX_DNS_CACHE_MEMORY: usize = 10 * 1024 * 1024;
/// DNS rate limiting per host /// DNS rate limiting per host
pub const DnsRateLimit = struct { pub const DnsRateLimit = struct {
last_lookup: std.AutoHashMap(u64, i64), last_lookup: std.AutoHashMap(u64, i64),
mutex: std.Thread.Mutex, mutex: Mutex,
allocator: mem.Allocator, allocator: mem.Allocator,
min_interval_ms: i64, min_interval_ms: i64,
@@ -852,7 +855,7 @@ pub const DnsRateLimit = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
if (self.last_lookup.get(hash)) |last_time| { if (self.last_lookup.get(hash)) |last_time| {
// Check if enough time has passed since last lookup // Check if enough time has passed since last lookup
@@ -877,13 +880,13 @@ pub const AddressResolver = struct {
/// SECURITY: Rate limiter to prevent DNS amplification attacks /// SECURITY: Rate limiter to prevent DNS amplification attacks
rate_limiter: DnsRateLimit, rate_limiter: DnsRateLimit,
/// SECURITY: Track total cache memory usage /// SECURITY: Track total cache memory usage
cache_memory_used: std.atomic.Value(usize), cache_memory_used: AtomicValue(usize),
pub fn init(allocator: mem.Allocator) AddressResolver { pub fn init(allocator: mem.Allocator) AddressResolver {
return .{ return .{
.allocator = allocator, .allocator = allocator,
.rate_limiter = DnsRateLimit.init(allocator, 1000), // 1 second minimum between lookups .rate_limiter = DnsRateLimit.init(allocator, 1000), // 1 second minimum between lookups
.cache_memory_used = std.atomic.Value(usize).init(0), .cache_memory_used = AtomicValue(usize).init(0),
}; };
} }

View File

@@ -7,11 +7,14 @@
const std = @import("std"); const std = @import("std");
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const atomic = std.atomic;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error; const Error = @import("error.zig").Error;
const limits = @import("limits.zig"); const limits = @import("limits.zig");
const log = @import("log.zig"); const log = @import("log.zig");
const platform_time = @import("platform").time;
/// Buffer type indicating intended usage /// Buffer type indicating intended usage
pub const BufferType = enum(u8) { pub const BufferType = enum(u8) {
@@ -58,11 +61,11 @@ pub const PoolConfig = struct {
/// Uses a sliding window algorithm for smooth rate limiting /// Uses a sliding window algorithm for smooth rate limiting
pub const RateLimiter = struct { pub const RateLimiter = struct {
/// Number of allocations in current window /// Number of allocations in current window
allocation_count: std.atomic.Value(u64), allocation_count: AtomicValue(u64),
/// Bytes allocated in current window /// Bytes allocated in current window
bytes_allocated: std.atomic.Value(u64), bytes_allocated: AtomicValue(u64),
/// Window start timestamp (ms since epoch) /// Window start timestamp (ms since epoch)
window_start_ms: std.atomic.Value(i64), window_start_ms: AtomicValue(i64),
/// Configuration limits /// Configuration limits
max_allocations_per_second: u32, max_allocations_per_second: u32,
max_bytes_per_second: u64, max_bytes_per_second: u64,
@@ -70,9 +73,9 @@ pub const RateLimiter = struct {
pub fn init(config: PoolConfig) RateLimiter { pub fn init(config: PoolConfig) RateLimiter {
return .{ return .{
.allocation_count = std.atomic.Value(u64).init(0), .allocation_count = AtomicValue(u64).init(0),
.bytes_allocated = std.atomic.Value(u64).init(0), .bytes_allocated = AtomicValue(u64).init(0),
.window_start_ms = std.atomic.Value(i64).init(std.time.milliTimestamp()), .window_start_ms = AtomicValue(i64).init(platform_time.milliTimestamp()),
.max_allocations_per_second = config.max_allocations_per_second, .max_allocations_per_second = config.max_allocations_per_second,
.max_bytes_per_second = config.max_bytes_per_second, .max_bytes_per_second = config.max_bytes_per_second,
.window_size_ms = config.rate_limit_window_ms, .window_size_ms = config.rate_limit_window_ms,
@@ -82,7 +85,7 @@ pub const RateLimiter = struct {
/// Check if allocation is allowed and record it if so /// Check if allocation is allowed and record it if so
/// Returns true if allowed, false if rate limited /// Returns true if allowed, false if rate limited
pub fn checkAndRecord(self: *RateLimiter, bytes: usize) bool { pub fn checkAndRecord(self: *RateLimiter, bytes: usize) bool {
const now_ms = std.time.milliTimestamp(); const now_ms = platform_time.milliTimestamp();
const window_start = self.window_start_ms.load(.acquire); const window_start = self.window_start_ms.load(.acquire);
// THR-M1 FIX: Properly synchronized window reset // THR-M1 FIX: Properly synchronized window reset
@@ -184,7 +187,7 @@ pub const BufferPool = struct {
chunks: std.ArrayList(PoolChunk), chunks: std.ArrayList(PoolChunk),
free_list_head: ?usize, // Index of first free chunk free_list_head: ?usize, // Index of first free chunk
allocator: mem.Allocator, allocator: mem.Allocator,
mutex: std.Thread.Mutex, mutex: Mutex,
/// SECURITY: Rate limiter for DoS prevention /// SECURITY: Rate limiter for DoS prevention
rate_limiter: RateLimiter, rate_limiter: RateLimiter,
@@ -437,7 +440,7 @@ const BufferBase = struct {
flags: BufferFlags, flags: BufferFlags,
pool: ?*BufferPool, pool: ?*BufferPool,
allocator: ?mem.Allocator, allocator: ?mem.Allocator,
ref_count: atomic.Value(u32), ref_count: AtomicValue(u32),
pub fn init(data: []u8, flags: BufferFlags, pool: ?*BufferPool) BufferBase { pub fn init(data: []u8, flags: BufferFlags, pool: ?*BufferPool) BufferBase {
return .{ return .{
@@ -448,7 +451,7 @@ const BufferBase = struct {
.flags = flags, .flags = flags,
.pool = pool, .pool = pool,
.allocator = null, .allocator = null,
.ref_count = atomic.Value(u32).init(1), .ref_count = AtomicValue(u32).init(1),
}; };
} }
@@ -461,7 +464,7 @@ const BufferBase = struct {
.flags = flags, .flags = flags,
.pool = null, .pool = null,
.allocator = allocator, .allocator = allocator,
.ref_count = atomic.Value(u32).init(1), .ref_count = AtomicValue(u32).init(1),
}; };
} }
@@ -891,7 +894,7 @@ pub const MessageBuffer = struct {
) void { ) void {
self.message_type = msg_type; self.message_type = msg_type;
self.message_id = msg_id; self.message_id = msg_id;
self.timestamp = std.time.timestamp(); self.timestamp = platform_time.timestamp();
} }
pub fn getMessageHeader(self: *const MessageBuffer) MessageHeader { pub fn getMessageHeader(self: *const MessageBuffer) MessageHeader {

View File

@@ -5,11 +5,15 @@
//! protocols with connection pooling, health checking, and graceful shutdown. //! protocols with connection pooling, health checking, and graceful shutdown.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const atomic = std.atomic;
const os = std.os; const os = std.os;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error; const Error = @import("error.zig").Error;
const Address = @import("address.zig").Address; const Address = @import("address.zig").Address;
const socket_mod = @import("socket.zig"); const socket_mod = @import("socket.zig");
@@ -17,6 +21,8 @@ const Socket = socket_mod.Socket;
const SocketConfig = socket_mod.SocketConfig; const SocketConfig = socket_mod.SocketConfig;
const Buffer = @import("buffer.zig"); const Buffer = @import("buffer.zig");
const log = @import("log.zig"); const log = @import("log.zig");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
/// Connection types /// Connection types
pub const ConnectionType = enum(u8) { pub const ConnectionType = enum(u8) {
@@ -51,33 +57,33 @@ pub const ConnectionConfig = struct {
/// Connection statistics /// Connection statistics
pub const ConnectionStats = struct { pub const ConnectionStats = struct {
bytes_sent: atomic.Value(u64), bytes_sent: AtomicValue(u64),
bytes_received: atomic.Value(u64), bytes_received: AtomicValue(u64),
messages_sent: atomic.Value(u64), messages_sent: AtomicValue(u64),
messages_received: atomic.Value(u64), messages_received: AtomicValue(u64),
connection_attempts: atomic.Value(u64), connection_attempts: AtomicValue(u64),
successful_connections: atomic.Value(u64), successful_connections: AtomicValue(u64),
failed_connections: atomic.Value(u64), failed_connections: AtomicValue(u64),
uptime: atomic.Value(i64), uptime: AtomicValue(i64),
last_activity: atomic.Value(i64), last_activity: AtomicValue(i64),
errors: atomic.Value(u64), errors: AtomicValue(u64),
health_checks: atomic.Value(u64), health_checks: AtomicValue(u64),
ref_count_errors: atomic.Value(u64), ref_count_errors: AtomicValue(u64),
pub fn init() ConnectionStats { pub fn init() ConnectionStats {
return .{ return .{
.bytes_sent = atomic.Value(u64).init(0), .bytes_sent = AtomicValue(u64).init(0),
.bytes_received = atomic.Value(u64).init(0), .bytes_received = AtomicValue(u64).init(0),
.messages_sent = atomic.Value(u64).init(0), .messages_sent = AtomicValue(u64).init(0),
.messages_received = atomic.Value(u64).init(0), .messages_received = AtomicValue(u64).init(0),
.connection_attempts = atomic.Value(u64).init(0), .connection_attempts = AtomicValue(u64).init(0),
.successful_connections = atomic.Value(u64).init(0), .successful_connections = AtomicValue(u64).init(0),
.failed_connections = atomic.Value(u64).init(0), .failed_connections = AtomicValue(u64).init(0),
.uptime = atomic.Value(i64).init(0), .uptime = AtomicValue(i64).init(0),
.last_activity = atomic.Value(i64).init(0), .last_activity = AtomicValue(i64).init(0),
.errors = atomic.Value(u64).init(0), .errors = AtomicValue(u64).init(0),
.health_checks = atomic.Value(u64).init(0), .health_checks = AtomicValue(u64).init(0),
.ref_count_errors = atomic.Value(u64).init(0), .ref_count_errors = AtomicValue(u64).init(0),
}; };
} }
@@ -116,7 +122,7 @@ pub const ConnectionStats = struct {
} }
} }
self.last_activity.store(std.time.timestamp(), .monotonic); self.last_activity.store(platform_time.timestamp(), .monotonic);
} }
/// CRIT-4 FIX: Record receive with atomic increment /// CRIT-4 FIX: Record receive with atomic increment
@@ -153,7 +159,7 @@ pub const ConnectionStats = struct {
} }
} }
self.last_activity.store(std.time.timestamp(), .monotonic); self.last_activity.store(platform_time.timestamp(), .monotonic);
} }
/// SECURITY FIX Issue 4: Increment counters with overflow detection /// SECURITY FIX Issue 4: Increment counters with overflow detection
@@ -173,7 +179,7 @@ pub const ConnectionStats = struct {
} else { } else {
std.log.warn("successful_connections counter saturated at maximum value", .{}); std.log.warn("successful_connections counter saturated at maximum value", .{});
} }
self.uptime.store(std.time.timestamp(), .monotonic); self.uptime.store(platform_time.timestamp(), .monotonic);
} }
pub fn recordFailedConnection(self: *ConnectionStats) void { pub fn recordFailedConnection(self: *ConnectionStats) void {
@@ -318,7 +324,7 @@ pub const HealthCheckResult = struct {
.status = .healthy, .status = .healthy,
.latency_ms = latency_ms, .latency_ms = latency_ms,
.err = null, .err = null,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -327,7 +333,7 @@ pub const HealthCheckResult = struct {
.status = .degraded, .status = .degraded,
.latency_ms = latency_ms, .latency_ms = latency_ms,
.err = e, .err = e,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -336,7 +342,7 @@ pub const HealthCheckResult = struct {
.status = .unhealthy, .status = .unhealthy,
.latency_ms = -1, .latency_ms = -1,
.err = e, .err = e,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -347,7 +353,7 @@ pub const Connection = struct {
connection_type: ConnectionType, connection_type: ConnectionType,
config: ConnectionConfig, config: ConnectionConfig,
/// Connection state - atomic for thread safety /// Connection state - atomic for thread safety
state: atomic.Value(ConnectionState), state: AtomicValue(ConnectionState),
socket: ?Socket, socket: ?Socket,
local_address: ?Address, local_address: ?Address,
remote_address: ?Address, remote_address: ?Address,
@@ -360,11 +366,11 @@ pub const Connection = struct {
/// Reference count for thread-safe shared ownership /// Reference count for thread-safe shared ownership
/// Starts at 1 when created, incremented by retain(), decremented by release() /// Starts at 1 when created, incremented by retain(), decremented by release()
ref_count: atomic.Value(u32), ref_count: AtomicValue(u32),
/// Mutex to protect socket operations from concurrent access /// Mutex to protect socket operations from concurrent access
/// Must be held during any socket read/write/connect/close operation /// Must be held during any socket read/write/connect/close operation
socket_mutex: std.Thread.Mutex, socket_mutex: Mutex,
pub fn init( pub fn init(
connection_type: ConnectionType, connection_type: ConnectionType,
@@ -373,7 +379,7 @@ pub const Connection = struct {
) Error!Connection { ) Error!Connection {
// Generate cryptographically random connection ID // Generate cryptographically random connection ID
var id_bytes: [8]u8 = undefined; var id_bytes: [8]u8 = undefined;
std.crypto.random.bytes(&id_bytes); platform_random.bytes(&id_bytes);
const id = std.mem.readInt(u64, &id_bytes, .little); const id = std.mem.readInt(u64, &id_bytes, .little);
const buffer_config = Buffer.PoolConfig{ const buffer_config = Buffer.PoolConfig{
@@ -387,7 +393,7 @@ pub const Connection = struct {
.id = id, .id = id,
.connection_type = connection_type, .connection_type = connection_type,
.config = config, .config = config,
.state = atomic.Value(ConnectionState).init(.disconnected), .state = AtomicValue(ConnectionState).init(.disconnected),
.socket = null, .socket = null,
.local_address = null, .local_address = null,
.remote_address = null, .remote_address = null,
@@ -396,8 +402,8 @@ pub const Connection = struct {
.last_health_check = 0, .last_health_check = 0,
.health_status = .unknown, .health_status = .unknown,
.allocator = allocator, .allocator = allocator,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.ref_count = atomic.Value(u32).init(1), .ref_count = AtomicValue(u32).init(1),
.socket_mutex = .{}, .socket_mutex = .{},
}; };
} }
@@ -438,7 +444,7 @@ pub const Connection = struct {
if (old_count == 0) { if (old_count == 0) {
_ = self.ref_count.fetchAdd(1, .acq_rel); // undo the wrapping fetchSub _ = self.ref_count.fetchAdd(1, .acq_rel); // undo the wrapping fetchSub
std.log.err("BUG: Connection ref count underflow (double-free). Stack trace:", .{}); std.log.err("BUG: Connection ref count underflow (double-free). Stack trace:", .{});
std.debug.dumpCurrentStackTrace(@returnAddress()); if (!is_wasm) std.debug.dumpCurrentStackTrace(@returnAddress());
return Error.InternalError; return Error.InternalError;
} }
return false; return false;
@@ -736,7 +742,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.milliTimestamp(); self.last_health_check = platform_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();
@@ -847,7 +853,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.milliTimestamp(); const now = platform_time.milliTimestamp();
return (now - self.last_health_check) >= self.config.health_check_interval; return (now - self.last_health_check) >= self.config.health_check_interval;
} }
@@ -856,7 +862,7 @@ pub const Connection = struct {
if (self.stats.getUptime() == 0) { if (self.stats.getUptime() == 0) {
return 0; return 0;
} }
return std.time.timestamp() - self.stats.getUptime(); return platform_time.timestamp() - self.stats.getUptime();
} }
/// Graceful shutdown with timeout /// Graceful shutdown with timeout
@@ -883,16 +889,18 @@ pub const Connection = struct {
if (self.connection_type == .tcp or self.connection_type == .unix_stream) { if (self.connection_type == .tcp or self.connection_type == .unix_stream) {
// Shutdown write side (send FIN) // Shutdown write side (send FIN)
if (socket.fd >= 0) { if (socket.fd >= 0) {
if (!is_wasm) {
std.posix.shutdown(socket.fd, .send) catch |err| { std.posix.shutdown(socket.fd, .send) catch |err| {
std.log.warn("Failed to shutdown write side (connection ID: {}): {}", .{ self.id, err }); std.log.warn("Failed to shutdown write side (connection ID: {}): {}", .{ self.id, err });
}; };
}
// Wait for remaining data with timeout // Wait for remaining data with timeout
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
var buffer: [1024]u8 = undefined; var buffer: [1024]u8 = undefined;
while (true) { while (true) {
const elapsed = std.time.milliTimestamp() - start_time; const elapsed = platform_time.milliTimestamp() - start_time;
if (elapsed > timeout_ms) { if (elapsed > timeout_ms) {
std.log.warn("Graceful shutdown timeout after {}ms (connection ID: {})", .{ timeout_ms, self.id }); std.log.warn("Graceful shutdown timeout after {}ms (connection ID: {})", .{ timeout_ms, self.id });
break; break;
@@ -932,7 +940,7 @@ pub const ConnectionPool = struct {
connections: std.ArrayList(*Connection), connections: std.ArrayList(*Connection),
config: ConnectionConfig, config: ConnectionConfig,
allocator: mem.Allocator, allocator: mem.Allocator,
mutex: std.Thread.Mutex, mutex: Mutex,
/// SECURITY FIX Issue 3: Maximum number of connections allowed in pool /// SECURITY FIX Issue 3: Maximum number of connections allowed in pool
max_pool_size: usize, max_pool_size: usize,
/// SECURITY: Maximum connections allowed per IP address /// SECURITY: Maximum connections allowed per IP address

View File

@@ -6,7 +6,10 @@
const std = @import("std"); const std = @import("std");
const testing = std.testing; const testing = std.testing;
const builtin = @import("builtin"); const builtin = @import("builtin");
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const log = @import("log.zig"); const log = @import("log.zig");
const platform_time = @import("platform").time;
/// Comprehensive error types for P2P networking operations /// Comprehensive error types for P2P networking operations
pub const Error = error{ pub const Error = error{
@@ -162,7 +165,7 @@ pub const ErrorInfo = struct {
.err = err, .err = err,
.message = message, .message = message,
.context = context, .context = context,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.location = .{ .location = .{
.file = file, .file = file,
.line = line, .line = line,
@@ -352,19 +355,19 @@ pub fn toInt(e: Error) i32 {
/// Error statistics and tracking /// Error statistics and tracking
pub const ErrorStats = struct { pub const ErrorStats = struct {
total_errors: std.atomic.Value(u64), total_errors: AtomicValue(u64),
/// Per-error counts using a simple array indexed by error code /// Per-error counts using a simple array indexed by error code
/// We use a fixed-size array for lock-free atomic access /// We use a fixed-size array for lock-free atomic access
error_counts: [256]std.atomic.Value(u64), error_counts: [256]AtomicValue(u64),
pub fn init() ErrorStats { pub fn init() ErrorStats {
var stats = ErrorStats{ var stats = ErrorStats{
.total_errors = std.atomic.Value(u64).init(0), .total_errors = AtomicValue(u64).init(0),
.error_counts = undefined, .error_counts = undefined,
}; };
// Initialize all error counts to 0 // Initialize all error counts to 0
for (&stats.error_counts) |*count| { for (&stats.error_counts) |*count| {
count.* = std.atomic.Value(u64).init(0); count.* = AtomicValue(u64).init(0);
} }
return stats; return stats;
} }
@@ -388,14 +391,14 @@ pub const ErrorStats = struct {
/// Enhanced error metrics with detailed tracking /// Enhanced error metrics with detailed tracking
pub const ErrorMetrics = struct { pub const ErrorMetrics = struct {
total_errors: std.atomic.Value(u64), total_errors: AtomicValue(u64),
errors_by_type: std.AutoHashMap(Error, u64), errors_by_type: std.AutoHashMap(Error, u64),
mutex: std.Thread.Mutex, mutex: Mutex,
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) ErrorMetrics { pub fn init(allocator: std.mem.Allocator) ErrorMetrics {
return .{ return .{
.total_errors = std.atomic.Value(u64).init(0), .total_errors = AtomicValue(u64).init(0),
.errors_by_type = std.AutoHashMap(Error, u64).init(allocator), .errors_by_type = std.AutoHashMap(Error, u64).init(allocator),
.mutex = .{}, .mutex = .{},
.allocator = allocator, .allocator = allocator,
@@ -448,7 +451,7 @@ pub const ErrorSnapshot = struct {
}; };
/// Global error statistics instance /// Global error statistics instance
var global_error_stats: std.atomic.Value(?*ErrorStats) = std.atomic.Value(?*ErrorStats).init(null); var global_error_stats: AtomicValue(?*ErrorStats) = AtomicValue(?*ErrorStats).init(null);
pub fn getGlobalErrorStats() ?*ErrorStats { pub fn getGlobalErrorStats() ?*ErrorStats {
return global_error_stats.load(.monotonic); return global_error_stats.load(.monotonic);

View File

@@ -5,28 +5,29 @@
const std = @import("std"); const std = @import("std");
const mem = std.mem; const mem = std.mem;
const time = std.time; const platform_time = @import("time");
const AtomicValue = @import("sync").AtomicValue;
const log = @import("log.zig"); const log = @import("log.zig");
/// Token bucket rate limiter /// Token bucket rate limiter
pub const RateLimiter = struct { pub const RateLimiter = struct {
/// Current number of tokens /// Current number of tokens
tokens: std.atomic.Value(u64), tokens: AtomicValue(u64),
/// Maximum tokens (burst capacity) /// Maximum tokens (burst capacity)
max_tokens: u64, max_tokens: u64,
/// Token refill rate (tokens per second) /// Token refill rate (tokens per second)
refill_rate: u64, refill_rate: u64,
/// Last refill timestamp (nanoseconds) /// Last refill timestamp (nanoseconds)
last_refill: std.atomic.Value(i64), last_refill: AtomicValue(i64),
/// Mutex for non-atomic operations /// Mutex for non-atomic operations
mutex: std.Thread.Mutex = .{}, mutex: std.Thread.Mutex = .{},
pub fn init(config: Config) RateLimiter { pub fn init(config: Config) RateLimiter {
return .{ return .{
.tokens = std.atomic.Value(u64).init(config.burst_size), .tokens = AtomicValue(u64).init(config.burst_size),
.max_tokens = config.burst_size, .max_tokens = config.burst_size,
.refill_rate = config.tokens_per_second, .refill_rate = config.tokens_per_second,
.last_refill = std.atomic.Value(i64).init(@intCast(time.nanoTimestamp())), .last_refill = AtomicValue(i64).init(@intCast(platform_time.nanoTimestamp())),
}; };
} }
@@ -79,7 +80,7 @@ pub const RateLimiter = struct {
/// Refill tokens based on elapsed time /// Refill tokens based on elapsed time
fn refill(self: *RateLimiter) void { fn refill(self: *RateLimiter) void {
const now: i64 = @intCast(time.nanoTimestamp()); const now: i64 = @intCast(platform_time.nanoTimestamp());
const last = self.last_refill.load(.acquire); const last = self.last_refill.load(.acquire);
const elapsed_ns = now - last; const elapsed_ns = now - last;
@@ -87,7 +88,7 @@ pub const RateLimiter = struct {
// Calculate tokens to add (using nanoseconds for precision) // Calculate tokens to add (using nanoseconds for precision)
const elapsed_ns_u64: u64 = @intCast(elapsed_ns); const elapsed_ns_u64: u64 = @intCast(elapsed_ns);
const elapsed_seconds = elapsed_ns_u64 / time.ns_per_s; const elapsed_seconds = elapsed_ns_u64 / 1_000_000_000;
if (elapsed_seconds == 0) return; if (elapsed_seconds == 0) return;
const new_tokens = elapsed_seconds * self.refill_rate; const new_tokens = elapsed_seconds * self.refill_rate;
@@ -238,7 +239,7 @@ pub const ConnectionRateLimiter = struct {
return false; return false;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Check per-IP rate limit // Check per-IP rate limit
self.mutex.lock(); self.mutex.lock();

View File

@@ -5,16 +5,23 @@
//! with both synchronous and asynchronous operation modes. //! with both synchronous and asynchronous operation modes.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing; const testing = std.testing;
const os = std.os; const os = std.os;
const posix = std.posix; const posix = if (!is_wasm) std.posix else undefined;
const net = std.net; const net = if (!is_wasm) std.net else undefined;
const fd_t = if (!is_wasm) std.posix.fd_t else i32;
const mem = std.mem; const mem = std.mem;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Error = @import("error.zig").Error; const Error = @import("error.zig").Error;
const Address = @import("address.zig").Address; const Address = @import("address.zig").Address;
const log = @import("log.zig"); const log = @import("log.zig");
const Buffer = @import("buffer.zig"); const Buffer = @import("buffer.zig");
const platform_time = @import("platform").time;
/// Socket protocol types /// Socket protocol types
pub const SocketProtocol = enum(u8) { pub const SocketProtocol = enum(u8) {
@@ -64,28 +71,28 @@ pub const SocketState = enum(u8) {
/// Socket statistics /// Socket statistics
/// THR-M2 FIX: Use atomics for thread-safe access from multiple threads /// THR-M2 FIX: Use atomics for thread-safe access from multiple threads
pub const SocketStats = struct { pub const SocketStats = struct {
bytes_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), bytes_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
bytes_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), bytes_received: AtomicValue(u64) = AtomicValue(u64).init(0),
packets_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), packets_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
packets_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), packets_received: AtomicValue(u64) = AtomicValue(u64).init(0),
errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), errors: AtomicValue(u64) = AtomicValue(u64).init(0),
last_activity: std.atomic.Value(i64) = std.atomic.Value(i64).init(0), last_activity: AtomicValue(i64) = AtomicValue(i64).init(0),
pub fn recordSend(self: *SocketStats, bytes: usize) void { pub fn recordSend(self: *SocketStats, bytes: usize) void {
_ = self.bytes_sent.fetchAdd(bytes, .monotonic); _ = self.bytes_sent.fetchAdd(bytes, .monotonic);
_ = self.packets_sent.fetchAdd(1, .monotonic); _ = self.packets_sent.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic); self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
} }
pub fn recordReceive(self: *SocketStats, bytes: usize) void { pub fn recordReceive(self: *SocketStats, bytes: usize) void {
_ = self.bytes_received.fetchAdd(bytes, .monotonic); _ = self.bytes_received.fetchAdd(bytes, .monotonic);
_ = self.packets_received.fetchAdd(1, .monotonic); _ = self.packets_received.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic); self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
} }
pub fn recordError(self: *SocketStats) void { pub fn recordError(self: *SocketStats) void {
_ = self.errors.fetchAdd(1, .monotonic); _ = self.errors.fetchAdd(1, .monotonic);
self.last_activity.store(std.time.milliTimestamp(), .monotonic); self.last_activity.store(platform_time.milliTimestamp(), .monotonic);
} }
/// Get snapshot of current stats (THR-M2 FIX: thread-safe getters) /// Get snapshot of current stats (THR-M2 FIX: thread-safe getters)
@@ -116,7 +123,7 @@ pub const SocketStats = struct {
/// Main socket abstraction /// Main socket abstraction
pub const Socket = struct { pub const Socket = struct {
fd: posix.fd_t, fd: fd_t,
config: SocketConfig, config: SocketConfig,
state: SocketState, state: SocketState,
stats: SocketStats, stats: SocketStats,
@@ -151,6 +158,7 @@ pub const Socket = struct {
/// Create system socket /// Create system socket
pub fn open(self: *Socket) Error!void { pub fn open(self: *Socket) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .created) { if (self.state != .created) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -181,6 +189,7 @@ pub const Socket = struct {
} }
fn applyOptions(self: *Socket) Error!void { fn applyOptions(self: *Socket) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// ERR-H2 FIX: Track compound failures to detect systemic socket option issues // ERR-H2 FIX: Track compound failures to detect systemic socket option issues
var option_failures: u32 = 0; var option_failures: u32 = 0;
const MAX_TOLERATED_FAILURES: u32 = 3; const MAX_TOLERATED_FAILURES: u32 = 3;
@@ -311,6 +320,7 @@ pub const Socket = struct {
/// Set socket to non-blocking mode /// Set socket to non-blocking mode
pub fn setNonBlocking(self: *Socket, non_blocking: bool) Error!void { pub fn setNonBlocking(self: *Socket, non_blocking: bool) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state == .created or self.state == .closed) { if (self.state == .created or self.state == .closed) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -341,6 +351,7 @@ pub const Socket = struct {
/// Set socket send timeout (useful for making sends non-blocking after connection) /// Set socket send timeout (useful for making sends non-blocking after connection)
/// A timeout of 0 means the send will return immediately if it would block /// A timeout of 0 means the send will return immediately if it would block
pub fn setSendTimeout(self: *Socket, timeout_ms: u32) Error!void { pub fn setSendTimeout(self: *Socket, timeout_ms: u32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.state == .created or self.state == .closed) { if (self.state == .created or self.state == .closed) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -361,6 +372,7 @@ pub const Socket = struct {
/// Bind socket to address /// Bind socket to address
pub fn bind(self: *Socket, address: Address) Error!void { pub fn bind(self: *Socket, address: Address) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Can bind from created (will auto-open) or opened state // Can bind from created (will auto-open) or opened state
if (self.state != .created and self.state != .opened) { if (self.state != .created and self.state != .opened) {
return Error.InvalidState; return Error.InvalidState;
@@ -404,6 +416,7 @@ pub const Socket = struct {
/// Listen for connections (TCP only) /// Listen for connections (TCP only)
pub fn listen(self: *Socket, backlog: u32) Error!void { pub fn listen(self: *Socket, backlog: u32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .tcp and self.config.protocol != .unix_stream) { if (self.config.protocol != .tcp and self.config.protocol != .unix_stream) {
return Error.OperationNotSupported; return Error.OperationNotSupported;
} }
@@ -429,6 +442,7 @@ pub const Socket = struct {
/// Accept incoming connection /// Accept incoming connection
pub fn accept(self: *Socket) Error!Socket { pub fn accept(self: *Socket) Error!Socket {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .listening) { if (self.state != .listening) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -459,7 +473,7 @@ pub const Socket = struct {
client_socket.fd = client_fd; client_socket.fd = client_fd;
client_socket.state = .connected; client_socket.state = .connected;
client_socket.local_address = self.local_address; client_socket.local_address = self.local_address;
client_socket.stats.last_activity.store(std.time.milliTimestamp(), .monotonic); client_socket.stats.last_activity.store(platform_time.milliTimestamp(), .monotonic);
// Extract and store peer address // Extract and store peer address
// Convert IPv4 address bytes and create proper Address // Convert IPv4 address bytes and create proper Address
@@ -482,6 +496,7 @@ pub const Socket = struct {
/// Connect to remote address /// Connect to remote address
pub fn connect(self: *Socket, address: Address) Error!void { pub fn connect(self: *Socket, address: Address) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Auto-open socket if needed // Auto-open socket if needed
if (self.state == .created) { if (self.state == .created) {
try self.open(); try self.open();
@@ -513,11 +528,12 @@ pub const Socket = struct {
self.remote_address = address; self.remote_address = address;
self.state = .connected; self.state = .connected;
self.stats.last_activity.store(std.time.milliTimestamp(), .monotonic); self.stats.last_activity.store(platform_time.milliTimestamp(), .monotonic);
} }
/// Send data over socket /// Send data over socket
pub fn send(self: *Socket, data: []const u8) Error!usize { pub fn send(self: *Socket, data: []const u8) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .connected and self.state != .bound) { if (self.state != .connected and self.state != .bound) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -535,6 +551,7 @@ pub const Socket = struct {
/// Send data to specific address (UDP only) /// Send data to specific address (UDP only)
pub fn sendTo(self: *Socket, data: []const u8, address: Address) Error!usize { pub fn sendTo(self: *Socket, data: []const u8, address: Address) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) { if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) {
return Error.OperationNotSupported; return Error.OperationNotSupported;
} }
@@ -562,6 +579,7 @@ pub const Socket = struct {
/// Receive data from socket /// Receive data from socket
pub fn receive(self: *Socket, buffer: []u8) Error!usize { pub fn receive(self: *Socket, buffer: []u8) Error!usize {
if (is_wasm) return Error.OperationNotSupported;
if (self.state != .connected and self.state != .bound) { if (self.state != .connected and self.state != .bound) {
return Error.InvalidState; return Error.InvalidState;
} }
@@ -585,6 +603,7 @@ pub const Socket = struct {
/// Receive data and get sender address (UDP only) /// Receive data and get sender address (UDP only)
pub fn receiveFrom(self: *Socket, buffer: []u8) Error!struct { size: usize, address: Address } { pub fn receiveFrom(self: *Socket, buffer: []u8) Error!struct { size: usize, address: Address } {
if (is_wasm) return Error.OperationNotSupported;
if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) { if (self.config.protocol != .udp and self.config.protocol != .unix_dgram) {
return Error.OperationNotSupported; return Error.OperationNotSupported;
} }
@@ -629,6 +648,11 @@ pub const Socket = struct {
// Skip if already closed or never opened (fd would be -1) // Skip if already closed or never opened (fd would be -1)
if (self.state == .closed or self.state == .created) return; if (self.state == .closed or self.state == .created) return;
if (is_wasm) {
self.state = .closed;
return;
}
// Check if fd is valid before closing // Check if fd is valid before closing
if (self.fd < 0) { if (self.fd < 0) {
self.state = .closed; self.state = .closed;
@@ -643,6 +667,7 @@ pub const Socket = struct {
/// Get socket option /// Get socket option
pub fn getOption(self: *Socket, option: SocketOption) Error!i32 { pub fn getOption(self: *Socket, option: SocketOption) Error!i32 {
if (is_wasm) return Error.OperationNotSupported;
// Ensure socket is opened before getting options // Ensure socket is opened before getting options
if (self.state == .created) { if (self.state == .created) {
try self.open(); try self.open();
@@ -688,6 +713,7 @@ pub const Socket = struct {
/// Set socket option /// Set socket option
pub fn setOption(self: *Socket, option: SocketOption, value: i32) Error!void { pub fn setOption(self: *Socket, option: SocketOption, value: i32) Error!void {
if (is_wasm) return Error.OperationNotSupported;
// Ensure socket is opened before setting options // Ensure socket is opened before setting options
if (self.state == .created) { if (self.state == .created) {
try self.open(); try self.open();
@@ -724,6 +750,7 @@ pub const Socket = struct {
/// Check if socket is ready for reading /// Check if socket is ready for reading
pub fn canRead(self: *const Socket) Error!bool { pub fn canRead(self: *const Socket) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
var fds = [_]posix.pollfd{.{ var fds = [_]posix.pollfd{.{
.fd = self.fd, .fd = self.fd,
.events = posix.POLL.IN, .events = posix.POLL.IN,
@@ -736,6 +763,7 @@ pub const Socket = struct {
/// Check if socket is ready for writing /// Check if socket is ready for writing
pub fn canWrite(self: *const Socket) Error!bool { pub fn canWrite(self: *const Socket) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
var fds = [_]posix.pollfd{.{ var fds = [_]posix.pollfd{.{
.fd = self.fd, .fd = self.fd,
.events = posix.POLL.OUT, .events = posix.POLL.OUT,
@@ -812,7 +840,7 @@ pub const SocketManager = struct {
allocator: mem.Allocator, allocator: mem.Allocator,
sockets: std.ArrayList(Socket), sockets: std.ArrayList(Socket),
factory: SocketFactory, factory: SocketFactory,
mutex: std.Thread.Mutex, mutex: Mutex,
pub fn init(allocator: mem.Allocator) SocketManager { pub fn init(allocator: mem.Allocator) SocketManager {
return .{ return .{
@@ -857,7 +885,7 @@ pub const SocketManager = struct {
} }
/// Remove socket by file descriptor - safe even if ArrayList has reallocated /// Remove socket by file descriptor - safe even if ArrayList has reallocated
pub fn removeSocketByFd(self: *SocketManager, fd: std.posix.fd_t) void { pub fn removeSocketByFd(self: *SocketManager, fd: fd_t) void {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();

View File

@@ -12,6 +12,8 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const limits = @import("limits.zig"); const limits = @import("limits.zig");
/// Thread-safe global memory tracking allocator /// Thread-safe global memory tracking allocator
@@ -23,19 +25,19 @@ pub const TrackingAllocator = struct {
max_bytes: u64, max_bytes: u64,
/// Current allocated bytes (atomic for thread safety) /// Current allocated bytes (atomic for thread safety)
allocated_bytes: std.atomic.Value(u64), allocated_bytes: AtomicValue(u64),
/// Peak allocation (for diagnostics) /// Peak allocation (for diagnostics)
peak_bytes: std.atomic.Value(u64), peak_bytes: AtomicValue(u64),
/// Number of rejected allocations (for diagnostics) /// Number of rejected allocations (for diagnostics)
rejected_count: std.atomic.Value(u64), rejected_count: AtomicValue(u64),
/// Number of successful allocations (for diagnostics) /// Number of successful allocations (for diagnostics)
allocation_count: std.atomic.Value(u64), allocation_count: AtomicValue(u64),
/// Number of frees (for diagnostics) /// Number of frees (for diagnostics)
free_count: std.atomic.Value(u64), free_count: AtomicValue(u64),
const Self = @This(); const Self = @This();
@@ -55,11 +57,11 @@ pub const TrackingAllocator = struct {
return .{ return .{
.backing_allocator = backing_allocator, .backing_allocator = backing_allocator,
.max_bytes = max_bytes, .max_bytes = max_bytes,
.allocated_bytes = std.atomic.Value(u64).init(0), .allocated_bytes = AtomicValue(u64).init(0),
.peak_bytes = std.atomic.Value(u64).init(0), .peak_bytes = AtomicValue(u64).init(0),
.rejected_count = std.atomic.Value(u64).init(0), .rejected_count = AtomicValue(u64).init(0),
.allocation_count = std.atomic.Value(u64).init(0), .allocation_count = AtomicValue(u64).init(0),
.free_count = std.atomic.Value(u64).init(0), .free_count = AtomicValue(u64).init(0),
}; };
} }
@@ -316,7 +318,7 @@ pub const TrackingAllocator = struct {
/// Global tracking allocator instance (optional singleton pattern) /// Global tracking allocator instance (optional singleton pattern)
var global_tracker: ?TrackingAllocator = null; var global_tracker: ?TrackingAllocator = null;
var global_tracker_mutex: std.Thread.Mutex = .{}; var global_tracker_mutex: Mutex = .{};
/// Initialize the global tracking allocator /// Initialize the global tracking allocator
/// Thread-safe, can be called multiple times (only first call takes effect) /// Thread-safe, can be called multiple times (only first call takes effect)

View File

@@ -24,9 +24,12 @@
//! - Pool calls release() when removing; if last ref, frees memory //! - Pool calls release() when removing; if last ref, frees memory
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const mem = std.mem; const mem = std.mem;
const atomic = std.atomic; const Mutex = @import("sync").Mutex;
const Mutex = std.Thread.Mutex; const AtomicValue = @import("sync").AtomicValue;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -83,7 +86,7 @@ pub const NetworkBridge = struct {
mutex: Mutex, mutex: Mutex,
/// Running state (atomic for lock-free checks) /// Running state (atomic for lock-free checks)
running: atomic.Value(bool), running: AtomicValue(bool),
/// Listen address /// Listen address
listen_address: Address, listen_address: Address,
@@ -97,19 +100,19 @@ pub const NetworkBridge = struct {
/// Bridge statistics /// Bridge statistics
pub const Stats = struct { pub const Stats = struct {
total_connections: atomic.Value(u64), total_connections: AtomicValue(u64),
active_connections: atomic.Value(u64), active_connections: AtomicValue(u64),
failed_connections: atomic.Value(u64), failed_connections: AtomicValue(u64),
total_bytes_sent: atomic.Value(u64), total_bytes_sent: AtomicValue(u64),
total_bytes_received: atomic.Value(u64), total_bytes_received: AtomicValue(u64),
pub fn init() Stats { pub fn init() Stats {
return .{ return .{
.total_connections = atomic.Value(u64).init(0), .total_connections = AtomicValue(u64).init(0),
.active_connections = atomic.Value(u64).init(0), .active_connections = AtomicValue(u64).init(0),
.failed_connections = atomic.Value(u64).init(0), .failed_connections = AtomicValue(u64).init(0),
.total_bytes_sent = atomic.Value(u64).init(0), .total_bytes_sent = AtomicValue(u64).init(0),
.total_bytes_received = atomic.Value(u64).init(0), .total_bytes_received = AtomicValue(u64).init(0),
}; };
} }
}; };
@@ -135,7 +138,7 @@ pub const NetworkBridge = struct {
.address_to_peer = std.StringHashMap(PeerId).init(allocator), .address_to_peer = std.StringHashMap(PeerId).init(allocator),
.listen_socket = null, .listen_socket = null,
.mutex = Mutex{}, .mutex = Mutex{},
.running = atomic.Value(bool).init(false), .running = AtomicValue(bool).init(false),
.listen_address = listen_address, .listen_address = listen_address,
.stats = Stats.init(), .stats = Stats.init(),
.message_callback = null, .message_callback = null,
@@ -203,6 +206,7 @@ pub const NetworkBridge = struct {
// CRIT-NEW-13 FIX: Set accept timeout on listen socket // CRIT-NEW-13 FIX: Set accept timeout on listen socket
// This provides additional protection against blocking accept() // This provides additional protection against blocking accept()
if (!is_wasm) {
const timeout_sec = ACCEPT_TIMEOUT_MS / 1000; const timeout_sec = ACCEPT_TIMEOUT_MS / 1000;
const timeout_usec = (ACCEPT_TIMEOUT_MS % 1000) * 1000; const timeout_usec = (ACCEPT_TIMEOUT_MS % 1000) * 1000;
const timeout = std.posix.timeval{ const timeout = std.posix.timeval{
@@ -212,6 +216,7 @@ pub const NetworkBridge = struct {
_ = std.posix.setsockopt(socket.fd, std.posix.SOL.SOCKET, std.posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch |err| { _ = std.posix.setsockopt(socket.fd, std.posix.SOL.SOCKET, std.posix.SO.RCVTIMEO, std.mem.asBytes(&timeout)) catch |err| {
std.log.warn("CRIT-NEW-13: Failed to set accept timeout: {}", .{err}); std.log.warn("CRIT-NEW-13: Failed to set accept timeout: {}", .{err});
}; };
}
// Start listening // Start listening
try socket.listen(128); // Backlog of 128 pending connections try socket.listen(128); // Backlog of 128 pending connections
@@ -285,12 +290,12 @@ pub const NetworkBridge = struct {
errdefer self.connection_pool.removeConnection(connection); errdefer self.connection_pool.removeConnection(connection);
// Measure connection latency // Measure connection latency
const start_time = std.time.nanoTimestamp(); const start_time = platform_time.nanoTimestamp();
connection.connect(address) catch |err| { connection.connect(address) catch |err| {
_ = self.stats.failed_connections.fetchAdd(1, .monotonic); _ = self.stats.failed_connections.fetchAdd(1, .monotonic);
return err; return err;
}; };
const end_time = std.time.nanoTimestamp(); const end_time = platform_time.nanoTimestamp();
const latency_ns = end_time - start_time; const latency_ns = end_time - start_time;
_ = latency_ns; // Store for later use if needed _ = latency_ns; // Store for later use if needed

View File

@@ -7,7 +7,10 @@
const std = @import("std"); const std = @import("std");
const mem = std.mem; const mem = std.mem;
const Allocator = mem.Allocator; const Allocator = mem.Allocator;
const crypto = std.crypto; const Mutex = @import("sync").Mutex;
const platform = @import("platform");
const platform_random = platform.random;
const platform_time = platform.time;
const core = @import("core"); const core = @import("core");
const Error = core.Error; const Error = core.Error;
@@ -58,7 +61,7 @@ pub const ConnectionBackoff = struct {
/// Configuration /// Configuration
config: BackoffConfig, config: BackoffConfig,
/// Thread safety /// Thread safety
mutex: std.Thread.Mutex, mutex: Mutex,
/// Allocator for hashmap /// Allocator for hashmap
allocator: Allocator, allocator: Allocator,
/// Timestamp of last automatic cleanup /// Timestamp of last automatic cleanup
@@ -73,7 +76,7 @@ pub const ConnectionBackoff = struct {
.config = config, .config = config,
.mutex = .{}, .mutex = .{},
.allocator = allocator, .allocator = allocator,
.last_cleanup_time = std.time.timestamp(), .last_cleanup_time = platform_time.timestamp(),
}; };
} }
@@ -91,7 +94,7 @@ pub const ConnectionBackoff = struct {
if (!state.in_backoff) return true; if (!state.in_backoff) return true;
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Check if backoff period has expired // Check if backoff period has expired
if (now >= state.backoff_until) { if (now >= state.backoff_until) {
@@ -110,7 +113,7 @@ pub const ConnectionBackoff = struct {
if (!state.in_backoff) return 0; if (!state.in_backoff) return 0;
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (now >= state.backoff_until) return 0; if (now >= state.backoff_until) return 0;
return @intCast((state.backoff_until - now) * 1000); return @intCast((state.backoff_until - now) * 1000);
@@ -122,7 +125,7 @@ pub const ConnectionBackoff = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Automatic cleanup: run when interval elapsed or map exceeds max_entries // Automatic cleanup: run when interval elapsed or map exceeds max_entries
if (now - self.last_cleanup_time >= self.config.cleanup_interval_secs or if (now - self.last_cleanup_time >= self.config.cleanup_interval_secs or
@@ -240,7 +243,7 @@ pub const ConnectionBackoff = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
return self.cleanupExpiredLocked(std.time.timestamp()); return self.cleanupExpiredLocked(platform_time.timestamp());
} }
/// Internal cleanup that assumes mutex is already held /// Internal cleanup that assumes mutex is already held
@@ -290,7 +293,7 @@ pub const ConnectionBackoff = struct {
// Get random bytes for jitter calculation // Get random bytes for jitter calculation
var random_bytes: [4]u8 = undefined; var random_bytes: [4]u8 = undefined;
crypto.random.bytes(&random_bytes); platform_random.bytes(&random_bytes);
const random_val = mem.readInt(u32, &random_bytes, .little); const random_val = mem.readInt(u32, &random_bytes, .little);
// Calculate jitter range // Calculate jitter range

View File

@@ -10,6 +10,10 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const routing = @import("routing.zig"); const routing = @import("routing.zig");
const peer_mod = @import("peer.zig"); const peer_mod = @import("peer.zig");
const topology = @import("topology.zig"); const topology = @import("topology.zig");
@@ -164,7 +168,7 @@ pub const SignedDhtMessage = struct {
/// Verify the signature and timestamp /// Verify the signature and timestamp
pub fn verify(self: SignedDhtMessage, signing_data: []const u8) DhtError!void { pub fn verify(self: SignedDhtMessage, signing_data: []const u8) DhtError!void {
// Check timestamp is not too old // Check timestamp is not too old
const now = std.time.timestamp(); const now = platform_time.timestamp();
const age = now - self.timestamp; const age = now - self.timestamp;
if (age > MAX_MESSAGE_AGE or age < -60) { // Allow 60 seconds clock skew if (age > MAX_MESSAGE_AGE or age < -60) { // Allow 60 seconds clock skew
std.log.warn("DHT: Rejected message with invalid timestamp (age: {d}s)", .{age}); std.log.warn("DHT: Rejected message with invalid timestamp (age: {d}s)", .{age});
@@ -467,9 +471,9 @@ pub const DhtCoordinator = struct {
/// Starts at 1 on all nodes — this is safe because replay protection uses per-message /// Starts at 1 on all nodes — this is safe because replay protection uses per-message
/// random wire_nonce (not request_id) for global deduplication. request_id is only used /// random wire_nonce (not request_id) for global deduplication. request_id is only used
/// for correlating request/response pairs within a single node. /// for correlating request/response pairs within a single node.
next_request_id: std.atomic.Value(u64) = std.atomic.Value(u64).init(1), next_request_id: AtomicValue(u64) = AtomicValue(u64).init(1),
/// Mutex for thread safety /// Mutex for thread safety
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
// SECURITY: Authentication infrastructure // SECURITY: Authentication infrastructure
/// Ed25519 identity keypair for signing DHT messages /// Ed25519 identity keypair for signing DHT messages
@@ -598,8 +602,8 @@ pub const DhtCoordinator = struct {
return; return;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
const now_ms = std.time.milliTimestamp(); const now_ms = platform_time.milliTimestamp();
if (self.peer_rate_limits.getPtr(peer_id)) |rate_limit| { if (self.peer_rate_limits.getPtr(peer_id)) |rate_limit| {
// Check minimum interval // Check minimum interval
@@ -717,7 +721,7 @@ pub const DhtCoordinator = struct {
/// SECURITY: Sign a message for sending /// SECURITY: Sign a message for sending
fn signMessage(self: *DhtCoordinator, request_id: u64, msg_type: u8, payload: []const u8) !SignedDhtMessage { fn signMessage(self: *DhtCoordinator, request_id: u64, msg_type: u8, payload: []const u8) !SignedDhtMessage {
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
const signing_data = try SignedDhtMessage.createSigningData( const signing_data = try SignedDhtMessage.createSigningData(
self.allocator, self.allocator,
request_id, request_id,
@@ -863,7 +867,7 @@ pub const DhtCoordinator = struct {
.request_id = request_id, .request_id = request_id,
.target = node_id, .target = node_id,
.query_type = .find_node, .query_type = .find_node,
.sent_at = std.time.timestamp(), .sent_at = platform_time.timestamp(),
}); });
queries_sent += 1; queries_sent += 1;
state.queries_in_flight += 1; state.queries_in_flight += 1;
@@ -1072,7 +1076,7 @@ pub const DhtCoordinator = struct {
self.discovered_peers.put(node_info.node_id, .{ self.discovered_peers.put(node_info.node_id, .{
.peer = peer_ptr, .peer = peer_ptr,
.position = position_ptr, .position = position_ptr,
.discovered_at = std.time.timestamp(), .discovered_at = platform_time.timestamp(),
}) catch |err| { }) catch |err| {
std.log.debug("DHT: Failed to track discovered peer: {}", .{err}); std.log.debug("DHT: Failed to track discovered peer: {}", .{err});
}; };
@@ -1252,7 +1256,7 @@ pub const DhtCoordinator = struct {
.request_id = request_id, .request_id = request_id,
.target = node_id, .target = node_id,
.query_type = .store, .query_type = .store,
.sent_at = std.time.timestamp(), .sent_at = platform_time.timestamp(),
}); });
sent_count += 1; sent_count += 1;
} }
@@ -1271,7 +1275,7 @@ pub const DhtCoordinator = struct {
// Check local storage first // Check local storage first
if (self.storage.get(key)) |stored| { if (self.storage.get(key)) |stored| {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (stored.expires_at > now) { if (stored.expires_at > now) {
// Return a copy of the value // Return a copy of the value
return try self.allocator.dupe(u8, stored.data); return try self.allocator.dupe(u8, stored.data);
@@ -1309,7 +1313,7 @@ pub const DhtCoordinator = struct {
.request_id = request_id, .request_id = request_id,
.target = node_id, .target = node_id,
.query_type = .find_value, .query_type = .find_value,
.sent_at = std.time.timestamp(), .sent_at = platform_time.timestamp(),
.search_key = key, .search_key = key,
}); });
sent_count += 1; sent_count += 1;
@@ -1379,7 +1383,7 @@ pub const DhtCoordinator = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
var to_remove: std.ArrayListUnmanaged(u64) = .{}; var to_remove: std.ArrayListUnmanaged(u64) = .{};
defer to_remove.deinit(self.allocator); defer to_remove.deinit(self.allocator);
@@ -1414,7 +1418,7 @@ pub const DhtCoordinator = struct {
if (self.pending_responses.count() >= MAX_PENDING_RESPONSES) { if (self.pending_responses.count() >= MAX_PENDING_RESPONSES) {
std.log.warn("DHT: Pending response limit reached ({}), forcing cleanup", .{MAX_PENDING_RESPONSES}); std.log.warn("DHT: Pending response limit reached ({}), forcing cleanup", .{MAX_PENDING_RESPONSES});
// Force cleanup of old entries (30 second timeout for forced cleanup) // Force cleanup of old entries (30 second timeout for forced cleanup)
const now = std.time.timestamp(); const now = platform_time.timestamp();
var to_remove: std.ArrayListUnmanaged(u64) = .{}; var to_remove: std.ArrayListUnmanaged(u64) = .{};
defer to_remove.deinit(self.allocator); defer to_remove.deinit(self.allocator);
@@ -1678,7 +1682,7 @@ pub const DhtCoordinator = struct {
const value_copy = try self.allocator.dupe(u8, value); const value_copy = try self.allocator.dupe(u8, value);
errdefer self.allocator.free(value_copy); errdefer self.allocator.free(value_copy);
const now = std.time.timestamp(); const now = platform_time.timestamp();
try self.storage.put(key, .{ try self.storage.put(key, .{
.data = value_copy, .data = value_copy,
.expires_at = now + @as(i64, @intCast(ttl)), .expires_at = now + @as(i64, @intCast(ttl)),
@@ -1717,7 +1721,7 @@ pub const DhtCoordinator = struct {
const value_copy = try self.allocator.dupe(u8, value); const value_copy = try self.allocator.dupe(u8, value);
errdefer self.allocator.free(value_copy); errdefer self.allocator.free(value_copy);
const now = std.time.timestamp(); const now = platform_time.timestamp();
try self.storage.put(key, .{ try self.storage.put(key, .{
.data = value_copy, .data = value_copy,
.expires_at = now + @as(i64, @intCast(ttl)), .expires_at = now + @as(i64, @intCast(ttl)),
@@ -1749,7 +1753,7 @@ pub const DhtCoordinator = struct {
// Check local storage // Check local storage
if (self.storage.get(msg.key)) |stored| { if (self.storage.get(msg.key)) |stored| {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (stored.expires_at > now) { if (stored.expires_at > now) {
// SECURITY: Sign the response // SECURITY: Sign the response
const auth = try self.signMessage(msg.request_id, DhtFindValueResponse.MSG_TYPE, stored.data); const auth = try self.signMessage(msg.request_id, DhtFindValueResponse.MSG_TYPE, stored.data);
@@ -1821,7 +1825,7 @@ pub const DhtCoordinator = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
var to_remove: std.ArrayListUnmanaged([32]u8) = .{}; var to_remove: std.ArrayListUnmanaged([32]u8) = .{};
defer to_remove.deinit(self.allocator); defer to_remove.deinit(self.allocator);
@@ -1893,7 +1897,7 @@ test "DHT store and retrieve" {
// Store a value // Store a value
var key: [32]u8 = undefined; var key: [32]u8 = undefined;
std.crypto.random.bytes(&key); platform_random.bytes(&key);
const value = "test value"; const value = "test value";
try dht.store(key, value, DEFAULT_TTL); try dht.store(key, value, DEFAULT_TTL);
@@ -1918,7 +1922,7 @@ test "DHT value expiration" {
// Store a value with 1 second TTL // Store a value with 1 second TTL
var key: [32]u8 = undefined; var key: [32]u8 = undefined;
std.crypto.random.bytes(&key); platform_random.bytes(&key);
const value = "expiring value"; const value = "expiring value";
try dht.store(key, value, 1); try dht.store(key, value, 1);
@@ -1951,7 +1955,7 @@ fn createTestSignedMessage(
msg_type: u8, msg_type: u8,
payload: []const u8, payload: []const u8,
) !SignedDhtMessage { ) !SignedDhtMessage {
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
const signing_data = try SignedDhtMessage.createSigningData( const signing_data = try SignedDhtMessage.createSigningData(
allocator, allocator,
request_id, request_id,
@@ -1990,10 +1994,10 @@ test "DHT handle FIND_NODE" {
// Create a FIND_NODE request // Create a FIND_NODE request
var target_id: [32]u8 = undefined; var target_id: [32]u8 = undefined;
std.crypto.random.bytes(&target_id); platform_random.bytes(&target_id);
var request_id: [8]u8 = undefined; var request_id: [8]u8 = undefined;
std.crypto.random.bytes(&request_id); platform_random.bytes(&request_id);
const req_id = std.mem.readInt(u64, &request_id, .little); const req_id = std.mem.readInt(u64, &request_id, .little);
// Create authentication // Create authentication
@@ -2037,12 +2041,12 @@ test "DHT handle STORE" {
// Create a STORE request // Create a STORE request
var key: [32]u8 = undefined; var key: [32]u8 = undefined;
std.crypto.random.bytes(&key); platform_random.bytes(&key);
const value = "stored value"; const value = "stored value";
const ttl = DEFAULT_TTL; const ttl = DEFAULT_TTL;
var request_id: [8]u8 = undefined; var request_id: [8]u8 = undefined;
std.crypto.random.bytes(&request_id); platform_random.bytes(&request_id);
const req_id = std.mem.readInt(u64, &request_id, .little); const req_id = std.mem.readInt(u64, &request_id, .little);
// Create message authentication // Create message authentication
@@ -2101,7 +2105,7 @@ test "DHT async lookup initiates correctly" {
// Create target to search for // Create target to search for
var target_id: [32]u8 = undefined; var target_id: [32]u8 = undefined;
std.crypto.random.bytes(&target_id); platform_random.bytes(&target_id);
// Start async lookup (should complete immediately with no peers) // Start async lookup (should complete immediately with no peers)
const lookup_id = try dht.findNodeAsync(target_id); const lookup_id = try dht.findNodeAsync(target_id);
@@ -2152,7 +2156,7 @@ test "DHT async lookup with peers" {
// Create target to search for // Create target to search for
var target_id: [32]u8 = undefined; var target_id: [32]u8 = undefined;
std.crypto.random.bytes(&target_id); platform_random.bytes(&target_id);
// Start async lookup // Start async lookup
const lookup_id = try dht.findNodeAsync(target_id); const lookup_id = try dht.findNodeAsync(target_id);
@@ -2184,7 +2188,7 @@ test "DHT cancel lookup" {
// Create target to search for // Create target to search for
var target_id: [32]u8 = undefined; var target_id: [32]u8 = undefined;
std.crypto.random.bytes(&target_id); platform_random.bytes(&target_id);
// Start and immediately cancel // Start and immediately cancel
const lookup_id = try dht.findNodeAsync(target_id); const lookup_id = try dht.findNodeAsync(target_id);
@@ -2218,7 +2222,7 @@ test "DHT handle FIND_NODE response with authentication" {
try routing_table.addPeer(&peer, &position); try routing_table.addPeer(&peer, &position);
var target_id: [32]u8 = undefined; var target_id: [32]u8 = undefined;
std.crypto.random.bytes(&target_id); platform_random.bytes(&target_id);
// Start async lookup - this will mark the peer as queried // Start async lookup - this will mark the peer as queried
const lookup_id = try dht.findNodeAsync(target_id); const lookup_id = try dht.findNodeAsync(target_id);
@@ -2227,7 +2231,7 @@ test "DHT handle FIND_NODE response with authentication" {
// Create a mock response (normally would come from network) // Create a mock response (normally would come from network)
const responder_keypair = Ed25519.KeyPair.generate(); const responder_keypair = Ed25519.KeyPair.generate();
var req_id_bytes: [8]u8 = undefined; var req_id_bytes: [8]u8 = undefined;
std.crypto.random.bytes(&req_id_bytes); platform_random.bytes(&req_id_bytes);
const req_id = std.mem.readInt(u64, &req_id_bytes, .little); const req_id = std.mem.readInt(u64, &req_id_bytes, .little);
// Track a pending response manually for testing // Track a pending response manually for testing
@@ -2236,7 +2240,7 @@ test "DHT handle FIND_NODE response with authentication" {
.request_id = req_id, .request_id = req_id,
.target = peer_id.bytes, .target = peer_id.bytes,
.query_type = .find_node, .query_type = .find_node,
.sent_at = std.time.timestamp(), .sent_at = platform_time.timestamp(),
}); });
dht.mutex.unlock(); dht.mutex.unlock();
@@ -2254,7 +2258,7 @@ test "DHT handle FIND_NODE response with authentication" {
var nodes: [2]NodeInfo = undefined; var nodes: [2]NodeInfo = undefined;
for (0..2) |i| { for (0..2) |i| {
var node_id: [32]u8 = undefined; var node_id: [32]u8 = undefined;
std.crypto.random.bytes(&node_id); platform_random.bytes(&node_id);
nodes[i] = .{ nodes[i] = .{
.node_id = node_id, .node_id = node_id,
.address = [_]u8{'1', '2', '7', '.', '0', '.', '0', '.', '1', ':', '8', '0', '0', '0'} ++ [_]u8{0} ** 32, .address = [_]u8{'1', '2', '7', '.', '0', '.', '0', '.', '1', ':', '8', '0', '0', '0'} ++ [_]u8{0} ** 32,

View File

@@ -5,8 +5,14 @@
//! the discovery process for finding new peers on the network. //! the discovery process for finding new peers on the network.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Mutex = @import("sync").Mutex;
const core = @import("core"); const core = @import("core");
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
const Address = core.address.Address; const Address = core.address.Address;
const Socket = core.socket.Socket; const Socket = core.socket.Socket;
const MockSocket = core.socket.MockSocket; const MockSocket = core.socket.MockSocket;
@@ -281,7 +287,7 @@ pub const PeerAdvertisement = struct {
.peer_count = @intCast(@min(peers.len, MAX_ADVERTISED_PEERS)), .peer_count = @intCast(@min(peers.len, MAX_ADVERTISED_PEERS)),
.peer_addresses = undefined, .peer_addresses = undefined,
.protocol_version = 2, .protocol_version = 2,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -381,7 +387,7 @@ pub const KeepAlive = struct {
.connection_count = connection_count, .connection_count = connection_count,
.uptime_seconds = uptime_seconds, .uptime_seconds = uptime_seconds,
.protocol_version = 2, .protocol_version = 2,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -463,7 +469,7 @@ pub const Goodbye = struct {
.sender_id = sender_id, .sender_id = sender_id,
.reason = reason, .reason = reason,
.protocol_version = 2, .protocol_version = 2,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -593,7 +599,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
last_discovery: i64 = 0, last_discovery: i64 = 0,
discovered_peers: std.ArrayList(Address), discovered_peers: std.ArrayList(Address),
/// Thread safety mutex for shared state protection /// Thread safety mutex for shared state protection
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
/// MED-3 FIX: Per-IP rate limiting to prevent amplification attacks /// MED-3 FIX: Per-IP rate limiting to prevent amplification attacks
rate_limits: std.AutoHashMap(u128, DiscoveryRateLimit), rate_limits: std.AutoHashMap(u128, DiscoveryRateLimit),
/// MED-3 FIX: Last rate limit cleanup time /// MED-3 FIX: Last rate limit cleanup time
@@ -641,7 +647,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
.rate_limits = std.AutoHashMap(u128, DiscoveryRateLimit).init(allocator), .rate_limits = std.AutoHashMap(u128, DiscoveryRateLimit).init(allocator),
.peer_last_seen = std.AutoHashMap(u128, i64).init(allocator), .peer_last_seen = std.AutoHashMap(u128, i64).init(allocator),
.peer_public_keys = std.AutoHashMap(u128, [32]u8).init(allocator), .peer_public_keys = std.AutoHashMap(u128, [32]u8).init(allocator),
.start_time = std.time.timestamp(), .start_time = platform_time.timestamp(),
}; };
} }
@@ -658,7 +664,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
.rate_limits = std.AutoHashMap(u128, DiscoveryRateLimit).init(allocator), .rate_limits = std.AutoHashMap(u128, DiscoveryRateLimit).init(allocator),
.peer_last_seen = std.AutoHashMap(u128, i64).init(allocator), .peer_last_seen = std.AutoHashMap(u128, i64).init(allocator),
.peer_public_keys = std.AutoHashMap(u128, [32]u8).init(allocator), .peer_public_keys = std.AutoHashMap(u128, [32]u8).init(allocator),
.start_time = std.time.timestamp(), .start_time = platform_time.timestamp(),
}; };
} }
@@ -730,14 +736,14 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
try manager.sendDiscoveryRequest(local_peer_id, local_port); try manager.sendDiscoveryRequest(local_peer_id, local_port);
// Calculate deadline for discovery process // Calculate deadline for discovery process
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
const deadline = start_time + @as(i64, timeout_ms); const deadline = start_time + @as(i64, timeout_ms);
var peers_found: u32 = 0; var peers_found: u32 = 0;
// Listen for responses until timeout // Listen for responses until timeout
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
const remaining_ms = deadline - std.time.milliTimestamp(); const remaining_ms = deadline - platform_time.milliTimestamp();
if (remaining_ms <= 0) break; if (remaining_ms <= 0) break;
// Listen for responses with remaining timeout // Listen for responses with remaining timeout
@@ -983,7 +989,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
if (current_state != .Scanning) return error.InvalidState; if (current_state != .Scanning) return error.InvalidState;
var metadata: [32]u8 = undefined; var metadata: [32]u8 = undefined;
std.crypto.random.bytes(&metadata); platform_random.bytes(&metadata);
// Build request with public key for signature verification // Build request with public key for signature verification
var request = DiscoveryRequest{ var request = DiscoveryRequest{
@@ -991,7 +997,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
.port = local_port, .port = local_port,
.protocol_version = 2, // Version 2 includes public key .protocol_version = 2, // Version 2 includes public key
.metadata = metadata, .metadata = metadata,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = our_public_key orelse [_]u8{0} ** 32, .public_key = our_public_key orelse [_]u8{0} ** 32,
}; };
@@ -1019,7 +1025,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
manager.mutex.lock(); manager.mutex.lock();
defer manager.mutex.unlock(); defer manager.mutex.unlock();
manager.stats.requests_sent += 1; manager.stats.requests_sent += 1;
manager.last_discovery = std.time.timestamp(); manager.last_discovery = platform_time.timestamp();
} }
/// Send a PeerAdvertisement message to share known peers with others /// Send a PeerAdvertisement message to share known peers with others
@@ -1074,7 +1080,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
const start_time = manager.start_time; const start_time = manager.start_time;
manager.mutex.unlock(); manager.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
const uptime: u32 = @intCast(@max(0, @min(now - start_time, std.math.maxInt(u32)))); const uptime: u32 = @intCast(@max(0, @min(now - start_time, std.math.maxInt(u32))));
var keepalive = KeepAlive.init(local_peer_id, connection_count, uptime); var keepalive = KeepAlive.init(local_peer_id, connection_count, uptime);
@@ -1165,7 +1171,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
manager.mutex.lock(); manager.mutex.lock();
defer manager.mutex.unlock(); defer manager.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
var removed: u32 = 0; var removed: u32 = 0;
// Remove stale entries from peer_last_seen // Remove stale entries from peer_last_seen
@@ -1210,27 +1216,31 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
pub fn listen(manager: *Self, timeout_ms: ?u32) !bool { pub fn listen(manager: *Self, timeout_ms: ?u32) !bool {
// Calculate deadline if timeout is provided // Calculate deadline if timeout is provided
const deadline: ?i64 = if (timeout_ms) |t| const deadline: ?i64 = if (timeout_ms) |t|
std.time.milliTimestamp() + @as(i64, t) platform_time.milliTimestamp() + @as(i64, t)
else else
null; null;
while (true) { while (true) {
// Check if timeout has been reached // Check if timeout has been reached
if (deadline) |d| { if (deadline) |d| {
if (std.time.milliTimestamp() >= d) { if (platform_time.milliTimestamp() >= d) {
return false; // Timeout reached return false; // Timeout reached
} }
} }
// Calculate remaining time for non-blocking poll // Calculate remaining time for non-blocking poll
const poll_timeout_ms: i64 = if (deadline) |d| blk: { const poll_timeout_ms: i64 = if (deadline) |d| blk: {
const remaining = d - std.time.milliTimestamp(); const remaining = d - platform_time.milliTimestamp();
break :blk @max(1, remaining); break :blk @max(1, remaining);
} else 100; // Default 100ms polling interval } else 100; // Default 100ms polling interval
// Check if socket has data available (non-blocking) // Check if socket has data available (non-blocking)
// For mock sockets, skip poll and check receive queue directly // For mock sockets, skip poll and check receive queue directly
if (comptime SocketType != MockSocket) { if (comptime SocketType != MockSocket) {
if (is_wasm) {
// On WASM, skip poll-based waiting, just sleep briefly
platform.time.sleep(@intCast(poll_timeout_ms * std.time.ns_per_ms));
} else {
var fds = [_]std.posix.pollfd{.{ var fds = [_]std.posix.pollfd{.{
.fd = manager.socket.fd, .fd = manager.socket.fd,
.events = std.posix.POLL.IN, .events = std.posix.POLL.IN,
@@ -1247,11 +1257,12 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
if (poll_result == 0) { if (poll_result == 0) {
continue; continue;
} }
}
} else { } else {
// For mock sockets, check if receive queue is empty // For mock sockets, check if receive queue is empty
if (manager.socket.receive_queue.items.len == 0) { if (manager.socket.receive_queue.items.len == 0) {
// Sleep briefly to simulate poll timeout // Sleep briefly to simulate poll timeout
std.Thread.sleep(@intCast(poll_timeout_ms * std.time.ns_per_ms)); platform.time.sleep(@intCast(poll_timeout_ms * std.time.ns_per_ms));
continue; continue;
} }
} }
@@ -1312,7 +1323,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
/// Handle incoming discovery request with ACTUAL signature verification /// Handle incoming discovery request with ACTUAL signature verification
fn handleDiscoveryRequest(manager: *Self, request: DiscoveryRequest, source: Address) !void { fn handleDiscoveryRequest(manager: *Self, request: DiscoveryRequest, source: Address) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Validate timestamp to prevent replay attacks (60 second window) // Validate timestamp to prevent replay attacks (60 second window)
const max_age: i64 = 60; const max_age: i64 = 60;
@@ -1426,7 +1437,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
.address = our_address, .address = our_address,
.capabilities = [8]u8{ 1, 0, 0, 0, 0, 0, 0, 0 }, // Basic capabilities .capabilities = [8]u8{ 1, 0, 0, 0, 0, 0, 0, 0 }, // Basic capabilities
.protocol_version = 2, // Version 2 includes public key .protocol_version = 2, // Version 2 includes public key
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = our_public_key orelse [_]u8{0} ** 32, .public_key = our_public_key orelse [_]u8{0} ** 32,
}; };
@@ -1466,7 +1477,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
/// Handle incoming discovery response with signature verification /// Handle incoming discovery response with signature verification
fn handleDiscoveryResponse(manager: *Self, response: DiscoveryResponse, source: Address) !void { fn handleDiscoveryResponse(manager: *Self, response: DiscoveryResponse, source: Address) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Validate timestamp to prevent replay attacks (60 second window) // Validate timestamp to prevent replay attacks (60 second window)
const max_age: i64 = 60; const max_age: i64 = 60;
@@ -1557,7 +1568,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
if (manager.peer_last_seen.count() >= MAX_TRACKED_PEERS) { if (manager.peer_last_seen.count() >= MAX_TRACKED_PEERS) {
std.log.warn("CRIT-4: peer_last_seen limit reached ({}), cannot track new peer {}", .{ MAX_TRACKED_PEERS, source }); std.log.warn("CRIT-4: peer_last_seen limit reached ({}), cannot track new peer {}", .{ MAX_TRACKED_PEERS, source });
} else { } else {
manager.peer_last_seen.put(peer_key, std.time.timestamp()) catch |err| { manager.peer_last_seen.put(peer_key, platform_time.timestamp()) catch |err| {
std.log.err("CRIT-4: Failed to update peer_last_seen for {}: {}", .{ source, err }); std.log.err("CRIT-4: Failed to update peer_last_seen for {}: {}", .{ source, err });
}; };
} }
@@ -1586,7 +1597,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
/// Handle incoming PeerAdvertisement message /// Handle incoming PeerAdvertisement message
/// Processes advertised peers and adds them to discovered peers list /// Processes advertised peers and adds them to discovered peers list
fn handlePeerAdvertisement(manager: *Self, advert: PeerAdvertisement, source: Address) !void { fn handlePeerAdvertisement(manager: *Self, advert: PeerAdvertisement, source: Address) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Validate timestamp (60 second window) // Validate timestamp (60 second window)
const max_age: i64 = 60; const max_age: i64 = 60;
@@ -1683,7 +1694,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
/// Handle incoming KeepAlive message /// Handle incoming KeepAlive message
/// Updates peer last-seen timestamp to maintain liveness tracking /// Updates peer last-seen timestamp to maintain liveness tracking
fn handleKeepAlive(manager: *Self, keepalive: KeepAlive, source: Address) !void { fn handleKeepAlive(manager: *Self, keepalive: KeepAlive, source: Address) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Validate timestamp (60 second window) // Validate timestamp (60 second window)
const max_age: i64 = 60; const max_age: i64 = 60;
@@ -1749,7 +1760,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
/// Handle incoming Goodbye message /// Handle incoming Goodbye message
/// Removes peer from discovered list and cleans up tracking /// Removes peer from discovered list and cleans up tracking
fn handleGoodbye(manager: *Self, goodbye: Goodbye, source: Address) void { fn handleGoodbye(manager: *Self, goodbye: Goodbye, source: Address) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Validate timestamp (60 second window) // Validate timestamp (60 second window)
const max_age: i64 = 60; const max_age: i64 = 60;
@@ -1849,7 +1860,7 @@ pub fn DiscoveryManagerGeneric(comptime SocketType: type) type {
if (current_state != .Scanning) return; if (current_state != .Scanning) return;
const now = std.time.timestamp(); const now = platform_time.timestamp();
const interval = @as(i64, manager.config.interval_seconds); const interval = @as(i64, manager.config.interval_seconds);
if (now - last_discovery >= interval) { if (now - last_discovery >= interval) {
@@ -1957,7 +1968,7 @@ test "Discovery message encoding/decoding" {
.port = 8080, .port = 8080,
.protocol_version = 1, .protocol_version = 1,
.metadata = [_]u8{1} ** 32, .metadata = [_]u8{1} ** 32,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -2002,9 +2013,9 @@ test "Discovery timeout functionality" {
try manager.start(); try manager.start();
// Test that listen respects timeout - should return false when timeout is reached // Test that listen respects timeout - should return false when timeout is reached
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
const result = try manager.listen(500); // 500ms timeout const result = try manager.listen(500); // 500ms timeout
const elapsed = std.time.milliTimestamp() - start_time; const elapsed = platform_time.milliTimestamp() - start_time;
// Should return false (timeout) since no discovery messages are being sent // Should return false (timeout) since no discovery messages are being sent
try std.testing.expectEqual(false, result); try std.testing.expectEqual(false, result);
@@ -2040,9 +2051,9 @@ test "Discovery listen without timeout" {
// Test with null timeout - should poll with default interval // Test with null timeout - should poll with default interval
// We'll use a very short actual timeout to avoid hanging the test // We'll use a very short actual timeout to avoid hanging the test
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
const result = try manager.listen(100); // 100ms timeout const result = try manager.listen(100); // 100ms timeout
const elapsed = std.time.milliTimestamp() - start_time; const elapsed = platform_time.milliTimestamp() - start_time;
// Should return false (timeout) since no discovery messages are being sent // Should return false (timeout) since no discovery messages are being sent
try std.testing.expectEqual(false, result); try std.testing.expectEqual(false, result);
@@ -2057,7 +2068,7 @@ test "Discovery discover() with timeout" {
const allocator = std.testing.allocator; const allocator = std.testing.allocator;
// Use a random port in high range to avoid collisions with other tests/processes // Use a random port in high range to avoid collisions with other tests/processes
const nano: u64 = @intCast(@mod(std.time.nanoTimestamp(), 1_000_000_000)); const nano: u64 = @intCast(@mod(platform_time.nanoTimestamp(), 1_000_000_000));
const random_port: u16 = 50000 + @as(u16, @intCast(nano % 10000)); const random_port: u16 = 50000 + @as(u16, @intCast(nano % 10000));
const config = DiscoveryConfig{ const config = DiscoveryConfig{
@@ -2083,7 +2094,7 @@ test "Discovery discover() with timeout" {
const local_port: u16 = 8080; const local_port: u16 = 8080;
// Test discover with 500ms timeout // Test discover with 500ms timeout
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
_ = manager.discover(local_peer_id, local_port, 500) catch |err| { _ = manager.discover(local_peer_id, local_port, 500) catch |err| {
// Network may not be available in test environment - this is acceptable // Network may not be available in test environment - this is acceptable
// Socket layer converts network errors to SocketSendFailed // Socket layer converts network errors to SocketSendFailed
@@ -2094,7 +2105,7 @@ test "Discovery discover() with timeout" {
} }
return err; return err;
}; };
const elapsed = std.time.milliTimestamp() - start_time; const elapsed = platform_time.milliTimestamp() - start_time;
// NOTE: We don't assert peers_found == 0 because we cannot control what other // NOTE: We don't assert peers_found == 0 because we cannot control what other
// processes or previous test runs might be broadcasting on the network. // processes or previous test runs might be broadcasting on the network.
@@ -2309,9 +2320,9 @@ test "MockDiscoveryManager: listen returns false on timeout with empty queue" {
try manager.start(); try manager.start();
// With empty receive queue, listen should timeout quickly // With empty receive queue, listen should timeout quickly
const start = std.time.milliTimestamp(); const start = platform_time.milliTimestamp();
const result = try manager.listen(50); // 50ms timeout const result = try manager.listen(50); // 50ms timeout
const elapsed = std.time.milliTimestamp() - start; const elapsed = platform_time.milliTimestamp() - start;
try std.testing.expectEqual(false, result); try std.testing.expectEqual(false, result);
try std.testing.expect(elapsed >= 50); try std.testing.expect(elapsed >= 50);
@@ -2336,7 +2347,7 @@ test "MockDiscoveryManager: pruneStalePeers removes old entries" {
// Add a last-seen entry that is very old (will be pruned) // Add a last-seen entry that is very old (will be pruned)
const peer_key = peer_addr.toU128(); const peer_key = peer_addr.toU128();
try manager.peer_last_seen.put(peer_key, std.time.timestamp() - MockDiscoveryManager.PEER_TIMEOUT_SECONDS - 100); try manager.peer_last_seen.put(peer_key, platform_time.timestamp() - MockDiscoveryManager.PEER_TIMEOUT_SECONDS - 100);
// Prune should remove the stale peer // Prune should remove the stale peer
const removed = manager.pruneStalePeers(); const removed = manager.pruneStalePeers();
@@ -2608,7 +2619,7 @@ test "DiscoveryRequest: isSigned check" {
.port = 8080, .port = 8080,
.protocol_version = 2, .protocol_version = 2,
.metadata = [_]u8{0} ** 32, .metadata = [_]u8{0} ** 32,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -2629,7 +2640,7 @@ test "DiscoveryResponse: isSigned check" {
.address = peer_address, .address = peer_address,
.capabilities = [_]u8{0} ** 8, .capabilities = [_]u8{0} ** 8,
.protocol_version = 2, .protocol_version = 2,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.signature = [_]u8{0} ** 64, .signature = [_]u8{0} ** 64,
.public_key = [_]u8{0} ** 32, .public_key = [_]u8{0} ** 32,
}; };
@@ -2656,7 +2667,7 @@ test "MockDiscoveryManager: rate limit entry management" {
defer manager.deinit(); defer manager.deinit();
// Add rate limit entries // Add rate limit entries
const now = std.time.timestamp(); const now = platform_time.timestamp();
const ip1: u128 = 0x0A0B0C0D00000000; const ip1: u128 = 0x0A0B0C0D00000000;
const ip2: u128 = 0x0A0B0C0E00000000; const ip2: u128 = 0x0A0B0C0E00000000;

View File

@@ -12,6 +12,11 @@
const std = @import("std"); const std = @import("std");
const mem = std.mem; const mem = std.mem;
const crypto = std.crypto; const crypto = std.crypto;
const platform = @import("platform");
const platform_random = platform.random;
const platform_time = platform.time;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const Blake2b256 = crypto.hash.blake2.Blake2b256; const Blake2b256 = crypto.hash.blake2.Blake2b256;
const HmacBlake2b256 = crypto.auth.hmac.Hmac(Blake2b256); const HmacBlake2b256 = crypto.auth.hmac.Hmac(Blake2b256);
const timingSafeEql = crypto.timing_safe.eql; const timingSafeEql = crypto.timing_safe.eql;
@@ -51,15 +56,15 @@ pub const DoSProtection = struct {
/// Timestamp when current secret was created /// Timestamp when current secret was created
secret_created_at: i64, secret_created_at: i64,
/// Connection counter for rate tracking /// Connection counter for rate tracking
connection_count: std.atomic.Value(u32), connection_count: AtomicValue(u32),
/// Timestamp of last counter reset /// Timestamp of last counter reset
last_reset: std.atomic.Value(i64), last_reset: AtomicValue(i64),
/// Threshold for requiring cookies (connections per second) /// Threshold for requiring cookies (connections per second)
cookie_threshold: u32, cookie_threshold: u32,
/// Whether DoS protection is enabled /// Whether DoS protection is enabled
enabled: bool, enabled: bool,
/// Mutex for secret rotation /// Mutex for secret rotation
secret_mutex: std.Thread.Mutex, secret_mutex: Mutex,
const Self = @This(); const Self = @This();
@@ -67,15 +72,15 @@ pub const DoSProtection = struct {
pub fn init() Self { pub fn init() Self {
var current_secret: [32]u8 = undefined; var current_secret: [32]u8 = undefined;
var previous_secret: [32]u8 = undefined; var previous_secret: [32]u8 = undefined;
crypto.random.bytes(&current_secret); platform_random.bytes(&current_secret);
crypto.random.bytes(&previous_secret); platform_random.bytes(&previous_secret);
return Self{ return Self{
.current_secret = current_secret, .current_secret = current_secret,
.previous_secret = previous_secret, .previous_secret = previous_secret,
.secret_created_at = std.time.timestamp(), .secret_created_at = platform_time.timestamp(),
.connection_count = std.atomic.Value(u32).init(0), .connection_count = AtomicValue(u32).init(0),
.last_reset = std.atomic.Value(i64).init(std.time.timestamp()), .last_reset = AtomicValue(i64).init(platform_time.timestamp()),
.cookie_threshold = DEFAULT_COOKIE_THRESHOLD, .cookie_threshold = DEFAULT_COOKIE_THRESHOLD,
.enabled = true, .enabled = true,
.secret_mutex = .{}, .secret_mutex = .{},
@@ -99,7 +104,7 @@ pub const DoSProtection = struct {
/// Record a new connection attempt /// Record a new connection attempt
/// Also handles counter reset at second boundaries /// Also handles counter reset at second boundaries
pub fn recordConnection(self: *Self) void { pub fn recordConnection(self: *Self) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const last = self.last_reset.load(.acquire); const last = self.last_reset.load(.acquire);
// Reset counter at the start of each new second // Reset counter at the start of each new second
@@ -121,7 +126,7 @@ pub const DoSProtection = struct {
self.secret_mutex.lock(); self.secret_mutex.lock();
defer self.secret_mutex.unlock(); defer self.secret_mutex.unlock();
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
return computeCookie(self.current_secret, client_ip, timestamp); return computeCookie(self.current_secret, client_ip, timestamp);
} }
@@ -132,7 +137,7 @@ pub const DoSProtection = struct {
self.secret_mutex.lock(); self.secret_mutex.lock();
defer self.secret_mutex.unlock(); defer self.secret_mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Check with current secret for recent timestamps // Check with current secret for recent timestamps
// Using constant-time comparison to prevent timing side-channel attacks // Using constant-time comparison to prevent timing side-channel attacks
@@ -178,7 +183,7 @@ pub const DoSProtection = struct {
/// Rotate secret if needed /// Rotate secret if needed
fn maybeRotateSecret(self: *Self) void { fn maybeRotateSecret(self: *Self) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
self.secret_mutex.lock(); self.secret_mutex.lock();
defer self.secret_mutex.unlock(); defer self.secret_mutex.unlock();
@@ -186,7 +191,7 @@ pub const DoSProtection = struct {
if (now - self.secret_created_at >= SECRET_ROTATION_SECS) { if (now - self.secret_created_at >= SECRET_ROTATION_SECS) {
// Rotate: current becomes previous, generate new current // Rotate: current becomes previous, generate new current
self.previous_secret = self.current_secret; self.previous_secret = self.current_secret;
crypto.random.bytes(&self.current_secret); platform_random.bytes(&self.current_secret);
self.secret_created_at = now; self.secret_created_at = now;
} }
} }

View File

@@ -12,8 +12,12 @@
//! The application should handle key mismatch events appropriately. //! The application should handle key mismatch events appropriately.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const platform_time = @import("platform").time;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const mem = std.mem; const mem = std.mem;
const Allocator = mem.Allocator; const Allocator = mem.Allocator;
const Mutex = @import("sync").Mutex;
const Blake2b256 = std.crypto.hash.blake2.Blake2b256; const Blake2b256 = std.crypto.hash.blake2.Blake2b256;
const timingSafeEql = std.crypto.timing_safe.eql; const timingSafeEql = std.crypto.timing_safe.eql;
@@ -94,7 +98,7 @@ pub const KeyPinStore = struct {
/// Pinned keys indexed by fingerprint /// Pinned keys indexed by fingerprint
keys: std.AutoHashMap(PeerFingerprint, PinnedKey), keys: std.AutoHashMap(PeerFingerprint, PinnedKey),
/// Mutex for thread safety /// Mutex for thread safety
mutex: std.Thread.Mutex, mutex: Mutex,
/// Maximum number of pinned keys (0 = unlimited) /// Maximum number of pinned keys (0 = unlimited)
max_keys: usize, max_keys: usize,
/// Current pinning mode /// Current pinning mode
@@ -155,7 +159,7 @@ pub const KeyPinStore = struct {
if (timingSafeEql([32]u8, pinned.public_key, public_key)) { if (timingSafeEql([32]u8, pinned.public_key, public_key)) {
// Key matches - update last seen // Key matches - update last seen
var entry = self.keys.getPtr(fingerprint).?; var entry = self.keys.getPtr(fingerprint).?;
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
entry.verification_count += 1; entry.verification_count += 1;
return .verified; return .verified;
} else { } else {
@@ -175,7 +179,7 @@ pub const KeyPinStore = struct {
return Error.StorageFull; return Error.StorageFull;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
self.keys.put(fingerprint, PinnedKey{ self.keys.put(fingerprint, PinnedKey{
.public_key = public_key, .public_key = public_key,
.first_seen = now, .first_seen = now,
@@ -208,7 +212,7 @@ pub const KeyPinStore = struct {
if (timingSafeEql([32]u8, pinned.public_key, public_key)) { if (timingSafeEql([32]u8, pinned.public_key, public_key)) {
// Key matches - update last seen // Key matches - update last seen
var entry = self.keys.getPtr(peer_id).?; var entry = self.keys.getPtr(peer_id).?;
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
entry.verification_count += 1; entry.verification_count += 1;
return .verified; return .verified;
} else { } else {
@@ -229,7 +233,7 @@ pub const KeyPinStore = struct {
return Error.StorageFull; return Error.StorageFull;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
self.keys.put(peer_id, PinnedKey{ self.keys.put(peer_id, PinnedKey{
.public_key = public_key, .public_key = public_key,
.first_seen = now, .first_seen = now,
@@ -257,7 +261,7 @@ pub const KeyPinStore = struct {
owned_label = self.allocator.dupe(u8, l) catch return Error.OutOfMemory; owned_label = self.allocator.dupe(u8, l) catch return Error.OutOfMemory;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
self.keys.put(peer_id, PinnedKey{ self.keys.put(peer_id, PinnedKey{
.public_key = public_key, .public_key = public_key,
.first_seen = now, .first_seen = now,
@@ -291,7 +295,7 @@ pub const KeyPinStore = struct {
if (self.keys.getPtr(peer_id)) |entry| { if (self.keys.getPtr(peer_id)) |entry| {
entry.public_key = new_public_key; entry.public_key = new_public_key;
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
entry.verification_count = 1; entry.verification_count = 1;
} else { } else {
return Error.UnknownPeer; return Error.UnknownPeer;
@@ -359,7 +363,7 @@ pub const KeyPinStore = struct {
defer self.mutex.unlock(); defer self.mutex.unlock();
var imported: usize = 0; var imported: usize = 0;
const now = std.time.timestamp(); const now = platform_time.timestamp();
for (exports) |export_item| { for (exports) |export_item| {
if (self.max_keys > 0 and self.keys.count() >= self.max_keys) { if (self.max_keys > 0 and self.keys.count() >= self.max_keys) {
@@ -405,6 +409,8 @@ pub const PinnedKeyExport = struct {
/// Save pinned keys to a file. /// Save pinned keys to a file.
/// Uses atomic write (temp file + rename) to prevent corruption on crash. /// Uses atomic write (temp file + rename) to prevent corruption on crash.
pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void { pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void {
if (is_wasm) return; // No persistent storage on WASM
const exports = try store.exportKeys(store.allocator); const exports = try store.exportKeys(store.allocator);
defer if (exports.len > 0) store.allocator.free(exports); defer if (exports.len > 0) store.allocator.free(exports);
@@ -463,6 +469,8 @@ pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void {
/// Load pinned keys from a file /// Load pinned keys from a file
pub fn loadFromFile(store: *KeyPinStore, path: []const u8) !usize { pub fn loadFromFile(store: *KeyPinStore, path: []const u8) !usize {
if (is_wasm) return 0; // No persistent storage on WASM
var file = std.fs.cwd().openFile(path, .{}) catch |err| { var file = std.fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) { if (err == error.FileNotFound) {
return 0; // No saved keys, that's fine return 0; // No saved keys, that's fine
@@ -486,7 +494,7 @@ pub fn loadFromFile(store: *KeyPinStore, path: []const u8) !usize {
// Read entries and import them directly // Read entries and import them directly
var imported: usize = 0; var imported: usize = 0;
const now = std.time.timestamp(); const now = platform_time.timestamp();
for (0..count) |_| { for (0..count) |_| {
var peer_id: [32]u8 = undefined; var peer_id: [32]u8 = undefined;

View File

@@ -25,11 +25,17 @@
//! ``` //! ```
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const net = std.net; const net = std.net;
const posix = std.posix; const posix = std.posix;
const core = @import("core"); const core = @import("core");
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
const Error = core.errors.Error; const Error = core.errors.Error;
const Address = core.Address; const Address = core.Address;
const Socket = core.Socket; const Socket = core.Socket;
@@ -197,7 +203,7 @@ pub fn StunClientGeneric(comptime SocketType: type) type {
var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined; var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined;
// Generate random transaction ID // Generate random transaction ID
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
// Build STUN header (CRIT-9 FIX: now returns error) // Build STUN header (CRIT-9 FIX: now returns error)
try buildStunHeader(&request, STUN_BINDING_REQUEST, 0, &transaction_id); try buildStunHeader(&request, STUN_BINDING_REQUEST, 0, &transaction_id);
@@ -207,13 +213,13 @@ pub fn StunClientGeneric(comptime SocketType: type) type {
// Wait for response with timeout // Wait for response with timeout
var response_buffer: [1024]u8 = undefined; var response_buffer: [1024]u8 = undefined;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
while (std.time.milliTimestamp() - start_time < self.timeout_ms) { while (platform_time.milliTimestamp() - start_time < self.timeout_ms) {
// Set socket to non-blocking for timeout handling // Set socket to non-blocking for timeout handling
const result = self.socket.receiveFrom(&response_buffer) catch |err| { const result = self.socket.receiveFrom(&response_buffer) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
std.Thread.sleep(50 * std.time.ns_per_ms); platform.time.sleep(50 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -550,9 +556,9 @@ pub fn HolePuncherGeneric(comptime SocketType: type) type {
if (self.local_endpoint) |local| { if (self.local_endpoint) |local| {
std.mem.writeInt(u16, punch_data[4..6], local.public_port, .big); std.mem.writeInt(u16, punch_data[4..6], local.public_port, .big);
// Remaining bytes are random // Remaining bytes are random
std.crypto.random.bytes(punch_data[6..32]); platform_random.bytes(punch_data[6..32]);
} else { } else {
std.crypto.random.bytes(punch_data[4..32]); platform_random.bytes(punch_data[4..32]);
} }
std.log.info("Starting hole punch to {any}", .{peer_endpoint}); std.log.info("Starting hole punch to {any}", .{peer_endpoint});
@@ -565,7 +571,7 @@ pub fn HolePuncherGeneric(comptime SocketType: type) type {
std.log.debug("Hole punch attempt {} to {}", .{ attempts + 1, target }); std.log.debug("Hole punch attempt {} to {}", .{ attempts + 1, target });
if (attempts < HOLE_PUNCH_ATTEMPTS - 1) { if (attempts < HOLE_PUNCH_ATTEMPTS - 1) {
std.Thread.sleep(HOLE_PUNCH_INTERVAL_MS * std.time.ns_per_ms); platform.time.sleep(HOLE_PUNCH_INTERVAL_MS * std.time.ns_per_ms);
} }
} }
@@ -576,12 +582,12 @@ pub fn HolePuncherGeneric(comptime SocketType: type) type {
/// Returns true if hole punch packet received within timeout /// Returns true if hole punch packet received within timeout
pub fn waitForPunch(self: *Self, peer_endpoint: Endpoint, timeout_ms: u64) !bool { pub fn waitForPunch(self: *Self, peer_endpoint: Endpoint, timeout_ms: u64) !bool {
var buffer: [32]u8 = undefined; var buffer: [32]u8 = undefined;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
while (std.time.milliTimestamp() - start_time < timeout_ms) { while (platform_time.milliTimestamp() - start_time < timeout_ms) {
const result = self.stun_client.socket.receiveFrom(&buffer) catch |err| { const result = self.stun_client.socket.receiveFrom(&buffer) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
std.Thread.sleep(50 * std.time.ns_per_ms); platform.time.sleep(50 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -607,10 +613,13 @@ pub fn HolePuncherGeneric(comptime SocketType: type) type {
/// Perform symmetric hole punching with peer /// Perform symmetric hole punching with peer
/// Both peers punch holes simultaneously /// Both peers punch holes simultaneously
/// On WASM: returns error (WASM uses WebRTC ICE for NAT traversal, not raw UDP)
pub fn symmetricPunch( pub fn symmetricPunch(
self: *Self, self: *Self,
peer_endpoint: Endpoint, peer_endpoint: Endpoint,
) !void { ) !void {
if (is_wasm) return Error.OperationNotSupported;
const punch_thread = try std.Thread.spawn(.{}, punchHoleThreadFn, .{ self, peer_endpoint }); const punch_thread = try std.Thread.spawn(.{}, punchHoleThreadFn, .{ self, peer_endpoint });
defer punch_thread.join(); defer punch_thread.join();
@@ -801,13 +810,13 @@ pub const TurnAllocation = struct {
transaction_id: [STUN_TRANSACTION_ID_SIZE]u8, transaction_id: [STUN_TRANSACTION_ID_SIZE]u8,
pub fn isExpired(self: TurnAllocation) bool { pub fn isExpired(self: TurnAllocation) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.created_at; const elapsed = now - self.created_at;
return elapsed >= self.lifetime; return elapsed >= self.lifetime;
} }
pub fn remainingLifetime(self: TurnAllocation) i64 { pub fn remainingLifetime(self: TurnAllocation) i64 {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.created_at; const elapsed = now - self.created_at;
const remaining = @as(i64, @intCast(self.lifetime)) - elapsed; const remaining = @as(i64, @intCast(self.lifetime)) - elapsed;
return @max(0, remaining); return @max(0, remaining);
@@ -822,7 +831,7 @@ pub const ChannelBinding = struct {
lifetime: u32 = 600, // 10 minutes default lifetime: u32 = 600, // 10 minutes default
pub fn isExpired(self: ChannelBinding) bool { pub fn isExpired(self: ChannelBinding) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.created_at; const elapsed = now - self.created_at;
return elapsed >= self.lifetime; return elapsed >= self.lifetime;
} }
@@ -864,7 +873,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Build TURN Allocate Request // Build TURN Allocate Request
var request: [128]u8 = undefined; var request: [128]u8 = undefined;
var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined; var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined;
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
var offset: usize = 0; var offset: usize = 0;
@@ -900,12 +909,12 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Wait for response // Wait for response
var response_buffer: [1024]u8 = undefined; var response_buffer: [1024]u8 = undefined;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
while (std.time.milliTimestamp() - start_time < self.timeout_ms) { while (platform_time.milliTimestamp() - start_time < self.timeout_ms) {
const result = self.socket.receiveFrom(&response_buffer) catch |err| { const result = self.socket.receiveFrom(&response_buffer) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
std.Thread.sleep(50 * std.time.ns_per_ms); platform.time.sleep(50 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -1010,7 +1019,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
return TurnAllocation{ return TurnAllocation{
.relayed_address = relayed_address.?, .relayed_address = relayed_address.?,
.lifetime = lifetime, .lifetime = lifetime,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.transaction_id = expected_transaction_id[0..STUN_TRANSACTION_ID_SIZE].*, .transaction_id = expected_transaction_id[0..STUN_TRANSACTION_ID_SIZE].*,
}; };
} }
@@ -1026,7 +1035,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Build CreatePermission request // Build CreatePermission request
var request: [128]u8 = undefined; var request: [128]u8 = undefined;
var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined; var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined;
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
var offset: usize = 0; var offset: usize = 0;
@@ -1052,12 +1061,12 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Wait for response // Wait for response
var response_buffer: [512]u8 = undefined; var response_buffer: [512]u8 = undefined;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
while (std.time.milliTimestamp() - start_time < self.timeout_ms) { while (platform_time.milliTimestamp() - start_time < self.timeout_ms) {
const result = self.socket.receiveFrom(&response_buffer) catch |err| { const result = self.socket.receiveFrom(&response_buffer) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
std.Thread.sleep(50 * std.time.ns_per_ms); platform.time.sleep(50 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -1103,7 +1112,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
std.mem.writeInt(u16, request[0..2], TURN_SEND_INDICATION, .big); std.mem.writeInt(u16, request[0..2], TURN_SEND_INDICATION, .big);
std.mem.writeInt(u32, request[4..8], STUN_MAGIC_COOKIE, .big); std.mem.writeInt(u32, request[4..8], STUN_MAGIC_COOKIE, .big);
var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined; var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined;
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
@memcpy(request[8..20], &transaction_id); @memcpy(request[8..20], &transaction_id);
offset = STUN_HEADER_SIZE; offset = STUN_HEADER_SIZE;
@@ -1233,7 +1242,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Build Refresh request // Build Refresh request
var request: [64]u8 = undefined; var request: [64]u8 = undefined;
var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined; var transaction_id: [STUN_TRANSACTION_ID_SIZE]u8 = undefined;
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
std.mem.writeInt(u16, request[0..2], TURN_REFRESH_REQUEST, .big); std.mem.writeInt(u16, request[0..2], TURN_REFRESH_REQUEST, .big);
std.mem.writeInt(u16, request[2..4], 8, .big); // LIFETIME attribute only std.mem.writeInt(u16, request[2..4], 8, .big); // LIFETIME attribute only
@@ -1249,12 +1258,12 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
// Wait for response // Wait for response
var response_buffer: [512]u8 = undefined; var response_buffer: [512]u8 = undefined;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
while (std.time.milliTimestamp() - start_time < self.timeout_ms) { while (platform_time.milliTimestamp() - start_time < self.timeout_ms) {
const result = self.socket.receiveFrom(&response_buffer) catch |err| { const result = self.socket.receiveFrom(&response_buffer) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
std.Thread.sleep(50 * std.time.ns_per_ms); platform.time.sleep(50 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -1267,7 +1276,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type {
if (msg_type == TURN_REFRESH_RESPONSE) { if (msg_type == TURN_REFRESH_RESPONSE) {
// Update allocation timestamp // Update allocation timestamp
if (self.allocation) |*alloc| { if (self.allocation) |*alloc| {
alloc.created_at = std.time.timestamp(); alloc.created_at = platform_time.timestamp();
} }
std.log.info("TURN allocation refreshed", .{}); std.log.info("TURN allocation refreshed", .{});
return; return;
@@ -1374,7 +1383,7 @@ test "TURN allocation state" {
const allocation = TurnAllocation{ const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345), .relayed_address = Address.ipv4(.{ 192, 168, 1, 1 }, 12345),
.lifetime = 600, .lifetime = 600,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE, .transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE,
}; };
@@ -1388,7 +1397,7 @@ test "channel binding state" {
const binding = ChannelBinding{ const binding = ChannelBinding{
.channel_number = 0x4000, .channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000), .peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
}; };
try testing.expect(!binding.isExpired()); try testing.expect(!binding.isExpired());
@@ -1665,7 +1674,7 @@ test "MockHolePuncher: waitForPunch succeeds with valid punch packet" {
// Queue a punch packet from the peer // Queue a punch packet from the peer
var punch_data: [32]u8 = undefined; var punch_data: [32]u8 = undefined;
std.mem.writeInt(u32, punch_data[0..4], HOLE_PUNCH_MAGIC, .big); std.mem.writeInt(u32, punch_data[0..4], HOLE_PUNCH_MAGIC, .big);
std.crypto.random.bytes(punch_data[4..32]); platform_random.bytes(punch_data[4..32]);
try mock_socket.queueReceive(&punch_data, peer_public_addr); try mock_socket.queueReceive(&punch_data, peer_public_addr);
// Wait should succeed // Wait should succeed
@@ -1724,7 +1733,7 @@ test "STUN response parsing: XOR-MAPPED-ADDRESS" {
@memcpy(attr_value[4..8], &xor_ip); @memcpy(attr_value[4..8], &xor_ip);
var transaction_id: [12]u8 = undefined; var transaction_id: [12]u8 = undefined;
std.crypto.random.bytes(&transaction_id); platform_random.bytes(&transaction_id);
const result = try parseXorMappedAddressAttr(&attr_value, &transaction_id); const result = try parseXorMappedAddressAttr(&attr_value, &transaction_id);
try testing.expectEqual(@as(u16, 12345), result.port); try testing.expectEqual(@as(u16, 12345), result.port);
@@ -2185,7 +2194,7 @@ test "ChannelBinding: isExpired with past creation" {
const binding = ChannelBinding{ const binding = ChannelBinding{
.channel_number = 0x4000, .channel_number = 0x4000,
.peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000), .peer_address = Address.ipv4(.{ 10, 0, 0, 1 }, 5000),
.created_at = std.time.timestamp() - 700, // 700 seconds ago, lifetime default 600 .created_at = platform_time.timestamp() - 700, // 700 seconds ago, lifetime default 600
.lifetime = 600, .lifetime = 600,
}; };
try testing.expect(binding.isExpired()); try testing.expect(binding.isExpired());
@@ -2196,7 +2205,7 @@ test "ChannelBinding: not expired with recent creation" {
const binding = ChannelBinding{ const binding = ChannelBinding{
.channel_number = 0x4001, .channel_number = 0x4001,
.peer_address = Address.ipv4(.{ 10, 0, 0, 2 }, 5001), .peer_address = Address.ipv4(.{ 10, 0, 0, 2 }, 5001),
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.lifetime = 600, .lifetime = 600,
}; };
try testing.expect(!binding.isExpired()); try testing.expect(!binding.isExpired());
@@ -2207,7 +2216,7 @@ test "TurnAllocation: remainingLifetime with expired allocation" {
const allocation = TurnAllocation{ const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 10, 0, 0, 1 }, 3000), .relayed_address = Address.ipv4(.{ 10, 0, 0, 1 }, 3000),
.lifetime = 100, .lifetime = 100,
.created_at = std.time.timestamp() - 200, // expired 100 seconds ago .created_at = platform_time.timestamp() - 200, // expired 100 seconds ago
.transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE, .transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE,
}; };
try testing.expectEqual(@as(i64, 0), allocation.remainingLifetime()); try testing.expectEqual(@as(i64, 0), allocation.remainingLifetime());
@@ -2219,7 +2228,7 @@ test "TurnAllocation: remainingLifetime with active allocation" {
const allocation = TurnAllocation{ const allocation = TurnAllocation{
.relayed_address = Address.ipv4(.{ 10, 0, 0, 1 }, 3000), .relayed_address = Address.ipv4(.{ 10, 0, 0, 1 }, 3000),
.lifetime = 600, .lifetime = 600,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE, .transaction_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE,
}; };
try testing.expect(allocation.remainingLifetime() > 0); try testing.expect(allocation.remainingLifetime() > 0);

View File

@@ -17,6 +17,8 @@
//! ``` //! ```
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const posix = std.posix; const posix = std.posix;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@@ -319,6 +321,8 @@ fn verifySourceAddress(src: *const posix.sockaddr.storage, expected_ip: [4]u8) b
/// Discover the default gateway IP address /// Discover the default gateway IP address
pub fn discoverGateway() ![4]u8 { pub fn discoverGateway() ![4]u8 {
if (is_wasm) return error.UnsupportedPlatform;
// Platform-specific gateway discovery // Platform-specific gateway discovery
if (@import("builtin").os.tag == .macos or @import("builtin").os.tag == .ios) { if (@import("builtin").os.tag == .macos or @import("builtin").os.tag == .ios) {
return discoverGatewayDarwin(); return discoverGatewayDarwin();

View File

@@ -48,13 +48,21 @@
//! 4. Use defer for lock release to ensure cleanup on error paths //! 4. Use defer for lock release to ensure cleanup on error paths
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem; const mem = std.mem;
const Mutex = std.Thread.Mutex; const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const core = @import("core"); const core = @import("core");
const noise = @import("noise"); const noise = @import("noise");
const Socket = core.socket.Socket; const Socket = core.socket.Socket;
const Error = core.errors.Error; const Error = core.errors.Error;
const Transport = core.transport.Transport;
const TransportState = core.transport.TransportState;
const platform = @import("platform");
const platform_time = platform.time;
const PosixStreamTransport = platform.PosixStreamTransport;
const peer = @import("peer.zig"); const peer = @import("peer.zig");
const PeerId = peer.PeerId; const PeerId = peer.PeerId;
const secure_connection = @import("secure_connection.zig"); const secure_connection = @import("secure_connection.zig");
@@ -134,8 +142,15 @@ pub const EncryptedQueueEntry = struct {
/// serialization on a global mutex - critical for achieving high throughput /// serialization on a global mutex - critical for achieving high throughput
/// when serving many peers. /// when serving many peers.
pub const PeerConnection = struct { pub const PeerConnection = struct {
/// The underlying socket for this peer /// The underlying socket for this peer (kept for cleanup, stats, state checks).
socket: *Socket, /// Null for non-socket transports (e.g. WebRTC DataChannel).
socket: ?*Socket,
/// Transport-agnostic I/O handle. All send/receive goes through this.
transport_handle: Transport,
/// Inline storage for the PosixStreamTransport wrapping the socket.
/// The transport_handle.ptr points here. Safe because PeerConnection is heap-allocated.
/// Undefined when socket is null (WebRTC transport). Void on WASM.
_posix_transport: if (is_wasm) void else PosixStreamTransport,
/// Per-peer mutex for serializing sends to THIS peer only. /// Per-peer mutex for serializing sends to THIS peer only.
/// This allows sends to different peers to happen in parallel. /// This allows sends to different peers to happen in parallel.
send_mutex: Mutex, send_mutex: Mutex,
@@ -151,28 +166,68 @@ pub const PeerConnection = struct {
pub fn init(allocator: mem.Allocator, socket: *Socket) Error!*PeerConnection { pub fn init(allocator: mem.Allocator, socket: *Socket) Error!*PeerConnection {
const conn = allocator.create(PeerConnection) catch return Error.SystemError; const conn = allocator.create(PeerConnection) catch return Error.SystemError;
conn.* = .{ if (!is_wasm) {
.socket = socket, conn._posix_transport = PosixStreamTransport.init(socket);
.send_mutex = .{}, conn.transport_handle = Transport.init(&conn._posix_transport);
.pending_send = null, } else {
.encrypted_queue = .{}, conn._posix_transport = {};
.allocator = allocator, conn.transport_handle = undefined;
.secure = null, }
}; conn.socket = socket;
conn.send_mutex = .{};
conn.pending_send = null;
conn.encrypted_queue = .{};
conn.allocator = allocator;
conn.secure = null;
return conn; return conn;
} }
/// Initialize with a secure connection /// Initialize with a secure connection
pub fn initSecure(allocator: mem.Allocator, socket: *Socket, secure_conn: *SecureConnection) Error!*PeerConnection { pub fn initSecure(allocator: mem.Allocator, socket: *Socket, secure_conn: *SecureConnection) Error!*PeerConnection {
const conn = allocator.create(PeerConnection) catch return Error.SystemError; const conn = allocator.create(PeerConnection) catch return Error.SystemError;
conn.* = .{ if (!is_wasm) {
.socket = socket, conn._posix_transport = PosixStreamTransport.init(socket);
.send_mutex = .{}, conn.transport_handle = Transport.init(&conn._posix_transport);
.pending_send = null, } else {
.encrypted_queue = .{}, conn._posix_transport = {};
.allocator = allocator, conn.transport_handle = undefined;
.secure = secure_conn, }
}; conn.socket = socket;
conn.send_mutex = .{};
conn.pending_send = null;
conn.encrypted_queue = .{};
conn.allocator = allocator;
conn.secure = secure_conn;
return conn;
}
/// Initialize with a pre-built Transport (e.g. WebRTC DataChannel).
/// No socket is associated; socket-dependent features (idle detection) are skipped.
pub fn initWithTransport(allocator: mem.Allocator, transport_handle_arg: Transport) Error!*PeerConnection {
const conn = allocator.create(PeerConnection) catch return Error.SystemError;
conn._posix_transport = undefined;
conn.transport_handle = transport_handle_arg;
conn.socket = null;
conn.send_mutex = .{};
conn.pending_send = null;
conn.encrypted_queue = .{};
conn.allocator = allocator;
conn.secure = null;
return conn;
}
/// Initialize with a pre-built Transport and a SecureConnection (e.g. WebRTC + Noise).
/// The SecureConnection must already have completed its handshake.
pub fn initWithTransportSecure(allocator: mem.Allocator, transport_handle_arg: Transport, secure_conn: *SecureConnection) Error!*PeerConnection {
const conn = allocator.create(PeerConnection) catch return Error.SystemError;
conn._posix_transport = undefined;
conn.transport_handle = transport_handle_arg;
conn.socket = null;
conn.send_mutex = .{};
conn.pending_send = null;
conn.encrypted_queue = .{};
conn.allocator = allocator;
conn.secure = secure_conn;
return conn; return conn;
} }
@@ -267,6 +322,10 @@ pub const ReceiveBuffer = struct {
last_activity: i64, last_activity: i64,
/// CRIT-6 FIX: Maximum buffer size for this peer /// CRIT-6 FIX: Maximum buffer size for this peer
max_buffer_size: usize, max_buffer_size: usize,
/// Read cursor: bytes before this offset have been consumed.
/// Avoids O(N) memmove on every extractMessage — only compacts
/// when consumed data exceeds half the buffer.
read_offset: usize,
/// Default maximum message size: 2MB (matches protocol.MAX_MESSAGE_SIZE) /// Default maximum message size: 2MB (matches protocol.MAX_MESSAGE_SIZE)
pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 2 * 1024 * 1024; pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 2 * 1024 * 1024;
@@ -289,19 +348,42 @@ pub const ReceiveBuffer = struct {
.allocator = allocator, .allocator = allocator,
.max_message_size = max_message_size, .max_message_size = max_message_size,
.has_protocol_error = false, .has_protocol_error = false,
.last_activity = std.time.timestamp(), .last_activity = platform_time.timestamp(),
.max_buffer_size = max_buffer_size, .max_buffer_size = max_buffer_size,
.read_offset = 0,
}; };
} }
/// Get current buffer size in bytes /// Unread data in the buffer (everything after read_offset)
fn unreadSlice(self: *const ReceiveBuffer) []const u8 {
return self.buffer.items[self.read_offset..];
}
/// Number of unread bytes
fn unreadLen(self: *const ReceiveBuffer) usize {
return self.buffer.items.len - self.read_offset;
}
/// Compact: shift unread data to the front. Called when consumed
/// bytes exceed half the total allocation to bound waste.
fn compact(self: *ReceiveBuffer) void {
if (self.read_offset == 0) return;
const remaining = self.unreadLen();
if (remaining > 0) {
std.mem.copyForwards(u8, self.buffer.items[0..remaining], self.buffer.items[self.read_offset..][0..remaining]);
}
self.buffer.shrinkRetainingCapacity(remaining);
self.read_offset = 0;
}
/// Get current buffer size in bytes (unread data only)
pub fn currentSize(self: *const ReceiveBuffer) usize { pub fn currentSize(self: *const ReceiveBuffer) usize {
return self.buffer.items.len; return self.unreadLen();
} }
/// Check if buffer has timed out (no activity for specified duration) /// Check if buffer has timed out (no activity for specified duration)
pub fn hasTimedOut(self: *const ReceiveBuffer, timeout_seconds: i64) bool { pub fn hasTimedOut(self: *const ReceiveBuffer, timeout_seconds: i64) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
return (now - self.last_activity) > timeout_seconds; return (now - self.last_activity) > timeout_seconds;
} }
@@ -311,11 +393,16 @@ pub const ReceiveBuffer = struct {
/// CRIT-6 FIX: Append with buffer size limit enforcement /// CRIT-6 FIX: Append with buffer size limit enforcement
pub fn append(self: *ReceiveBuffer, data: []const u8) ReceiveBufferError!void { pub fn append(self: *ReceiveBuffer, data: []const u8) ReceiveBufferError!void {
// Check if appending would exceed per-peer buffer limit // Compact before appending if we've consumed a lot of space
const new_size = self.buffer.items.len + data.len; if (self.read_offset > 0 and self.read_offset >= self.buffer.items.len / 2) {
if (new_size > self.max_buffer_size) { self.compact();
}
// Check if appending would exceed per-peer buffer limit (use unread size)
const effective_size = self.unreadLen() + data.len;
if (effective_size > self.max_buffer_size) {
core.log.err("SECURITY CRIT-6: Peer receive buffer would exceed limit ({} + {} > {})", .{ core.log.err("SECURITY CRIT-6: Peer receive buffer would exceed limit ({} + {} > {})", .{
self.buffer.items.len, self.unreadLen(),
data.len, data.len,
self.max_buffer_size, self.max_buffer_size,
}); });
@@ -326,7 +413,7 @@ pub const ReceiveBuffer = struct {
self.buffer.appendSlice(self.allocator, data) catch return ReceiveBufferError.OutOfMemory; self.buffer.appendSlice(self.allocator, data) catch return ReceiveBufferError.OutOfMemory;
// Update last activity timestamp // Update last activity timestamp
self.last_activity = std.time.timestamp(); self.last_activity = platform_time.timestamp();
} }
/// Check if a complete message is available /// Check if a complete message is available
@@ -335,20 +422,21 @@ pub const ReceiveBuffer = struct {
// If we already have a protocol error, don't try to parse more // If we already have a protocol error, don't try to parse more
if (self.has_protocol_error) return ReceiveBufferError.MessageTooLarge; if (self.has_protocol_error) return ReceiveBufferError.MessageTooLarge;
if (self.buffer.items.len < 4) return false; const unread = self.unreadLen();
if (unread < 4) return false;
// First 4 bytes are message length // First 4 bytes are message length
if (self.expected_length == null) { if (self.expected_length == null) {
const len_bytes = self.buffer.items[0..4]; const len_bytes = self.buffer.items[self.read_offset..][0..4];
const msg_len = std.mem.readInt(u32, len_bytes[0..4], .big); const msg_len = std.mem.readInt(u32, len_bytes, .big);
// SECURITY: Validate message size before accepting it // SECURITY: Validate message size before accepting it
if (msg_len > self.max_message_size) { if (msg_len > self.max_message_size) {
core.log.err("SECURITY: Peer sent oversized message ({} bytes, max {}). Marking buffer as invalid.", .{ msg_len, self.max_message_size }); core.log.err("SECURITY: Peer sent oversized message ({} bytes, max {}). Marking buffer as invalid.", .{ msg_len, self.max_message_size });
// DEBUG: Print first 32 bytes of buffer to help diagnose framing issues const debug_start = self.read_offset;
const debug_len = @min(self.buffer.items.len, 32); const debug_len = @min(unread, 32);
core.log.err("DEBUG: Buffer first {} bytes: {x}", .{ debug_len, self.buffer.items[0..debug_len] }); core.log.err("DEBUG: Buffer first {} bytes: {x}", .{ debug_len, self.buffer.items[debug_start..][0..debug_len] });
core.log.err("DEBUG: Buffer total length: {}, len_bytes: {x}", .{ self.buffer.items.len, len_bytes.* }); core.log.err("DEBUG: Buffer unread length: {}, len_bytes: {x}", .{ unread, len_bytes.* });
self.has_protocol_error = true; self.has_protocol_error = true;
return ReceiveBufferError.MessageTooLarge; return ReceiveBufferError.MessageTooLarge;
} }
@@ -356,20 +444,24 @@ pub const ReceiveBuffer = struct {
self.expected_length = msg_len; self.expected_length = msg_len;
} }
return self.buffer.items.len >= self.expected_length.? + 4; return unread >= self.expected_length.? + 4;
} }
pub fn extractMessage(self: *ReceiveBuffer, allocator: mem.Allocator) ![]u8 { pub fn extractMessage(self: *ReceiveBuffer, allocator: mem.Allocator) ![]u8 {
const msg_len = self.expected_length.?; const msg_len = self.expected_length.?;
const msg_data = try allocator.dupe(u8, self.buffer.items[4 .. 4 + msg_len]); const msg_start = self.read_offset + 4;
const msg_data = try allocator.dupe(u8, self.buffer.items[msg_start .. msg_start + msg_len]);
// Remove processed bytes // Advance read cursor instead of shifting data
const remaining = self.buffer.items[4 + msg_len ..]; self.read_offset += 4 + msg_len;
std.mem.copyForwards(u8, self.buffer.items[0..remaining.len], remaining);
self.buffer.shrinkRetainingCapacity(remaining.len);
self.expected_length = null; self.expected_length = null;
// Compact when consumed data exceeds half the buffer to bound waste
if (self.read_offset >= self.buffer.items.len / 2) {
self.compact();
}
return msg_data; return msg_data;
} }
@@ -378,6 +470,7 @@ pub const ReceiveBuffer = struct {
self.buffer.clearRetainingCapacity(); self.buffer.clearRetainingCapacity();
self.expected_length = null; self.expected_length = null;
self.has_protocol_error = false; self.has_protocol_error = false;
self.read_offset = 0;
} }
}; };
@@ -432,33 +525,33 @@ pub const NetworkManager = struct {
stats: NetworkStats, stats: NetworkStats,
config: Config, config: Config,
/// Thread safety mutex for protecting send_queue and receive_buffers /// Thread safety mutex for protecting send_queue and receive_buffers
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
/// CRITICAL FIX: Pointer to P2P's socket mutex for atomic socket access. /// CRITICAL FIX: Pointer to P2P's socket mutex for atomic socket access.
/// This ensures that all socket sends (file transfer, regular messages, etc.) /// This ensures that all socket sends (file transfer, regular messages, etc.)
/// use the same mutex to prevent message interleaving on the wire. /// use the same mutex to prevent message interleaving on the wire.
socket_mutex: ?*std.Thread.Mutex = null, socket_mutex: ?*Mutex = null,
/// Optional rate limiter for incoming messages /// Optional rate limiter for incoming messages
peer_rate_limiter: ?*core.rate_limiter.PeerRateLimiter, peer_rate_limiter: ?*core.rate_limiter.PeerRateLimiter,
/// Counter for failed disconnection tracking attempts /// Counter for failed disconnection tracking attempts
failed_disconnect_tracking: std.atomic.Value(u64), failed_disconnect_tracking: AtomicValue(u64),
/// Error event callback for monitoring /// Error event callback for monitoring
error_callback: ?*const fn (error_event: NetworkError, context: ?*anyopaque) void, error_callback: ?*const fn (error_event: NetworkError, context: ?*anyopaque) void,
error_callback_context: ?*anyopaque, error_callback_context: ?*anyopaque,
// CRIT-5 FIX: Track send queue memory usage // CRIT-5 FIX: Track send queue memory usage
/// Current total bytes in send queue (atomic for thread-safe reads) /// Current total bytes in send queue (atomic for thread-safe reads)
send_queue_bytes: std.atomic.Value(usize), send_queue_bytes: AtomicValue(usize),
/// Messages dropped due to queue full /// Messages dropped due to queue full
send_queue_drops: std.atomic.Value(u64), send_queue_drops: AtomicValue(u64),
// CRIT-6 FIX: Track receive buffer memory usage // CRIT-6 FIX: Track receive buffer memory usage
/// Current total bytes across all receive buffers /// Current total bytes across all receive buffers
total_receive_buffer_bytes: std.atomic.Value(usize), total_receive_buffer_bytes: AtomicValue(usize),
/// Connections rejected due to receive buffer memory limit /// Connections rejected due to receive buffer memory limit
receive_buffer_rejections: std.atomic.Value(u64), receive_buffer_rejections: AtomicValue(u64),
// THR-2 FIX: Mutex to protect callback assignments (prevents callback/context mismatch) // THR-2 FIX: Mutex to protect callback assignments (prevents callback/context mismatch)
callback_mutex: std.Thread.Mutex = .{}, callback_mutex: Mutex = .{},
// Callbacks with context // Callbacks with context
// //
@@ -481,19 +574,25 @@ pub const NetworkManager = struct {
disconnect_callback_context: ?*anyopaque, disconnect_callback_context: ?*anyopaque,
pub const NetworkStats = struct { pub const NetworkStats = struct {
messages_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), messages_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
messages_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), messages_received: AtomicValue(u64) = AtomicValue(u64).init(0),
bytes_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), bytes_sent: AtomicValue(u64) = AtomicValue(u64).init(0),
bytes_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), bytes_received: AtomicValue(u64) = AtomicValue(u64).init(0),
send_errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), send_errors: AtomicValue(u64) = AtomicValue(u64).init(0),
receive_errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), receive_errors: AtomicValue(u64) = AtomicValue(u64).init(0),
messages_rate_limited: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), messages_rate_limited: AtomicValue(u64) = AtomicValue(u64).init(0),
/// Internal operations that failed (tracking, buffer creation, etc.) /// Internal operations that failed (tracking, buffer creation, etc.)
failed_operations: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), failed_operations: AtomicValue(u64) = AtomicValue(u64).init(0),
/// ERR-M1 FIX: Aggregate broadcast failures /// ERR-M1 FIX: Aggregate broadcast failures
broadcast_failures: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), broadcast_failures: AtomicValue(u64) = AtomicValue(u64).init(0),
/// ERR-M4 FIX: Aggregate queue retry exhaustions /// ERR-M4 FIX: Aggregate queue retry exhaustions
queue_retry_exhausted: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), queue_retry_exhausted: AtomicValue(u64) = AtomicValue(u64).init(0),
/// Successful Noise decryptions (for diagnosing nonce desync)
successful_decryptions: AtomicValue(u64) = AtomicValue(u64).init(0),
/// Successful Noise encryptions (for diagnosing nonce desync)
successful_encryptions: AtomicValue(u64) = AtomicValue(u64).init(0),
/// Ciphertext length of first decrypt failure (0 = no failure yet)
first_decrypt_fail_ct_len: AtomicValue(u64) = AtomicValue(u64).init(0),
/// Record a sent message with atomic updates /// Record a sent message with atomic updates
/// Uses .release ordering so readers with .acquire see consistent values /// Uses .release ordering so readers with .acquire see consistent values
@@ -573,15 +672,15 @@ pub const NetworkManager = struct {
.message_callback_context = null, .message_callback_context = null,
.disconnect_callback = null, .disconnect_callback = null,
.disconnect_callback_context = null, .disconnect_callback_context = null,
.failed_disconnect_tracking = std.atomic.Value(u64).init(0), .failed_disconnect_tracking = AtomicValue(u64).init(0),
.error_callback = null, .error_callback = null,
.error_callback_context = null, .error_callback_context = null,
// CRIT-5 FIX: Initialize send queue tracking // CRIT-5 FIX: Initialize send queue tracking
.send_queue_bytes = std.atomic.Value(usize).init(0), .send_queue_bytes = AtomicValue(usize).init(0),
.send_queue_drops = std.atomic.Value(u64).init(0), .send_queue_drops = AtomicValue(u64).init(0),
// CRIT-6 FIX: Initialize receive buffer tracking // CRIT-6 FIX: Initialize receive buffer tracking
.total_receive_buffer_bytes = std.atomic.Value(usize).init(0), .total_receive_buffer_bytes = AtomicValue(usize).init(0),
.receive_buffer_rejections = std.atomic.Value(u64).init(0), .receive_buffer_rejections = AtomicValue(u64).init(0),
}; };
} }
@@ -613,7 +712,7 @@ pub const NetworkManager = struct {
/// CRITICAL FIX: Set the socket mutex to ensure atomic socket access. /// CRITICAL FIX: Set the socket mutex to ensure atomic socket access.
/// This MUST be called with P2P's peer_connections_mutex to prevent /// This MUST be called with P2P's peer_connections_mutex to prevent
/// message interleaving between file transfer and regular message sends. /// message interleaving between file transfer and regular message sends.
pub fn setSocketMutex(self: *NetworkManager, mutex: *std.Thread.Mutex) void { pub fn setSocketMutex(self: *NetworkManager, mutex: *Mutex) void {
self.socket_mutex = mutex; self.socket_mutex = mutex;
} }
@@ -676,107 +775,67 @@ pub const NetworkManager = struct {
}; };
}; };
_ = self.stats.successful_encryptions.fetchAdd(1, .monotonic);
self.stats.recordSend(data.len + 16 + 4); // +16 for tag, +4 for length self.stats.recordSend(data.len + 16 + 4); // +16 for tag, +4 for length
// Generate cryptographically random message ID // Generate cryptographically random message ID
var id: [8]u8 = undefined; var id: [8]u8 = undefined;
std.crypto.random.bytes(&id); platform.random.bytes(&id);
return std.mem.readInt(u64, &id, .little); return std.mem.readInt(u64, &id, .little);
} }
var socket = peer_conn.socket;
// Prepare length-prefixed message (unencrypted path) // Prepare length-prefixed message (unencrypted path)
if (data.len > std.math.maxInt(u32)) { if (data.len > std.math.maxInt(u32)) {
self.releaseSocketLock(); self.releaseSocketLock();
return Error.MessageTooLarge; return Error.MessageTooLarge;
} }
const msg_len: u32 = @intCast(data.len); const msg_len: u32 = @intCast(data.len);
var header: [4]u8 = undefined;
std.mem.writeInt(u32, &header, msg_len, .big);
// DEBUG: Log header and data length // Combine header + data into a single buffer for atomic send.
std.log.debug("SEND-DEBUG: msg_len={}, data_len={}", .{ msg_len, data.len }); // On message-based transports (DataChannel), this ensures one frame per message
// instead of splitting header/payload into separate DataChannel messages.
// Send header with retry on WouldBlock // On stream transports (TCP), this reduces syscalls.
// CRITICAL FIX: Do NOT release lock during retry - releasing allows another thread var frame = self.allocator.alloc(u8, 4 + data.len) catch {
// to interleave data on the same socket, corrupting message framing
var header_sent: usize = 0;
var retries: u32 = 0;
var total_bytes_sent: usize = 0;
while (header_sent < 4 and retries < self.config.max_connection_retries) {
const n = socket.send(header[header_sent..]) catch |err| {
if (err == Error.ConnectionTimeout) {
// WouldBlock - brief yield then retry (keep lock held for atomicity)
std.Thread.sleep(self.config.retry_delay_ms * std.time.ns_per_ms);
retries += 1;
continue;
}
// CRITICAL FIX: If we already sent some bytes, stream is corrupted
if (header_sent > 0) {
std.log.err("FRAMING-CORRUPT: Header send failed after {} bytes, removing peer", .{header_sent});
_ = self.connections.remove(peer_id);
socket.close() catch |close_err| {
std.log.debug("Socket close after framing corruption: {}", .{close_err});
};
}
self.stats.recordSendError();
self.releaseSocketLock(); self.releaseSocketLock();
return err; return Error.OutOfMemory;
}; };
header_sent += n; defer self.allocator.free(frame);
total_bytes_sent += n; std.mem.writeInt(u32, frame[0..4], msg_len, .big);
} @memcpy(frame[4..], data);
if (header_sent < 4) { // Send combined frame with retry on WouldBlock
// CRITICAL FIX: Partial header sent means stream is corrupted
if (header_sent > 0) {
std.log.err("FRAMING-CORRUPT: Header timeout after {} bytes, removing peer", .{header_sent});
_ = self.connections.remove(peer_id);
socket.close() catch |close_err| {
std.log.debug("Socket close after framing corruption: {}", .{close_err});
};
}
self.stats.recordSendError();
self.releaseSocketLock();
return Error.ConnectionTimeout;
}
// Send data with retry on WouldBlock
// CRITICAL FIX: Keep lock held throughout to ensure atomic header+data send
var sent: usize = 0; var sent: usize = 0;
retries = 0; var retries: u32 = 0;
while (sent < data.len and retries < self.config.max_connection_retries) {
const n = socket.send(data[sent..]) catch |err| { while (sent < frame.len and retries < self.config.max_connection_retries) {
const n = peer_conn.transport_handle.send(frame[sent..]) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
// WouldBlock - brief yield then retry (keep lock held for atomicity) // WouldBlock - brief yield then retry (keep lock held for atomicity)
std.Thread.sleep(self.config.retry_delay_ms * std.time.ns_per_ms); platform.time.sleep(self.config.retry_delay_ms * std.time.ns_per_ms);
retries += 1; retries += 1;
continue; continue;
} }
// CRITICAL FIX: Header was fully sent, any failure now corrupts stream // If we already sent some bytes, stream is corrupted
std.log.err("FRAMING-CORRUPT: Data send failed after {} total bytes, removing peer", .{total_bytes_sent + sent}); if (sent > 0) {
std.log.err("FRAMING-CORRUPT: Send failed after {} bytes, removing peer", .{sent});
_ = self.connections.remove(peer_id); _ = self.connections.remove(peer_id);
socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close after framing corruption: {}", .{close_err}); }
};
self.stats.recordSendError(); self.stats.recordSendError();
self.releaseSocketLock(); self.releaseSocketLock();
return err; return err;
}; };
sent += n; sent += n;
total_bytes_sent += n;
retries = 0; // Reset retries on successful send retries = 0; // Reset retries on successful send
} }
if (sent < data.len) { if (sent < frame.len) {
// CRITICAL FIX: Partial data means stream is corrupted (header already sent) // Partial send means stream is corrupted
std.log.err("FRAMING-CORRUPT: Data timeout after {} total bytes, removing peer", .{total_bytes_sent}); if (sent > 0) {
std.log.err("FRAMING-CORRUPT: Send timeout after {} bytes, removing peer", .{sent});
_ = self.connections.remove(peer_id); _ = self.connections.remove(peer_id);
socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close after framing corruption: {}", .{close_err}); }
};
self.stats.recordSendError(); self.stats.recordSendError();
self.releaseSocketLock(); self.releaseSocketLock();
return Error.ConnectionTimeout; return Error.ConnectionTimeout;
@@ -786,7 +845,7 @@ pub const NetworkManager = struct {
// Generate cryptographically random message ID // Generate cryptographically random message ID
var id: [8]u8 = undefined; var id: [8]u8 = undefined;
std.crypto.random.bytes(&id); platform.random.bytes(&id);
const msg_id = std.mem.readInt(u64, &id, .little); const msg_id = std.mem.readInt(u64, &id, .little);
self.releaseSocketLock(); self.releaseSocketLock();
@@ -827,14 +886,14 @@ pub const NetworkManager = struct {
// Generate cryptographically random message ID // Generate cryptographically random message ID
var id: [8]u8 = undefined; var id: [8]u8 = undefined;
std.crypto.random.bytes(&id); platform.random.bytes(&id);
const msg_id = std.mem.readInt(u64, &id, .little); const msg_id = std.mem.readInt(u64, &id, .little);
self.send_queue.append(self.allocator, .{ self.send_queue.append(self.allocator, .{
.peer_id = peer_id, .peer_id = peer_id,
.data = data_copy, .data = data_copy,
.message_id = msg_id, .message_id = msg_id,
.queued_at = std.time.milliTimestamp(), .queued_at = platform_time.milliTimestamp(),
.priority = priority, .priority = priority,
.retries = 0, .retries = 0,
}) catch { }) catch {
@@ -851,7 +910,7 @@ pub const NetworkManager = struct {
/// CRIT-5 FIX: Evict messages that have been in the queue too long /// CRIT-5 FIX: Evict messages that have been in the queue too long
/// Must be called while holding mutex /// Must be called while holding mutex
fn evictStaleQueuedMessages(self: *NetworkManager) void { fn evictStaleQueuedMessages(self: *NetworkManager) void {
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
const max_age_ms = self.config.max_send_queue_age_seconds * 1000; const max_age_ms = self.config.max_send_queue_age_seconds * 1000;
var i: usize = 0; var i: usize = 0;
@@ -1008,14 +1067,13 @@ pub const NetworkManager = struct {
while (iter.next()) |entry| { while (iter.next()) |entry| {
const peer_id = entry.key_ptr.*; const peer_id = entry.key_ptr.*;
const peer_conn = entry.value_ptr.*; const peer_conn = entry.value_ptr.*;
const socket = peer_conn.socket;
// THROUGHPUT FIX: Loop to drain all available data from socket // THROUGHPUT FIX: Loop to drain all available data from socket
// Previously only did one receive() per socket per call, limiting throughput // Previously only did one receive() per socket per call, limiting throughput
var should_continue_peer = false; var should_continue_peer = false;
recv_loop: while (true) { recv_loop: while (true) {
// Try to receive data // Try to receive data (via transport abstraction)
const bytes_read = socket.receive(buffer) catch |err| { const bytes_read = peer_conn.transport_handle.receive(buffer) catch |err| {
if (err == Error.ConnectionTimeout) break :recv_loop; // WouldBlock - no more data available if (err == Error.ConnectionTimeout) break :recv_loop; // WouldBlock - no more data available
if (err == Error.ConnectionClosed) { if (err == Error.ConnectionClosed) {
disconnected.append(self.allocator, peer_id) catch |append_err| { disconnected.append(self.allocator, peer_id) catch |append_err| {
@@ -1133,7 +1191,7 @@ pub const NetworkManager = struct {
.error_type = .disconnect_tracking_failed, .error_type = .disconnect_tracking_failed,
.peer_id = peer_id, .peer_id = peer_id,
.count = count, .count = count,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
}, self.error_callback_context); }, self.error_callback_context);
} }
@@ -1174,13 +1232,27 @@ pub const NetworkManager = struct {
}; };
const plaintext = secure.transport.?.receive(msg_data, decrypt_buf) catch |err| { const plaintext = secure.transport.?.receive(msg_data, decrypt_buf) catch |err| {
std.log.err("Decryption failed for peer {}: {}", .{ peer_id, err }); std.log.err("Decryption failed for peer {}: {} (ok_before={})", .{ peer_id, err, self.stats.successful_decryptions.load(.monotonic) });
// Record first failure details
_ = self.stats.first_decrypt_fail_ct_len.cmpxchgStrong(0, msg_data.len, .monotonic, .monotonic);
self.allocator.free(msg_data); self.allocator.free(msg_data);
self.allocator.free(decrypt_buf); self.allocator.free(decrypt_buf);
self.stats.recordReceiveError(); self.stats.recordReceiveError();
continue; continue;
}; };
// FIX: Call maybeRekeyInbound() after successful decryption.
// The sender's SecureConnection.send() calls maybeRekeyOutbound()
// which rekeys the send cipher every DEFAULT_REKEY_INTERVAL (1000)
// messages. This receive path bypasses SecureConnection.receive()
// (which has its own framing via receiveRaw), so the corresponding
// maybeRekeyInbound() was never called. After 1000 messages the
// sender would rekey but the receiver wouldn't, causing permanent
// decryption failure from nonce/key desync.
secure.maybeRekeyInbound();
_ = self.stats.successful_decryptions.fetchAdd(1, .monotonic);
// Free the encrypted data, keep decrypted // Free the encrypted data, keep decrypted
self.allocator.free(msg_data); self.allocator.free(msg_data);
@@ -1357,7 +1429,6 @@ pub const NetworkManager = struct {
// Send without retries (best effort only) // Send without retries (best effort only)
const peer_conn = self.connections.get(peer_id) orelse return Error.ConnectionNotFound; const peer_conn = self.connections.get(peer_id) orelse return Error.ConnectionNotFound;
const socket = peer_conn.socket;
// Prepare length-prefixed message // Prepare length-prefixed message
const msg_len: u32 = @intCast(error_msg.len); const msg_len: u32 = @intCast(error_msg.len);
@@ -1365,12 +1436,12 @@ pub const NetworkManager = struct {
std.mem.writeInt(u32, &header, msg_len, .big); std.mem.writeInt(u32, &header, msg_len, .big);
// ERR-H4 FIX: Log send failures instead of silently swallowing // ERR-H4 FIX: Log send failures instead of silently swallowing
_ = socket.send(&header) catch |err| { _ = peer_conn.transport_handle.send(&header) catch |err| {
std.log.debug("ERR-H4: Failed to send rate limit header to peer: {}", .{err}); std.log.debug("ERR-H4: Failed to send rate limit header to peer: {}", .{err});
return; return;
}; };
_ = socket.send(&error_msg) catch |err| { _ = peer_conn.transport_handle.send(&error_msg) catch |err| {
std.log.debug("ERR-H4: Failed to send rate limit message to peer: {}", .{err}); std.log.debug("ERR-H4: Failed to send rate limit message to peer: {}", .{err});
return; return;
}; };
@@ -1405,7 +1476,7 @@ pub const NetworkManager = struct {
const buf_size = buf.currentSize(); const buf_size = buf.currentSize();
std.log.debug("CRIT-6: Evicting stale receive buffer for peer (size: {}, age: {}s)", .{ std.log.debug("CRIT-6: Evicting stale receive buffer for peer (size: {}, age: {}s)", .{
buf_size, buf_size,
std.time.timestamp() - buf.last_activity, platform_time.timestamp() - buf.last_activity,
}); });
_ = self.total_receive_buffer_bytes.fetchSub(buf_size, .monotonic); _ = self.total_receive_buffer_bytes.fetchSub(buf_size, .monotonic);
buf.deinit(self.allocator); buf.deinit(self.allocator);
@@ -1570,7 +1641,7 @@ test "QueuedMessage: deinit frees memory" {
.peer_id = PeerId.init(), .peer_id = PeerId.init(),
.data = data, .data = data,
.message_id = 1, .message_id = 1,
.queued_at = std.time.timestamp(), .queued_at = platform_time.timestamp(),
.priority = 0, .priority = 0,
.retries = 0, .retries = 0,
}; };
@@ -1605,7 +1676,7 @@ test "ReceiveBuffer: hasTimedOut" {
// Use a very short timeout to test immediately // Use a very short timeout to test immediately
try std.testing.expect(!buf.hasTimedOut(1000)); try std.testing.expect(!buf.hasTimedOut(1000));
// Force last_activity to the past // Force last_activity to the past
buf.last_activity = std.time.timestamp() - 100; buf.last_activity = platform_time.timestamp() - 100;
try std.testing.expect(buf.hasTimedOut(50)); try std.testing.expect(buf.hasTimedOut(50));
} }

View File

@@ -6,6 +6,9 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
const Mutex = @import("sync").Mutex;
const AtomicValue = @import("sync").AtomicValue;
const core = @import("core"); const core = @import("core");
const Address = core.address.Address; const Address = core.address.Address;
const Socket = core.socket.Socket; const Socket = core.socket.Socket;
@@ -107,7 +110,7 @@ pub const RoutingMessage = struct {
.sequence = sequence, .sequence = sequence,
.ttl = 64, // Default TTL .ttl = 64, // Default TTL
.payload = payload, .payload = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.max_age = 60, // Default 60 seconds (SECURITY: reduced from 5 minutes) .max_age = 60, // Default 60 seconds (SECURITY: reduced from 5 minutes)
}; };
} }
@@ -120,7 +123,7 @@ pub const RoutingMessage = struct {
.sequence = sequence, .sequence = sequence,
.ttl = 64, // Default TTL .ttl = 64, // Default TTL
.payload = payload, .payload = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.max_age = config.message_max_age_seconds, .max_age = config.message_max_age_seconds,
}; };
} }
@@ -191,7 +194,7 @@ pub const RoutingMessage = struct {
/// Check if message has expired /// Check if message has expired
pub fn isExpired(self: RoutingMessage) bool { pub fn isExpired(self: RoutingMessage) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
return now - self.timestamp > self.max_age; return now - self.timestamp > self.max_age;
} }
}; };
@@ -218,7 +221,7 @@ pub const RoutingTableEntry = struct {
.dest_id = dest_id, .dest_id = dest_id,
.next_hop = next_hop, .next_hop = next_hop,
.distance = distance, .distance = distance,
.last_updated = std.time.timestamp(), .last_updated = platform_time.timestamp(),
.quality = if (is_direct) 100 else 70, .quality = if (is_direct) 100 else 70,
.is_direct = is_direct, .is_direct = is_direct,
.max_age = 600, // Default 10 minutes .max_age = 600, // Default 10 minutes
@@ -230,7 +233,7 @@ pub const RoutingTableEntry = struct {
.dest_id = dest_id, .dest_id = dest_id,
.next_hop = next_hop, .next_hop = next_hop,
.distance = distance, .distance = distance,
.last_updated = std.time.timestamp(), .last_updated = platform_time.timestamp(),
.quality = if (is_direct) 100 else 70, .quality = if (is_direct) 100 else 70,
.is_direct = is_direct, .is_direct = is_direct,
.max_age = config.route_max_age_seconds, .max_age = config.route_max_age_seconds,
@@ -242,12 +245,12 @@ pub const RoutingTableEntry = struct {
self.next_hop = next_hop; self.next_hop = next_hop;
self.distance = distance; self.distance = distance;
self.quality = quality; self.quality = quality;
self.last_updated = std.time.timestamp(); self.last_updated = platform_time.timestamp();
} }
/// Check if route is still valid /// Check if route is still valid
pub fn isValid(self: RoutingTableEntry) bool { pub fn isValid(self: RoutingTableEntry) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
return now - self.last_updated < self.max_age; return now - self.last_updated < self.max_age;
} }
}; };
@@ -286,7 +289,7 @@ pub const Node = struct {
/// Routing table /// Routing table
routing_table: std.AutoHashMap([32]u8, RoutingTableEntry), routing_table: std.AutoHashMap([32]u8, RoutingTableEntry),
/// Message sequence counter (atomic for thread safety) /// Message sequence counter (atomic for thread safety)
sequence_counter: std.atomic.Value(u64), sequence_counter: AtomicValue(u64),
/// Statistics /// Statistics
stats: NodeStats, stats: NodeStats,
/// Creation timestamp /// Creation timestamp
@@ -296,7 +299,7 @@ pub const Node = struct {
/// Connected neighbors /// Connected neighbors
neighbors: std.ArrayList(PeerId), neighbors: std.ArrayList(PeerId),
/// Thread safety mutex /// Thread safety mutex
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
pub fn init(allocator: Allocator, id: PeerId, address: Address, topology: *NetworkTopology, config: NodeConfig) Node { pub fn init(allocator: Allocator, id: PeerId, address: Address, topology: *NetworkTopology, config: NodeConfig) Node {
return Node{ return Node{
@@ -305,8 +308,8 @@ pub const Node = struct {
.address = address, .address = address,
.topology = topology, .topology = topology,
.routing_table = std.AutoHashMap([32]u8, RoutingTableEntry).init(allocator), .routing_table = std.AutoHashMap([32]u8, RoutingTableEntry).init(allocator),
.sequence_counter = std.atomic.Value(u64).init(0), .sequence_counter = AtomicValue(u64).init(0),
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.config = config, .config = config,
.neighbors = .{}, .neighbors = .{},
.stats = NodeStats{}, .stats = NodeStats{},
@@ -340,7 +343,7 @@ pub const Node = struct {
try node.initializeRoutingTable(); try node.initializeRoutingTable();
node.state = .Online; node.state = .Online;
node.stats.last_activity = std.time.timestamp(); node.stats.last_activity = platform_time.timestamp();
} }
/// Stop the node /// Stop the node
@@ -370,7 +373,7 @@ pub const Node = struct {
pub fn processMessage(node: *Node, message: *RoutingMessage, _: Address) !RoutingDecision { pub fn processMessage(node: *Node, message: *RoutingMessage, _: Address) !RoutingDecision {
node.mutex.lock(); node.mutex.lock();
node.stats.messages_processed += 1; node.stats.messages_processed += 1;
node.stats.last_activity = std.time.timestamp(); node.stats.last_activity = platform_time.timestamp();
node.mutex.unlock(); node.mutex.unlock();
// Check message validity // Check message validity
@@ -612,7 +615,7 @@ pub const Node = struct {
defer mut_node.mutex.unlock(); defer mut_node.mutex.unlock();
var stats = node.stats; var stats = node.stats;
stats.uptime_seconds = std.time.timestamp() - node.created_at; stats.uptime_seconds = platform_time.timestamp() - node.created_at;
stats.routing_table_size = node.routing_table.size(); stats.routing_table_size = node.routing_table.size();
return stats; return stats;
} }

View File

@@ -10,6 +10,8 @@ const core = @import("core");
const Address = core.Address; const Address = core.Address;
const Connection = core.Connection; const Connection = core.Connection;
const Error = core.Error; const Error = core.Error;
const platform_random = @import("platform").random;
const platform_time = @import("platform").time;
/// Peer identifier - unique per peer /// Peer identifier - unique per peer
/// Can be randomly generated or derived from a Noise public key for identity binding. /// Can be randomly generated or derived from a Noise public key for identity binding.
@@ -19,7 +21,7 @@ pub const PeerId = struct {
/// Generate a random PeerId (for testing or non-encrypted connections) /// Generate a random PeerId (for testing or non-encrypted connections)
pub fn init() PeerId { pub fn init() PeerId {
var bytes: [32]u8 = undefined; var bytes: [32]u8 = undefined;
std.crypto.random.bytes(&bytes); platform_random.bytes(&bytes);
return PeerId{ .bytes = bytes }; return PeerId{ .bytes = bytes };
} }
@@ -210,8 +212,8 @@ pub const Peer = struct {
.capabilities = PeerCapabilities{}, .capabilities = PeerCapabilities{},
.reputation = PeerReputation{}, .reputation = PeerReputation{},
.stats = PeerStats{}, .stats = PeerStats{},
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.last_seen = std.time.timestamp(), .last_seen = platform_time.timestamp(),
}; };
} }
@@ -231,7 +233,7 @@ pub const Peer = struct {
/// Update peer activity timestamp /// Update peer activity timestamp
pub fn updateActivity(peer: *Peer) void { pub fn updateActivity(peer: *Peer) void {
peer.last_seen = std.time.timestamp(); peer.last_seen = platform_time.timestamp();
peer.stats.last_activity = peer.last_seen; peer.stats.last_activity = peer.last_seen;
} }

View File

@@ -6,6 +6,8 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const core = @import("core"); const core = @import("core");
const Address = core.address.Address; const Address = core.address.Address;
const peer_mod = @import("peer.zig"); const peer_mod = @import("peer.zig");
@@ -84,7 +86,7 @@ pub const RoutingBucket = struct {
.allocator = allocator, .allocator = allocator,
.index = index, .index = index,
.peers = .{}, .peers = .{},
.last_refresh = std.time.timestamp(), .last_refresh = platform_time.timestamp(),
.queried = false, .queried = false,
.max_size = max_size, .max_size = max_size,
}; };
@@ -117,7 +119,7 @@ pub const RoutingBucket = struct {
if (std.crypto.timing_safe.eql([32]u8, entry.peer.id.bytes, peer.id.bytes)) { if (std.crypto.timing_safe.eql([32]u8, entry.peer.id.bytes, peer.id.bytes)) {
// Update existing entry (entry is *PeerEntry, so modifications persist) // Update existing entry (entry is *PeerEntry, so modifications persist)
entry.position_info = topology.NodePositionInfo.fromNodePosition(position); entry.position_info = topology.NodePositionInfo.fromNodePosition(position);
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
return .updated; return .updated;
} }
} }
@@ -187,7 +189,7 @@ pub const RoutingBucket = struct {
if (bucket.peers.items.len == 0) return null; if (bucket.peers.items.len == 0) return null;
const max_index = @as(u32, @intCast(bucket.peers.items.len - 1)); const max_index = @as(u32, @intCast(bucket.peers.items.len - 1));
const index = std.crypto.random.intRangeAtMost(u32, 0, max_index); const index = platform_random.intRangeAtMost(u32, 0, max_index);
return PeerEntryInfo.fromPeerEntry(bucket.peers.items[index]); return PeerEntryInfo.fromPeerEntry(bucket.peers.items[index]);
} }
@@ -196,7 +198,7 @@ pub const RoutingBucket = struct {
for (bucket.peers.items) |entry| { for (bucket.peers.items) |entry| {
// SECURITY: Timing-safe comparison for peer ID // SECURITY: Timing-safe comparison for peer ID
if (std.crypto.timing_safe.eql([32]u8, entry.peer.id.bytes, peer_id.bytes)) { if (std.crypto.timing_safe.eql([32]u8, entry.peer.id.bytes, peer_id.bytes)) {
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
entry.queries = 0; entry.queries = 0;
return; return;
} }
@@ -205,7 +207,7 @@ pub const RoutingBucket = struct {
/// Check if bucket needs refresh /// Check if bucket needs refresh
pub fn needsRefresh(bucket: RoutingBucket, config: RoutingConfig) bool { pub fn needsRefresh(bucket: RoutingBucket, config: RoutingConfig) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const age = now - bucket.last_refresh; const age = now - bucket.last_refresh;
// Refresh buckets that haven't been touched in a while // Refresh buckets that haven't been touched in a while
@@ -284,9 +286,9 @@ pub const PeerEntry = struct {
// Store copies, not pointers - prevents dangling references // Store copies, not pointers - prevents dangling references
.peer = peer.*, .peer = peer.*,
.position_info = topology.NodePositionInfo.fromNodePosition(position), .position_info = topology.NodePositionInfo.fromNodePosition(position),
.last_seen = std.time.timestamp(), .last_seen = platform_time.timestamp(),
.queries = 0, .queries = 0,
.last_success = std.time.timestamp(), .last_success = platform_time.timestamp(),
.responsive = true, .responsive = true,
}; };
} }
@@ -298,7 +300,7 @@ pub const PeerEntry = struct {
/// Update peer responsiveness /// Update peer responsiveness
pub fn updateResponsiveness(entry: *PeerEntry, success: bool) void { pub fn updateResponsiveness(entry: *PeerEntry, success: bool) void {
entry.last_seen = std.time.timestamp(); entry.last_seen = platform_time.timestamp();
if (success) { if (success) {
entry.last_success = entry.last_seen; entry.last_success = entry.last_seen;
@@ -365,7 +367,7 @@ pub const KademliaRoutingTable = struct {
.local_id = local_id, .local_id = local_id,
.buckets = undefined, .buckets = undefined,
.total_peers = std.atomic.Value(usize).init(0), .total_peers = std.atomic.Value(usize).init(0),
.last_cleanup = std.time.timestamp(), .last_cleanup = platform_time.timestamp(),
.stats = RoutingTableStats{}, .stats = RoutingTableStats{},
.config = .{}, .config = .{},
}; };
@@ -556,7 +558,7 @@ pub const KademliaRoutingTable = struct {
} }
// Mark bucket as refreshed // Mark bucket as refreshed
bucket.last_refresh = std.time.timestamp(); bucket.last_refresh = platform_time.timestamp();
} }
} }
@@ -568,7 +570,7 @@ pub const KademliaRoutingTable = struct {
table.mutex.lock(); table.mutex.lock();
defer table.mutex.unlock(); defer table.mutex.unlock();
const now = std.time.timestamp(); const now = platform_time.timestamp();
// Clean up unresponsive peers (iterate backwards to avoid index issues) // Clean up unresponsive peers (iterate backwards to avoid index issues)
for (&table.buckets) |*bucket| { for (&table.buckets) |*bucket| {

View File

@@ -6,6 +6,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
const core = @import("core"); const core = @import("core");
const Address = core.address.Address; const Address = core.address.Address;
const Connection = core.connection.Connection; const Connection = core.connection.Connection;
@@ -36,7 +37,7 @@ pub const PeerConnection = struct {
pub fn init(source_id: PeerId, dest_id: PeerId) PeerConnection { pub fn init(source_id: PeerId, dest_id: PeerId) PeerConnection {
// RACE CONDITION FIX: Call timestamp() once and reuse // RACE CONDITION FIX: Call timestamp() once and reuse
const now = std.time.timestamp(); const now = platform_time.timestamp();
return PeerConnection{ return PeerConnection{
.source_id = source_id, .source_id = source_id,
.dest_id = dest_id, .dest_id = dest_id,
@@ -50,7 +51,7 @@ pub const PeerConnection = struct {
conn.latency_ms = latency; conn.latency_ms = latency;
conn.bandwidth_bps = bandwidth; conn.bandwidth_bps = bandwidth;
conn.quality = quality; conn.quality = quality;
conn.last_activity = std.time.timestamp(); conn.last_activity = platform_time.timestamp();
} }
/// Check if connection is active /// Check if connection is active
@@ -59,7 +60,7 @@ pub const PeerConnection = struct {
/// be inconsistent if another thread updates last_activity during this check. /// be inconsistent if another thread updates last_activity during this check.
/// This is acceptable since we're just checking staleness with a large timeout. /// This is acceptable since we're just checking staleness with a large timeout.
pub fn isActive(conn: PeerConnection) bool { pub fn isActive(conn: PeerConnection) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const inactive_duration = now - conn.last_activity; const inactive_duration = now - conn.last_activity;
return inactive_duration < 300; // 5 minutes timeout return inactive_duration < 300; // 5 minutes timeout
} }
@@ -431,7 +432,7 @@ pub const NetworkTopology = struct {
/// Analyze network topology metrics /// Analyze network topology metrics
pub fn analyzeTopology(topology: *NetworkTopology) !void { pub fn analyzeTopology(topology: *NetworkTopology) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (now - topology.last_analysis < 60) return; // Cache for 1 minute if (now - topology.last_analysis < 60) return; // Cache for 1 minute
const node_count = topology.nodes.count(); const node_count = topology.nodes.count();

View File

@@ -8,6 +8,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -198,7 +199,7 @@ pub fn TurnIntegrationGeneric(comptime SocketType: type) type {
.turn_client = client, .turn_client = client,
.turn_socket = socket, .turn_socket = socket,
.config = config, .config = config,
.last_refresh = std.time.timestamp(), .last_refresh = platform_time.timestamp(),
}; };
} }
@@ -261,7 +262,7 @@ pub fn TurnIntegrationGeneric(comptime SocketType: type) type {
// Attempt to allocate relay address // Attempt to allocate relay address
if (client_ptr.allocate()) |allocation| { if (client_ptr.allocate()) |allocation| {
std.log.info("TURN allocation successful: relayed address allocated for {} seconds", .{allocation.lifetime}); std.log.info("TURN allocation successful: relayed address allocated for {} seconds", .{allocation.lifetime});
self.last_refresh = std.time.timestamp(); self.last_refresh = platform_time.timestamp();
} else |err| { } else |err| {
std.log.warn("TURN allocation failed: {}. TURN relay will not be available.", .{err}); std.log.warn("TURN allocation failed: {}. TURN relay will not be available.", .{err});
// Don't fail startup - we can still work without TURN // Don't fail startup - we can still work without TURN
@@ -289,12 +290,12 @@ pub fn TurnIntegrationGeneric(comptime SocketType: type) type {
std.log.err("ERR-H3: Failed to re-allocate TURN (failures: {}): {}", .{ self.allocation_failures, err }); std.log.err("ERR-H3: Failed to re-allocate TURN (failures: {}): {}", .{ self.allocation_failures, err });
return err; return err;
}; };
self.last_refresh = std.time.timestamp(); self.last_refresh = platform_time.timestamp();
return; return;
} }
// Check if refresh is needed // Check if refresh is needed
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed_ms = (now - self.last_refresh) * 1000; const elapsed_ms = (now - self.last_refresh) * 1000;
if (elapsed_ms >= self.config.refresh_interval_ms) { if (elapsed_ms >= self.config.refresh_interval_ms) {
std.log.debug("Refreshing TURN allocation", .{}); std.log.debug("Refreshing TURN allocation", .{});

View File

@@ -21,6 +21,7 @@
//! ``` //! ```
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const posix = std.posix; const posix = std.posix;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@@ -434,10 +435,10 @@ fn httpRequest(
// Individual recv calls have a 5s SO_RCVTIMEO, but an attacker could send 1 byte // Individual recv calls have a 5s SO_RCVTIMEO, but an attacker could send 1 byte
// every 4s to keep the loop alive indefinitely. This bounds total elapsed time. // every 4s to keep the loop alive indefinitely. This bounds total elapsed time.
var total_read: usize = 0; var total_read: usize = 0;
const recv_start = std.time.milliTimestamp(); const recv_start = platform_time.milliTimestamp();
const max_recv_total_ms: i64 = 10_000; // 10s total for entire response const max_recv_total_ms: i64 = 10_000; // 10s total for entire response
while (total_read < resp_buf.len) { while (total_read < resp_buf.len) {
if (std.time.milliTimestamp() - recv_start > max_recv_total_ms) { if (platform_time.milliTimestamp() - recv_start > max_recv_total_ms) {
std.log.debug("UPnP: HTTP response total timeout exceeded ({d}ms)", .{max_recv_total_ms}); std.log.debug("UPnP: HTTP response total timeout exceeded ({d}ms)", .{max_recv_total_ms});
break; break;
} }

View File

@@ -5,6 +5,7 @@
const std = @import("std"); const std = @import("std");
const X25519 = std.crypto.dh.X25519; const X25519 = std.crypto.dh.X25519;
const platform_random = @import("platform").random;
const noise = @import("noise.zig"); const noise = @import("noise.zig");
const Error = noise.Error; const Error = noise.Error;
@@ -23,10 +24,17 @@ pub const KeyPair = struct {
/// Generate a new random key pair /// Generate a new random key pair
pub fn generate() Self { pub fn generate() Self {
const seed = X25519.KeyPair.generate(); var seed: [32]u8 = undefined;
platform_random.bytes(&seed);
const kp = X25519.KeyPair.generateDeterministic(seed) catch {
// Identity element is astronomically unlikely with random seed;
// regenerate if it somehow happens.
platform_random.bytes(&seed);
return generate();
};
return Self{ return Self{
.private = seed.secret_key, .private = kp.secret_key,
.public = seed.public_key, .public = kp.public_key,
}; };
} }

View File

@@ -1,5 +1,9 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core"); const core = @import("core");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const ChaCha20Poly1305 = std.crypto.aead.chacha_poly.ChaCha20Poly1305; const ChaCha20Poly1305 = std.crypto.aead.chacha_poly.ChaCha20Poly1305;
const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256; const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256;
const X25519 = std.crypto.dh.X25519; const X25519 = std.crypto.dh.X25519;
@@ -613,7 +617,7 @@ pub const CryptoManager = struct {
/// SECURITY: Production code SHOULD provide a callback that prompts the user /// SECURITY: Production code SHOULD provide a callback that prompts the user
pub fn initWithTofuCallback(allocator: std.mem.Allocator, tofu_callback: TofuCallback) CryptoManager { pub fn initWithTofuCallback(allocator: std.mem.Allocator, tofu_callback: TofuCallback) CryptoManager {
var local_key: [32]u8 = [_]u8{0} ** 32; var local_key: [32]u8 = [_]u8{0} ** 32;
std.crypto.random.bytes(&local_key); platform_random.bytes(&local_key);
// Generate Ed25519 identity keypair for signing // Generate Ed25519 identity keypair for signing
const identity_keypair = Ed25519.KeyPair.generate(); const identity_keypair = Ed25519.KeyPair.generate();
return .{ return .{
@@ -888,6 +892,8 @@ pub const CryptoManager = struct {
/// CRIT-3 FIX: Uses atomic file update pattern (write temp, fsync, rename) /// CRIT-3 FIX: Uses atomic file update pattern (write temp, fsync, rename)
/// Format: magic(4) + version(4) + data... + hmac(32) /// Format: magic(4) + version(4) + data... + hmac(32)
pub fn saveTofuKeys(self: *const CryptoManager, path: []const u8) !void { pub fn saveTofuKeys(self: *const CryptoManager, path: []const u8) !void {
if (is_wasm) return error.SaveFailed;
// CRIT-3 FIX: Atomic file update pattern // CRIT-3 FIX: Atomic file update pattern
// 1. Write to temporary file // 1. Write to temporary file
// 2. fsync to ensure data is on disk // 2. fsync to ensure data is on disk
@@ -1007,6 +1013,8 @@ pub const CryptoManager = struct {
/// SECURITY: This restores trust relationships after restart /// SECURITY: This restores trust relationships after restart
/// CRY-M4 FIX: Verifies HMAC integrity for version 2 files /// CRY-M4 FIX: Verifies HMAC integrity for version 2 files
pub fn loadTofuKeys(self: *CryptoManager, path: []const u8) !void { pub fn loadTofuKeys(self: *CryptoManager, path: []const u8) !void {
if (is_wasm) return error.LoadFailed;
const file = std.fs.cwd().openFile(path, .{}) catch |err| { const file = std.fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) { if (err == error.FileNotFound) {
std.log.info("CRY-1: No TOFU keys file found, starting fresh", .{}); std.log.info("CRY-1: No TOFU keys file found, starting fresh", .{});
@@ -1166,6 +1174,8 @@ pub const CryptoManager = struct {
/// CRY-M4 FIX: Save rate limit state to file for persistence across restarts /// CRY-M4 FIX: Save rate limit state to file for persistence across restarts
/// This prevents attackers from bypassing rate limits by forcing restarts /// This prevents attackers from bypassing rate limits by forcing restarts
pub fn saveRateLimitState(self: *const CryptoManager, path: []const u8) !void { pub fn saveRateLimitState(self: *const CryptoManager, path: []const u8) !void {
if (is_wasm) return error.SaveFailed;
const file = std.fs.cwd().createFile(path, .{}) catch |err| { const file = std.fs.cwd().createFile(path, .{}) catch |err| {
std.log.err("CRY-M4: Failed to create rate limit state file: {}", .{err}); std.log.err("CRY-M4: Failed to create rate limit state file: {}", .{err});
return error.SaveFailed; return error.SaveFailed;
@@ -1195,6 +1205,8 @@ pub const CryptoManager = struct {
/// CRY-M4 FIX: Load rate limit state from file /// CRY-M4 FIX: Load rate limit state from file
pub fn loadRateLimitState(self: *CryptoManager, path: []const u8) !void { pub fn loadRateLimitState(self: *CryptoManager, path: []const u8) !void {
if (is_wasm) return error.LoadFailed;
const file = std.fs.cwd().openFile(path, .{}) catch |err| { const file = std.fs.cwd().openFile(path, .{}) catch |err| {
std.log.debug("CRY-M4: No rate limit state file found ({}), starting fresh", .{err}); std.log.debug("CRY-M4: No rate limit state file found ({}), starting fresh", .{err});
return; return;
@@ -1221,7 +1233,7 @@ pub const CryptoManager = struct {
// Read entry count // Read entry count
const count = reader.readInt(u32, .little) catch return error.InvalidFormat; const count = reader.readInt(u32, .little) catch return error.InvalidFormat;
var loaded: u32 = 0; var loaded: u32 = 0;
const now = std.time.timestamp(); const now = platform_time.timestamp();
var i: u32 = 0; var i: u32 = 0;
while (i < count) : (i += 1) { while (i < count) : (i += 1) {
@@ -1303,6 +1315,8 @@ pub const CryptoManager = struct {
pub const RECOMMENDED_PASSWORD_LENGTH: usize = 16; pub const RECOMMENDED_PASSWORD_LENGTH: usize = 16;
pub fn saveIdentityKeyEncrypted(self: *const CryptoManager, path: []const u8, password: []const u8) CryptoError!void { pub fn saveIdentityKeyEncrypted(self: *const CryptoManager, path: []const u8, password: []const u8) CryptoError!void {
if (is_wasm) return CryptoError.SaveFailed;
// HIGH-2 FIX: Enforce minimum password length // HIGH-2 FIX: Enforce minimum password length
if (password.len < MIN_PASSWORD_LENGTH) { if (password.len < MIN_PASSWORD_LENGTH) {
std.log.err("HIGH-2: Password too short ({d} chars). Minimum required: {d} chars", .{ password.len, MIN_PASSWORD_LENGTH }); std.log.err("HIGH-2: Password too short ({d} chars). Minimum required: {d} chars", .{ password.len, MIN_PASSWORD_LENGTH });
@@ -1339,7 +1353,7 @@ pub const CryptoManager = struct {
// Generate random salt // Generate random salt
var salt: [16]u8 = undefined; var salt: [16]u8 = undefined;
std.crypto.random.bytes(&salt); platform_random.bytes(&salt);
writer.writeAll(&salt) catch return CryptoError.SaveFailed; writer.writeAll(&salt) catch return CryptoError.SaveFailed;
// Derive encryption key from password // Derive encryption key from password
@@ -1348,7 +1362,7 @@ pub const CryptoManager = struct {
// Generate random nonce // Generate random nonce
var nonce: [12]u8 = undefined; var nonce: [12]u8 = undefined;
std.crypto.random.bytes(&nonce); platform_random.bytes(&nonce);
writer.writeAll(&nonce) catch return CryptoError.SaveFailed; writer.writeAll(&nonce) catch return CryptoError.SaveFailed;
// Write public key (unencrypted, not secret) // Write public key (unencrypted, not secret)
@@ -1405,6 +1419,8 @@ pub const CryptoManager = struct {
/// # Returns /// # Returns
/// Error if decryption fails (wrong password) or file is corrupted /// Error if decryption fails (wrong password) or file is corrupted
pub fn loadIdentityKeyEncrypted(self: *CryptoManager, path: []const u8, password: []const u8) CryptoError!void { pub fn loadIdentityKeyEncrypted(self: *CryptoManager, path: []const u8, password: []const u8) CryptoError!void {
if (is_wasm) return CryptoError.LoadFailed;
const file = std.fs.cwd().openFile(path, .{}) catch |err| { const file = std.fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) { if (err == error.FileNotFound) {
std.log.info("SEC-H3: No identity key file found at {s}, using generated key", .{path}); std.log.info("SEC-H3: No identity key file found at {s}, using generated key", .{path});
@@ -1497,6 +1513,8 @@ pub const CryptoManager = struct {
/// The payload contains all TOFU data (peer identity keys, blacklist, revoked keys) /// The payload contains all TOFU data (peer identity keys, blacklist, revoked keys)
/// serialized and then encrypted. /// serialized and then encrypted.
pub fn saveTofuKeysEncrypted(self: *const CryptoManager, path: []const u8, password: []const u8) CryptoError!void { pub fn saveTofuKeysEncrypted(self: *const CryptoManager, path: []const u8, password: []const u8) CryptoError!void {
if (is_wasm) return CryptoError.SaveFailed;
// First, serialize the TOFU data into a buffer // First, serialize the TOFU data into a buffer
var payload = std.ArrayList(u8).init(self.allocator); var payload = std.ArrayList(u8).init(self.allocator);
defer payload.deinit(); defer payload.deinit();
@@ -1560,7 +1578,7 @@ pub const CryptoManager = struct {
// Generate and write salt // Generate and write salt
var salt: [16]u8 = undefined; var salt: [16]u8 = undefined;
std.crypto.random.bytes(&salt); platform_random.bytes(&salt);
writer.writeAll(&salt) catch return CryptoError.SaveFailed; writer.writeAll(&salt) catch return CryptoError.SaveFailed;
// Derive encryption key // Derive encryption key
@@ -1569,7 +1587,7 @@ pub const CryptoManager = struct {
// Generate and write nonce // Generate and write nonce
var nonce: [12]u8 = undefined; var nonce: [12]u8 = undefined;
std.crypto.random.bytes(&nonce); platform_random.bytes(&nonce);
writer.writeAll(&nonce) catch return CryptoError.SaveFailed; writer.writeAll(&nonce) catch return CryptoError.SaveFailed;
// Write payload length // Write payload length
@@ -1616,6 +1634,8 @@ pub const CryptoManager = struct {
/// SEC-H3 FIX: Load TOFU identity keys from encrypted file /// SEC-H3 FIX: Load TOFU identity keys from encrypted file
pub fn loadTofuKeysEncrypted(self: *CryptoManager, path: []const u8, password: []const u8) CryptoError!void { pub fn loadTofuKeysEncrypted(self: *CryptoManager, path: []const u8, password: []const u8) CryptoError!void {
if (is_wasm) return CryptoError.LoadFailed;
const file = std.fs.cwd().openFile(path, .{}) catch |err| { const file = std.fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) { if (err == error.FileNotFound) {
std.log.info("SEC-H3: No encrypted TOFU file found at {s}, starting fresh", .{path}); std.log.info("SEC-H3: No encrypted TOFU file found at {s}, starting fresh", .{path});
@@ -1951,7 +1971,7 @@ pub const CryptoManager = struct {
/// Automatically removes expired blacklist entries /// Automatically removes expired blacklist entries
pub fn isPeerBlacklisted(self: *CryptoManager, peer_id: [32]u8) bool { pub fn isPeerBlacklisted(self: *CryptoManager, peer_id: [32]u8) bool {
if (self.peer_blacklist.get(peer_id)) |blacklist_time| { if (self.peer_blacklist.get(peer_id)) |blacklist_time| {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (now - blacklist_time < IDENTITY_KEY_MISMATCH_BLACKLIST_DURATION) { if (now - blacklist_time < IDENTITY_KEY_MISMATCH_BLACKLIST_DURATION) {
return true; return true;
} }
@@ -1978,7 +1998,7 @@ pub const CryptoManager = struct {
std.log.warn("SECURITY: revoked_keys at capacity ({}), cannot revoke more keys", .{MAX_REVOKED_KEYS}); std.log.warn("SECURITY: revoked_keys at capacity ({}), cannot revoke more keys", .{MAX_REVOKED_KEYS});
return CryptoError.OutOfMemory; return CryptoError.OutOfMemory;
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
try self.revoked_keys.put(identity_key, now); try self.revoked_keys.put(identity_key, now);
const fingerprint = getIdentityFingerprint(identity_key); const fingerprint = getIdentityFingerprint(identity_key);
@@ -2074,7 +2094,7 @@ pub const CryptoManager = struct {
// HIGH-7 FIX: Handle the decision // HIGH-7 FIX: Handle the decision
switch (decision) { switch (decision) {
.reject_and_blacklist => { .reject_and_blacklist => {
const now = std.time.timestamp(); const now = platform_time.timestamp();
core.log.err("SECURITY CRITICAL: Identity key change REJECTED and peer BLACKLISTED.", .{}); core.log.err("SECURITY CRITICAL: Identity key change REJECTED and peer BLACKLISTED.", .{});
core.log.err("SECURITY: Old key (fp={s}...) -> Rejected new key (fp={s}...)", .{ old_fp_str[0..8], new_fp_str[0..8] }); core.log.err("SECURITY: Old key (fp={s}...) -> Rejected new key (fp={s}...)", .{ old_fp_str[0..8], new_fp_str[0..8] });
// SECURITY: Enforce limit but still reject // SECURITY: Enforce limit but still reject
@@ -2150,7 +2170,7 @@ pub const CryptoManager = struct {
/// SECURITY: Check rate limit for key exchange with a peer /// SECURITY: Check rate limit for key exchange with a peer
/// Returns error if rate limit exceeded /// Returns error if rate limit exceeded
fn checkKeyExchangeRateLimit(self: *CryptoManager, peer_id: [32]u8) !void { fn checkKeyExchangeRateLimit(self: *CryptoManager, peer_id: [32]u8) !void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (self.key_exchange_rate_limits.getPtr(peer_id)) |rate_limit| { if (self.key_exchange_rate_limits.getPtr(peer_id)) |rate_limit| {
// Check minimum interval // Check minimum interval
@@ -2225,11 +2245,11 @@ pub const CryptoManager = struct {
// SECURITY: Generate cryptographically random session nonce // SECURITY: Generate cryptographically random session nonce
var session_nonce: [32]u8 = undefined; var session_nonce: [32]u8 = undefined;
std.crypto.random.bytes(&session_nonce); platform_random.bytes(&session_nonce);
errdefer secureZero([32]u8, &session_nonce); errdefer secureZero([32]u8, &session_nonce);
// SECURITY FIX: Get current timestamp for freshness // SECURITY FIX: Get current timestamp for freshness
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
// SECURITY FIX: Sign ephemeral_key || timestamp || session_nonce // SECURITY FIX: Sign ephemeral_key || timestamp || session_nonce
// This prevents replay attacks and proves freshness // This prevents replay attacks and proves freshness
@@ -2291,7 +2311,7 @@ pub const CryptoManager = struct {
try self.checkKeyExchangeRateLimit(peer_id); try self.checkKeyExchangeRateLimit(peer_id);
// SECURITY: Validate timestamp to prevent replay attacks // SECURITY: Validate timestamp to prevent replay attacks
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const max_message_age: i64 = 60; // 60 seconds (SECURITY: reduced from 5 minutes) const max_message_age: i64 = 60; // 60 seconds (SECURITY: reduced from 5 minutes)
const max_clock_skew: i64 = 30; // 30 seconds const max_clock_skew: i64 = 30; // 30 seconds
@@ -2451,7 +2471,7 @@ pub const CryptoManager = struct {
// SECURITY: Sign our_public || our_timestamp || their_session_nonce // SECURITY: Sign our_public || our_timestamp || their_session_nonce
// This binds our response to the specific initiator session // This binds our response to the specific initiator session
const our_timestamp = std.time.timestamp(); const our_timestamp = platform_time.timestamp();
var response_signing_data: [72]u8 = undefined; var response_signing_data: [72]u8 = undefined;
@memcpy(response_signing_data[0..32], &key_pair.public); @memcpy(response_signing_data[0..32], &key_pair.public);
std.mem.writeInt(i64, response_signing_data[32..40], our_timestamp, .little); std.mem.writeInt(i64, response_signing_data[32..40], our_timestamp, .little);
@@ -2529,7 +2549,7 @@ pub const CryptoManager = struct {
} }
// SECURITY: Validate timestamp to prevent replay attacks // SECURITY: Validate timestamp to prevent replay attacks
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const max_message_age: i64 = 60; // 60 seconds (SECURITY: reduced from 5 minutes) const max_message_age: i64 = 60; // 60 seconds (SECURITY: reduced from 5 minutes)
const max_clock_skew: i64 = 30; // 30 seconds const max_clock_skew: i64 = 30; // 30 seconds
@@ -2705,7 +2725,7 @@ pub const CryptoManager = struct {
.their_public = their_public, .their_public = their_public,
.is_initiator = state.initiated_by_us, .is_initiator = state.initiated_by_us,
.hmac_key = keys.hmac_key, .hmac_key = keys.hmac_key,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
}); });
// CRIT-10 FIX: Securely zeroize key exchange state before removal // CRIT-10 FIX: Securely zeroize key exchange state before removal
@@ -2838,7 +2858,7 @@ pub const CryptoManager = struct {
// Generate random nonce // Generate random nonce
var nonce: [12]u8 = undefined; var nonce: [12]u8 = undefined;
std.crypto.random.bytes(&nonce); platform_random.bytes(&nonce);
// Allocate output buffer: nonce(12) + ciphertext(plaintext.len) + tag(16) // Allocate output buffer: nonce(12) + ciphertext(plaintext.len) + tag(16)
const ciphertext = self.allocator.alloc(u8, 12 + plaintext.len + 16) catch return CryptoError.OutOfMemory; const ciphertext = self.allocator.alloc(u8, 12 + plaintext.len + 16) catch return CryptoError.OutOfMemory;

View File

@@ -51,6 +51,11 @@
//! - Periodic cleanup of old nonces based on generation //! - Periodic cleanup of old nonces based on generation
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const core = @import("core"); const core = @import("core");
const crypto = @import("crypto.zig"); const crypto = @import("crypto.zig");
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
@@ -85,7 +90,7 @@ pub const NonceTracker = struct {
siphash_key: [16]u8, siphash_key: [16]u8,
/// CRIT-NEW-4 FIX: Mutex for thread-safe access to all NonceTracker state /// CRIT-NEW-4 FIX: Mutex for thread-safe access to all NonceTracker state
/// Required because HashMap operations and state updates are not atomic /// Required because HashMap operations and state updates are not atomic
mutex: std.Thread.Mutex, mutex: Mutex,
const WINDOW_SIZE: u7 = 64; const WINDOW_SIZE: u7 = 64;
const DEFAULT_MAX_TRACKED: usize = 10000; const DEFAULT_MAX_TRACKED: usize = 10000;
@@ -93,7 +98,7 @@ pub const NonceTracker = struct {
pub fn init(allocator: std.mem.Allocator) NonceTracker { pub fn init(allocator: std.mem.Allocator) NonceTracker {
// CRY-CRIT-1 FIX: Generate random SipHash key at initialization // CRY-CRIT-1 FIX: Generate random SipHash key at initialization
var siphash_key: [16]u8 = undefined; var siphash_key: [16]u8 = undefined;
std.crypto.random.bytes(&siphash_key); platform_random.bytes(&siphash_key);
return .{ return .{
.current_generation = 0, .current_generation = 0,
@@ -326,7 +331,7 @@ pub const EncryptionKey = struct {
created_at: i64, created_at: i64,
/// Nonce counter for preventing nonce reuse /// Nonce counter for preventing nonce reuse
/// CRIT-NEW-16 FIX: Now atomic to prevent torn reads/writes on 32-bit systems /// CRIT-NEW-16 FIX: Now atomic to prevent torn reads/writes on 32-bit systems
nonce_counter: std.atomic.Value(u64), nonce_counter: AtomicValue(u64),
/// Flag to track if key rotation is needed /// Flag to track if key rotation is needed
needs_rotation: bool, needs_rotation: bool,
@@ -344,9 +349,9 @@ pub const EncryptionKey = struct {
.previous_key = null, .previous_key = null,
.previous_key_stored_at = 0, .previous_key_stored_at = 0,
.generation = generation, .generation = generation,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
// CRIT-NEW-16 FIX: Initialize as atomic // CRIT-NEW-16 FIX: Initialize as atomic
.nonce_counter = std.atomic.Value(u64).init(0), .nonce_counter = AtomicValue(u64).init(0),
.needs_rotation = false, .needs_rotation = false,
}; };
} }
@@ -355,7 +360,7 @@ pub const EncryptionKey = struct {
/// Returns the previous key only if it hasn't expired /// Returns the previous key only if it hasn't expired
pub fn getValidPreviousKey(self: *EncryptionKey) ?[32]u8 { pub fn getValidPreviousKey(self: *EncryptionKey) ?[32]u8 {
if (self.previous_key) |prev| { if (self.previous_key) |prev| {
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (now - self.previous_key_stored_at > PREVIOUS_KEY_RETENTION_SECONDS) { if (now - self.previous_key_stored_at > PREVIOUS_KEY_RETENTION_SECONDS) {
// Previous key has expired - zeroize and clear it // Previous key has expired - zeroize and clear it
crypto.secureZero([32]u8, &self.previous_key.?); crypto.secureZero([32]u8, &self.previous_key.?);
@@ -376,7 +381,7 @@ pub const EncryptionKey = struct {
crypto.secureZero([32]u8, existing); crypto.secureZero([32]u8, existing);
} }
self.previous_key = prev_key; self.previous_key = prev_key;
self.previous_key_stored_at = std.time.timestamp(); self.previous_key_stored_at = platform_time.timestamp();
} }
/// SECURITY: Zeroize all key material to prevent key leakage /// SECURITY: Zeroize all key material to prevent key leakage
@@ -436,14 +441,14 @@ pub const EncryptionKey = struct {
std.mem.writeInt(u32, nonce[4..8], @as(u32, @intCast(current_counter)), .little); std.mem.writeInt(u32, nonce[4..8], @as(u32, @intCast(current_counter)), .little);
// Last 4 bytes: random (additional entropy) // Last 4 bytes: random (additional entropy)
std.crypto.random.bytes(nonce[8..12]); platform_random.bytes(nonce[8..12]);
return nonce; return nonce;
} }
/// Check if this key should be rotated based on age, usage, or nonce exhaustion /// Check if this key should be rotated based on age, usage, or nonce exhaustion
pub fn shouldRotate(self: *const EncryptionKey, max_age_seconds: i64, max_messages: u64) bool { pub fn shouldRotate(self: *const EncryptionKey, max_age_seconds: i64, max_messages: u64) bool {
const age = std.time.timestamp() - self.created_at; const age = platform_time.timestamp() - self.created_at;
// CRIT-NEW-16 FIX: Use atomic load for thread safety // CRIT-NEW-16 FIX: Use atomic load for thread safety
const counter = self.nonce_counter.load(.acquire); const counter = self.nonce_counter.load(.acquire);
return age >= max_age_seconds or return age >= max_age_seconds or
@@ -484,14 +489,14 @@ pub const EncryptionManager = struct {
/// MED-11 FIX: Maximum number of peer trackers to prevent unbounded memory /// MED-11 FIX: Maximum number of peer trackers to prevent unbounded memory
max_tracked_peers: usize, max_tracked_peers: usize,
/// MED-11 FIX: Track total nonces across all trackers /// MED-11 FIX: Track total nonces across all trackers
total_nonce_count: std.atomic.Value(usize), total_nonce_count: AtomicValue(usize),
/// MED-11 FIX: Maximum total nonces across all peers (default: 1M) /// MED-11 FIX: Maximum total nonces across all peers (default: 1M)
max_total_nonces: usize, max_total_nonces: usize,
/// MED-3 FIX: Maximum evicted peer entries to track /// MED-3 FIX: Maximum evicted peer entries to track
max_evicted_peers: usize, max_evicted_peers: usize,
/// CRIT-NEW-5 FIX: Mutex for thread-safe access to all encryption state /// CRIT-NEW-5 FIX: Mutex for thread-safe access to all encryption state
/// Required to prevent iterator invalidation during eviction and other races /// Required to prevent iterator invalidation during eviction and other races
mutex: std.Thread.Mutex, mutex: Mutex,
pub fn init(allocator: std.mem.Allocator, crypto_manager: *crypto.CryptoManager) EncryptionManager { pub fn init(allocator: std.mem.Allocator, crypto_manager: *crypto.CryptoManager) EncryptionManager {
return .{ return .{
@@ -503,7 +508,7 @@ pub const EncryptionManager = struct {
.max_messages_per_key = 1_000_000, .max_messages_per_key = 1_000_000,
.crypto_manager = crypto_manager, .crypto_manager = crypto_manager,
.max_tracked_peers = DEFAULT_MAX_TRACKED_PEERS, .max_tracked_peers = DEFAULT_MAX_TRACKED_PEERS,
.total_nonce_count = std.atomic.Value(usize).init(0), .total_nonce_count = AtomicValue(usize).init(0),
.max_total_nonces = 1_000_000, .max_total_nonces = 1_000_000,
.max_evicted_peers = DEFAULT_MAX_EVICTED_PEERS, .max_evicted_peers = DEFAULT_MAX_EVICTED_PEERS,
.mutex = .{}, // CRIT-NEW-5 FIX: Initialize mutex .mutex = .{}, // CRIT-NEW-5 FIX: Initialize mutex
@@ -613,7 +618,7 @@ pub const EncryptionManager = struct {
} }
} }
const now = std.time.timestamp(); const now = platform_time.timestamp();
// MED-3 FIX: Clean up old evicted entries if at limit // MED-3 FIX: Clean up old evicted entries if at limit
if (self.evicted_peer_generations.count() >= self.max_evicted_peers) { if (self.evicted_peer_generations.count() >= self.max_evicted_peers) {
@@ -702,7 +707,7 @@ pub const EncryptionManager = struct {
std.log.warn("Key rotation required for peer (generation={}, nonce_counter={}, age={}s)", .{ std.log.warn("Key rotation required for peer (generation={}, nonce_counter={}, age={}s)", .{
entry.generation, entry.generation,
counter, counter,
std.time.timestamp() - entry.created_at, platform_time.timestamp() - entry.created_at,
}); });
// If nonce exhaustion is imminent, we MUST NOT return the key // If nonce exhaustion is imminent, we MUST NOT return the key
@@ -859,7 +864,7 @@ pub const EncryptionManager = struct {
if (needs_proactive_rotation) { if (needs_proactive_rotation) {
std.log.info("SECURITY: Proactive key rotation triggered (counter={}, age={}s)", .{ std.log.info("SECURITY: Proactive key rotation triggered (counter={}, age={}s)", .{
counter, counter,
std.time.timestamp() - enc_key.created_at, platform_time.timestamp() - enc_key.created_at,
}); });
// Use locked version to avoid deadlock // Use locked version to avoid deadlock
try self.rotateKeyForPeerLocked(peer_id); try self.rotateKeyForPeerLocked(peer_id);
@@ -1056,7 +1061,7 @@ pub const EncryptionManager = struct {
const writer = file.writer(); const writer = file.writer();
// Write header // Write header
const now = std.time.timestamp(); const now = platform_time.timestamp();
const header = PersistentState{ const header = PersistentState{
.saved_at = now, .saved_at = now,
.startup_timestamp = now, // Will be updated on load .startup_timestamp = now, // Will be updated on load
@@ -1117,7 +1122,7 @@ pub const EncryptionManager = struct {
const file = fs.cwd().openFile(path, .{}) catch |err| { const file = fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) { if (err == error.FileNotFound) {
// No previous state - use current time as startup timestamp // No previous state - use current time as startup timestamp
const now = std.time.timestamp(); const now = platform_time.timestamp();
std.log.info("MED-5: No previous state found, starting fresh with timestamp {}", .{now}); std.log.info("MED-5: No previous state found, starting fresh with timestamp {}", .{now});
return now; return now;
} }
@@ -1132,12 +1137,12 @@ pub const EncryptionManager = struct {
const header_read = try reader.readAll(&header_bytes); const header_read = try reader.readAll(&header_bytes);
if (header_read != @sizeOf(PersistentState)) { if (header_read != @sizeOf(PersistentState)) {
std.log.warn("MED-5: Corrupt state file (header too short), starting fresh", .{}); std.log.warn("MED-5: Corrupt state file (header too short), starting fresh", .{});
return std.time.timestamp(); return platform_time.timestamp();
} }
const header: *const PersistentState = @ptrCast(&header_bytes); const header: *const PersistentState = @ptrCast(&header_bytes);
// Validate header // Validate header
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (header.saved_at > now + 3600) { // Allow 1 hour clock skew if (header.saved_at > now + 3600) { // Allow 1 hour clock skew
std.log.warn("MED-5: State file from future, ignoring", .{}); std.log.warn("MED-5: State file from future, ignoring", .{});
return now; return now;
@@ -1229,7 +1234,7 @@ test "encryption key rotation check" {
// Simulate old key // Simulate old key
key.nonce_counter.store(0, .release); key.nonce_counter.store(0, .release);
key.created_at = std.time.timestamp() - 7200; // 2 hours ago key.created_at = platform_time.timestamp() - 7200; // 2 hours ago
try std.testing.expect(key.shouldRotate(3600, 1_000_000)); try std.testing.expect(key.shouldRotate(3600, 1_000_000));
} }

View File

@@ -1,6 +1,14 @@
//! Message handler framework //! Message handler framework
const std = @import("std"); const std = @import("std");
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const builtin = @import("builtin");
const core = @import("core"); const core = @import("core");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
const message = @import("message.zig"); const message = @import("message.zig");
const serializer = @import("serializer.zig"); const serializer = @import("serializer.zig");
@@ -134,7 +142,7 @@ pub const HandlerContext = struct {
// HIGH-2 FIX: Mutex for protecting compound type fields during configuration // HIGH-2 FIX: Mutex for protecting compound type fields during configuration
// This protects: network_sender, config, data_response_handler // This protects: network_sender, config, data_response_handler
config_mutex: std.Thread.Mutex = .{}, config_mutex: Mutex = .{},
// IMP-M1/M2 FIX: Configurable handler settings // IMP-M1/M2 FIX: Configurable handler settings
// HIGH-2 FIX: Protected by config_mutex // HIGH-2 FIX: Protected by config_mutex
@@ -572,22 +580,22 @@ pub const HandlerContext = struct {
/// Handler metrics tracking /// Handler metrics tracking
pub const HandlerMetrics = struct { pub const HandlerMetrics = struct {
messages_processed: std.atomic.Value(u64), messages_processed: AtomicValue(u64),
messages_failed: std.atomic.Value(u64), messages_failed: AtomicValue(u64),
handlers_registered: u16, handlers_registered: u16,
average_processing_time: f64, average_processing_time: f64,
mutex: std.Thread.Mutex, mutex: Mutex,
/// ERR-M2 FIX: Track peer addition failures for aggregation /// ERR-M2 FIX: Track peer addition failures for aggregation
peer_addition_failures: std.atomic.Value(u64), peer_addition_failures: AtomicValue(u64),
pub fn init() HandlerMetrics { pub fn init() HandlerMetrics {
return .{ return .{
.messages_processed = std.atomic.Value(u64).init(0), .messages_processed = AtomicValue(u64).init(0),
.messages_failed = std.atomic.Value(u64).init(0), .messages_failed = AtomicValue(u64).init(0),
.handlers_registered = 0, .handlers_registered = 0,
.average_processing_time = 0.0, .average_processing_time = 0.0,
.mutex = .{}, .mutex = .{},
.peer_addition_failures = std.atomic.Value(u64).init(0), .peer_addition_failures = AtomicValue(u64).init(0),
}; };
} }
@@ -719,7 +727,7 @@ pub const RequestTracker = struct {
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
requests: std.AutoHashMap(u64, RequestInfo), requests: std.AutoHashMap(u64, RequestInfo),
mutex: std.Thread.Mutex, mutex: Mutex,
request_timeout_seconds: i64, request_timeout_seconds: i64,
pub fn init(allocator: std.mem.Allocator) RequestTracker { pub fn init(allocator: std.mem.Allocator) RequestTracker {
@@ -755,7 +763,7 @@ pub const RequestTracker = struct {
) !u64 { ) !u64 {
// Generate cryptographically random request ID // Generate cryptographically random request ID
var id: [8]u8 = undefined; var id: [8]u8 = undefined;
std.crypto.random.bytes(&id); platform_random.bytes(&id);
const request_id = std.mem.readInt(u64, &id, .little); const request_id = std.mem.readInt(u64, &id, .little);
const info = RequestInfo{ const info = RequestInfo{
@@ -764,7 +772,7 @@ pub const RequestTracker = struct {
.size = size, .size = size,
.file_hash = file_hash, .file_hash = file_hash,
.peer_id = peer_id, .peer_id = peer_id,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
self.mutex.lock(); self.mutex.lock();
@@ -788,7 +796,7 @@ pub const RequestTracker = struct {
/// Clean up expired entries (must hold mutex) /// Clean up expired entries (must hold mutex)
fn cleanupExpiredLocked(self: *RequestTracker) void { fn cleanupExpiredLocked(self: *RequestTracker) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
var to_remove = std.ArrayList(u64){}; var to_remove = std.ArrayList(u64){};
defer to_remove.deinit(self.allocator); defer to_remove.deinit(self.allocator);
@@ -815,7 +823,7 @@ pub const RequestTracker = struct {
const info = entry.value; const info = entry.value;
// Check if request has expired // Check if request has expired
const now = std.time.timestamp(); const now = platform_time.timestamp();
if (now - info.timestamp > self.request_timeout_seconds) { if (now - info.timestamp > self.request_timeout_seconds) {
std.log.warn("Request {d} expired (age: {d}s)", .{ request_id, now - info.timestamp }); std.log.warn("Request {d} expired (age: {d}s)", .{ request_id, now - info.timestamp });
return null; return null;
@@ -834,7 +842,7 @@ pub const RequestTracker = struct {
/// Clean up expired requests /// Clean up expired requests
pub fn cleanupStaleRequests(self: *RequestTracker) usize { pub fn cleanupStaleRequests(self: *RequestTracker) usize {
const now = std.time.timestamp(); const now = platform_time.timestamp();
var expired_ids: std.ArrayList(u64) = .{}; var expired_ids: std.ArrayList(u64) = .{};
defer expired_ids.deinit(self.allocator); defer expired_ids.deinit(self.allocator);
@@ -914,12 +922,12 @@ pub const HandlerRegistry = struct {
request_tracker: RequestTracker, request_tracker: RequestTracker,
last_cleanup_time: i64, last_cleanup_time: i64,
/// Thread safety mutex for handler registration/unregistration /// Thread safety mutex for handler registration/unregistration
handlers_mutex: std.Thread.Mutex = .{}, handlers_mutex: Mutex = .{},
/// THR-H4 FIX: Mutex to ensure only one message is processed at a time. /// THR-H4 FIX: Mutex to ensure only one message is processed at a time.
/// This prevents race conditions on context.source_peer_id between concurrent /// This prevents race conditions on context.source_peer_id between concurrent
/// message processing threads. Each processMessage call acquires this mutex, /// message processing threads. Each processMessage call acquires this mutex,
/// sets source_peer_id, runs handlers, then clears source_peer_id. /// sets source_peer_id, runs handlers, then clears source_peer_id.
processing_mutex: std.Thread.Mutex = .{}, processing_mutex: Mutex = .{},
pub fn init(allocator: std.mem.Allocator) !HandlerRegistry { pub fn init(allocator: std.mem.Allocator) !HandlerRegistry {
const metrics = try allocator.create(HandlerMetrics); const metrics = try allocator.create(HandlerMetrics);
@@ -935,7 +943,7 @@ pub const HandlerRegistry = struct {
.context = context, .context = context,
.replay_protector = replay_protection.ReplayProtector.init(allocator), .replay_protector = replay_protection.ReplayProtector.init(allocator),
.request_tracker = RequestTracker.init(allocator), .request_tracker = RequestTracker.init(allocator),
.last_cleanup_time = std.time.timestamp(), .last_cleanup_time = platform_time.timestamp(),
}; };
// Wire replay protector and request tracker into context (must be done after struct is created) // Wire replay protector and request tracker into context (must be done after struct is created)
@@ -1003,9 +1011,9 @@ pub const HandlerRegistry = struct {
self.processing_mutex.lock(); self.processing_mutex.lock();
defer self.processing_mutex.unlock(); defer self.processing_mutex.unlock();
const start_time = std.time.timestamp(); const start_time = platform_time.timestamp();
defer { defer {
const elapsed = @as(f64, @floatFromInt(std.time.timestamp() - start_time)); const elapsed = @as(f64, @floatFromInt(platform_time.timestamp() - start_time));
self.context.metrics.recordMessageProcessed(elapsed); self.context.metrics.recordMessageProcessed(elapsed);
} }
@@ -1094,7 +1102,7 @@ pub const HandlerRegistry = struct {
/// Cleanup replay protection state (remove old entries) /// Cleanup replay protection state (remove old entries)
/// Should be called periodically to prevent unbounded memory growth /// Should be called periodically to prevent unbounded memory growth
pub fn cleanupReplayProtection(self: *HandlerRegistry) void { pub fn cleanupReplayProtection(self: *HandlerRegistry) void {
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
// Only cleanup if enough time has passed since last cleanup // Only cleanup if enough time has passed since last cleanup
const cleanup_interval: i64 = 60; // 60 seconds default const cleanup_interval: i64 = 60; // 60 seconds default
@@ -1355,7 +1363,7 @@ pub const DiscoveryHandler = struct {
const effective_ttl = @min(msg.ttl, MAX_ANNOUNCE_TTL); const effective_ttl = @min(msg.ttl, MAX_ANNOUNCE_TTL);
// CRIT-NEW-12 FIX: Check rate limit for this source (using deduplication cache) // CRIT-NEW-12 FIX: Check rate limit for this source (using deduplication cache)
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
if (self.announce_timestamps.get(source_id)) |last_time| { if (self.announce_timestamps.get(source_id)) |last_time| {
if (now - last_time < ANNOUNCE_RATE_LIMIT_MS) { if (now - last_time < ANNOUNCE_RATE_LIMIT_MS) {
std.log.warn("SECURITY: Rate limiting discovery announce from source ({}ms since last)", .{now - last_time}); std.log.warn("SECURITY: Rate limiting discovery announce from source ({}ms since last)", .{now - last_time});
@@ -1720,7 +1728,7 @@ pub const ControlHandler = struct {
const source_id = context.source_peer_id orelse return error.InvalidMessage; const source_id = context.source_peer_id orelse return error.InvalidMessage;
// 1. Calculate current timestamp for RTT calculation // 1. Calculate current timestamp for RTT calculation
const current_time = std.time.milliTimestamp(); const current_time = platform_time.milliTimestamp();
const rtt: u32 = if (msg.timestamp > 0) const rtt: u32 = if (msg.timestamp > 0)
@intCast(@as(u64, @intCast(current_time)) -| msg.timestamp) @intCast(@as(u64, @intCast(current_time)) -| msg.timestamp)
else else
@@ -1835,7 +1843,7 @@ pub const AppHandler = struct {
callback_contexts: std.AutoHashMap(u32, ?*anyopaque) = undefined, callback_contexts: std.AutoHashMap(u32, ?*anyopaque) = undefined,
allocator: std.mem.Allocator = undefined, allocator: std.mem.Allocator = undefined,
initialized: bool = false, initialized: bool = false,
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
pub fn init() AppHandler { pub fn init() AppHandler {
return .{}; return .{};
@@ -2256,15 +2264,15 @@ pub const AsyncMessageProcessor = struct {
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
registry: *HandlerRegistry, registry: *HandlerRegistry,
queue: std.ArrayList(message.Message), queue: std.ArrayList(message.Message),
queue_mutex: std.Thread.Mutex, queue_mutex: Mutex,
workers: std.ArrayList(std.Thread), workers: if (is_wasm) void else std.ArrayList(std.Thread),
shutdown: std.atomic.Value(bool), shutdown: AtomicValue(bool),
/// CRIT-NEW-11 FIX: Per-source message counts for backpressure /// CRIT-NEW-11 FIX: Per-source message counts for backpressure
per_source_counts: std.AutoHashMap([32]u8, u32), per_source_counts: std.AutoHashMap([32]u8, u32),
/// CRIT-NEW-11 FIX: Track rejected messages for metrics /// CRIT-NEW-11 FIX: Track rejected messages for metrics
rejected_count: std.atomic.Value(u64), rejected_count: AtomicValue(u64),
/// CRIT-NEW-11 FIX: Track backpressure events /// CRIT-NEW-11 FIX: Track backpressure events
backpressure_events: std.atomic.Value(u64), backpressure_events: AtomicValue(u64),
/// CRIT-NEW-11 FIX: Backpressure threshold (80% of max) /// CRIT-NEW-11 FIX: Backpressure threshold (80% of max)
// MED-12 FIX: Start backpressure earlier (60%) to allow more time for queue draining // MED-12 FIX: Start backpressure earlier (60%) to allow more time for queue draining
@@ -2278,31 +2286,34 @@ pub const AsyncMessageProcessor = struct {
.registry = registry, .registry = registry,
.queue = .{}, .queue = .{},
.queue_mutex = .{}, .queue_mutex = .{},
.workers = .{}, .workers = if (is_wasm) {} else .{},
.shutdown = std.atomic.Value(bool).init(false), .shutdown = AtomicValue(bool).init(false),
.per_source_counts = std.AutoHashMap([32]u8, u32).init(allocator), .per_source_counts = std.AutoHashMap([32]u8, u32).init(allocator),
.rejected_count = std.atomic.Value(u64).init(0), .rejected_count = AtomicValue(u64).init(0),
.backpressure_events = std.atomic.Value(u64).init(0), .backpressure_events = AtomicValue(u64).init(0),
}; };
} }
pub fn deinit(self: *AsyncMessageProcessor) void { pub fn deinit(self: *AsyncMessageProcessor) void {
self.shutdown.store(true, .monotonic); self.shutdown.store(true, .monotonic);
if (!is_wasm) {
// Wait for workers to finish // Wait for workers to finish
for (self.workers.items) |worker| { for (self.workers.items) |worker| {
worker.join(); worker.join();
} }
self.workers.deinit(self.allocator); self.workers.deinit(self.allocator);
}
self.queue.deinit(self.allocator); self.queue.deinit(self.allocator);
// CRIT-NEW-11 FIX: Clean up per-source tracking // CRIT-NEW-11 FIX: Clean up per-source tracking
self.per_source_counts.deinit(); self.per_source_counts.deinit();
} }
/// Start worker threads /// Start worker threads (no-op on WASM — use processSynchronously instead)
/// Returns error if no workers could be started (critical failure) /// Returns error if no workers could be started (critical failure)
pub fn startWorkers(self: *AsyncMessageProcessor, num_workers: usize) !void { pub fn startWorkers(self: *AsyncMessageProcessor, num_workers: usize) !void {
if (is_wasm) return;
var started: usize = 0; var started: usize = 0;
var spawn_failures: usize = 0; var spawn_failures: usize = 0;
@@ -2331,6 +2342,25 @@ pub const AsyncMessageProcessor = struct {
} }
} }
/// Process up to `max_messages` queued messages synchronously.
/// For WASM: call this from the update loop since threads are unavailable.
/// On native: this can also be used for single-threaded operation.
pub fn processSynchronously(self: *AsyncMessageProcessor, max_messages: usize) void {
var processed: usize = 0;
while (processed < max_messages) : (processed += 1) {
var msg: message.Message = undefined;
{
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
if (self.queue.items.len == 0) break;
msg = self.queue.orderedRemove(0);
}
self.registry.processMessage(msg) catch |err| {
std.log.err("Error processing message of type {}: {s}", .{ msg.getType(), @errorName(err) });
};
}
}
/// Queue a message for processing /// Queue a message for processing
/// CRIT-NEW-11 FIX: Implements backpressure when queue approaches capacity /// CRIT-NEW-11 FIX: Implements backpressure when queue approaches capacity
/// source_id: Optional source peer ID for backpressure tracking (null = anonymous tracking by type) /// source_id: Optional source peer ID for backpressure tracking (null = anonymous tracking by type)

View File

@@ -23,6 +23,7 @@ const std = @import("std");
const handler_mod = @import("handler.zig"); const handler_mod = @import("handler.zig");
const message = @import("message.zig"); const message = @import("message.zig");
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
const platform_time = @import("platform").time;
// Import network and file components via module exports // Import network and file components via module exports
const network = @import("network"); const network = @import("network");
@@ -71,7 +72,7 @@ pub fn handleDiscoveryHello(
} }
// Verify timestamp is recent (within 5 minutes) // Verify timestamp is recent (within 5 minutes)
const now = std.time.timestamp(); const now = platform_time.timestamp();
const max_age: i64 = 300; // 5 minutes const max_age: i64 = 300; // 5 minutes
if (@abs(now - msg.timestamp) > max_age) { if (@abs(now - msg.timestamp) > max_age) {
std.log.warn("SECURITY: Discovery hello rejected - timestamp too old ({d}s)", .{@abs(now - msg.timestamp)}); std.log.warn("SECURITY: Discovery hello rejected - timestamp too old ({d}s)", .{@abs(now - msg.timestamp)});
@@ -184,7 +185,7 @@ pub fn handlePing(
} }
// Record ping time for RTT calculation // Record ping time for RTT calculation
const now = std.time.timestamp(); const now = platform_time.timestamp();
try ping_times.put(msg.sequence, now); try ping_times.put(msg.sequence, now);
// Send Pong response back to the sender // Send Pong response back to the sender
@@ -211,7 +212,7 @@ pub fn handlePong(
const source_id = context.source_peer_id orelse return error.InvalidMessage; const source_id = context.source_peer_id orelse return error.InvalidMessage;
const calculated_rtt: u32 = if (ping_times.get(msg.sequence)) |ping_time| blk: { const calculated_rtt: u32 = if (ping_times.get(msg.sequence)) |ping_time| blk: {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// MED-1 FIX: Safe RTT calculation with bounds checking // MED-1 FIX: Safe RTT calculation with bounds checking
const elapsed = now - ping_time; const elapsed = now - ping_time;
const rtt_ms = if (elapsed < 0) 0 else std.math.mul(i64, elapsed, 1000) catch std.math.maxInt(i64); const rtt_ms = if (elapsed < 0) 0 else std.math.mul(i64, elapsed, 1000) catch std.math.maxInt(i64);
@@ -957,7 +958,7 @@ pub fn handleDhtFindNode(
.observed_addr = observed.addr, .observed_addr = observed.addr,
.observed_addr_len = observed.len, .observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(), .wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };
@@ -1075,7 +1076,7 @@ pub fn handleDhtStore(
.observed_addr = observed.addr, .observed_addr = observed.addr,
.observed_addr_len = observed.len, .observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(), .wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };
_ = context.sendDhtMessage(msg.sender_id, fail_response); _ = context.sendDhtMessage(msg.sender_id, fail_response);
@@ -1091,7 +1092,7 @@ pub fn handleDhtStore(
.observed_addr = observed.addr, .observed_addr = observed.addr,
.observed_addr_len = observed.len, .observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(), .wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };
@@ -1207,7 +1208,7 @@ pub fn handleDhtFindValue(
.observed_addr = observed.addr, .observed_addr = observed.addr,
.observed_addr_len = observed.len, .observed_addr_len = observed.len,
.wire_nonce = message.generateWireNonce(), .wire_nonce = message.generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}, },
}; };

View File

@@ -1,6 +1,8 @@
//! Message definitions and types for the protocol //! Message definitions and types for the protocol
const std = @import("std"); const std = @import("std");
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
const random = @import("platform").random;
const platform_time = @import("platform").time;
/// Unique message identifier /// Unique message identifier
pub const MessageId = u64; pub const MessageId = u64;
@@ -51,7 +53,7 @@ pub const MessageHeader = struct {
.id = id, .id = id,
.source = source, .source = source,
.dest = dest, .dest = dest,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -561,7 +563,7 @@ pub const DhtFindNode = struct {
.target_observed_addr = [_]u8{0} ** 18, .target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0, .target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -573,7 +575,7 @@ pub const DhtFindNode = struct {
.target_observed_addr = addr, .target_observed_addr = addr,
.target_observed_addr_len = addr_len, .target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -605,7 +607,7 @@ pub const DhtFindNodeResponse = struct {
.observed_addr = [_]u8{0} ** 18, .observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0, .observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -616,7 +618,7 @@ pub const DhtFindNodeResponse = struct {
.observed_addr = addr, .observed_addr = addr,
.observed_addr_len = addr_len, .observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -648,7 +650,7 @@ pub const DhtStore = struct {
.target_observed_addr = [_]u8{0} ** 18, .target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0, .target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -662,7 +664,7 @@ pub const DhtStore = struct {
.target_observed_addr = addr, .target_observed_addr = addr,
.target_observed_addr_len = addr_len, .target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -687,7 +689,7 @@ pub const DhtStoreResponse = struct {
.observed_addr = [_]u8{0} ** 18, .observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0, .observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -698,7 +700,7 @@ pub const DhtStoreResponse = struct {
.observed_addr = addr, .observed_addr = addr,
.observed_addr_len = addr_len, .observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -726,7 +728,7 @@ pub const DhtFindValue = struct {
.target_observed_addr = [_]u8{0} ** 18, .target_observed_addr = [_]u8{0} ** 18,
.target_observed_addr_len = 0, .target_observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -738,7 +740,7 @@ pub const DhtFindValue = struct {
.target_observed_addr = addr, .target_observed_addr = addr,
.target_observed_addr_len = addr_len, .target_observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
@@ -767,7 +769,7 @@ pub const DhtFindValueResponse = struct {
.observed_addr = [_]u8{0} ** 18, .observed_addr = [_]u8{0} ** 18,
.observed_addr_len = 0, .observed_addr_len = 0,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
@@ -780,25 +782,25 @@ pub const DhtFindValueResponse = struct {
.observed_addr = addr, .observed_addr = addr,
.observed_addr_len = addr_len, .observed_addr_len = addr_len,
.wire_nonce = generateWireNonce(), .wire_nonce = generateWireNonce(),
.wire_timestamp = std.time.timestamp(), .wire_timestamp = platform_time.timestamp(),
}; };
} }
}; };
/// Generate a cryptographically random wire nonce for replay detection /// Generate a cryptographically random wire nonce for replay detection
pub fn generateWireNonce() u64 { pub fn generateWireNonce() u64 {
var bytes: [8]u8 = undefined; var buf: [8]u8 = undefined;
std.crypto.random.bytes(&bytes); random.bytes(&buf);
return std.mem.readInt(u64, &bytes, .little); return std.mem.readInt(u64, &buf, .little);
} }
/// Generate a unique request ID for correlating DHT request/response pairs. /// Generate a unique request ID for correlating DHT request/response pairs.
/// Replay detection is handled by wire_nonce, so this only needs to be unique /// Replay detection is handled by wire_nonce, so this only needs to be unique
/// enough to match responses to their pending requests. /// enough to match responses to their pending requests.
fn generateRequestId() u64 { fn generateRequestId() u64 {
var bytes: [8]u8 = undefined; var buf: [8]u8 = undefined;
std.crypto.random.bytes(&bytes); random.bytes(&buf);
return std.mem.readInt(u64, &bytes, .little); return std.mem.readInt(u64, &buf, .little);
} }
/// Security messages for key exchange /// Security messages for key exchange
@@ -932,7 +934,7 @@ var replay_siphash_key: [16]u8 = undefined;
var replay_siphash_key_once = std.once(initReplaySiphashKey); var replay_siphash_key_once = std.once(initReplaySiphashKey);
fn initReplaySiphashKey() void { fn initReplaySiphashKey() void {
std.crypto.random.bytes(&replay_siphash_key); random.bytes(&replay_siphash_key);
} }
fn getReplaySiphashKey() *const [16]u8 { fn getReplaySiphashKey() *const [16]u8 {
@@ -1075,7 +1077,7 @@ pub const Message = union(protocol.MessageType) {
// this switch. Using random means replay protection relies solely // this switch. Using random means replay protection relies solely
// on per-peer msg_id dedup and Noise AEAD. // on per-peer msg_id dedup and Noise AEAD.
var id: [8]u8 = undefined; var id: [8]u8 = undefined;
std.crypto.random.bytes(&id); random.bytes(&id);
break :blk std.mem.readInt(u64, &id, .little); break :blk std.mem.readInt(u64, &id, .little);
}, },
}; };
@@ -1085,7 +1087,7 @@ pub const Message = union(protocol.MessageType) {
/// ///
/// Returns the sender-provided timestamp where available, enabling the replay /// Returns the sender-provided timestamp where available, enabling the replay
/// protector to reject stale or future-dated messages. Types without an embedded /// protector to reject stale or future-dated messages. Types without an embedded
/// timestamp return the receiver's clock (std.time.timestamp()), which makes /// timestamp return the receiver's clock (platform_time.timestamp()), which makes
/// timestamp validation a no-op for those types. This is acceptable because: /// timestamp validation a no-op for those types. This is acceptable because:
/// ///
/// - With Noise ON (production): AEAD prevents replay at the transport layer. /// - With Noise ON (production): AEAD prevents replay at the transport layer.
@@ -1114,7 +1116,7 @@ pub const Message = union(protocol.MessageType) {
// All other types have no sender timestamp. Returning receiver's clock // All other types have no sender timestamp. Returning receiver's clock
// makes validateTimestamp() a no-op. Replay defense for these types relies // makes validateTimestamp() a no-op. Replay defense for these types relies
// on msg_id dedup, sequence windows, and Noise AEAD. // on msg_id dedup, sequence windows, and Noise AEAD.
else => std.time.timestamp(), else => platform_time.timestamp(),
}; };
} }
@@ -1185,7 +1187,7 @@ pub const MessageBuilder = struct {
// Use full 64 bits of cryptographic randomness for message IDs // Use full 64 bits of cryptographic randomness for message IDs
// This provides maximum entropy and unpredictability for security // This provides maximum entropy and unpredictability for security
var random_bytes: [8]u8 = undefined; var random_bytes: [8]u8 = undefined;
std.crypto.random.bytes(&random_bytes); random.bytes(&random_bytes);
return std.mem.readInt(u64, &random_bytes, .little); return std.mem.readInt(u64, &random_bytes, .little);
} }
}; };

View File

@@ -6,6 +6,8 @@
//! - Per-peer, per-type message ID dedup //! - Per-peer, per-type message ID dedup
const std = @import("std"); const std = @import("std");
const Mutex = @import("sync").Mutex;
const platform_time = @import("platform").time;
const message = @import("message.zig"); const message = @import("message.zig");
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
@@ -62,7 +64,7 @@ const PeerSequenceState = struct {
pub fn init() PeerSequenceState { pub fn init() PeerSequenceState {
return .{ return .{
.last_sequence = 0, .last_sequence = 0,
.last_update = std.time.timestamp(), .last_update = platform_time.timestamp(),
.window = 0, .window = 0,
}; };
} }
@@ -118,7 +120,7 @@ const PeerSequenceState = struct {
/// Reset sequence state (for peer reconnection) /// Reset sequence state (for peer reconnection)
pub fn reset(self: *PeerSequenceState) void { pub fn reset(self: *PeerSequenceState) void {
self.last_sequence = 0; self.last_sequence = 0;
self.last_update = std.time.timestamp(); self.last_update = platform_time.timestamp();
self.window = 0; self.window = 0;
} }
}; };
@@ -160,7 +162,7 @@ pub const ReplayProtector = struct {
cleanup_interval: i64, cleanup_interval: i64,
/// Mutex for thread-safe operations /// Mutex for thread-safe operations
mutex: std.Thread.Mutex, mutex: Mutex,
/// SECURITY: Maximum number of tracked messages to prevent memory exhaustion /// SECURITY: Maximum number of tracked messages to prevent memory exhaustion
/// At 60 seconds TTL and assuming max 10k msg/sec, 600k is ~1 minute of traffic /// At 60 seconds TTL and assuming max 10k msg/sec, 600k is ~1 minute of traffic
@@ -176,7 +178,7 @@ pub const ReplayProtector = struct {
.peer_sequences = std.AutoHashMap([32]u8, PeerSequenceState).init(allocator), .peer_sequences = std.AutoHashMap([32]u8, PeerSequenceState).init(allocator),
.max_clock_skew = 5, // HIGH-3: 5 seconds (reduced from 15s) .max_clock_skew = 5, // HIGH-3: 5 seconds (reduced from 15s)
.message_ttl = 10, // HIGH-3: 10 seconds (reduced from 30s) .message_ttl = 10, // HIGH-3: 10 seconds (reduced from 30s)
.last_cleanup = std.time.timestamp(), .last_cleanup = platform_time.timestamp(),
.cleanup_interval = 30, // CRY-M5: 30 seconds (reduced from 60s) .cleanup_interval = 30, // CRY-M5: 30 seconds (reduced from 60s)
.mutex = .{}, .mutex = .{},
}; };
@@ -208,7 +210,7 @@ pub const ReplayProtector = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
// SECURITY: Check and enforce memory limits before adding entries // SECURITY: Check and enforce memory limits before adding entries
if (self.seen_messages.count() >= MAX_TRACKED_MESSAGES) { if (self.seen_messages.count() >= MAX_TRACKED_MESSAGES) {
@@ -406,7 +408,7 @@ pub const ReplayProtector = struct {
self.mutex.lock(); self.mutex.lock();
defer self.mutex.unlock(); defer self.mutex.unlock();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
self.cleanup(current_time); self.cleanup(current_time);
self.last_cleanup = current_time; self.last_cleanup = current_time;
} }
@@ -475,7 +477,7 @@ test "timestamp validation - reject old timestamps" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const old_timestamp = current_time - 7200; // 2 hours ago const old_timestamp = current_time - 7200; // 2 hours ago
const peer_id = [_]u8{1} ** 32; const peer_id = [_]u8{1} ** 32;
@@ -488,7 +490,7 @@ test "timestamp validation - reject future timestamps" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const future_timestamp = current_time + 600; // 10 minutes in future const future_timestamp = current_time + 600; // 10 minutes in future
const peer_id = [_]u8{1} ** 32; const peer_id = [_]u8{1} ** 32;
@@ -501,7 +503,7 @@ test "timestamp validation - accept valid timestamps" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
// HIGH-3: TTL is now 10 seconds, so use 5 seconds ago to be safely within TTL // HIGH-3: TTL is now 10 seconds, so use 5 seconds ago to be safely within TTL
const valid_timestamp = current_time - 5; const valid_timestamp = current_time - 5;
@@ -516,7 +518,7 @@ test "duplicate message ID detection" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{1} ** 32; const peer_id = [_]u8{1} ** 32;
// First message should succeed // First message should succeed
@@ -531,7 +533,7 @@ test "sequence number enforcement - in order" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{1} ** 32; const peer_id = [_]u8{1} ** 32;
// Send messages in order // Send messages in order
@@ -547,7 +549,7 @@ test "sequence number enforcement - out of order within window" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{2} ** 32; const peer_id = [_]u8{2} ** 32;
// Send sequence 1, 2, 5, then 3 (out of order but within window) // Send sequence 1, 2, 5, then 3 (out of order but within window)
@@ -561,7 +563,7 @@ test "sequence number enforcement - reject duplicate sequence" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{3} ** 32; const peer_id = [_]u8{3} ** 32;
// Send sequence 1, 2, then 2 again // Send sequence 1, 2, then 2 again
@@ -576,7 +578,7 @@ test "sequence number enforcement - reject too old sequence" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{4} ** 32; const peer_id = [_]u8{4} ** 32;
// Send sequence 100, then try to send sequence 1 (too old, outside window) // Send sequence 100, then try to send sequence 1 (too old, outside window)
@@ -590,7 +592,7 @@ test "sliding window - large sequence jump" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{5} ** 32; const peer_id = [_]u8{5} ** 32;
// Small sequence // Small sequence
@@ -610,7 +612,7 @@ test "cleanup removes old entries" {
// Use short TTL for testing (1 second) // Use short TTL for testing (1 second)
protector.configure(null, 1, null); protector.configure(null, 1, null);
const base_time = std.time.timestamp(); const base_time = platform_time.timestamp();
const peer_id = [_]u8{6} ** 32; const peer_id = [_]u8{6} ** 32;
// Add messages with current timestamp (within TTL window) // Add messages with current timestamp (within TTL window)
@@ -634,7 +636,7 @@ test "peer sequence reset" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer_id = [_]u8{7} ** 32; const peer_id = [_]u8{7} ** 32;
// Send some messages // Send some messages
@@ -652,7 +654,7 @@ test "multiple peers tracked independently" {
var protector = ReplayProtector.init(std.testing.allocator); var protector = ReplayProtector.init(std.testing.allocator);
defer protector.deinit(); defer protector.deinit();
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
const peer1 = [_]u8{1} ** 32; const peer1 = [_]u8{1} ** 32;
const peer2 = [_]u8{2} ** 32; const peer2 = [_]u8{2} ** 32;

View File

@@ -3,6 +3,9 @@
//! file corruption during concurrent downloads and large file transfers. //! file corruption during concurrent downloads and large file transfers.
const std = @import("std"); const std = @import("std");
const Mutex = @import("sync").Mutex;
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const message = @import("message.zig"); const message = @import("message.zig");
/// Information stored for each tracked request /// Information stored for each tracked request
@@ -31,7 +34,7 @@ pub const RequestInfo = struct {
.piece_index = piece_index, .piece_index = piece_index,
.offset = offset, .offset = offset,
.file_hash = file_hash, .file_hash = file_hash,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.peer_id = peer_id, .peer_id = peer_id,
.size = size, .size = size,
}; };
@@ -39,7 +42,7 @@ pub const RequestInfo = struct {
/// Check if this request has timed out /// Check if this request has timed out
pub fn isExpired(self: RequestInfo, timeout_seconds: i64) bool { pub fn isExpired(self: RequestInfo, timeout_seconds: i64) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
return (now - self.timestamp) > timeout_seconds; return (now - self.timestamp) > timeout_seconds;
} }
}; };
@@ -50,7 +53,7 @@ pub const RequestTracker = struct {
/// Map from request_id to request info /// Map from request_id to request info
requests: std.AutoHashMap(message.MessageId, RequestInfo), requests: std.AutoHashMap(message.MessageId, RequestInfo),
/// Mutex for thread-safe access /// Mutex for thread-safe access
mutex: std.Thread.Mutex, mutex: Mutex,
/// Default timeout in seconds /// Default timeout in seconds
timeout_seconds: i64, timeout_seconds: i64,
@@ -78,13 +81,13 @@ pub const RequestTracker = struct {
_ = self; _ = self;
// Get nanosecond timestamp and use lower 32 bits // Get nanosecond timestamp and use lower 32 bits
// nanoTimestamp() returns i128, so we take the absolute value and truncate // nanoTimestamp() returns i128, so we take the absolute value and truncate
const ts = std.time.nanoTimestamp(); const ts = platform_time.nanoTimestamp();
const ts_abs: u128 = @intCast(if (ts < 0) -ts else ts); const ts_abs: u128 = @intCast(if (ts < 0) -ts else ts);
const ts_component: u32 = @truncate(ts_abs); const ts_component: u32 = @truncate(ts_abs);
// Get 4 bytes of cryptographic randomness // Get 4 bytes of cryptographic randomness
var random_bytes: [4]u8 = undefined; var random_bytes: [4]u8 = undefined;
std.crypto.random.bytes(&random_bytes); platform_random.bytes(&random_bytes);
const random_component = std.mem.readInt(u32, &random_bytes, .little); const random_component = std.mem.readInt(u32, &random_bytes, .little);
// Combine: timestamp in high bits, random in low bits // Combine: timestamp in high bits, random in low bits

View File

@@ -15,7 +15,9 @@
//! unless they are within the same transaction (e.g., acquiring metrics_lock is safe //! unless they are within the same transaction (e.g., acquiring metrics_lock is safe
//! because it's Level 0). //! because it's Level 0).
const std = @import("std"); const std = @import("std");
const Mutex = @import("sync").Mutex;
const core = @import("core"); const core = @import("core");
const platform_time = @import("platform").time;
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
const message = @import("message.zig"); const message = @import("message.zig");
const serializer = @import("serializer.zig"); const serializer = @import("serializer.zig");
@@ -119,9 +121,9 @@ pub const MessageRouter = struct {
// Thread safety: Protect all shared state // Thread safety: Protect all shared state
// Use RwLock for route_table (read-heavy operation) // Use RwLock for route_table (read-heavy operation)
// Use Mutex for pending_queries and other maps // Use Mutex for pending_queries and other maps
route_table_lock: std.Thread.RwLock = .{}, route_table_lock: @import("sync").RwLock = .{},
pending_queries_lock: std.Thread.Mutex = .{}, pending_queries_lock: Mutex = .{},
metrics_lock: std.Thread.Mutex = .{}, metrics_lock: Mutex = .{},
// THR-1 FIX: Lock ordering documentation to prevent deadlock // THR-1 FIX: Lock ordering documentation to prevent deadlock
// LOCK ORDERING (must be acquired in this order to prevent deadlock): // LOCK ORDERING (must be acquired in this order to prevent deadlock):
@@ -129,8 +131,8 @@ pub const MessageRouter = struct {
// 2. peers_lock // 2. peers_lock
// When acquiring both locks, ALWAYS acquire neighbors_lock first. // When acquiring both locks, ALWAYS acquire neighbors_lock first.
// Never acquire neighbors_lock while holding peers_lock. // Never acquire neighbors_lock while holding peers_lock.
neighbors_lock: std.Thread.Mutex = .{}, neighbors_lock: Mutex = .{},
peers_lock: std.Thread.Mutex = .{}, // Protects directly_connected_peers and peer_public_keys peers_lock: Mutex = .{}, // Protects directly_connected_peers and peer_public_keys
// SECURITY: Signed routes are MANDATORY (compile-time enforced) // SECURITY: Signed routes are MANDATORY (compile-time enforced)
/// Route signatures prevent route poisoning attacks and are always required /// Route signatures prevent route poisoning attacks and are always required
@@ -167,7 +169,7 @@ pub const MessageRouter = struct {
/// Cleanup timed out pending queries - MUST hold pending_queries_lock /// Cleanup timed out pending queries - MUST hold pending_queries_lock
fn cleanupTimedOutQueriesLocked(self: *MessageRouter) void { fn cleanupTimedOutQueriesLocked(self: *MessageRouter) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
var keys_to_remove: std.ArrayListUnmanaged(message.MessageId) = .{}; var keys_to_remove: std.ArrayListUnmanaged(message.MessageId) = .{};
defer keys_to_remove.deinit(self.allocator); defer keys_to_remove.deinit(self.allocator);
@@ -204,9 +206,9 @@ pub const MessageRouter = struct {
/// Route a message to its destination /// Route a message to its destination
pub fn routeMessage(self: *MessageRouter, base_msg: message.BaseMessage) RouteResult { pub fn routeMessage(self: *MessageRouter, base_msg: message.BaseMessage) RouteResult {
const start_time = std.time.timestamp(); const start_time = platform_time.timestamp();
defer { defer {
const elapsed = @as(f64, @floatFromInt(std.time.timestamp() - start_time)); const elapsed = @as(f64, @floatFromInt(platform_time.timestamp() - start_time));
self.metrics_lock.lock(); self.metrics_lock.lock();
self.metrics.average_lookup_time = (self.metrics.average_lookup_time * 0.9) + (elapsed * 0.1); self.metrics.average_lookup_time = (self.metrics.average_lookup_time * 0.9) + (elapsed * 0.1);
self.metrics_lock.unlock(); self.metrics_lock.unlock();
@@ -308,7 +310,7 @@ pub const MessageRouter = struct {
sig: RouteSignature, sig: RouteSignature,
) bool { ) bool {
// Verify timestamp is recent (SECURITY: reduced from 5 minutes to 60 seconds) // Verify timestamp is recent (SECURITY: reduced from 5 minutes to 60 seconds)
const now = std.time.timestamp(); const now = platform_time.timestamp();
const max_sig_age: i64 = 60; // 60 seconds const max_sig_age: i64 = 60; // 60 seconds
if (now - sig.timestamp > max_sig_age or sig.timestamp > now + 60) { if (now - sig.timestamp > max_sig_age or sig.timestamp > now + 60) {
std.log.warn("Route signature timestamp out of acceptable range", .{}); std.log.warn("Route signature timestamp out of acceptable range", .{});
@@ -490,7 +492,7 @@ pub const MessageRouter = struct {
.destination = destination, .destination = destination,
.next_hop = next_hop, .next_hop = next_hop,
.cost = cost, .cost = cost,
.last_updated = std.time.timestamp(), .last_updated = platform_time.timestamp(),
.is_valid = true, .is_valid = true,
.signature = signature, .signature = signature,
}; };
@@ -514,7 +516,7 @@ pub const MessageRouter = struct {
/// Evict the least recently used route (caller must hold route_table_lock) /// Evict the least recently used route (caller must hold route_table_lock)
fn evictLRURoute(self: *MessageRouter) !void { fn evictLRURoute(self: *MessageRouter) !void {
var oldest_time: i64 = std.time.timestamp(); var oldest_time: i64 = platform_time.timestamp();
var oldest_dest: ?message.NodeId = null; var oldest_dest: ?message.NodeId = null;
var it = self.routes.iterator(); var it = self.routes.iterator();
@@ -558,7 +560,7 @@ pub const MessageRouter = struct {
if (self.routes.getEntry(destination)) |entry| { if (self.routes.getEntry(destination)) |entry| {
entry.value_ptr.is_valid = false; entry.value_ptr.is_valid = false;
entry.value_ptr.last_updated = std.time.timestamp(); entry.value_ptr.last_updated = platform_time.timestamp();
self.metrics_lock.lock(); self.metrics_lock.lock();
self.metrics.active_routes -= 1; self.metrics.active_routes -= 1;
self.metrics_lock.unlock(); self.metrics_lock.unlock();
@@ -654,7 +656,7 @@ pub const MessageRouter = struct {
cost: u32, cost: u32,
signer_secret_key: [64]u8, // Ed25519 secret key (includes public key in last 32 bytes) signer_secret_key: [64]u8, // Ed25519 secret key (includes public key in last 32 bytes)
) SignatureError!RouteSignature { ) SignatureError!RouteSignature {
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
// Construct the data to sign - now includes origin // Construct the data to sign - now includes origin
const signed_data = self.constructSignedData(origin, destination, next_hop, cost, timestamp); const signed_data = self.constructSignedData(origin, destination, next_hop, cost, timestamp);
@@ -773,7 +775,7 @@ pub const MessageRouter = struct {
self.pending_queries.put(msg_id, .{ self.pending_queries.put(msg_id, .{
.destination = destination, .destination = destination,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}) catch |err| { }) catch |err| {
self.pending_queries_lock.unlock(); self.pending_queries_lock.unlock();
std.log.err("Failed to track route discovery query: {}", .{err}); std.log.err("Failed to track route discovery query: {}", .{err});
@@ -901,7 +903,7 @@ pub const MessageRouter = struct {
/// Clean up expired routes (uses max_route_age from router config) /// Clean up expired routes (uses max_route_age from router config)
pub fn cleanupExpiredRoutes(self: *MessageRouter, max_age: i64) void { pub fn cleanupExpiredRoutes(self: *MessageRouter, max_age: i64) void {
const current_time = std.time.timestamp(); const current_time = platform_time.timestamp();
var expired_destinations: std.ArrayList(message.NodeId) = .{}; var expired_destinations: std.ArrayList(message.NodeId) = .{};
defer expired_destinations.deinit(self.allocator); defer expired_destinations.deinit(self.allocator);

View File

@@ -3,6 +3,7 @@ const std = @import("std");
const protocol = @import("protocol.zig"); const protocol = @import("protocol.zig");
const message = @import("message.zig"); const message = @import("message.zig");
const crypto = @import("crypto.zig"); const crypto = @import("crypto.zig");
const platform_time = @import("platform").time;
/// Helper to read little-endian integers from buffer slices /// Helper to read little-endian integers from buffer slices
fn readLittle(comptime T: type, buf: []const u8) T { fn readLittle(comptime T: type, buf: []const u8) T {
@@ -702,7 +703,7 @@ pub const MessageSerializer = struct {
.id = id, .id = id,
.source = self.local_peer_id, .source = self.local_peer_id,
.dest = self.peer_id, .dest = self.peer_id,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -1930,7 +1931,7 @@ test "key exchange messages are not encrypted" {
const signature = [_]u8{0xAA} ** 64; const signature = [_]u8{0xAA} ** 64;
const identity_key = [_]u8{0xBB} ** 32; const identity_key = [_]u8{0xBB} ** 32;
const session_nonce = [_]u8{0xCC} ** 32; const session_nonce = [_]u8{0xCC} ** 32;
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
const key_exchange = message.KeyExchangeInit.init(public_key, signature, identity_key, session_nonce, timestamp); const key_exchange = message.KeyExchangeInit.init(public_key, signature, identity_key, session_nonce, timestamp);
const msg = message.Message{ .key_exchange_init = key_exchange }; const msg = message.Message{ .key_exchange_init = key_exchange };
@@ -2334,7 +2335,7 @@ test "key exchange response serialization roundtrip" {
const signature = [_]u8{0x22} ** 64; const signature = [_]u8{0x22} ** 64;
const identity_key = [_]u8{0x33} ** 32; const identity_key = [_]u8{0x33} ** 32;
const initiator_nonce = [_]u8{0x44} ** 32; const initiator_nonce = [_]u8{0x44} ** 32;
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
const key_resp = message.KeyExchangeResponse.init(public_key, signature, identity_key, timestamp, initiator_nonce); const key_resp = message.KeyExchangeResponse.init(public_key, signature, identity_key, timestamp, initiator_nonce);
const msg = message.Message{ .key_exchange_response = key_resp }; const msg = message.Message{ .key_exchange_response = key_resp };