1631 lines
67 KiB
Zig
1631 lines
67 KiB
Zig
//! Network Manager - Handles message sending and receiving for P2P
|
|
//!
|
|
//! Coordinates message serialization, queuing, and delivery across peer connections.
|
|
//!
|
|
//! CRIT-NEW-17 FIX: Lock Ordering Documentation
|
|
//! =============================================
|
|
//! To prevent deadlocks, locks MUST be acquired in this order (lowest first):
|
|
//!
|
|
//! Level 0 (innermost, acquired last):
|
|
//! - rate_limiter.mutex
|
|
//! - stats_mutex
|
|
//! - metrics_lock
|
|
//!
|
|
//! Level 1:
|
|
//! - socket_mutex
|
|
//! - buffer.mutex
|
|
//!
|
|
//! Level 2:
|
|
//! - encryption_manager.mutex
|
|
//! - nonce_tracker.mutex
|
|
//! - replay_protection.mutex
|
|
//!
|
|
//! Level 3:
|
|
//! - queue_mutex
|
|
//! - pending_queries_lock
|
|
//! - neighbors_lock
|
|
//! - peers_lock
|
|
//!
|
|
//! Level 4:
|
|
//! - handlers_mutex
|
|
//! - processing_mutex
|
|
//! - config_mutex
|
|
//!
|
|
//! Level 5:
|
|
//! - sessions_mutex
|
|
//! - file_registry_mutex
|
|
//! - reputation_mutex
|
|
//!
|
|
//! Level 6 (outermost, acquired first):
|
|
//! - network_manager.mutex
|
|
//! - router.mutex (if any)
|
|
//! - p2p.mutex
|
|
//!
|
|
//! RULES:
|
|
//! 1. Never acquire a lower-level lock while holding a higher-level lock
|
|
//! 2. Never call into other subsystems while holding a lock unless documented
|
|
//! 3. Release locks as early as possible
|
|
//! 4. Use defer for lock release to ensure cleanup on error paths
|
|
|
|
const std = @import("std");
|
|
const mem = std.mem;
|
|
const Mutex = std.Thread.Mutex;
|
|
const core = @import("core");
|
|
const noise = @import("noise");
|
|
|
|
const Socket = core.socket.Socket;
|
|
const Error = core.errors.Error;
|
|
const peer = @import("peer.zig");
|
|
const PeerId = peer.PeerId;
|
|
const secure_connection = @import("secure_connection.zig");
|
|
const SecureConnection = secure_connection.SecureConnection;
|
|
|
|
/// Pending send state for non-blocking sends.
|
|
/// When a send operation cannot complete immediately (WouldBlock), the remaining
|
|
/// data is stored here to be drained on subsequent update() calls.
|
|
pub const PendingSend = struct {
|
|
/// Combined data buffer (header + payload) - heap allocated
|
|
data: []u8,
|
|
/// How many bytes have been successfully sent
|
|
offset: usize,
|
|
/// Allocator used for data (for deallocation)
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn init(allocator: mem.Allocator, segments: []const []const u8) Error!PendingSend {
|
|
// Calculate total size
|
|
var total_size: usize = 0;
|
|
for (segments) |seg| {
|
|
total_size += seg.len;
|
|
}
|
|
|
|
// Allocate combined buffer
|
|
const data = allocator.alloc(u8, total_size) catch return Error.SystemError;
|
|
|
|
// Copy all segments into combined buffer
|
|
var write_offset: usize = 0;
|
|
for (segments) |seg| {
|
|
@memcpy(data[write_offset..][0..seg.len], seg);
|
|
write_offset += seg.len;
|
|
}
|
|
|
|
return .{
|
|
.data = data,
|
|
.offset = 0,
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *PendingSend) void {
|
|
self.allocator.free(self.data);
|
|
}
|
|
|
|
/// Returns remaining data to send
|
|
pub fn remaining(self: *const PendingSend) []const u8 {
|
|
return self.data[self.offset..];
|
|
}
|
|
|
|
/// Returns true if all data has been sent
|
|
pub fn isComplete(self: *const PendingSend) bool {
|
|
return self.offset >= self.data.len;
|
|
}
|
|
};
|
|
|
|
/// ASYNC SEND: Queue entry for encrypted data waiting to be sent
|
|
pub const EncryptedQueueEntry = struct {
|
|
data: []u8,
|
|
offset: usize,
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn deinit(self: *EncryptedQueueEntry) void {
|
|
self.allocator.free(self.data);
|
|
}
|
|
|
|
pub fn remaining(self: *const EncryptedQueueEntry) []const u8 {
|
|
return self.data[self.offset..];
|
|
}
|
|
|
|
pub fn isComplete(self: *const EncryptedQueueEntry) bool {
|
|
return self.offset >= self.data.len;
|
|
}
|
|
};
|
|
|
|
/// Per-peer connection state with its own send mutex for parallel I/O.
|
|
/// This enables sending data to multiple peers simultaneously without
|
|
/// serialization on a global mutex - critical for achieving high throughput
|
|
/// when serving many peers.
|
|
pub const PeerConnection = struct {
|
|
/// The underlying socket for this peer
|
|
socket: *Socket,
|
|
/// Per-peer mutex for serializing sends to THIS peer only.
|
|
/// This allows sends to different peers to happen in parallel.
|
|
send_mutex: Mutex,
|
|
/// Pending send data for non-blocking operations (unencrypted path)
|
|
pending_send: ?PendingSend,
|
|
/// ASYNC SEND: Queue of encrypted packets waiting to be sent
|
|
/// This enables non-blocking encrypted sends for high throughput
|
|
encrypted_queue: std.ArrayListUnmanaged(EncryptedQueueEntry),
|
|
/// Allocator for cleanup
|
|
allocator: mem.Allocator,
|
|
/// Optional Noise protocol secure connection (for encrypted transport)
|
|
secure: ?*SecureConnection,
|
|
|
|
pub fn init(allocator: mem.Allocator, socket: *Socket) Error!*PeerConnection {
|
|
const conn = allocator.create(PeerConnection) catch return Error.SystemError;
|
|
conn.* = .{
|
|
.socket = socket,
|
|
.send_mutex = .{},
|
|
.pending_send = null,
|
|
.encrypted_queue = .{},
|
|
.allocator = allocator,
|
|
.secure = null,
|
|
};
|
|
return conn;
|
|
}
|
|
|
|
/// Initialize with a secure connection
|
|
pub fn initSecure(allocator: mem.Allocator, socket: *Socket, secure_conn: *SecureConnection) Error!*PeerConnection {
|
|
const conn = allocator.create(PeerConnection) catch return Error.SystemError;
|
|
conn.* = .{
|
|
.socket = socket,
|
|
.send_mutex = .{},
|
|
.pending_send = null,
|
|
.encrypted_queue = .{},
|
|
.allocator = allocator,
|
|
.secure = secure_conn,
|
|
};
|
|
return conn;
|
|
}
|
|
|
|
pub fn deinit(self: *PeerConnection) void {
|
|
if (self.pending_send) |*ps| {
|
|
ps.deinit();
|
|
}
|
|
// ASYNC SEND: Clean up encrypted queue
|
|
for (self.encrypted_queue.items) |*entry| {
|
|
entry.deinit();
|
|
}
|
|
self.encrypted_queue.deinit(self.allocator);
|
|
if (self.secure) |sec| {
|
|
self.allocator.destroy(sec);
|
|
}
|
|
self.allocator.destroy(self);
|
|
}
|
|
|
|
/// Check if this connection is encrypted
|
|
pub fn isEncrypted(self: *const PeerConnection) bool {
|
|
if (self.secure) |sec| {
|
|
return sec.isEncrypted();
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Get remote peer's Noise public key (if encrypted)
|
|
pub fn getRemoteNoiseKey(self: *const PeerConnection) ?[32]u8 {
|
|
if (self.secure) |sec| {
|
|
return sec.getRemotePublicKey();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Get per-session envelope key from Noise handshake (null when unencrypted)
|
|
pub fn getEnvelopeKey(self: *const PeerConnection) ?[16]u8 {
|
|
if (self.secure) |sec| {
|
|
return sec.getEnvelopeKey();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Get remaining data to send (if any)
|
|
pub fn getPendingRemaining(self: *const PeerConnection) ?[]const u8 {
|
|
if (self.pending_send) |*ps| {
|
|
return ps.remaining();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Check if pending send is complete
|
|
pub fn isPendingComplete(self: *const PeerConnection) bool {
|
|
if (self.pending_send) |*ps| {
|
|
return ps.isComplete();
|
|
}
|
|
return true; // No pending = complete
|
|
}
|
|
};
|
|
|
|
/// Queued outgoing message
|
|
pub const QueuedMessage = struct {
|
|
peer_id: PeerId,
|
|
data: []u8,
|
|
message_id: u64,
|
|
queued_at: i64,
|
|
priority: u8,
|
|
retries: u8,
|
|
|
|
pub fn deinit(self: *QueuedMessage, allocator: mem.Allocator) void {
|
|
allocator.free(self.data);
|
|
}
|
|
};
|
|
|
|
/// Error type for receive buffer operations
|
|
pub const ReceiveBufferError = error{
|
|
/// Message size exceeds maximum allowed
|
|
MessageTooLarge,
|
|
/// Out of memory
|
|
OutOfMemory,
|
|
};
|
|
|
|
/// Buffer for incomplete incoming messages
|
|
pub const ReceiveBuffer = struct {
|
|
buffer: std.ArrayListUnmanaged(u8),
|
|
expected_length: ?usize,
|
|
allocator: mem.Allocator,
|
|
/// Maximum allowed message size (prevents unbounded allocation from malicious peers)
|
|
max_message_size: usize,
|
|
/// Set when an oversized message is detected - requires reset or disconnect
|
|
has_protocol_error: bool,
|
|
/// CRIT-6 FIX: Timestamp of last data received (for timeout cleanup)
|
|
last_activity: i64,
|
|
/// CRIT-6 FIX: Maximum buffer size for this peer
|
|
max_buffer_size: usize,
|
|
|
|
/// Default maximum message size: 2MB (matches protocol.MAX_MESSAGE_SIZE)
|
|
pub const DEFAULT_MAX_MESSAGE_SIZE: usize = 2 * 1024 * 1024;
|
|
/// Default maximum buffer size per peer: 4MB (2x message size for buffering)
|
|
pub const DEFAULT_MAX_BUFFER_SIZE: usize = 4 * 1024 * 1024;
|
|
|
|
pub fn init(allocator: mem.Allocator) ReceiveBuffer {
|
|
return initWithMaxSize(allocator, DEFAULT_MAX_MESSAGE_SIZE);
|
|
}
|
|
|
|
pub fn initWithMaxSize(allocator: mem.Allocator, max_size: usize) ReceiveBuffer {
|
|
return initWithLimits(allocator, max_size, DEFAULT_MAX_BUFFER_SIZE);
|
|
}
|
|
|
|
/// CRIT-6 FIX: Initialize with both message size and buffer size limits
|
|
pub fn initWithLimits(allocator: mem.Allocator, max_message_size: usize, max_buffer_size: usize) ReceiveBuffer {
|
|
return .{
|
|
.buffer = .{},
|
|
.expected_length = null,
|
|
.allocator = allocator,
|
|
.max_message_size = max_message_size,
|
|
.has_protocol_error = false,
|
|
.last_activity = std.time.timestamp(),
|
|
.max_buffer_size = max_buffer_size,
|
|
};
|
|
}
|
|
|
|
/// Get current buffer size in bytes
|
|
pub fn currentSize(self: *const ReceiveBuffer) usize {
|
|
return self.buffer.items.len;
|
|
}
|
|
|
|
/// Check if buffer has timed out (no activity for specified duration)
|
|
pub fn hasTimedOut(self: *const ReceiveBuffer, timeout_seconds: i64) bool {
|
|
const now = std.time.timestamp();
|
|
return (now - self.last_activity) > timeout_seconds;
|
|
}
|
|
|
|
pub fn deinit(self: *ReceiveBuffer, allocator: std.mem.Allocator) void {
|
|
self.buffer.deinit(allocator);
|
|
}
|
|
|
|
/// CRIT-6 FIX: Append with buffer size limit enforcement
|
|
pub fn append(self: *ReceiveBuffer, data: []const u8) ReceiveBufferError!void {
|
|
// Check if appending would exceed per-peer buffer limit
|
|
const new_size = self.buffer.items.len + data.len;
|
|
if (new_size > self.max_buffer_size) {
|
|
core.log.err("SECURITY CRIT-6: Peer receive buffer would exceed limit ({} + {} > {})", .{
|
|
self.buffer.items.len,
|
|
data.len,
|
|
self.max_buffer_size,
|
|
});
|
|
self.has_protocol_error = true;
|
|
return ReceiveBufferError.MessageTooLarge;
|
|
}
|
|
|
|
self.buffer.appendSlice(self.allocator, data) catch return ReceiveBufferError.OutOfMemory;
|
|
|
|
// Update last activity timestamp
|
|
self.last_activity = std.time.timestamp();
|
|
}
|
|
|
|
/// Check if a complete message is available
|
|
/// Returns error if message size exceeds maximum (requires disconnect or reset)
|
|
pub fn hasCompleteMessage(self: *ReceiveBuffer) ReceiveBufferError!bool {
|
|
// If we already have a protocol error, don't try to parse more
|
|
if (self.has_protocol_error) return ReceiveBufferError.MessageTooLarge;
|
|
|
|
if (self.buffer.items.len < 4) return false;
|
|
|
|
// First 4 bytes are message length
|
|
if (self.expected_length == null) {
|
|
const len_bytes = self.buffer.items[0..4];
|
|
const msg_len = std.mem.readInt(u32, len_bytes[0..4], .big);
|
|
|
|
// SECURITY: Validate message size before accepting it
|
|
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 });
|
|
// DEBUG: Print first 32 bytes of buffer to help diagnose framing issues
|
|
const debug_len = @min(self.buffer.items.len, 32);
|
|
core.log.err("DEBUG: Buffer first {} bytes: {x}", .{ debug_len, self.buffer.items[0..debug_len] });
|
|
core.log.err("DEBUG: Buffer total length: {}, len_bytes: {x}", .{ self.buffer.items.len, len_bytes.* });
|
|
self.has_protocol_error = true;
|
|
return ReceiveBufferError.MessageTooLarge;
|
|
}
|
|
|
|
self.expected_length = msg_len;
|
|
}
|
|
|
|
return self.buffer.items.len >= self.expected_length.? + 4;
|
|
}
|
|
|
|
pub fn extractMessage(self: *ReceiveBuffer, allocator: mem.Allocator) ![]u8 {
|
|
const msg_len = self.expected_length.?;
|
|
|
|
const msg_data = try allocator.dupe(u8, self.buffer.items[4 .. 4 + msg_len]);
|
|
|
|
// Remove processed bytes
|
|
const remaining = self.buffer.items[4 + msg_len ..];
|
|
std.mem.copyForwards(u8, self.buffer.items[0..remaining.len], remaining);
|
|
self.buffer.shrinkRetainingCapacity(remaining.len);
|
|
self.expected_length = null;
|
|
|
|
return msg_data;
|
|
}
|
|
|
|
/// Reset buffer state after a protocol error (clears all buffered data)
|
|
pub fn reset(self: *ReceiveBuffer) void {
|
|
self.buffer.clearRetainingCapacity();
|
|
self.expected_length = null;
|
|
self.has_protocol_error = false;
|
|
}
|
|
};
|
|
|
|
/// Configuration for network manager
|
|
pub const Config = struct {
|
|
/// Maximum connection retries on WouldBlock errors (default: 1000 retries = ~10 seconds at 10ms each)
|
|
max_connection_retries: u32 = 1000,
|
|
/// Retry delay in milliseconds when WouldBlock is encountered
|
|
retry_delay_ms: u32 = 10,
|
|
/// Maximum retries for queued messages before giving up
|
|
max_queue_retries: u8 = 3,
|
|
/// Receive buffer size (configurable to avoid stack overflow)
|
|
receive_buffer_size: usize = 512 * 1024, // 512KB - balance between throughput and memory overhead
|
|
/// Maximum message size (for validation) - 2MB for large piece transfers
|
|
max_message_size: usize = 2 * 1024 * 1024, // 2MB default
|
|
|
|
// CRIT-5 FIX: Send queue limits
|
|
/// Maximum messages in send queue
|
|
max_send_queue_messages: usize = 10000,
|
|
/// Maximum total bytes in send queue
|
|
max_send_queue_bytes: usize = 256 * 1024 * 1024, // 256MB
|
|
/// Maximum age of queued message before eviction in seconds
|
|
max_send_queue_age_seconds: i64 = 60,
|
|
|
|
// CRIT-6 FIX: Receive buffer limits
|
|
/// Maximum total receive buffer memory across all peers
|
|
max_total_receive_buffer_bytes: usize = 2 * 1024 * 1024 * 1024, // 2GB for large file transfers
|
|
/// Maximum receive buffer size per peer
|
|
max_receive_buffer_per_peer: usize = 32 * 1024 * 1024, // 32MB for high throughput transfers
|
|
/// Timeout for incomplete messages in receive buffer in seconds
|
|
receive_buffer_timeout_seconds: i64 = 30,
|
|
};
|
|
|
|
/// Event type for network errors
|
|
pub const NetworkError = struct {
|
|
error_type: ErrorType,
|
|
peer_id: ?PeerId,
|
|
count: u64,
|
|
timestamp: i64,
|
|
|
|
pub const ErrorType = enum {
|
|
disconnect_tracking_failed,
|
|
};
|
|
};
|
|
|
|
/// Network Manager coordinates all peer message I/O
|
|
pub const NetworkManager = struct {
|
|
allocator: mem.Allocator,
|
|
connections: *std.AutoHashMap(PeerId, *PeerConnection),
|
|
send_queue: std.ArrayListUnmanaged(QueuedMessage),
|
|
receive_buffers: std.AutoHashMap(PeerId, ReceiveBuffer),
|
|
stats: NetworkStats,
|
|
config: Config,
|
|
/// Thread safety mutex for protecting send_queue and receive_buffers
|
|
mutex: std.Thread.Mutex = .{},
|
|
/// CRITICAL FIX: Pointer to P2P's socket mutex for atomic socket access.
|
|
/// This ensures that all socket sends (file transfer, regular messages, etc.)
|
|
/// use the same mutex to prevent message interleaving on the wire.
|
|
socket_mutex: ?*std.Thread.Mutex = null,
|
|
/// Optional rate limiter for incoming messages
|
|
peer_rate_limiter: ?*core.rate_limiter.PeerRateLimiter,
|
|
/// Counter for failed disconnection tracking attempts
|
|
failed_disconnect_tracking: std.atomic.Value(u64),
|
|
/// Error event callback for monitoring
|
|
error_callback: ?*const fn (error_event: NetworkError, context: ?*anyopaque) void,
|
|
error_callback_context: ?*anyopaque,
|
|
|
|
// CRIT-5 FIX: Track send queue memory usage
|
|
/// Current total bytes in send queue (atomic for thread-safe reads)
|
|
send_queue_bytes: std.atomic.Value(usize),
|
|
/// Messages dropped due to queue full
|
|
send_queue_drops: std.atomic.Value(u64),
|
|
|
|
// CRIT-6 FIX: Track receive buffer memory usage
|
|
/// Current total bytes across all receive buffers
|
|
total_receive_buffer_bytes: std.atomic.Value(usize),
|
|
/// Connections rejected due to receive buffer memory limit
|
|
receive_buffer_rejections: std.atomic.Value(u64),
|
|
|
|
// THR-2 FIX: Mutex to protect callback assignments (prevents callback/context mismatch)
|
|
callback_mutex: std.Thread.Mutex = .{},
|
|
|
|
// Callbacks with context
|
|
//
|
|
// CRITICAL DATA OWNERSHIP: Message callback receives borrowed data (const []const u8).
|
|
// The data is ONLY valid during the callback execution and will be freed
|
|
// immediately after the callback returns.
|
|
//
|
|
// If the callback needs to keep the data, it MUST make a copy using allocator.dupe()
|
|
// and manage the lifetime of that copy.
|
|
//
|
|
// Example safe usage:
|
|
// fn onMessage(peer_id: PeerId, data: []const u8, ctx: ?*anyopaque) void {
|
|
// const my_data = allocator.dupe(u8, data) catch return; // Make copy
|
|
// defer allocator.free(my_data); // Or store and free later
|
|
// // Use my_data safely
|
|
// }
|
|
message_callback: ?*const fn (peer_id: PeerId, message: []const u8, context: ?*anyopaque) void,
|
|
message_callback_context: ?*anyopaque,
|
|
disconnect_callback: ?*const fn (peer_id: PeerId, context: ?*anyopaque) void,
|
|
disconnect_callback_context: ?*anyopaque,
|
|
|
|
pub const NetworkStats = struct {
|
|
messages_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
messages_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
bytes_sent: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
bytes_received: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
send_errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
receive_errors: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
messages_rate_limited: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
/// Internal operations that failed (tracking, buffer creation, etc.)
|
|
failed_operations: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
/// ERR-M1 FIX: Aggregate broadcast failures
|
|
broadcast_failures: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
/// ERR-M4 FIX: Aggregate queue retry exhaustions
|
|
queue_retry_exhausted: std.atomic.Value(u64) = std.atomic.Value(u64).init(0),
|
|
|
|
/// Record a sent message with atomic updates
|
|
/// Uses .release ordering so readers with .acquire see consistent values
|
|
pub fn recordSend(self: *NetworkStats, bytes: usize) void {
|
|
_ = self.messages_sent.fetchAdd(1, .release);
|
|
_ = self.bytes_sent.fetchAdd(bytes, .release);
|
|
}
|
|
|
|
/// Record a received message with atomic updates
|
|
pub fn recordReceive(self: *NetworkStats, bytes: usize) void {
|
|
_ = self.messages_received.fetchAdd(1, .release);
|
|
_ = self.bytes_received.fetchAdd(bytes, .release);
|
|
}
|
|
|
|
/// Record a send error with atomic update
|
|
pub fn recordSendError(self: *NetworkStats) void {
|
|
_ = self.send_errors.fetchAdd(1, .release);
|
|
}
|
|
|
|
/// Record a receive error with atomic update
|
|
pub fn recordReceiveError(self: *NetworkStats) void {
|
|
_ = self.receive_errors.fetchAdd(1, .release);
|
|
}
|
|
|
|
/// Record a rate limited message with atomic update
|
|
pub fn recordRateLimited(self: *NetworkStats) void {
|
|
_ = self.messages_rate_limited.fetchAdd(1, .release);
|
|
}
|
|
|
|
/// Get a snapshot of current stats (thread-safe)
|
|
pub fn getSnapshot(self: *const NetworkStats) StatsSnapshot {
|
|
return .{
|
|
.messages_sent = self.messages_sent.load(.acquire),
|
|
.messages_received = self.messages_received.load(.acquire),
|
|
.bytes_sent = self.bytes_sent.load(.acquire),
|
|
.bytes_received = self.bytes_received.load(.acquire),
|
|
.send_errors = self.send_errors.load(.acquire),
|
|
.receive_errors = self.receive_errors.load(.acquire),
|
|
.messages_rate_limited = self.messages_rate_limited.load(.acquire),
|
|
.failed_operations = self.failed_operations.load(.acquire),
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Snapshot of network stats at a point in time
|
|
pub const StatsSnapshot = struct {
|
|
messages_sent: u64,
|
|
messages_received: u64,
|
|
bytes_sent: u64,
|
|
bytes_received: u64,
|
|
send_errors: u64,
|
|
receive_errors: u64,
|
|
messages_rate_limited: u64,
|
|
failed_operations: u64,
|
|
};
|
|
|
|
/// Result of broadcast operation
|
|
pub const BroadcastResult = struct {
|
|
sent_count: usize,
|
|
failed_count: usize,
|
|
total_peers: usize,
|
|
};
|
|
|
|
pub fn init(
|
|
allocator: mem.Allocator,
|
|
connections: *std.AutoHashMap(PeerId, *PeerConnection),
|
|
) NetworkManager {
|
|
return .{
|
|
.allocator = allocator,
|
|
.connections = connections,
|
|
.send_queue = .{},
|
|
.receive_buffers = std.AutoHashMap(PeerId, ReceiveBuffer).init(allocator),
|
|
.stats = .{},
|
|
.config = .{},
|
|
.peer_rate_limiter = null,
|
|
.message_callback = null,
|
|
.message_callback_context = null,
|
|
.disconnect_callback = null,
|
|
.disconnect_callback_context = null,
|
|
.failed_disconnect_tracking = std.atomic.Value(u64).init(0),
|
|
.error_callback = null,
|
|
.error_callback_context = null,
|
|
// CRIT-5 FIX: Initialize send queue tracking
|
|
.send_queue_bytes = std.atomic.Value(usize).init(0),
|
|
.send_queue_drops = std.atomic.Value(u64).init(0),
|
|
// CRIT-6 FIX: Initialize receive buffer tracking
|
|
.total_receive_buffer_bytes = std.atomic.Value(usize).init(0),
|
|
.receive_buffer_rejections = std.atomic.Value(u64).init(0),
|
|
};
|
|
}
|
|
|
|
pub fn initWithConfig(
|
|
allocator: mem.Allocator,
|
|
connections: *std.AutoHashMap(PeerId, *PeerConnection),
|
|
config: Config,
|
|
) NetworkManager {
|
|
var manager = init(allocator, connections);
|
|
manager.config = config;
|
|
return manager;
|
|
}
|
|
|
|
pub fn deinit(self: *NetworkManager) void {
|
|
// Clean up send queue
|
|
for (self.send_queue.items) |*msg| {
|
|
msg.deinit(self.allocator);
|
|
}
|
|
self.send_queue.deinit(self.allocator);
|
|
|
|
// Clean up receive buffers
|
|
var iter = self.receive_buffers.iterator();
|
|
while (iter.next()) |entry| {
|
|
entry.value_ptr.deinit(self.allocator);
|
|
}
|
|
self.receive_buffers.deinit();
|
|
}
|
|
|
|
/// CRITICAL FIX: Set the socket mutex to ensure atomic socket access.
|
|
/// This MUST be called with P2P's peer_connections_mutex to prevent
|
|
/// message interleaving between file transfer and regular message sends.
|
|
pub fn setSocketMutex(self: *NetworkManager, mutex: *std.Thread.Mutex) void {
|
|
self.socket_mutex = mutex;
|
|
}
|
|
|
|
/// Helper to acquire the socket mutex (uses socket_mutex if set, otherwise self.mutex)
|
|
fn acquireSocketLock(self: *NetworkManager) void {
|
|
if (self.socket_mutex) |sm| {
|
|
sm.lock();
|
|
} else {
|
|
self.mutex.lock();
|
|
}
|
|
}
|
|
|
|
/// Helper to release the socket mutex
|
|
fn releaseSocketLock(self: *NetworkManager) void {
|
|
if (self.socket_mutex) |sm| {
|
|
sm.unlock();
|
|
} else {
|
|
self.mutex.unlock();
|
|
}
|
|
}
|
|
|
|
/// Send a message to a specific peer
|
|
/// Thread-safe: acquires socket mutex and re-fetches socket after any unlock/relock
|
|
/// CRITICAL FIX: Now uses socket_mutex if set to ensure atomic socket access
|
|
/// across all send paths (file transfer, regular messages, etc.)
|
|
pub fn sendMessage(self: *NetworkManager, peer_id: PeerId, data: []const u8) Error!u64 {
|
|
self.acquireSocketLock();
|
|
|
|
const peer_conn = self.connections.get(peer_id) orelse {
|
|
self.releaseSocketLock();
|
|
return Error.ConnectionNotFound;
|
|
};
|
|
|
|
// If connection is encrypted, use SecureConnection for sending
|
|
if (peer_conn.secure) |secure| {
|
|
defer self.releaseSocketLock();
|
|
|
|
// Prepend 4-byte big-endian inner length header to plaintext.
|
|
// The receive side strips this after decryption (line ~1184).
|
|
// This matches the unencrypted framing format inside the ciphertext.
|
|
var inner_msg = self.allocator.alloc(u8, 4 + data.len) catch {
|
|
return Error.OutOfMemory;
|
|
};
|
|
defer self.allocator.free(inner_msg);
|
|
std.mem.writeInt(u32, inner_msg[0..4], @intCast(data.len), .big);
|
|
@memcpy(inner_msg[4..], data);
|
|
|
|
// SecureConnection.send handles encryption and outer length prefixing
|
|
_ = secure.send(inner_msg) catch |err| {
|
|
self.stats.recordSendError();
|
|
return switch (err) {
|
|
secure_connection.Error.HandshakeTimeout,
|
|
secure_connection.Error.SocketError,
|
|
=> Error.ConnectionTimeout,
|
|
secure_connection.Error.MessageTooLarge => Error.MessageTooLarge,
|
|
secure_connection.Error.EncryptionFailed,
|
|
secure_connection.Error.NotEncrypted,
|
|
=> Error.EncryptionFailed,
|
|
else => Error.SocketSendFailed,
|
|
};
|
|
};
|
|
|
|
self.stats.recordSend(data.len + 16 + 4); // +16 for tag, +4 for length
|
|
|
|
// Generate cryptographically random message ID
|
|
var id: [8]u8 = undefined;
|
|
std.crypto.random.bytes(&id);
|
|
return std.mem.readInt(u64, &id, .little);
|
|
}
|
|
|
|
var socket = peer_conn.socket;
|
|
|
|
// Prepare length-prefixed message (unencrypted path)
|
|
if (data.len > std.math.maxInt(u32)) {
|
|
self.releaseSocketLock();
|
|
return Error.MessageTooLarge;
|
|
}
|
|
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
|
|
std.log.debug("SEND-DEBUG: msg_len={}, data_len={}", .{ msg_len, data.len });
|
|
|
|
// Send header with retry on WouldBlock
|
|
// CRITICAL FIX: Do NOT release lock during retry - releasing allows another thread
|
|
// 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();
|
|
return err;
|
|
};
|
|
header_sent += n;
|
|
total_bytes_sent += n;
|
|
}
|
|
|
|
if (header_sent < 4) {
|
|
// 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;
|
|
retries = 0;
|
|
while (sent < data.len and retries < self.config.max_connection_retries) {
|
|
const n = socket.send(data[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: Header was fully sent, any failure now corrupts stream
|
|
std.log.err("FRAMING-CORRUPT: Data send failed after {} total bytes, removing peer", .{total_bytes_sent + 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 err;
|
|
};
|
|
sent += n;
|
|
total_bytes_sent += n;
|
|
retries = 0; // Reset retries on successful send
|
|
}
|
|
|
|
if (sent < data.len) {
|
|
// CRITICAL FIX: Partial data means stream is corrupted (header already sent)
|
|
std.log.err("FRAMING-CORRUPT: Data timeout after {} total bytes, removing peer", .{total_bytes_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;
|
|
}
|
|
|
|
self.stats.recordSend(4 + data.len);
|
|
|
|
// Generate cryptographically random message ID
|
|
var id: [8]u8 = undefined;
|
|
std.crypto.random.bytes(&id);
|
|
const msg_id = std.mem.readInt(u64, &id, .little);
|
|
|
|
self.releaseSocketLock();
|
|
return msg_id;
|
|
}
|
|
|
|
/// Queue a message for sending (for async/batched sending)
|
|
/// CRIT-5 FIX: Now enforces queue size and memory limits
|
|
pub fn queueMessage(self: *NetworkManager, peer_id: PeerId, data: []const u8, priority: u8) Error!u64 {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// CRIT-5 FIX: First, clean up stale messages to make room
|
|
self.evictStaleQueuedMessages();
|
|
|
|
// CRIT-5 FIX: Check queue message count limit
|
|
if (self.send_queue.items.len >= self.config.max_send_queue_messages) {
|
|
std.log.warn("CRIT-5: Send queue full ({} messages), rejecting new message", .{
|
|
self.send_queue.items.len,
|
|
});
|
|
_ = self.send_queue_drops.fetchAdd(1, .monotonic);
|
|
return Error.QueueFull;
|
|
}
|
|
|
|
// CRIT-5 FIX: Check queue byte limit
|
|
const current_bytes = self.send_queue_bytes.load(.monotonic);
|
|
if (current_bytes + data.len > self.config.max_send_queue_bytes) {
|
|
std.log.warn("CRIT-5: Send queue memory limit reached ({} + {} > {} bytes), rejecting", .{
|
|
current_bytes,
|
|
data.len,
|
|
self.config.max_send_queue_bytes,
|
|
});
|
|
_ = self.send_queue_drops.fetchAdd(1, .monotonic);
|
|
return Error.QueueFull;
|
|
}
|
|
|
|
const data_copy = self.allocator.dupe(u8, data) catch return Error.OutOfMemory;
|
|
|
|
// Generate cryptographically random message ID
|
|
var id: [8]u8 = undefined;
|
|
std.crypto.random.bytes(&id);
|
|
const msg_id = std.mem.readInt(u64, &id, .little);
|
|
|
|
self.send_queue.append(self.allocator, .{
|
|
.peer_id = peer_id,
|
|
.data = data_copy,
|
|
.message_id = msg_id,
|
|
.queued_at = std.time.milliTimestamp(),
|
|
.priority = priority,
|
|
.retries = 0,
|
|
}) catch {
|
|
self.allocator.free(data_copy);
|
|
return Error.OutOfMemory;
|
|
};
|
|
|
|
// CRIT-5 FIX: Update queue byte counter
|
|
_ = self.send_queue_bytes.fetchAdd(data.len, .monotonic);
|
|
|
|
return msg_id;
|
|
}
|
|
|
|
/// CRIT-5 FIX: Evict messages that have been in the queue too long
|
|
/// Must be called while holding mutex
|
|
fn evictStaleQueuedMessages(self: *NetworkManager) void {
|
|
const now = std.time.milliTimestamp();
|
|
const max_age_ms = self.config.max_send_queue_age_seconds * 1000;
|
|
|
|
var i: usize = 0;
|
|
while (i < self.send_queue.items.len) {
|
|
const msg = &self.send_queue.items[i];
|
|
if (now - msg.queued_at > max_age_ms) {
|
|
// Message is stale, evict it
|
|
std.log.debug("CRIT-5: Evicting stale queued message (age: {}ms)", .{now - msg.queued_at});
|
|
const msg_size = msg.data.len;
|
|
msg.deinit(self.allocator);
|
|
_ = self.send_queue.orderedRemove(i);
|
|
// Update byte counter
|
|
_ = self.send_queue_bytes.fetchSub(msg_size, .monotonic);
|
|
_ = self.send_queue_drops.fetchAdd(1, .monotonic);
|
|
// Don't increment i since we removed an element
|
|
} else {
|
|
i += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Broadcast message to all connected peers
|
|
/// FIX: Copy peer IDs under lock to prevent iterator invalidation during broadcast
|
|
pub fn broadcastMessage(self: *NetworkManager, data: []const u8) Error!BroadcastResult {
|
|
var sent_count: usize = 0;
|
|
var failed_count: usize = 0;
|
|
|
|
// Copy peer IDs under lock to prevent race condition
|
|
var peer_ids: std.ArrayList(PeerId) = .{};
|
|
defer peer_ids.deinit(self.allocator);
|
|
|
|
{
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
var iter = self.connections.keyIterator();
|
|
while (iter.next()) |key| {
|
|
peer_ids.append(self.allocator, key.*) catch {
|
|
std.log.err("Failed to copy peer ID for broadcast - skipping", .{});
|
|
continue;
|
|
};
|
|
}
|
|
}
|
|
|
|
const total_peers = peer_ids.items.len;
|
|
|
|
// Send messages WITHOUT holding lock (prevents blocking other operations)
|
|
for (peer_ids.items) |peer_id| {
|
|
_ = self.sendMessage(peer_id, data) catch |err| {
|
|
std.log.warn("Failed to broadcast message to peer: {}", .{err});
|
|
failed_count += 1;
|
|
// ERR-M1 FIX: Aggregate failures in metrics
|
|
_ = self.stats.broadcast_failures.fetchAdd(1, .monotonic);
|
|
continue;
|
|
};
|
|
sent_count += 1;
|
|
}
|
|
|
|
if (failed_count > 0) {
|
|
std.log.warn("Broadcast completed with {} failures out of {} peers (total failures: {})", .{
|
|
failed_count,
|
|
total_peers,
|
|
self.stats.broadcast_failures.load(.monotonic),
|
|
});
|
|
}
|
|
|
|
return BroadcastResult{
|
|
.sent_count = sent_count,
|
|
.failed_count = failed_count,
|
|
.total_peers = total_peers,
|
|
};
|
|
}
|
|
|
|
/// Process send queue
|
|
/// CRIT-5 FIX: Now properly tracks byte usage when removing messages
|
|
pub fn processSendQueue(self: *NetworkManager) void {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// CRIT-5 FIX: Also evict stale messages during processing
|
|
self.evictStaleQueuedMessages();
|
|
|
|
var i: usize = 0;
|
|
while (i < self.send_queue.items.len) {
|
|
var msg = &self.send_queue.items[i];
|
|
const msg_size = msg.data.len;
|
|
|
|
_ = self.sendMessage(msg.peer_id, msg.data) catch |err| {
|
|
msg.retries += 1;
|
|
if (msg.retries >= self.config.max_queue_retries) {
|
|
// ERR-M4 FIX: Track and report retry exhaustion
|
|
_ = self.stats.queue_retry_exhausted.fetchAdd(1, .monotonic);
|
|
std.log.warn("ERR-M4: Send queue message dropped after {} retries (error: {}, total exhaustions: {})", .{
|
|
msg.retries,
|
|
err,
|
|
self.stats.queue_retry_exhausted.load(.monotonic),
|
|
});
|
|
msg.deinit(self.allocator);
|
|
_ = self.send_queue.orderedRemove(i);
|
|
// CRIT-5 FIX: Update byte counter
|
|
_ = self.send_queue_bytes.fetchSub(msg_size, .monotonic);
|
|
continue;
|
|
}
|
|
i += 1;
|
|
continue;
|
|
};
|
|
|
|
// Success - remove from queue
|
|
msg.deinit(self.allocator);
|
|
_ = self.send_queue.orderedRemove(i);
|
|
// CRIT-5 FIX: Update byte counter
|
|
_ = self.send_queue_bytes.fetchSub(msg_size, .monotonic);
|
|
}
|
|
}
|
|
|
|
/// Process incoming data from all connections
|
|
pub fn processReceive(self: *NetworkManager) Error!void {
|
|
// Structure to hold messages to deliver after releasing mutex
|
|
const PendingMessage = struct {
|
|
peer_id: PeerId,
|
|
data: []u8,
|
|
};
|
|
|
|
var messages_to_deliver = std.ArrayListUnmanaged(PendingMessage){};
|
|
defer {
|
|
// HIGH-9 FIX: Data ownership documentation
|
|
// The msg.data is "borrowed" by callbacks - it remains valid only during
|
|
// callback execution. This defer runs AFTER processIncoming() returns,
|
|
// which is AFTER all callbacks complete. The execution order is:
|
|
// 1. Collect messages into messages_to_deliver (lines 888-891)
|
|
// 2. Release mutex (line 913)
|
|
// 3. Invoke callbacks with borrowed data (lines 928-930)
|
|
// 4. This defer runs - frees all msg.data
|
|
// Callbacks MUST copy data if they need it beyond their return.
|
|
for (messages_to_deliver.items) |msg| {
|
|
self.allocator.free(msg.data);
|
|
}
|
|
messages_to_deliver.deinit(self.allocator);
|
|
}
|
|
|
|
var disconnected: std.ArrayListUnmanaged(PeerId) = .{};
|
|
defer disconnected.deinit(self.allocator);
|
|
|
|
// CRITICAL: Hold mutex only while extracting messages, NOT while calling callbacks
|
|
{
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// Allocate on heap instead of stack to avoid overflow (using configurable buffer size)
|
|
const buffer = self.allocator.alloc(u8, self.config.receive_buffer_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(buffer);
|
|
|
|
var iter = self.connections.iterator();
|
|
while (iter.next()) |entry| {
|
|
const peer_id = entry.key_ptr.*;
|
|
const peer_conn = entry.value_ptr.*;
|
|
const socket = peer_conn.socket;
|
|
|
|
// THROUGHPUT FIX: Loop to drain all available data from socket
|
|
// Previously only did one receive() per socket per call, limiting throughput
|
|
var should_continue_peer = false;
|
|
recv_loop: while (true) {
|
|
// Try to receive data
|
|
const bytes_read = socket.receive(buffer) catch |err| {
|
|
if (err == Error.ConnectionTimeout) break :recv_loop; // WouldBlock - no more data available
|
|
if (err == Error.ConnectionClosed) {
|
|
disconnected.append(self.allocator, peer_id) catch |append_err| {
|
|
std.log.err("Failed to track peer disconnection: {}", .{append_err});
|
|
_ = self.stats.failed_operations.fetchAdd(1, .monotonic);
|
|
};
|
|
should_continue_peer = true;
|
|
break :recv_loop;
|
|
}
|
|
self.stats.recordReceiveError();
|
|
break :recv_loop;
|
|
};
|
|
|
|
if (bytes_read == 0) {
|
|
disconnected.append(self.allocator, peer_id) catch |append_err| {
|
|
std.log.err("Failed to track peer disconnection (EOF): {}", .{append_err});
|
|
_ = self.stats.failed_operations.fetchAdd(1, .monotonic);
|
|
};
|
|
should_continue_peer = true;
|
|
break :recv_loop;
|
|
}
|
|
|
|
// Validate message size
|
|
if (bytes_read > self.config.max_message_size) {
|
|
self.stats.recordReceiveError();
|
|
break :recv_loop;
|
|
}
|
|
|
|
// Record bytes received atomically
|
|
_ = self.stats.bytes_received.fetchAdd(bytes_read, .monotonic);
|
|
|
|
// CRIT-6 FIX: Check total receive buffer memory limit before accepting more data
|
|
const current_total_bytes = self.total_receive_buffer_bytes.load(.monotonic);
|
|
if (current_total_bytes + bytes_read > self.config.max_total_receive_buffer_bytes) {
|
|
std.log.warn("CRIT-6: Total receive buffer limit reached ({} + {} > {}), rejecting data from peer", .{
|
|
current_total_bytes,
|
|
bytes_read,
|
|
self.config.max_total_receive_buffer_bytes,
|
|
});
|
|
_ = self.receive_buffer_rejections.fetchAdd(1, .monotonic);
|
|
self.stats.recordReceiveError();
|
|
// Mark peer for disconnection - they're contributing to memory exhaustion
|
|
disconnected.append(self.allocator, peer_id) catch |err| {
|
|
std.log.err("SECURITY: Failed to track peer for disconnect (possible OOM during DoS): {}", .{err});
|
|
};
|
|
should_continue_peer = true;
|
|
break :recv_loop;
|
|
}
|
|
|
|
// Get or create receive buffer (protected by mutex)
|
|
var recv_buf = self.receive_buffers.getPtr(peer_id);
|
|
if (recv_buf == null) {
|
|
// CRIT-6 FIX: Create buffer with configured limits
|
|
self.receive_buffers.put(peer_id, ReceiveBuffer.initWithLimits(
|
|
self.allocator,
|
|
self.config.max_message_size,
|
|
self.config.max_receive_buffer_per_peer,
|
|
)) catch |err| {
|
|
std.log.err("Failed to create receive buffer for peer: {}", .{err});
|
|
_ = self.stats.failed_operations.fetchAdd(1, .monotonic);
|
|
break :recv_loop;
|
|
};
|
|
recv_buf = self.receive_buffers.getPtr(peer_id);
|
|
}
|
|
|
|
// CRIT-6 FIX: Get buffer size before append for tracking
|
|
const old_buffer_size = recv_buf.?.currentSize();
|
|
|
|
// Append received data
|
|
recv_buf.?.append(buffer[0..bytes_read]) catch |err| {
|
|
switch (err) {
|
|
ReceiveBufferError.MessageTooLarge => {
|
|
std.log.err("Peer receive buffer limit exceeded, disconnecting", .{});
|
|
_ = self.receive_buffer_rejections.fetchAdd(1, .monotonic);
|
|
disconnected.append(self.allocator, peer_id) catch |append_err| {
|
|
std.log.err("SECURITY: Failed to track peer for disconnect: {}", .{append_err});
|
|
};
|
|
},
|
|
ReceiveBufferError.OutOfMemory => {
|
|
std.log.err("Failed to append to receive buffer: OOM", .{});
|
|
_ = self.stats.failed_operations.fetchAdd(1, .monotonic);
|
|
},
|
|
}
|
|
break :recv_loop;
|
|
};
|
|
|
|
// CRIT-6 FIX: Update total receive buffer memory tracking
|
|
const new_buffer_size = recv_buf.?.currentSize();
|
|
const size_delta = new_buffer_size - old_buffer_size;
|
|
_ = self.total_receive_buffer_bytes.fetchAdd(size_delta, .monotonic);
|
|
|
|
// Continue loop to drain more data if available
|
|
}
|
|
if (should_continue_peer) continue;
|
|
|
|
// Get receive buffer for message extraction (it was created in the loop if needed)
|
|
const recv_buf = self.receive_buffers.getPtr(peer_id) orelse continue;
|
|
|
|
// Extract complete messages to local list
|
|
// SECURITY: hasCompleteMessage now validates message size
|
|
while (true) {
|
|
const has_message = recv_buf.hasCompleteMessage() catch |err| {
|
|
switch (err) {
|
|
ReceiveBufferError.MessageTooLarge => {
|
|
// Peer sent oversized message - mark for disconnection
|
|
core.log.err("SECURITY: Disconnecting peer due to oversized message", .{});
|
|
disconnected.append(self.allocator, peer_id) catch |append_err| {
|
|
// CRITICAL: Failed to track disconnection - log and emit error event
|
|
std.log.err("CRITICAL: Failed to track peer disconnection (peer: {}, error: {})", .{ peer_id, append_err });
|
|
const count = self.failed_disconnect_tracking.fetchAdd(1, .monotonic) + 1;
|
|
|
|
// Emit error event for monitoring
|
|
if (self.error_callback) |callback| {
|
|
callback(.{
|
|
.error_type = .disconnect_tracking_failed,
|
|
.peer_id = peer_id,
|
|
.count = count,
|
|
.timestamp = std.time.milliTimestamp(),
|
|
}, self.error_callback_context);
|
|
}
|
|
|
|
// Still try to clean up the receive buffer immediately to prevent zombie entry
|
|
if (self.receive_buffers.fetchRemove(peer_id)) |kv| {
|
|
var buf = kv.value;
|
|
buf.deinit(self.allocator);
|
|
}
|
|
};
|
|
},
|
|
ReceiveBufferError.OutOfMemory => {
|
|
std.log.err("Out of memory processing receive buffer", .{});
|
|
},
|
|
}
|
|
break;
|
|
};
|
|
if (!has_message) break;
|
|
|
|
// CRIT-6 FIX: Track buffer size before extraction to update memory counter
|
|
const size_before_extract = recv_buf.currentSize();
|
|
const msg_data = recv_buf.extractMessage(self.allocator) catch |err| {
|
|
std.log.err("Failed to extract message from buffer: {}", .{err});
|
|
_ = self.stats.failed_operations.fetchAdd(1, .monotonic);
|
|
continue;
|
|
};
|
|
// CRIT-6 FIX: Decrement total receive buffer bytes after message extraction
|
|
const size_after_extract = recv_buf.currentSize();
|
|
const extracted_bytes = size_before_extract - size_after_extract;
|
|
_ = self.total_receive_buffer_bytes.fetchSub(extracted_bytes, .monotonic);
|
|
|
|
// Decrypt message data if connection is encrypted
|
|
const final_msg_data = blk: {
|
|
if (peer_conn.secure) |secure| {
|
|
// Decrypt the message data
|
|
const decrypt_buf = self.allocator.alloc(u8, msg_data.len) catch {
|
|
self.allocator.free(msg_data);
|
|
break;
|
|
};
|
|
|
|
const plaintext = secure.transport.?.receive(msg_data, decrypt_buf) catch |err| {
|
|
std.log.err("Decryption failed for peer {}: {}", .{ peer_id, err });
|
|
self.allocator.free(msg_data);
|
|
self.allocator.free(decrypt_buf);
|
|
self.stats.recordReceiveError();
|
|
continue;
|
|
};
|
|
|
|
// Free the encrypted data, keep decrypted
|
|
self.allocator.free(msg_data);
|
|
|
|
// FIX: The sender includes a 4-byte length header in the plaintext (for
|
|
// non-encrypted framing compatibility). Strip it here since ReceiveBuffer
|
|
// already handles framing for the encrypted packet.
|
|
if (plaintext.len < 4) {
|
|
self.allocator.free(decrypt_buf);
|
|
continue;
|
|
}
|
|
const inner_len = std.mem.readInt(u32, plaintext[0..4], .big);
|
|
if (inner_len > plaintext.len - 4) {
|
|
std.log.warn("Decrypted message inner length mismatch: {} > {}", .{ inner_len, plaintext.len - 4 });
|
|
self.allocator.free(decrypt_buf);
|
|
continue;
|
|
}
|
|
const payload = plaintext[4 .. 4 + inner_len];
|
|
|
|
// Create properly sized slice
|
|
const decrypted = self.allocator.alloc(u8, payload.len) catch {
|
|
self.allocator.free(decrypt_buf);
|
|
continue;
|
|
};
|
|
@memcpy(decrypted, payload);
|
|
self.allocator.free(decrypt_buf);
|
|
|
|
break :blk decrypted;
|
|
} else {
|
|
break :blk msg_data;
|
|
}
|
|
};
|
|
|
|
// Check rate limiter before processing message
|
|
if (self.peer_rate_limiter) |limiter| {
|
|
if (!limiter.tryConsume(peer_id.bytes)) {
|
|
// Rate limited - drop message and log
|
|
self.stats.recordRateLimited();
|
|
self.allocator.free(final_msg_data);
|
|
std.log.warn("Rate limited message from peer {} (total rate limited: {})", .{
|
|
peer_id,
|
|
self.stats.messages_rate_limited.load(.acquire),
|
|
});
|
|
|
|
// Send rate limit error response (best effort, ignore errors)
|
|
self.sendRateLimitError(peer_id) catch |err| {
|
|
std.log.debug("Failed to send rate limit error to peer {}: {}", .{ peer_id, err });
|
|
};
|
|
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// Record message received atomically
|
|
_ = self.stats.messages_received.fetchAdd(1, .monotonic);
|
|
|
|
// Add to pending delivery list instead of calling callback immediately
|
|
messages_to_deliver.append(self.allocator, .{
|
|
.peer_id = peer_id,
|
|
.data = final_msg_data,
|
|
}) catch {
|
|
// If we can't queue it, free the data
|
|
self.allocator.free(final_msg_data);
|
|
continue;
|
|
};
|
|
}
|
|
}
|
|
|
|
// Handle disconnections while still holding mutex
|
|
for (disconnected.items) |peer_id| {
|
|
if (self.receive_buffers.fetchRemove(peer_id)) |kv| {
|
|
var buf = kv.value;
|
|
// CRIT-6 FIX: Update total receive buffer memory tracking
|
|
const buf_size = buf.currentSize();
|
|
_ = self.total_receive_buffer_bytes.fetchSub(buf_size, .monotonic);
|
|
buf.deinit(self.allocator);
|
|
}
|
|
}
|
|
|
|
// CRIT-6 FIX: Clean up stale receive buffers (no activity for too long)
|
|
self.cleanupStaleReceiveBuffers();
|
|
}
|
|
// Mutex is now released
|
|
|
|
// CRITICAL: Call message callbacks WITHOUT holding main mutex to prevent deadlock
|
|
// This allows callbacks to safely call sendMessage() or other NetworkManager methods
|
|
// THR-2 FIX: Read callback and context atomically, then call without holding mutex
|
|
const msg_cb_info: struct {
|
|
cb: ?*const fn (PeerId, []const u8, ?*anyopaque) void,
|
|
ctx: ?*anyopaque,
|
|
} = blk: {
|
|
self.callback_mutex.lock();
|
|
defer self.callback_mutex.unlock();
|
|
break :blk .{ .cb = self.message_callback, .ctx = self.message_callback_context };
|
|
};
|
|
|
|
if (msg_cb_info.cb) |callback| {
|
|
for (messages_to_deliver.items) |msg| {
|
|
callback(msg.peer_id, msg.data, msg_cb_info.ctx);
|
|
}
|
|
}
|
|
|
|
// THR-2 FIX: Read disconnect callback atomically too
|
|
const disc_cb_info: struct {
|
|
cb: ?*const fn (PeerId, ?*anyopaque) void,
|
|
ctx: ?*anyopaque,
|
|
} = blk: {
|
|
self.callback_mutex.lock();
|
|
defer self.callback_mutex.unlock();
|
|
break :blk .{ .cb = self.disconnect_callback, .ctx = self.disconnect_callback_context };
|
|
};
|
|
|
|
if (disc_cb_info.cb) |callback| {
|
|
for (disconnected.items) |peer_id| {
|
|
callback(peer_id, disc_cb_info.ctx);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// THR-2 FIX: Uses callback_mutex to atomically set both callback and context
|
|
pub fn setMessageCallback(
|
|
self: *NetworkManager,
|
|
callback: *const fn (PeerId, []const u8, ?*anyopaque) void,
|
|
context: ?*anyopaque,
|
|
) void {
|
|
self.callback_mutex.lock();
|
|
defer self.callback_mutex.unlock();
|
|
self.message_callback = callback;
|
|
self.message_callback_context = context;
|
|
}
|
|
|
|
/// THR-2 FIX: Uses callback_mutex to atomically set both callback and context
|
|
pub fn setDisconnectCallback(
|
|
self: *NetworkManager,
|
|
callback: *const fn (PeerId, ?*anyopaque) void,
|
|
context: ?*anyopaque,
|
|
) void {
|
|
self.callback_mutex.lock();
|
|
defer self.callback_mutex.unlock();
|
|
self.disconnect_callback = callback;
|
|
self.disconnect_callback_context = context;
|
|
}
|
|
|
|
pub fn setPeerRateLimiter(self: *NetworkManager, rate_limiter: *core.rate_limiter.PeerRateLimiter) void {
|
|
self.peer_rate_limiter = rate_limiter;
|
|
}
|
|
|
|
/// THR-2 FIX: Uses callback_mutex to atomically set both callback and context
|
|
pub fn setErrorCallback(
|
|
self: *NetworkManager,
|
|
callback: *const fn (NetworkError, ?*anyopaque) void,
|
|
context: ?*anyopaque,
|
|
) void {
|
|
self.callback_mutex.lock();
|
|
defer self.callback_mutex.unlock();
|
|
self.error_callback = callback;
|
|
self.error_callback_context = context;
|
|
}
|
|
|
|
/// Get count of failed disconnect tracking attempts
|
|
pub fn getFailedDisconnectTracking(self: *const NetworkManager) u64 {
|
|
return self.failed_disconnect_tracking.load(.acquire);
|
|
}
|
|
|
|
/// Send a rate limit error message to a peer (best effort)
|
|
/// ERR-H4 FIX: Now logs failures instead of silently swallowing them
|
|
/// CRITICAL FIX: Now uses socket_mutex to prevent message interleaving
|
|
fn sendRateLimitError(self: *NetworkManager, peer_id: PeerId) Error!void {
|
|
// Simple error message: [error_code: u8 = 0x42 (err)] [rate_limited: u16 = 0x000A]
|
|
const error_msg = [_]u8{ 0x42, 0x00, 0x0A };
|
|
|
|
// CRITICAL FIX: Acquire socket lock to prevent interleaving with other sends
|
|
self.acquireSocketLock();
|
|
defer self.releaseSocketLock();
|
|
|
|
// Send without retries (best effort only)
|
|
const peer_conn = self.connections.get(peer_id) orelse return Error.ConnectionNotFound;
|
|
const socket = peer_conn.socket;
|
|
|
|
// Prepare length-prefixed message
|
|
const msg_len: u32 = @intCast(error_msg.len);
|
|
var header: [4]u8 = undefined;
|
|
std.mem.writeInt(u32, &header, msg_len, .big);
|
|
|
|
// ERR-H4 FIX: Log send failures instead of silently swallowing
|
|
_ = socket.send(&header) catch |err| {
|
|
std.log.debug("ERR-H4: Failed to send rate limit header to peer: {}", .{err});
|
|
return;
|
|
};
|
|
|
|
_ = socket.send(&error_msg) catch |err| {
|
|
std.log.debug("ERR-H4: Failed to send rate limit message to peer: {}", .{err});
|
|
return;
|
|
};
|
|
}
|
|
|
|
/// CRIT-6 FIX: Clean up receive buffers that have been inactive for too long
|
|
/// This prevents memory exhaustion from peers sending partial messages and going silent
|
|
/// Must be called while holding mutex
|
|
fn cleanupStaleReceiveBuffers(self: *NetworkManager) void {
|
|
const timeout_seconds = self.config.receive_buffer_timeout_seconds;
|
|
|
|
// Collect keys to remove (can't modify while iterating)
|
|
var keys_to_remove: [64]PeerId = undefined;
|
|
var remove_count: usize = 0;
|
|
|
|
var iter = self.receive_buffers.iterator();
|
|
while (iter.next()) |entry| {
|
|
const buf = entry.value_ptr;
|
|
// Only consider buffers with incomplete messages (have data but no complete message)
|
|
if (buf.currentSize() > 0 and buf.hasTimedOut(timeout_seconds)) {
|
|
if (remove_count < keys_to_remove.len) {
|
|
keys_to_remove[remove_count] = entry.key_ptr.*;
|
|
remove_count += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Remove stale buffers
|
|
for (keys_to_remove[0..remove_count]) |peer_id| {
|
|
if (self.receive_buffers.fetchRemove(peer_id)) |kv| {
|
|
var buf = kv.value;
|
|
const buf_size = buf.currentSize();
|
|
std.log.debug("CRIT-6: Evicting stale receive buffer for peer (size: {}, age: {}s)", .{
|
|
buf_size,
|
|
std.time.timestamp() - buf.last_activity,
|
|
});
|
|
_ = self.total_receive_buffer_bytes.fetchSub(buf_size, .monotonic);
|
|
buf.deinit(self.allocator);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Get current queue and buffer statistics for monitoring
|
|
/// Thread-safe: acquires mutex for non-atomic collection access
|
|
pub fn getResourceStats(self: *NetworkManager) ResourceStats {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
return .{
|
|
.send_queue_messages = self.send_queue.items.len,
|
|
.send_queue_bytes = self.send_queue_bytes.load(.acquire),
|
|
.send_queue_drops = self.send_queue_drops.load(.acquire),
|
|
.receive_buffer_count = self.receive_buffers.count(),
|
|
.receive_buffer_bytes = self.total_receive_buffer_bytes.load(.acquire),
|
|
.receive_buffer_rejections = self.receive_buffer_rejections.load(.acquire),
|
|
};
|
|
}
|
|
|
|
/// Resource usage statistics
|
|
pub const ResourceStats = struct {
|
|
send_queue_messages: usize,
|
|
send_queue_bytes: usize,
|
|
send_queue_drops: u64,
|
|
receive_buffer_count: usize,
|
|
receive_buffer_bytes: usize,
|
|
receive_buffer_rejections: u64,
|
|
};
|
|
|
|
pub fn getStats(self: *const NetworkManager) NetworkStats {
|
|
return self.stats;
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// Tests
|
|
// ============================================================================
|
|
|
|
test "PendingSend: init and deinit" {
|
|
const allocator = std.testing.allocator;
|
|
const segments = [_][]const u8{ "hello", " world" };
|
|
var pending = try PendingSend.init(allocator, &segments);
|
|
defer pending.deinit();
|
|
|
|
try std.testing.expectEqual(@as(usize, 11), pending.data.len);
|
|
try std.testing.expectEqualStrings("hello world", pending.data);
|
|
}
|
|
|
|
test "PendingSend: remaining and isComplete" {
|
|
const allocator = std.testing.allocator;
|
|
const segments = [_][]const u8{"test"};
|
|
var pending = try PendingSend.init(allocator, &segments);
|
|
defer pending.deinit();
|
|
|
|
try std.testing.expect(!pending.isComplete());
|
|
try std.testing.expectEqual(@as(usize, 4), pending.remaining().len);
|
|
|
|
pending.offset = 2;
|
|
try std.testing.expect(!pending.isComplete());
|
|
try std.testing.expectEqual(@as(usize, 2), pending.remaining().len);
|
|
|
|
pending.offset = 4;
|
|
try std.testing.expect(pending.isComplete());
|
|
try std.testing.expectEqual(@as(usize, 0), pending.remaining().len);
|
|
}
|
|
|
|
test "ReceiveBuffer: init with defaults" {
|
|
const allocator = std.testing.allocator;
|
|
var buf = ReceiveBuffer.init(allocator);
|
|
defer buf.deinit(allocator);
|
|
|
|
try std.testing.expectEqual(@as(usize, 0), buf.currentSize());
|
|
}
|
|
|
|
test "ReceiveBuffer: append data" {
|
|
const allocator = std.testing.allocator;
|
|
var buf = ReceiveBuffer.initWithMaxSize(allocator, 1024);
|
|
defer buf.deinit(allocator);
|
|
|
|
try buf.append("hello");
|
|
try std.testing.expectEqual(@as(usize, 5), buf.currentSize());
|
|
|
|
try buf.append(" world");
|
|
try std.testing.expectEqual(@as(usize, 11), buf.currentSize());
|
|
}
|
|
|
|
test "ReceiveBuffer: reset clears buffer" {
|
|
const allocator = std.testing.allocator;
|
|
var buf = ReceiveBuffer.initWithMaxSize(allocator, 1024);
|
|
defer buf.deinit(allocator);
|
|
|
|
try buf.append("test data");
|
|
try std.testing.expectEqual(@as(usize, 9), buf.currentSize());
|
|
|
|
buf.reset();
|
|
try std.testing.expectEqual(@as(usize, 0), buf.currentSize());
|
|
}
|
|
|
|
test "Config: default values" {
|
|
const config = Config{};
|
|
try std.testing.expectEqual(@as(u32, 1000), config.max_connection_retries);
|
|
try std.testing.expectEqual(@as(usize, 512 * 1024), config.receive_buffer_size);
|
|
try std.testing.expectEqual(@as(usize, 2 * 1024 * 1024), config.max_message_size);
|
|
}
|
|
|
|
test "Config: custom values" {
|
|
const config = Config{
|
|
.max_connection_retries = 500,
|
|
.receive_buffer_size = 256 * 1024,
|
|
.max_message_size = 1 * 1024 * 1024,
|
|
};
|
|
try std.testing.expectEqual(@as(u32, 500), config.max_connection_retries);
|
|
try std.testing.expectEqual(@as(usize, 256 * 1024), config.receive_buffer_size);
|
|
}
|
|
|
|
test "NetworkStats: recordSend" {
|
|
var stats = NetworkManager.NetworkStats{};
|
|
stats.recordSend(100);
|
|
try std.testing.expectEqual(@as(u64, 100), stats.bytes_sent.load(.acquire));
|
|
try std.testing.expectEqual(@as(u64, 1), stats.messages_sent.load(.acquire));
|
|
}
|
|
|
|
test "NetworkStats: recordReceive" {
|
|
var stats = NetworkManager.NetworkStats{};
|
|
stats.recordReceive(200);
|
|
try std.testing.expectEqual(@as(u64, 200), stats.bytes_received.load(.acquire));
|
|
try std.testing.expectEqual(@as(u64, 1), stats.messages_received.load(.acquire));
|
|
}
|
|
|
|
test "NetworkStats: error counters" {
|
|
var stats = NetworkManager.NetworkStats{};
|
|
stats.recordSendError();
|
|
stats.recordReceiveError();
|
|
stats.recordRateLimited();
|
|
|
|
try std.testing.expectEqual(@as(u64, 1), stats.send_errors.load(.acquire));
|
|
try std.testing.expectEqual(@as(u64, 1), stats.receive_errors.load(.acquire));
|
|
try std.testing.expectEqual(@as(u64, 1), stats.messages_rate_limited.load(.acquire));
|
|
}
|
|
|
|
test "ResourceStats: default values" {
|
|
const stats = NetworkManager.ResourceStats{
|
|
.send_queue_messages = 0,
|
|
.send_queue_bytes = 0,
|
|
.send_queue_drops = 0,
|
|
.receive_buffer_count = 0,
|
|
.receive_buffer_bytes = 0,
|
|
.receive_buffer_rejections = 0,
|
|
};
|
|
try std.testing.expectEqual(@as(usize, 0), stats.send_queue_messages);
|
|
try std.testing.expectEqual(@as(u64, 0), stats.send_queue_drops);
|
|
}
|
|
|
|
test "QueuedMessage: deinit frees memory" {
|
|
const allocator = std.testing.allocator;
|
|
const data = try allocator.dupe(u8, "test message");
|
|
var msg = QueuedMessage{
|
|
.peer_id = PeerId.init(),
|
|
.data = data,
|
|
.message_id = 1,
|
|
.queued_at = std.time.timestamp(),
|
|
.priority = 0,
|
|
.retries = 0,
|
|
};
|
|
msg.deinit(allocator);
|
|
// If no leak, test passes
|
|
}
|
|
|
|
test "ReceiveBuffer: initWithLimits custom values" {
|
|
const buf = ReceiveBuffer.initWithLimits(std.testing.allocator, 1024, 2048);
|
|
try std.testing.expectEqual(@as(usize, 1024), buf.max_message_size);
|
|
try std.testing.expectEqual(@as(usize, 2048), buf.max_buffer_size);
|
|
try std.testing.expect(!buf.has_protocol_error);
|
|
}
|
|
|
|
test "ReceiveBuffer: initWithMaxSize" {
|
|
const buf = ReceiveBuffer.initWithMaxSize(std.testing.allocator, 512);
|
|
try std.testing.expectEqual(@as(usize, 512), buf.max_message_size);
|
|
try std.testing.expectEqual(ReceiveBuffer.DEFAULT_MAX_BUFFER_SIZE, buf.max_buffer_size);
|
|
}
|
|
|
|
test "ReceiveBuffer: currentSize" {
|
|
var buf = ReceiveBuffer.init(std.testing.allocator);
|
|
defer buf.deinit(std.testing.allocator);
|
|
|
|
try std.testing.expectEqual(@as(usize, 0), buf.currentSize());
|
|
try buf.append("hello");
|
|
try std.testing.expectEqual(@as(usize, 5), buf.currentSize());
|
|
}
|
|
|
|
test "ReceiveBuffer: hasTimedOut" {
|
|
var buf = ReceiveBuffer.init(std.testing.allocator);
|
|
// Use a very short timeout to test immediately
|
|
try std.testing.expect(!buf.hasTimedOut(1000));
|
|
// Force last_activity to the past
|
|
buf.last_activity = std.time.timestamp() - 100;
|
|
try std.testing.expect(buf.hasTimedOut(50));
|
|
}
|
|
|
|
test "ReceiveBuffer: append exceeds buffer size" {
|
|
var buf = ReceiveBuffer.initWithLimits(std.testing.allocator, 1024, 10);
|
|
defer buf.deinit(std.testing.allocator);
|
|
|
|
const result = buf.append("this is too long for buffer");
|
|
try std.testing.expectError(ReceiveBufferError.MessageTooLarge, result);
|
|
try std.testing.expect(buf.has_protocol_error);
|
|
}
|
|
|
|
test "ReceiveBuffer: constants" {
|
|
try std.testing.expectEqual(@as(usize, 2 * 1024 * 1024), ReceiveBuffer.DEFAULT_MAX_MESSAGE_SIZE);
|
|
try std.testing.expectEqual(@as(usize, 4 * 1024 * 1024), ReceiveBuffer.DEFAULT_MAX_BUFFER_SIZE);
|
|
}
|
|
|
|
test "ReceiveBufferError enum" {
|
|
const err1: ReceiveBufferError = ReceiveBufferError.MessageTooLarge;
|
|
const err2: ReceiveBufferError = ReceiveBufferError.OutOfMemory;
|
|
try std.testing.expect(err1 != err2);
|
|
}
|