From 7b120731a6e0235942132eb45aab0d05ddf6f09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Thu, 19 Feb 2026 11:36:11 -0300 Subject: [PATCH] refactor p2p: keepalive pings, WASM-safe messaging, non-blocking connections --- src/p2p.zig | 1 + src/p2p/circuit_breaker.zig | 12 +-- src/p2p/config.zig | 7 ++ src/p2p/dht.zig | 10 ++- src/p2p/events.zig | 19 +++-- src/p2p/file_ops.zig | 3 +- src/p2p/lifecycle.zig | 162 +++++++++++++++++++++++------------- src/p2p/messaging.zig | 50 +++++++---- src/p2p/p2p.zig | 108 +++++++++++++++++++----- src/p2p/stats.zig | 58 ++++++------- 10 files changed, 288 insertions(+), 142 deletions(-) diff --git a/src/p2p.zig b/src/p2p.zig index 169a67e..544f435 100644 --- a/src/p2p.zig +++ b/src/p2p.zig @@ -60,6 +60,7 @@ pub const circuit_breaker = @import("p2p/circuit_breaker.zig"); pub const p2p_impl = @import("p2p/p2p.zig"); pub const dht = @import("p2p/dht.zig"); pub const messaging = @import("p2p/messaging.zig"); +pub const file_ops = @import("p2p/file_ops.zig"); // Re-export main types pub const P2P = p2p_impl.P2P; diff --git a/src/p2p/circuit_breaker.zig b/src/p2p/circuit_breaker.zig index 73609ec..31adb38 100644 --- a/src/p2p/circuit_breaker.zig +++ b/src/p2p/circuit_breaker.zig @@ -7,6 +7,8 @@ //! - HalfOpen: Testing if service has recovered const std = @import("std"); +const Mutex = @import("sync").Mutex; +const platform_time = @import("platform").time; /// Circuit breaker to prevent cascading failures /// @@ -16,7 +18,7 @@ const std = @import("std"); /// race conditions when accessed from multiple threads. pub const CircuitBreaker = struct { // THR-CRIT-1 FIX: Mutex to protect all mutable state - mutex: std.Thread.Mutex = .{}, + mutex: Mutex = .{}, state: State = .closed, failure_count: u32 = 0, @@ -48,7 +50,7 @@ pub const CircuitBreaker = struct { self.mutex.lock(); defer self.mutex.unlock(); - const now = std.time.milliTimestamp(); + const now = platform_time.milliTimestamp(); switch (self.state) { .closed => return true, @@ -75,7 +77,7 @@ pub const CircuitBreaker = struct { self.mutex.lock(); defer self.mutex.unlock(); - const now = std.time.milliTimestamp(); + const now = platform_time.milliTimestamp(); switch (self.state) { .closed => { @@ -102,7 +104,7 @@ pub const CircuitBreaker = struct { self.mutex.lock(); defer self.mutex.unlock(); - const now = std.time.milliTimestamp(); + const now = platform_time.milliTimestamp(); self.last_failure_time = now; switch (self.state) { @@ -142,7 +144,7 @@ pub const CircuitBreaker = struct { self.failure_count = 0; self.success_count = 0; self.last_failure_time = 0; - self.last_state_change = std.time.milliTimestamp(); + self.last_state_change = platform_time.milliTimestamp(); } }; diff --git a/src/p2p/config.zig b/src/p2p/config.zig index a65085e..df57b5d 100644 --- a/src/p2p/config.zig +++ b/src/p2p/config.zig @@ -223,6 +223,13 @@ pub const NetworkConfig = struct { handshake_max_backoff_ms: u32 = 10000, /// Backoff multiplier (e.g., 2.0 = double each time) handshake_backoff_multiplier: f32 = 2.0, + /// Enable the UDP listener and related subsystems (discovery, TURN, bootstrap). + /// Set to false for WebRTC-only operation where no POSIX sockets are needed. + /// Desktop/mobile can run both UDP and WebRTC simultaneously (default). + enable_udp_listener: bool = true, + /// Enable WebRTC transport for browser peer connectivity. + /// Requires building with -Denable-webrtc=true to have effect. + webrtc_enabled: bool = false, }; /// Protocol configuration diff --git a/src/p2p/dht.zig b/src/p2p/dht.zig index 3aa2c44..5774aa0 100644 --- a/src/p2p/dht.zig +++ b/src/p2p/dht.zig @@ -5,6 +5,8 @@ //! table management, value storage/retrieval, and network message propagation. const std = @import("std"); +const platform_time = @import("platform").time; +const platform_random = @import("platform").random; // Core components (via module import) const core = @import("core"); @@ -30,7 +32,7 @@ const MAX_DHT_VALUE_SIZE: u32 = 1024 * 1024; /// Generate a cryptographically random wire nonce for replay detection fn generateWireNonce() u64 { var bytes: [8]u8 = undefined; - std.crypto.random.bytes(&bytes); + platform_random.bytes(&bytes); return std.mem.readInt(u64, &bytes, .little); } @@ -208,7 +210,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender { .target_observed_addr = target_observed.addr, .target_observed_addr_len = target_observed.len, .wire_nonce = generateWireNonce(), - .wire_timestamp = std.time.timestamp(), + .wire_timestamp = platform_time.timestamp(), }, }; @@ -231,7 +233,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender { .target_observed_addr = target_observed.addr, .target_observed_addr_len = target_observed.len, .wire_nonce = generateWireNonce(), - .wire_timestamp = std.time.timestamp(), + .wire_timestamp = platform_time.timestamp(), }, }; @@ -252,7 +254,7 @@ pub fn createDhtNetworkSenderImpl(p2p: *P2P) network.dht.NetworkSender { .target_observed_addr = target_observed.addr, .target_observed_addr_len = target_observed.len, .wire_nonce = generateWireNonce(), - .wire_timestamp = std.time.timestamp(), + .wire_timestamp = platform_time.timestamp(), }, }; diff --git a/src/p2p/events.zig b/src/p2p/events.zig index e93c5a0..0b0ee6a 100644 --- a/src/p2p/events.zig +++ b/src/p2p/events.zig @@ -6,6 +6,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const core = @import("core"); +const platform = @import("platform"); const network = @import("network"); const Error = core.errors.Error; const PeerId = network.peer.PeerId; @@ -49,6 +50,7 @@ pub const P2PEvent = struct { upload_started = 0x3004, upload_completed = 0x3005, upload_failed = 0x3006, + file_transfer_progress = 0x3007, /// Protocol events message_sent = 0x4000, @@ -82,6 +84,13 @@ pub const P2PEvent = struct { upload_started: struct { session_id: u64, file_path: []const u8 }, upload_completed: struct { session_id: u64, bytes_uploaded: u64 }, upload_failed: struct { session_id: u64, err: Error }, + file_transfer_progress: struct { + session_id: u64, + direction: enum { send, receive }, + bytes_transferred: u64, + total_bytes: u64, + speed_bps: u64, + }, message_sent: struct { message_type: u8, destination: ?PeerId }, message_received: struct { message_type: u8, source: PeerId, data: []const u8 }, @@ -98,7 +107,7 @@ pub const P2PEvent = struct { return P2PEvent{ .event_type = event_type, .data = data, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .session_id = null, }; } @@ -108,7 +117,7 @@ pub const P2PEvent = struct { return P2PEvent{ .event_type = event_type, .data = data, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .session_id = session_id, }; } @@ -221,7 +230,7 @@ test "P2PEvent: deinit with owned message_received" { .data = owned_data, }, }, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .owns_payload = true, .allocator = allocator, }; @@ -243,7 +252,7 @@ test "P2PEvent: deinit with owned library_error" { .message = owned_msg, }, }, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .owns_payload = true, .allocator = allocator, }; @@ -265,7 +274,7 @@ test "P2PEvent: deinit with owned peer_disconnected" { .reason = owned_reason, }, }, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .owns_payload = true, .allocator = allocator, }; diff --git a/src/p2p/file_ops.zig b/src/p2p/file_ops.zig index 8cab890..bf669c5 100644 --- a/src/p2p/file_ops.zig +++ b/src/p2p/file_ops.zig @@ -4,6 +4,7 @@ //! These functions handle file addition, sharing, downloading, and transfer message processing. const std = @import("std"); +const platform_time = @import("platform").time; // Core components (via module import) const core = @import("core"); @@ -315,7 +316,7 @@ pub fn handleFileTransferMessageImpl(p2p: *P2P, peer_id: [32]u8, data: []const u .message_id = 0, .peer_id = &peer_id, .data = &reject_payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; if (fm.network_sender) |sender| { _ = sender.sendMessage(reject_msg) catch {}; diff --git a/src/p2p/lifecycle.zig b/src/p2p/lifecycle.zig index c4b8a56..bc3c5ab 100644 --- a/src/p2p/lifecycle.zig +++ b/src/p2p/lifecycle.zig @@ -6,10 +6,14 @@ //! All functions take a `*P2P` as the first parameter. const std = @import("std"); +const builtin = @import("builtin"); const Thread = std.Thread; +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; // Core components const core = @import("core"); +const platform = @import("platform"); +const platform_time = platform.time; const Error = core.errors.Error; const Address = core.Address; @@ -126,23 +130,26 @@ pub fn startImpl(p2p: *P2P) Error!void { p2p.node.?.* = Node.init(p2p.allocator, peer_id, p2p.address, p2p.topology.?, node_config); // Initialize discovery manager (optional - may fail if port in use) - const discovery_config = network.discovery.DiscoveryConfig{ - .broadcast_address = p2p.address, - .discovery_port = if (p2p.config.network.listen_port == 0) 9999 else p2p.config.network.listen_port, - }; - // First try to init, then allocate - this way if init fails, we don't have a dangling pointer - if (DiscoveryManager.init(p2p.allocator, discovery_config)) |discovery_mgr| { - p2p.discovery_manager = p2p.allocator.create(DiscoveryManager) catch { - // discovery_mgr was successfully initialized, need to clean up - var temp = discovery_mgr; - temp.deinit(); - return Error.SystemError; + // Only when UDP listener is enabled (discovery uses broadcast sockets) + if (p2p.config.network.enable_udp_listener) { + const discovery_config = network.discovery.DiscoveryConfig{ + .broadcast_address = p2p.address, + .discovery_port = if (p2p.config.network.listen_port == 0) 9999 else p2p.config.network.listen_port, }; - p2p.discovery_manager.?.* = discovery_mgr; - } else |err| { - // Discovery failed to initialize - continue without it - std.log.warn("Discovery manager failed to initialize: {}. Continuing without discovery.", .{err}); - p2p.discovery_manager = null; + // First try to init, then allocate - this way if init fails, we don't have a dangling pointer + if (DiscoveryManager.init(p2p.allocator, discovery_config)) |discovery_mgr| { + p2p.discovery_manager = p2p.allocator.create(DiscoveryManager) catch { + // discovery_mgr was successfully initialized, need to clean up + var temp = discovery_mgr; + temp.deinit(); + return Error.SystemError; + }; + p2p.discovery_manager.?.* = discovery_mgr; + } else |err| { + // Discovery failed to initialize - continue without it + std.log.warn("Discovery manager failed to initialize: {}. Continuing without discovery.", .{err}); + p2p.discovery_manager = null; + } } // Initialize protocol components @@ -202,12 +209,14 @@ pub fn startImpl(p2p: *P2P) Error!void { } // Initialize file sharing manager - const fm_ptr = p2p.allocator.create(FileSharingManager) catch return Error.SystemError; - fm_ptr.* = FileSharingManager.init(p2p.config.file_sharing, p2p.allocator) catch { - p2p.allocator.destroy(fm_ptr); - return Error.SystemError; - }; - p2p.file_manager = fm_ptr; + { + const fm_ptr = p2p.allocator.create(FileSharingManager) catch return Error.SystemError; + fm_ptr.* = FileSharingManager.init(p2p.config.file_sharing, p2p.allocator) catch { + p2p.allocator.destroy(fm_ptr); + return Error.SystemError; + }; + p2p.file_manager = fm_ptr; + } // Wire file transfer to network if (p2p.file_manager) |fm| { @@ -263,31 +272,33 @@ pub fn startImpl(p2p: *P2P) Error!void { p2p.connection_pool = p2p.allocator.create(core.connection.ConnectionPool) catch return Error.SystemError; p2p.connection_pool.?.* = core.connection.ConnectionPool.init(connection_config, p2p.allocator); - // Start the node - try p2p.node.?.start(); + // Start the node (binds UDP socket) — only when UDP listener is enabled + if (p2p.config.network.enable_udp_listener) { + try p2p.node.?.start(); - // Initialize TURN integration if enabled - if (p2p.config.network.turn_enabled) { - const turn_config = network.turn_integration.TurnConfig{ - .enabled = p2p.config.network.turn_enabled, - .servers = p2p.config.network.turn_servers, - .fallback_timeout_ms = p2p.config.network.turn_fallback_timeout_ms, - .refresh_interval_ms = p2p.config.network.turn_refresh_interval_ms, - }; - - p2p.turn_integration = p2p.allocator.create(network.TurnIntegration) catch |err| blk: { - std.log.warn("Failed to allocate TURN integration: {}, continuing without TURN support", .{err}); - break :blk null; - }; - - if (p2p.turn_integration) |integration| { - integration.* = network.TurnIntegration.init(p2p.allocator, turn_config); - integration.start() catch |err| { - std.log.warn("TURN integration failed to start: {}. TURN relay unavailable.", .{err}); - integration.deinit(); - p2p.allocator.destroy(integration); - p2p.turn_integration = null; + // Initialize TURN integration if enabled + if (p2p.config.network.turn_enabled) { + const turn_config = network.turn_integration.TurnConfig{ + .enabled = p2p.config.network.turn_enabled, + .servers = p2p.config.network.turn_servers, + .fallback_timeout_ms = p2p.config.network.turn_fallback_timeout_ms, + .refresh_interval_ms = p2p.config.network.turn_refresh_interval_ms, }; + + p2p.turn_integration = p2p.allocator.create(network.TurnIntegration) catch |err| blk: { + std.log.warn("Failed to allocate TURN integration: {}, continuing without TURN support", .{err}); + break :blk null; + }; + + if (p2p.turn_integration) |integration| { + integration.* = network.TurnIntegration.init(p2p.allocator, turn_config); + integration.start() catch |err| { + std.log.warn("TURN integration failed to start: {}. TURN relay unavailable.", .{err}); + integration.deinit(); + p2p.allocator.destroy(integration); + p2p.turn_integration = null; + }; + } } } @@ -349,7 +360,11 @@ pub fn startImpl(p2p: *P2P) Error!void { p2p.state_mutex.unlock(); p2p.running.store(true, .release); - p2p.start_time = std.time.timestamp(); + p2p.start_time = platform_time.timestamp(); + + if (!p2p.config.network.enable_udp_listener) { + std.log.info("P2P started with UDP listener disabled (WebRTC-only mode)", .{}); + } // PERF: Start verification thread pool for parallel SHA-256 if (p2p.file_manager) |fm| { @@ -362,8 +377,10 @@ pub fn startImpl(p2p: *P2P) Error!void { }; } - // Connect to bootstrap nodes if configured - if (p2p.config.network.bootstrap_nodes.len > 0) { + // Connect to bootstrap nodes if configured (requires UDP listener) + if (p2p.config.network.enable_udp_listener and + (p2p.config.network.bootstrap_nodes.len > 0 or p2p.config.network.pinned_bootstrap_nodes.len > 0)) + { connectToBootstrapNodesImpl(p2p); } @@ -390,7 +407,7 @@ pub fn stopImpl(p2p: *P2P) Error!void { if (p2p.file_manager) |fm| { // MED-1 FIX: Safe widening cast from u32 to i64 const shutdown_timeout_ms: i64 = @as(i64, p2p.config.library.shutdown_timeout_ms); - const deadline = std.time.milliTimestamp() + shutdown_timeout_ms; + const deadline = platform_time.milliTimestamp() + shutdown_timeout_ms; var initial_active_count: usize = 0; // Get initial transfer count for logging @@ -401,7 +418,7 @@ pub fn stopImpl(p2p: *P2P) Error!void { std.log.info("Gracefully stopping: waiting up to {}ms for {} active transfers to complete", .{ shutdown_timeout_ms, initial_active_count }); } - while (std.time.milliTimestamp() < deadline) { + while (platform_time.milliTimestamp() < deadline) { // Check if there are any active transfers const fm_stats = fm.getStats(); const has_active = fm_stats.downloading_sessions > 0 or fm_stats.uploading_sessions > 0; @@ -420,11 +437,11 @@ pub fn stopImpl(p2p: *P2P) Error!void { }; // Sleep briefly to avoid spinning - Thread.sleep(p2p.config.library.shutdown_poll_interval_ms * std.time.ns_per_ms); + platform.time.sleep(p2p.config.library.shutdown_poll_interval_ms * std.time.ns_per_ms); } // Check if timeout was reached - if (std.time.milliTimestamp() >= deadline) { + if (platform_time.milliTimestamp() >= deadline) { const remaining_stats = fm.getStats(); const remaining = remaining_stats.downloading_sessions + remaining_stats.uploading_sessions; if (remaining > 0) { @@ -635,34 +652,46 @@ pub fn connectToBootstrapNodesImpl(p2p: *P2P) void { } } -/// Perform health checks on all connections +/// Perform health checks on all connections. +/// Sends keepalive pings to idle-but-alive connections to prevent premature timeout. pub fn performHealthChecksImpl(p2p: *P2P) Error!void { var dead_peers: std.ArrayListUnmanaged(PeerId) = .{}; defer dead_peers.deinit(p2p.allocator); + var keepalive_peers: std.ArrayListUnmanaged(PeerId) = .{}; + defer keepalive_peers.deinit(p2p.allocator); + + const keepalive_ms: i64 = @intCast(p2p.config.network.keepalive_interval_ms); + const idle_timeout_ms: i64 = @intCast(p2p.config.network.idle_timeout_ms); + p2p.peer_connections_mutex.lock(); var iter = p2p.peer_connections.iterator(); while (iter.next()) |entry| { const peer_id = entry.key_ptr.*; const peer_conn = entry.value_ptr.*; - const socket = peer_conn.socket; - if (socket.state == .closed) { - std.log.debug("Health check: peer {x} has closed socket, marking dead", .{peer_id.bytes[0..8].*}); + if (peer_conn.transport_handle.getState() == .closed) { + std.log.debug("Health check: peer {x} has closed transport, marking dead", .{peer_id.bytes[0..8].*}); dead_peers.append(p2p.allocator, peer_id) catch |err| { - std.log.warn("Failed to track dead peer during health check (closed socket): {}", .{err}); + std.log.warn("Failed to track dead peer during health check (closed transport): {}", .{err}); continue; }; continue; } - const idle_ms = std.time.milliTimestamp() - socket.stats.getLastActivity(); - if (idle_ms > p2p.config.network.idle_timeout_ms) { + // Use socket stats for idle detection (transport abstraction doesn't track stats yet) + // WebRTC connections (socket == null) skip socket-based idle detection. + const socket = peer_conn.socket orelse continue; + const idle_ms = platform_time.milliTimestamp() - socket.stats.getLastActivity(); + if (idle_ms > idle_timeout_ms) { std.log.debug("Health check: peer {x} idle for {}ms, marking dead", .{ peer_id.bytes[0..8].*, idle_ms }); dead_peers.append(p2p.allocator, peer_id) catch |err| { std.log.warn("Failed to track idle peer during health check (idle: {}ms): {}", .{ idle_ms, err }); continue; }; + } else if (idle_ms > keepalive_ms) { + // Connection is idle but not dead yet — send keepalive to prevent timeout + keepalive_peers.append(p2p.allocator, peer_id) catch {}; } } p2p.peer_connections_mutex.unlock(); @@ -672,11 +701,24 @@ pub fn performHealthChecksImpl(p2p: *P2P) Error!void { std.log.warn("Failed to disconnect dead peer during health check: {}", .{err}); }; } + + // Send keepalive pings to idle-but-alive peers. + // The send updates socket.stats.last_activity on both sender (via Socket.send) + // and receiver (via Socket.receive), preventing idle timeout on both sides. + if (keepalive_peers.items.len > 0) { + const nm = p2p.network_manager orelse return; + const keepalive_frame = [_]u8{messaging.KEEPALIVE_APP_ID}; + for (keepalive_peers.items) |peer_id| { + _ = nm.sendMessage(peer_id, &keepalive_frame) catch |err| { + std.log.debug("Keepalive send failed for peer {x}: {}", .{ peer_id.bytes[0..8].*, err }); + }; + } + } } /// Check error rate and transition to maintenance/error state if needed pub fn checkErrorRateAndTransitionStateImpl(p2p: *P2P) Error!void { - const now = std.time.milliTimestamp(); + const now = platform_time.milliTimestamp(); const window_duration_ms: i64 = @as(i64, p2p.config.network.session_cleanup_interval_ms); if (p2p.error_window_start == 0 or (now - p2p.error_window_start) >= window_duration_ms) { diff --git a/src/p2p/messaging.zig b/src/p2p/messaging.zig index 80e488a..441d360 100644 --- a/src/p2p/messaging.zig +++ b/src/p2p/messaging.zig @@ -5,7 +5,9 @@ //! and network message/disconnect handling callbacks. const std = @import("std"); +const builtin = @import("builtin"); const Allocator = std.mem.Allocator; +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; // Core components const core = @import("core"); @@ -18,6 +20,9 @@ const PeerId = network.peer.PeerId; // Protocol components const protocol = @import("protocol"); +// Platform components +const platform = @import("platform"); + // File sharing components const files = @import("files"); @@ -81,13 +86,15 @@ fn getPerSessionEnvelopeKey(p2p: *P2P, peer_id: PeerId) ?[16]u8 { } /// Reserved app_ids that have their own send paths and replay protection. +/// Keepalive (0x00): internal ping to prevent idle timeout, silently discarded on receive. /// File transfer (0x01): own integrity via piece hashing / session tracking. /// DHT (0x02): own wire_nonce/wire_timestamp embedded in serialization. +pub const KEEPALIVE_APP_ID: u8 = 0x00; 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; + return app_id == KEEPALIVE_APP_ID or app_id == RESERVED_FILE_TRANSFER or app_id == RESERVED_DHT; } /// Send a custom message to a peer @@ -116,7 +123,7 @@ pub fn sendMessageImpl(p2p: *P2P, destination: ?PeerId, message_type: u8, data: // - 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(); + const wire_timestamp = platform.time.timestamp(); std.mem.writeInt(u64, full_msg[1..9], wire_salt, .little); std.mem.writeInt(i64, full_msg[9..17], wire_timestamp, .little); } @@ -178,7 +185,7 @@ pub fn emitEventImpl(p2p: *P2P, event: P2PEvent) Error!void { p2p.event_queue.append(p2p.allocator, event) catch return Error.OutOfMemory; - if (p2p.config.events.enable_logging) { + if (!is_wasm and p2p.config.events.enable_logging) { std.debug.print("P2P Event: {s}\n", .{@tagName(event.event_type)}); } } @@ -195,7 +202,7 @@ pub fn emitErrorEventImpl(p2p: *P2P, err: anyerror, message: []const u8) Error!v .message = message, }, }, - .timestamp = std.time.timestamp(), + .timestamp = platform.time.timestamp(), .session_id = null, }; try emitEventImpl(p2p, event); @@ -218,6 +225,9 @@ pub fn updateImpl(p2p: *P2P) Error!void { }; } + // 1b. Advance pending (non-blocking) connections + p2p.advancePendingConnections(); + // 2. Process network I/O if (p2p.network_manager) |nm| { nm.processReceive() catch |err| { @@ -246,7 +256,7 @@ pub fn updateImpl(p2p: *P2P) Error!void { } // 4. Health checks - const now = std.time.milliTimestamp(); + const now = platform.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}); @@ -256,12 +266,12 @@ pub fn updateImpl(p2p: *P2P) Error!void { p2p.last_health_check = now; } - // 5. TURN allocation refresh - if (p2p.turn_integration) |integration| { + // 5. TURN allocation refresh (not available on WASM) + if (!is_wasm) 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; @@ -294,7 +304,7 @@ pub fn updateImpl(p2p: *P2P) Error!void { /// Update statistics from various sources pub fn updateStatsImpl(p2p: *P2P) void { if (p2p.start_time > 0) { - const now = std.time.timestamp(); + const now = platform.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); } @@ -322,6 +332,10 @@ pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*an const app_id: u8 = if (data.len > 0) data[0] else 0; + // Keepalive ping — silently discard. The receive itself already + // updated socket.stats.last_activity, which is all we need. + if (app_id == KEEPALIVE_APP_ID) return; + // File transfer messages bypass event system if (data.len > 1 and app_id == 0x01) { file_ops.handleFileTransferMessageImpl(p2p, peer_id.bytes, data[1..]); @@ -372,11 +386,17 @@ pub fn handleNetworkMessageImpl(peer_id: PeerId, data: []const u8, context: ?*an 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; + if (is_wasm) { + // WASM mode: no HandlerRegistry (would pull in POSIX deps). + // Skip replay protection — WebRTC DataChannels are already encrypted + // and integrity-protected by DTLS, so passive replay is not a concern. + } 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; @@ -436,7 +456,7 @@ pub fn handleNetworkDisconnectImpl(peer_id: PeerId, context: ?*anyopaque) void { socket.close() catch {}; socket.deinit(); p2p.allocator.destroy(socket); - } + } // null: either peer not found or WebRTC (no socket to clean up) emitEventImpl(p2p, P2PEvent.create(.peer_disconnected, .{ .peer_disconnected = .{ diff --git a/src/p2p/p2p.zig b/src/p2p/p2p.zig index 1be8a08..ce5eeb0 100644 --- a/src/p2p/p2p.zig +++ b/src/p2p/p2p.zig @@ -22,9 +22,13 @@ const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; const Thread = std.Thread; -const Mutex = std.Thread.Mutex; -const atomic = std.atomic; +const sync = @import("sync"); +const Mutex = sync.Mutex; +const AtomicValue = sync.AtomicValue; const Ed25519 = std.crypto.sign.Ed25519; +const platform = @import("platform"); +const platform_time = platform.time; +const platform_random = platform.random; // Core components (via module import) const core = @import("core"); @@ -55,6 +59,9 @@ const VerifyResult = network.VerifyResult; const NatPmp = network.NatPmp; const Upnp = network.Upnp; +const builtin = @import("builtin"); +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; + // Protocol components (via module import) const protocol = @import("protocol"); const MessageHandler = protocol.handler.MessageHandler; @@ -119,7 +126,7 @@ pub const ObservedAddress = struct { if (addr_len == 0) return null; var result: ObservedAddress = undefined; - result.timestamp = std.time.milliTimestamp(); + result.timestamp = platform_time.milliTimestamp(); result.observer_id = observer; if (addr_len == 6) { @@ -424,8 +431,8 @@ pub const P2P = struct { /// Statistics stats: P2PStats, /// Internal flags (THREAD SAFETY: atomic for lock-free access from multiple threads) - initialized: atomic.Value(bool) = atomic.Value(bool).init(false), - running: atomic.Value(bool) = atomic.Value(bool).init(false), + initialized: AtomicValue(bool) = AtomicValue(bool).init(false), + running: AtomicValue(bool) = AtomicValue(bool).init(false), /// Start time for uptime tracking start_time: i64 = 0, /// Last health check timestamp @@ -434,7 +441,7 @@ pub const P2P = struct { last_replay_cleanup: i64 = 0, /// Error rate tracking for maintenance mode error_window_start: i64 = 0, - errors_in_window: atomic.Value(u32) = atomic.Value(u32).init(0), + errors_in_window: AtomicValue(u32) = AtomicValue(u32).init(0), /// Last maintenance check timestamp last_maintenance_check: i64 = 0, /// IMP-2 FIX: Circuit breaker for preventing cascading failures @@ -443,6 +450,11 @@ pub const P2P = struct { /// Last error summary emission last_error_summary: i64 = 0, + /// Non-blocking connections in progress (DoS exchange + Noise handshake) + pending_connections: std.ArrayList(connection.PendingConnection), + /// Mutex for pending_connections list + pending_connections_mutex: Mutex, + // ========================================================================= // Init/Deinit Methods (kept inline - complex initialization logic) // ========================================================================= @@ -482,7 +494,7 @@ pub const P2P = struct { .turn_integration = null, .routing_table = null, .dht_coordinator = null, - .identity_keypair = Ed25519.KeyPair.generate(), + .identity_keypair = generateEd25519KeyPair(), .local_node_id = undefined, .noise_keypair = if (p2p_config.network.enable_noise_encryption) (if (p2p_config.network.noise_static_key) |key| @@ -504,27 +516,29 @@ pub const P2P = struct { .state = .Uninitialized, .uptime_seconds = 0, .memory_allocated = 0, - .active_connections = atomic.Value(u32).init(0), - .total_connections = atomic.Value(u64).init(0), - .messages_sent = atomic.Value(u64).init(0), - .messages_received = atomic.Value(u64).init(0), - .current_download_rate = atomic.Value(u64).init(0), - .current_upload_rate = atomic.Value(u64).init(0), - .active_downloads = atomic.Value(u32).init(0), - .active_uploads = atomic.Value(u32).init(0), - .total_downloaded = atomic.Value(u64).init(0), - .total_uploaded = atomic.Value(u64).init(0), + .active_connections = AtomicValue(u32).init(0), + .total_connections = AtomicValue(u64).init(0), + .messages_sent = AtomicValue(u64).init(0), + .messages_received = AtomicValue(u64).init(0), + .current_download_rate = AtomicValue(u64).init(0), + .current_upload_rate = AtomicValue(u64).init(0), + .active_downloads = AtomicValue(u32).init(0), + .active_uploads = AtomicValue(u32).init(0), + .total_downloaded = AtomicValue(u64).init(0), + .total_uploaded = AtomicValue(u64).init(0), .event_queue_size = 0, - .events_processed = atomic.Value(u64).init(0), - .events_dropped = atomic.Value(u64).init(0), - .errors_total = atomic.Value(u64).init(0), - .receive_errors = atomic.Value(u64).init(0), + .events_processed = AtomicValue(u64).init(0), + .events_dropped = AtomicValue(u64).init(0), + .errors_total = AtomicValue(u64).init(0), + .receive_errors = AtomicValue(u64).init(0), }, .start_time = 0, .last_health_check = 0, .last_replay_cleanup = 0, .error_window_start = 0, .last_maintenance_check = 0, + .pending_connections = .{}, + .pending_connections_mutex = Mutex{}, }; errdefer p2p.peer_connections.deinit(); errdefer p2p.event_queue.deinit(allocator); @@ -767,13 +781,21 @@ pub const P2P = struct { p2p.allocator.destroy(pm); } + // Clean up pending (in-progress) connections + for (p2p.pending_connections.items) |*pending| { + pending.deinit(); + } + p2p.pending_connections.deinit(p2p.allocator); + // Close and cleanup peer connections p2p.peer_connections_mutex.lock(); var iter = p2p.peer_connections.iterator(); while (iter.next()) |entry| { const peer_conn = entry.value_ptr.*; - peer_conn.socket.deinit(); - p2p.allocator.destroy(peer_conn.socket); + if (peer_conn.socket) |socket| { + socket.deinit(); + p2p.allocator.destroy(socket); + } peer_conn.deinit(); } p2p.peer_connections.deinit(); @@ -864,6 +886,16 @@ pub const P2P = struct { return connection.acceptConnectionsImpl(p2p); } + /// Start a non-blocking outbound connection (async DoS + Noise handshake). + pub fn startNonBlockingConnect(p2p: *P2P, address: Address) Error!void { + return connection.startNonBlockingConnectImpl(p2p, address); + } + + /// Advance all pending (non-blocking) connections by one step. + pub fn advancePendingConnections(p2p: *P2P) void { + connection.advancePendingConnectionsImpl(p2p); + } + pub fn startListening(p2p: *P2P, address: Address) Error!void { return connection.startListeningImpl(p2p, address); } @@ -884,6 +916,22 @@ pub const P2P = struct { return connection.removePeerConnectionImpl(p2p, peer_id); } + /// Add a peer connection backed by a pre-built Transport (e.g. WebRTC DataChannel). + pub fn addPeerConnectionWithTransport(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport) Error!void { + return connection.addPeerConnectionWithTransportImpl(p2p, peer_id, transport_handle); + } + + /// Add a peer connection with a pre-built Transport and Noise encryption (e.g. WebRTC + Noise). + pub fn addPeerConnectionWithTransportSecure(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport, secure: *SecureConnection) Error!void { + return connection.addPeerConnectionWithTransportSecureImpl(p2p, peer_id, transport_handle, secure); + } + + /// Get the Noise keypair if Noise encryption is enabled. + pub fn getNoiseKeyPair(self: *P2P) ?NoiseKeyPair { + if (self.noise_enabled) return self.noise_keypair; + return null; + } + pub fn sendToPeerAtomic(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!bool { return connection.sendToPeerAtomicImpl(p2p, peer_id, data); } @@ -1660,6 +1708,7 @@ test "P2P: reference all decls" { _ = P2P.addPeerConnection; _ = P2P.addPeerConnectionSecure; _ = P2P.removePeerConnection; + _ = P2P.addPeerConnectionWithTransport; _ = P2P.sendToPeerAtomic; _ = P2P.sendSegmentsToPeerAtomic; _ = P2P.drainPendingSends; @@ -1705,3 +1754,16 @@ test "P2P: reference all decls" { _ = registerNodeIdCallback; _ = handleDataResponseCallback; } + +/// Generate an Ed25519 keypair using platform random (WASM-compatible). +/// Equivalent to Ed25519.KeyPair.generate() but uses platform_random instead of std.crypto.random. +fn generateEd25519KeyPair() Ed25519.KeyPair { + while (true) { + var seed: [Ed25519.KeyPair.seed_length]u8 = undefined; + platform_random.bytes(&seed); + return Ed25519.KeyPair.generateDeterministic(seed) catch { + @branchHint(.unlikely); + continue; + }; + } +} diff --git a/src/p2p/stats.zig b/src/p2p/stats.zig index eca4a1c..3eb02df 100644 --- a/src/p2p/stats.zig +++ b/src/p2p/stats.zig @@ -5,7 +5,7 @@ const std = @import("std"); const Allocator = std.mem.Allocator; -const atomic = std.atomic; +const AtomicValue = @import("sync").AtomicValue; const types = @import("types.zig"); const P2PState = types.P2PState; const core = @import("core"); @@ -33,29 +33,29 @@ pub const P2PStats = struct { /// Total memory allocated memory_allocated: usize, /// Active connections (atomic for thread-safe concurrent updates) - active_connections: atomic.Value(u32), + active_connections: AtomicValue(u32), /// Total connections established (atomic for thread-safe concurrent updates) - total_connections: atomic.Value(u64), + total_connections: AtomicValue(u64), /// Messages sent/received (atomic for thread-safe concurrent updates) - messages_sent: atomic.Value(u64), - messages_received: atomic.Value(u64), + messages_sent: AtomicValue(u64), + messages_received: AtomicValue(u64), /// Bandwidth usage (atomic for thread-safe concurrent updates) - current_download_rate: atomic.Value(u64), // bytes/second - current_upload_rate: atomic.Value(u64), // bytes/second + current_download_rate: AtomicValue(u64), // bytes/second + current_upload_rate: AtomicValue(u64), // bytes/second /// File sharing statistics (atomic for thread-safe concurrent updates) - active_downloads: atomic.Value(u32), - active_uploads: atomic.Value(u32), - total_downloaded: atomic.Value(u64), - total_uploaded: atomic.Value(u64), + active_downloads: AtomicValue(u32), + active_uploads: AtomicValue(u32), + total_downloaded: AtomicValue(u64), + total_uploaded: AtomicValue(u64), /// Event queue statistics event_queue_size: usize, /// Atomic counter for events processed (thread-safe) - events_processed: atomic.Value(u64), + events_processed: AtomicValue(u64), /// Atomic counter for events dropped due to queue full (thread-safe) - events_dropped: atomic.Value(u64), + events_dropped: AtomicValue(u64), /// Error statistics (atomic for thread-safe concurrent updates) - errors_total: atomic.Value(u64), - receive_errors: atomic.Value(u64), + errors_total: AtomicValue(u64), + receive_errors: AtomicValue(u64), last_error: ?Error = null, /// Get formatted statistics string @@ -140,21 +140,21 @@ test "P2PStats: atomic counter operations" { .state = .Initialized, .uptime_seconds = 0, .memory_allocated = 0, - .active_connections = atomic.Value(u32).init(0), - .total_connections = atomic.Value(u64).init(0), - .messages_sent = atomic.Value(u64).init(0), - .messages_received = atomic.Value(u64).init(0), - .current_download_rate = atomic.Value(u64).init(0), - .current_upload_rate = atomic.Value(u64).init(0), - .active_downloads = atomic.Value(u32).init(0), - .active_uploads = atomic.Value(u32).init(0), - .total_downloaded = atomic.Value(u64).init(0), - .total_uploaded = atomic.Value(u64).init(0), + .active_connections = AtomicValue(u32).init(0), + .total_connections = AtomicValue(u64).init(0), + .messages_sent = AtomicValue(u64).init(0), + .messages_received = AtomicValue(u64).init(0), + .current_download_rate = AtomicValue(u64).init(0), + .current_upload_rate = AtomicValue(u64).init(0), + .active_downloads = AtomicValue(u32).init(0), + .active_uploads = AtomicValue(u32).init(0), + .total_downloaded = AtomicValue(u64).init(0), + .total_uploaded = AtomicValue(u64).init(0), .event_queue_size = 0, - .events_processed = atomic.Value(u64).init(0), - .events_dropped = atomic.Value(u64).init(0), - .errors_total = atomic.Value(u64).init(0), - .receive_errors = atomic.Value(u64).init(0), + .events_processed = AtomicValue(u64).init(0), + .events_dropped = AtomicValue(u64).init(0), + .errors_total = AtomicValue(u64).init(0), + .receive_errors = AtomicValue(u64).init(0), }; // Test increment operations