fix files: resume state hash validation, download cancel batching, piece

response bounds
This commit is contained in:
2026-02-11 14:21:44 -03:00
parent 30bad26e67
commit 47f949e4cc
4 changed files with 96 additions and 60 deletions

View File

@@ -156,6 +156,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );

View File

@@ -136,6 +136,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );
@@ -175,6 +176,7 @@ pub fn main() !void {
resume_file, resume_file,
total_size + 1024, // Wrong size total_size + 1024, // Wrong size
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );
@@ -190,6 +192,7 @@ pub fn main() !void {
"nonexistent_resume_file.resume", "nonexistent_resume_file.resume",
total_size, total_size,
piece_size, piece_size,
null,
.rarest_first, .rarest_first,
); );

View File

@@ -532,6 +532,8 @@ pub const DownloadManager = struct {
endgame_initialized: bool = false, endgame_initialized: bool = false,
/// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates) /// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates)
endgame_broadcast_pending: bool = false, 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( pub fn init(
total_size: u64, total_size: u64,
@@ -756,7 +758,9 @@ pub const DownloadManager = struct {
/// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation /// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation
fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void { fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void {
// Collect pieces to cancel (can't modify while iterating) // Collect pieces to cancel (can't modify while iterating)
// Use 1024 to handle large downloads (1GB = 1024 pieces at 1MB each) // 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 to_cancel: [1024]u32 = undefined;
var cancel_count: usize = 0; var cancel_count: usize = 0;
@@ -770,6 +774,9 @@ pub const DownloadManager = struct {
} }
} }
if (cancel_count == 0) break;
total_cancelled += cancel_count;
// Move cancelled downloads back to pending queue // Move cancelled downloads back to pending queue
for (to_cancel[0..cancel_count]) |piece_index| { for (to_cancel[0..cancel_count]) |piece_index| {
_ = self.active_downloads.remove(piece_index); _ = self.active_downloads.remove(piece_index);
@@ -818,9 +825,10 @@ pub const DownloadManager = struct {
}; };
} }
} }
}
if (cancel_count > 0) { if (total_cancelled > 0) {
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count}); 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_size = self.piece_size,
.piece_count = self.state.piece_count, .piece_count = self.state.piece_count,
.completed_count = self.state.completed_pieces.load(.acquire), .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 // Write header
@@ -2152,6 +2160,7 @@ pub const DownloadManager = struct {
resume_path: []const u8, resume_path: []const u8,
expected_total_size: u64, expected_total_size: u64,
expected_piece_size: u64, expected_piece_size: u64,
expected_content_hash: ?[32]u8,
strategy: SelectionStrategy, strategy: SelectionStrategy,
) Error!?DownloadManager { ) Error!?DownloadManager {
// Validate path // Validate path
@@ -2197,6 +2206,17 @@ pub const DownloadManager = struct {
return null; 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 // Create download manager
var manager = try DownloadManager.init( var manager = try DownloadManager.init(
header.total_size, header.total_size,
@@ -2206,6 +2226,7 @@ pub const DownloadManager = struct {
allocator, allocator,
); );
errdefer manager.deinit(); errdefer manager.deinit();
manager.content_hash = header.file_hash;
// Read bitfield // Read bitfield
const bitfield_size = (header.piece_count + 7) / 8; const bitfield_size = (header.piece_count + 7) / 8;

View File

@@ -691,7 +691,13 @@ pub const PreSerializedPieceResponse = struct {
// Data length (4 bytes, big endian) // Data length (4 bytes, big endian)
// Data = [content_hash:32][piece_index:4][offset:4][piece_data:N] // 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); std.mem.writeInt(u32, result.header[off..][0..4], data_len, .big);
off += 4; off += 4;
@@ -933,6 +939,7 @@ pub const FileSharingSession = struct {
allocator, allocator,
); );
manager.content_hash = self.content_hash;
try manager.setOutputFile(output_path); try manager.setOutputFile(output_path);
self.download_manager = manager; self.download_manager = manager;
self.status = .ready; self.status = .ready;
@@ -4567,7 +4574,7 @@ pub const FileSharingManager = struct {
else else
self.config.piece_size; self.config.piece_size;
existing.download_manager = download_mod.DownloadManager.init( var dm = download_mod.DownloadManager.init(
metadata.size, metadata.size,
metadata.piece_count, metadata.piece_count,
.rarest_first, .rarest_first,
@@ -4577,6 +4584,8 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err}); std.log.err("Failed to create download manager: {}", .{err});
return err; return err;
}; };
dm.content_hash = existing.content_hash;
existing.download_manager = dm;
} }
return; return;
} }
@@ -4611,7 +4620,7 @@ pub const FileSharingManager = struct {
else else
self.config.piece_size; self.config.piece_size;
session.download_manager = download_mod.DownloadManager.init( var new_dm = download_mod.DownloadManager.init(
metadata.size, metadata.size,
metadata.piece_count, metadata.piece_count,
.rarest_first, .rarest_first,
@@ -4621,12 +4630,14 @@ pub const FileSharingManager = struct {
std.log.err("Failed to create download manager: {}", .{err}); std.log.err("Failed to create download manager: {}", .{err});
return err; return err;
}; };
new_dm.content_hash = session.content_hash;
session.download_manager = new_dm;
// Store session // Store session
self.sessions.put(session.session_id, session) catch |err| { self.sessions.put(session.session_id, session) catch |err| {
std.log.err("Failed to store session: {}", .{err}); std.log.err("Failed to store session: {}", .{err});
if (session.download_manager) |*dm| { if (session.download_manager) |*cleanup_dm| {
dm.deinit(); cleanup_dm.deinit();
} }
return err; return err;
}; };