2499 lines
98 KiB
Zig
2499 lines
98 KiB
Zig
//! Message handler framework
|
|
const std = @import("std");
|
|
const protocol = @import("protocol.zig");
|
|
const message = @import("message.zig");
|
|
const serializer = @import("serializer.zig");
|
|
const replay_protection = @import("replay_protection.zig");
|
|
const handler_impl = @import("handler_impl.zig");
|
|
|
|
/// Callback for handling data responses
|
|
/// Used to avoid cross-module dependency between protocol and files modules
|
|
/// The P2P layer provides this callback which has access to the file manager
|
|
pub const DataResponseHandler = struct {
|
|
handler_fn: *const fn (
|
|
context: ?*anyopaque,
|
|
request_tracker: *RequestTracker,
|
|
data_resp: message.DataResponse,
|
|
metrics: *HandlerMetrics,
|
|
) anyerror!void,
|
|
context: ?*anyopaque,
|
|
|
|
pub fn handle(
|
|
self: DataResponseHandler,
|
|
request_tracker: *RequestTracker,
|
|
data_resp: message.DataResponse,
|
|
metrics: *HandlerMetrics,
|
|
) !void {
|
|
return self.handler_fn(self.context, request_tracker, data_resp, metrics);
|
|
}
|
|
};
|
|
|
|
/// Node ID registration callback - maps remote peer's identity key (node ID) to connection peer ID
|
|
/// Called during key exchange when a peer's identity is verified
|
|
pub const NodeIdRegistrationCallback = struct {
|
|
/// Callback function to register the mapping
|
|
/// @param node_id: The remote peer's identity public key (= their DHT node ID)
|
|
/// @param peer_id: The connection peer ID for this peer
|
|
/// @param context: User context passed during setup
|
|
register_fn: *const fn (node_id: [32]u8, peer_id: [32]u8, context: ?*anyopaque) void,
|
|
context: ?*anyopaque,
|
|
|
|
pub fn register(self: NodeIdRegistrationCallback, node_id: [32]u8, peer_id: [32]u8) void {
|
|
self.register_fn(node_id, peer_id, self.context);
|
|
}
|
|
};
|
|
|
|
/// Handler limits for memory exhaustion protection
|
|
pub const HandlerLimits = struct {
|
|
pub const MAX_PENDING_MESSAGES: usize = 10000; // Max messages in async queue
|
|
pub const MAX_HANDLER_REGISTRY_SIZE: usize = 1000; // Max handlers per type
|
|
};
|
|
|
|
/// Handler function signature
|
|
pub const HandlerFunc = *const fn (message.Message, *anyopaque) anyerror!void;
|
|
|
|
/// IMP-M1/M2 FIX: Handler configuration for configurable values
|
|
pub const HandlerConfig = struct {
|
|
/// Default port for discovered peers (IMP-M1 FIX)
|
|
default_discovery_port: u16 = 9999,
|
|
/// Default capabilities flags (IMP-M2 FIX)
|
|
default_capabilities: u32 = 0x0F,
|
|
/// Maximum known nodes to return in discovery response
|
|
max_discovery_nodes: u32 = 20,
|
|
};
|
|
|
|
/// Network sender callback for sending serialized messages to peers
|
|
/// This is the interface between protocol handlers and the network layer
|
|
pub const NetworkSender = struct {
|
|
/// Function to send raw bytes to a peer
|
|
/// Returns true on success, false on failure
|
|
send_fn: *const fn (peer_id: [32]u8, data: []const u8, context: ?*anyopaque) bool,
|
|
/// Optional context pointer passed to send_fn
|
|
context: ?*anyopaque,
|
|
|
|
/// Send serialized data to a peer
|
|
pub fn send(self: NetworkSender, peer_id: [32]u8, data: []const u8) bool {
|
|
return self.send_fn(peer_id, data, self.context);
|
|
}
|
|
};
|
|
|
|
/// Handler context for storing handler state and dependencies
|
|
///
|
|
/// ## Thread Safety (THR-M1 FIX)
|
|
/// This context is designed to be configured during initialization and then
|
|
/// used read-only during message processing. The following thread-safety
|
|
/// guarantees apply:
|
|
///
|
|
/// - Setter methods (setRouter, setNetworkSender, etc.) are NOT thread-safe
|
|
/// and MUST be called during initialization before message processing begins.
|
|
/// - Once configured, the component pointers (peer_manager, file_manager, etc.)
|
|
/// are read-only and safe to access from multiple threads.
|
|
/// - The `source_peer_id` field is protected by HandlerRegistry.processing_mutex.
|
|
/// THR-H4 FIX: processMessage() acquires the mutex before setting source_peer_id.
|
|
/// - The `metrics` field points to HandlerMetrics which uses atomic operations
|
|
/// for thread-safe counter updates.
|
|
/// - Component pointers (peer_manager, file_manager, etc.) point to objects
|
|
/// with their own internal synchronization.
|
|
pub const HandlerContext = struct {
|
|
allocator: std.mem.Allocator,
|
|
router: ?*anyopaque, // Pointer to message router
|
|
metrics: *HandlerMetrics,
|
|
|
|
// HIGH-2 FIX: Mutex for protecting compound type fields during configuration
|
|
// This protects: network_sender, config, data_response_handler
|
|
config_mutex: std.Thread.Mutex = .{},
|
|
|
|
// IMP-M1/M2 FIX: Configurable handler settings
|
|
// HIGH-2 FIX: Protected by config_mutex
|
|
config: HandlerConfig = .{},
|
|
|
|
// P2P component references for full integration
|
|
// THR-M1: Set during init only; components have internal sync
|
|
peer_manager: ?*anyopaque = null,
|
|
file_manager: ?*anyopaque = null,
|
|
routing_table: ?*anyopaque = null,
|
|
topology: ?*anyopaque = null,
|
|
dht_coordinator: ?*anyopaque = null,
|
|
|
|
// Network sender for sending messages to peers
|
|
// HIGH-2 FIX: Protected by config_mutex (compound type)
|
|
network_sender: ?NetworkSender = null,
|
|
|
|
// Message serializer for encoding outgoing messages
|
|
// THR-M1: Serializer is thread-safe
|
|
message_serializer: ?*serializer.MessageSerializer = null,
|
|
|
|
// Source peer ID for tracking message origin
|
|
// THR-H4 FIX: This field is now protected by HandlerRegistry.processing_mutex.
|
|
// processMessage() sets this field before invoking handlers and clears it after.
|
|
// The mutex ensures only one message is processed at a time, preventing races.
|
|
source_peer_id: ?message.NodeId = null,
|
|
|
|
// Replay protection
|
|
replay_protector: ?*replay_protection.ReplayProtector = null,
|
|
|
|
// Request tracking for correlating data responses
|
|
request_tracker: ?*RequestTracker = null,
|
|
|
|
// Crypto manager for encryption/decryption
|
|
crypto_manager: ?*anyopaque = null,
|
|
|
|
// Our node ID for identifying ourselves in responses
|
|
local_node_id: message.NodeId = [_]u8{0} ** 32,
|
|
|
|
// CRIT-1 FIX: Data response handler callback
|
|
// HIGH-2 FIX: Protected by config_mutex (compound type)
|
|
// Set by P2P layer to handle data responses with proper file manager access
|
|
data_response_handler: ?DataResponseHandler = null,
|
|
|
|
// Node ID registration callback - called when a peer's identity is verified
|
|
// Maps remote peer's identity public key (node ID) to connection peer ID
|
|
node_id_registration_callback: ?NodeIdRegistrationCallback = null,
|
|
|
|
pub fn init(allocator: std.mem.Allocator, metrics: *HandlerMetrics) HandlerContext {
|
|
return .{
|
|
.allocator = allocator,
|
|
.router = null,
|
|
.metrics = metrics,
|
|
};
|
|
}
|
|
|
|
/// IMP-M1/M2 FIX: Set handler configuration
|
|
/// HIGH-2 FIX: Thread-safe with mutex protection
|
|
pub fn setConfig(self: *HandlerContext, config: HandlerConfig) void {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
self.config = config;
|
|
}
|
|
|
|
/// HIGH-2 FIX: Thread-safe getter for config
|
|
pub fn getConfig(self: *HandlerContext) HandlerConfig {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
return self.config;
|
|
}
|
|
|
|
pub fn setRouter(self: *HandlerContext, router_ptr: *anyopaque) void {
|
|
self.router = router_ptr;
|
|
}
|
|
|
|
/// Set the network sender for outgoing messages
|
|
/// HIGH-2 FIX: Thread-safe with mutex protection (compound type)
|
|
pub fn setNetworkSender(self: *HandlerContext, sender: NetworkSender) void {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
self.network_sender = sender;
|
|
}
|
|
|
|
/// HIGH-2 FIX: Thread-safe getter for network sender
|
|
pub fn getNetworkSender(self: *HandlerContext) ?NetworkSender {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
return self.network_sender;
|
|
}
|
|
|
|
/// Set the message serializer
|
|
pub fn setSerializer(self: *HandlerContext, msg_serializer: *serializer.MessageSerializer) void {
|
|
self.message_serializer = msg_serializer;
|
|
}
|
|
|
|
/// Set our local node ID
|
|
pub fn setLocalNodeId(self: *HandlerContext, node_id: message.NodeId) void {
|
|
self.local_node_id = node_id;
|
|
}
|
|
|
|
/// Set P2P component references
|
|
pub fn setP2PComponents(
|
|
self: *HandlerContext,
|
|
peer_manager: ?*anyopaque,
|
|
file_manager: ?*anyopaque,
|
|
routing_table: ?*anyopaque,
|
|
topology: ?*anyopaque,
|
|
) void {
|
|
self.peer_manager = peer_manager;
|
|
self.file_manager = file_manager;
|
|
self.routing_table = routing_table;
|
|
self.topology = topology;
|
|
}
|
|
|
|
/// CRIT-1 FIX: Set the data response handler callback
|
|
/// HIGH-2 FIX: Thread-safe with mutex protection (compound type)
|
|
/// This should be called by the P2P layer to wire in file manager handling
|
|
pub fn setDataResponseHandler(self: *HandlerContext, handler: DataResponseHandler) void {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
self.data_response_handler = handler;
|
|
}
|
|
|
|
/// HIGH-2 FIX: Thread-safe getter for data response handler
|
|
pub fn getDataResponseHandler(self: *HandlerContext) ?DataResponseHandler {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
return self.data_response_handler;
|
|
}
|
|
|
|
/// Set the node ID registration callback
|
|
/// This callback is invoked during key exchange to map remote peer's identity key to connection peer ID
|
|
pub fn setNodeIdRegistrationCallback(self: *HandlerContext, callback: NodeIdRegistrationCallback) void {
|
|
self.config_mutex.lock();
|
|
defer self.config_mutex.unlock();
|
|
self.node_id_registration_callback = callback;
|
|
}
|
|
|
|
/// Register a node ID to peer ID mapping (if callback is set)
|
|
/// Called internally when a peer's identity is verified during key exchange
|
|
pub fn registerNodeId(self: *HandlerContext, node_id: [32]u8, peer_id: [32]u8) void {
|
|
self.config_mutex.lock();
|
|
const callback = self.node_id_registration_callback;
|
|
self.config_mutex.unlock();
|
|
|
|
if (callback) |cb| {
|
|
cb.register(node_id, peer_id);
|
|
std.log.debug("Registered node ID mapping: {x} -> peer {x}", .{ node_id[0..8].*, peer_id[0..8].* });
|
|
}
|
|
}
|
|
|
|
// MEM-M1 FIX: Type-safe getter methods for pointer casts.
|
|
// These methods encapsulate the unsafe pointer casts and provide
|
|
// proper error handling instead of undefined behavior on type mismatch.
|
|
|
|
/// Get the peer manager with type-safe cast
|
|
/// Returns null if not set, error if memory corruption detected
|
|
pub fn getPeerManager(self: *const HandlerContext) error{InvalidPointer}!?*@import("network").PeerManager {
|
|
const ptr = self.peer_manager orelse return null;
|
|
// Validate alignment - if misaligned, pointer was likely corrupted
|
|
if (@intFromPtr(ptr) % @alignOf(@import("network").PeerManager) != 0) {
|
|
std.log.err("MEM-M1: Misaligned peer_manager pointer detected", .{});
|
|
return error.InvalidPointer;
|
|
}
|
|
return @as(*@import("network").PeerManager, @ptrCast(@alignCast(ptr)));
|
|
}
|
|
|
|
/// Get the file manager with type-safe cast
|
|
pub fn getFileManager(self: *const HandlerContext) error{InvalidPointer}!?*@import("files").FileSharingManager {
|
|
const files = @import("files");
|
|
const ptr = self.file_manager orelse return null;
|
|
if (@intFromPtr(ptr) % @alignOf(files.FileSharingManager) != 0) {
|
|
std.log.err("MEM-M1: Misaligned file_manager pointer detected", .{});
|
|
return error.InvalidPointer;
|
|
}
|
|
return @as(*files.FileSharingManager, @ptrCast(@alignCast(ptr)));
|
|
}
|
|
|
|
/// Get the routing table with type-safe cast
|
|
pub fn getRoutingTable(self: *const HandlerContext) error{InvalidPointer}!?*@import("network").KademliaRoutingTable {
|
|
const network = @import("network");
|
|
const ptr = self.routing_table orelse return null;
|
|
if (@intFromPtr(ptr) % @alignOf(network.KademliaRoutingTable) != 0) {
|
|
std.log.err("MEM-M1: Misaligned routing_table pointer detected", .{});
|
|
return error.InvalidPointer;
|
|
}
|
|
return @as(*network.KademliaRoutingTable, @ptrCast(@alignCast(ptr)));
|
|
}
|
|
|
|
/// Get the topology with type-safe cast
|
|
pub fn getTopology(self: *const HandlerContext) error{InvalidPointer}!?*@import("network").NetworkTopology {
|
|
const network = @import("network");
|
|
const ptr = self.topology orelse return null;
|
|
if (@intFromPtr(ptr) % @alignOf(network.NetworkTopology) != 0) {
|
|
std.log.err("MEM-M1: Misaligned topology pointer detected", .{});
|
|
return error.InvalidPointer;
|
|
}
|
|
return @as(*network.NetworkTopology, @ptrCast(@alignCast(ptr)));
|
|
}
|
|
|
|
/// Set the source peer ID for the current message
|
|
pub fn setSource(self: *HandlerContext, source: message.NodeId) void {
|
|
self.source_peer_id = source;
|
|
}
|
|
|
|
/// Clear the source peer ID after processing
|
|
pub fn clearSource(self: *HandlerContext) void {
|
|
self.source_peer_id = null;
|
|
}
|
|
|
|
/// Send a response message to a peer
|
|
/// Serializes the message and sends it via the network sender
|
|
/// SEC-M1 FIX: Uses dynamic buffer allocation instead of fixed 8KB
|
|
pub fn sendResponse(self: *HandlerContext, peer_id: message.NodeId, msg: message.Message) !void {
|
|
const sender = self.network_sender orelse return error.NoNetworkSender;
|
|
const msg_serializer = self.message_serializer orelse {
|
|
// Fallback: create temporary serializer if none configured
|
|
var temp_serializer = serializer.MessageSerializer.init(self.allocator);
|
|
|
|
// Calculate required buffer size: header + payload + HMAC (32) + overhead (64)
|
|
const payload_size = temp_serializer.getPayloadSizePublic(msg);
|
|
const header_overhead: usize = 128; // Header + message header + HMAC + padding
|
|
const required_size = std.math.add(usize, payload_size, header_overhead) catch {
|
|
return error.SerializationFailed;
|
|
};
|
|
|
|
// Cap at max message size
|
|
const buffer_size = @min(required_size, serializer.Limits.MAX_MESSAGE_SIZE);
|
|
|
|
// Allocate dynamic buffer
|
|
const buffer = self.allocator.alloc(u8, buffer_size) catch return error.OutOfMemory;
|
|
defer self.allocator.free(buffer);
|
|
|
|
const len = temp_serializer.serialize(msg, buffer) catch return error.SerializationFailed;
|
|
if (!sender.send(peer_id, buffer[0..len])) {
|
|
return error.SendFailed;
|
|
}
|
|
return;
|
|
};
|
|
|
|
// Calculate required buffer size: header + payload + HMAC (32) + overhead (64)
|
|
const payload_size = msg_serializer.getPayloadSizePublic(msg);
|
|
const header_overhead: usize = 128; // Header + message header + HMAC + padding
|
|
const required_size = std.math.add(usize, payload_size, header_overhead) catch {
|
|
return error.SerializationFailed;
|
|
};
|
|
|
|
// Cap at max message size
|
|
const buffer_size = @min(required_size, serializer.Limits.MAX_MESSAGE_SIZE);
|
|
|
|
// Allocate dynamic buffer
|
|
const buffer = self.allocator.alloc(u8, buffer_size) catch return error.OutOfMemory;
|
|
defer self.allocator.free(buffer);
|
|
|
|
// Serialize the message
|
|
const len = msg_serializer.serialize(msg, buffer) catch return error.SerializationFailed;
|
|
|
|
// Send via network sender
|
|
if (!sender.send(peer_id, buffer[0..len])) {
|
|
return error.SendFailed;
|
|
}
|
|
}
|
|
|
|
/// Send a message to a peer (alias for sendResponse)
|
|
pub fn sendMessage(self: *HandlerContext, peer_id: message.NodeId, msg: message.Message) !void {
|
|
try self.sendResponse(peer_id, msg);
|
|
}
|
|
|
|
/// Send a message to all connected peers (broadcast)
|
|
pub fn broadcast(self: *HandlerContext, msg: message.Message, exclude_peer: ?message.NodeId) !usize {
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
const pm = (try self.getPeerManager()) orelse return error.NoPeerManager;
|
|
|
|
const peers = pm.getConnectedPeers() catch return error.PeerManagerError;
|
|
defer peers.deinit();
|
|
|
|
var sent_count: usize = 0;
|
|
for (peers.items) |peer_info| {
|
|
// Skip excluded peer
|
|
if (exclude_peer) |excluded| {
|
|
// SECURITY: Timing-safe comparison for peer ID
|
|
if (std.crypto.timing_safe.eql([32]u8, peer_info.id.bytes, excluded)) continue;
|
|
}
|
|
|
|
self.sendResponse(peer_info.id.bytes, msg) catch |err| {
|
|
std.log.warn("Failed to broadcast to peer: {}", .{err});
|
|
continue;
|
|
};
|
|
sent_count += 1;
|
|
}
|
|
|
|
return sent_count;
|
|
}
|
|
|
|
/// CRIT-NEW-12 FIX: Send a message to a limited number of connected peers
|
|
/// This limits fan-out to prevent amplification attacks
|
|
pub fn broadcastLimited(self: *HandlerContext, msg: message.Message, exclude_peer: ?message.NodeId, max_peers: usize) !usize {
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
const pm = (try self.getPeerManager()) orelse return error.NoPeerManager;
|
|
|
|
const peers = pm.getConnectedPeers() catch return error.PeerManagerError;
|
|
defer peers.deinit();
|
|
|
|
var sent_count: usize = 0;
|
|
for (peers.items) |peer_info| {
|
|
// CRIT-NEW-12 FIX: Stop after reaching limit
|
|
if (sent_count >= max_peers) {
|
|
std.log.debug("CRIT-NEW-12: Broadcast limited to {} peers", .{max_peers});
|
|
break;
|
|
}
|
|
|
|
// Skip excluded peer
|
|
if (exclude_peer) |excluded| {
|
|
// SECURITY: Timing-safe comparison for peer ID
|
|
if (std.crypto.timing_safe.eql([32]u8, peer_info.id.bytes, excluded)) continue;
|
|
}
|
|
|
|
self.sendResponse(peer_info.id.bytes, msg) catch |err| {
|
|
std.log.warn("Failed to broadcast to peer: {}", .{err});
|
|
continue;
|
|
};
|
|
sent_count += 1;
|
|
}
|
|
|
|
return sent_count;
|
|
}
|
|
};
|
|
|
|
/// Handler metrics tracking
|
|
pub const HandlerMetrics = struct {
|
|
messages_processed: std.atomic.Value(u64),
|
|
messages_failed: std.atomic.Value(u64),
|
|
handlers_registered: u16,
|
|
average_processing_time: f64,
|
|
mutex: std.Thread.Mutex,
|
|
/// ERR-M2 FIX: Track peer addition failures for aggregation
|
|
peer_addition_failures: std.atomic.Value(u64),
|
|
|
|
pub fn init() HandlerMetrics {
|
|
return .{
|
|
.messages_processed = std.atomic.Value(u64).init(0),
|
|
.messages_failed = std.atomic.Value(u64).init(0),
|
|
.handlers_registered = 0,
|
|
.average_processing_time = 0.0,
|
|
.mutex = .{},
|
|
.peer_addition_failures = std.atomic.Value(u64).init(0),
|
|
};
|
|
}
|
|
|
|
pub fn recordMessageProcessed(self: *HandlerMetrics, processing_time: f64) void {
|
|
_ = self.messages_processed.fetchAdd(1, .monotonic);
|
|
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
self.average_processing_time = (self.average_processing_time * 0.9) + (processing_time * 0.1);
|
|
}
|
|
|
|
pub fn recordMessageFailed(self: *HandlerMetrics) void {
|
|
_ = self.messages_failed.fetchAdd(1, .monotonic);
|
|
}
|
|
|
|
/// ERR-M2 FIX: Record a peer addition failure
|
|
pub fn recordPeerAdditionFailed(self: *HandlerMetrics) void {
|
|
_ = self.peer_addition_failures.fetchAdd(1, .monotonic);
|
|
}
|
|
|
|
pub fn getSuccessRate(self: *HandlerMetrics) f64 {
|
|
const processed = self.messages_processed.load(.monotonic);
|
|
const failed = self.messages_failed.load(.monotonic);
|
|
const total = processed + failed;
|
|
return if (total > 0) @as(f64, @floatFromInt(processed)) / @as(f64, @floatFromInt(total)) else 1.0;
|
|
}
|
|
};
|
|
|
|
/// Information about a tracked request
|
|
pub const RequestInfo = struct {
|
|
piece_index: u32,
|
|
offset: u64,
|
|
size: u32,
|
|
file_hash: [32]u8,
|
|
peer_id: message.NodeId,
|
|
timestamp: i64,
|
|
};
|
|
|
|
/// Thread-safe tracker for mapping request IDs to piece information
|
|
/// Used to correlate DataResponse messages with their original DataRequest
|
|
///
|
|
/// ## Purpose
|
|
/// The RequestTracker solves the fundamental problem of correlating data responses
|
|
/// with their original requests in a distributed P2P system. Without proper tracking,
|
|
/// there's no reliable way to know which piece a DataResponse belongs to.
|
|
///
|
|
/// ## The Problem it Solves
|
|
/// Previously, code used `request_id % 1000000` to derive piece indices. This is broken because:
|
|
/// 1. Collisions occur when request_id wraps around (causes file corruption)
|
|
/// 2. No verification that the response matches the original request
|
|
/// 3. No timeout handling (memory leaks from unanswered requests)
|
|
/// 4. Security vulnerability (malicious peers can send wrong pieces)
|
|
/// 5. Fails with concurrent downloads of multiple files
|
|
///
|
|
/// ## How it Works
|
|
/// 1. Before sending a DataRequest, call trackRequest() with the piece information
|
|
/// 2. Use the returned request_id in your DataRequest message
|
|
/// 3. When the DataResponse arrives, call resolveRequest() to get back the piece info
|
|
/// 4. The tracker automatically removes the request and enforces timeouts
|
|
///
|
|
/// ## Usage Example
|
|
/// ```zig
|
|
/// // Initialize (typically done once during setup)
|
|
/// var tracker = RequestTracker.init(allocator);
|
|
/// defer tracker.deinit();
|
|
///
|
|
/// // Configure timeout (optional, default is 60 seconds)
|
|
/// tracker.setRequestTimeout(30); // 30 second timeout
|
|
///
|
|
/// // When sending a request:
|
|
/// const file_hash: [32]u8 = ...; // Hash of the file being downloaded
|
|
/// const peer_id: [32]u8 = ...; // Peer we're requesting from
|
|
/// const piece_index: u32 = 42; // Which piece we want
|
|
/// const offset: u64 = 0; // Offset within piece
|
|
/// const size: u32 = 16384; // Size of data requested
|
|
///
|
|
/// const request_id = try tracker.trackRequest(
|
|
/// piece_index,
|
|
/// offset,
|
|
/// size,
|
|
/// file_hash,
|
|
/// peer_id,
|
|
/// );
|
|
///
|
|
/// // Send the request with this ID
|
|
/// const data_request = DataRequest{
|
|
/// .request_id = request_id,
|
|
/// .data_id = &file_hash,
|
|
/// .offset = offset,
|
|
/// .size = size,
|
|
/// };
|
|
/// try sendToPeer(peer_id, data_request);
|
|
///
|
|
/// // When response arrives (in handler):
|
|
/// const info = tracker.resolveRequest(response.request_id) orelse {
|
|
/// // Request not found - either expired, already processed, or invalid
|
|
/// return error.UnknownRequest;
|
|
/// };
|
|
///
|
|
/// // Now we have the piece information back
|
|
/// std.debug.assert(info.piece_index == 42);
|
|
/// std.debug.assert(info.size == 16384);
|
|
///
|
|
/// // Verify the response came from the expected peer
|
|
/// if (!std.mem.eql(u8, &info.peer_id, &actual_peer_id)) {
|
|
/// return error.PeerMismatch; // Response spoofing detected!
|
|
/// }
|
|
///
|
|
/// // Write the data to the correct location
|
|
/// try writeToFile(info.file_hash, info.piece_index, info.offset, response.data);
|
|
/// ```
|
|
///
|
|
/// ## Thread Safety
|
|
/// All methods are thread-safe and can be called from multiple threads concurrently.
|
|
/// The tracker uses a mutex to protect its internal state.
|
|
///
|
|
/// ## Memory Management
|
|
/// - Call cleanupStaleRequests() periodically to remove expired requests
|
|
/// - Each request is automatically removed when resolved
|
|
/// - Call clear() to remove all pending requests (useful for shutdown)
|
|
///
|
|
/// ## Integration with HandlerRegistry
|
|
/// The HandlerRegistry automatically creates and manages a RequestTracker instance.
|
|
/// Access it via `context.request_tracker` in your handlers.
|
|
///
|
|
pub const RequestTracker = struct {
|
|
/// Maximum tracked requests to prevent DoS via memory exhaustion
|
|
pub const MAX_TRACKED_REQUESTS: usize = 10000;
|
|
|
|
allocator: std.mem.Allocator,
|
|
requests: std.AutoHashMap(u64, RequestInfo),
|
|
mutex: std.Thread.Mutex,
|
|
request_timeout_seconds: i64,
|
|
|
|
pub fn init(allocator: std.mem.Allocator) RequestTracker {
|
|
return .{
|
|
.allocator = allocator,
|
|
.requests = std.AutoHashMap(u64, RequestInfo).init(allocator),
|
|
.mutex = .{},
|
|
.request_timeout_seconds = 60, // Default 60 second timeout
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *RequestTracker) void {
|
|
self.requests.deinit();
|
|
}
|
|
|
|
/// Configure the request timeout
|
|
pub fn setRequestTimeout(self: *RequestTracker, timeout_seconds: i64) void {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
self.request_timeout_seconds = timeout_seconds;
|
|
}
|
|
|
|
/// Generate a unique request ID and track the request
|
|
/// Returns the request_id to use in the DataRequest message
|
|
/// Returns error.OutOfMemory if too many requests are being tracked
|
|
pub fn trackRequest(
|
|
self: *RequestTracker,
|
|
piece_index: u32,
|
|
offset: u64,
|
|
size: u32,
|
|
file_hash: [32]u8,
|
|
peer_id: message.NodeId,
|
|
) !u64 {
|
|
// Generate cryptographically random request ID
|
|
var id: [8]u8 = undefined;
|
|
std.crypto.random.bytes(&id);
|
|
const request_id = std.mem.readInt(u64, &id, .little);
|
|
|
|
const info = RequestInfo{
|
|
.piece_index = piece_index,
|
|
.offset = offset,
|
|
.size = size,
|
|
.file_hash = file_hash,
|
|
.peer_id = peer_id,
|
|
.timestamp = std.time.timestamp(),
|
|
};
|
|
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// Enforce size limit to prevent DoS
|
|
if (self.requests.count() >= MAX_TRACKED_REQUESTS) {
|
|
// Try to clean up expired entries first
|
|
self.cleanupExpiredLocked();
|
|
|
|
// Still over limit after cleanup - reject
|
|
if (self.requests.count() >= MAX_TRACKED_REQUESTS) {
|
|
std.log.warn("SECURITY: Request tracker at capacity ({d}), rejecting new request", .{MAX_TRACKED_REQUESTS});
|
|
return error.OutOfMemory;
|
|
}
|
|
}
|
|
|
|
try self.requests.put(request_id, info);
|
|
return request_id;
|
|
}
|
|
|
|
/// Clean up expired entries (must hold mutex)
|
|
fn cleanupExpiredLocked(self: *RequestTracker) void {
|
|
const now = std.time.timestamp();
|
|
var to_remove = std.ArrayList(u64){};
|
|
defer to_remove.deinit(self.allocator);
|
|
|
|
var iter = self.requests.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (now - entry.value_ptr.timestamp > self.request_timeout_seconds) {
|
|
to_remove.append(self.allocator, entry.key_ptr.*) catch continue;
|
|
}
|
|
}
|
|
|
|
for (to_remove.items) |key| {
|
|
_ = self.requests.remove(key);
|
|
}
|
|
}
|
|
|
|
/// Resolve a request ID to its RequestInfo
|
|
/// Returns null if request_id not found or expired
|
|
/// Removes the request from tracking after resolution
|
|
pub fn resolveRequest(self: *RequestTracker, request_id: u64) ?RequestInfo {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
const entry = self.requests.fetchRemove(request_id) orelse return null;
|
|
const info = entry.value;
|
|
|
|
// Check if request has expired
|
|
const now = std.time.timestamp();
|
|
if (now - info.timestamp > self.request_timeout_seconds) {
|
|
std.log.warn("Request {d} expired (age: {d}s)", .{ request_id, now - info.timestamp });
|
|
return null;
|
|
}
|
|
|
|
return info;
|
|
}
|
|
|
|
/// Look up request info without removing it
|
|
pub fn peekRequest(self: *RequestTracker, request_id: u64) ?RequestInfo {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
return self.requests.get(request_id);
|
|
}
|
|
|
|
/// Clean up expired requests
|
|
pub fn cleanupStaleRequests(self: *RequestTracker) usize {
|
|
const now = std.time.timestamp();
|
|
var expired_ids: std.ArrayList(u64) = .{};
|
|
defer expired_ids.deinit(self.allocator);
|
|
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// Find expired requests
|
|
var it = self.requests.iterator();
|
|
while (it.next()) |entry| {
|
|
if (now - entry.value_ptr.timestamp > self.request_timeout_seconds) {
|
|
expired_ids.append(self.allocator, entry.key_ptr.*) catch |err| {
|
|
std.log.warn("Failed to track expired request ID for cleanup: {}", .{err});
|
|
continue;
|
|
};
|
|
}
|
|
}
|
|
|
|
// Remove expired requests
|
|
for (expired_ids.items) |id| {
|
|
_ = self.requests.remove(id);
|
|
}
|
|
|
|
if (expired_ids.items.len > 0) {
|
|
std.log.info("Cleaned up {d} stale requests", .{expired_ids.items.len});
|
|
}
|
|
|
|
return expired_ids.items.len;
|
|
}
|
|
|
|
/// Get the number of pending requests
|
|
pub fn pendingCount(self: *RequestTracker) usize {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
return self.requests.count();
|
|
}
|
|
|
|
/// Cancel a pending request
|
|
pub fn cancelRequest(self: *RequestTracker, request_id: u64) bool {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
return self.requests.remove(request_id);
|
|
}
|
|
};
|
|
|
|
/// Message handler interface
|
|
pub const MessageHandler = struct {
|
|
handler_func: HandlerFunc,
|
|
context: *anyopaque,
|
|
msg_type: protocol.MessageType,
|
|
priority: u8,
|
|
|
|
pub fn init(func: HandlerFunc, context: *anyopaque, msg_type: protocol.MessageType) MessageHandler {
|
|
return .{
|
|
.handler_func = func,
|
|
.context = context,
|
|
.msg_type = msg_type,
|
|
.priority = 0,
|
|
};
|
|
}
|
|
|
|
pub fn process(self: *MessageHandler, msg: message.Message) !void {
|
|
try self.handler_func(msg, self.context);
|
|
}
|
|
};
|
|
|
|
/// Handler registry for managing message handlers
|
|
pub const HandlerRegistry = struct {
|
|
/// SECURITY: Replay protection is MANDATORY. This is a compile-time constant.
|
|
/// Disabling replay protection would allow replay attacks where valid messages
|
|
/// are captured and retransmitted to cause duplicate actions.
|
|
const REQUIRE_REPLAY_PROTECTION: bool = true;
|
|
|
|
allocator: std.mem.Allocator,
|
|
handlers: std.AutoHashMap(protocol.MessageType, std.ArrayList(MessageHandler)),
|
|
context: HandlerContext,
|
|
replay_protector: replay_protection.ReplayProtector,
|
|
request_tracker: RequestTracker,
|
|
last_cleanup_time: i64,
|
|
/// Thread safety mutex for handler registration/unregistration
|
|
handlers_mutex: std.Thread.Mutex = .{},
|
|
/// 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
|
|
/// message processing threads. Each processMessage call acquires this mutex,
|
|
/// sets source_peer_id, runs handlers, then clears source_peer_id.
|
|
processing_mutex: std.Thread.Mutex = .{},
|
|
|
|
pub fn init(allocator: std.mem.Allocator) !HandlerRegistry {
|
|
const metrics = try allocator.create(HandlerMetrics);
|
|
errdefer allocator.destroy(metrics);
|
|
metrics.* = HandlerMetrics.init();
|
|
|
|
const context = HandlerContext.init(allocator, metrics);
|
|
|
|
// Create HandlerRegistry with replay protector and request tracker initialized
|
|
var result = HandlerRegistry{
|
|
.allocator = allocator,
|
|
.handlers = std.AutoHashMap(protocol.MessageType, std.ArrayList(MessageHandler)).init(allocator),
|
|
.context = context,
|
|
.replay_protector = replay_protection.ReplayProtector.init(allocator),
|
|
.request_tracker = RequestTracker.init(allocator),
|
|
.last_cleanup_time = std.time.timestamp(),
|
|
};
|
|
|
|
// Wire replay protector and request tracker into context (must be done after struct is created)
|
|
result.context.replay_protector = &result.replay_protector;
|
|
result.context.request_tracker = &result.request_tracker;
|
|
|
|
return result;
|
|
}
|
|
|
|
pub fn deinit(self: *HandlerRegistry) void {
|
|
var it = self.handlers.valueIterator();
|
|
while (it.next()) |handler_list| {
|
|
handler_list.*.deinit(self.allocator);
|
|
}
|
|
self.handlers.deinit();
|
|
self.replay_protector.deinit();
|
|
self.request_tracker.deinit();
|
|
self.allocator.destroy(self.context.metrics);
|
|
}
|
|
|
|
/// Register a handler for a specific message type
|
|
pub fn registerHandler(self: *HandlerRegistry, msg_type: protocol.MessageType, handler: MessageHandler) !void {
|
|
self.handlers_mutex.lock();
|
|
defer self.handlers_mutex.unlock();
|
|
|
|
// SECURITY: Enforce maximum handlers per type to prevent memory exhaustion
|
|
if (self.handlers.getEntry(msg_type)) |entry| {
|
|
if (entry.value_ptr.items.len >= HandlerLimits.MAX_HANDLER_REGISTRY_SIZE) {
|
|
return error.TooManyHandlers;
|
|
}
|
|
try entry.value_ptr.append(self.allocator, handler);
|
|
} else {
|
|
var handler_list: std.ArrayList(MessageHandler) = .{};
|
|
errdefer handler_list.deinit(self.allocator);
|
|
try handler_list.append(self.allocator, handler);
|
|
try self.handlers.put(msg_type, handler_list);
|
|
}
|
|
|
|
self.context.metrics.mutex.lock();
|
|
self.context.metrics.handlers_registered += 1;
|
|
self.context.metrics.mutex.unlock();
|
|
}
|
|
|
|
/// Unregister all handlers for a message type
|
|
pub fn unregisterHandlers(self: *HandlerRegistry, msg_type: protocol.MessageType) void {
|
|
self.handlers_mutex.lock();
|
|
defer self.handlers_mutex.unlock();
|
|
|
|
if (self.handlers.fetchRemove(msg_type)) |entry| {
|
|
const handler_count = @as(u16, @intCast(entry.value.items.len));
|
|
entry.value.deinit(self.allocator);
|
|
|
|
self.context.metrics.mutex.lock();
|
|
self.context.metrics.handlers_registered -= handler_count;
|
|
self.context.metrics.mutex.unlock();
|
|
}
|
|
}
|
|
|
|
/// Process a message through registered handlers
|
|
/// THR-H4 FIX: Uses processing_mutex to ensure source_peer_id is set correctly
|
|
/// for each message and not changed by concurrent message processing.
|
|
pub fn processMessage(self: *HandlerRegistry, msg: message.Message) !void {
|
|
// THR-H4 FIX: Acquire processing mutex to ensure exclusive access to source_peer_id
|
|
// This serializes message processing but ensures thread safety.
|
|
self.processing_mutex.lock();
|
|
defer self.processing_mutex.unlock();
|
|
|
|
const start_time = std.time.timestamp();
|
|
defer {
|
|
const elapsed = @as(f64, @floatFromInt(std.time.timestamp() - start_time));
|
|
self.context.metrics.recordMessageProcessed(elapsed);
|
|
}
|
|
|
|
// REPLAY PROTECTION: Check message before processing
|
|
// Extract message metadata for replay detection
|
|
const msg_id = msg.getIdForReplay();
|
|
const timestamp = msg.getTimestamp();
|
|
const nonce = msg.getNonce();
|
|
const sequence = msg.getSequence();
|
|
|
|
// Get source from message (fallback since msg.getSource() may return zeros)
|
|
// The source should be set by the network layer before calling processMessage
|
|
const source_id = self.context.source_peer_id orelse msg.getSource();
|
|
|
|
// THR-H4 FIX: Set source_peer_id for handlers to use
|
|
// Clear it when we're done (via defer) to prevent stale values
|
|
self.context.source_peer_id = source_id;
|
|
defer self.context.source_peer_id = null;
|
|
|
|
// SECURITY: Check for replay attack (compile-time enforced, cannot be disabled)
|
|
if (comptime REQUIRE_REPLAY_PROTECTION) {
|
|
self.replay_protector.checkMessage(
|
|
msg_id,
|
|
timestamp,
|
|
nonce,
|
|
sequence,
|
|
source_id,
|
|
) catch |err| {
|
|
// Replay detected - reject message and record failure
|
|
self.context.metrics.recordMessageFailed();
|
|
// SEC-M4 FIX: Don't log full peer ID to prevent correlation attacks
|
|
// Only log first 4 bytes as identifier hint
|
|
std.log.err("SECURITY: Replay attack detected: {s} (msg_id={}, peer_hint={x:0>2}{x:0>2}{x:0>2}{x:0>2})", .{
|
|
@errorName(err),
|
|
msg_id,
|
|
source_id[0],
|
|
source_id[1],
|
|
source_id[2],
|
|
source_id[3],
|
|
});
|
|
return err;
|
|
};
|
|
}
|
|
|
|
const msg_type = msg.getType();
|
|
|
|
// FIX: Copy handlers while holding lock, then release lock before calling handlers
|
|
// This prevents deadlock if a handler tries to register/unregister handlers
|
|
var handlers_copy: std.ArrayList(MessageHandler) = .{};
|
|
defer handlers_copy.deinit(self.allocator);
|
|
|
|
{
|
|
self.handlers_mutex.lock();
|
|
defer self.handlers_mutex.unlock();
|
|
|
|
if (self.handlers.getEntry(msg_type)) |entry| {
|
|
const handler_list = entry.value_ptr;
|
|
|
|
// Sort handlers by priority (higher values first)
|
|
std.mem.sort(MessageHandler, handler_list.items, {}, compareHandlerPriority);
|
|
|
|
// Copy handlers to process outside the lock
|
|
for (handler_list.items) |handler| {
|
|
handlers_copy.append(self.allocator, handler) catch {
|
|
std.log.err("Failed to copy handler for processing - skipping message", .{});
|
|
return;
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
// Process handlers WITHOUT holding lock (prevents reentrancy deadlock)
|
|
// Note: source_peer_id is now set and protected by processing_mutex
|
|
for (handlers_copy.items) |*handler| {
|
|
handler.process(msg) catch |err| {
|
|
self.context.metrics.recordMessageFailed();
|
|
return err;
|
|
};
|
|
}
|
|
}
|
|
|
|
/// Get the context for handlers
|
|
pub fn getContext(self: *HandlerRegistry) *HandlerContext {
|
|
return &self.context;
|
|
}
|
|
|
|
/// Cleanup replay protection state (remove old entries)
|
|
/// Should be called periodically to prevent unbounded memory growth
|
|
pub fn cleanupReplayProtection(self: *HandlerRegistry) void {
|
|
const current_time = std.time.timestamp();
|
|
|
|
// Only cleanup if enough time has passed since last cleanup
|
|
const cleanup_interval: i64 = 60; // 60 seconds default
|
|
if (current_time - self.last_cleanup_time < cleanup_interval) {
|
|
return;
|
|
}
|
|
|
|
// Perform cleanup
|
|
self.replay_protector.forceCleanup();
|
|
self.last_cleanup_time = current_time;
|
|
|
|
// SEC-M7 FIX: Use std.log instead of debug.print for production
|
|
const stats = self.replay_protector.getStats();
|
|
std.log.debug("Replay protection cleanup: {d} messages, {d} nonces, {d} peers tracked", .{
|
|
stats.tracked_messages,
|
|
stats.tracked_nonces,
|
|
stats.tracked_peers,
|
|
});
|
|
}
|
|
|
|
/// Get replay protection statistics
|
|
pub fn getReplayStats(self: *HandlerRegistry) replay_protection.ReplayStats {
|
|
return self.replay_protector.getStats();
|
|
}
|
|
|
|
/// Reset replay state for a specific peer (useful for peer reconnection)
|
|
pub fn resetPeerReplayState(self: *HandlerRegistry, peer_id: message.NodeId) !void {
|
|
try self.replay_protector.resetPeerSequence(peer_id);
|
|
}
|
|
|
|
fn compareHandlerPriority(ctx: void, a: MessageHandler, b: MessageHandler) bool {
|
|
_ = ctx;
|
|
return a.priority > b.priority;
|
|
}
|
|
};
|
|
|
|
/// Discovery message handler
|
|
pub const DiscoveryHandler = struct {
|
|
/// Maximum tracked sources to prevent DoS via memory exhaustion
|
|
pub const MAX_TRACKED_SOURCES: usize = 5000;
|
|
|
|
/// Track last announce time per source for rate limiting
|
|
announce_timestamps: std.AutoHashMap([32]u8, i64),
|
|
allocator: std.mem.Allocator,
|
|
|
|
pub fn init(allocator: std.mem.Allocator) DiscoveryHandler {
|
|
return .{
|
|
.announce_timestamps = std.AutoHashMap([32]u8, i64).init(allocator),
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *DiscoveryHandler) void {
|
|
self.announce_timestamps.deinit();
|
|
}
|
|
|
|
/// Evict oldest 10% of entries to make room for new ones
|
|
fn evictOldestEntries(self: *DiscoveryHandler) void {
|
|
const count = self.announce_timestamps.count();
|
|
if (count == 0) return;
|
|
|
|
// Find and remove the oldest 10% of entries
|
|
const to_remove_count = @max(1, count / 10);
|
|
var removed: usize = 0;
|
|
var oldest_time: i64 = std.math.maxInt(i64);
|
|
var oldest_key: ?[32]u8 = null;
|
|
|
|
while (removed < to_remove_count) {
|
|
oldest_time = std.math.maxInt(i64);
|
|
oldest_key = null;
|
|
|
|
var iter = self.announce_timestamps.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (entry.value_ptr.* < oldest_time) {
|
|
oldest_time = entry.value_ptr.*;
|
|
oldest_key = entry.key_ptr.*;
|
|
}
|
|
}
|
|
|
|
if (oldest_key) |key| {
|
|
_ = self.announce_timestamps.remove(key);
|
|
removed += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn handleHello(self: *DiscoveryHandler, msg: message.DiscoveryHello, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.debug("Processing discovery hello from version {d} with capabilities {d}", .{
|
|
msg.version,
|
|
msg.capabilities,
|
|
});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Validate protocol version
|
|
const protocol_mod = @import("protocol.zig");
|
|
if (msg.version != protocol_mod.PROTOCOL_VERSION) {
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.warn("Protocol version mismatch: {d} vs {d}", .{
|
|
msg.version,
|
|
protocol_mod.PROTOCOL_VERSION,
|
|
});
|
|
}
|
|
|
|
// 2. Update peer list with capabilities
|
|
// Note: getPeerById returns a PeerInfo copy for thread safety.
|
|
// Capability updates should be done through a dedicated update method.
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const network = @import("network");
|
|
const peer_id = network.PeerId{ .bytes = source_id };
|
|
|
|
if (pm.getPeerById(peer_id)) |_| {
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.debug("Peer exists, received capabilities: relay={}, storage={}, discovery={}, routing={}", .{
|
|
(msg.capabilities & 0x01) != 0,
|
|
(msg.capabilities & 0x02) != 0,
|
|
(msg.capabilities & 0x04) != 0,
|
|
(msg.capabilities & 0x08) != 0,
|
|
});
|
|
}
|
|
}
|
|
|
|
// 3. Send DiscoveryResponse back
|
|
// CRIT-NEW-20 FIX: Only share peer list with authenticated/known peers
|
|
// This prevents network topology enumeration attacks
|
|
var known_peers: [8]message.NodeId = undefined;
|
|
var peer_count: usize = 0;
|
|
|
|
// CRIT-NEW-20 FIX: Check if source peer is already known (authenticated)
|
|
// Only share peer information with peers we already know about
|
|
var source_is_known = false;
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const network = @import("network");
|
|
const source_peer_id = network.PeerId{ .bytes = source_id };
|
|
source_is_known = pm.getPeerById(source_peer_id) != null;
|
|
}
|
|
|
|
// Collect known peers from peer manager ONLY if source is authenticated
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (source_is_known) {
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const peers = pm.getConnectedPeers() catch {
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.warn("Failed to get connected peers", .{});
|
|
return;
|
|
};
|
|
defer peers.deinit();
|
|
|
|
// CRIT-NEW-20 FIX: Only share a subset of peers (max 4) to limit exposure
|
|
const max_share: usize = 4;
|
|
for (peers.items) |peer_info| {
|
|
if (peer_count >= max_share) break;
|
|
// Don't share the requesting peer's own ID back to them
|
|
// SECURITY: Timing-safe comparison for peer ID
|
|
if (std.crypto.timing_safe.eql([32]u8, peer_info.id.bytes, source_id)) continue;
|
|
known_peers[peer_count] = peer_info.id.bytes;
|
|
peer_count += 1;
|
|
}
|
|
}
|
|
} else {
|
|
std.log.warn("SECURITY CRIT-NEW-20: Discovery request from unknown peer {x} - not sharing peer list", .{source_id[0..8].*});
|
|
}
|
|
|
|
// Create response with our capabilities
|
|
// IMP-M2 FIX: Use configured capabilities instead of hardcoded value
|
|
const our_caps: u32 = context.config.default_capabilities;
|
|
const our_addr = message.NetworkAddress{
|
|
.ip = [_]u8{0} ** protocol_mod.Network.ADDRESS_SIZE,
|
|
.port = 0,
|
|
};
|
|
|
|
const response = message.Message{
|
|
.discovery_response = message.DiscoveryResponse{
|
|
.original_id = 0, // Will be set by router
|
|
.capabilities = our_caps,
|
|
.address = our_addr,
|
|
.known_nodes = known_peers[0..peer_count],
|
|
},
|
|
};
|
|
|
|
// Send response back to source peer
|
|
context.sendResponse(source_id, response) catch |err| {
|
|
std.log.warn("Failed to send DiscoveryResponse to peer: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
std.log.info("Sent DiscoveryResponse with {d} known peers", .{peer_count});
|
|
}
|
|
|
|
pub fn handleResponse(self: *DiscoveryHandler, msg: message.DiscoveryResponse, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.debug("Processing discovery response with {d} known nodes", .{
|
|
msg.known_nodes.len,
|
|
});
|
|
|
|
// 1. Add known nodes to peer list
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const core = @import("core");
|
|
|
|
for (msg.known_nodes) |_| {
|
|
// Create address from node ID (simplified - in production would use proper addressing)
|
|
var addr = core.Address.init();
|
|
// IMP-M1 FIX: Use configured port instead of hardcoded value
|
|
addr.port = context.config.default_discovery_port;
|
|
|
|
// Try to add peer if not already known
|
|
_ = pm.addPeer(addr) catch |err| {
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
// ERR-M2 FIX: Record failure in metrics for aggregation
|
|
std.log.debug("Could not add peer from discovery: {}", .{err});
|
|
context.metrics.recordPeerAdditionFailed();
|
|
continue;
|
|
};
|
|
}
|
|
}
|
|
|
|
// 2. Update routing table with known nodes
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getRoutingTable() catch null) |rt| {
|
|
const network = @import("network");
|
|
|
|
for (msg.known_nodes) |node_id| {
|
|
const peer_id = network.PeerId{ .bytes = node_id };
|
|
rt.addPeer(peer_id) catch |err| {
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.debug("Could not add peer to routing table: {}", .{err});
|
|
};
|
|
}
|
|
}
|
|
|
|
// SEC-M7 FIX: Use std.log instead of debug.print
|
|
std.log.debug("Added {d} known nodes from discovery response", .{msg.known_nodes.len});
|
|
}
|
|
|
|
/// CRIT-NEW-12 FIX: Constants for discovery amplification protection
|
|
pub const MAX_ANNOUNCE_TTL: u8 = 3; // Max allowed TTL (was unlimited)
|
|
pub const MAX_FORWARD_PEERS: usize = 5; // Max peers to forward to (limit fan-out)
|
|
pub const ANNOUNCE_RATE_LIMIT_MS: i64 = 1000; // Min time between announces from same source
|
|
|
|
pub fn handleAnnounce(self: *DiscoveryHandler, msg: message.DiscoveryAnnounce, context: *HandlerContext) !void {
|
|
std.log.debug("Processing discovery announce with capabilities {d}, TTL {d}", .{
|
|
msg.capabilities,
|
|
msg.ttl,
|
|
});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// CRIT-NEW-12 FIX: Enforce max TTL to limit amplification
|
|
if (msg.ttl > MAX_ANNOUNCE_TTL) {
|
|
std.log.warn("SECURITY CRIT-NEW-12: Discovery announce TTL {} exceeds max {}, clamping", .{ 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)
|
|
const now = std.time.milliTimestamp();
|
|
if (self.announce_timestamps.get(source_id)) |last_time| {
|
|
if (now - last_time < ANNOUNCE_RATE_LIMIT_MS) {
|
|
std.log.warn("SECURITY: Rate limiting discovery announce from source ({}ms since last)", .{now - last_time});
|
|
return; // Silently drop rate-limited announces
|
|
}
|
|
}
|
|
// Enforce size limit to prevent DoS via memory exhaustion
|
|
if (self.announce_timestamps.count() >= MAX_TRACKED_SOURCES) {
|
|
// Evict oldest entries to make room
|
|
self.evictOldestEntries();
|
|
}
|
|
try self.announce_timestamps.put(source_id, now);
|
|
|
|
// 1. Add announcing node to peer list (always process locally, regardless of TTL)
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const network = @import("network");
|
|
const peer_id = network.PeerId{ .bytes = source_id };
|
|
const core = @import("core");
|
|
|
|
// Check if peer exists (getPeerById returns a copy for thread safety)
|
|
if (pm.getPeerById(peer_id)) |_| {
|
|
// Peer exists - log capability update
|
|
std.log.debug("Peer exists, received announce with capabilities: relay={}, storage={}, discovery={}, routing={}", .{
|
|
(msg.capabilities & 0x01) != 0,
|
|
(msg.capabilities & 0x02) != 0,
|
|
(msg.capabilities & 0x04) != 0,
|
|
(msg.capabilities & 0x08) != 0,
|
|
});
|
|
} else {
|
|
// Create new peer from address
|
|
var addr = core.Address.init();
|
|
addr.port = msg.address.port;
|
|
for (msg.address.ip, 0..) |byte, i| {
|
|
if (i < addr.ip.len) addr.ip[i] = byte;
|
|
}
|
|
|
|
_ = pm.addPeer(addr) catch |err| {
|
|
std.log.debug("Could not add announcing peer: {}", .{err});
|
|
};
|
|
}
|
|
}
|
|
|
|
// 2. Update network topology
|
|
if (context.topology) |_| {
|
|
// Topology updates would go here
|
|
std.log.debug("Updated topology with announcing peer", .{});
|
|
}
|
|
|
|
// SEC-3 FIX: Check TTL to prevent amplification attacks
|
|
// CRIT-NEW-12 FIX: Use clamped TTL for propagation decision
|
|
if (effective_ttl == 0) {
|
|
std.log.debug("Not propagating discovery announce: TTL expired", .{});
|
|
return;
|
|
}
|
|
|
|
// 3. Propagate announce to other connected peers (excluding source) with decremented TTL
|
|
// SEC-3 FIX: Decrement TTL before forwarding to prevent infinite propagation
|
|
var forwarded_msg = msg;
|
|
// CRIT-NEW-12 FIX: Override TTL with clamped value before decrementing
|
|
forwarded_msg.ttl = effective_ttl;
|
|
if (!forwarded_msg.decrementTtl()) {
|
|
std.log.debug("Not propagating discovery announce: TTL exhausted after decrement", .{});
|
|
return;
|
|
}
|
|
|
|
const announce_msg = message.Message{
|
|
.discovery_announce = forwarded_msg,
|
|
};
|
|
|
|
// CRIT-NEW-12 FIX: Use limited broadcast to cap fan-out
|
|
// This limits amplification by only forwarding to MAX_FORWARD_PEERS peers
|
|
const sent_count = context.broadcastLimited(announce_msg, source_id, MAX_FORWARD_PEERS) catch |err| {
|
|
// Fall back to regular broadcast if limited version not available
|
|
_ = context.broadcast(announce_msg, source_id) catch |broadcast_err| {
|
|
std.log.warn("Failed to broadcast announce: {}", .{broadcast_err});
|
|
return;
|
|
};
|
|
std.log.debug("Limited broadcast unavailable: {}", .{err});
|
|
return;
|
|
};
|
|
|
|
std.log.info("CRIT-NEW-12: Propagated discovery announce to {d} peers (max {d}, TTL now {d})", .{
|
|
sent_count,
|
|
MAX_FORWARD_PEERS,
|
|
forwarded_msg.ttl,
|
|
});
|
|
}
|
|
};
|
|
|
|
/// Topology message handler
|
|
pub const TopologyHandler = struct {
|
|
pub fn init() TopologyHandler {
|
|
return .{};
|
|
}
|
|
|
|
pub fn handleQuery(self: *TopologyHandler, msg: message.TopologyQuery, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing topology query {d} for type {d}", .{
|
|
msg.query_id,
|
|
msg.topology_type,
|
|
});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Collect local topology information - get connected peers
|
|
var nodes: [16]message.NodeId = undefined;
|
|
var node_count: usize = 0;
|
|
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const peers = pm.getConnectedPeers() catch {
|
|
std.log.warn("Failed to get connected peers for topology query", .{});
|
|
return error.PeerManagerError;
|
|
};
|
|
defer peers.deinit();
|
|
|
|
for (peers.items) |peer_info| {
|
|
if (node_count >= 16) break;
|
|
nodes[node_count] = peer_info.id.bytes;
|
|
node_count += 1;
|
|
}
|
|
}
|
|
|
|
// 2. Send topology response
|
|
const response = message.Message{
|
|
.topology_response = message.TopologyResponse{
|
|
.query_id = msg.query_id,
|
|
.topology_type = msg.topology_type,
|
|
.nodes = nodes[0..node_count],
|
|
.update_sequence = 0, // Current sequence
|
|
},
|
|
};
|
|
|
|
context.sendResponse(source_id, response) catch |err| {
|
|
std.log.warn("Failed to send TopologyResponse: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
std.log.info("Sent TopologyResponse with {d} nodes", .{node_count});
|
|
}
|
|
|
|
pub fn handleResponse(self: *TopologyHandler, msg: message.TopologyResponse, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing topology response for query {d} with {d} nodes", .{
|
|
msg.query_id,
|
|
msg.nodes.len,
|
|
});
|
|
|
|
// 1. Update routing table with received nodes
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getRoutingTable() catch null) |rt| {
|
|
const network = @import("network");
|
|
|
|
for (msg.nodes) |node_id| {
|
|
const peer_id = network.PeerId{ .bytes = node_id };
|
|
rt.addPeer(peer_id) catch |err| {
|
|
std.log.debug("Could not add node to routing table: {}", .{err});
|
|
};
|
|
}
|
|
}
|
|
|
|
std.log.info("Updated topology with {d} nodes from response", .{msg.nodes.len});
|
|
}
|
|
|
|
pub fn handleUpdate(self: *TopologyHandler, msg: message.TopologyUpdate, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing topology update sequence {d} with TTL {d}", .{
|
|
msg.sequence,
|
|
msg.ttl,
|
|
});
|
|
|
|
// SEC-2 FIX: Check TTL to prevent amplification attacks
|
|
if (msg.ttl == 0) {
|
|
std.log.debug("Dropping topology update sequence {d}: TTL expired", .{msg.sequence});
|
|
return;
|
|
}
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Apply topology changes to routing table
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getRoutingTable() catch null) |rt| {
|
|
const network = @import("network");
|
|
|
|
// Add new nodes from the update
|
|
for (msg.added_nodes) |node_id| {
|
|
const peer_id = network.PeerId{ .bytes = node_id };
|
|
rt.addPeer(peer_id) catch |err| {
|
|
std.log.debug("Could not add node from topology update: {}", .{err});
|
|
};
|
|
}
|
|
|
|
// Remove departed nodes
|
|
for (msg.removed_nodes) |node_id| {
|
|
const peer_id = network.PeerId{ .bytes = node_id };
|
|
rt.removePeer(peer_id) catch |err| {
|
|
std.log.debug("Could not remove node from topology update: {}", .{err});
|
|
};
|
|
}
|
|
}
|
|
|
|
// 2. Forward update to other connected peers (excluding source) with decremented TTL
|
|
// SEC-2 FIX: Decrement TTL before forwarding to prevent infinite propagation
|
|
var forwarded_msg = msg;
|
|
if (!forwarded_msg.decrementTtl()) {
|
|
std.log.debug("Not forwarding topology update sequence {d}: TTL exhausted after decrement", .{msg.sequence});
|
|
return;
|
|
}
|
|
|
|
const update_msg = message.Message{
|
|
.topology_update = forwarded_msg,
|
|
};
|
|
|
|
const sent_count = context.broadcast(update_msg, source_id) catch |err| {
|
|
std.log.warn("Failed to forward topology update: {}", .{err});
|
|
return;
|
|
};
|
|
|
|
std.log.info("Forwarded topology update sequence {d} to {d} peers (TTL now {d})", .{ msg.sequence, sent_count, forwarded_msg.ttl });
|
|
}
|
|
};
|
|
|
|
/// Data message handler
|
|
pub const DataHandler = struct {
|
|
pub fn init() DataHandler {
|
|
return .{};
|
|
}
|
|
|
|
pub fn handleRequest(self: *DataHandler, msg: message.DataRequest, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing data request {d} for piece {d} at offset {d} size {d}", .{
|
|
msg.request_id,
|
|
msg.piece_index,
|
|
msg.offset,
|
|
msg.size,
|
|
});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Check if we have the file manager and can serve the data
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getFileManager() catch null) |fm| {
|
|
// Try to get the piece data
|
|
const piece_data = fm.getPieceData(msg.data_id, msg.piece_index) catch |err| {
|
|
// Send error response
|
|
const error_response = message.Message{
|
|
.error_msg = message.Error{
|
|
.error_code = .data_not_found,
|
|
.original_id = msg.request_id,
|
|
.message = "Data not available",
|
|
},
|
|
};
|
|
context.sendResponse(source_id, error_response) catch |send_err| {
|
|
std.log.err("Failed to send error response for missing piece: {}", .{send_err});
|
|
// MED-7 FIX: Track error for metrics
|
|
context.metrics.recordMessageFailed();
|
|
};
|
|
std.log.warn("Data request failed, piece not found: {}", .{err});
|
|
return;
|
|
};
|
|
defer context.allocator.free(piece_data);
|
|
|
|
// 2. Send data response with the piece data
|
|
const response = message.Message{
|
|
.data_response = message.DataResponse{
|
|
.request_id = msg.request_id,
|
|
.data_id = msg.data_id,
|
|
.piece_index = msg.piece_index,
|
|
.data = piece_data,
|
|
.is_final = true,
|
|
},
|
|
};
|
|
|
|
context.sendResponse(source_id, response) catch |err| {
|
|
std.log.warn("Failed to send DataResponse: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
std.log.info("Sent data response for piece {d}", .{msg.piece_index});
|
|
} else {
|
|
// No file manager - send error
|
|
const error_response = message.Message{
|
|
.error_msg = message.Error{
|
|
.error_code = .service_unavailable,
|
|
.original_id = msg.request_id,
|
|
.message = "File service not available",
|
|
},
|
|
};
|
|
context.sendResponse(source_id, error_response) catch |err| {
|
|
std.log.err("Failed to send service unavailable error: {}", .{err});
|
|
// MED-7 FIX: Track error for metrics
|
|
context.metrics.recordMessageFailed();
|
|
};
|
|
}
|
|
}
|
|
|
|
pub fn handleResponse(self: *DataHandler, msg: message.DataResponse, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing data response for request {d}, piece {d}", .{
|
|
msg.request_id,
|
|
msg.piece_index,
|
|
});
|
|
|
|
// 1. Deliver data to file manager for storage
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getFileManager() catch null) |fm| {
|
|
// Write the received piece data
|
|
fm.writePieceData(msg.data_id, msg.piece_index, msg.data) catch |err| {
|
|
std.log.warn("Failed to write piece data: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
std.log.info("Stored piece {d} from data response", .{msg.piece_index});
|
|
}
|
|
|
|
// 2. Update metrics
|
|
context.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
|
|
pub fn handleChunk(self: *DataHandler, msg: message.DataChunk, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing data chunk {d} for data {any} (final: {})", .{
|
|
msg.sequence,
|
|
msg.data_id,
|
|
msg.is_final,
|
|
});
|
|
|
|
// 1. Deliver chunk to file manager for reassembly
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getFileManager() catch null) |fm| {
|
|
// Add chunk to reassembly buffer
|
|
fm.addChunk(msg.data_id, msg.sequence, msg.data, msg.is_final) catch |err| {
|
|
std.log.warn("Failed to process chunk: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
if (msg.is_final) {
|
|
std.log.info("Completed chunk reassembly for data", .{});
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
/// Control message handler
|
|
pub const ControlHandler = struct {
|
|
pub fn init() ControlHandler {
|
|
return .{};
|
|
}
|
|
|
|
pub fn handlePing(self: *ControlHandler, msg: message.Ping, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
std.log.debug("Processing ping sequence {d}", .{msg.sequence});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Calculate current timestamp for RTT calculation
|
|
const current_time = std.time.milliTimestamp();
|
|
const rtt: u32 = if (msg.timestamp > 0)
|
|
@intCast(@as(u64, @intCast(current_time)) -| msg.timestamp)
|
|
else
|
|
0;
|
|
|
|
// 2. Send pong response with RTT
|
|
const pong_response = message.Message{
|
|
.pong = message.Pong{
|
|
.sequence = msg.sequence,
|
|
.rtt = rtt,
|
|
.timestamp = @intCast(@as(u64, @intCast(current_time))),
|
|
},
|
|
};
|
|
|
|
context.sendResponse(source_id, pong_response) catch |err| {
|
|
std.log.warn("Failed to send Pong response: {}", .{err});
|
|
return err;
|
|
};
|
|
|
|
// 3. Update peer activity in peer manager
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const network = @import("network");
|
|
const peer_id = network.PeerId{ .bytes = source_id };
|
|
|
|
// getPeerById returns a copy, activity is updated via updatePeerActivity if available
|
|
if (pm.getPeerById(peer_id)) |_| {
|
|
std.log.debug("Peer is active, ping received", .{});
|
|
}
|
|
}
|
|
|
|
std.log.info("Sent pong response for ping sequence {d}", .{msg.sequence});
|
|
}
|
|
|
|
pub fn handlePong(self: *ControlHandler, msg: message.Pong, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
// SEC-M3 FIX: Reduce information disclosure - only log at debug level
|
|
// and avoid logging exact RTT values that could enable timing attacks
|
|
std.log.debug("Processing pong sequence {d}", .{msg.sequence});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Update peer RTT metrics in peer manager
|
|
// MEM-M1 FIX: Use type-safe getter instead of direct cast
|
|
if (context.getPeerManager() catch null) |pm| {
|
|
const network = @import("network");
|
|
const peer_id = network.PeerId{ .bytes = source_id };
|
|
|
|
if (pm.getPeerById(peer_id)) |_| {
|
|
// SEC-M3 FIX: Log RTT at debug level only, not info
|
|
std.log.debug("Pong received from peer", .{});
|
|
}
|
|
}
|
|
|
|
// 2. Record successful ping-pong for metrics (internal only)
|
|
context.metrics.recordMessageProcessed(@as(f64, @floatFromInt(msg.rtt)));
|
|
}
|
|
|
|
pub fn handleError(self: *ControlHandler, msg: message.Error, context: *HandlerContext) !void {
|
|
_ = self;
|
|
|
|
// SEC-M4 FIX: Sanitize error message logging to prevent log injection
|
|
// and avoid exposing internal state
|
|
const original_id_str = if (msg.original_id) |id| @as(u64, id) else 0;
|
|
|
|
// Truncate message to reasonable length and filter control characters
|
|
const max_msg_len = 256;
|
|
const safe_msg_len = @min(msg.message.len, max_msg_len);
|
|
var safe_msg: [max_msg_len]u8 = undefined;
|
|
for (msg.message[0..safe_msg_len], 0..) |c, i| {
|
|
// Replace control characters and non-printable chars with '?'
|
|
safe_msg[i] = if (c >= 0x20 and c < 0x7F) c else '?';
|
|
}
|
|
|
|
std.log.err("Received error code={} for message {d}", .{
|
|
msg.error_code,
|
|
original_id_str,
|
|
});
|
|
|
|
// 1. Record error in metrics
|
|
context.metrics.recordMessageFailed();
|
|
|
|
// 2. Log sanitized error for debugging (no peer ID to prevent correlation)
|
|
std.log.debug("Error details (truncated): {s}", .{safe_msg[0..safe_msg_len]});
|
|
|
|
// 3. Handle specific error types
|
|
switch (msg.error_code) {
|
|
.protocol_violation => {
|
|
std.log.err("Protocol violation detected - may need to disconnect peer", .{});
|
|
},
|
|
.rate_limited => {
|
|
std.log.warn("Rate limited by peer - reducing request rate", .{});
|
|
},
|
|
.authentication_failed => {
|
|
std.log.err("Authentication failed - check credentials", .{});
|
|
},
|
|
else => {
|
|
std.log.debug("Unhandled error code: {any}", .{msg.error_code});
|
|
},
|
|
}
|
|
}
|
|
};
|
|
|
|
/// Application message handler
|
|
pub const AppHandler = struct {
|
|
/// Application callback function type
|
|
pub const AppCallback = *const fn (app_id: u32, data: []const u8, context: ?*anyopaque) void;
|
|
|
|
/// Registered application callbacks
|
|
app_callbacks: std.AutoHashMap(u32, AppCallback) = undefined,
|
|
callback_contexts: std.AutoHashMap(u32, ?*anyopaque) = undefined,
|
|
allocator: std.mem.Allocator = undefined,
|
|
initialized: bool = false,
|
|
mutex: std.Thread.Mutex = .{},
|
|
|
|
pub fn init() AppHandler {
|
|
return .{};
|
|
}
|
|
|
|
pub fn initWithAllocator(allocator: std.mem.Allocator) AppHandler {
|
|
return .{
|
|
.app_callbacks = std.AutoHashMap(u32, AppCallback).init(allocator),
|
|
.callback_contexts = std.AutoHashMap(u32, ?*anyopaque).init(allocator),
|
|
.allocator = allocator,
|
|
.initialized = true,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *AppHandler) void {
|
|
// SEC-M6 FIX: Use mutex to prevent race with handleAppData
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
if (self.initialized) {
|
|
self.initialized = false; // Mark as uninitialized first
|
|
self.app_callbacks.deinit();
|
|
self.callback_contexts.deinit();
|
|
}
|
|
}
|
|
|
|
/// Register an application callback
|
|
/// THR-H5 FIX: Check initialized inside mutex to prevent race with deinit()
|
|
pub fn registerApp(self: *AppHandler, app_id: u32, callback: AppCallback, ctx: ?*anyopaque) !void {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
if (!self.initialized) return error.NotInitialized;
|
|
try self.app_callbacks.put(app_id, callback);
|
|
try self.callback_contexts.put(app_id, ctx);
|
|
}
|
|
|
|
/// Unregister an application
|
|
/// THR-H5 FIX: Check initialized inside mutex to prevent race with deinit()
|
|
pub fn unregisterApp(self: *AppHandler, app_id: u32) void {
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
if (!self.initialized) return;
|
|
_ = self.app_callbacks.remove(app_id);
|
|
_ = self.callback_contexts.remove(app_id);
|
|
}
|
|
|
|
pub fn handleAppData(self: *AppHandler, msg: message.AppData, context: *HandlerContext) !void {
|
|
std.log.debug("Processing app data for app {d}: {d} bytes", .{
|
|
msg.app_id,
|
|
msg.data.len,
|
|
});
|
|
|
|
// 1. Route to registered application callback
|
|
// SEC-M6 FIX: Check initialized AND copy callback while holding lock to prevent race
|
|
// where deinit() could set initialized=false while we're in this function
|
|
var callback_copy: ?*const fn (u32, []const u8, ?*anyopaque) void = null;
|
|
var context_copy: ?*anyopaque = null;
|
|
|
|
{
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
|
|
// Check initialized inside lock to prevent race with deinit
|
|
if (self.initialized) {
|
|
if (self.app_callbacks.get(msg.app_id)) |cb| {
|
|
callback_copy = cb;
|
|
context_copy = self.callback_contexts.get(msg.app_id) orelse null;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Now call callback WITHOUT holding lock (prevents deadlock if callback re-enters)
|
|
if (callback_copy) |callback| {
|
|
callback(msg.app_id, msg.data, context_copy);
|
|
std.log.debug("Delivered {d} bytes to app {d}", .{ msg.data.len, msg.app_id });
|
|
} else {
|
|
std.log.warn("No handler registered for app {d}", .{msg.app_id});
|
|
}
|
|
|
|
// 2. Update metrics
|
|
context.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
|
|
pub fn handleAppControl(self: *AppHandler, msg: message.AppControl, context: *HandlerContext) !void {
|
|
std.log.debug("Processing app control for app {d} command {d}", .{
|
|
msg.app_id,
|
|
msg.command,
|
|
});
|
|
|
|
const source_id = context.source_peer_id orelse return error.InvalidMessage;
|
|
|
|
// 1. Process control commands
|
|
switch (msg.command) {
|
|
0 => {
|
|
// Command 0: Status query - respond with app status
|
|
std.log.debug("App status query for app {d}", .{msg.app_id});
|
|
|
|
const response = message.Message{
|
|
.app_control = message.AppControl{
|
|
.app_id = msg.app_id,
|
|
.command = 1, // Response command
|
|
.params = &[_]u8{1}, // Status: OK
|
|
},
|
|
};
|
|
|
|
context.sendResponse(source_id, response) catch |err| {
|
|
std.log.warn("Failed to send app control response: {}", .{err});
|
|
// MED-7 FIX: Track error for metrics
|
|
context.metrics.recordMessageFailed();
|
|
};
|
|
},
|
|
1 => {
|
|
// Command 1: Response - process response
|
|
std.log.debug("App control response for app {d}", .{msg.app_id});
|
|
},
|
|
else => {
|
|
std.log.warn("Unknown app control command {d} for app {d}", .{ msg.command, msg.app_id });
|
|
},
|
|
}
|
|
|
|
// 2. Notify registered callback if any
|
|
// THR-H5 FIX: Check initialized inside mutex to prevent race with deinit()
|
|
var callback_copy: ?AppCallback = null;
|
|
var context_copy: ?*anyopaque = null;
|
|
{
|
|
self.mutex.lock();
|
|
defer self.mutex.unlock();
|
|
if (self.initialized) {
|
|
callback_copy = self.app_callbacks.get(msg.app_id);
|
|
if (callback_copy != null) {
|
|
context_copy = self.callback_contexts.get(msg.app_id) orelse null;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Call callback outside lock to prevent deadlock
|
|
if (callback_copy) |callback| {
|
|
callback(msg.app_id, msg.params, context_copy);
|
|
}
|
|
|
|
context.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
};
|
|
|
|
/// Handler builder for easy handler registration
|
|
pub const HandlerBuilder = struct {
|
|
registry: *HandlerRegistry,
|
|
discovery_handler: DiscoveryHandler,
|
|
topology_handler: TopologyHandler,
|
|
data_handler: DataHandler,
|
|
control_handler: ControlHandler,
|
|
app_handler: AppHandler,
|
|
|
|
pub fn init(registry: *HandlerRegistry) HandlerBuilder {
|
|
return .{
|
|
.registry = registry,
|
|
.discovery_handler = DiscoveryHandler.init(),
|
|
.topology_handler = TopologyHandler.init(),
|
|
.data_handler = DataHandler.init(),
|
|
.control_handler = ControlHandler.init(),
|
|
.app_handler = AppHandler.init(),
|
|
};
|
|
}
|
|
|
|
/// MEM-M7 FIX: Add deinit to clean up AppHandler
|
|
/// This must be called when the HandlerBuilder is no longer needed
|
|
pub fn deinit(self: *HandlerBuilder) void {
|
|
// AppHandler is the only handler with allocations that need cleanup
|
|
self.app_handler.deinit();
|
|
}
|
|
|
|
/// Register all default handlers
|
|
pub fn registerDefaultHandlers(self: *HandlerBuilder) !void {
|
|
const context = self.registry.getContext();
|
|
|
|
// Discovery handlers
|
|
try self.registerDiscoveryHandlers(context);
|
|
|
|
// Topology handlers
|
|
try self.registerTopologyHandlers(context);
|
|
|
|
// Data handlers
|
|
try self.registerDataHandlers(context);
|
|
|
|
// Control handlers
|
|
try self.registerControlHandlers(context);
|
|
|
|
// Application handlers
|
|
try self.registerAppHandlers(context);
|
|
|
|
// DHT handlers for distributed peer discovery
|
|
try self.registerDhtHandlers(context);
|
|
}
|
|
|
|
/// IMP-H1 NOTE: These are DEFAULT/FALLBACK handlers that only record metrics.
|
|
/// Real implementations in handler_impl.zig should be used for production.
|
|
/// These defaults allow the system to start without crashing on unhandled messages.
|
|
fn registerDiscoveryHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
const hello_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Process discovery hello - update metrics
|
|
_ = msg.discovery_hello.version;
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.discovery_hello,
|
|
);
|
|
|
|
const response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(_: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Discovery response updates peer state
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.discovery_response,
|
|
);
|
|
|
|
try self.registry.registerHandler(.discovery_hello, hello_handler);
|
|
try self.registry.registerHandler(.discovery_response, response_handler);
|
|
}
|
|
|
|
fn registerTopologyHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
const query_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Handle topology query - record metrics
|
|
_ = msg.topology_query.source_id;
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.topology_query,
|
|
);
|
|
|
|
try self.registry.registerHandler(.topology_query, query_handler);
|
|
}
|
|
|
|
fn registerDataHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
const request_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Handle data request - record metrics
|
|
_ = msg.data_request.piece_index;
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.data_request,
|
|
);
|
|
|
|
try self.registry.registerHandler(.data_request, request_handler);
|
|
|
|
// CRIT-1 FIX: Register data_response handler to properly handle file transfer responses
|
|
// This handler uses the RequestTracker to map request_ids to piece information,
|
|
// preventing file corruption and enabling safe concurrent downloads.
|
|
const response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
const data_resp = msg.data_response;
|
|
|
|
// Get the request tracker to resolve request_id -> piece info
|
|
const request_tracker = context_ptr.request_tracker orelse {
|
|
std.log.err("CRITICAL: DataResponse received without RequestTracker configured!", .{});
|
|
std.log.err("Please ensure HandlerRegistry.init() is called to initialize the RequestTracker.", .{});
|
|
context_ptr.metrics.recordMessageFailed();
|
|
return error.RequestTrackerNotConfigured;
|
|
};
|
|
|
|
// Use the callback to handle the data response
|
|
// This callback is set by the P2P layer which has access to the file manager
|
|
const data_handler = context_ptr.data_response_handler orelse {
|
|
std.log.err("CRITICAL: DataResponse handler callback not configured!", .{});
|
|
std.log.err("The P2P layer must call setDataResponseHandler() during initialization.", .{});
|
|
context_ptr.metrics.recordMessageFailed();
|
|
return error.DataResponseHandlerNotConfigured;
|
|
};
|
|
|
|
try data_handler.handle(request_tracker, data_resp, context_ptr.metrics);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.data_response,
|
|
);
|
|
|
|
try self.registry.registerHandler(.data_response, response_handler);
|
|
}
|
|
|
|
fn registerControlHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
const ping_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Simple ping handling - update metrics
|
|
_ = msg.ping.sequence;
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.ping,
|
|
);
|
|
|
|
try self.registry.registerHandler(.ping, ping_handler);
|
|
}
|
|
|
|
fn registerAppHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
const app_data_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
// Forward app data to registered callbacks
|
|
_ = msg.app_data;
|
|
context_ptr.metrics.recordMessageProcessed(0.0);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.app_data,
|
|
);
|
|
|
|
try self.registry.registerHandler(.app_data, app_data_handler);
|
|
}
|
|
|
|
/// Register DHT message handlers for distributed peer discovery
|
|
/// These handlers call the real implementations in handler_impl.zig
|
|
fn registerDhtHandlers(self: *HandlerBuilder, context: *HandlerContext) !void {
|
|
// DHT FIND_NODE handler
|
|
const find_node_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtFindNode(msg.dht_find_node, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_node,
|
|
);
|
|
|
|
// DHT FIND_NODE_RESPONSE handler
|
|
const find_node_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtFindNodeResponse(msg.dht_find_node_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_node_response,
|
|
);
|
|
|
|
// DHT STORE handler
|
|
const store_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtStore(msg.dht_store, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_store,
|
|
);
|
|
|
|
// DHT STORE_RESPONSE handler
|
|
const store_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtStoreResponse(msg.dht_store_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_store_response,
|
|
);
|
|
|
|
// DHT FIND_VALUE handler
|
|
const find_value_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtFindValue(msg.dht_find_value, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_value,
|
|
);
|
|
|
|
// DHT FIND_VALUE_RESPONSE handler
|
|
const find_value_response_handler = MessageHandler.init(
|
|
struct {
|
|
fn handler(msg: message.Message, ctx: *anyopaque) !void {
|
|
const context_ptr = @as(*HandlerContext, @ptrCast(@alignCast(ctx)));
|
|
try handler_impl.handleDhtFindValueResponse(msg.dht_find_value_response, context_ptr);
|
|
}
|
|
}.handler,
|
|
context,
|
|
.dht_find_value_response,
|
|
);
|
|
|
|
// Register all DHT handlers
|
|
try self.registry.registerHandler(.dht_find_node, find_node_handler);
|
|
try self.registry.registerHandler(.dht_find_node_response, find_node_response_handler);
|
|
try self.registry.registerHandler(.dht_store, store_handler);
|
|
try self.registry.registerHandler(.dht_store_response, store_response_handler);
|
|
try self.registry.registerHandler(.dht_find_value, find_value_handler);
|
|
try self.registry.registerHandler(.dht_find_value_response, find_value_response_handler);
|
|
}
|
|
};
|
|
|
|
/// Async message processor for handling messages asynchronously
|
|
pub const AsyncMessageProcessor = struct {
|
|
allocator: std.mem.Allocator,
|
|
registry: *HandlerRegistry,
|
|
queue: std.ArrayList(message.Message),
|
|
queue_mutex: std.Thread.Mutex,
|
|
workers: std.ArrayList(std.Thread),
|
|
shutdown: std.atomic.Value(bool),
|
|
/// CRIT-NEW-11 FIX: Per-source message counts for backpressure
|
|
per_source_counts: std.AutoHashMap([32]u8, u32),
|
|
/// CRIT-NEW-11 FIX: Track rejected messages for metrics
|
|
rejected_count: std.atomic.Value(u64),
|
|
/// CRIT-NEW-11 FIX: Track backpressure events
|
|
backpressure_events: std.atomic.Value(u64),
|
|
|
|
/// CRIT-NEW-11 FIX: Backpressure threshold (80% of max)
|
|
// MED-12 FIX: Start backpressure earlier (60%) to allow more time for queue draining
|
|
pub const BACKPRESSURE_THRESHOLD: usize = HandlerLimits.MAX_PENDING_MESSAGES * 60 / 100;
|
|
/// CRIT-NEW-11 FIX: Per-source limit during backpressure
|
|
pub const PER_SOURCE_LIMIT: u32 = 100;
|
|
|
|
pub fn init(allocator: std.mem.Allocator, registry: *HandlerRegistry) AsyncMessageProcessor {
|
|
return .{
|
|
.allocator = allocator,
|
|
.registry = registry,
|
|
.queue = .{},
|
|
.queue_mutex = .{},
|
|
.workers = .{},
|
|
.shutdown = std.atomic.Value(bool).init(false),
|
|
.per_source_counts = std.AutoHashMap([32]u8, u32).init(allocator),
|
|
.rejected_count = std.atomic.Value(u64).init(0),
|
|
.backpressure_events = std.atomic.Value(u64).init(0),
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *AsyncMessageProcessor) void {
|
|
self.shutdown.store(true, .monotonic);
|
|
|
|
// Wait for workers to finish
|
|
for (self.workers.items) |worker| {
|
|
worker.join();
|
|
}
|
|
|
|
self.workers.deinit(self.allocator);
|
|
self.queue.deinit(self.allocator);
|
|
// CRIT-NEW-11 FIX: Clean up per-source tracking
|
|
self.per_source_counts.deinit();
|
|
}
|
|
|
|
/// Start worker threads
|
|
/// Returns error if no workers could be started (critical failure)
|
|
pub fn startWorkers(self: *AsyncMessageProcessor, num_workers: usize) !void {
|
|
var started: usize = 0;
|
|
var spawn_failures: usize = 0;
|
|
|
|
for (0..num_workers) |_| {
|
|
const worker = std.Thread.spawn(.{}, workerThread, .{self}) catch |err| {
|
|
std.log.err("Failed to spawn worker thread: {}", .{err});
|
|
spawn_failures += 1;
|
|
continue;
|
|
};
|
|
self.workers.append(self.allocator, worker) catch |err| {
|
|
std.log.err("Failed to track worker thread: {}", .{err});
|
|
worker.join();
|
|
continue;
|
|
};
|
|
started += 1;
|
|
}
|
|
|
|
// SECURITY: Log worker count and fail if none started
|
|
if (started == 0 and num_workers > 0) {
|
|
std.log.err("CRITICAL: Failed to start any worker threads ({} spawn failures)", .{spawn_failures});
|
|
return error.ThreadSpawnFailed;
|
|
}
|
|
|
|
if (started < num_workers) {
|
|
std.log.warn("Only started {}/{} worker threads ({} failures)", .{ started, num_workers, spawn_failures });
|
|
}
|
|
}
|
|
|
|
/// Queue a message for processing
|
|
/// CRIT-NEW-11 FIX: Implements backpressure when queue approaches capacity
|
|
/// source_id: Optional source peer ID for backpressure tracking (null = anonymous tracking by type)
|
|
pub fn queueMessage(self: *AsyncMessageProcessor, msg: message.Message) !void {
|
|
// Call with null source_id for backwards compatibility
|
|
return self.queueMessageWithSource(msg, null);
|
|
}
|
|
|
|
/// Queue a message with explicit source tracking
|
|
/// CRIT-NEW-11 FIX: Implements per-source backpressure when queue approaches capacity
|
|
pub fn queueMessageWithSource(self: *AsyncMessageProcessor, msg: message.Message, source_id: ?[32]u8) !void {
|
|
self.queue_mutex.lock();
|
|
defer self.queue_mutex.unlock();
|
|
|
|
// SECURITY: Check queue size limit to prevent memory exhaustion
|
|
if (self.queue.items.len >= HandlerLimits.MAX_PENDING_MESSAGES) {
|
|
_ = self.rejected_count.fetchAdd(1, .monotonic);
|
|
std.log.warn("CRIT-NEW-11: Message queue full ({} messages), rejecting message", .{self.queue.items.len});
|
|
return error.QueueFull;
|
|
}
|
|
|
|
// CRIT-NEW-11 FIX: Implement backpressure when approaching capacity
|
|
// When queue is >80% full, apply per-source limits to prevent flooding
|
|
if (self.queue.items.len >= BACKPRESSURE_THRESHOLD) {
|
|
// Use provided source_id, or generate one from message type (for anonymous tracking)
|
|
const tracking_id = source_id orelse blk: {
|
|
// Use message type + zero padding as a fallback tracking key
|
|
var id: [32]u8 = [_]u8{0} ** 32;
|
|
const msg_type_int: u8 = @intFromEnum(msg.getType());
|
|
id[0] = msg_type_int;
|
|
break :blk id;
|
|
};
|
|
|
|
// Check if this source has exceeded their limit during backpressure
|
|
const current_count = self.per_source_counts.get(tracking_id) orelse 0;
|
|
if (current_count >= PER_SOURCE_LIMIT) {
|
|
_ = self.rejected_count.fetchAdd(1, .monotonic);
|
|
_ = self.backpressure_events.fetchAdd(1, .monotonic);
|
|
std.log.warn("CRIT-NEW-11: Backpressure active - rejecting message from heavy sender (count={})", .{current_count});
|
|
return error.BackpressureActive;
|
|
}
|
|
|
|
// Record this message from source
|
|
try self.per_source_counts.put(tracking_id, current_count + 1);
|
|
|
|
// Log backpressure activation periodically
|
|
const total_backpressure = self.backpressure_events.load(.monotonic);
|
|
if (total_backpressure % 100 == 0 and total_backpressure > 0) {
|
|
std.log.warn("CRIT-NEW-11: Backpressure active (queue={}, threshold={}, total_events={})", .{
|
|
self.queue.items.len,
|
|
BACKPRESSURE_THRESHOLD,
|
|
total_backpressure,
|
|
});
|
|
}
|
|
}
|
|
|
|
try self.queue.append(self.allocator, msg);
|
|
}
|
|
|
|
/// CRIT-NEW-11 FIX: Reset per-source counts (call periodically)
|
|
pub fn resetBackpressureCounts(self: *AsyncMessageProcessor) void {
|
|
self.queue_mutex.lock();
|
|
defer self.queue_mutex.unlock();
|
|
self.per_source_counts.clearRetainingCapacity();
|
|
}
|
|
|
|
/// CRIT-NEW-11 FIX: Get queue statistics for monitoring
|
|
pub fn getQueueStats(self: *AsyncMessageProcessor) QueueStats {
|
|
self.queue_mutex.lock();
|
|
defer self.queue_mutex.unlock();
|
|
return QueueStats{
|
|
.queue_size = self.queue.items.len,
|
|
.rejected_count = self.rejected_count.load(.monotonic),
|
|
.backpressure_events = self.backpressure_events.load(.monotonic),
|
|
.unique_sources = self.per_source_counts.count(),
|
|
};
|
|
}
|
|
|
|
/// CRIT-NEW-11 FIX: Queue statistics
|
|
pub const QueueStats = struct {
|
|
queue_size: usize,
|
|
rejected_count: u64,
|
|
backpressure_events: u64,
|
|
unique_sources: usize,
|
|
};
|
|
|
|
fn workerThread(self_ref: *AsyncMessageProcessor) void {
|
|
while (!self_ref.shutdown.load(.monotonic)) {
|
|
// Get message from queue
|
|
var msg_opt: ?message.Message = null;
|
|
|
|
self_ref.queue_mutex.lock();
|
|
if (self_ref.queue.items.len > 0) {
|
|
msg_opt = self_ref.queue.orderedRemove(0);
|
|
}
|
|
self_ref.queue_mutex.unlock();
|
|
|
|
if (msg_opt) |msg| {
|
|
self_ref.registry.processMessage(msg) catch |err| {
|
|
// Log error properly and record in metrics
|
|
std.log.err("Error processing message of type {}: {s}", .{ msg.getType(), @errorName(err) });
|
|
self_ref.registry.context.metrics.recordMessageFailed();
|
|
};
|
|
} else {
|
|
// No messages to process, sleep briefly
|
|
std.time.sleep(std.time.ns_per_ms * 10);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
test "message handler framework" {
|
|
const allocator = std.testing.allocator;
|
|
var registry = try HandlerRegistry.init(allocator);
|
|
defer registry.deinit();
|
|
|
|
// Test handler registration
|
|
const handler = MessageHandler.init(
|
|
struct {
|
|
fn testHandler(msg: message.Message, ctx: *anyopaque) !void {
|
|
_ = msg;
|
|
_ = ctx;
|
|
// Simple test handler
|
|
}
|
|
}.testHandler,
|
|
registry.getContext(),
|
|
.ping,
|
|
);
|
|
|
|
try registry.registerHandler(.ping, handler);
|
|
try std.testing.expectEqual(@as(u16, 1), registry.context.metrics.handlers_registered);
|
|
|
|
// Test message processing
|
|
const ping = message.Ping.init(123);
|
|
const msg = message.Message{ .ping = ping };
|
|
|
|
try registry.processMessage(msg);
|
|
try std.testing.expectEqual(@as(u64, 1), registry.context.metrics.messages_processed.load(.monotonic));
|
|
}
|
|
|
|
test "request tracker - basic operations" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
// Track a request
|
|
var file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
var peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
const request_id = try tracker.trackRequest(
|
|
42, // piece_index
|
|
1024, // offset
|
|
4096, // size
|
|
file_hash,
|
|
peer_id,
|
|
);
|
|
|
|
try std.testing.expect(request_id > 0);
|
|
try std.testing.expectEqual(@as(usize, 1), tracker.pendingCount());
|
|
|
|
// Resolve the request
|
|
const info = tracker.resolveRequest(request_id).?;
|
|
try std.testing.expectEqual(@as(u32, 42), info.piece_index);
|
|
try std.testing.expectEqual(@as(u64, 1024), info.offset);
|
|
try std.testing.expectEqual(@as(u32, 4096), info.size);
|
|
try std.testing.expect(std.mem.eql(u8, &file_hash, &info.file_hash));
|
|
try std.testing.expect(std.mem.eql(u8, &peer_id, &info.peer_id));
|
|
|
|
// Request should be removed after resolution
|
|
try std.testing.expectEqual(@as(usize, 0), tracker.pendingCount());
|
|
try std.testing.expect(tracker.resolveRequest(request_id) == null);
|
|
}
|
|
|
|
test "request tracker - unique IDs" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
const file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
const peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
// Track multiple requests
|
|
const id1 = try tracker.trackRequest(0, 0, 100, file_hash, peer_id);
|
|
const id2 = try tracker.trackRequest(1, 0, 100, file_hash, peer_id);
|
|
const id3 = try tracker.trackRequest(2, 0, 100, file_hash, peer_id);
|
|
|
|
// All IDs should be unique
|
|
try std.testing.expect(id1 != id2);
|
|
try std.testing.expect(id2 != id3);
|
|
try std.testing.expect(id1 != id3);
|
|
|
|
try std.testing.expectEqual(@as(usize, 3), tracker.pendingCount());
|
|
}
|
|
|
|
test "request tracker - unknown request returns null" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
// Try to resolve non-existent request
|
|
try std.testing.expect(tracker.resolveRequest(999999) == null);
|
|
}
|
|
|
|
test "request tracker - cancel request" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
const file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
const peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
const request_id = try tracker.trackRequest(0, 0, 100, file_hash, peer_id);
|
|
try std.testing.expectEqual(@as(usize, 1), tracker.pendingCount());
|
|
|
|
// Cancel the request
|
|
try std.testing.expect(tracker.cancelRequest(request_id));
|
|
try std.testing.expectEqual(@as(usize, 0), tracker.pendingCount());
|
|
|
|
// Cancelling again should return false
|
|
try std.testing.expect(!tracker.cancelRequest(request_id));
|
|
}
|
|
|
|
test "request tracker - peek without removing" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
const file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
const peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
const request_id = try tracker.trackRequest(42, 0, 100, file_hash, peer_id);
|
|
|
|
// Peek should return info but not remove
|
|
const info1 = tracker.peekRequest(request_id).?;
|
|
try std.testing.expectEqual(@as(u32, 42), info1.piece_index);
|
|
try std.testing.expectEqual(@as(usize, 1), tracker.pendingCount());
|
|
|
|
// Peek again - still there
|
|
const info2 = tracker.peekRequest(request_id).?;
|
|
try std.testing.expectEqual(@as(u32, 42), info2.piece_index);
|
|
try std.testing.expectEqual(@as(usize, 1), tracker.pendingCount());
|
|
}
|
|
|
|
test "request tracker - resolveRequest removes request" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
const file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
const peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
const request_id = try tracker.trackRequest(42, 0, 100, file_hash, peer_id);
|
|
try std.testing.expectEqual(@as(usize, 1), tracker.pendingCount());
|
|
|
|
// Resolve the request
|
|
const info = tracker.resolveRequest(request_id).?;
|
|
try std.testing.expectEqual(@as(u32, 42), info.piece_index);
|
|
try std.testing.expectEqual(@as(usize, 0), tracker.pendingCount());
|
|
|
|
// Resolving again should return null
|
|
try std.testing.expect(tracker.resolveRequest(request_id) == null);
|
|
}
|
|
|
|
test "request tracker - multiple requests" {
|
|
const allocator = std.testing.allocator;
|
|
var tracker = RequestTracker.init(allocator);
|
|
defer tracker.deinit();
|
|
|
|
const file_hash: [32]u8 = [_]u8{1} ** 32;
|
|
const peer_id: message.NodeId = [_]u8{2} ** 32;
|
|
|
|
const id1 = try tracker.trackRequest(1, 0, 100, file_hash, peer_id);
|
|
const id2 = try tracker.trackRequest(2, 100, 100, file_hash, peer_id);
|
|
const id3 = try tracker.trackRequest(3, 200, 100, file_hash, peer_id);
|
|
|
|
try std.testing.expectEqual(@as(usize, 3), tracker.pendingCount());
|
|
|
|
// Resolve all requests
|
|
_ = tracker.resolveRequest(id1);
|
|
_ = tracker.resolveRequest(id2);
|
|
_ = tracker.resolveRequest(id3);
|
|
try std.testing.expectEqual(@as(usize, 0), tracker.pendingCount());
|
|
}
|
|
|
|
test "HandlerMetrics: initialization" {
|
|
const metrics = HandlerMetrics.init();
|
|
try std.testing.expectEqual(@as(u64, 0), metrics.messages_processed.load(.acquire));
|
|
try std.testing.expectEqual(@as(u64, 0), metrics.messages_failed.load(.acquire));
|
|
}
|
|
|
|
test "HandlerMetrics: recordMessageProcessed" {
|
|
var metrics = HandlerMetrics.init();
|
|
metrics.recordMessageProcessed(10.5);
|
|
try std.testing.expectEqual(@as(u64, 1), metrics.messages_processed.load(.acquire));
|
|
}
|
|
|
|
test "HandlerMetrics: recordMessageFailed" {
|
|
var metrics = HandlerMetrics.init();
|
|
metrics.recordMessageFailed();
|
|
try std.testing.expectEqual(@as(u64, 1), metrics.messages_failed.load(.acquire));
|
|
}
|