//! Central file sharing coordination //! //! This module provides the main file sharing manager that coordinates //! all file sharing operations including download, upload, and transfer management. //! //! CRIT-NEW-17 FIX: Lock Ordering //! ============================== //! This module's locks are at Level 5 in the global hierarchy. //! See src/network/network_manager.zig for the complete lock ordering. //! //! Lock levels in this module: //! - sessions_mutex: Level 5 //! - file_registry_mutex: Level 5 //! - stats_mutex: Level 0 //! - reputation_mutex: Level 5 //! - config_mutex: Level 4 //! //! IMPORTANT: Never acquire lower-level locks (0-4) while holding Level 5 locks. const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const mem = std.mem; const fmt = std.fmt; const atomic = std.atomic; const core = @import("core"); const Error = core.errors.Error; const hash_mod = @import("hash.zig"); const HashUtils = hash_mod.HashUtils; const FileMetadata = hash_mod.FileMetadata; const PieceHash = hash_mod.PieceHash; const ContentHash = hash_mod.ContentHash; const file_mod = @import("file.zig"); const FileChunker = file_mod.FileChunker; const FileWriter = file_mod.FileWriter; const FileUtils = file_mod.FileUtils; const FileInfo = file_mod.FileInfo; const piece_mod = @import("piece.zig"); const PieceSelector = piece_mod.PieceSelector; const SelectionStrategy = piece_mod.SelectionStrategy; const PiecePool = piece_mod.PiecePool; const download_mod = @import("download.zig"); const DownloadManager = download_mod.DownloadManager; const DownloadQueue = download_mod.DownloadQueue; const DownloadConfig = download_mod.DownloadConfig; const upload_mod = @import("upload.zig"); const UploadManager = upload_mod.UploadManager; const UploadQueue = upload_mod.UploadQueue; const transfer_mod = @import("transfer.zig"); const TransferProtocol = transfer_mod.TransferProtocol; const TransferMessage = transfer_mod.TransferMessage; const TransferConfig = transfer_mod.TransferConfig; const path_security = @import("path_security.zig"); const PathValidator = path_security.PathValidator; const sanitizeFilename = path_security.sanitizeFilename; const verification_pool_mod = @import("verification_pool.zig"); const VerificationPool = verification_pool_mod.VerificationPool; const VerificationPoolConfig = verification_pool_mod.VerificationPoolConfig; const piece_pipeline_mod = @import("piece_pipeline.zig"); const PiecePipeline = piece_pipeline_mod.PiecePipeline; const PiecePipelineConfig = piece_pipeline_mod.PiecePipelineConfig; const PipelineCallbacks = piece_pipeline_mod.PipelineCallbacks; const piece_buffer_pool_mod = @import("piece_buffer_pool.zig"); const adaptive_concurrency = @import("adaptive_concurrency.zig"); const AdaptiveConcurrencyController = adaptive_concurrency.AdaptiveConcurrencyController; /// File sharing limits for memory exhaustion protection /// MED-12 FIX: Now uses centralized limits configuration from core.limits pub const FileSharingLimits = struct { /// Get max piece size from centralized config pub fn maxPieceSize() u64 { return core.limits.global.file.max_piece_size; } /// Get max file size from centralized config pub fn maxFileSize() u64 { return core.limits.global.file.max_file_size; } /// Get max filename length from centralized config pub fn maxFilenameLength() usize { return core.limits.global.file.max_filename_length; } /// Get max sessions from centralized config pub fn maxSessions() usize { return core.limits.global.file.max_sessions; } /// Get max piece data size from centralized config pub fn maxPieceDataSize() usize { return core.limits.global.file.max_piece_data_size; } /// Get max peer memory quota from centralized config pub fn maxPeerMemoryQuota() u64 { return core.limits.global.memory.max_peer_memory_quota; } /// Get max global memory quota from centralized config pub fn maxGlobalMemoryQuota() u64 { return core.limits.global.memory.max_global_memory_quota; } // Compile-time constants for backwards compatibility pub const MAX_PIECE_SIZE: u64 = 64 * 1024 * 1024; pub const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024 * 1024; pub const MAX_FILENAME_LENGTH: usize = 255; pub const MAX_SESSIONS: usize = 1000; pub const MAX_PIECE_DATA_SIZE: usize = 32 * 1024 * 1024; pub const MAX_PEER_MEMORY_QUOTA: u64 = 128 * 1024 * 1024; pub const MAX_GLOBAL_MEMORY_QUOTA: u64 = 2 * 1024 * 1024 * 1024; // PROTOCOL INVARIANT: The wire protocol uses u32 for within-piece offsets. // This compile-time check ensures MAX_PIECE_SIZE can never exceed u32 max, // guaranteeing that all valid within-piece offsets fit in the protocol format. comptime { if (MAX_PIECE_SIZE > std.math.maxInt(u32)) { @compileError("MAX_PIECE_SIZE exceeds u32 max - wire protocol cannot represent within-piece offsets"); } } }; /// Peer reputation tracking for identifying malicious peers /// /// THR-CRIT-2 NOTE: Thread Safety Design /// This struct uses "external locking" - all access to PeerReputation instances /// stored in the FileSharingManager.peer_reputation HashMap is protected by /// FileSharingManager.reputation_mutex. The mutex is held for: /// - All HashMap lookups (.get() returns a copy, safe to use outside mutex) /// - All HashMap modifications (getOrPut + value_ptr mutation within mutex) /// This design is thread-safe because: /// 1. No pointers to PeerReputation escape the mutex-protected region /// 2. All mutations happen while holding the mutex /// 3. Read operations get a copy, not a reference pub const PeerReputation = struct { peer_id: [32]u8, bad_pieces: u32, good_pieces: u32, last_bad_piece_time: i64, blacklisted_until: i64, // HIGH-4 FIX: Per-peer memory usage tracking memory_usage: u64, pending_requests: u32, // MED-4 FIX: Track blacklist count for exponential backoff blacklist_count: u32, // MED-12 FIX: Compile-time constants for backwards compatibility pub const MAX_BAD_PIECES: u32 = 3; // MED-4 FIX: Base duration is now configurable via global config pub const DEFAULT_BLACKLIST_DURATION_SECONDS: i64 = 300; // 5 minutes base pub const MAX_BLACKLIST_DURATION_SECONDS: i64 = 86400; // 24 hours max pub const MAX_PENDING_REQUESTS: u32 = 64; // Max concurrent requests per peer // MED-12 FIX: Runtime accessors for centralized limits pub fn maxBadPieces() u32 { return core.limits.global.security.max_bad_pieces; } pub fn baseBlacklistDuration() i64 { return core.limits.global.security.base_blacklist_duration; } pub fn maxBlacklistDuration() i64 { return core.limits.global.security.max_blacklist_duration; } pub fn maxRequestsPerPeer() u32 { return core.limits.global.security.max_requests_per_peer; } // MED-4 FIX: Global configurable blacklist duration (thread-safe) var configured_base_duration: std.atomic.Value(i64) = std.atomic.Value(i64).init(DEFAULT_BLACKLIST_DURATION_SECONDS); /// MED-4 FIX: Configure the base blacklist duration /// MED-6 FIX: Uses .release ordering for security config to ensure visibility pub fn setBaseBlacklistDuration(seconds: i64) void { if (seconds > 0 and seconds <= MAX_BLACKLIST_DURATION_SECONDS) { configured_base_duration.store(seconds, .release); } } /// MED-4 FIX: Get the current base blacklist duration /// MED-6 FIX: Uses .acquire ordering for security config to ensure visibility pub fn getBaseBlacklistDuration() i64 { return configured_base_duration.load(.acquire); } pub fn init(peer_id: [32]u8) PeerReputation { return PeerReputation{ .peer_id = peer_id, .bad_pieces = 0, .good_pieces = 0, .last_bad_piece_time = 0, .blacklisted_until = 0, .memory_usage = 0, .pending_requests = 0, .blacklist_count = 0, }; } /// HIGH-4 FIX: Check if peer has exceeded their memory quota pub fn hasExceededMemoryQuota(self: *const PeerReputation) bool { return self.memory_usage > FileSharingLimits.MAX_PEER_MEMORY_QUOTA; } /// HIGH-4 FIX: Reserve memory for a pending piece from this peer pub fn reserveMemory(self: *PeerReputation, size: u64) bool { if (self.memory_usage + size > FileSharingLimits.MAX_PEER_MEMORY_QUOTA) { return false; } if (self.pending_requests >= MAX_PENDING_REQUESTS) { return false; } self.memory_usage += size; self.pending_requests += 1; return true; } /// HIGH-4 FIX: Release memory reservation after piece is processed pub fn releaseMemory(self: *PeerReputation, size: u64) void { if (self.memory_usage >= size) { self.memory_usage -= size; } else { self.memory_usage = 0; } if (self.pending_requests > 0) { self.pending_requests -= 1; } } /// Record a bad piece from this peer /// MED-4 FIX: Uses exponential backoff for repeat offenders pub fn recordBadPiece(self: *PeerReputation) void { self.bad_pieces += 1; self.last_bad_piece_time = std.time.timestamp(); // Blacklist peer if they've sent too many bad pieces if (self.bad_pieces >= MAX_BAD_PIECES) { self.blacklist_count += 1; // MED-4 FIX: Exponential backoff - double duration for each subsequent blacklist // Duration = base_duration * 2^(blacklist_count - 1), capped at MAX const base = getBaseBlacklistDuration(); const multiplier: i64 = @as(i64, 1) << @min(self.blacklist_count - 1, 10); // Cap at 2^10 = 1024x const duration = @min(base * multiplier, MAX_BLACKLIST_DURATION_SECONDS); self.blacklisted_until = std.time.timestamp() + duration; std.log.info("MED-4: Peer blacklisted for {}s (offense #{}, base={}s)", .{ duration, self.blacklist_count, base, }); } } /// Record a good piece from this peer pub fn recordGoodPiece(self: *PeerReputation) void { self.good_pieces += 1; } /// Check if peer is currently blacklisted pub fn isBlacklisted(self: *const PeerReputation) bool { return std.time.timestamp() < self.blacklisted_until; } /// Get reputation score (0.0 to 1.0, higher is better) pub fn getScore(self: *const PeerReputation) f32 { const total = self.good_pieces + self.bad_pieces; if (total == 0) return 0.5; // Neutral for new peers return @as(f32, @floatFromInt(self.good_pieces)) / @as(f32, @floatFromInt(total)); } /// Reset reputation (e.g., after blacklist expires) pub fn reset(self: *PeerReputation) void { self.bad_pieces = 0; self.good_pieces = 0; self.blacklisted_until = 0; } }; /// FAIR QUEUE ARCHITECTURE: Per-peer response slot tracking /// /// This struct implements fair queuing for piece_data responses to ensure no single peer /// can monopolize the response queue. Each peer gets a fair share of response slots, /// with guaranteed minimums and enforced maximums. /// /// Design: /// - Track queued piece_data count per peer /// - Calculate fair share dynamically based on active peer count /// - Guarantee minimum slots (16) for every peer /// - Cap maximum slots per peer to prevent monopolization /// - Prioritize peers with fewer pending responses when queue is congested /// /// Thread Safety: Protected by the session's transfer_protocol mutex (sessions_mutex) pub const PeerResponseTracker = struct { /// Per-peer slot allocation tracking peer_slots: std.AutoHashMap([32]u8, PeerSlotInfo), /// Memory allocator allocator: mem.Allocator, /// Configuration max_total_slots: usize, min_slots_per_peer: usize, max_slots_per_peer: usize, /// Per-peer tracking info pub const PeerSlotInfo = struct { /// Number of piece_data messages queued for this peer queued_count: u32, /// Timestamp of last activity (for cleanup of stale entries) last_activity: i64, /// Total bytes queued for this peer (for memory tracking) queued_bytes: u64, pub fn init() PeerSlotInfo { return .{ .queued_count = 0, .last_activity = std.time.timestamp(), .queued_bytes = 0, }; } }; /// Fair queue configuration constants pub const Config = struct { /// Minimum guaranteed slots per peer (ensures progress for all peers) pub const MIN_SLOTS_PER_PEER: usize = 32; /// Maximum slots any single peer can use (prevents monopolization) /// THROUGHPUT FIX: Increased from 512 to 2048 to match max_total_slots. /// With single-peer scenarios (1 downloader from N seeders), the per-peer /// limit was causing request rejection even when total capacity available. pub const MAX_SLOTS_PER_PEER: usize = 2048; /// Soft limit percentage - allow new requests below this threshold freely pub const SOFT_LIMIT_PERCENT: usize = 70; /// Stale peer cleanup interval (5 minutes) pub const STALE_PEER_TIMEOUT_MS: i64 = 5 * 60 * 1000; }; pub fn init(allocator: mem.Allocator, max_total_slots: usize) PeerResponseTracker { return .{ .peer_slots = std.AutoHashMap([32]u8, PeerSlotInfo).init(allocator), .allocator = allocator, .max_total_slots = max_total_slots, .min_slots_per_peer = Config.MIN_SLOTS_PER_PEER, .max_slots_per_peer = Config.MAX_SLOTS_PER_PEER, }; } pub fn deinit(self: *PeerResponseTracker) void { self.peer_slots.deinit(); } /// Get total slots currently in use pub fn getTotalSlotsUsed(self: *const PeerResponseTracker) usize { var total: usize = 0; var iter = self.peer_slots.valueIterator(); while (iter.next()) |info| { total += info.queued_count; } return total; } /// Get number of active peers (peers with queued responses) pub fn getActivePeerCount(self: *const PeerResponseTracker) usize { return self.peer_slots.count(); } /// Calculate fair share per peer based on active peer count pub fn calculateFairShare(self: *const PeerResponseTracker) usize { const active_peers = @max(1, self.getActivePeerCount()); const fair = self.max_total_slots / active_peers; // Fair share bounded between min and max return @max(self.min_slots_per_peer, @min(fair, self.max_slots_per_peer)); } /// Check if a peer can be allocated a new response slot /// Returns: .allowed, .soft_limit (allowed but near capacity), or .rejected pub const AllocationResult = enum { allowed, soft_limit, rejected_peer_limit, rejected_total_limit, }; pub fn canAllocateSlot(self: *PeerResponseTracker, peer_id: [32]u8) AllocationResult { const total_used = self.getTotalSlotsUsed(); const peer_count = self.peer_slots.get(peer_id); const peer_slots = if (peer_count) |info| info.queued_count else 0; const fair_share = self.calculateFairShare(); const soft_limit = self.max_total_slots * Config.SOFT_LIMIT_PERCENT / 100; // Rule 1: Hard limit - never exceed max total slots if (total_used >= self.max_total_slots) { return .rejected_total_limit; } // Rule 2: Peer limit - no peer can exceed their max allocation // Max is 2x fair share, capped at absolute max const peer_max = @min(fair_share * 2, self.max_slots_per_peer); if (peer_slots >= peer_max) { return .rejected_peer_limit; } // Rule 3: Below soft limit - allow freely if (total_used < soft_limit) { return .allowed; } // Rule 4: Above soft limit - only allow if peer is below fair share // This prioritizes peers with fewer pending responses if (peer_slots < fair_share) { return .soft_limit; } // Rule 5: Peer is at or above fair share while queue is congested - reject return .rejected_peer_limit; } /// Allocate a response slot for a peer /// Returns true if allocation succeeded, false if rejected pub fn allocateSlot(self: *PeerResponseTracker, peer_id: [32]u8, piece_size: u64) bool { const result = self.canAllocateSlot(peer_id); switch (result) { .allowed, .soft_limit => { const gop = self.peer_slots.getOrPut(peer_id) catch return false; if (!gop.found_existing) { gop.value_ptr.* = PeerSlotInfo.init(); } gop.value_ptr.queued_count += 1; gop.value_ptr.queued_bytes += piece_size; gop.value_ptr.last_activity = std.time.timestamp(); return true; }, .rejected_peer_limit, .rejected_total_limit => return false, } } /// Release a response slot when message is sent pub fn releaseSlot(self: *PeerResponseTracker, peer_id: [32]u8, piece_size: u64) void { if (self.peer_slots.getPtr(peer_id)) |info| { if (info.queued_count > 0) { info.queued_count -= 1; } if (info.queued_bytes >= piece_size) { info.queued_bytes -= piece_size; } else { info.queued_bytes = 0; } info.last_activity = std.time.timestamp(); // Clean up entry if peer has no more queued responses if (info.queued_count == 0) { _ = self.peer_slots.remove(peer_id); } } } /// Remove all slots for a disconnected peer pub fn removePeer(self: *PeerResponseTracker, peer_id: [32]u8) u32 { if (self.peer_slots.fetchRemove(peer_id)) |kv| { return kv.value.queued_count; } return 0; } /// Clean up stale peer entries (peers with no activity for a while) pub fn cleanupStalePeers(self: *PeerResponseTracker) usize { const now = std.time.timestamp(); var to_remove = std.ArrayList([32]u8).init(self.allocator); defer to_remove.deinit(); var iter = self.peer_slots.iterator(); while (iter.next()) |entry| { const age_ms = (now - entry.value_ptr.last_activity) * 1000; if (age_ms > Config.STALE_PEER_TIMEOUT_MS and entry.value_ptr.queued_count == 0) { to_remove.append(entry.key_ptr.*) catch continue; } } for (to_remove.items) |peer_id| { _ = self.peer_slots.remove(peer_id); } return to_remove.items.len; } /// Get statistics for debugging/monitoring pub const Stats = struct { total_slots_used: usize, max_total_slots: usize, active_peer_count: usize, fair_share: usize, utilization_percent: usize, }; pub fn getStats(self: *PeerResponseTracker) Stats { const total = self.getTotalSlotsUsed(); return .{ .total_slots_used = total, .max_total_slots = self.max_total_slots, .active_peer_count = self.getActivePeerCount(), .fair_share = self.calculateFairShare(), .utilization_percent = if (self.max_total_slots > 0) total * 100 / self.max_total_slots else 0, }; } /// Log current state for debugging (only when significant) pub fn logState(self: *PeerResponseTracker, piece_index: u32) void { // Only log every 50 pieces to reduce spam if (piece_index % 50 != 0) return; const stats = self.getStats(); std.log.info("FAIR QUEUE: {}/{} slots ({} peers, fair_share={})", .{ stats.total_slots_used, stats.max_total_slots, stats.active_peer_count, stats.fair_share, }); } }; /// Network sender callback type for actual message transmission /// Returns true if message was sent successfully, false otherwise pub const NetworkSendCallback = *const fn (peer_id: []const u8, data: []const u8, context: ?*anyopaque) bool; /// ZERO-COPY: Network sender callback for scatter-gather sends /// Sends multiple segments without copying them into a single buffer /// Returns true if all segments were sent successfully, false otherwise pub const NetworkSendSegmentsCallback = *const fn (peer_id: []const u8, segments: []const []const u8, context: ?*anyopaque) bool; /// Network sender interface for transmitting messages over the network /// Callback to get all connected peer IDs for broadcasting /// Returns the number of peer IDs written to the buffer pub const GetConnectedPeersCallback = *const fn ( out_peers: [][32]u8, context: ?*anyopaque, ) usize; pub const NetworkSender = struct { /// Callback function for sending data (single buffer) send_fn: NetworkSendCallback, /// ZERO-COPY: Callback function for sending multiple segments send_segments_fn: ?NetworkSendSegmentsCallback, /// Callback to get all connected peers for broadcasting get_peers_fn: ?GetConnectedPeersCallback, /// User context passed to callback context: ?*anyopaque, /// Allocator for serialization allocator: mem.Allocator, pub fn init(send_fn: NetworkSendCallback, context: ?*anyopaque, allocator: mem.Allocator) NetworkSender { return NetworkSender{ .send_fn = send_fn, .send_segments_fn = null, .get_peers_fn = null, .context = context, .allocator = allocator, }; } pub fn initWithPeers( send_fn: NetworkSendCallback, get_peers_fn: GetConnectedPeersCallback, context: ?*anyopaque, allocator: mem.Allocator, ) NetworkSender { return NetworkSender{ .send_fn = send_fn, .send_segments_fn = null, .get_peers_fn = get_peers_fn, .context = context, .allocator = allocator, }; } /// ZERO-COPY: Initialize with all callbacks including scatter-gather support pub fn initWithSegments( send_fn: NetworkSendCallback, send_segments_fn: NetworkSendSegmentsCallback, get_peers_fn: GetConnectedPeersCallback, context: ?*anyopaque, allocator: mem.Allocator, ) NetworkSender { return NetworkSender{ .send_fn = send_fn, .send_segments_fn = send_segments_fn, .get_peers_fn = get_peers_fn, .context = context, .allocator = allocator, }; } /// ZERO-COPY: Send multiple segments without copying /// Falls back to single-buffer send if segments callback not available pub fn sendSegments(self: *const NetworkSender, peer_id: []const u8, segments: []const []const u8) bool { if (self.send_segments_fn) |send_segments| { return send_segments(peer_id, segments, self.context); } // Fallback: concatenate segments and use single-buffer send var total_len: usize = 0; for (segments) |seg| { total_len += seg.len; } const buffer = self.allocator.alloc(u8, total_len) catch return false; defer self.allocator.free(buffer); var offset: usize = 0; for (segments) |seg| { @memcpy(buffer[offset..][0..seg.len], seg); offset += seg.len; } return self.send_fn(peer_id, buffer, self.context); } /// Get all connected peers pub fn getConnectedPeers(self: *const NetworkSender, out_peers: [][32]u8) usize { if (self.get_peers_fn) |get_peers| { return get_peers(out_peers, self.context); } return 0; } /// Send a transfer message to a peer pub fn sendMessage(self: *NetworkSender, message: TransferMessage) Error!bool { // Serialize the message const data = message.serialize(self.allocator) catch { return Error.SocketSendFailed; }; defer self.allocator.free(data); // Send via callback return self.send_fn(message.peer_id, data, self.context); } }; /// ZERO-COPY: Pre-serialized piece response for scatter-gather sending /// This struct is specifically designed for the piece_data response format expected by handlePieceData. /// /// Wire format (after app_prefix which is added by transport): /// [type:1][msg_id:4][peer_len:2][timestamp:8][data_len:4][peer_id:32][content_hash:32][piece_index:4][offset:4][piece_data:N] /// /// Split into segments: /// - header: [type:1][msg_id:4][peer_len:2][timestamp:8][data_len:4][peer_id:32] = 51 bytes /// - prefix: [content_hash:32][piece_index:4][offset:4] = 40 bytes /// - data: [piece_data:N] (borrowed from mmap, zero-copy) pub const PreSerializedPieceResponse = struct { /// Pre-serialized header + prefix (91 bytes total) /// Layout: [app_prefix:1][type:1][msg_id:4][peer_len:2][timestamp:8][data_len:4][peer_id:32][content_hash:32][piece_index:4][offset:4] header: [92]u8, // 1 (app_prefix) + 51 (msg header) + 40 (data prefix) = 92 bytes header_len: usize, /// Reference to piece data (NOT owned unless owns_data is true) data: []const u8, /// Peer ID for routing (used by sendSegments) peer_id: [32]u8, /// Whether we own the data and must free it owns_data: bool, /// Allocator (only used if owns_data is true) allocator: ?mem.Allocator, /// Create pre-serialized piece response from components /// ZERO-COPY: Only builds header, data is borrowed (not copied!) pub fn create( peer_id: [32]u8, content_hash: [32]u8, piece_index: u32, offset_val: u32, data: []const u8, owns_data: bool, data_allocator: ?mem.Allocator, ) PreSerializedPieceResponse { var result = PreSerializedPieceResponse{ .header = undefined, .header_len = 0, .data = data, .peer_id = peer_id, .owns_data = owns_data, .allocator = data_allocator, }; // Build header in-place (no allocation!) var off: usize = 0; // App prefix (1 byte) - file transfer = 0x01 result.header[off] = 0x01; off += 1; // Message type (1 byte) - piece_data = 6 result.header[off] = @intFromEnum(transfer_mod.MessageType.piece_data); off += 1; // Message ID (4 bytes, big endian) const msg_id = std.crypto.random.int(u32); std.mem.writeInt(u32, result.header[off..][0..4], msg_id, .big); off += 4; // Peer ID length (2 bytes, big endian) - always 32 std.mem.writeInt(u16, result.header[off..][0..2], 32, .big); off += 2; // Timestamp (8 bytes, big endian) const timestamp = std.time.timestamp(); std.mem.writeInt(i64, result.header[off..][0..8], timestamp, .big); off += 8; // Data length (4 bytes, big endian) // Data = [content_hash:32][piece_index:4][offset:4][piece_data:N] const data_len: u32 = @intCast(32 + 4 + 4 + data.len); std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big); off += 4; // Peer ID (32 bytes) @memcpy(result.header[off..][0..32], &peer_id); off += 32; // --- Data prefix starts here --- // Content hash (32 bytes) @memcpy(result.header[off..][0..32], &content_hash); off += 32; // Piece index (4 bytes, big endian) std.mem.writeInt(u32, result.header[off..][0..4], piece_index, .big); off += 4; // Offset (4 bytes, big endian) std.mem.writeInt(u32, result.header[off..][0..4], offset_val, .big); off += 4; result.header_len = off; // Should be 92 bytes return result; } /// Get segments for scatter-gather send /// Returns 2 segments: [header+prefix, piece_data] pub fn getSegments(self: *const PreSerializedPieceResponse) [2][]const u8 { return [2][]const u8{ self.header[0..self.header_len], self.data, }; } /// Get total wire size (for logging/debugging) pub fn wireSize(self: *const PreSerializedPieceResponse) usize { return self.header_len + self.data.len; } /// Free owned resources pub fn deinit(self: *PreSerializedPieceResponse) void { if (self.owns_data) { if (self.allocator) |alloc| { const data_mut: []u8 = @constCast(self.data); alloc.free(data_mut); } } self.* = undefined; } }; /// File sharing manager configuration /// Defaults are read from the centralized core.limits configuration pub const FileSharingConfig = struct { piece_size: u64 = core.limits.defaults.file.piece_size, max_concurrent_downloads: usize = core.limits.defaults.file.max_concurrent_downloads, max_concurrent_uploads: usize = core.limits.defaults.file.max_concurrent_uploads, max_bandwidth_download: u64 = core.limits.defaults.file.max_bandwidth_download, max_bandwidth_upload: u64 = core.limits.defaults.file.max_bandwidth_upload, selection_strategy: SelectionStrategy = .rarest_first, enable_upload: bool = true, enable_download: bool = true, auto_verify: bool = true, temp_dir: []const u8 = "tests/test_data/temp", allowed_share_directories: []const []const u8 = &[_][]const u8{}, allow_symlinks: bool = false, /// MED-14 FIX: Maximum number of files to track in registry max_registry_files: usize = 10000, /// MED-15 FIX: Maximum number of peers to track reputation for max_reputation_peers: usize = 1000, /// Buffer pool size for piece verification (default: 64 buffers of piece_size each) /// Higher values use more memory but improve throughput for large transfers buffer_pool_size: usize = 64, /// Number of pipeline workers for disk I/O. /// pwrite() is fast (~0.1ms to kernel buffer), so 2 workers is sufficient /// for most workloads. Increase only if disk I/O is slow. pipeline_workers: u32 = 2, /// Number of verification workers (0 = auto-detect based on CPU count) verification_workers: u32 = 8, /// Enable adaptive concurrency control (AIMD-based) /// When enabled, max_concurrent_downloads is dynamically adjusted based on network health adaptive_concurrency_enabled: bool = true, /// Minimum concurrency limit (floor for AIMD decrease) /// Lower values allow more aggressive throttling when network is congested adaptive_min_concurrency: usize = 64, /// Maximum concurrency limit (ceiling for AIMD increase) adaptive_max_concurrency: usize = 256, /// Initial concurrency (starting point for AIMD) /// THROUGHPUT FIX: Reduced from 200 to 100 to avoid initial congestion collapse. /// Starting too high causes request pile-up, timeouts, and adaptive decrease spiral. adaptive_initial_concurrency: usize = 100, pub fn default() FileSharingConfig { return FileSharingConfig{}; } pub fn high_performance() FileSharingConfig { return FileSharingConfig{ .max_concurrent_downloads = 256, // CASCADE PERF: Increased from 8 .max_concurrent_uploads = 256, // CASCADE PERF: Increased from 8 .max_bandwidth_download = 1024 * 1024 * 1024, // 1 GB/s .max_bandwidth_upload = 1024 * 1024 * 1024, // 1 GB/s .piece_size = 1024 * 1024, // 1MB pieces for parallel download .selection_strategy = .balanced, .pipeline_workers = 4, // pwrite is fast; 4 workers sufficient even for high throughput .verification_workers = 16, .buffer_pool_size = 128, // Larger buffer pool // ADAPTIVE: Balanced limits for high-performance scenarios .adaptive_concurrency_enabled = true, .adaptive_min_concurrency = 64, .adaptive_max_concurrency = 256, .adaptive_initial_concurrency = 128, }; } pub fn low_bandwidth() FileSharingConfig { return FileSharingConfig{ .max_concurrent_downloads = 2, .max_concurrent_uploads = 2, .max_bandwidth_download = 256 * 1024, // 256KB/s .max_bandwidth_upload = 256 * 1024, // 256KB/s .piece_size = 8 * 1024 * 1024, // 8MB pieces .selection_strategy = .sequential, }; } }; /// File sharing session pub const FileSharingSession = struct { session_id: u64, file_metadata: FileMetadata, /// PERF FIX: Cached content_hash to avoid O(piece_count) recomputation on every lookup. /// Computed once at session creation from metadataHash(file_metadata). content_hash: [32]u8, download_manager: ?DownloadManager, upload_manager: ?UploadManager, transfer_protocol: TransferProtocol, piece_pool: PiecePool, status: SessionStatus, created_at: i64, updated_at: i64, allocator: mem.Allocator, /// FAIR QUEUE: Per-peer response slot tracking for upload sessions response_tracker: ?PeerResponseTracker, /// ZERO-COPY: Queue for pre-serialized piece responses (scatter-gather optimized) pending_piece_responses: std.ArrayList(PreSerializedPieceResponse), pub const SessionStatus = enum(u8) { initializing = 1, ready = 2, downloading = 3, uploading = 4, completed = 5, failed = 6, cancelled = 7, }; /// Create new file sharing session pub fn create( file_metadata: FileMetadata, _: FileSharingConfig, allocator: mem.Allocator, ) Error!FileSharingSession { // PERF FIX: Compute content_hash once at creation instead of on every lookup. // This saves O(piece_count) hash operations per lookup (81920 ops for 5GB file). const content_hash = try HashUtils.metadataHash(file_metadata); return FileSharingSession{ .session_id = std.crypto.random.int(u64), .file_metadata = file_metadata, .content_hash = content_hash, .download_manager = null, .upload_manager = null, .transfer_protocol = TransferProtocol.init(allocator), .piece_pool = PiecePool.init(allocator), .status = .initializing, .created_at = std.time.timestamp(), .updated_at = std.time.timestamp(), .allocator = allocator, .response_tracker = null, // Initialized when upload starts .pending_piece_responses = .{}, }; } pub fn deinit(self: *FileSharingSession) void { // MEM-M1 FIX: Proper cleanup order to prevent use-after-free // 1. First, clean up managers that might reference transfer_protocol if (self.download_manager) |*manager| { manager.deinit(); self.download_manager = null; } if (self.upload_manager) |*manager| { manager.deinit(); self.upload_manager = null; } // 2. Clean up fair queue tracker if (self.response_tracker) |*tracker| { tracker.deinit(); self.response_tracker = null; } // 2.5 ZERO-COPY: Clean up pre-serialized piece responses queue for (self.pending_piece_responses.items) |*resp| { resp.deinit(); } self.pending_piece_responses.deinit(self.allocator); // 3. Clean up piece pool (may reference transfer state) self.piece_pool.deinit(); // 4. Finally clean up transfer protocol self.transfer_protocol.deinit(); // 5. Free metadata allocations (check for valid pointers) if (self.file_metadata.piece_hashes.len > 0) { self.allocator.free(self.file_metadata.piece_hashes); } if (self.file_metadata.name.len > 0) { self.allocator.free(self.file_metadata.name); } // MEM-M1 FIX: Mark as deinitialized self.status = .failed; } /// Initialize download manager pub fn initDownload(self: *FileSharingSession, output_path: []const u8, config: FileSharingConfig, allocator: mem.Allocator) Error!void { if (!config.enable_download) return Error.OperationNotSupported; // Calculate piece_size from metadata to match how the file was chunked // This ensures write offsets match the original piece boundaries const piece_size: u64 = if (self.file_metadata.piece_count > 0) (self.file_metadata.size + self.file_metadata.piece_count - 1) / self.file_metadata.piece_count else config.piece_size; var manager = try DownloadManager.init( self.file_metadata.size, self.file_metadata.piece_count, config.selection_strategy, piece_size, allocator, ); try manager.setOutputFile(output_path); self.download_manager = manager; self.status = .ready; } /// Initialize upload manager pub fn initUpload(self: *FileSharingSession, file_path: []const u8, config: FileSharingConfig, allocator: mem.Allocator) Error!void { if (!config.enable_upload) return Error.OperationNotSupported; var manager = try UploadManager.init( config.max_bandwidth_upload, config.piece_size, allocator, ); // Set the file path so the upload manager can read piece data try manager.setFilePath(file_path, self.file_metadata.size); // Add all pieces as available for upload for (self.file_metadata.piece_hashes, 0..) |hash, i| { try manager.addAvailablePiece(@as(u32, @intCast(i)), hash); } self.upload_manager = manager; // FAIR QUEUE: Initialize response tracker for this upload session // Calculate max slots based on piece size (384MB / piece_size) const piece_size = config.piece_size; const max_slots = FileSharingManager.calculateMaxQueuedResponses(piece_size); self.response_tracker = PeerResponseTracker.init(allocator, max_slots); self.status = .ready; } /// Initialize upload manager for cascade support (download-to-upload) /// CASCADE FIX: This is called for download sessions to enable serving pieces /// to other peers as soon as we download them (cascading distribution). /// Unlike initUpload, this does NOT add any pieces - they are added as we download them. pub fn initUploadForCascade(self: *FileSharingSession, file_path: []const u8, config: FileSharingConfig, allocator: mem.Allocator) Error!void { // CASCADE: Even if upload is "disabled", we need upload capability for cascading // Skip only if explicitly forbidden by config (future: add cascade_enabled flag) // CASCADE PERF: Use config bandwidth limit (default 1 GB/s for high performance) // Previous 50 MB/s was too low and caused ResourceExhausted errors const bandwidth = if (config.max_bandwidth_upload > 0) config.max_bandwidth_upload else 1024 * 1024 * 1024; const piece_size: u64 = if (self.file_metadata.piece_count > 0) (self.file_metadata.size + self.file_metadata.piece_count - 1) / self.file_metadata.piece_count else 1024 * 1024; // Default 1MB piece size var manager = try UploadManager.init( bandwidth, piece_size, allocator, ); // Set the file path so the upload manager can read piece data we've downloaded // CASCADE FIX: Disable mmap for cascade scenario - the file is being actively // written by DownloadManager, and MAP_PRIVATE mmap may return stale data. try manager.setFilePathWithOptions(file_path, self.file_metadata.size, true); // Don't add any pieces - they'll be added via markPieceAvailableForUpload // as we successfully download and verify them self.upload_manager = manager; // FAIR QUEUE: Initialize response tracker for cascade uploads const max_slots = FileSharingManager.calculateMaxQueuedResponses(piece_size); self.response_tracker = PeerResponseTracker.init(allocator, max_slots); std.log.debug("CASCADE: Upload manager initialized for download session (fair queue: {} slots)", .{max_slots}); } /// Update session timestamp pub fn update(self: *FileSharingSession) void { self.updated_at = std.time.timestamp(); } /// Check if session is active /// CASCADE FIX: Completed sessions with upload capability should remain active /// so they can continue serving pieces to other peers. This is critical for /// cascade distribution where completed downloaders become seeders. pub fn isActive(self: *FileSharingSession) bool { return switch (self.status) { .initializing, .ready, .downloading, .uploading => true, .completed => { // Completed sessions should remain active if they have: // 1. An upload manager (can serve pieces) // 2. Pending response messages to send const has_upload = self.upload_manager != null; const has_pending = self.transfer_protocol.pending_responses.items.len > 0 or self.transfer_protocol.pending_requests.items.len > 0; return has_upload or has_pending; }, .failed, .cancelled => false, }; } /// Get session progress pub fn getProgress(self: *FileSharingSession) f32 { switch (self.status) { .downloading => { if (self.download_manager) |*manager| { return manager.getStats().progress; } }, .uploading => { if (self.upload_manager) |*manager| { const stats = manager.getStats(); if (self.file_metadata.piece_count > 0) { return @as(f32, @floatFromInt(stats.state.completed_uploads)) / @as(f32, @floatFromInt(self.file_metadata.piece_count)); } } }, .completed => return 1.0, else => {}, } return 0.0; } /// Get session statistics pub fn getStats(self: *FileSharingSession) SessionStats { const pieces_completed: u32 = blk: { if (self.download_manager) |*dm| { break :blk dm.state.completed_pieces.load(.acquire); } if (self.upload_manager) |*um| { break :blk um.getStats().state.completed_uploads; } break :blk 0; }; return SessionStats{ .session_id = self.session_id, .status = self.status, .progress = self.getProgress(), .file_size = self.file_metadata.size, .piece_count = self.file_metadata.piece_count, .pieces_completed = pieces_completed, .created_at = self.created_at, .updated_at = self.updated_at, }; } }; /// File sharing manager - central coordination pub const FileSharingManager = struct { config: FileSharingConfig, sessions: std.AutoHashMap(u64, FileSharingSession), download_queue: DownloadQueue, upload_queue: UploadQueue, file_registry: std.AutoHashMap(ContentHash, FileInfo), allocator: mem.Allocator, temp_dir: []const u8, /// Network sender for actual message transmission (optional) network_sender: ?*NetworkSender, /// Statistics for network transmission messages_sent: u64, messages_failed: u64, /// Reference to P2P context for full integration p2p_context: ?*anyopaque, /// Path validator for security path_validator: PathValidator, /// Peer reputation tracking for identifying malicious peers peer_reputation: std.AutoHashMap([32]u8, PeerReputation), /// PERF: Thread pool for parallel SHA-256 verification verification_pool: ?*VerificationPool, /// PERF: Multi-threaded piece processing pipeline piece_pipeline: ?*PiecePipeline, /// Adaptive concurrency controller (optional based on config) /// Dynamically adjusts max_concurrent_downloads based on network health adaptive_controller: ?AdaptiveConcurrencyController, /// TIMING: Counter for periodic timing logs timing_log_counter: u32 = 0, // ======================================================================== // HIGH-5 FIX: LOCK ORDERING DOCUMENTATION // ======================================================================== // To prevent deadlocks, mutexes MUST be acquired in this order: // // 1. reputation_mutex (outer-most) // 2. sessions_mutex // 3. file_registry_mutex (independent, but after sessions if both needed) // 4. config_mutex (inner-most) // 5. stats_mutex (independent, low contention) // // RULES: // - NEVER acquire reputation_mutex while holding sessions_mutex // - NEVER acquire sessions_mutex while holding config_mutex // - stats_mutex and file_registry_mutex are leaf locks (no nesting) // // THR-H3 FIX: handlePieceData respects this by deferring reputation updates // until AFTER releasing sessions_mutex. // // DownloadManager.manager_mutex is only acquired while holding sessions_mutex, // so it's implicitly ordered after sessions_mutex. // ======================================================================== sessions_mutex: std.Thread.Mutex = .{}, file_registry_mutex: std.Thread.Mutex = .{}, stats_mutex: std.Thread.Mutex = .{}, // Protects messages_sent/failed /// THR-CRIT-2: Protects peer_reputation HashMap and all PeerReputation entry mutations. /// All HashMap access (.get, .getOrPut, .put) must be done while holding this mutex. /// Mutations to PeerReputation entries (recordBadPiece, recordGoodPiece) must be done /// while holding this mutex. Read operations via .get() return a copy which is safe /// to use outside the mutex. reputation_mutex: std.Thread.Mutex = .{}, /// THR-H2 FIX: Protects runtime config modifications (bandwidth limits, strategies, features) /// Config is read during session operations and modified via updateBandwidthLimits, /// setSelectionStrategy, setFeatures. Mutex ensures atomic reads/writes. config_mutex: std.Thread.Mutex = .{}, // HIGH-5 FIX: Debug tracking for lock ordering verification lock_order_debug: if (@import("builtin").mode == .Debug) LockOrderDebug else void = if (@import("builtin").mode == .Debug) .{} else {}, const LockOrderDebug = struct { // MED-5 FIX: Thread-local storage for per-thread lock tracking // Using threadlocal static ensures each thread has its own copy threadlocal var tls_reputation_held: bool = false; threadlocal var tls_sessions_held: bool = false; threadlocal var tls_file_registry_held: bool = false; threadlocal var tls_config_held: bool = false; // Statistics for lock order violations (for monitoring) - global counter is fine violations_detected: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), fn checkCanAcquireSessions(self: *LockOrderDebug) Error!void { // sessions_mutex can only be acquired if we either: // 1. Already hold reputation_mutex, OR // 2. Don't hold any lock that should come after sessions // MED-5 FIX: Use thread-local storage for current thread's lock state if (tls_config_held) { std.log.err("LOCK ORDER VIOLATION: Attempting to acquire sessions_mutex while holding config_mutex!", .{}); _ = self.violations_detected.fetchAdd(1, .monotonic); return Error.LockOrderViolation; } } fn checkCanAcquireReputation(self: *LockOrderDebug) Error!void { // reputation_mutex must be first - cannot hold sessions or config // MED-5 FIX: Use thread-local storage for current thread's lock state if (tls_sessions_held or tls_config_held) { std.log.err("LOCK ORDER VIOLATION: Attempting to acquire reputation_mutex while holding inner locks!", .{}); _ = self.violations_detected.fetchAdd(1, .monotonic); return Error.LockOrderViolation; } } // MED-5 FIX: Thread-safe accessors for lock state fn setReputationHeld(held: bool) void { tls_reputation_held = held; } fn setSessionsHeld(held: bool) void { tls_sessions_held = held; } fn setFileRegistryHeld(held: bool) void { tls_file_registry_held = held; } fn setConfigHeld(held: bool) void { tls_config_held = held; } fn getViolationCount(self: *const LockOrderDebug) u64 { return self.violations_detected.load(.monotonic); } }; pub fn init(config: FileSharingConfig, allocator: mem.Allocator) Error!FileSharingManager { // Ensure temp directory exists try FileUtils.ensureDir(config.temp_dir); // Build allowed directories list (temp_dir + configured share dirs) var allowed_dirs = std.ArrayList([]const u8){}; defer allowed_dirs.deinit(allocator); // Add temp directory as allowed try allowed_dirs.append(allocator, config.temp_dir); // Add configured share directories for (config.allowed_share_directories) |dir| { try allowed_dirs.append(allocator, dir); } // Create path validator with all allowed directories const allowed_dirs_slice = try allocator.dupe([]const u8, allowed_dirs.items); errdefer allocator.free(allowed_dirs_slice); var path_validator = PathValidator.init(allowed_dirs_slice); path_validator.allow_symlinks = config.allow_symlinks; // PERF: Create verification pool for parallel SHA-256 with buffer pool const pool_ptr = allocator.create(VerificationPool) catch { return Error.OutOfMemory; }; errdefer allocator.destroy(pool_ptr); pool_ptr.* = VerificationPool.init(allocator, .{ .num_workers = config.verification_workers, // 0 = auto-detect .max_pending_tasks = 2048, .use_results_queue = true, // PERF: Pre-allocate buffers for piece verification .num_piece_buffers = config.buffer_pool_size, .piece_buffer_size = config.piece_size, }) catch { // errdefer will handle destroy return Error.OutOfMemory; }; // Add deinit errdefer after successful init errdefer pool_ptr.deinit(); // PERF: Create piece processing pipeline const pipeline_ptr = allocator.create(PiecePipeline) catch { // errdefers will handle pool cleanup return Error.OutOfMemory; }; pipeline_ptr.* = PiecePipeline.init(allocator, .{ .num_workers = config.pipeline_workers, // 0 = auto-detect .max_queue_size = 4096, }); // Create adaptive concurrency controller if enabled const adaptive_ctrl = if (config.adaptive_concurrency_enabled) AdaptiveConcurrencyController.init(.{ .min_concurrency = config.adaptive_min_concurrency, .max_concurrency = config.adaptive_max_concurrency, .initial_concurrency = config.adaptive_initial_concurrency, }) else null; return FileSharingManager{ .config = config, .sessions = std.AutoHashMap(u64, FileSharingSession).init(allocator), .download_queue = DownloadQueue.init(allocator), .upload_queue = UploadQueue.init(allocator), .file_registry = std.AutoHashMap(ContentHash, FileInfo).init(allocator), .allocator = allocator, .temp_dir = config.temp_dir, .network_sender = null, .messages_sent = 0, .messages_failed = 0, .p2p_context = null, .path_validator = path_validator, .peer_reputation = std.AutoHashMap([32]u8, PeerReputation).init(allocator), .verification_pool = pool_ptr, .piece_pipeline = pipeline_ptr, .adaptive_controller = adaptive_ctrl, }; } /// Initialize for testing - creates a lighter manager without thread pools /// This is useful for unit tests that don't need parallel verification pub fn initForTesting(config: FileSharingConfig, allocator: mem.Allocator) Error!FileSharingManager { // Ensure temp directory exists try FileUtils.ensureDir(config.temp_dir); // Build allowed directories list (temp_dir + configured share dirs) var allowed_dirs = std.ArrayList([]const u8){}; defer allowed_dirs.deinit(allocator); try allowed_dirs.append(allocator, config.temp_dir); for (config.allowed_share_directories) |dir| { try allowed_dirs.append(allocator, dir); } const allowed_dirs_slice = try allocator.dupe([]const u8, allowed_dirs.items); // FIX: Add errdefer to free allocated slice if subsequent initialization fails // This matches the production init() pattern at line 664 errdefer allocator.free(allowed_dirs_slice); var path_validator = PathValidator.init(allowed_dirs_slice); path_validator.allow_symlinks = config.allow_symlinks; // Create adaptive concurrency controller if enabled (even for testing) const adaptive_ctrl = if (config.adaptive_concurrency_enabled) AdaptiveConcurrencyController.init(.{ .min_concurrency = config.adaptive_min_concurrency, .max_concurrency = config.adaptive_max_concurrency, .initial_concurrency = config.adaptive_initial_concurrency, }) else null; return FileSharingManager{ .config = config, .sessions = std.AutoHashMap(u64, FileSharingSession).init(allocator), .download_queue = DownloadQueue.init(allocator), .upload_queue = UploadQueue.init(allocator), .file_registry = std.AutoHashMap(ContentHash, FileInfo).init(allocator), .allocator = allocator, .temp_dir = config.temp_dir, .network_sender = null, .messages_sent = 0, .messages_failed = 0, .p2p_context = null, .path_validator = path_validator, .peer_reputation = std.AutoHashMap([32]u8, PeerReputation).init(allocator), .verification_pool = null, // No thread pool for testing .piece_pipeline = null, // No pipeline for testing .adaptive_controller = adaptive_ctrl, }; } /// Set network sender for actual message transmission pub fn setNetworkSender(self: *FileSharingManager, sender: *NetworkSender) void { self.network_sender = sender; } /// Remove network sender pub fn clearNetworkSender(self: *FileSharingManager) void { self.network_sender = null; } /// PERF: Start the verification thread pool for parallel SHA-256 pub fn startVerificationPool(self: *FileSharingManager) Error!void { if (self.verification_pool) |pool| { try pool.start(); } } /// PERF: Stop the verification thread pool pub fn stopVerificationPool(self: *FileSharingManager) void { if (self.verification_pool) |pool| { pool.stop(); } } /// PERF: Start the piece processing pipeline pub fn startPiecePipeline(self: *FileSharingManager) Error!void { if (self.piece_pipeline) |pipeline| { // Set up callbacks - use self as context pipeline.setCallbacks(.{ .context = @ptrCast(self), .process_piece_fn = pipelineProcessPiece, }); try pipeline.start(); } } /// PERF: Stop the piece processing pipeline pub fn stopPiecePipeline(self: *FileSharingManager) void { if (self.piece_pipeline) |pipeline| { pipeline.stop(); } } /// Pipeline callback: process a piece from the queue fn pipelineProcessPiece( ctx: *anyopaque, peer_id: [32]u8, content_hash: [32]u8, piece_index: u32, offset: u32, data: []const u8, ) Error!void { const self: *FileSharingManager = @ptrCast(@alignCast(ctx)); return self.processPieceInternal(peer_id, content_hash, piece_index, offset, data); } /// PERF: Process completed verifications and update piece states /// Call this periodically (e.g., in update loop) to process async verification results pub fn processVerificationResults(self: *FileSharingManager) void { const pool = self.verification_pool orelse return; // Process all available results while (pool.getResult()) |result| { self.handleVerificationResult(result.session_id, result.piece_index, result.is_valid, result.peer_id); } } /// Handle a completed verification result /// Note: Pipeline slot was already released in the async path when data was received. /// This function just handles verification success/failure and updates state. fn handleVerificationResult(self: *FileSharingManager, session_id: u64, piece_index: u32, is_valid: bool, peer_id: [32]u8) void { // Track piece hash for cascade broadcast var piece_hash: [32]u8 = undefined; var should_broadcast = false; var download_completed = false; // First update session state (sessions_mutex) { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return; if (session.download_manager) |*dm| { if (is_valid) { // RACE FIX: Check if piece was already verified by another thread // In endgame mode, same piece can arrive from multiple peers and // get queued for verification multiple times. const already_verified = if (dm.selector.availability_map.get(piece_index)) |info| info.is_verified else false; if (already_verified) { // Another verification already completed - skip counter update std.log.debug("ASYNC RACE: Piece {d} already verified, skipping duplicate", .{piece_index}); // Note: active_downloads already removed, slot already released in async path } else { // First verification to complete - mark it done // FIX: Mark verified FIRST to prevent other threads from also updating counter dm.selector.markVerified(piece_index) catch {}; dm.state.addVerifiedBytes(dm.piece_size); dm.state.markPieceCompleted(); // Note: active_downloads already removed, slot already released in async path // ADAPTIVE: Record successful piece completion if (self.adaptive_controller) |*ctrl| { ctrl.recordSuccess(); } // CASCADE FIX: Get piece hash for upload registration if (piece_index < session.file_metadata.piece_hashes.len) { piece_hash = session.file_metadata.piece_hashes[piece_index]; should_broadcast = true; } const completed = dm.state.completed_pieces.load(.acquire); if (completed == dm.state.piece_count) { // PRE-COMPLETION VERIFICATION: Verify all pieces are actually marked // as verified in the selector before marking download complete. // This matches the sync path verification (lines 3795-3843). var all_verified = true; var verified_count: u32 = 0; var unverified_pieces: [10]u32 = undefined; var unverified_count: usize = 0; var selector_iter = dm.selector.availability_map.iterator(); while (selector_iter.next()) |entry| { if (entry.value_ptr.is_verified) { verified_count += 1; } else { all_verified = false; if (unverified_count < 10) { unverified_pieces[unverified_count] = entry.key_ptr.*; unverified_count += 1; } } } if (!all_verified) { // Log mismatch - counter says complete but selector disagrees std.log.warn("COMPLETION MISMATCH (async): Counter={d}, Verified={d}/{d}, unverified pieces: {any}", .{ completed, verified_count, dm.state.piece_count, unverified_pieces[0..unverified_count], }); // Don't mark as complete - let pieces be re-requested // Reset completed counter to match actual verified count dm.state.completed_pieces.store(verified_count, .release); } else { // FIX: Sync file to ensure all pwrite data is flushed if (dm.file_writer) |*fw| { fw.flush() catch |flush_err| { std.log.warn("Failed to flush file on async completion: {}", .{flush_err}); }; } session.status = .completed; session.updated_at = std.time.timestamp(); std.log.info("Download completed! Session {d}: All {d} pieces verified (async), file_path={s}", .{ session_id, dm.state.piece_count, dm.file_path orelse "unknown", }); download_completed = true; } } } } else { // ADAPTIVE: Record timeout/failure for bad piece if (self.adaptive_controller) |*ctrl| { ctrl.recordTimeout(); } // FIX: Reset downloaded state so piece can be re-requested dm.selector.resetDownloaded(piece_index); // Verification failed - mark for retry // Note: active_downloads already removed, slot already released in async path dm.handleDownloadFailure(piece_index, "Hash verification failed (async)") catch |err| { std.log.err("Failed to handle download failure for piece {d}: {}", .{ piece_index, err }); }; } } } // Update peer reputation (separate lock to respect ordering) self.updatePeerReputation(peer_id, is_valid); // CASCADE FIX: After verification, make piece available for upload and broadcast to peers if (should_broadcast) { self.markPieceAvailableForUpload(session_id, piece_index, piece_hash); self.broadcastHavePiece(session_id, piece_index); } // CASCADE FIX: Broadcast full bitfield when download completes // This notifies all connected peers that we now have ALL pieces if (download_completed) { self.broadcastFullBitfield(session_id); } } pub fn deinit(self: *FileSharingManager) void { // PERF: Clean up piece pipeline first (it may be using verification pool) if (self.piece_pipeline) |pipeline| { pipeline.deinit(); self.allocator.destroy(pipeline); } // PERF: Clean up verification pool if (self.verification_pool) |pool| { pool.deinit(); self.allocator.destroy(pool); } // Clean up all sessions var it = self.sessions.valueIterator(); while (it.next()) |session| { session.deinit(); } self.sessions.deinit(); // Clean up queues self.download_queue.deinit(); self.upload_queue.deinit(); // Clean up file registry var reg_it = self.file_registry.valueIterator(); while (reg_it.next()) |file_info| { file_info.deinit(self.allocator); } self.file_registry.deinit(); // Clean up peer reputation self.peer_reputation.deinit(); // Clean up path validator self.allocator.free(self.path_validator.allowed_directories); } /// Add file to sharing system /// /// Returns session ID for thread-safe access. Use getSessionInfo() to get /// session details, or withSession() for operations requiring direct access. /// /// THREAD SAFETY: This function returns a session ID (u64) instead of a /// pointer to avoid use-after-free bugs. The session ID remains valid /// until the session is explicitly removed. pub fn addFile(self: *FileSharingManager, file_path: []const u8) Error!u64 { // SECURITY: Validate that file_path is readable and within allowed directories const validated_path = self.path_validator.validateReadable(file_path, self.allocator) catch |err| { return switch (err) { path_security.PathSecurityError.PathTraversal, path_security.PathSecurityError.PathOutsideAllowedDirectory, path_security.PathSecurityError.SymlinkNotAllowed, path_security.PathSecurityError.InvalidPath, path_security.PathSecurityError.PathTooLong, => Error.InvalidData, else => Error.FileError, }; }; defer self.allocator.free(validated_path); // Create file info const file_info = try FileInfo.fromPath(validated_path, self.allocator); // Calculate content hash const content_hash = try FileUtils.hashFile(validated_path, self.allocator); // FIX TOCTOU: Atomically reserve the slot in file_registry using getOrPut // This prevents race conditions where two threads could both pass the "exists" check self.file_registry_mutex.lock(); // CRIT-3 FIX: Enforce file registry limit to prevent resource exhaustion if (self.file_registry.count() >= self.config.max_registry_files) { self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); std.log.err("CRIT-3: File registry limit reached ({}/{}), rejecting new file", .{ self.file_registry.count(), self.config.max_registry_files }); return Error.PoolExhausted; } const gop = self.file_registry.getOrPut(content_hash) catch { self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); return Error.SystemError; }; if (gop.found_existing) { // File already registered by another thread self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); return Error.ConnectionAlreadyExists; } // Reserve slot with our file_info - we own this slot now gop.value_ptr.* = file_info; self.file_registry_mutex.unlock(); // Cleanup helper in case of failure - removes our reserved slot const cleanup_file_registry = struct { fn remove(mgr: *FileSharingManager, hash: [32]u8) void { mgr.file_registry_mutex.lock(); if (mgr.file_registry.fetchRemove(hash)) |removed| { removed.value.deinit(mgr.allocator); } mgr.file_registry_mutex.unlock(); } }; // Create file metadata const chunker = FileChunker.init(self.config.piece_size, self.allocator); const metadata = chunker.createMetadata(validated_path) catch |err| { cleanup_file_registry.remove(self, content_hash); return err; }; // Create sharing session var session = FileSharingSession.create(metadata, self.config, self.allocator) catch |err| { cleanup_file_registry.remove(self, content_hash); return err; }; const session_id = session.session_id; // Initialize upload if enabled if (self.config.enable_upload) { session.initUpload(validated_path, self.config, self.allocator) catch |err| { cleanup_file_registry.remove(self, content_hash); return err; }; } // Store session - return ID, not pointer (THREAD SAFETY FIX) self.sessions_mutex.lock(); // CRIT-3 FIX: Enforce session limit to prevent resource exhaustion const max_sessions = core.limits.global.file.max_sessions; if (self.sessions.count() >= max_sessions) { self.sessions_mutex.unlock(); cleanup_file_registry.remove(self, content_hash); std.log.err("CRIT-3: Session limit reached ({}/{}), rejecting new share request", .{ self.sessions.count(), max_sessions }); return Error.PoolExhausted; } // HIGH-8 FIX: Check for session ID collision (extremely unlikely with 64-bit random) // Regenerate ID if collision detected (birthday paradox at ~2^32 sessions) var final_session_id = session_id; const max_collision_retries = 10; var retries: u32 = 0; while (self.sessions.contains(final_session_id)) { retries += 1; if (retries >= max_collision_retries) { // This should be practically impossible - something is very wrong self.sessions_mutex.unlock(); cleanup_file_registry.remove(self, content_hash); std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); return Error.SystemError; } final_session_id = std.crypto.random.int(u64); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); } session.session_id = final_session_id; self.sessions.put(final_session_id, session) catch { self.sessions_mutex.unlock(); cleanup_file_registry.remove(self, content_hash); return Error.SystemError; }; self.sessions_mutex.unlock(); return final_session_id; } /// Add file for sharing with pre-computed metadata (skips hashing) /// /// This is useful when multiple P2P instances need to share the same file - /// only the first instance needs to compute the metadata, subsequent instances /// can reuse it to avoid expensive re-hashing of large files. /// /// Returns session ID for thread-safe access. pub fn addFileWithMetadata( self: *FileSharingManager, file_path: []const u8, source_metadata: FileMetadata, ) Error!u64 { // SECURITY: Validate that file_path is readable and within allowed directories const validated_path = self.path_validator.validateReadable(file_path, self.allocator) catch |err| { return switch (err) { path_security.PathSecurityError.PathTraversal, path_security.PathSecurityError.PathOutsideAllowedDirectory, path_security.PathSecurityError.SymlinkNotAllowed, path_security.PathSecurityError.InvalidPath, path_security.PathSecurityError.PathTooLong, => Error.InvalidData, else => Error.FileError, }; }; defer self.allocator.free(validated_path); // Create file info (lightweight - just stats, no hashing) const file_info = try FileInfo.fromPath(validated_path, self.allocator); // Verify file size matches metadata (sanity check) if (file_info.size != source_metadata.size) { file_info.deinit(self.allocator); std.log.err("File size mismatch: file={} metadata={}", .{ file_info.size, source_metadata.size }); return Error.InvalidData; } // Use the content hash from the metadata's piece hashes // (compute a hash of the metadata to use as registry key) var hasher = std.crypto.hash.sha2.Sha256.init(.{}); hasher.update(source_metadata.name); hasher.update(std.mem.asBytes(&source_metadata.size)); for (source_metadata.piece_hashes) |ph| { hasher.update(&ph); } var content_hash: [32]u8 = undefined; hasher.final(&content_hash); // Register in file_registry self.file_registry_mutex.lock(); if (self.file_registry.count() >= self.config.max_registry_files) { self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); std.log.err("CRIT-3: File registry limit reached ({}/{}), rejecting new file", .{ self.file_registry.count(), self.config.max_registry_files }); return Error.PoolExhausted; } const gop = self.file_registry.getOrPut(content_hash) catch { self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); return Error.SystemError; }; if (gop.found_existing) { self.file_registry_mutex.unlock(); file_info.deinit(self.allocator); return Error.ConnectionAlreadyExists; } gop.value_ptr.* = file_info; self.file_registry_mutex.unlock(); const cleanup_file_registry = struct { fn remove(mgr: *FileSharingManager, hash: [32]u8) void { mgr.file_registry_mutex.lock(); if (mgr.file_registry.fetchRemove(hash)) |removed| { removed.value.deinit(mgr.allocator); } mgr.file_registry_mutex.unlock(); } }; // Create owned copy of metadata const name_copy = self.allocator.dupe(u8, source_metadata.name) catch { cleanup_file_registry.remove(self, content_hash); return Error.OutOfMemory; }; errdefer self.allocator.free(name_copy); const hashes_copy = self.allocator.dupe(PieceHash, source_metadata.piece_hashes) catch { self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); return Error.OutOfMemory; }; errdefer self.allocator.free(hashes_copy); const metadata = FileMetadata{ .name = name_copy, .size = source_metadata.size, .piece_count = source_metadata.piece_count, .piece_hashes = hashes_copy, .created_at = source_metadata.created_at, .modified_at = source_metadata.modified_at, }; // Create sharing session var session = FileSharingSession.create(metadata, self.config, self.allocator) catch |err| { self.allocator.free(hashes_copy); self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); return err; }; const session_id = session.session_id; // Initialize upload if enabled if (self.config.enable_upload) { session.initUpload(validated_path, self.config, self.allocator) catch |err| { self.allocator.free(hashes_copy); self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); return err; }; } // Store session self.sessions_mutex.lock(); const max_sessions = core.limits.global.file.max_sessions; if (self.sessions.count() >= max_sessions) { self.sessions_mutex.unlock(); self.allocator.free(hashes_copy); self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); std.log.err("CRIT-3: Session limit reached ({}/{}), rejecting new share request", .{ self.sessions.count(), max_sessions }); return Error.PoolExhausted; } var final_session_id = session_id; const max_collision_retries = 10; var retries: u32 = 0; while (self.sessions.contains(final_session_id)) { retries += 1; if (retries >= max_collision_retries) { self.sessions_mutex.unlock(); self.allocator.free(hashes_copy); self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); return Error.SystemError; } final_session_id = std.crypto.random.int(u64); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); } session.session_id = final_session_id; self.sessions.put(final_session_id, session) catch { self.sessions_mutex.unlock(); self.allocator.free(hashes_copy); self.allocator.free(name_copy); cleanup_file_registry.remove(self, content_hash); return Error.SystemError; }; self.sessions_mutex.unlock(); return final_session_id; } /// Download file from peers /// /// Returns session ID for thread-safe access. Use getSessionInfo() to get /// session details, or withSession() for operations requiring direct access. /// /// THREAD SAFETY: This function returns a session ID (u64) instead of a /// pointer to avoid use-after-free bugs. The session ID remains valid /// until the session is explicitly removed. pub fn downloadFile( self: *FileSharingManager, file_metadata: FileMetadata, output_path: []const u8, ) Error!u64 { // SECURITY: Sanitize the filename from metadata to prevent path traversal // This is used for validation, not for determining the output path const sanitized_name = sanitizeFilename(file_metadata.name, self.allocator) catch return Error.OutOfMemory; defer self.allocator.free(sanitized_name); // FIX: Determine if output_path is a directory or a full file path // If it's a directory, append the sanitized metadata name // If it's a file path, use it directly (user specified the exact destination) const is_directory = blk: { // Check if output_path exists and is a directory const stat = std.fs.cwd().statFile(output_path) catch { // Path doesn't exist - check if it ends with a path separator or has no extension const base = std.fs.path.basename(output_path); // If basename has no extension and doesn't look like a filename, treat as directory // Otherwise treat as file path that will be created break :blk mem.indexOf(u8, base, ".") == null and !mem.endsWith(u8, output_path, ".txt"); }; break :blk stat.kind == .directory; }; // Build the final output path const final_output_path = if (is_directory) std.fs.path.join(self.allocator, &[_][]const u8{ output_path, sanitized_name }) catch return Error.OutOfMemory else self.allocator.dupe(u8, output_path) catch return Error.OutOfMemory; defer self.allocator.free(final_output_path); // SECURITY: Validate final output_path is writable and within allowed directories const validated_final_path = self.path_validator.validateWritable(final_output_path, self.allocator) catch |err| { return switch (err) { path_security.PathSecurityError.PathTraversal, path_security.PathSecurityError.PathOutsideAllowedDirectory, path_security.PathSecurityError.SymlinkNotAllowed, path_security.PathSecurityError.InvalidPath, path_security.PathSecurityError.PathTooLong, => Error.InvalidData, else => Error.FileError, }; }; errdefer self.allocator.free(validated_final_path); // Calculate content hash const content_hash = try HashUtils.metadataHash(file_metadata); // THREAD SAFETY FIX: Check and create atomically to prevent TOCTOU race // We hold the mutex for the entire operation to ensure no other thread // can start a download for the same file between check and creation. self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // CRIT-3 FIX: Enforce session limit to prevent resource exhaustion const max_sessions = core.limits.global.file.max_sessions; if (self.sessions.count() >= max_sessions) { std.log.err("CRIT-3: Session limit reached ({}/{}), rejecting new download request", .{ self.sessions.count(), max_sessions }); return Error.PoolExhausted; } // Check if already downloading (protect sessions) var it = self.sessions.valueIterator(); while (it.next()) |session| { // ERR-M3 FIX: Log error instead of silently continuing const session_hash = HashUtils.metadataHash(session.file_metadata) catch |err| { std.log.warn("ERR-M3: Failed to calculate session metadata hash: {}", .{err}); continue; }; if (mem.eql(u8, &content_hash, &session_hash)) { if (session.download_manager != null) { // Already downloading - return existing session ID self.allocator.free(validated_final_path); return session.session_id; } } } // Not already downloading - create new session while still holding mutex // This prevents race condition where two threads could both create sessions // Duplicate metadata since session takes ownership // CRITICAL: Use the original name from file_metadata, NOT sanitized_name! // The sanitized_name is used for file path security, but session metadata // must match the server's metadata for content hash to be identical. const name_copy = self.allocator.dupe(u8, file_metadata.name) catch { self.allocator.free(validated_final_path); return Error.OutOfMemory; }; errdefer { self.allocator.free(name_copy); self.allocator.free(validated_final_path); } const hashes_copy = if (file_metadata.piece_hashes.len > 0) self.allocator.dupe(PieceHash, file_metadata.piece_hashes) catch { // name_copy cleanup handled by errdefer above return Error.OutOfMemory; } else &[_]PieceHash{}; errdefer { if (hashes_copy.len > 0) self.allocator.free(hashes_copy); // name_copy and validated_final_path cleanup handled by errdefer above } const owned_metadata = FileMetadata{ .name = name_copy, .size = file_metadata.size, .piece_count = file_metadata.piece_count, .piece_hashes = hashes_copy, .created_at = file_metadata.created_at, .modified_at = file_metadata.modified_at, }; // Create new session with owned metadata var session = FileSharingSession.create(owned_metadata, self.config, self.allocator) catch |err| { return err; }; const session_id = session.session_id; // Initialize download with validated path session.initDownload(validated_final_path, self.config, self.allocator) catch |err| { return err; }; // CASCADE FIX: Initialize upload manager to enable serving pieces to other peers // as we download them (cascading distribution) session.initUploadForCascade(validated_final_path, self.config, self.allocator) catch |err| { std.log.warn("CASCADE: Failed to initialize upload for cascade: {}", .{err}); // Non-fatal - download can still work without cascade }; self.allocator.free(validated_final_path); // Session stores a copy // HIGH-8 FIX: Check for session ID collision (extremely unlikely with 64-bit random) // Regenerate ID if collision detected (birthday paradox at ~2^32 sessions) var final_session_id = session_id; const max_collision_retries = 10; var retries: u32 = 0; while (self.sessions.contains(final_session_id)) { retries += 1; if (retries >= max_collision_retries) { // This should be practically impossible - something is very wrong std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); return Error.SystemError; } final_session_id = std.crypto.random.int(u64); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); } session.session_id = final_session_id; // Store session atomically (still holding mutex) self.sessions.put(final_session_id, session) catch { return Error.SystemError; }; return final_session_id; } /// Start file sharing (download/upload) pub fn startSharing(self: *FileSharingManager, session_id: u64) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse { return Error.ConnectionNotFound; }; session.update(); // Start download if available if (session.download_manager) |*dm| { session.status = .downloading; // ARCH-1 FIX: Use session's download_manager directly instead of creating a disconnected one // The queue pattern was broken - it created separate managers that weren't linked to sessions // ARCH-2 FIX: Initiate piece requests for all pieces we need // BUG FIX: Only request pieces if we have valid peer(s) with those pieces. // Previously used "broadcast" as peer_id which is invalid (9 bytes, not 32). // Now we defer piece requests until handleBitfield/handleHave are called, // which provide valid peer_ids for each piece. const piece_count = session.file_metadata.piece_count; if (piece_count > 0) { // Try to get a valid peer from the peer_piece_map var peer_buffer: [32]u8 = [_]u8{0} ** 32; var i: u32 = 0; var requested: u32 = 0; while (i < piece_count) : (i += 1) { // Check if we know any peers that have this piece const peer_count = dm.getPeersWithPiece(i, &peer_buffer); if (peer_count > 0) { // Use the first known peer for this piece dm.requestPiece(i, .normal, &peer_buffer) catch |err| { if (err != error.InvalidData) { std.log.debug("Piece {} request deferred: {}", .{ i, err }); } continue; }; requested += 1; } // If no peers known yet, piece will be requested when handleBitfield is called } if (requested > 0) { std.log.info("ARCH-2: Initiated download of {} pieces for session {}", .{ requested, session_id }); } else { std.log.info("ARCH-2: Waiting for peer bitfield before requesting pieces for session {}", .{session_id}); } } } // Start upload if available if (session.upload_manager) |_| { session.status = .uploading; // ARCH-1 FIX: Upload queue similarly needs rework, but uploads are typically triggered by peer requests // For now, just mark as uploading - piece requests from peers will drive the actual upload std.log.info("ARCH-1: Session {} ready for upload, awaiting piece requests", .{session_id}); } } /// Stop file sharing session pub fn stopSharing(self: *FileSharingManager, session_id: u64) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return Error.ConnectionNotFound; session.status = .cancelled; session.update(); // Clean up resources session.deinit(); _ = self.sessions.remove(session_id); } /// Process all active sessions pub fn processSessions(self: *FileSharingManager) Error!void { // TIMING: Track overall function time and phases const timer_start = std.time.nanoTimestamp(); var phase1_time: i128 = 0; var phase2_time: i128 = 0; var phase3_time: i128 = 0; var phase4_time: i128 = 0; // FIX: Collect messages to send first, then send without holding lock // This prevents deadlock when network sender needs to call back into manager // Define a structure to hold pending message data // PERF FIX: Use []const u8 to allow ownership transfer without copying const PendingMessage = struct { peer_id_copy: []const u8, data_copy: []const u8, message_type: transfer_mod.MessageType, // FIX: Preserve original message type allocator: mem.Allocator, fn deinit(msg: *@This()) void { // Cast away const for free - original allocations were mutable if (msg.peer_id_copy.len > 0) { const peer_id_mut: []u8 = @constCast(msg.peer_id_copy); msg.allocator.free(peer_id_mut); } if (msg.data_copy.len > 0) { const data_mut: []u8 = @constCast(msg.data_copy); msg.allocator.free(data_mut); } } }; var messages_to_send: std.ArrayListUnmanaged(PendingMessage) = .{}; defer { for (messages_to_send.items) |*msg| { msg.deinit(); } messages_to_send.deinit(self.allocator); } // ZERO-COPY: List of pre-serialized messages to send outside lock (old format from transfer_protocol) var preserialized_to_send: std.ArrayListUnmanaged(transfer_mod.PreSerializedPieceData) = .{}; defer { for (preserialized_to_send.items) |*item| { item.deinit(); } preserialized_to_send.deinit(self.allocator); } // ZERO-COPY: List of pre-serialized piece RESPONSES to send (new format from manager.handlePieceRequest) var piece_responses_to_send: std.ArrayListUnmanaged(PreSerializedPieceResponse) = .{}; defer { for (piece_responses_to_send.items) |*item| { item.deinit(); } piece_responses_to_send.deinit(self.allocator); } // PHASE 1: Collect messages to send (with lock held) // CRIT-NEW-21 FIX: Track dropped messages due to OOM var dropped_messages: usize = 0; var total_messages: usize = 0; const phase1_start = std.time.nanoTimestamp(); self.sessions_mutex.lock(); var it = self.sessions.valueIterator(); while (it.next()) |session| { if (session.isActive()) { session.update(); // Process transfer protocol - pop messages for sending // FAIR QUEUE: Use popMessagesFair to prioritize requests and track slot releases // Values from centralized config for high throughput const max_messages_per_call: usize = core.limits.defaults.file.max_messages_per_call; const max_piece_data_per_call: usize = core.limits.defaults.file.max_piece_data_per_call; var pop_result = session.transfer_protocol.popMessagesFair( max_messages_per_call, max_piece_data_per_call, self.allocator, ) catch |err| { std.log.warn("Failed to pop messages: {}", .{err}); continue; }; defer pop_result.deinit(self.allocator); // FAIR QUEUE: Release slots for popped piece_data messages if (session.response_tracker) |*tracker| { for (pop_result.piece_data_info.items) |info| { tracker.releaseSlot(info.peer_id, info.piece_size); } } if (pop_result.messages.items.len > 0) { std.log.info("PHASE1: Session {} popped {} messages to send (fair queue)", .{ session.session_id, pop_result.messages.items.len }); } for (pop_result.messages.items) |message| { // PERF FIX: popMessagesFair transferred ownership to us // Transfer ownership directly to messages_to_send instead of copying // This eliminates a full 1MB copy per piece_data message! total_messages += 1; messages_to_send.append(self.allocator, PendingMessage{ .peer_id_copy = message.peer_id, // Transfer ownership (no copy) .data_copy = message.data, // Transfer ownership (no copy) .message_type = message.message_type, .allocator = self.allocator, }) catch { dropped_messages += 1; // Must free on error since we own the data if (message.data.len > 0) self.allocator.free(message.data); if (message.peer_id.len > 0) self.allocator.free(message.peer_id); core.errors.recordAndLogError("OOM queueing message for send", error.OutOfMemory); continue; }; // Success - ownership transferred to messages_to_send, don't free } // ZERO-COPY: Pop pre-serialized piece data messages and collect for PHASE 2 var preserialized_result = session.transfer_protocol.popPreserialized( max_piece_data_per_call, self.allocator, ) catch |err| { std.log.warn("Failed to pop preserialized: {}", .{err}); continue; }; if (preserialized_result.items.len > 0) { std.log.debug("PHASE1: Session {} popped {} preserialized messages", .{ session.session_id, preserialized_result.items.len }); } // Transfer ownership to preserialized_to_send for PHASE 2 for (preserialized_result.items) |item| { preserialized_to_send.append(self.allocator, item) catch { // On error, clean up this item var item_copy = item; item_copy.deinit(); continue; }; } // Don't deinit items - ownership transferred to preserialized_to_send preserialized_result.deinit(self.allocator); // No clearSentMessages() needed - popMessagesFair/popPreserialized already removed them // ZERO-COPY: Pop pre-serialized piece RESPONSES (new format from handlePieceRequest) const max_responses_to_pop = max_piece_data_per_call; const responses_to_pop = @min(session.pending_piece_responses.items.len, max_responses_to_pop); if (responses_to_pop > 0) { std.log.debug("PHASE1: Session {} popping {} piece responses (zero-copy)", .{ session.session_id, responses_to_pop }); // FAIR QUEUE: Release slots for popped responses for (session.pending_piece_responses.items[0..responses_to_pop]) |*resp| { if (session.response_tracker) |*tracker| { tracker.releaseSlot(resp.peer_id, resp.data.len); } } // Transfer ownership to piece_responses_to_send for (session.pending_piece_responses.items[0..responses_to_pop]) |item| { piece_responses_to_send.append(self.allocator, item) catch { // On error, clean up this item var item_copy = item; item_copy.deinit(); continue; }; } // Bulk remove from session queue (shift remaining items) const remaining = session.pending_piece_responses.items.len - responses_to_pop; if (remaining > 0) { std.mem.copyForwards( PreSerializedPieceResponse, session.pending_piece_responses.items[0..remaining], session.pending_piece_responses.items[responses_to_pop..], ); } session.pending_piece_responses.items.len = remaining; } } } self.sessions_mutex.unlock(); // CRIT-NEW-21 FIX: Return error if too many messages were dropped (over 50%) if (total_messages > 0 and dropped_messages > total_messages / 2) { std.log.err("SECURITY CRIT-NEW-21: Critical message loss - {d}/{d} messages dropped due to OOM", .{ dropped_messages, total_messages, }); return Error.OutOfMemory; } else if (dropped_messages > 0) { std.log.warn("CRIT-NEW-21: {d}/{d} messages dropped due to OOM", .{ dropped_messages, total_messages }); } // TIMING: Phase 1 complete phase1_time = std.time.nanoTimestamp() - phase1_start; const phase2_start = std.time.nanoTimestamp(); // PHASE 2: Send messages (NO lock held - prevents deadlock) for (messages_to_send.items) |msg| { // Create temporary TransferMessage for sending // FIX: Use preserved message type instead of hardcoding piece_request const temp_message = TransferMessage{ .message_type = msg.message_type, .message_id = 0, .peer_id = msg.peer_id_copy, .data = msg.data_copy, .timestamp = std.time.timestamp(), }; std.log.debug("PHASE2: Sending message type={}", .{msg.message_type}); // CRIT-NEW-19 FIX: Record swallowed error for tracking self.sendTransferMessage(temp_message) catch |err| { core.errors.recordAndLogError("sendTransferMessage in processSessionsOnce", err); }; } // ZERO-COPY: Send pre-serialized messages using scatter-gather (NO lock held) // PERF FIX: Batch stats updates to avoid 2048+ lock/unlock cycles per call if (self.network_sender) |sender| { var local_sent: usize = 0; var local_failed: usize = 0; for (preserialized_to_send.items) |*preserialized| { const segments = preserialized.getSegments(); const sent = sender.sendSegments(&preserialized.peer_id, &segments); if (sent) { local_sent += 1; } else { local_failed += 1; } } // ZERO-COPY: Send piece responses using scatter-gather (NO lock held) // These come from manager.handlePieceRequest and use the new PreSerializedPieceResponse format for (piece_responses_to_send.items) |*response| { const segments = response.getSegments(); const sent = sender.sendSegments(&response.peer_id, &segments); if (sent) { local_sent += 1; } else { local_failed += 1; } } // Single lock for all stats updates (was 2048+ locks before) self.stats_mutex.lock(); self.messages_sent += local_sent; self.messages_failed += local_failed; self.stats_mutex.unlock(); } // TIMING: Phase 2 complete phase2_time = std.time.nanoTimestamp() - phase2_start; const phase3_start = std.time.nanoTimestamp(); // ARCH-1 FIX: Process session download managers directly instead of the disconnected queue // The queue held separate DownloadManagers that weren't linked to sessions self.sessions_mutex.lock(); // ADAPTIVE: Get effective concurrency limit from controller (or use static config) const effective_concurrency = if (self.adaptive_controller) |*ctrl| ctrl.getEffectiveConcurrency() else self.config.max_concurrent_downloads; // Collect session IDs first to avoid iterator invalidation issues var session_ids: [256]u64 = undefined; var session_count: usize = 0; var key_iter = self.sessions.keyIterator(); while (key_iter.next()) |key_ptr| { if (session_count >= session_ids.len) break; session_ids[session_count] = key_ptr.*; session_count += 1; } // Process each session with mutable access via getPtr var idx: usize = 0; while (idx < session_count) : (idx += 1) { const session_id = session_ids[idx]; if (self.sessions.getPtr(session_id)) |session| { if (session.download_manager) |*dm| { // Log pending/active counts before processing const pending_before = dm.pending_requests.items.len; const active_before = dm.active_downloads.count(); // Process pending piece requests with adaptive concurrency limit dm.processRequests(effective_concurrency) catch |err| { std.log.warn("ARCH-1: Error processing download requests for session: {}", .{err}); }; const pending_after = dm.pending_requests.items.len; const active_after = dm.active_downloads.count(); if (pending_before > 0 or active_after > 0) { std.log.debug("Session {}: pending {}->{}, active {}->{}", .{ session.session_id, pending_before, pending_after, active_before, active_after, }); } // ARCH-3 FIX: Generate piece request messages for active downloads // This was the missing link - processRequests marks pieces as active but nothing sent network requests! // PERF FIX: Use cached content_hash instead of recomputing // Old code called HashUtils.metadataHash which iterates 81920 piece_hashes const content_hash = session.content_hash; // PERF: Batch requests by peer to reduce message overhead var peer_batches = std.AutoHashMap([32]u8, std.ArrayList(u32)).init(self.allocator); defer { var batch_iter = peer_batches.valueIterator(); while (batch_iter.next()) |list| { list.deinit(self.allocator); } peer_batches.deinit(); } var active_iter = dm.active_downloads.iterator(); while (active_iter.next()) |entry| { const piece_index = entry.key_ptr.*; const active_ptr = entry.value_ptr; // Only send request if download is in 'downloading' state AND no bytes received yet // We use downloaded_bytes == 0 to mean "not yet requested" if (active_ptr.status == .downloading and active_ptr.downloaded_bytes == 0) { // PERF: Check if we can pipeline more requests to this peer if (!dm.request_tracker.canRequestFromPeer(active_ptr.peer_id)) { // This peer has hit queue depth limit, skip for now continue; } // Add to peer's batch const gop = peer_batches.getOrPut(active_ptr.peer_id) catch continue; if (!gop.found_existing) { gop.value_ptr.* = std.ArrayList(u32){}; } gop.value_ptr.append(self.allocator, piece_index) catch continue; // PERF: Track in-flight request for pipelining (maintains rate limit during collection) dm.request_tracker.recordRequest(active_ptr.peer_id, piece_index) catch |err| { std.log.warn("PERF: Failed to record request for piece {}: {}", .{ piece_index, err }); }; // Mark as request sent (tentatively - will be undone if queueing fails) active_ptr.downloaded_bytes = 1; // Sentinel: request sent but no data yet } } // Send batch requests for each peer (O(1) lookup via sessions_by_hash) // QUEUE LIMIT: Cap total pending messages to prevent unbounded growth // Requests are small (~40-300 bytes) so use a higher limit than responses const max_pending_total: usize = 2048; // FIX: Increased from 512 (was starving with 8 peers × 64 depth) var batch_send_iter = peer_batches.iterator(); while (batch_send_iter.next()) |batch_entry| { const peer_id = batch_entry.key_ptr.*; const pieces = batch_entry.value_ptr.items; if (pieces.len == 0) continue; // FAIR QUEUE: Check request queue limit (requests are small, higher limit) const total_pending = session.transfer_protocol.pending_requests.items.len + session.transfer_protocol.pending_responses.items.len; if (total_pending >= max_pending_total) { std.log.debug("QUEUE LIMIT: Skipping peer request, queues at capacity ({} items)", .{max_pending_total}); // FIX: Undo the tentative marking for pieces we can't queue for (pieces) |piece_index| { if (dm.active_downloads.getPtr(piece_index)) |active_ptr| { active_ptr.downloaded_bytes = 0; // Reset - will retry next cycle } dm.request_tracker.recordCompletion(peer_id, piece_index); } continue; // FIX: Was `break` which dropped ALL remaining peers' requests } if (pieces.len == 1) { // Single piece - use regular request (goes to request queue) const piece_request = TransferMessage.pieceRequest( &peer_id, content_hash, pieces[0], 0, self.allocator, ); session.transfer_protocol.pending_requests.append(self.allocator, piece_request) catch { // FIX: Undo tentative marking on queue failure if (dm.active_downloads.getPtr(pieces[0])) |active_ptr| { active_ptr.downloaded_bytes = 0; } dm.request_tracker.recordCompletion(peer_id, pieces[0]); continue; }; } else { // Multiple pieces - use batch request (goes to request queue) const batch_request = TransferMessage.batchPieceRequest( &peer_id, content_hash, pieces, self.allocator, ); session.transfer_protocol.pending_requests.append(self.allocator, batch_request) catch { // FIX: Undo tentative marking on queue failure for all pieces in batch for (pieces) |piece_index| { if (dm.active_downloads.getPtr(piece_index)) |active_ptr| { active_ptr.downloaded_bytes = 0; } dm.request_tracker.recordCompletion(peer_id, piece_index); } continue; }; } } } } } // TIMING: Phase 3 complete phase3_time = std.time.nanoTimestamp() - phase3_start; const phase4_start = std.time.nanoTimestamp(); // ADAPTIVE: Record cycle statistics after processing all sessions // Record stuck downloads as partial timeouts - provides congestion signal // that helps prevent death spiral while allowing high throughput if (self.adaptive_controller != null) { var total_in_flight: usize = 0; var total_stuck: u32 = 0; for (session_ids[0..session_count]) |sid| { if (self.sessions.getPtr(sid)) |session| { if (session.download_manager) |*dm| { total_in_flight += dm.active_downloads.count(); total_stuck += dm.getAndResetStuckDownloads(); } } } self.sessions_mutex.unlock(); // Record stuck downloads as partial timeouts (1 timeout per 4 stuck) // Higher divisor allows more aggressive pipelining while still responding to congestion // Note: Real verification failures still record 1:1 timeouts elsewhere if (self.adaptive_controller) |*ctrl| { const weighted_timeouts = total_stuck / 4; for (0..weighted_timeouts) |_| { ctrl.recordTimeout(); } ctrl.recordCycleEnd(total_in_flight); // Debug logging for adaptive controller state if (total_stuck > 0 or total_in_flight > 50) { const stats = ctrl.getStats(); std.log.info("ADAPTIVE: in_flight={}, stuck={}, timeouts_recorded={}, success={d:.1}%, timeout={d:.1}%, concurrency={}", .{ total_in_flight, total_stuck, weighted_timeouts, stats.success_rate * 100, stats.timeout_rate * 100, stats.current_concurrency, }); } } } else { self.sessions_mutex.unlock(); } // TIMING: Phase 4 complete phase4_time = std.time.nanoTimestamp() - phase4_start; // PHASE 5: Check for endgame broadcast trigger (outside lock to avoid deadlock) { self.sessions_mutex.lock(); var sessions_iter = self.sessions.valueIterator(); while (sessions_iter.next()) |session| { if (session.download_manager) |*dm| { if (dm.needsEndgameBroadcast()) { self.sessions_mutex.unlock(); _ = dm.broadcastEndgameRequests() catch |err| { std.log.warn("ENDGAME: Broadcast failed: {}", .{err}); }; self.sessions_mutex.lock(); } } } self.sessions_mutex.unlock(); } // Process upload queue (uploads are typically request-driven, so queue is less broken) try self.upload_queue.processAll(@as(u32, @intCast(self.config.max_concurrent_uploads))); // Clean up completed/failed sessions self.cleanupCompletedSessions(); // TIMING: Log timing breakdown (only when significant time spent) const total_time = std.time.nanoTimestamp() - timer_start; const total_ms = @as(f64, @floatFromInt(total_time)) / 1_000_000.0; // Log every 100th call or when > 1ms to reduce spam while getting data self.timing_log_counter +%= 1; if (total_ms > 1.0 or self.timing_log_counter % 100 == 0) { const p1_ms = @as(f64, @floatFromInt(phase1_time)) / 1_000_000.0; const p2_ms = @as(f64, @floatFromInt(phase2_time)) / 1_000_000.0; const p3_ms = @as(f64, @floatFromInt(phase3_time)) / 1_000_000.0; const p4_ms = @as(f64, @floatFromInt(phase4_time)) / 1_000_000.0; std.log.warn("TIMING processSessions: total={d:.1}ms | P1(collect)={d:.1}ms P2(send)={d:.1}ms P3(download)={d:.1}ms P4(adaptive)={d:.1}ms", .{ total_ms, p1_ms, p2_ms, p3_ms, p4_ms, }); } } /// Send a transfer message over the network fn sendTransferMessage(self: *FileSharingManager, message: TransferMessage) Error!void { std.log.debug("sendTransferMessage called: type={}, peer_id len={}", .{ message.message_type, message.peer_id.len }); if (self.network_sender) |sender| { // Serialize the message const serialized = message.serialize(self.allocator) catch |err| { std.log.warn("sendMessage serialize failed: {}", .{err}); self.stats_mutex.lock(); self.messages_failed += 1; self.stats_mutex.unlock(); return err; }; defer self.allocator.free(serialized); // Add app ID prefix (0x01 for file transfer) const full_msg = self.allocator.alloc(u8, 1 + serialized.len) catch { std.log.warn("sendMessage alloc failed", .{}); self.stats_mutex.lock(); self.messages_failed += 1; self.stats_mutex.unlock(); return Error.OutOfMemory; }; defer self.allocator.free(full_msg); full_msg[0] = 0x01; // File transfer app ID @memcpy(full_msg[1..], serialized); // DEBUG: Log the message size and first bytes const preview_len = @min(full_msg.len, 16); std.log.debug("sendTransferMessage: sending {} bytes, first bytes: {x}", .{ full_msg.len, full_msg[0..preview_len] }); // Send via callback const sent = sender.send_fn(message.peer_id, full_msg, sender.context); self.stats_mutex.lock(); if (sent) { self.messages_sent += 1; std.log.info("Message sent successfully (type={})", .{message.message_type}); } else { self.messages_failed += 1; std.log.warn("Message send returned false", .{}); } self.stats_mutex.unlock(); } else { std.log.warn("No network sender configured - message dropped", .{}); } } /// Clean up completed sessions /// /// RACE CONDITION FIX: This function properly handles the iterator-while-modifying race: /// 1. First pass: Iterate over sessions to collect IDs to remove (read-only) /// 2. Second pass: Remove sessions using collected IDs (modification) /// /// This two-phase approach ensures we don't modify the hashmap while iterating, /// which would cause undefined behavior. The bounded array limits batch size /// to avoid unbounded memory growth. /// /// THREAD SAFETY: This function MUST hold sessions_mutex for the entire operation /// to prevent use-after-free in other threads that may hold session pointers. fn cleanupCompletedSessions(self: *FileSharingManager) void { // CRITICAL: Hold mutex for entire cleanup to prevent use-after-free // in getSession() callers who might be using session pointers self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // Collect session IDs to remove - use a bounded array to avoid allocation var to_remove: [64]u64 = undefined; var remove_count: usize = 0; // PHASE 1: Iterate and collect (read-only, no modifications) var it = self.sessions.keyIterator(); while (it.next()) |session_id| { if (remove_count >= to_remove.len) break; // Limit batch size const session = self.sessions.getPtr(session_id.*) orelse continue; if (!session.isActive()) { // CASCADE FIX: Keep completed sessions longer for cascade distribution // Previously 60 seconds was too short - peers couldn't serve pieces to slower downloaders const grace_period_seconds: i64 = 3600; // Keep for 1 hour after completion const age = std.time.timestamp() - session.updated_at; if (session.status == .completed) { // Only remove completed sessions after grace period if (age >= grace_period_seconds) { to_remove[remove_count] = session_id.*; remove_count += 1; } } else { // Remove failed/cancelled sessions immediately to_remove[remove_count] = session_id.*; remove_count += 1; } } } // PHASE 2: Remove collected sessions (safe to modify now) for (to_remove[0..remove_count]) |session_id| { const session = self.sessions.getPtr(session_id); if (session) |sess| { sess.deinit(); } _ = self.sessions.remove(session_id); } } /// Get all active sessions /// Caller is responsible for freeing the returned slice with self.allocator.free() pub fn getActiveSessions(self: *FileSharingManager) Error![]u64 { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // Count active sessions first var count: usize = 0; var count_it = self.sessions.iterator(); while (count_it.next()) |entry| { if (entry.value_ptr.isActive()) { count += 1; } } if (count == 0) { return &[_]u64{}; } // Allocate result array const result = self.allocator.alloc(u64, count) catch return Error.OutOfMemory; errdefer self.allocator.free(result); // Fill in active session IDs var idx: usize = 0; var it = self.sessions.iterator(); while (it.next()) |entry| { if (entry.value_ptr.isActive()) { if (idx < result.len) { result[idx] = entry.key_ptr.*; idx += 1; } } } return result[0..idx]; } /// Get session info by ID (THREAD-SAFE) /// /// Returns a copy of session statistics that is safe to use across threads. /// This is the preferred method for reading session state. pub fn getSessionInfo(self: *FileSharingManager, session_id: u64) ?SessionStats { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return null; return session.getStats(); } /// Execute a callback with exclusive access to a session (THREAD-SAFE) /// /// This is the safe way to perform operations on a session. The callback /// receives a pointer to the session while the mutex is held, ensuring /// the session cannot be freed during the operation. /// /// Example: /// ```zig /// const result = manager.withSession(session_id, struct { /// fn callback(session: *FileSharingSession) Error!void { /// session.status = .cancelled; /// } /// }.callback); /// ``` pub fn withSession( self: *FileSharingManager, session_id: u64, callback: *const fn (*FileSharingSession) Error!void, ) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return Error.ConnectionNotFound; return callback(session); } /// Execute a callback with exclusive access to a session, returning a value (THREAD-SAFE) /// /// Generic version of withSession that can return a value from the callback. pub fn withSessionResult( self: *FileSharingManager, session_id: u64, comptime T: type, callback: *const fn (*FileSharingSession) T, ) ?T { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return null; return callback(session); } /// Get session by ID (INTERNAL/UNSAFE - prefer getSessionInfo or withSession) /// /// WARNING: This returns a raw pointer that becomes invalid when the mutex /// is released. Only use this for internal operations where the caller /// manages locking manually. /// /// For external use, prefer: /// - getSessionInfo() for reading session state /// - withSession() for modifying session state fn getSessionUnsafe(self: *FileSharingManager, session_id: u64) ?*FileSharingSession { // Note: Caller MUST hold sessions_mutex return self.sessions.getPtr(session_id); } // REMOVED: getSession() was unsafe - returned pointer after lock release // Use getSessionInfo() for reading state, or withSession()/withSessionResult() for modifications /// Get file sharing statistics pub fn getStats(self: *FileSharingManager) FileSharingStats { var total_sessions: usize = 0; var active_sessions: usize = 0; var downloading_sessions: usize = 0; var uploading_sessions: usize = 0; var completed_sessions: usize = 0; var total_downloaded: u64 = 0; var total_uploaded: u64 = 0; self.sessions_mutex.lock(); var it = self.sessions.valueIterator(); while (it.next()) |session| { total_sessions += 1; if (session.isActive()) { active_sessions += 1; switch (session.status) { .downloading => downloading_sessions += 1, .uploading => uploading_sessions += 1, else => {}, } } else if (session.status == .completed) { completed_sessions += 1; } // Sum up data transferred if (session.download_manager) |manager| { total_downloaded += manager.state.downloaded_bytes.load(.monotonic); } if (session.upload_manager) |manager| { total_uploaded += manager.state.total_uploaded.load(.monotonic); } } self.sessions_mutex.unlock(); self.file_registry_mutex.lock(); const registered_files = self.file_registry.count(); self.file_registry_mutex.unlock(); self.stats_mutex.lock(); const messages_sent = self.messages_sent; const messages_failed = self.messages_failed; self.stats_mutex.unlock(); return FileSharingStats{ .total_sessions = total_sessions, .active_sessions = active_sessions, .downloading_sessions = downloading_sessions, .uploading_sessions = uploading_sessions, .completed_sessions = completed_sessions, .total_downloaded = total_downloaded, .total_uploaded = total_uploaded, .registered_files = registered_files, .messages_sent = messages_sent, .messages_failed = messages_failed, }; } /// PERF: Get detailed profiling statistics for performance analysis pub fn getProfilingStats(self: *FileSharingManager) ProfilingStats { // Pipeline stats var pipeline_stats = piece_pipeline_mod.PipelineStats{ .tasks_queued = 0, .tasks_processed = 0, .tasks_failed = 0, .queue_full_count = 0, .current_queue_depth = 0, .worker_count = 0, .avg_queue_wait_ns = 0, }; if (self.piece_pipeline) |pipeline| { pipeline_stats = pipeline.getStats(); } // Verification pool stats var verification_completed: u64 = 0; var verification_failed: u64 = 0; var verification_bytes_verified: u64 = 0; var verification_pending: usize = 0; var buffer_total: usize = 0; var buffer_available: usize = 0; var buffer_in_use: usize = 0; var buffer_hits: u64 = 0; var buffer_misses: u64 = 0; var buffer_fallbacks: u64 = 0; if (self.verification_pool) |pool| { const vs = pool.getStats(); verification_completed = vs.completed; verification_failed = vs.failed; verification_bytes_verified = vs.bytes_verified; verification_pending = vs.pending; // Buffer pool stats (from verification pool's buffer pool) if (pool.buffer_pool) |bp| { const bs = bp.getStats(); buffer_total = bs.total_buffers; buffer_available = bs.available_buffers; buffer_in_use = bs.in_use_buffers; buffer_hits = bs.pool_hits; buffer_misses = bs.pool_misses; buffer_fallbacks = bs.fallback_count; } } return ProfilingStats{ .pipeline_tasks_queued = pipeline_stats.tasks_queued, .pipeline_tasks_processed = pipeline_stats.tasks_processed, .pipeline_tasks_failed = pipeline_stats.tasks_failed, .pipeline_queue_full_count = pipeline_stats.queue_full_count, .pipeline_current_queue_depth = pipeline_stats.current_queue_depth, .pipeline_worker_count = pipeline_stats.worker_count, .pipeline_avg_queue_wait_ns = pipeline_stats.avg_queue_wait_ns, .verification_completed = verification_completed, .verification_failed = verification_failed, .verification_bytes_verified = verification_bytes_verified, .verification_pending = verification_pending, .buffer_pool_total = buffer_total, .buffer_pool_available = buffer_available, .buffer_pool_in_use = buffer_in_use, .buffer_pool_hits = buffer_hits, .buffer_pool_misses = buffer_misses, .buffer_pool_fallbacks = buffer_fallbacks, }; } /// Get adaptive concurrency controller statistics /// Returns null if adaptive concurrency is disabled pub fn getAdaptiveStats(self: *FileSharingManager) ?AdaptiveConcurrencyController.Stats { if (self.adaptive_controller) |*ctrl| { return ctrl.getStats(); } return null; } /// Get current effective concurrency limit /// Returns the adaptive limit if enabled, otherwise the static config value pub fn getEffectiveConcurrency(self: *FileSharingManager) usize { if (self.adaptive_controller) |*ctrl| { return ctrl.getEffectiveConcurrency(); } return self.config.max_concurrent_downloads; } /// Check if manager is idle pub fn isIdle(self: *FileSharingManager) bool { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var it = self.sessions.valueIterator(); while (it.next()) |session| { if (session.isActive()) { return false; } } return true; } /// Copied file info for thread-safe access pub const FileInfoCopy = struct { size: u64, created_at: i64, modified_at: i64, /// Caller owns this memory and must free it path: []const u8, /// Caller owns this memory and must free it name: []const u8, pub fn deinit(self: *FileInfoCopy, allocator: mem.Allocator) void { allocator.free(self.path); allocator.free(self.name); } }; /// Get file info by content hash (THREAD-SAFE) /// /// Returns a copy of file info that is safe to use across threads. /// Caller must call deinit() on the returned value to free memory. pub fn getFileInfoByHash(self: *FileSharingManager, content_hash: ContentHash) ?FileInfoCopy { self.file_registry_mutex.lock(); defer self.file_registry_mutex.unlock(); const file_info = self.file_registry.getPtr(content_hash) orelse return null; // Create copies of strings const path_copy = self.allocator.dupe(u8, file_info.path) catch return null; const name_copy = self.allocator.dupe(u8, file_info.name) catch { self.allocator.free(path_copy); return null; }; return FileInfoCopy{ .size = file_info.size, .created_at = file_info.created_at, .modified_at = file_info.modified_at, .path = path_copy, .name = name_copy, }; } /// Check if file exists by hash (THREAD-SAFE) /// /// Returns true if the file is registered, false otherwise. pub fn hasFile(self: *FileSharingManager, content_hash: ContentHash) bool { self.file_registry_mutex.lock(); defer self.file_registry_mutex.unlock(); return self.file_registry.contains(content_hash); } // MEM-M6 FIX: Removed thread-unsafe getFileByHash function. // The function returned a raw pointer that became invalid when the mutex was released. // Use getFileInfoByHash instead, which returns a safe copy of the file info. /// Remove file from registry pub fn removeFile(self: *FileSharingManager, content_hash: ContentHash) Error!void { self.file_registry_mutex.lock(); defer self.file_registry_mutex.unlock(); if (self.file_registry.fetchRemove(content_hash)) |kv| { kv.value.deinit(self.allocator); } } /// Update bandwidth limits (thread-safe) /// THR-H2 FIX: Uses config_mutex to prevent torn reads/writes pub fn updateBandwidthLimits(self: *FileSharingManager, download_limit: u64, upload_limit: u64) void { self.config_mutex.lock(); defer self.config_mutex.unlock(); self.config.max_bandwidth_download = download_limit; self.config.max_bandwidth_upload = upload_limit; } /// Set piece selection strategy (thread-safe) /// THR-H2 FIX: Uses config_mutex to prevent torn reads/writes pub fn setSelectionStrategy(self: *FileSharingManager, strategy: SelectionStrategy) void { self.config_mutex.lock(); defer self.config_mutex.unlock(); self.config.selection_strategy = strategy; } /// Enable/disable features (thread-safe) /// THR-H2 FIX: Uses config_mutex to prevent torn reads/writes pub fn setFeatures(self: *FileSharingManager, enable_upload: bool, enable_download: bool) void { self.config_mutex.lock(); defer self.config_mutex.unlock(); self.config.enable_upload = enable_upload; self.config.enable_download = enable_download; } /// Get a copy of current config (thread-safe) /// THR-H2 FIX: Returns a copy to prevent holding mutex while reading pub fn getConfig(self: *FileSharingManager) FileSharingConfig { self.config_mutex.lock(); defer self.config_mutex.unlock(); return self.config; } // CRIT-1 FIX: Removed public findSessionByHash that returned pointer after mutex release. // All callers have been migrated to thread-safe alternatives: // - servePieceDataByHash() for reading piece data from uploads // - writePieceDataByHash() for writing piece data to downloads // - getFileMetadataByHash() for getting metadata copy // - checkAndCompleteDownloadByHash() for completion checks // - withSessionByHash() / withSessionByHashResult() for callbacks // - hasSessionByHash() for existence checks // - getSessionInfoByHash() for reading session stats // - findSessionIdByHash() for getting session ID /// Check if a session exists for the given content hash (THREAD-SAFE) /// /// THR-M3 FIX: Safe alternative for existence checks that doesn't return a pointer pub fn hasSessionByHash(self: *FileSharingManager, content_hash: [32]u8) bool { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); return self.findSessionByHashUnsafe(content_hash) != null; } /// Find session by content hash (requires caller to hold sessions_mutex) /// PERF FIX: Now uses cached content_hash field instead of recomputing metadataHash. /// Before: O(sessions * piece_count) per lookup. After: O(sessions) per lookup. fn findSessionByHashUnsafe(self: *FileSharingManager, content_hash: [32]u8) ?*FileSharingSession { var it = self.sessions.valueIterator(); while (it.next()) |session| { // PERF FIX: Use cached content_hash instead of recomputing // Old code called HashUtils.metadataHash which iterates all piece_hashes if (std.crypto.timing_safe.eql([32]u8, session.content_hash, content_hash)) { return session; } } return null; } /// Execute a callback with exclusive access to a session found by content hash (THREAD-SAFE) /// /// MEM-1 FIX: This is the safe way to access sessions by hash. The callback /// executes while the mutex is held, preventing use-after-free. /// /// Example: /// ```zig /// const result = try manager.withSessionByHash(hash, struct { /// fn callback(session: *FileSharingSession) Error!void { /// // Safe to access session here /// session.status = .active; /// } /// }.callback); /// ``` pub fn withSessionByHash( self: *FileSharingManager, content_hash: [32]u8, callback: *const fn (*FileSharingSession) Error!void, ) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse return Error.FileError; return callback(session); } /// Execute a callback with exclusive access to a session found by hash, returning a value (THREAD-SAFE) /// /// MEM-1 FIX: Generic version that can return a value from the callback. pub fn withSessionByHashResult( self: *FileSharingManager, content_hash: [32]u8, comptime T: type, callback: *const fn (*FileSharingSession) ?T, ) ?T { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse return null; return callback(session); } /// Get a copy of session info by content hash (THREAD-SAFE) /// /// MEM-1 FIX: Returns a copy of session stats rather than a pointer. /// This is safe for reading session state without holding the mutex. pub fn getSessionInfoByHash(self: *FileSharingManager, content_hash: [32]u8) ?SessionStats { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse return null; return session.getStats(); } /// Get session ID by content hash (THREAD-SAFE) /// /// MEM-1 FIX: Returns just the session ID, which can be used with /// withSession() for safe modifications. pub fn findSessionIdByHash(self: *FileSharingManager, content_hash: [32]u8) ?u64 { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse return null; return session.session_id; } /// Find peers with file (broadcast metadata request) pub fn findPeersWithFile(self: *FileSharingManager, content_hash: [32]u8) Error!void { const sender = self.network_sender orelse return Error.InvalidState; // Create metadata request const request = TransferMessage.metadataRequest("", content_hash, self.allocator); defer self.allocator.free(request.data); const data = request.serialize(self.allocator) catch return Error.OutOfMemory; defer self.allocator.free(data); // Broadcast to all peers (the P2P layer handles this) // We use empty peer_id to indicate broadcast // CRIT-4 FIX: Check network send return value const send_success = sender.send_fn("", data, sender.context); if (!send_success) { std.log.err("CRIT-4: Failed to broadcast metadata request for file hash - peers may not respond", .{}); return Error.NetworkError; } } /// Handle piece request from peer /// MEM-1 FIX: Lock sessions_mutex for the entire operation to prevent use-after-free /// Maximum memory for queued piece_data responses per session to prevent memory exhaustion. /// This provides backpressure when network can't keep up with disk reads. /// THROUGHPUT FIX: Increased from 2GB to 4GB for high-throughput localhost testing. /// With 1MB pieces: 4GB / 1MB = 4096 messages /// This allows deep pipelines without triggering fair queue rejection. const MAX_QUEUED_RESPONSE_BYTES: usize = 4 * 1024 * 1024 * 1024; // 4GB max for high throughput /// Calculate adaptive queue limit based on piece size fn calculateMaxQueuedResponses(piece_size: u64) usize { // Minimum 64 to ensure reasonable throughput, max 4000 for smaller pieces // THROUGHPUT FIX: Increased limits to prevent silent request rejection const piece_size_usize: usize = if (piece_size > std.math.maxInt(usize)) std.math.maxInt(usize) else @intCast(piece_size); if (piece_size_usize == 0) return 4000; const calculated = MAX_QUEUED_RESPONSE_BYTES / piece_size_usize; return @min(4000, @max(64, calculated)); } /// Count only piece_data messages in the queue (the memory-heavy ones). /// BACKPRESSURE FIX: Requests (small, ~40 bytes) should NOT count against the /// response memory limit. Only piece_data responses (large, ~1MB) should be counted. fn countPieceDataMessages(pending_messages: []const TransferMessage) usize { var count: usize = 0; for (pending_messages) |msg| { if (msg.message_type == .piece_data) { count += 1; } } return count; } /// FAIR QUEUE FIX: Count piece_data messages for a specific peer. /// This enables per-peer backpressure to prevent one peer from monopolizing the queue. fn countPieceDataForPeer(pending_messages: []const TransferMessage, peer_id: [32]u8) usize { var count: usize = 0; for (pending_messages) |msg| { if (msg.message_type == .piece_data and msg.peer_id.len >= 32) { if (std.mem.eql(u8, msg.peer_id[0..32], &peer_id)) { count += 1; } } } return count; } /// ZERO-COPY: Handle piece request using mmap and scatter-gather sends /// This eliminates all data copies on the upload path for maximum throughput. pub fn handlePieceRequest(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { if (payload.len < 40) return Error.InvalidData; // Parse: content_hash(32) + piece_index(4) + offset(4) const content_hash = payload[0..32].*; const piece_index = std.mem.readInt(u32, payload[32..36], .big); const offset = std.mem.readInt(u32, payload[36..40], .big); // PERF FIX: Extract info needed for disk I/O while holding mutex, then release // before doing I/O. This allows other operations to proceed during disk reads. var metadata_piece_size: u64 = undefined; var session_id: u64 = undefined; // Phase 1: Validate and extract info (with mutex) { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; // Extract piece size FIRST for adaptive backpressure calculation metadata_piece_size = if (session.file_metadata.piece_count > 0) (session.file_metadata.size + session.file_metadata.piece_count - 1) / session.file_metadata.piece_count else self.config.piece_size; // NOTE: Backpressure is now handled by PeerResponseTracker (fair queue) // which provides per-peer slot allocation instead of global count. // SECURITY: Validate piece_index if (piece_index >= session.file_metadata.piece_count) { return Error.InvalidData; } session_id = session.session_id; // Validate offset if (offset >= metadata_piece_size) { return Error.InvalidData; } if (metadata_piece_size > FileSharingLimits.MAX_PIECE_SIZE) { return Error.InvalidData; } } // Mutex released here - other operations can proceed // Phase 2: Read piece data using zero-copy mmap path // Calculate read size based on offset within piece const remaining_in_piece = metadata_piece_size - offset; const read_size: u32 = @intCast(@min(remaining_in_piece, FileSharingLimits.MAX_PIECE_DATA_SIZE)); // ZERO-COPY: Use readPieceData which returns mmap'd slice when available var piece_data: upload_mod.PieceData = undefined; { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; if (session.session_id != session_id) { return Error.FileError; } if (session.upload_manager) |*manager| { piece_data = manager.readPieceData(piece_index, offset, read_size) catch |err| { std.log.debug("readPieceData failed: {}", .{err}); return Error.FileError; }; } else { return Error.OperationNotSupported; } } // piece_data.data is either mmap'd (zero-copy) or allocated // On error, we must call piece_data.deinit() to free allocated data // SECURITY: Validate returned piece data size if (piece_data.data.len > FileSharingLimits.MAX_PIECE_DATA_SIZE) { piece_data.deinit(); return Error.InvalidData; } // Phase 3: Create zero-copy pre-serialized response // PreSerializedPieceResponse holds a reference to piece_data (no copy!) // owns_data indicates whether piece_data was allocated (true) or mmap'd (false) const owns_data = piece_data.allocator != null; const preserialized = PreSerializedPieceResponse.create( peer_id, content_hash, piece_index, offset, piece_data.data, owns_data, piece_data.allocator, ); // DO NOT call piece_data.deinit() here - ownership transferred to preserialized // Phase 4: Queue response (with mutex) // FAIR QUEUE: Allocate slot here (after we know exact size) to avoid slot leaks on earlier errors { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { // Must clean up preserialized since queue failed var cleanup = preserialized; cleanup.deinit(); return Error.FileError; }; // FAIR QUEUE: Allocate slot just before queueing (ensures release on any failure) if (session.response_tracker) |*tracker| { if (!tracker.allocateSlot(peer_id, piece_data.data.len)) { std.log.debug("FAIR QUEUE: Rejected - peer at slot limit", .{}); var cleanup = preserialized; cleanup.deinit(); return Error.ResourceExhausted; } } // ZERO-COPY: Queue to new preserialized queue (scatter-gather optimized) session.pending_piece_responses.append(self.allocator, preserialized) catch |err| { std.log.err("Failed to queue piece {} data response: {}", .{ piece_index, err }); // Release slot on queue failure if (session.response_tracker) |*tracker| { tracker.releaseSlot(peer_id, piece_data.data.len); } var cleanup = preserialized; cleanup.deinit(); return Error.OutOfMemory; }; // Track upload stats if (session.upload_manager) |*manager| { manager.state.addUploadedBytes(piece_data.data.len); } } } /// Handle batch piece request - multiple pieces in single message /// Format: content_hash(32) + piece_count(2) + piece_indices(4 * count) pub fn handleBatchPieceRequest(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { if (payload.len < 34) return Error.InvalidData; const content_hash = payload[0..32].*; const piece_count = std.mem.readInt(u16, payload[32..34], .big); if (piece_count == 0 or piece_count > 64) return Error.InvalidData; const expected_len = 34 + (@as(usize, piece_count) * 4); if (payload.len < expected_len) return Error.InvalidData; // Process each piece in the batch var offset: usize = 34; for (0..piece_count) |_| { const piece_index = std.mem.readInt(u32, payload[offset..][0..4], .big); offset += 4; // Build single piece request payload and reuse existing handler var single_payload: [40]u8 = undefined; @memcpy(single_payload[0..32], &content_hash); std.mem.writeInt(u32, single_payload[32..36], piece_index, .big); std.mem.writeInt(u32, single_payload[36..40], 0, .big); // offset = 0 self.handlePieceRequest(peer_id, &single_payload) catch |err| { std.log.debug("BATCH: Failed to handle piece {}: {}", .{ piece_index, err }); // THROUGHPUT FIX: Send piece_reject for each failed piece in batch // Without this, client waits for stuck timeout instead of immediate retry const reason: u8 = switch (err) { Error.ResourceExhausted => 0, // busy Error.FileError, Error.OperationNotSupported => 1, // not_available else => 2, // rate_limited/other }; var reject_payload: [37]u8 = undefined; @memcpy(reject_payload[0..32], &content_hash); std.mem.writeInt(u32, reject_payload[32..36], piece_index, .big); reject_payload[36] = reason; if (self.network_sender) |sender| { const reject_msg = transfer_mod.TransferMessage{ .message_type = .piece_reject, .message_id = 0, .peer_id = &peer_id, .data = &reject_payload, .timestamp = std.time.timestamp(), }; _ = sender.sendMessage(reject_msg) catch {}; } continue; }; } } /// Handle piece data from peer - queues to pipeline for parallel processing /// PERF: Network thread just validates and queues; worker threads do heavy lifting pub fn handlePieceData(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { if (payload.len < 40) return Error.InvalidData; // Quick blacklist check before any processing { self.reputation_mutex.lock(); defer self.reputation_mutex.unlock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { if (rep.isBlacklisted()) { std.log.warn("Rejecting piece from blacklisted peer", .{}); return Error.InvalidData; } } } // Parse header for queueing const content_hash = payload[0..32].*; const piece_index = std.mem.readInt(u32, payload[32..36], .big); const offset = std.mem.readInt(u32, payload[36..40], .big); const piece_data = payload[40..]; // Basic size validation if (piece_data.len > FileSharingLimits.MAX_PIECE_DATA_SIZE) { return Error.InvalidData; } // PERF: Queue to pipeline for parallel processing if (self.piece_pipeline) |pipeline| { pipeline.queuePiece(peer_id, content_hash, piece_index, offset, piece_data) catch |err| { // Pipeline full or allocation failed - fall back to direct processing if (err == Error.QueueFull) { // Process directly when queue is full return self.processPieceInternal(peer_id, content_hash, piece_index, offset, piece_data); } return err; }; return; } // No pipeline - process directly return self.processPieceInternal(peer_id, content_hash, piece_index, offset, piece_data); } /// Internal piece processing - called by pipeline workers or directly /// Contains the full piece processing logic: validation, verification, disk write fn processPieceInternal( self: *FileSharingManager, peer_id: [32]u8, content_hash: [32]u8, piece_index: u32, offset: u32, piece_data: []const u8, ) Error!void { // HIGH-4 FIX: Reserve memory quota for this piece before processing var memory_reserved = false; self.reputation_mutex.lock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { // Check quota before reserving if (rep.hasExceededMemoryQuota()) { self.reputation_mutex.unlock(); std.log.warn("HIGH-4: Rejecting piece - peer has exceeded memory quota", .{}); return Error.RateLimitExceeded; } memory_reserved = rep.reserveMemory(piece_data.len); } else { // CRIT-3 FIX: Enforce peer reputation limit to prevent resource exhaustion if (self.peer_reputation.count() >= self.config.max_reputation_peers) { self.reputation_mutex.unlock(); std.log.err("CRIT-3: Peer reputation limit reached ({}/{}), rejecting piece from unknown peer", .{ self.peer_reputation.count(), self.config.max_reputation_peers }); return Error.PoolExhausted; } // Create new reputation entry for unknown peer const gop = self.peer_reputation.getOrPut(peer_id) catch { self.reputation_mutex.unlock(); return Error.OutOfMemory; }; if (!gop.found_existing) { gop.value_ptr.* = PeerReputation.init(peer_id); } memory_reserved = gop.value_ptr.reserveMemory(piece_data.len); } self.reputation_mutex.unlock(); if (!memory_reserved) { std.log.warn("HIGH-4: Rejecting piece - peer would exceed memory quota", .{}); return Error.RateLimitExceeded; } // Ensure memory is released on all error paths errdefer { self.reputation_mutex.lock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { rep.releaseMemory(piece_data.len); } self.reputation_mutex.unlock(); } // PERF FIX: Extract info needed for SHA-256 while holding mutex, then release // before doing CPU-intensive hash verification. Disk I/O uses cached file handle. var expected_hash: [32]u8 = undefined; var metadata_piece_size: u64 = undefined; var expected_piece_size: u64 = undefined; var session_id: u64 = undefined; // Phase 1: Extract info for SHA-256 verification (with mutex) { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; if (session.download_manager) |*dm| { // FIX: Check if piece is already downloaded or verified (duplicate handling) // In endgame mode, same piece can be requested from multiple peers // and multiple responses may arrive. Skip duplicates to avoid // double-counting in completion statistics. // Also skip pieces marked is_downloaded (pending async verification). if (dm.selector.availability_map.get(piece_index)) |piece_info| { if (piece_info.is_verified or piece_info.is_downloaded) { // Piece already processed or pending verification - skip duplicate defer { self.reputation_mutex.lock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { rep.releaseMemory(piece_data.len); } self.reputation_mutex.unlock(); } return; } } // Validate piece_index if (piece_index >= session.file_metadata.piece_count) { return Error.InvalidData; } // Calculate piece size metadata_piece_size = if (session.file_metadata.piece_count > 0) (session.file_metadata.size + session.file_metadata.piece_count - 1) / session.file_metadata.piece_count else self.config.piece_size; // Validate offset if (offset >= metadata_piece_size) { return Error.InvalidData; } // Get expected hash for verification if (piece_index >= session.file_metadata.piece_hashes.len) { return Error.InvalidData; } expected_hash = session.file_metadata.piece_hashes[piece_index]; // Calculate expected piece size const piece_file_offset = std.math.mul(u64, piece_index, metadata_piece_size) catch { return Error.BufferOverflow; }; expected_piece_size = @min(metadata_piece_size, session.file_metadata.size - piece_file_offset); session_id = session.session_id; } else { return Error.OperationNotSupported; } } // Mutex released - now do CPU/IO intensive work // PERF: Phase 2 - Get write info with mutex, then release for disk I/O // ASYNC VERIFICATION: Do disk write FIRST, then queue verification. // This allows parallel verification while writes complete atomically via pwrite. // Using pwrite allows concurrent writes without holding mutex during I/O var write_file: std.fs.File = undefined; var absolute_offset: u64 = undefined; var write_file_path: []const u8 = undefined; { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; if (session.session_id != session_id) { return Error.FileError; } if (session.download_manager) |*dm| { const write_info = dm.getWriteInfo(piece_index, offset) catch { return Error.FileError; }; write_file = write_info.file; absolute_offset = write_info.absolute_offset; write_file_path = write_info.file_path; } else { return Error.OperationNotSupported; } } // Mutex released - now do disk I/O without blocking other threads // PERF: Phase 3b - Disk write WITHOUT mutex using pwrite (thread-safe) file_mod.checkDiskSpace(write_file_path, piece_data.len) catch { return Error.FileError; }; write_file.pwriteAll(piece_data, absolute_offset) catch { return Error.FileError; }; // CASCADE RACE FIX: Sync data to ensure visibility for cascade reads. // All writes need to be synced so cascade readers (UploadManager) see the data. // Note: F_FULLFSYNC is too slow per-piece; we use it only at completion time. write_file.sync() catch |sync_err| { std.log.err("SYNC FAILED for piece {d}: {} - data may not be persisted", .{ piece_index, sync_err }); // Continue anyway - data is in OS buffer, will eventually be written }; // ASYNC VERIFICATION: For complete pieces, queue verification to thread pool // This enables parallel SHA-256 computation across multiple CPU cores const is_complete_piece = (offset == 0 and piece_data.len == expected_piece_size); var async_queued = false; if (is_complete_piece) { if (self.verification_pool) |pool| { // Queue for async verification - handleVerificationResult will update state // NOTE: This verifies the in-memory network data, not disk data. // A full disk verification is done at completion time to catch any write failures. const queued = queue_blk: { pool.queueVerification( session_id, piece_index, piece_data, expected_hash, peer_id, ) catch |err| { // Queue full or OOM - fall back to sync verification below std.log.warn("ASYNC: Queue full, falling back to sync verification: {}", .{err}); break :queue_blk false; }; break :queue_blk true; }; if (queued) { async_queued = true; // Track downloaded bytes, remove from active_downloads, and release pipeline slot // Removing from active_downloads prevents stuck download cleanup from // timing out pieces that are pending verification in the thread pool. // Releasing pipeline slot allows new requests to be sent to this peer immediately. // handleVerificationResult will mark the piece complete when verification finishes. { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); if (self.findSessionByHashUnsafe(content_hash)) |session| { if (session.download_manager) |*dm| { dm.addDownloadedBytesExternal(piece_data.len); // Remove from active to prevent stuck timeout _ = dm.active_downloads.remove(piece_index); // CRITICAL: Release pipeline slot immediately so new requests can be sent // We don't need to wait for verification - if it fails, we'll re-request dm.request_tracker.recordCompletion(peer_id, piece_index); // FIX: Mark piece as pending verification to prevent re-selection. // Without this, the piece remains isReady()=true during async verification, // allowing endgame mode to re-request it. Multiple completions inflate // the completed_pieces counter, triggering COMPLETION MISMATCH resets // that cause progress to oscillate between ~98% and single digits. // Use markPendingVerification (not markDownloaded) to avoid resetting // is_verified if a concurrent verification already completed. dm.selector.markPendingVerification(piece_index); } } } // Release memory reservation - data is copied to verification queue self.reputation_mutex.lock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { rep.releaseMemory(piece_data.len); } self.reputation_mutex.unlock(); // Return early - handleVerificationResult will mark piece complete return; } } // No verification pool or queue failed - fall through to sync path } // SYNC PATH: For partial pieces or when verification_pool unavailable/full // Phase 3: SHA-256 verification (sync fallback) var reputation_update: ?bool = null; if (is_complete_piece and !async_queued) { const is_valid = HashUtils.verify(piece_data, expected_hash) catch |err| { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); if (self.findSessionByHashUnsafe(content_hash)) |session| { if (session.download_manager) |*dm| { _ = dm.active_downloads.remove(piece_index); dm.handleDownloadFailure(piece_index, "Hash computation error") catch |fail_err| { std.log.err("Failed to handle download failure for piece {d}: {}", .{ piece_index, fail_err }); }; } } return err; }; if (!is_valid) { // ADAPTIVE: Record timeout/failure for bad piece if (self.adaptive_controller) |*ctrl| { ctrl.recordTimeout(); } self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); if (self.findSessionByHashUnsafe(content_hash)) |session| { if (session.download_manager) |*dm| { _ = dm.active_downloads.remove(piece_index); dm.handleDownloadFailure(piece_index, "Hash verification failed") catch |fail_err| { std.log.err("Failed to handle download failure for piece {d}: {}", .{ piece_index, fail_err }); }; } } self.updatePeerReputation(peer_id, false); return Error.InvalidData; } reputation_update = true; } // Phase 4: Re-acquire mutex for state updates only // CASCADE FIX: Track whether to broadcast after releasing mutex var cascade_broadcast = false; var cascade_piece_hash: [32]u8 = undefined; var download_completed = false; { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; if (session.session_id != session_id) { return Error.FileError; } if (session.download_manager) |*dm| { // Update downloaded bytes count dm.addDownloadedBytesExternal(piece_data.len); // Check if piece is complete const bytes_written_end = std.math.add(u64, offset, piece_data.len) catch { return Error.BufferOverflow; }; if (bytes_written_end == expected_piece_size) { // RACE FIX: Check if piece was already verified by another thread // In endgame mode, same piece can arrive from multiple peers. // If both threads passed the initial check before either marked verified, // without this check both would increment the counter causing over-count. const already_verified = if (dm.selector.availability_map.get(piece_index)) |info| info.is_verified else false; if (already_verified) { // Another thread already completed this piece - skip counter update std.log.debug("RACE: Piece {d} already verified, skipping duplicate", .{piece_index}); _ = dm.active_downloads.remove(piece_index); // Still need to release pipeline slot dm.request_tracker.recordCompletion(peer_id, piece_index); } else { // First thread to complete this piece - mark it done // FIX: Mark verified FIRST to prevent other threads from also updating counter dm.selector.markVerified(piece_index) catch {}; dm.state.addVerifiedBytes(piece_data.len); dm.state.markPieceCompleted(); _ = dm.active_downloads.remove(piece_index); dm.request_tracker.recordCompletion(peer_id, piece_index); // ADAPTIVE: Record successful piece completion if (self.adaptive_controller) |*ctrl| { ctrl.recordSuccess(); } // CASCADE FIX: Prepare to broadcast after mutex release if (piece_index < session.file_metadata.piece_hashes.len) { cascade_piece_hash = session.file_metadata.piece_hashes[piece_index]; cascade_broadcast = true; } const completed = dm.state.completed_pieces.load(.acquire); // Check if download is complete if (completed == dm.state.piece_count) { // PRE-COMPLETION VERIFICATION: Verify all pieces are actually marked // as verified in the selector before marking download complete. // This catches any race conditions where the counter is correct but // some pieces weren't properly verified. var all_verified = true; var verified_count: u32 = 0; var unverified_pieces: [10]u32 = undefined; var unverified_count: usize = 0; var selector_iter = dm.selector.availability_map.iterator(); while (selector_iter.next()) |entry| { if (entry.value_ptr.is_verified) { verified_count += 1; } else { all_verified = false; if (unverified_count < 10) { unverified_pieces[unverified_count] = entry.key_ptr.*; unverified_count += 1; } } } if (!all_verified) { // Log mismatch - counter says complete but selector disagrees std.log.warn("COMPLETION MISMATCH: Counter={d}, Verified={d}/{d}, unverified pieces: {any}", .{ completed, verified_count, dm.state.piece_count, unverified_pieces[0..unverified_count], }); // Don't mark as complete - let pieces be re-requested // Reset completed counter to match actual verified count dm.state.completed_pieces.store(verified_count, .release); } else { // FIX: Sync file to ensure all pwrite data is flushed // Other pieces may have completed out of order and their // pwrite operations may still be in OS buffers if (dm.file_writer) |*fw| { fw.flush() catch |flush_err| { std.log.warn("Failed to flush file on completion: {}", .{flush_err}); }; } session.status = .completed; session.updated_at = std.time.timestamp(); std.log.info("Download completed! All {d} pieces verified", .{dm.state.piece_count}); // CASCADE FIX: Mark for full bitfield broadcast download_completed = true; } } } } } } // CASCADE FIX: Broadcast "have" message AFTER releasing sessions_mutex // This enables cascading distribution - other peers can now download this piece from us if (cascade_broadcast) { self.markPieceAvailableForUpload(session_id, piece_index, cascade_piece_hash); self.broadcastHavePiece(session_id, piece_index); } // CASCADE FIX: Broadcast full bitfield when download completes // This notifies all connected peers that we now have ALL pieces if (download_completed) { self.broadcastFullBitfield(session_id); } // Now update reputation (acquires reputation_mutex) - respecting lock ordering if (reputation_update) |is_good| { self.updatePeerReputation(peer_id, is_good); } // HIGH-4 FIX: Release memory reservation after successful processing self.reputation_mutex.lock(); if (self.peer_reputation.getPtr(peer_id)) |rep| { rep.releaseMemory(piece_data.len); } self.reputation_mutex.unlock(); } /// Update peer reputation based on piece validity fn updatePeerReputation(self: *FileSharingManager, peer_id: [32]u8, is_good: bool) void { self.reputation_mutex.lock(); defer self.reputation_mutex.unlock(); // CRIT-3 FIX: Check limit BEFORE getOrPut to prevent unbounded growth // First check if peer already exists (no limit issue for existing peers) if (self.peer_reputation.get(peer_id) == null) { // New peer - check if we're at the limit if (self.peer_reputation.count() >= self.config.max_reputation_peers) { std.log.warn("CRIT-3: Peer reputation limit reached ({}/{}), cannot track new peer", .{ self.peer_reputation.count(), self.config.max_reputation_peers }); return; } } const gop = self.peer_reputation.getOrPut(peer_id) catch { std.log.warn("Failed to update peer reputation", .{}); return; }; if (!gop.found_existing) { gop.value_ptr.* = PeerReputation.init(peer_id); } if (is_good) { gop.value_ptr.recordGoodPiece(); } else { gop.value_ptr.recordBadPiece(); if (gop.value_ptr.isBlacklisted()) { std.log.warn("Peer blacklisted after {} bad pieces", .{gop.value_ptr.bad_pieces}); } } } /// Get peer reputation score (for monitoring/debugging) pub fn getPeerReputation(self: *FileSharingManager, peer_id: [32]u8) ?PeerReputation { self.reputation_mutex.lock(); defer self.reputation_mutex.unlock(); return self.peer_reputation.get(peer_id); } /// Result of piece data write operation pub const PieceWriteResult = struct { /// Whether the download is now complete is_complete: bool, /// Current download progress (0.0 to 1.0) progress: f64, }; /// Write piece data by content hash (THREAD-SAFE) /// /// CRIT-1 FIX: This method holds the sessions_mutex during the entire operation, /// preventing TOCTOU race conditions that could occur with findSessionByHash(). /// /// This is the safe way to write piece data from external callbacks (like /// handleDataResponseCallback) that receive data identified by content hash. /// /// Parameters: /// - content_hash: The content hash identifying the download session /// - piece_index: The index of the piece being written /// - offset: Offset within the piece /// - data: The piece data to write /// /// Returns: /// - PieceWriteResult with completion status and progress /// - Error if session not found, not downloading, or write fails pub fn writePieceDataByHash( self: *FileSharingManager, content_hash: [32]u8, piece_index: u32, offset: u64, data: []const u8, ) Error!PieceWriteResult { // CRIT-1 FIX: Hold lock for entire operation to prevent use-after-free self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // Find session while holding lock const session = self.findSessionByHashUnsafe(content_hash) orelse { std.log.warn("writePieceDataByHash: session not found for hash", .{}); return Error.FileError; }; // Check if we're downloading this file if (session.download_manager) |*dm| { // Validate piece_index is within valid range if (piece_index >= session.file_metadata.piece_count) { std.log.warn("writePieceDataByHash: invalid piece_index {d} >= {d}", .{ piece_index, session.file_metadata.piece_count, }); return Error.InvalidData; } // Write the piece data dm.writePieceData(piece_index, offset, data) catch |err| { std.log.err("writePieceDataByHash: write failed for piece {d} at offset {d}: {}", .{ piece_index, offset, err, }); return Error.FileError; }; // Get stats and check completion const stats = dm.getStats(); const is_complete = dm.isComplete(); // Update session status if complete if (is_complete) { session.status = .completed; std.log.info("writePieceDataByHash: download completed for session", .{}); } return PieceWriteResult{ .is_complete = is_complete, .progress = stats.progress, }; } else { std.log.err("writePieceDataByHash: no download manager for session", .{}); return Error.OperationNotSupported; } } /// Serve piece data by content hash (THREAD-SAFE) /// /// CRIT-1 FIX: This method holds the sessions_mutex during the entire operation, /// preventing use-after-free that would occur with findSessionByHash(). /// /// Used by handleDataRequest to safely read and serve piece data from upload sessions. /// Returns PieceData which may be zero-copy (mmap) or owned - caller must call .deinit() pub fn servePieceDataByHash( self: *FileSharingManager, content_hash: [32]u8, piece_index: u32, offset: u32, size: u32, ) Error!upload_mod.PieceData { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; // HIGH-1 FIX: Validate piece_index is within valid range if (piece_index >= session.file_metadata.piece_count) { return Error.InvalidData; } // HIGH-1 FIX: Validate offset is within piece bounds if (offset >= self.config.piece_size) { return Error.InvalidData; } // HIGH-1 FIX: Validate requested size doesn't exceed piece bounds const remaining_in_piece = self.config.piece_size - offset; if (size > remaining_in_piece) { return Error.InvalidData; } if (session.upload_manager) |*um| { return um.readPieceData(piece_index, offset, size) catch Error.FileError; } else { return Error.OperationNotSupported; } } /// Get a deep copy of file metadata by session ID (THREAD-SAFE) /// /// Returns owned copies of all metadata fields for sharing with other peers. /// Caller must free the returned name and piece_hashes using the provided allocator. pub fn getFileMetadataBySessionId(self: *FileSharingManager, session_id: u64, allocator: mem.Allocator) Error!?FileMetadata { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse { return null; }; // Deep copy the metadata to avoid returning pointers to session-owned memory const name_copy = allocator.dupe(u8, session.file_metadata.name) catch return Error.OutOfMemory; errdefer allocator.free(name_copy); const hashes_copy = allocator.dupe(hash_mod.PieceHash, session.file_metadata.piece_hashes) catch { allocator.free(name_copy); return Error.OutOfMemory; }; return FileMetadata{ .name = name_copy, .size = session.file_metadata.size, .piece_count = session.file_metadata.piece_count, .piece_hashes = hashes_copy, .created_at = session.file_metadata.created_at, .modified_at = session.file_metadata.modified_at, }; } /// Get a deep copy of file metadata by content hash (THREAD-SAFE) /// /// CRIT-1 FIX: Returns owned copies of all metadata fields. /// Caller must free the returned name and piece_hashes using the provided allocator. pub fn getFileMetadataByHash(self: *FileSharingManager, content_hash: [32]u8, allocator: mem.Allocator) Error!?FileMetadata { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return null; }; // Deep copy the metadata to avoid returning pointers to session-owned memory const name_copy = allocator.dupe(u8, session.file_metadata.name) catch return Error.OutOfMemory; errdefer allocator.free(name_copy); const hashes_copy = allocator.dupe(hash_mod.PieceHash, session.file_metadata.piece_hashes) catch { allocator.free(name_copy); return Error.OutOfMemory; }; return FileMetadata{ .name = name_copy, .size = session.file_metadata.size, .piece_count = session.file_metadata.piece_count, .piece_hashes = hashes_copy, .created_at = session.file_metadata.created_at, .modified_at = session.file_metadata.modified_at, }; } /// Check if download is complete and update status (THREAD-SAFE) /// /// CRIT-1 FIX: Safely checks completion status while holding the mutex. /// Returns true if download is now complete, false otherwise. pub fn checkAndCompleteDownloadByHash(self: *FileSharingManager, content_hash: [32]u8) bool { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(content_hash) orelse { return false; }; if (session.download_manager) |*dm| { if (dm.isComplete()) { session.status = .completed; return true; } } return false; } /// Handle piece reject message - seeder was busy/overloaded (THREAD-SAFE) /// /// THROUGHPUT FIX: When a seeder sends piece_reject, we immediately mark the piece /// for retry with a different peer. This eliminates the 16-second stuck timeout /// that was causing 20%+ of requests to timeout. /// /// Format: content_hash(32) + piece_index(4) + reason(1) /// Reason: 0=busy, 1=not_available, 2=rate_limited pub fn handlePieceReject(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { if (payload.len < 37) return Error.InvalidData; const content_hash = payload[0..32].*; const piece_index = std.mem.readInt(u32, payload[32..36], .big); const reason = payload[36]; std.log.debug("Received piece_reject for piece {} reason={} from peer", .{ piece_index, reason }); self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // Find session by content hash const session = self.findSessionByHashUnsafe(content_hash) orelse { return Error.FileError; }; // Get download manager (mutable pointer for locking) if (session.download_manager) |*dm| { // Mark the piece for immediate retry: // 1. Remove from active downloads so stuck cleanup doesn't interfere // 2. Release the request tracker slot // 3. Re-add to pending_requests for immediate retry dm.manager_mutex.lock(); defer dm.manager_mutex.unlock(); if (dm.active_downloads.remove(piece_index)) { // Release request tracker slot dm.request_tracker.recordCompletion(peer_id, piece_index); // Record this as a soft failure for the peer (not as severe as timeout) // This helps peer selection prefer other peers if (reason == 0) { // busy dm.request_tracker.metrics_manager.recordRequestRejected(peer_id); } // BUG FIX: Re-add piece to pending_requests for immediate retry // The piece was removed from pending_requests when it became active, // so we MUST re-add it here or the piece will be "lost". const piece_offset = std.math.mul(u64, piece_index, dm.piece_size) catch { std.log.warn("Piece {} overflow in reject handler", .{piece_index}); return; }; const piece_size_u32: u32 = if (dm.piece_size > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(dm.piece_size); const request = download_mod.DownloadRequest{ .piece_index = piece_index, .offset = piece_offset, .length = piece_size_u32, .priority = .normal, .requested_at = std.time.timestamp(), // Use zero peer_id so a different peer will be selected .peer_id = [_]u8{0} ** 32, }; // Insert at FRONT of queue for immediate retry dm.pending_requests.insert(self.allocator, 0, request) catch { std.log.warn("Failed to re-queue piece {} after reject", .{piece_index}); return; }; std.log.debug("Piece {} re-queued for immediate retry after reject", .{piece_index}); } } } /// Handle bitfield message - peer announcing which pieces they have (THREAD-SAFE) /// /// This processes bitfield messages from peers who are sharing files we want to download. /// Updates the download manager's peer-piece availability map. /// BUG FIX: Only adds peer to download sessions where piece_count matches the bitfield's piece_count. pub fn handleBitfield(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { // First extract the piece count from bitfield header (first 4 bytes) if (payload.len < 4) { std.log.warn("Bitfield payload too short: {} bytes", .{payload.len}); return Error.InvalidData; } const bitfield_piece_count = std.mem.readInt(u32, payload[0..4], .big); // Parse bitfield to get list of available piece indices const available_pieces = transfer_mod.TransferMessage.parseBitfield(payload, self.allocator) orelse { std.log.warn("Failed to parse bitfield message", .{}); return Error.InvalidData; }; defer self.allocator.free(available_pieces); std.log.debug("Received bitfield from peer with {} available pieces (piece_count={})", .{ available_pieces.len, bitfield_piece_count }); // Update only MATCHING download sessions with this peer's availability self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var session_count: usize = 0; var download_session_count: usize = 0; var matched_session_count: usize = 0; var sessions_it = self.sessions.valueIterator(); while (sessions_it.next()) |session| { session_count += 1; // Only update download sessions if (session.download_manager) |*dm| { download_session_count += 1; // BUG FIX: Only add peer to sessions where piece_count matches // This prevents adding a peer sharing file A to download sessions for file B if (session.file_metadata.piece_count != bitfield_piece_count) { std.log.debug("Skipping session {} - piece count mismatch (session={}, bitfield={})", .{ session.session_id, session.file_metadata.piece_count, bitfield_piece_count, }); continue; } matched_session_count += 1; // Add peer with their available pieces dm.addPeer(&peer_id, available_pieces) catch |err| { std.log.warn("Failed to add peer to download manager: {}", .{err}); continue; }; std.log.info("Added peer to download session {} with {} pieces (piece_count matched)", .{ session.session_id, available_pieces.len }); // PERF FIX: Use load-balanced piece distribution // This handles the case where startSharing was called before any peers were known // Instead of assigning ALL pieces to this peer, use load balancing to distribute // pieces across all available peers and rebalance from overloaded peers var assigned: usize = 0; for (available_pieces) |piece_idx| { const result = dm.requestPieceWithLoadBalancing(piece_idx, peer_id) catch |err| { if (err != error.InvalidData) { std.log.debug("Piece {} request deferred: {}", .{ piece_idx, err }); } continue; }; if (result) { assigned += 1; } } // Log the peer's load after assignment const peer_load = dm.getPendingCountForPeer(peer_id); if (peer_load > 0) { std.log.info("PERF: Assigned {} pieces to new peer (peer now has {} pending)", .{ assigned, peer_load }); } // RECONNECT FIX: Check for any stuck pieces this peer can help with // This handles the case where a peer disconnected and reconnected - // pieces that were in-flight when they disconnected may be stuck const requeued = self.requeueStuckPiecesForPeer(dm, peer_id); if (requeued > 0) { std.log.info("RECONNECT: Re-queued {} stuck pieces for peer in session {}", .{ requeued, session.session_id }); } } } std.log.debug("handleBitfield: found {} sessions, {} download managers, {} matched piece_count", .{ session_count, download_session_count, matched_session_count }); } /// Handle have message - peer announcing they have a new piece (THREAD-SAFE) pub fn handleHave(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { // Parse have message to get content_hash and piece_index // CASCADE FIX: Now extracts content_hash for proper file identification const parsed = transfer_mod.TransferMessage.parseHave(payload) orelse { std.log.warn("Failed to parse have message", .{}); return Error.InvalidData; }; std.log.debug("Peer has piece {} for content {x}", .{ parsed.piece_index, parsed.content_hash[0..8].* }); // Find the specific session by content_hash and update peer availability self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.findSessionByHashUnsafe(parsed.content_hash) orelse { // Session not found - peer is advertising a file we're not downloading return; }; if (session.download_manager) |*dm| { dm.updatePeerAvailability(&peer_id, parsed.piece_index, true) catch |err| { std.log.warn("Failed to update peer availability: {}", .{err}); return; }; // CASCADE PERF: If we need this piece and don't have it yet, immediately request it // This accelerates cascade distribution by not waiting for the next processSessions cycle if (dm.selector.availability_map.get(parsed.piece_index)) |piece_info| { if (!piece_info.is_downloaded and !piece_info.is_verified) { // Check if we're already downloading this piece if (!dm.active_downloads.contains(parsed.piece_index)) { dm.requestPiece(parsed.piece_index, .normal, &peer_id) catch |err| { std.log.debug("CASCADE: Immediate piece request failed: {}", .{err}); }; } } } // RECONNECT FIX: A "have" message means peer is online // Check for other stuck pieces this peer can help with const requeued = self.requeueStuckPiecesForPeer(dm, peer_id); if (requeued > 0) { std.log.info("RECONNECT: Have message triggered re-queue of {} stuck pieces", .{requeued}); } } } /// Handle peer disconnect - immediately cancel all requests to this peer /// CASCADE PERF: Critical for fast failover when peers go offline /// FAIR QUEUE: Cleans both request and response queues, releases tracker slots pub fn handlePeerDisconnect(self: *FileSharingManager, peer_id: [32]u8) void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var sessions_updated: usize = 0; var messages_removed: usize = 0; var slots_released: usize = 0; var iter = self.sessions.valueIterator(); while (iter.next()) |session| { if (session.download_manager) |*dm| { dm.removePeer(&peer_id); sessions_updated += 1; } // FAIR QUEUE: Clean request queue for this peer var pending_req = &session.transfer_protocol.pending_requests; var i: usize = 0; while (i < pending_req.items.len) { const msg = pending_req.items[i]; if (msg.peer_id.len >= 32 and std.mem.eql(u8, msg.peer_id[0..32], &peer_id)) { if (msg.data.len > 0) self.allocator.free(msg.data); if (msg.peer_id.len > 0) self.allocator.free(msg.peer_id); _ = pending_req.orderedRemove(i); messages_removed += 1; } else { i += 1; } } // FAIR QUEUE: Clean response queue AND release tracker slots var pending_resp = &session.transfer_protocol.pending_responses; i = 0; while (i < pending_resp.items.len) { const msg = pending_resp.items[i]; if (msg.peer_id.len >= 32 and std.mem.eql(u8, msg.peer_id[0..32], &peer_id)) { // Release slot for piece_data messages if (msg.message_type == .piece_data) { if (session.response_tracker) |*tracker| { tracker.releaseSlot(peer_id, msg.data.len); slots_released += 1; } } if (msg.data.len > 0) self.allocator.free(msg.data); if (msg.peer_id.len > 0) self.allocator.free(msg.peer_id); _ = pending_resp.orderedRemove(i); messages_removed += 1; } else { i += 1; } } // Remove tracker entry entirely for this peer if (session.response_tracker) |*tracker| { _ = tracker.removePeer(peer_id); } } if (sessions_updated > 0 or messages_removed > 0 or slots_released > 0) { std.log.info("FAIR QUEUE: Peer disconnect handled, updated {} sessions, removed {} queued messages, released {} slots", .{ sessions_updated, messages_removed, slots_released }); } } /// Handle peer reconnect - re-trigger requests for missing pieces (THREAD-SAFE) /// Called when a peer reconnects (detected via bitfield/have message from known peer) /// Per BitTorrent best practices: immediately re-request pieces we need from reconnected peer pub fn handlePeerReconnect(self: *FileSharingManager, peer_id: [32]u8) void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var pieces_requeued: usize = 0; var iter = self.sessions.valueIterator(); while (iter.next()) |session| { if (session.download_manager) |*dm| { pieces_requeued += self.requeueStuckPiecesForPeer(dm, peer_id); } } if (pieces_requeued > 0) { std.log.info("RECONNECT: Peer reconnected, re-queued {} stuck pieces for immediate retry", .{pieces_requeued}); } } /// Re-queue stuck pieces for a specific peer in a specific download manager /// Returns number of pieces re-queued /// Note: Caller must hold sessions_mutex, this function acquires manager_mutex fn requeueStuckPiecesForPeer(self: *FileSharingManager, dm: *download_mod.DownloadManager, peer_id: [32]u8) usize { _ = self; dm.manager_mutex.lock(); defer dm.manager_mutex.unlock(); var pieces_requeued: usize = 0; // Find pieces we need that this peer has var selector_iter = dm.selector.availability_map.iterator(); while (selector_iter.next()) |entry| { const piece_index = entry.key_ptr.*; const piece_info = entry.value_ptr; // Skip already verified pieces if (piece_info.is_verified) continue; // Check if this peer has the piece if (!dm.peer_piece_map.peerHasPiece(peer_id, piece_index)) continue; // Check if piece is stuck (not in active downloads and not in pending) if (dm.active_downloads.contains(piece_index)) continue; var in_pending = false; for (dm.pending_requests.items) |pending| { if (pending.piece_index == piece_index) { in_pending = true; break; } } if (in_pending) continue; // Clear any retry tracker for this piece (fresh start with reconnected peer) if (dm.retry_trackers.getPtr(piece_index)) |tracker| { tracker.reset(); } // Re-queue piece for download from reconnected peer dm.pending_requests.insert(dm.allocator, 0, download_mod.DownloadRequest{ .piece_index = piece_index, .peer_id = peer_id, .offset = 0, .length = @intCast(dm.piece_size), .priority = .high, .requested_at = std.time.timestamp(), }) catch continue; pieces_requeued += 1; } return pieces_requeued; } /// Handle metadata response - peer sending file metadata (THREAD-SAFE) pub fn handleMetadataResponse(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { // Parse metadata from response const metadata = transfer_mod.TransferMessage.parseMetadataResponse(payload, self.allocator) catch |err| { std.log.err("Failed to parse metadata response: {}", .{err}); return err; }; errdefer { self.allocator.free(metadata.name); self.allocator.free(metadata.piece_hashes); } std.log.info("Received metadata for file: {s} ({d} bytes, {d} pieces)", .{ metadata.name, metadata.size, metadata.piece_count, }); // Find an existing download session that's waiting for this metadata // or create a new one self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); // PERF FIX: Compute proper content_hash using metadataHash once // Old code used first piece hash which was incorrect const content_hash = try HashUtils.metadataHash(metadata); // Check if session already exists if (self.findSessionByHashUnsafe(content_hash)) |existing| { // Update existing session with new metadata if needed if (existing.download_manager == null) { const piece_size: u64 = if (metadata.piece_count > 0) (metadata.size + metadata.piece_count - 1) / metadata.piece_count else self.config.piece_size; existing.download_manager = download_mod.DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, piece_size, self.allocator, ) catch |err| { std.log.err("Failed to create download manager: {}", .{err}); return err; }; } return; } // Create new download session with the received metadata // Limit check if (self.sessions.count() >= self.config.max_concurrent_downloads + self.config.max_concurrent_uploads) { std.log.warn("Session limit reached, cannot create session for received metadata", .{}); return Error.PoolExhausted; } // content_hash already computed above for session lookup - reuse it var session = FileSharingSession{ .session_id = std.crypto.random.int(u64), .file_metadata = metadata, .content_hash = content_hash, .download_manager = null, .upload_manager = null, .status = .ready, .transfer_protocol = transfer_mod.TransferProtocol.init(self.allocator), .piece_pool = PiecePool.init(self.allocator), .created_at = std.time.timestamp(), .updated_at = std.time.timestamp(), .allocator = self.allocator, .response_tracker = null, // Download sessions don't need response tracking .pending_piece_responses = .{}, // ZERO-COPY: Initialize empty }; // Initialize download manager const piece_size: u64 = if (metadata.piece_count > 0) (metadata.size + metadata.piece_count - 1) / metadata.piece_count else self.config.piece_size; session.download_manager = download_mod.DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, piece_size, self.allocator, ) catch |err| { std.log.err("Failed to create download manager: {}", .{err}); return err; }; // Store session self.sessions.put(session.session_id, session) catch |err| { std.log.err("Failed to store session: {}", .{err}); if (session.download_manager) |*dm| { dm.deinit(); } return err; }; // Send bitfield to peer with our current pieces (none for new download) // This establishes the handshake _ = peer_id; // Would send empty bitfield here in full implementation std.log.info("Created download session for: {s}", .{metadata.name}); } /// Handle piece response - peer responding to our piece request (THREAD-SAFE) pub fn handlePieceResponse(self: *FileSharingManager, peer_id: [32]u8, payload: []const u8) Error!void { // Parse piece response: piece_index(4) + available(1) + request_id(4) if (payload.len < 9) return Error.InvalidData; const piece_index = std.mem.readInt(u32, payload[0..4], .big); const available = payload[4] == 1; const request_id = std.mem.readInt(u32, payload[5..9], .big); std.log.debug("Piece response: index={}, available={}, request_id={}", .{ piece_index, available, request_id }); if (!available) { // Peer doesn't have this piece return; } // Update peer availability and potentially send piece request self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var sessions_it = self.sessions.valueIterator(); while (sessions_it.next()) |session| { if (session.download_manager) |*dm| { // Update availability dm.updatePeerAvailability(&peer_id, piece_index, true) catch |err| { std.log.warn("Failed to update peer availability: {}", .{err}); continue; }; } } } /// Send bitfield message to peer announcing our available pieces pub fn sendBitfieldToPeer(self: *FileSharingManager, session_id: u64, peer_id: [32]u8) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse { return Error.FileError; }; // Build bitfield based on upload manager's available pieces if (session.upload_manager) |*um| { const piece_count = session.file_metadata.piece_count; // Get available pieces from upload manager var available_pieces: std.ArrayListUnmanaged(u32) = .{}; defer available_pieces.deinit(self.allocator); var piece_iter = um.available_pieces.keyIterator(); while (piece_iter.next()) |piece_idx| { available_pieces.append(self.allocator, piece_idx.*) catch continue; } // Create and send bitfield message var msg = transfer_mod.TransferMessage.bitfieldFromIndices( &peer_id, piece_count, available_pieces.items, self.allocator, ); defer msg.deinit(self.allocator); if (msg.message_type == .err) { return Error.OutOfMemory; } const serialized = msg.serialize(self.allocator) catch |err| { return err; }; defer self.allocator.free(serialized); // FIX: Add 0x01 file transfer app ID prefix const full_msg = self.allocator.alloc(u8, 1 + serialized.len) catch { return Error.OutOfMemory; }; defer self.allocator.free(full_msg); full_msg[0] = 0x01; // File transfer app ID @memcpy(full_msg[1..], serialized); // Send via network if (self.network_sender) |sender| { const success = sender.send_fn(&peer_id, full_msg, sender.context); self.stats_mutex.lock(); if (success) { self.messages_sent += 1; } else { self.messages_failed += 1; std.log.warn("Failed to send bitfield to peer", .{}); } self.stats_mutex.unlock(); } } } /// Send bitfield to a newly connected peer for all upload sessions /// This enables the peer to discover what pieces we have available for download pub fn sendBitfieldToNewPeer(self: *FileSharingManager, peer_id: [32]u8) Error!void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); var sessions_it = self.sessions.valueIterator(); while (sessions_it.next()) |session| { // Only send bitfield for sessions that have upload capability if (session.upload_manager) |*um| { const piece_count = session.file_metadata.piece_count; // Collect available pieces from upload manager var available_pieces: std.ArrayListUnmanaged(u32) = .{}; defer available_pieces.deinit(self.allocator); var piece_iter = um.available_pieces.keyIterator(); while (piece_iter.next()) |piece_idx| { available_pieces.append(self.allocator, piece_idx.*) catch continue; } if (available_pieces.items.len == 0) continue; // Create bitfield message var msg = transfer_mod.TransferMessage.bitfieldFromIndices( &peer_id, piece_count, available_pieces.items, self.allocator, ); defer msg.deinit(self.allocator); if (msg.message_type == .err) { std.log.warn("Failed to create bitfield message for new peer", .{}); continue; } // Serialize message with app ID prefix (0x01 for file transfer) const serialized = msg.serialize(self.allocator) catch |err| { std.log.warn("Failed to serialize bitfield message: {}", .{err}); continue; }; defer self.allocator.free(serialized); // Prepend app ID const full_msg = self.allocator.alloc(u8, 1 + serialized.len) catch { std.log.warn("Failed to allocate bitfield message buffer", .{}); continue; }; defer self.allocator.free(full_msg); full_msg[0] = 0x01; // File transfer app ID @memcpy(full_msg[1..], serialized); // Send via network if (self.network_sender) |sender| { const success = sender.send_fn(&peer_id, full_msg, sender.context); self.stats_mutex.lock(); if (success) { self.messages_sent += 1; self.stats_mutex.unlock(); std.log.info("Sent bitfield ({} pieces) to new peer", .{available_pieces.items.len}); } else { self.messages_failed += 1; self.stats_mutex.unlock(); std.log.warn("Failed to send bitfield to new peer", .{}); } } else { std.log.warn("No network sender configured - cannot send bitfield", .{}); } } } } /// Broadcast "have" message to all connected peers for a session /// CASCADE FIX: When we complete downloading a piece, announce it to all peers /// so they know they can now download it from us. This enables cascading distribution. pub fn broadcastHavePiece(self: *FileSharingManager, session_id: u64, piece_index: u32) void { // Get peers without holding session lock (to avoid deadlock) var peers_buffer: [64][32]u8 = undefined; var peer_count: usize = 0; var content_hash: [32]u8 = undefined; // CASCADE FIX: Get content_hash and peers // First, get content_hash from session (need lock) { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return; content_hash = session.content_hash; } // CASCADE FIX: Get ALL connected peers from the P2P layer, not just download peers. // This is critical for cascade distribution - we need to tell ALL connected peers // about new pieces, not just the seeders we're downloading from. if (self.network_sender) |sender| { peer_count = sender.getConnectedPeers(&peers_buffer); } if (peer_count == 0) { // Fallback to download manager peers if no get_peers_fn self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return; if (session.download_manager) |*dm| { peer_count = dm.getKnownPeers(&peers_buffer); } if (peer_count == 0) { std.log.debug("CASCADE: No peers available to broadcast 'have' for piece {}", .{piece_index}); return; } } // Create and send "have" message to each peer var sent_count: usize = 0; for (peers_buffer[0..peer_count]) |peer_id_bytes| { var msg = transfer_mod.TransferMessage.have(&peer_id_bytes, content_hash, piece_index, self.allocator); defer msg.deinit(self.allocator); if (msg.message_type == .err) continue; // Serialize message const serialized = msg.serialize(self.allocator) catch continue; defer self.allocator.free(serialized); // Prepend app ID (0x01 for file transfer) const full_msg = self.allocator.alloc(u8, 1 + serialized.len) catch continue; defer self.allocator.free(full_msg); full_msg[0] = 0x01; @memcpy(full_msg[1..], serialized); // Send via network if (self.network_sender) |sender| { const success = sender.send_fn(&peer_id_bytes, full_msg, sender.context); self.stats_mutex.lock(); if (success) { self.messages_sent += 1; sent_count += 1; } else { self.messages_failed += 1; } self.stats_mutex.unlock(); } } // Log only periodically to avoid spam (every 100 pieces) if (piece_index % 100 == 0) { std.log.debug("CASCADE: Broadcast 'have' for piece {} to {}/{} peers", .{ piece_index, sent_count, peer_count }); } std.log.debug("CASCADE: Broadcast 'have' for piece {} to {} peers", .{ piece_index, peer_count }); } /// CASCADE FIX: Broadcast full bitfield to all connected peers /// Called when a download completes to notify all peers we now have all pieces pub fn broadcastFullBitfield(self: *FileSharingManager, session_id: u64) void { // Get peers without holding session lock (to avoid deadlock) var peers_buffer: [64][32]u8 = undefined; var peer_count: usize = 0; var piece_count: u32 = 0; // ARCHITECTURAL FIX: Collect ACTUAL available pieces from upload_manager // instead of blindly assuming all pieces 0 to piece_count-1 are available. // This prevents advertising pieces that haven't been added to available_pieces yet. var all_pieces: std.ArrayListUnmanaged(u32) = .{}; defer all_pieces.deinit(self.allocator); // Get piece count and actual available pieces { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse return; piece_count = session.file_metadata.piece_count; // Query actual available pieces from upload_manager if (session.upload_manager) |*um| { um.manager_mutex.lock(); defer um.manager_mutex.unlock(); var iter = um.available_pieces.keyIterator(); while (iter.next()) |piece_index| { all_pieces.append(self.allocator, piece_index.*) catch continue; } } } // RACE FIX: If not all pieces are available yet, don't broadcast a partial bitfield. // Due to parallel piece processing, some pieces may still be in the pipeline. // The individual "have" messages for those pieces will handle cascade distribution. // Sending a partial bitfield claiming to be "complete" causes peers to think // we DON'T have the missing pieces, breaking cascade distribution. if (all_pieces.items.len == 0) { std.log.warn("CASCADE: broadcastFullBitfield called but no pieces in available_pieces", .{}); return; } if (all_pieces.items.len < piece_count) { std.log.warn("CASCADE: broadcastFullBitfield skipped - only {}/{} pieces available (pipeline race), relying on 'have' messages", .{ all_pieces.items.len, piece_count, }); return; } // Get all connected peers if (self.network_sender) |sender| { peer_count = sender.getConnectedPeers(&peers_buffer); } if (peer_count == 0) return; // Send bitfield to each peer for (peers_buffer[0..peer_count]) |peer_id| { var msg = transfer_mod.TransferMessage.bitfieldFromIndices( &peer_id, piece_count, all_pieces.items, self.allocator, ); defer msg.deinit(self.allocator); if (msg.message_type == .err) continue; const serialized = msg.serialize(self.allocator) catch continue; defer self.allocator.free(serialized); const full_msg = self.allocator.alloc(u8, 1 + serialized.len) catch continue; defer self.allocator.free(full_msg); full_msg[0] = 0x01; @memcpy(full_msg[1..], serialized); if (self.network_sender) |sender| { _ = sender.send_fn(&peer_id, full_msg, sender.context); } } std.log.info("CASCADE: Broadcast bitfield ({}/{} pieces available) to {} peers on completion", .{ all_pieces.items.len, piece_count, peer_count }); } /// Mark a piece as available for upload after we've downloaded it /// CASCADE FIX: When a download completes a piece, we can now serve it to others pub fn markPieceAvailableForUpload(self: *FileSharingManager, session_id: u64, piece_index: u32, piece_hash: [32]u8) void { self.sessions_mutex.lock(); defer self.sessions_mutex.unlock(); const session = self.sessions.getPtr(session_id) orelse { std.log.warn("CASCADE DEBUG: Session {} not found for piece {}", .{ session_id, piece_index }); return; }; // Add to upload manager if we have one if (session.upload_manager) |*um| { um.addAvailablePiece(piece_index, piece_hash) catch |err| { std.log.warn("Failed to add piece {} to upload manager: {}", .{ piece_index, err }); return; }; std.log.info("CASCADE: Piece {} now available for upload (session {})", .{ piece_index, session_id }); } else { std.log.warn("CASCADE DEBUG: No upload_manager for session {}", .{ session_id }); } } }; /// Session statistics pub const SessionStats = struct { session_id: u64, status: FileSharingSession.SessionStatus, progress: f32, file_size: u64, piece_count: u32, pieces_completed: u32, created_at: i64, updated_at: i64, /// Get session age in seconds pub fn getAge(self: SessionStats) i64 { return std.time.timestamp() - self.created_at; } /// Get time since last update pub fn getTimeSinceUpdate(self: SessionStats) i64 { return std.time.timestamp() - self.updated_at; } /// Get formatted status string pub fn getStatusString(self: SessionStats, allocator: mem.Allocator) Error![]u8 { const status_name = switch (self.status) { .initializing => "Initializing", .ready => "Ready", .downloading => "Downloading", .uploading => "Uploading", .completed => "Completed", .failed => "Failed", .cancelled => "Cancelled", }; const progress_str = try fmt.allocPrint(allocator, "{d:.1}%", .{ self.progress * 100 }); defer allocator.free(progress_str); return fmt.allocPrint(allocator, "{s} ({s})", .{ status_name, progress_str }); } }; /// File sharing statistics pub const FileSharingStats = struct { total_sessions: usize, active_sessions: usize, downloading_sessions: usize, uploading_sessions: usize, completed_sessions: usize, total_downloaded: u64, total_uploaded: u64, registered_files: usize, /// Number of messages successfully sent over network messages_sent: u64, /// Number of messages that failed to send messages_failed: u64, /// Get total data transferred pub fn getTotalTransferred(self: FileSharingStats) u64 { return self.total_downloaded + self.total_uploaded; } /// Get message success rate pub fn getMessageSuccessRate(self: FileSharingStats) f32 { const total = self.messages_sent + self.messages_failed; if (total == 0) return 1.0; return @as(f32, @floatFromInt(self.messages_sent)) / @as(f32, @floatFromInt(total)); } /// Get active session rate pub fn getActiveRate(self: FileSharingStats) f32 { if (self.total_sessions == 0) return 0.0; return @as(f32, @floatFromInt(self.active_sessions)) / @as(f32, @floatFromInt(self.total_sessions)); } /// Get completion rate pub fn getCompletionRate(self: FileSharingStats) f32 { if (self.total_sessions == 0) return 0.0; return @as(f32, @floatFromInt(self.completed_sessions)) / @as(f32, @floatFromInt(self.total_sessions)); } /// Format statistics as string pub fn formatString(self: FileSharingStats, allocator: mem.Allocator) Error![]u8 { const downloaded_mb = @as(f32, @floatFromInt(self.total_downloaded)) / (1024 * 1024); const uploaded_mb = @as(f32, @floatFromInt(self.total_uploaded)) / (1024 * 1024); return fmt.allocPrint( allocator, "Sessions: {d} active/{d} total | Download: {d:.1}MB | Upload: {d:.1}MB | Files: {d}", .{ self.active_sessions, self.total_sessions, downloaded_mb, uploaded_mb, self.registered_files, }, ); } }; /// PERF: Profiling statistics for performance analysis pub const ProfilingStats = struct { // Pipeline stats pipeline_tasks_queued: u64, pipeline_tasks_processed: u64, pipeline_tasks_failed: u64, pipeline_queue_full_count: u64, pipeline_current_queue_depth: usize, pipeline_worker_count: usize, pipeline_avg_queue_wait_ns: u64, // Verification pool stats verification_completed: u64, verification_failed: u64, verification_bytes_verified: u64, verification_pending: usize, // Buffer pool stats buffer_pool_total: usize, buffer_pool_available: usize, buffer_pool_in_use: usize, buffer_pool_hits: u64, buffer_pool_misses: u64, buffer_pool_fallbacks: u64, pub fn print(self: ProfilingStats) void { std.debug.print("\n=== PROFILING STATS ===\n", .{}); std.debug.print("\nPipeline:\n", .{}); std.debug.print(" Tasks: queued={}, processed={}, failed={}\n", .{ self.pipeline_tasks_queued, self.pipeline_tasks_processed, self.pipeline_tasks_failed, }); std.debug.print(" Queue: depth={}, full_count={}, workers={}\n", .{ self.pipeline_current_queue_depth, self.pipeline_queue_full_count, self.pipeline_worker_count, }); std.debug.print(" Avg queue wait: {d:.2} ms\n", .{ @as(f64, @floatFromInt(self.pipeline_avg_queue_wait_ns)) / 1_000_000.0, }); std.debug.print("\nVerification Pool:\n", .{}); std.debug.print(" Completed={}, failed={}, pending={}\n", .{ self.verification_completed, self.verification_failed, self.verification_pending, }); std.debug.print(" Bytes verified: {d:.1} MB\n", .{ @as(f64, @floatFromInt(self.verification_bytes_verified)) / (1024 * 1024), }); std.debug.print("\nBuffer Pool:\n", .{}); std.debug.print(" Buffers: total={}, in_use={}, available={}\n", .{ self.buffer_pool_total, self.buffer_pool_in_use, self.buffer_pool_available, }); const total_requests = self.buffer_pool_hits + self.buffer_pool_misses; const hit_rate = if (total_requests > 0) @as(f64, @floatFromInt(self.buffer_pool_hits)) / @as(f64, @floatFromInt(total_requests)) * 100.0 else 100.0; std.debug.print(" Hit rate: {d:.1}% (hits={}, misses={}, fallbacks={})\n", .{ hit_rate, self.buffer_pool_hits, self.buffer_pool_misses, self.buffer_pool_fallbacks, }); std.debug.print("========================\n", .{}); } }; /// File sharing events for monitoring pub const FileSharingEvent = struct { event_type: EventType, session_id: u64, timestamp: i64, data: []const u8, pub const EventType = enum(u8) { session_started = 1, session_completed = 2, session_failed = 3, piece_downloaded = 4, piece_uploaded = 5, bandwidth_limit_reached = 6, peer_connected = 7, peer_disconnected = 8, }; /// Create event pub fn create(event_type: EventType, session_id: u64, data: []const u8) FileSharingEvent { return FileSharingEvent{ .event_type = event_type, .session_id = session_id, .timestamp = std.time.timestamp(), .data = data, }; } }; // Testing functions test "file sharing configuration" { // Test default config const default_config = FileSharingConfig.default(); try testing.expectEqual(@as(u64, 1 * 1024 * 1024), default_config.piece_size); try testing.expectEqual(SelectionStrategy.rarest_first, default_config.selection_strategy); try testing.expect(default_config.enable_download); try testing.expect(default_config.enable_upload); // Test high performance config const hp_config = FileSharingConfig.high_performance(); try testing.expectEqual(@as(usize, 256), hp_config.max_concurrent_downloads); try testing.expectEqual(SelectionStrategy.balanced, hp_config.selection_strategy); // Test low bandwidth config const lb_config = FileSharingConfig.low_bandwidth(); try testing.expectEqual(@as(u64, 256 * 1024), lb_config.max_bandwidth_download); try testing.expectEqual(SelectionStrategy.sequential, lb_config.selection_strategy); } test "file sharing session creation" { const allocator = testing.allocator; const piece_hashes = try allocator.alloc(PieceHash, 2); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create("test.bin", 2048, piece_hashes, allocator); // Note: session.deinit() frees both piece_hashes and metadata.name const config = FileSharingConfig.default(); var session = try FileSharingSession.create(metadata, config, allocator); defer session.deinit(); // This frees piece_hashes and metadata.name try testing.expect(session.session_id != 0); try testing.expectEqual(FileSharingSession.SessionStatus.initializing, session.status); try testing.expectEqual(@as(f32, 0.0), session.getProgress()); try testing.expect(session.isActive()); // Test stats const stats = session.getStats(); try testing.expectEqual(session.session_id, stats.session_id); try testing.expectEqual(FileSharingSession.SessionStatus.initializing, stats.status); } test "file sharing manager basic operations" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Test initial stats const stats = manager.getStats(); try testing.expectEqual(@as(usize, 0), stats.total_sessions); try testing.expectEqual(@as(usize, 0), stats.active_sessions); try testing.expect(manager.isIdle()); // Test getting active sessions (should be empty) const active_sessions = try manager.getActiveSessions(); defer if (active_sessions.len > 0) manager.allocator.free(active_sessions); try testing.expectEqual(@as(usize, 0), active_sessions.len); } test "file sharing manager processing" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Process empty manager (should not crash) try manager.processSessions(); // Test stats after processing const stats = manager.getStats(); try testing.expectEqual(@as(usize, 0), stats.total_sessions); try testing.expectEqual(@as(u64, 0), stats.total_downloaded); try testing.expectEqual(@as(u64, 0), stats.total_uploaded); } test "session statistics formatting" { const allocator = testing.allocator; var stats = SessionStats{ .session_id = 12345, .status = .downloading, .progress = 0.65, .file_size = 1024 * 1024, .piece_count = 10, .pieces_completed = 6, .created_at = std.time.timestamp() - 3600, // 1 hour ago .updated_at = std.time.timestamp() - 300, // 5 minutes ago }; try testing.expectEqual(@as(i64, 3600), stats.getAge()); try testing.expectEqual(@as(i64, 300), stats.getTimeSinceUpdate()); const status_str = try stats.getStatusString(allocator); defer allocator.free(status_str); try testing.expect(std.mem.indexOf(u8, status_str, "Downloading") != null); try testing.expect(std.mem.indexOf(u8, status_str, "65") != null); } test "file sharing statistics formatting" { const allocator = testing.allocator; const stats = FileSharingStats{ .total_sessions = 5, .active_sessions = 3, .downloading_sessions = 2, .uploading_sessions = 1, .completed_sessions = 1, .total_downloaded = 1024 * 1024 * 5, // 5MB .total_uploaded = 1024 * 1024 * 3, // 3MB .registered_files = 2, .messages_sent = 100, .messages_failed = 5, }; try testing.expectEqual(@as(u64, 8 * 1024 * 1024), stats.getTotalTransferred()); try testing.expectEqual(@as(f32, 0.6), stats.getActiveRate()); try testing.expectEqual(@as(f32, 0.2), stats.getCompletionRate()); // Test message success rate (100 / 105 ≈ 0.952) const success_rate = stats.getMessageSuccessRate(); try testing.expect(success_rate > 0.95); try testing.expect(success_rate < 0.96); const stats_str = try stats.formatString(allocator); defer allocator.free(stats_str); try testing.expect(std.mem.indexOf(u8, stats_str, "3 active/5 total") != null); try testing.expect(std.mem.indexOf(u8, stats_str, "Files: 2") != null); } test "file sharing events" { const event = FileSharingEvent.create(.session_started, 12345, "Test session started"); try testing.expectEqual(FileSharingEvent.EventType.session_started, event.event_type); try testing.expectEqual(@as(u64, 12345), event.session_id); try testing.expect(event.timestamp > 0); try testing.expectEqualSlices(u8, "Test session started", event.data); } test "peer reputation tracking" { const peer_id: [32]u8 = [_]u8{1} ** 32; var reputation = PeerReputation.init(peer_id); // Initial state try testing.expectEqual(@as(u32, 0), reputation.bad_pieces); try testing.expectEqual(@as(u32, 0), reputation.good_pieces); try testing.expect(!reputation.isBlacklisted()); try testing.expectEqual(@as(f32, 0.5), reputation.getScore()); // Neutral for new peer // Record good pieces reputation.recordGoodPiece(); reputation.recordGoodPiece(); try testing.expectEqual(@as(u32, 2), reputation.good_pieces); try testing.expectEqual(@as(f32, 1.0), reputation.getScore()); // Record bad piece reputation.recordBadPiece(); try testing.expectEqual(@as(u32, 1), reputation.bad_pieces); const score = reputation.getScore(); try testing.expect(score > 0.6 and score < 0.7); // 2/3 ≈ 0.666 try testing.expect(!reputation.isBlacklisted()); // Record more bad pieces to trigger blacklist reputation.recordBadPiece(); reputation.recordBadPiece(); try testing.expectEqual(@as(u32, 3), reputation.bad_pieces); try testing.expect(reputation.isBlacklisted()); // Reset reputation reputation.reset(); try testing.expectEqual(@as(u32, 0), reputation.bad_pieces); try testing.expectEqual(@as(u32, 0), reputation.good_pieces); try testing.expect(!reputation.isBlacklisted()); } test "handlePieceData verifies hash and updates reputation" { const allocator = testing.allocator; // Get absolute path for current working directory for path security var cwd_buf: [std.fs.max_path_bytes]u8 = undefined; const cwd = std.fs.cwd().realpath(".", &cwd_buf) catch return; // Create config with current directory allowed for path security const allowed_dirs = [_][]const u8{cwd}; var config = FileSharingConfig.default(); config.allowed_share_directories = &allowed_dirs; // Use initForTesting for synchronous piece processing (no async pipeline) var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Create test file with known content - use absolute path const test_file = "test_piece_verify.bin"; const test_data = "This is test data for piece verification with proper hash checking"; // Write test file const file = std.fs.cwd().createFile(test_file, .{}) catch return; file.writeAll(test_data) catch return; file.close(); defer std.fs.cwd().deleteFile(test_file) catch {}; // Create file metadata with proper hash const chunker = FileChunker.init(config.piece_size, allocator); const metadata = try chunker.createMetadata(test_file); defer allocator.free(metadata.piece_hashes); defer allocator.free(metadata.name); // Pass metadata directly - downloadFile makes its own copies const output_file = "tests/test_data/test_download_output.bin"; const session_id = try manager.downloadFile(metadata, output_file); defer std.fs.cwd().deleteFile(output_file) catch {}; // Start download try manager.startSharing(session_id); // Create payload with correct hash const peer_id: [32]u8 = [_]u8{42} ** 32; const content_hash = try HashUtils.metadataHash(metadata); var payload: std.ArrayList(u8) = .{}; defer payload.deinit(allocator); try payload.appendSlice(allocator, &content_hash); const piece_index: u32 = 0; var piece_index_bytes: [4]u8 = undefined; std.mem.writeInt(u32, &piece_index_bytes, piece_index, .big); try payload.appendSlice(allocator, &piece_index_bytes); const offset: u32 = 0; var offset_bytes: [4]u8 = undefined; std.mem.writeInt(u32, &offset_bytes, offset, .big); try payload.appendSlice(allocator, &offset_bytes); try payload.appendSlice(allocator, test_data); // Handle piece data - should succeed with correct hash try manager.handlePieceData(peer_id, payload.items); // Verify reputation was updated positively const rep = manager.getPeerReputation(peer_id); try testing.expect(rep != null); try testing.expectEqual(@as(u32, 1), rep.?.good_pieces); try testing.expectEqual(@as(u32, 0), rep.?.bad_pieces); try testing.expect(!rep.?.isBlacklisted()); } test "handlePieceData rejects bad hash and blacklists peer" { const allocator = testing.allocator; // Get absolute path for current working directory for path security var cwd_buf: [std.fs.max_path_bytes]u8 = undefined; const cwd = std.fs.cwd().realpath(".", &cwd_buf) catch return; // Create config with current directory allowed for path security const allowed_dirs = [_][]const u8{cwd}; var config = FileSharingConfig.default(); config.allowed_share_directories = &allowed_dirs; // Use initForTesting for synchronous piece processing (no async pipeline) var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Create test file const test_file = "test_bad_hash.bin"; const test_data = "Original test data for hash mismatch testing"; const file = std.fs.cwd().createFile(test_file, .{}) catch return; file.writeAll(test_data) catch return; file.close(); defer std.fs.cwd().deleteFile(test_file) catch {}; // Create metadata with proper hash const chunker = FileChunker.init(config.piece_size, allocator); const metadata = try chunker.createMetadata(test_file); defer allocator.free(metadata.piece_hashes); defer allocator.free(metadata.name); // Pass metadata directly - downloadFile makes its own copies const output_file = "tests/test_data/test_bad_hash_output.bin"; const session_id = try manager.downloadFile(metadata, output_file); defer std.fs.cwd().deleteFile(output_file) catch {}; try manager.startSharing(session_id); const peer_id: [32]u8 = [_]u8{99} ** 32; const content_hash = try HashUtils.metadataHash(metadata); // Send bad data (different from original) multiple times to trigger blacklist var i: u32 = 0; while (i < 3) : (i += 1) { var payload: std.ArrayList(u8) = .{}; defer payload.deinit(allocator); try payload.appendSlice(allocator, &content_hash); var piece_index_bytes: [4]u8 = undefined; std.mem.writeInt(u32, &piece_index_bytes, 0, .big); try payload.appendSlice(allocator, &piece_index_bytes); var offset_bytes: [4]u8 = undefined; std.mem.writeInt(u32, &offset_bytes, 0, .big); try payload.appendSlice(allocator, &offset_bytes); const bad_data = "This is WRONG data that won't match the hash"; try payload.appendSlice(allocator, bad_data); // Should fail due to hash mismatch const result = manager.handlePieceData(peer_id, payload.items); try testing.expectError(Error.InvalidData, result); } // Verify peer is now blacklisted const rep = manager.getPeerReputation(peer_id); try testing.expect(rep != null); try testing.expectEqual(@as(u32, 3), rep.?.bad_pieces); try testing.expect(rep.?.isBlacklisted()); } test "blacklisted peer cannot send pieces" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{77} ** 32; // Manually blacklist peer manager.reputation_mutex.lock(); var rep = PeerReputation.init(peer_id); rep.bad_pieces = 3; rep.blacklisted_until = std.time.timestamp() + 1000; // Blacklisted for future try manager.peer_reputation.put(peer_id, rep); manager.reputation_mutex.unlock(); // Try to send piece data - should be rejected immediately const dummy_payload: [40]u8 = [_]u8{0} ** 40; const result = manager.handlePieceData(peer_id, &dummy_payload); try testing.expectError(Error.InvalidData, result); } // ============================================================================ // Mock-based Tests using initForTesting // ============================================================================ /// Mock network sender state for capturing sent messages const MockSenderState = struct { messages_sent: usize = 0, last_peer_id: ?[32]u8 = null, should_succeed: bool = true, allocator: mem.Allocator, sent_data: std.ArrayList([]u8) = .{}, fn init(allocator: mem.Allocator) MockSenderState { return MockSenderState{ .allocator = allocator, }; } fn deinit(self: *MockSenderState) void { for (self.sent_data.items) |data| { self.allocator.free(data); } self.sent_data.deinit(self.allocator); } }; /// Mock send function that captures sent messages fn mockSendCallback(peer_id: []const u8, data: []const u8, context: ?*anyopaque) bool { const state: *MockSenderState = @ptrCast(@alignCast(context.?)); state.messages_sent += 1; if (peer_id.len == 32) { state.last_peer_id = peer_id[0..32].*; } // Store a copy of the data if (state.should_succeed) { const data_copy = state.allocator.dupe(u8, data) catch return false; state.sent_data.append(state.allocator, data_copy) catch { state.allocator.free(data_copy); return false; }; } return state.should_succeed; } test "FileSharingManager: initForTesting creates light manager" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should have no thread pools try testing.expect(manager.verification_pool == null); try testing.expect(manager.piece_pipeline == null); // Should have empty collections try testing.expectEqual(@as(usize, 0), manager.sessions.count()); try testing.expectEqual(@as(usize, 0), manager.file_registry.count()); try testing.expectEqual(@as(usize, 0), manager.peer_reputation.count()); } test "FileSharingManager: setNetworkSender and clearNetworkSender" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); var mock_state = MockSenderState.init(allocator); defer mock_state.deinit(); var sender = NetworkSender.init(mockSendCallback, &mock_state, allocator); try testing.expect(manager.network_sender == null); manager.setNetworkSender(&sender); try testing.expect(manager.network_sender != null); manager.clearNetworkSender(); try testing.expect(manager.network_sender == null); } test "FileSharingManager: getConfig returns current config" { const allocator = testing.allocator; var config = FileSharingConfig.default(); config.max_concurrent_downloads = 5; config.max_concurrent_uploads = 3; var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const retrieved = manager.getConfig(); try testing.expectEqual(@as(usize, 5), retrieved.max_concurrent_downloads); try testing.expectEqual(@as(usize, 3), retrieved.max_concurrent_uploads); } test "FileSharingManager: updateBandwidthLimits changes config" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const new_download: u64 = 5 * 1024 * 1024; // 5MB/s const new_upload: u64 = 2 * 1024 * 1024; // 2MB/s manager.updateBandwidthLimits(new_download, new_upload); const updated = manager.getConfig(); try testing.expectEqual(new_download, updated.max_bandwidth_download); try testing.expectEqual(new_upload, updated.max_bandwidth_upload); } test "FileSharingManager: setSelectionStrategy changes strategy" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expectEqual(SelectionStrategy.rarest_first, manager.getConfig().selection_strategy); manager.setSelectionStrategy(.sequential); try testing.expectEqual(SelectionStrategy.sequential, manager.getConfig().selection_strategy); manager.setSelectionStrategy(.random); try testing.expectEqual(SelectionStrategy.random, manager.getConfig().selection_strategy); } test "FileSharingManager: setFeatures enables/disables features" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Default should have both enabled var current = manager.getConfig(); try testing.expect(current.enable_download); try testing.expect(current.enable_upload); // Disable upload: setFeatures(enable_upload, enable_download) manager.setFeatures(false, true); current = manager.getConfig(); try testing.expect(current.enable_download); try testing.expect(!current.enable_upload); // Disable both manager.setFeatures(false, false); current = manager.getConfig(); try testing.expect(!current.enable_download); try testing.expect(!current.enable_upload); } test "FileSharingManager: getStats returns statistics" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const stats = manager.getStats(); try testing.expectEqual(@as(usize, 0), stats.active_sessions); try testing.expectEqual(@as(usize, 0), stats.downloading_sessions); try testing.expectEqual(@as(usize, 0), stats.uploading_sessions); try testing.expectEqual(@as(usize, 0), stats.registered_files); try testing.expectEqual(@as(u64, 0), stats.total_downloaded); try testing.expectEqual(@as(u64, 0), stats.total_uploaded); } test "FileSharingManager: empty manager has no active sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Empty manager should have no sessions const active = try manager.getActiveSessions(); defer if (active.len > 0) manager.allocator.free(active); try testing.expectEqual(@as(usize, 0), active.len); } test "FileSharingManager: getSessionInfo returns null for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expect(manager.getSessionInfo(12345) == null); try testing.expect(manager.getSessionInfo(0) == null); } test "FileSharingManager: hasSessionByHash returns false for unknown hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const unknown_hash = [_]u8{0xFF} ** 32; try testing.expect(!manager.hasSessionByHash(unknown_hash)); } test "PeerReputation: memory quota tracking" { var rep = PeerReputation.init([_]u8{1} ** 32); // Should be able to reserve memory try testing.expect(rep.reserveMemory(1024)); try testing.expectEqual(@as(u64, 1024), rep.memory_usage); try testing.expectEqual(@as(u32, 1), rep.pending_requests); // Reserve more try testing.expect(rep.reserveMemory(2048)); try testing.expectEqual(@as(u64, 3072), rep.memory_usage); try testing.expectEqual(@as(u32, 2), rep.pending_requests); // Release memory rep.releaseMemory(1024); try testing.expectEqual(@as(u64, 2048), rep.memory_usage); try testing.expectEqual(@as(u32, 1), rep.pending_requests); } test "PeerReputation: reset clears all state" { var rep = PeerReputation.init([_]u8{1} ** 32); rep.bad_pieces = 5; rep.good_pieces = 10; rep.blacklisted_until = std.time.timestamp() + 1000; rep.reset(); try testing.expectEqual(@as(u32, 0), rep.bad_pieces); try testing.expectEqual(@as(u32, 0), rep.good_pieces); try testing.expectEqual(@as(i64, 0), rep.blacklisted_until); } test "PeerReputation: score calculation" { var rep = PeerReputation.init([_]u8{1} ** 32); // New peer should have neutral score try testing.expectEqual(@as(f32, 0.5), rep.getScore()); // All good pieces rep.good_pieces = 10; try testing.expectEqual(@as(f32, 1.0), rep.getScore()); // Mixed pieces rep.bad_pieces = 5; // 10 / 15 = 0.666... try testing.expect(rep.getScore() > 0.66); try testing.expect(rep.getScore() < 0.67); } test "PeerReputation: blacklist duration configuration" { // Save original value const original = PeerReputation.getBaseBlacklistDuration(); defer PeerReputation.setBaseBlacklistDuration(original); // Set new duration PeerReputation.setBaseBlacklistDuration(600); try testing.expectEqual(@as(i64, 600), PeerReputation.getBaseBlacklistDuration()); // Invalid values should be ignored PeerReputation.setBaseBlacklistDuration(0); try testing.expectEqual(@as(i64, 600), PeerReputation.getBaseBlacklistDuration()); PeerReputation.setBaseBlacklistDuration(-100); try testing.expectEqual(@as(i64, 600), PeerReputation.getBaseBlacklistDuration()); } test "NetworkSender: sendMessage with mock callback" { const allocator = testing.allocator; var mock_state = MockSenderState.init(allocator); defer mock_state.deinit(); var sender = NetworkSender.init(mockSendCallback, &mock_state, allocator); const peer_id: [32]u8 = [_]u8{42} ** 32; const msg = TransferMessage{ .message_type = .piece_request, .message_id = 1, .peer_id = &peer_id, .data = &[_]u8{}, .timestamp = std.time.timestamp(), }; const result = try sender.sendMessage(msg); try testing.expect(result == true); try testing.expectEqual(@as(usize, 1), mock_state.messages_sent); try testing.expectEqual(peer_id, mock_state.last_peer_id.?); } test "NetworkSender: sendMessage failure" { const allocator = testing.allocator; var mock_state = MockSenderState.init(allocator); defer mock_state.deinit(); mock_state.should_succeed = false; var sender = NetworkSender.init(mockSendCallback, &mock_state, allocator); const peer_id: [32]u8 = [_]u8{42} ** 32; const msg = TransferMessage{ .message_type = .piece_request, .message_id = 1, .peer_id = &peer_id, .data = &[_]u8{}, .timestamp = std.time.timestamp(), }; const result = try sender.sendMessage(msg); try testing.expect(result == false); try testing.expectEqual(@as(usize, 1), mock_state.messages_sent); } test "FileSharingConfig: presets" { const default_cfg = FileSharingConfig.default(); try testing.expect(default_cfg.enable_download); try testing.expect(default_cfg.enable_upload); // CASCADE PERF: high_performance now uses 256 concurrent transfers const high_perf = FileSharingConfig.high_performance(); try testing.expectEqual(@as(usize, 256), high_perf.max_concurrent_downloads); try testing.expectEqual(@as(usize, 256), high_perf.max_concurrent_uploads); const low_bw = FileSharingConfig.low_bandwidth(); try testing.expectEqual(@as(usize, 2), low_bw.max_concurrent_downloads); try testing.expectEqual(@as(usize, 2), low_bw.max_concurrent_uploads); } test "FileSharingSession: status transitions" { const metadata = FileMetadata{ .name = "", .size = 1024, .piece_count = 4, .piece_hashes = &[_]PieceHash{}, .created_at = std.time.timestamp(), .modified_at = std.time.timestamp(), }; var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); defer session.deinit(); try testing.expectEqual(FileSharingSession.SessionStatus.initializing, session.status); try testing.expect(session.isActive()); session.status = .completed; try testing.expect(!session.isActive()); session.status = .failed; try testing.expect(!session.isActive()); session.status = .cancelled; try testing.expect(!session.isActive()); } test "FileSharingSession: update timestamp" { const metadata = FileMetadata{ .name = "", .size = 1024, .piece_count = 4, .piece_hashes = &[_]PieceHash{}, .created_at = std.time.timestamp(), .modified_at = std.time.timestamp(), }; var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); defer session.deinit(); const initial_time = session.updated_at; std.Thread.sleep(10 * std.time.ns_per_ms); session.update(); try testing.expect(session.updated_at >= initial_time); } test "FileSharingLimits: accessor functions" { // Test that limit accessors return reasonable values try testing.expect(FileSharingLimits.maxPieceSize() > 0); try testing.expect(FileSharingLimits.maxFileSize() > 0); try testing.expect(FileSharingLimits.maxFilenameLength() > 0); try testing.expect(FileSharingLimits.maxSessions() > 0); try testing.expect(FileSharingLimits.maxPieceDataSize() > 0); try testing.expect(FileSharingLimits.maxPeerMemoryQuota() > 0); try testing.expect(FileSharingLimits.maxGlobalMemoryQuota() > 0); } test "FileSharingManager: getActiveSessions returns empty for no sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const sessions = try manager.getActiveSessions(); try testing.expectEqual(@as(usize, 0), sessions.len); } test "FileSharingManager: getSessionInfo handles invalid session ids" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expect(manager.getSessionInfo(12345) == null); try testing.expect(manager.getSessionInfo(0) == null); } test "FileSharingManager: hasSessionByHash returns false for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{99} ** 32; try testing.expect(!manager.hasSessionByHash(fake_hash)); } test "FileSharingManager: getSessionInfoByHash returns null for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{99} ** 32; try testing.expect(manager.getSessionInfoByHash(fake_hash) == null); } test "FileSharingManager: findSessionIdByHash returns null for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{99} ** 32; try testing.expect(manager.findSessionIdByHash(fake_hash) == null); } test "FileSharingManager: hasFile returns false for non-existent file" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: ContentHash = [_]u8{88} ** 32; try testing.expect(!manager.hasFile(fake_hash)); } test "FileSharingManager: getFileInfoByHash returns null for non-existent file" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: ContentHash = [_]u8{88} ** 32; try testing.expect(manager.getFileInfoByHash(fake_hash) == null); } test "FileSharingManager: removeFile for non-existent file is no-op" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // removeFile is now a silent no-op for non-existent files (idempotent) const fake_hash: ContentHash = [_]u8{88} ** 32; try manager.removeFile(fake_hash); // Should succeed (no error) } test "FileSharingManager: isIdle returns true when no sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expect(manager.isIdle()); } test "FileSharingManager: getPeerReputation returns null for unknown peer" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const unknown_peer: [32]u8 = [_]u8{55} ** 32; try testing.expect(manager.getPeerReputation(unknown_peer) == null); } test "FileSharingManager: startVerificationPool with no pool" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with null verification_pool try manager.startVerificationPool(); } test "FileSharingManager: stopVerificationPool with no pool" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with null verification_pool manager.stopVerificationPool(); } test "FileSharingManager: startPiecePipeline with no pipeline" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with null piece_pipeline try manager.startPiecePipeline(); } test "FileSharingManager: stopPiecePipeline with no pipeline" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with null piece_pipeline manager.stopPiecePipeline(); } test "FileSharingManager: processVerificationResults with no pool" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with null verification_pool manager.processVerificationResults(); } test "FileSharingManager: processSessions with no sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Should not crash with empty sessions try manager.processSessions(); } test "FileSharingManager: getProfilingStats" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const stats = manager.getProfilingStats(); try testing.expectEqual(@as(u64, 0), stats.pipeline_tasks_queued); try testing.expectEqual(@as(u64, 0), stats.pipeline_tasks_failed); } test "FileSharingManager: getFileMetadataBySessionId returns null for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const result = try manager.getFileMetadataBySessionId(12345, allocator); try testing.expect(result == null); } test "FileSharingManager: getFileMetadataByHash returns null for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{88} ** 32; const result = try manager.getFileMetadataByHash(fake_hash, allocator); try testing.expect(result == null); } test "FileSharingManager: checkAndCompleteDownloadByHash returns false for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{88} ** 32; try testing.expect(!manager.checkAndCompleteDownloadByHash(fake_hash)); } test "FileSharingManager: withSession fails for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const TestCallback = struct { fn callback(_: *FileSharingSession) Error!void {} }; try testing.expectError(Error.ConnectionNotFound, manager.withSession(12345, TestCallback.callback)); } test "FileSharingManager: stopSharing fails for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expectError(Error.ConnectionNotFound, manager.stopSharing(12345)); } test "FileSharingManager: startSharing fails for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); try testing.expectError(Error.ConnectionNotFound, manager.startSharing(12345)); } test "SessionStats: utility methods" { const stats = SessionStats{ .session_id = 12345, .status = FileSharingSession.SessionStatus.downloading, .progress = 0.5, .file_size = 1024, .piece_count = 4, .pieces_completed = 2, .created_at = std.time.timestamp() - 100, .updated_at = std.time.timestamp() - 50, }; // Test getAge const age = stats.getAge(); try testing.expect(age >= 100); // Test getTimeSinceUpdate const since_update = stats.getTimeSinceUpdate(); try testing.expect(since_update >= 50); } test "FileSharingStats: utility methods" { const stats = FileSharingStats{ .total_sessions = 10, .active_sessions = 5, .downloading_sessions = 3, .uploading_sessions = 2, .completed_sessions = 8, .total_downloaded = 1024 * 1024, .total_uploaded = 512 * 1024, .registered_files = 20, .messages_sent = 100, .messages_failed = 5, }; // Test getTotalTransferred try testing.expectEqual(@as(u64, 1536 * 1024), stats.getTotalTransferred()); // Test getMessageSuccessRate const msg_rate = stats.getMessageSuccessRate(); try testing.expect(msg_rate > 0.94); try testing.expect(msg_rate < 0.96); // Test getActiveRate const active_rate = stats.getActiveRate(); try testing.expect(active_rate == 0.5); // 5/10 = 0.5 // Test getCompletionRate const completion_rate = stats.getCompletionRate(); // 8 / 10 = 0.8 try testing.expect(completion_rate > 0.79); try testing.expect(completion_rate < 0.81); } test "PeerReputation: hasExceededMemoryQuota" { var rep = PeerReputation.init([_]u8{1} ** 32); // Initially should not exceed quota try testing.expect(!rep.hasExceededMemoryQuota()); // Set high memory usage rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA + 1; try testing.expect(rep.hasExceededMemoryQuota()); // Exactly at quota should not exceed rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA; try testing.expect(!rep.hasExceededMemoryQuota()); } test "PeerReputation: reserveMemory fails when over quota" { var rep = PeerReputation.init([_]u8{1} ** 32); // Reserve up to quota limit rep.memory_usage = FileSharingLimits.MAX_PEER_MEMORY_QUOTA - 100; // Should fail - would exceed quota try testing.expect(!rep.reserveMemory(200)); try testing.expectEqual(FileSharingLimits.MAX_PEER_MEMORY_QUOTA - 100, rep.memory_usage); } test "PeerReputation: reserveMemory fails when max pending requests reached" { var rep = PeerReputation.init([_]u8{1} ** 32); // Set pending requests to max rep.pending_requests = PeerReputation.MAX_PENDING_REQUESTS; // Should fail - max pending reached try testing.expect(!rep.reserveMemory(100)); } test "PeerReputation: releaseMemory handles underflow" { var rep = PeerReputation.init([_]u8{1} ** 32); // Set some memory usage rep.memory_usage = 100; rep.pending_requests = 1; // Release more than current usage rep.releaseMemory(200); // Should be clamped to 0 try testing.expectEqual(@as(u64, 0), rep.memory_usage); try testing.expectEqual(@as(u32, 0), rep.pending_requests); } test "PeerReputation: releaseMemory handles zero pending" { var rep = PeerReputation.init([_]u8{1} ** 32); rep.memory_usage = 100; rep.pending_requests = 0; rep.releaseMemory(50); try testing.expectEqual(@as(u64, 50), rep.memory_usage); try testing.expectEqual(@as(u32, 0), rep.pending_requests); } test "PeerReputation: exponential backoff blacklist" { var rep = PeerReputation.init([_]u8{1} ** 32); // First blacklist - base duration rep.bad_pieces = 2; rep.recordBadPiece(); // 3rd bad piece triggers blacklist try testing.expectEqual(@as(u32, 1), rep.blacklist_count); try testing.expect(rep.isBlacklisted()); // Reset and trigger again - should have longer duration rep.bad_pieces = 2; const first_until = rep.blacklisted_until; rep.recordBadPiece(); // 2nd blacklist try testing.expectEqual(@as(u32, 2), rep.blacklist_count); try testing.expect(rep.blacklisted_until > first_until); } test "handlePieceRequest: payload too short" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const short_payload: [10]u8 = [_]u8{0} ** 10; const result = manager.handlePieceRequest(peer_id, &short_payload); try testing.expectError(Error.InvalidData, result); } test "handleBatchPieceRequest: payload too short" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const short_payload: [10]u8 = [_]u8{0} ** 10; const result = manager.handleBatchPieceRequest(peer_id, &short_payload); try testing.expectError(Error.InvalidData, result); } test "handleBatchPieceRequest: zero piece count" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; var payload: [34]u8 = [_]u8{0} ** 34; // Set piece_count to 0 std.mem.writeInt(u16, payload[32..34], 0, .big); const result = manager.handleBatchPieceRequest(peer_id, &payload); try testing.expectError(Error.InvalidData, result); } test "handleBatchPieceRequest: too many pieces" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; var payload: [34]u8 = [_]u8{0} ** 34; // Set piece_count to 65 (exceeds max of 64) std.mem.writeInt(u16, payload[32..34], 65, .big); const result = manager.handleBatchPieceRequest(peer_id, &payload); try testing.expectError(Error.InvalidData, result); } test "handlePieceData: payload too short" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const short_payload: [10]u8 = [_]u8{0} ** 10; const result = manager.handlePieceData(peer_id, &short_payload); try testing.expectError(Error.InvalidData, result); } test "findPeersWithFile: no network sender" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const fake_hash: [32]u8 = [_]u8{99} ** 32; const result = manager.findPeersWithFile(fake_hash); try testing.expectError(Error.InvalidState, result); } test "withSessionByHash: error for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const TestCallback = struct { fn callback(_: *FileSharingSession) Error!void {} }; const fake_hash: [32]u8 = [_]u8{99} ** 32; try testing.expectError(Error.FileError, manager.withSessionByHash(fake_hash, TestCallback.callback)); } test "withSessionByHashResult: null for non-existent hash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const TestCallback = struct { fn callback(_: *FileSharingSession) ?u64 { return 12345; } }; const fake_hash: [32]u8 = [_]u8{99} ** 32; try testing.expect(manager.withSessionByHashResult(fake_hash, u64, TestCallback.callback) == null); } test "withSessionResult: null for non-existent session" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const TestCallback = struct { fn callback(_: *FileSharingSession) u64 { return 12345; } }; try testing.expect(manager.withSessionResult(99999, u64, TestCallback.callback) == null); } test "updatePeerReputation: good piece" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; // Update with good piece manager.updatePeerReputation(peer_id, true); const rep = manager.getPeerReputation(peer_id); try testing.expect(rep != null); try testing.expectEqual(@as(u32, 1), rep.?.good_pieces); try testing.expectEqual(@as(u32, 0), rep.?.bad_pieces); } test "updatePeerReputation: bad piece" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; // Update with bad piece manager.updatePeerReputation(peer_id, false); const rep = manager.getPeerReputation(peer_id); try testing.expect(rep != null); try testing.expectEqual(@as(u32, 0), rep.?.good_pieces); try testing.expectEqual(@as(u32, 1), rep.?.bad_pieces); } test "FileSharingLimits: compile-time constants" { // Verify compile-time constants match the static values try testing.expectEqual(@as(u64, 64 * 1024 * 1024), FileSharingLimits.MAX_PIECE_SIZE); try testing.expectEqual(@as(u64, 10 * 1024 * 1024 * 1024), FileSharingLimits.MAX_FILE_SIZE); try testing.expectEqual(@as(usize, 255), FileSharingLimits.MAX_FILENAME_LENGTH); try testing.expectEqual(@as(usize, 1000), FileSharingLimits.MAX_SESSIONS); try testing.expectEqual(@as(usize, 32 * 1024 * 1024), FileSharingLimits.MAX_PIECE_DATA_SIZE); try testing.expectEqual(@as(u64, 128 * 1024 * 1024), FileSharingLimits.MAX_PEER_MEMORY_QUOTA); try testing.expectEqual(@as(u64, 2 * 1024 * 1024 * 1024), FileSharingLimits.MAX_GLOBAL_MEMORY_QUOTA); } test "PeerReputation: runtime limit accessors" { // Verify runtime accessors return values > 0 try testing.expect(PeerReputation.maxBadPieces() > 0); try testing.expect(PeerReputation.baseBlacklistDuration() > 0); try testing.expect(PeerReputation.maxBlacklistDuration() > 0); try testing.expect(PeerReputation.maxRequestsPerPeer() > 0); } test "FileSharingStats: zero sessions edge cases" { const stats = FileSharingStats{ .total_sessions = 0, .active_sessions = 0, .downloading_sessions = 0, .uploading_sessions = 0, .completed_sessions = 0, .total_downloaded = 0, .total_uploaded = 0, .registered_files = 0, .messages_sent = 0, .messages_failed = 0, }; // Should handle zero case without division by zero try testing.expectEqual(@as(u64, 0), stats.getTotalTransferred()); try testing.expectEqual(@as(f32, 1.0), stats.getMessageSuccessRate()); // 0/0 = 1.0 try testing.expectEqual(@as(f32, 0.0), stats.getActiveRate()); // 0 active try testing.expectEqual(@as(f32, 0.0), stats.getCompletionRate()); // 0/0 = 0.0 } test "ProfilingStats: all fields accessible" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const stats = manager.getProfilingStats(); // All pipeline stats should be 0 with null pipeline try testing.expectEqual(@as(u64, 0), stats.pipeline_tasks_queued); try testing.expectEqual(@as(u64, 0), stats.pipeline_tasks_processed); try testing.expectEqual(@as(u64, 0), stats.pipeline_tasks_failed); try testing.expectEqual(@as(u64, 0), stats.pipeline_queue_full_count); try testing.expectEqual(@as(usize, 0), stats.pipeline_current_queue_depth); try testing.expectEqual(@as(u32, 0), stats.pipeline_worker_count); try testing.expectEqual(@as(u64, 0), stats.pipeline_avg_queue_wait_ns); // Verification stats should be 0 with null pool try testing.expectEqual(@as(u64, 0), stats.verification_completed); try testing.expectEqual(@as(u64, 0), stats.verification_failed); try testing.expectEqual(@as(u64, 0), stats.verification_bytes_verified); try testing.expectEqual(@as(usize, 0), stats.verification_pending); // Buffer pool stats should be 0 with null pool try testing.expectEqual(@as(usize, 0), stats.buffer_pool_total); try testing.expectEqual(@as(usize, 0), stats.buffer_pool_available); try testing.expectEqual(@as(usize, 0), stats.buffer_pool_in_use); try testing.expectEqual(@as(u64, 0), stats.buffer_pool_hits); try testing.expectEqual(@as(u64, 0), stats.buffer_pool_misses); try testing.expectEqual(@as(u64, 0), stats.buffer_pool_fallbacks); } test "FileInfoCopy: deinit frees memory" { const allocator = testing.allocator; // Create owned copies const path = try allocator.dupe(u8, "/test/path.txt"); const name = try allocator.dupe(u8, "path.txt"); var info = FileSharingManager.FileInfoCopy{ .size = 1024, .created_at = 0, .modified_at = 0, .path = path, .name = name, }; // Should free both path and name without leaking info.deinit(allocator); } test "NetworkSender: init creates valid sender" { const allocator = testing.allocator; var mock_state = MockSenderState.init(allocator); defer mock_state.deinit(); const sender = NetworkSender.init(mockSendCallback, &mock_state, allocator); try testing.expect(sender.send_fn == mockSendCallback); try testing.expect(sender.context == @as(?*anyopaque, @ptrCast(&mock_state))); try testing.expect(sender.allocator.ptr == allocator.ptr); } test "FileSharingEvent: all event types" { // Test creating events of each type const types = [_]FileSharingEvent.EventType{ .session_started, .session_completed, .session_failed, .piece_downloaded, .piece_uploaded, .bandwidth_limit_reached, .peer_connected, .peer_disconnected, }; for (types) |event_type| { const event = FileSharingEvent.create(event_type, 12345, "test"); try testing.expectEqual(event_type, event.event_type); try testing.expectEqual(@as(u64, 12345), event.session_id); try testing.expect(event.timestamp > 0); } } test "FileSharingSession: getProgress for completed session" { const allocator = testing.allocator; const piece_hashes = try allocator.alloc(PieceHash, 2); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create("test.bin", 2048, piece_hashes, allocator); const config = FileSharingConfig.default(); var session = try FileSharingSession.create(metadata, config, allocator); defer session.deinit(); // Frees both piece_hashes and metadata.name // Set to completed session.status = .completed; // Should return 1.0 for completed session try testing.expectEqual(@as(f32, 1.0), session.getProgress()); } test "FileSharingSession: getProgress for initializing session" { const allocator = testing.allocator; const piece_hashes = try allocator.alloc(PieceHash, 2); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create("test.bin", 2048, piece_hashes, allocator); const config = FileSharingConfig.default(); var session = try FileSharingSession.create(metadata, config, allocator); defer session.deinit(); // Frees both piece_hashes and metadata.name // Initializing status should return 0.0 try testing.expectEqual(@as(f32, 0.0), session.getProgress()); } test "FileSharingSession: getStats includes all fields" { const allocator = testing.allocator; const piece_hashes = try allocator.alloc(PieceHash, 4); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create("test.bin", 4096, piece_hashes, allocator); const config = FileSharingConfig.default(); var session = try FileSharingSession.create(metadata, config, allocator); defer session.deinit(); const stats = session.getStats(); try testing.expect(stats.session_id != 0); try testing.expectEqual(FileSharingSession.SessionStatus.initializing, stats.status); try testing.expectEqual(@as(u64, 4096), stats.file_size); try testing.expectEqual(@as(u32, 4), stats.piece_count); try testing.expect(stats.created_at > 0); try testing.expect(stats.updated_at > 0); } test "handleBitfield: empty bitfield returns error" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const empty_payload: []const u8 = &[_]u8{}; // Empty payload should fail parsing const result = manager.handleBitfield(peer_id, empty_payload); try testing.expectError(Error.InvalidData, result); } test "handleBitfield: with no sessions does not crash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; // Create a valid bitfield payload (4 byte piece count + bitfield) var payload: [6]u8 = undefined; std.mem.writeInt(u32, payload[0..4], 8, .big); // 8 pieces payload[4] = 0xFF; // First 8 bits set payload[5] = 0x00; // Padding // Should not crash even with no sessions try manager.handleBitfield(peer_id, &payload); } test "handleHave: invalid payload" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const short_payload: [2]u8 = [_]u8{ 0, 0 }; // Short payload should fail parsing const result = manager.handleHave(peer_id, &short_payload); try testing.expectError(Error.InvalidData, result); } test "handleHave: with no sessions does not crash" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; // Valid have payload: content_hash (32 bytes) + piece_index (4 bytes) = 36 bytes var payload: [36]u8 = undefined; @memcpy(payload[0..32], &([_]u8{0xAA} ** 32)); // content_hash std.mem.writeInt(u32, payload[32..36], 5, .big); // piece_index // Should not crash with no sessions - just returns without error try manager.handleHave(peer_id, &payload); } test "handlePieceResponse: invalid payload" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const short_payload: [5]u8 = [_]u8{ 0, 0, 0, 0, 0 }; // Too short payload should fail const result = manager.handlePieceResponse(peer_id, &short_payload); try testing.expectError(Error.InvalidData, result); } test "handlePieceResponse: with no sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; // Valid piece response: piece_index(4) + available(1) + request_id(4) var payload: [9]u8 = undefined; std.mem.writeInt(u32, payload[0..4], 5, .big); // piece 5 payload[4] = 1; // available std.mem.writeInt(u32, payload[5..9], 123, .big); // request_id // Should not crash with no sessions (returns early) try manager.handlePieceResponse(peer_id, &payload); } test "cleanupCompletedSessions: handles failed sessions" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); // Create a test session manually const piece_hashes = try allocator.alloc(PieceHash, 2); for (piece_hashes) |*hash| { hash.* = [_]u8{0} ** 32; } const metadata = try FileMetadata.create("test.bin", 2048, piece_hashes, allocator); const session = try FileSharingSession.create(metadata, config, allocator); // Store session const session_id = session.session_id; manager.sessions_mutex.lock(); try manager.sessions.put(session_id, session); manager.sessions_mutex.unlock(); try testing.expectEqual(@as(usize, 1), manager.sessions.count()); // Mark as failed manager.sessions_mutex.lock(); if (manager.sessions.getPtr(session_id)) |s| { s.status = .failed; } manager.sessions_mutex.unlock(); // Run cleanup manager.cleanupCompletedSessions(); // Should be removed (failed sessions removed immediately) try testing.expectEqual(@as(usize, 0), manager.sessions.count()); } test "getSessionUnsafe: returns null for non-existent" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); manager.sessions_mutex.lock(); const result = manager.getSessionUnsafe(99999); manager.sessions_mutex.unlock(); try testing.expect(result == null); } test "FileSharingManager.init: creates thread pools" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.init(config, allocator); defer manager.deinit(); // Full init should create thread pools try testing.expect(manager.verification_pool != null); try testing.expect(manager.piece_pipeline != null); } test "pipelineProcessPiece: called via context" { const allocator = testing.allocator; const config = FileSharingConfig.default(); var manager = try FileSharingManager.initForTesting(config, allocator); defer manager.deinit(); const peer_id: [32]u8 = [_]u8{42} ** 32; const content_hash: [32]u8 = [_]u8{0xFF} ** 32; // Call pipeline callback directly (for coverage) // Should return error since no session exists const result = FileSharingManager.pipelineProcessPiece( @ptrCast(&manager), peer_id, content_hash, 0, // piece_index 0, // offset "test data", ); try testing.expectError(Error.FileError, result); }