470 lines
19 KiB
Zig
470 lines
19 KiB
Zig
//! P2P Messaging Implementation
|
|
//!
|
|
//! This module contains implementations for P2P messaging operations including
|
|
//! sending messages, emitting events, the main update loop, statistics updates,
|
|
//! and network message/disconnect handling callbacks.
|
|
|
|
const std = @import("std");
|
|
const Allocator = std.mem.Allocator;
|
|
|
|
// Core components
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
|
|
// Network components
|
|
const network = @import("network");
|
|
const PeerId = network.peer.PeerId;
|
|
|
|
// Protocol components
|
|
const protocol = @import("protocol");
|
|
|
|
// File sharing components
|
|
const files = @import("files");
|
|
|
|
// Import P2P type
|
|
const P2P = @import("p2p.zig").P2P;
|
|
|
|
// Sibling module imports
|
|
const events = @import("events.zig");
|
|
const P2PEvent = events.P2PEvent;
|
|
const lifecycle = @import("lifecycle.zig");
|
|
const file_ops = @import("file_ops.zig");
|
|
|
|
// ============================================================================
|
|
// Message Sending
|
|
// ============================================================================
|
|
|
|
/// Size of the wire envelope prepended to non-DHT, non-file-transfer messages:
|
|
/// 8 bytes random salt (LE) + 8 bytes sender timestamp (LE)
|
|
///
|
|
/// Wire format: [app_id:1][salt:8 LE][timestamp:8 LE][payload:N]
|
|
///
|
|
/// ## Security model
|
|
///
|
|
/// **Noise ON (production)**: The entire message is inside AEAD ciphertext, so
|
|
/// transport-level authentication prevents any modification or replay. The
|
|
/// envelope provides defense-in-depth: a per-session SipHash key derived from
|
|
/// the Noise handshake hash binds (salt || timestamp || app_id || payload) into
|
|
/// a replay nonce. Even if a Noise implementation bug allows replay, this
|
|
/// independent layer catches it. The per-session key means an attacker who
|
|
/// compromises one session cannot forge envelopes for other peer pairs.
|
|
///
|
|
/// **Noise OFF (dev/testing only)**: No shared secret exists, so the raw salt
|
|
/// is used directly as the replay nonce. This stops passive network replays
|
|
/// (exact byte replay by a router/ISP) but provides NO authentication — any
|
|
/// active attacker can construct fresh messages. This mode is NOT secure for
|
|
/// production. Enforce `enable_noise_encryption = true` in production configs.
|
|
pub const WIRE_ENVELOPE_SIZE: usize = 16;
|
|
|
|
/// Derive a replay nonce bound to the envelope, payload, and per-session key.
|
|
/// Uses keyed SipHash-2-4 over (salt, timestamp, app_id, payload).
|
|
/// The per-session key is derived from the Noise handshake hash, so only the
|
|
/// two peers in the session can compute the correct nonce.
|
|
fn deriveEnvelopeNonce(key: *const [16]u8, salt: *const [8]u8, ts_bytes: *const [8]u8, app_id: u8, payload: []const u8) u64 {
|
|
var hasher = std.crypto.auth.siphash.SipHash64(2, 4).init(key);
|
|
hasher.update(salt);
|
|
hasher.update(ts_bytes);
|
|
hasher.update(&[_]u8{app_id});
|
|
hasher.update(payload);
|
|
return hasher.finalInt();
|
|
}
|
|
|
|
/// Look up the per-session envelope key for a peer from their Noise connection.
|
|
/// Returns null when the peer has no Noise session (Noise off or not yet handshaked).
|
|
/// Caller MUST hold peer_connections_mutex or accept TOCTOU (acceptable here since
|
|
/// the key is immutable after handshake and the connection outlives message processing).
|
|
fn getPerSessionEnvelopeKey(p2p: *P2P, peer_id: PeerId) ?[16]u8 {
|
|
p2p.peer_connections_mutex.lock();
|
|
defer p2p.peer_connections_mutex.unlock();
|
|
const peer_conn = p2p.peer_connections.get(peer_id) orelse return null;
|
|
return peer_conn.getEnvelopeKey();
|
|
}
|
|
|
|
/// Reserved app_ids that have their own send paths and replay protection.
|
|
/// File transfer (0x01): own integrity via piece hashing / session tracking.
|
|
/// DHT (0x02): own wire_nonce/wire_timestamp embedded in serialization.
|
|
const RESERVED_FILE_TRANSFER: u8 = 0x01;
|
|
const RESERVED_DHT: u8 = 0x02;
|
|
|
|
fn isReservedAppId(app_id: u8) bool {
|
|
return app_id == RESERVED_FILE_TRANSFER or app_id == RESERVED_DHT;
|
|
}
|
|
|
|
/// Send a custom message to a peer
|
|
pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data: []const u8) Error!u64 {
|
|
if (!p2p.running.load(.acquire)) return Error.InvalidState;
|
|
if (data.len == 0) return Error.InvalidArgument;
|
|
if (data.len > p2p.config.protocol.max_message_size) {
|
|
return Error.MessageTooLarge;
|
|
}
|
|
|
|
const nm = p2p.network_manager orelse return Error.InvalidState;
|
|
|
|
// Only add wire envelope for non-reserved app_ids.
|
|
// Reserved types (file transfer, DHT) have their own send paths with
|
|
// their own replay protection; adding an envelope here would corrupt
|
|
// them if someone mistakenly sends through the public API.
|
|
const envelope_len: usize = if (isReservedAppId(message_type)) 0 else WIRE_ENVELOPE_SIZE;
|
|
|
|
var full_msg = p2p.allocator.alloc(u8, data.len + 1 + envelope_len) catch return Error.OutOfMemory;
|
|
defer p2p.allocator.free(full_msg);
|
|
full_msg[0] = message_type;
|
|
|
|
if (!isReservedAppId(message_type)) {
|
|
// Write wire envelope: salt (8 random LE) + timestamp (8 LE)
|
|
// The receiver derives the replay nonce from these fields:
|
|
// - Noise ON: SipHash(session_key, salt || ts || app_id || payload)
|
|
// - Noise OFF: raw salt (passive replay protection only)
|
|
const wire_salt = protocol.message.generateWireNonce(); // 8 random bytes
|
|
const wire_timestamp = std.time.timestamp();
|
|
std.mem.writeInt(u64, full_msg[1..9], wire_salt, .little);
|
|
std.mem.writeInt(i64, full_msg[9..17], wire_timestamp, .little);
|
|
}
|
|
|
|
// Copy payload after app_id + envelope (if any)
|
|
@memcpy(full_msg[1 + envelope_len ..], data);
|
|
|
|
if (destination) |peer_id| {
|
|
const msg_id = try nm.sendMessage(peer_id, full_msg);
|
|
try emitEventImpl(p2p, P2PEvent.create(.message_sent, .{ .message_sent = .{
|
|
.message_type = message_type,
|
|
.destination = destination,
|
|
} }));
|
|
return msg_id;
|
|
} else {
|
|
_ = try nm.broadcastMessage(full_msg);
|
|
try emitEventImpl(p2p, P2PEvent.create(.message_sent, .{ .message_sent = .{
|
|
.message_type = message_type,
|
|
.destination = null,
|
|
} }));
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Event Emission
|
|
// ============================================================================
|
|
|
|
/// Emit an internal event
|
|
pub fn emitEventImpl(p2p: *P2P, event: P2PEvent) Error!void {
|
|
p2p.event_mutex.lock();
|
|
defer p2p.event_mutex.unlock();
|
|
|
|
if (p2p.event_queue.items.len >= p2p.config.events.max_event_queue) {
|
|
_ = p2p.stats.events_dropped.fetchAdd(1, .monotonic);
|
|
switch (p2p.config.events.overflow_policy) {
|
|
.drop_oldest => {
|
|
std.log.warn("Event queue overflow - dropping oldest event (queue size: {})", .{p2p.event_queue.items.len});
|
|
if (p2p.event_queue.items.len > 0) {
|
|
var dropped = p2p.event_queue.orderedRemove(0);
|
|
dropped.deinit();
|
|
}
|
|
},
|
|
.drop_newest => {
|
|
std.log.warn("Event queue overflow - dropping new event '{s}' (queue size: {})", .{ @tagName(event.event_type), p2p.event_queue.items.len });
|
|
// Caller passed event by value; deinit in case it owns payload
|
|
var mutable_event = event;
|
|
mutable_event.deinit();
|
|
return;
|
|
},
|
|
.fail => {
|
|
std.log.err("Event queue full (size: {}), rejecting event '{s}'", .{ p2p.event_queue.items.len, @tagName(event.event_type) });
|
|
var mutable_event = event;
|
|
mutable_event.deinit();
|
|
return Error.QueueFull;
|
|
},
|
|
}
|
|
}
|
|
|
|
p2p.event_queue.append(p2p.allocator, event) catch return Error.OutOfMemory;
|
|
|
|
if (p2p.config.events.enable_logging) {
|
|
std.debug.print("P2P Event: {s}\n", .{@tagName(event.event_type)});
|
|
}
|
|
}
|
|
|
|
/// Emit an error event
|
|
pub fn emitErrorEventImpl(p2p: *P2P, err: anyerror, message: []const u8) Error!void {
|
|
const error_value: Error = @errorCast(err);
|
|
|
|
const event = P2PEvent{
|
|
.event_type = .library_error,
|
|
.data = .{
|
|
.library_error = .{
|
|
.err = error_value,
|
|
.message = message,
|
|
},
|
|
},
|
|
.timestamp = std.time.timestamp(),
|
|
.session_id = null,
|
|
};
|
|
try emitEventImpl(p2p, event);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Update Loop
|
|
// ============================================================================
|
|
|
|
/// Internal update function called periodically
|
|
pub fn updateImpl(p2p: *P2P) Error!void {
|
|
if (!p2p.running.load(.acquire)) return;
|
|
|
|
// 1. Accept incoming connections
|
|
if (p2p.listen_socket != null) {
|
|
p2p.acceptConnections() catch |err| {
|
|
std.log.warn("Accept connections failed: {}", .{err});
|
|
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
|
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
|
|
};
|
|
}
|
|
|
|
// 2. Process network I/O
|
|
if (p2p.network_manager) |nm| {
|
|
nm.processReceive() catch |err| {
|
|
std.log.warn("Network receive failed: {}", .{err});
|
|
_ = p2p.stats.receive_errors.fetchAdd(1, .monotonic);
|
|
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
|
|
};
|
|
nm.processSendQueue();
|
|
}
|
|
|
|
// 2b. Drain pending sends
|
|
p2p.drainPendingSends();
|
|
|
|
// 3. File sharing operations
|
|
if (p2p.file_manager) |fm| {
|
|
fm.processSessions() catch |err| {
|
|
std.log.err("File manager error: {}", .{err});
|
|
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
|
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
|
|
emitErrorEventImpl(p2p, err, "File manager error") catch |emit_err| {
|
|
std.log.warn("Failed to emit error event: {}", .{emit_err});
|
|
};
|
|
};
|
|
|
|
fm.processVerificationResults();
|
|
}
|
|
|
|
// 4. Health checks
|
|
const now = std.time.milliTimestamp();
|
|
if (now - p2p.last_health_check > p2p.config.network.health_check_interval_ms) {
|
|
lifecycle.performHealthChecksImpl(p2p) catch |err| {
|
|
std.log.warn("Health checks failed: {}", .{err});
|
|
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
|
_ = p2p.errors_in_window.fetchAdd(1, .monotonic);
|
|
};
|
|
p2p.last_health_check = now;
|
|
}
|
|
|
|
// 5. TURN allocation refresh
|
|
if (p2p.turn_integration) |integration| {
|
|
integration.refreshIfNeeded() catch |err| {
|
|
std.log.warn("TURN refresh failed: {} - NAT traversal may be degraded", .{err});
|
|
};
|
|
}
|
|
|
|
// 6. Replay protection cleanup
|
|
const cleanup_interval_ms = p2p.config.protocol.replay_protection_cleanup_interval * 1000;
|
|
if ((now - p2p.last_replay_cleanup) > cleanup_interval_ms) {
|
|
if (p2p.handler_registry) |registry| {
|
|
registry.cleanupReplayProtection();
|
|
}
|
|
p2p.last_replay_cleanup = now;
|
|
}
|
|
|
|
// 7. Check error rates and manage state transitions
|
|
if (p2p.config.library.enable_auto_maintenance) {
|
|
const check_interval: i64 = @as(i64, p2p.config.library.maintenance_check_interval_ms);
|
|
if (now - p2p.last_maintenance_check > check_interval) {
|
|
lifecycle.checkErrorRateAndTransitionStateImpl(p2p) catch |err| {
|
|
std.log.warn("Failed to check error rate: {}", .{err});
|
|
};
|
|
p2p.last_maintenance_check = now;
|
|
}
|
|
}
|
|
|
|
// 8. Update statistics
|
|
updateStatsImpl(p2p);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Statistics
|
|
// ============================================================================
|
|
|
|
/// Update statistics from various sources
|
|
pub fn updateStatsImpl(p2p: *P2P) void {
|
|
if (p2p.start_time > 0) {
|
|
const now = std.time.timestamp();
|
|
const elapsed = now - p2p.start_time;
|
|
p2p.stats.uptime_seconds = if (elapsed < 0) 0 else if (elapsed > std.math.maxInt(u64)) std.math.maxInt(u64) else @intCast(elapsed);
|
|
}
|
|
|
|
p2p.peer_connections_mutex.lock();
|
|
const count = p2p.peer_connections.count();
|
|
const conn_count: u32 = if (count > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(count);
|
|
p2p.peer_connections_mutex.unlock();
|
|
p2p.stats.active_connections.store(conn_count, .monotonic);
|
|
|
|
if (p2p.network_manager) |nm| {
|
|
const nm_stats = nm.getStats();
|
|
p2p.stats.messages_sent.store(nm_stats.messages_sent.load(.acquire), .release);
|
|
p2p.stats.messages_received.store(nm_stats.messages_received.load(.acquire), .release);
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Network Callbacks
|
|
// ============================================================================
|
|
|
|
/// Callback for receiving messages from NetworkManager
|
|
pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*anyopaque) void {
|
|
const p2p: *P2P = @ptrCast(@alignCast(context orelse return));
|
|
|
|
const app_id: u8 = if (data.len > 0) data[0] else 0;
|
|
|
|
// File transfer messages bypass event system
|
|
if (data.len > 1 and app_id == 0x01) {
|
|
file_ops.handleFileTransferMessageImpl(p2p, peer_id.bytes, data[1..]);
|
|
return;
|
|
}
|
|
|
|
// DHT messages - deserialize and route through handler_registry
|
|
if (data.len > 1 and app_id == 0x02) {
|
|
handleDhtMessageImpl(p2p, peer_id, data[1..]);
|
|
return;
|
|
}
|
|
|
|
// Non-DHT, non-file-transfer: extract wire envelope and check replay
|
|
if (data.len < 1 + WIRE_ENVELOPE_SIZE) {
|
|
// Too short to contain envelope — drop silently
|
|
return;
|
|
}
|
|
|
|
const wire_timestamp = std.mem.readInt(i64, data[9..17], .little);
|
|
const payload_src: []const u8 = if (data.len > 1 + WIRE_ENVELOPE_SIZE) data[1 + WIRE_ENVELOPE_SIZE ..] else &[_]u8{};
|
|
|
|
// Derive per-peer message ID. Two modes:
|
|
//
|
|
// 1. Noise ON: Use per-session SipHash key from the Noise handshake.
|
|
// This binds (salt || timestamp || app_id || payload) into an ID that
|
|
// only the two peers in this session can compute. An attacker who captures
|
|
// traffic cannot forge envelopes without the session key.
|
|
//
|
|
// 2. Noise OFF: No shared secret. Use the raw 8-byte salt as the ID.
|
|
// This only stops passive replay (exact same bytes). No authentication.
|
|
const envelope_msg_id = if (getPerSessionEnvelopeKey(p2p, peer_id)) |key|
|
|
deriveEnvelopeNonce(&key, data[1..9], data[9..17], app_id, payload_src)
|
|
else
|
|
std.mem.readInt(u64, data[1..9], .little); // raw salt fallback
|
|
|
|
// Replay protection check (per-peer msg_id dedup + timestamp validation)
|
|
if (p2p.handler_registry) |registry| {
|
|
registry.replay_protector.checkMessage(
|
|
envelope_msg_id, // msg_id: per-peer dedup
|
|
wire_timestamp, // sender's timestamp
|
|
0, // sequence: not applicable
|
|
peer_id.bytes, // [32]u8 peer ID
|
|
app_id, // message type
|
|
) catch |err| {
|
|
std.log.warn("Replay protection rejected non-DHT message: {s} (app_id={}, peer_hint={x:0>2}{x:0>2})", .{
|
|
@errorName(err), app_id, peer_id.bytes[0], peer_id.bytes[1],
|
|
});
|
|
return;
|
|
};
|
|
} else {
|
|
// SECURITY: No handler registry means no replay protection. Drop the message.
|
|
// This should never happen after start() completes (handler_registry is initialized
|
|
// in startImpl before network callbacks are wired), but guard against it defensively.
|
|
std.log.warn("SECURITY: Non-DHT message DROPPED — no handler registry for replay protection (app_id={})", .{app_id});
|
|
return;
|
|
}
|
|
|
|
const payload = p2p.allocator.dupe(u8, payload_src) catch return;
|
|
|
|
var event = P2PEvent.create(.message_received, .{
|
|
.message_received = .{
|
|
.message_type = app_id,
|
|
.source = peer_id,
|
|
.data = payload,
|
|
},
|
|
});
|
|
event.owns_payload = true;
|
|
event.allocator = p2p.allocator;
|
|
|
|
emitEventImpl(p2p, event) catch |err| {
|
|
std.log.warn("Failed to emit message_received event: {}", .{err});
|
|
p2p.allocator.free(payload);
|
|
};
|
|
}
|
|
|
|
/// Handle incoming DHT protocol messages (app_id = 0x02)
|
|
/// This deserializes the message and routes it through the handler registry,
|
|
/// setting the connection peer ID as source_peer_id for auto-registration.
|
|
fn handleDhtMessageImpl(p2p: *P2P, connection_peer_id: PeerId, payload: []const u8) void {
|
|
const registry = p2p.handler_registry orelse {
|
|
std.log.warn("DHT: Received message but no handler registry initialized", .{});
|
|
return;
|
|
};
|
|
|
|
// Use simple binary deserialization (no HMAC - Noise transport provides security)
|
|
const dht = @import("dht.zig");
|
|
const msg = dht.deserializeDhtMessage(payload, p2p.allocator) orelse {
|
|
std.log.warn("DHT: Failed to deserialize message (len={})", .{payload.len});
|
|
return;
|
|
};
|
|
defer dht.freeDhtMessage(p2p.allocator, msg);
|
|
|
|
// CRITICAL: Set the connection peer ID as source before processing
|
|
// This allows DHT handlers to auto-register the node_id -> peer_id mapping
|
|
registry.context.setSource(connection_peer_id.bytes);
|
|
defer registry.context.clearSource();
|
|
|
|
// Process the message through the handler registry
|
|
registry.processMessage(msg) catch |err| {
|
|
std.log.warn("DHT: Failed to process message: {}", .{err});
|
|
};
|
|
}
|
|
|
|
/// Callback for peer disconnection from NetworkManager
|
|
pub fn handleNetworkDisconnectImpl(peer_id: PeerId, context: ?*anyopaque) void {
|
|
const p2p: *P2P = @ptrCast(@alignCast(context orelse return));
|
|
|
|
// SOCKET FIX: Remove from peer_connections FIRST to stop further send attempts
|
|
// This must happen before notifying file manager to prevent race conditions
|
|
const connection = @import("connection.zig");
|
|
if (connection.removePeerConnectionImpl(p2p, peer_id)) |socket| {
|
|
socket.close() catch {};
|
|
socket.deinit();
|
|
p2p.allocator.destroy(socket);
|
|
}
|
|
|
|
emitEventImpl(p2p, P2PEvent.create(.peer_disconnected, .{
|
|
.peer_disconnected = .{
|
|
.peer_id = peer_id,
|
|
.reason = "network disconnect",
|
|
},
|
|
})) catch |err| {
|
|
std.log.warn("Failed to emit disconnect event: {}", .{err});
|
|
};
|
|
|
|
const current = p2p.stats.active_connections.load(.monotonic);
|
|
if (current > 0) {
|
|
_ = p2p.stats.active_connections.fetchSub(1, .monotonic);
|
|
}
|
|
|
|
// CRITICAL FIX: Use removePeerById to properly clean up both peer_ids and peers maps.
|
|
// The old code was buggy - pm.peers is keyed by address string, not peer_id bytes.
|
|
if (p2p.peer_manager) |pm| {
|
|
_ = pm.removePeerById(peer_id);
|
|
}
|
|
|
|
if (p2p.peer_rate_limiter) |limiter| {
|
|
limiter.removePeer(peer_id.bytes);
|
|
}
|
|
|
|
// CASCADE PERF: Notify file manager to immediately cancel requests to this peer
|
|
if (p2p.file_manager) |fm| {
|
|
fm.handlePeerDisconnect(peer_id.bytes);
|
|
}
|
|
}
|