diff --git a/examples/interrupted_transfer_test.zig b/examples/interrupted_transfer_test.zig index 225a46c..ffef9d2 100644 --- a/examples/interrupted_transfer_test.zig +++ b/examples/interrupted_transfer_test.zig @@ -156,6 +156,7 @@ pub fn main() !void { resume_file, total_size, piece_size, + null, .rarest_first, ); diff --git a/examples/resume_test.zig b/examples/resume_test.zig index cdcc740..6397bd1 100644 --- a/examples/resume_test.zig +++ b/examples/resume_test.zig @@ -136,6 +136,7 @@ pub fn main() !void { resume_file, total_size, piece_size, + null, .rarest_first, ); @@ -175,6 +176,7 @@ pub fn main() !void { resume_file, total_size + 1024, // Wrong size piece_size, + null, .rarest_first, ); @@ -190,6 +192,7 @@ pub fn main() !void { "nonexistent_resume_file.resume", total_size, piece_size, + null, .rarest_first, ); diff --git a/src/files/download.zig b/src/files/download.zig index c4b33ad..d6c25e8 100644 --- a/src/files/download.zig +++ b/src/files/download.zig @@ -532,6 +532,8 @@ pub const DownloadManager = struct { endgame_initialized: bool = false, /// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates) endgame_broadcast_pending: bool = false, + /// Content hash of the file being downloaded (for resume state validation) + content_hash: [32]u8 = [_]u8{0} ** 32, pub fn init( total_size: u64, @@ -756,71 +758,77 @@ pub const DownloadManager = struct { /// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void { // Collect pieces to cancel (can't modify while iterating) - // Use 1024 to handle large downloads (1GB = 1024 pieces at 1MB each) - var to_cancel: [1024]u32 = undefined; - var cancel_count: usize = 0; + // Process in batches of 1024 to avoid heap allocation while handling any download size + var total_cancelled: usize = 0; + while (true) { + var to_cancel: [1024]u32 = undefined; + var cancel_count: usize = 0; - var iter = self.active_downloads.iterator(); - while (iter.next()) |entry| { - if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) { - if (cancel_count < to_cancel.len) { - to_cancel[cancel_count] = entry.key_ptr.*; - cancel_count += 1; - } - } - } - - // Move cancelled downloads back to pending queue - for (to_cancel[0..cancel_count]) |piece_index| { - _ = self.active_downloads.remove(piece_index); - - // SOCKET FIX: Release request tracker slot so new requests can be sent - self.request_tracker.recordCompletion(peer_id, piece_index); - - // DISCONNECT FIX: Clear retry tracker for this peer so piece can be - // immediately retried from another peer without counting against retry limit. - // Per BitTorrent best practices, peer disconnect should not penalize the piece. - if (self.retry_trackers.getPtr(piece_index)) |tracker| { - // Only reset if the last failure was from this peer - if (tracker.last_peer) |last| { - if (std.mem.eql(u8, &last, &peer_id)) { - tracker.reset(); + var iter = self.active_downloads.iterator(); + while (iter.next()) |entry| { + if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) { + if (cancel_count < to_cancel.len) { + to_cancel[cancel_count] = entry.key_ptr.*; + cancel_count += 1; } } } - // Check if already in pending queue - var already_pending = false; - for (self.pending_requests.items) |pending| { - if (pending.piece_index == piece_index) { - already_pending = true; - break; + if (cancel_count == 0) break; + total_cancelled += cancel_count; + + // Move cancelled downloads back to pending queue + for (to_cancel[0..cancel_count]) |piece_index| { + _ = self.active_downloads.remove(piece_index); + + // SOCKET FIX: Release request tracker slot so new requests can be sent + self.request_tracker.recordCompletion(peer_id, piece_index); + + // DISCONNECT FIX: Clear retry tracker for this peer so piece can be + // immediately retried from another peer without counting against retry limit. + // Per BitTorrent best practices, peer disconnect should not penalize the piece. + if (self.retry_trackers.getPtr(piece_index)) |tracker| { + // Only reset if the last failure was from this peer + if (tracker.last_peer) |last| { + if (std.mem.eql(u8, &last, &peer_id)) { + tracker.reset(); + } + } } - } - // Check if piece is already verified (might have completed from another peer) - var already_verified = false; - if (self.selector.availability_map.get(piece_index)) |info| { - already_verified = info.is_verified; - } + // Check if already in pending queue + var already_pending = false; + for (self.pending_requests.items) |pending| { + if (pending.piece_index == piece_index) { + already_pending = true; + break; + } + } - if (!already_pending and !already_verified) { - // Re-add to pending with priority (front of queue) - self.pending_requests.insert(self.allocator, 0, DownloadRequest{ - .piece_index = piece_index, - .peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests - .offset = 0, - .length = @intCast(self.piece_size), - .priority = .high, // Boost priority for retried pieces - .requested_at = std.time.timestamp(), - }) catch { - std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index}); - }; + // Check if piece is already verified (might have completed from another peer) + var already_verified = false; + if (self.selector.availability_map.get(piece_index)) |info| { + already_verified = info.is_verified; + } + + if (!already_pending and !already_verified) { + // Re-add to pending with priority (front of queue) + self.pending_requests.insert(self.allocator, 0, DownloadRequest{ + .piece_index = piece_index, + .peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests + .offset = 0, + .length = @intCast(self.piece_size), + .priority = .high, // Boost priority for retried pieces + .requested_at = std.time.timestamp(), + }) catch { + std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index}); + }; + } } } - if (cancel_count > 0) { - std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count}); + if (total_cancelled > 0) { + std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{total_cancelled}); } } @@ -2110,7 +2118,7 @@ pub const DownloadManager = struct { .piece_size = self.piece_size, .piece_count = self.state.piece_count, .completed_count = self.state.completed_pieces.load(.acquire), - .file_hash = [_]u8{0} ** 32, // TODO: Store actual file hash if available + .file_hash = self.content_hash, }; // Write header @@ -2152,6 +2160,7 @@ pub const DownloadManager = struct { resume_path: []const u8, expected_total_size: u64, expected_piece_size: u64, + expected_content_hash: ?[32]u8, strategy: SelectionStrategy, ) Error!?DownloadManager { // Validate path @@ -2197,6 +2206,17 @@ pub const DownloadManager = struct { return null; } + // Validate content hash if provided (non-zero hash in file must match) + if (expected_content_hash) |expected_hash| { + const zero_hash = [_]u8{0} ** 32; + if (!std.mem.eql(u8, &header.file_hash, &zero_hash)) { + if (!std.crypto.timing_safe.eql([32]u8, header.file_hash, expected_hash)) { + std.log.warn("Resume file content hash mismatch", .{}); + return null; + } + } + } + // Create download manager var manager = try DownloadManager.init( header.total_size, @@ -2206,6 +2226,7 @@ pub const DownloadManager = struct { allocator, ); errdefer manager.deinit(); + manager.content_hash = header.file_hash; // Read bitfield const bitfield_size = (header.piece_count + 7) / 8; diff --git a/src/files/manager.zig b/src/files/manager.zig index 95a49f0..c6c0d25 100644 --- a/src/files/manager.zig +++ b/src/files/manager.zig @@ -691,7 +691,13 @@ pub const PreSerializedPieceResponse = struct { // 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); + const total_data_len = 32 + 4 + 4 + data.len; + if (total_data_len > std.math.maxInt(u32)) { + // Piece data too large for u32 length field — return empty response + result.header_len = 0; + return result; + } + const data_len: u32 = @intCast(total_data_len); std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big); off += 4; @@ -933,6 +939,7 @@ pub const FileSharingSession = struct { allocator, ); + manager.content_hash = self.content_hash; try manager.setOutputFile(output_path); self.download_manager = manager; self.status = .ready; @@ -4567,7 +4574,7 @@ pub const FileSharingManager = struct { else self.config.piece_size; - existing.download_manager = download_mod.DownloadManager.init( + var dm = download_mod.DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, @@ -4577,6 +4584,8 @@ pub const FileSharingManager = struct { std.log.err("Failed to create download manager: {}", .{err}); return err; }; + dm.content_hash = existing.content_hash; + existing.download_manager = dm; } return; } @@ -4611,7 +4620,7 @@ pub const FileSharingManager = struct { else self.config.piece_size; - session.download_manager = download_mod.DownloadManager.init( + var new_dm = download_mod.DownloadManager.init( metadata.size, metadata.piece_count, .rarest_first, @@ -4621,12 +4630,14 @@ pub const FileSharingManager = struct { std.log.err("Failed to create download manager: {}", .{err}); return err; }; + new_dm.content_hash = session.content_hash; + session.download_manager = new_dm; // 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(); + if (session.download_manager) |*cleanup_dm| { + cleanup_dm.deinit(); } return err; };