1743 lines
64 KiB
Zig
1743 lines
64 KiB
Zig
//! File metadata, chunking, and verification
|
|
//!
|
|
//! This module handles file metadata, chunking files into pieces,
|
|
//! and provides file-level operations for the file sharing system.
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const mem = std.mem;
|
|
const fs = std.fs;
|
|
const fmt = std.fmt;
|
|
const builtin = @import("builtin");
|
|
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
const hash_mod = @import("hash.zig");
|
|
const PieceHash = hash_mod.PieceHash;
|
|
const HashUtils = hash_mod.HashUtils;
|
|
pub const FileMetadata = hash_mod.FileMetadata;
|
|
const path_security = @import("path_security.zig");
|
|
const PathValidator = path_security.PathValidator;
|
|
const PathSecurityError = path_security.PathSecurityError;
|
|
|
|
// Filesystem abstraction for testability
|
|
const filesystem = @import("filesystem.zig");
|
|
const FileSystem = filesystem.FileSystem;
|
|
const FSFile = filesystem.File;
|
|
|
|
// Note: Types are defined below and exported from this module
|
|
|
|
/// Default piece size for file chunking (1MB - must be under 2MB MAX_MESSAGE_SIZE)
|
|
/// MED-12 FIX: Now references centralized limits configuration
|
|
pub const DEFAULT_PIECE_SIZE: u64 = 1 * 1024 * 1024;
|
|
|
|
/// Get the configured default piece size at runtime
|
|
pub fn getDefaultPieceSize() u64 {
|
|
return core.limits.global.file.piece_size;
|
|
}
|
|
|
|
/// File type enumeration
|
|
pub const FileType = enum {
|
|
text,
|
|
image,
|
|
video,
|
|
audio,
|
|
archive,
|
|
binary,
|
|
|
|
pub fn isCompressed(self: FileType) bool {
|
|
return switch (self) {
|
|
.archive => true,
|
|
else => false,
|
|
};
|
|
}
|
|
|
|
pub fn description(self: FileType) []const u8 {
|
|
return switch (self) {
|
|
.text => "Text Document",
|
|
.image => "Image File",
|
|
.video => "Video File",
|
|
.audio => "Audio File",
|
|
.archive => "Archive File",
|
|
.binary => "Binary File",
|
|
};
|
|
}
|
|
};
|
|
|
|
/// File information structure
|
|
pub const FileInfo = struct {
|
|
path: []const u8,
|
|
name: []const u8,
|
|
size: u64,
|
|
created_at: i64,
|
|
modified_at: i64,
|
|
|
|
/// Create file info from filesystem
|
|
/// Allocates copies of both path and name - caller must call deinit() to free
|
|
pub fn fromPath(path: []const u8, allocator: mem.Allocator) Error!FileInfo {
|
|
// Validate path before opening
|
|
if (!path_security.PathValidator.isPathSafe(path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
var file = FileSystem.openFile(path, .{}) catch return Error.FileError;
|
|
defer file.close();
|
|
|
|
const stat = file.stat() catch return Error.FileError;
|
|
|
|
// Copy path to avoid dangling pointer
|
|
const path_copy = allocator.dupe(u8, path) catch return Error.OutOfMemory;
|
|
errdefer allocator.free(path_copy);
|
|
|
|
// Copy file name
|
|
const basename = std.fs.path.basename(path);
|
|
const name_copy = allocator.dupe(u8, basename) catch {
|
|
allocator.free(path_copy);
|
|
return Error.OutOfMemory;
|
|
};
|
|
|
|
// MED-1 FIX: Safe timestamp conversion with bounds check
|
|
const max_ts: i128 = std.math.maxInt(i64);
|
|
const min_ts: i128 = std.math.minInt(i64);
|
|
const safe_ctime: i64 = if (stat.ctime > max_ts) std.math.maxInt(i64) else if (stat.ctime < min_ts) std.math.minInt(i64) else @intCast(stat.ctime);
|
|
const safe_mtime: i64 = if (stat.mtime > max_ts) std.math.maxInt(i64) else if (stat.mtime < min_ts) std.math.minInt(i64) else @intCast(stat.mtime);
|
|
|
|
return FileInfo{
|
|
.path = path_copy,
|
|
.name = name_copy,
|
|
.size = stat.size,
|
|
.created_at = safe_ctime,
|
|
.modified_at = safe_mtime,
|
|
};
|
|
}
|
|
|
|
/// Get file extension
|
|
pub fn extension(self: FileInfo) []const u8 {
|
|
return std.fs.path.extension(self.name);
|
|
}
|
|
|
|
/// Get file size in human readable format
|
|
pub fn sizeString(self: FileInfo, allocator: mem.Allocator) Error![]u8 {
|
|
return FileUtils.formatSize(self.size, allocator);
|
|
}
|
|
|
|
/// Check if file is empty
|
|
pub fn isEmpty(self: FileInfo) bool {
|
|
return self.size == 0;
|
|
}
|
|
|
|
pub fn deinit(self: FileInfo, allocator: mem.Allocator) void {
|
|
allocator.free(self.path);
|
|
allocator.free(self.name);
|
|
}
|
|
};
|
|
|
|
/// File chunker for breaking files into pieces
|
|
pub const FileChunker = struct {
|
|
piece_size: u64,
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn init(piece_size: u64, allocator: mem.Allocator) FileChunker {
|
|
return FileChunker{
|
|
.piece_size = piece_size,
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
/// Initialize with variable chunk size strategy
|
|
pub fn initVariable(allocator: mem.Allocator) FileChunker {
|
|
// Start with larger chunks and reduce for last pieces
|
|
return FileChunker{
|
|
.piece_size = 32 * 1024 * 1024, // 32MB for variable size
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
/// Create file metadata by reading file and calculating hashes
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn createMetadata(self: FileChunker, file_path: []const u8) Error!FileMetadata {
|
|
// Validate path before any file operations
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
const file_info = try FileInfo.fromPath(file_path, self.allocator);
|
|
defer file_info.deinit(self.allocator);
|
|
|
|
// Calculate piece count with overflow checking
|
|
const piece_count_calc = std.math.divCeil(u64, file_info.size, self.piece_size) catch return Error.BufferOverflow;
|
|
if (piece_count_calc > std.math.maxInt(u32)) return Error.BufferOverflow;
|
|
const piece_count: u32 = @intCast(piece_count_calc);
|
|
|
|
// Allocate array for piece hashes
|
|
const piece_hashes = self.allocator.alloc(PieceHash, piece_count) catch return Error.OutOfMemory;
|
|
errdefer self.allocator.free(piece_hashes);
|
|
|
|
// Open file and read pieces using FileSystem abstraction
|
|
var file = FileSystem.openFile(file_path, .{}) catch return Error.FileError;
|
|
defer file.close();
|
|
|
|
var piece_index: u32 = 0;
|
|
var total_read: u64 = 0;
|
|
|
|
while (total_read < file_info.size and piece_index < piece_count) {
|
|
const remaining = file_info.size - total_read;
|
|
const current_piece_size = @min(self.piece_size, remaining);
|
|
|
|
// Read piece data
|
|
const piece_data = self.allocator.alloc(u8, current_piece_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(piece_data);
|
|
|
|
const bytes_read = file.read(piece_data) catch return Error.FileError;
|
|
if (bytes_read != current_piece_size) {
|
|
return Error.FileError;
|
|
}
|
|
|
|
// Calculate hash
|
|
piece_hashes[piece_index] = try HashUtils.sha256(piece_data);
|
|
|
|
total_read += current_piece_size;
|
|
piece_index += 1;
|
|
}
|
|
|
|
// Clone the name to avoid dangling pointer
|
|
const name_copy = try self.allocator.dupe(u8, file_info.name);
|
|
errdefer self.allocator.free(name_copy);
|
|
|
|
return FileMetadata{
|
|
.name = name_copy,
|
|
.size = file_info.size,
|
|
.piece_count = piece_count,
|
|
.piece_hashes = piece_hashes,
|
|
.created_at = file_info.created_at,
|
|
.modified_at = file_info.modified_at,
|
|
};
|
|
}
|
|
|
|
/// Read specific piece from file
|
|
pub fn readPiece(
|
|
self: FileChunker,
|
|
file_path: []const u8,
|
|
piece_index: u32,
|
|
piece_size: u64,
|
|
) Error![]u8 {
|
|
// Validate path before reading
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
std.log.warn("readPiece: path safety check failed for '{s}'", .{file_path});
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Open the file
|
|
const file = fs.cwd().openFile(file_path, .{}) catch |err| {
|
|
std.log.warn("readPiece: openFile failed for '{s}': {}", .{ file_path, err });
|
|
return Error.FileError;
|
|
};
|
|
defer file.close();
|
|
return self.readPieceInternal(file, piece_index, piece_size);
|
|
}
|
|
|
|
/// PERF FIX: Public method to read piece from an already-open file handle.
|
|
/// This avoids the overhead of opening/closing the file for every piece.
|
|
pub fn readPieceFromHandle(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 {
|
|
return self.readPieceInternal(file, piece_index, piece_size);
|
|
}
|
|
|
|
fn readPieceInternal(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 {
|
|
// OVERFLOW FIX: Use checked multiplication to prevent overflow
|
|
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
|
|
// THREAD SAFETY FIX: Use preadAll instead of seek+read to allow concurrent reads
|
|
// from the same file handle without race conditions on file position.
|
|
const piece_data = self.allocator.alloc(u8, piece_size) catch return Error.OutOfMemory;
|
|
const bytes_read = file.preadAll(piece_data, offset) catch |err| {
|
|
std.log.warn("readPiece: preadAll failed: {}", .{err});
|
|
self.allocator.free(piece_data);
|
|
return Error.FileError;
|
|
};
|
|
|
|
// For partial reads (e.g., last piece of file), resize and return what we got
|
|
if (bytes_read < piece_size) {
|
|
const result = self.allocator.realloc(piece_data, bytes_read) catch {
|
|
self.allocator.free(piece_data);
|
|
return Error.OutOfMemory;
|
|
};
|
|
return result;
|
|
}
|
|
|
|
return piece_data;
|
|
}
|
|
|
|
/// Write piece to file
|
|
pub fn writePiece(
|
|
self: FileChunker,
|
|
file_path: []const u8,
|
|
piece_index: u32,
|
|
piece_data: []const u8,
|
|
) Error!void {
|
|
const file = fs.cwd().openFile(file_path, .{
|
|
.mode = .write_only,
|
|
}) catch return Error.FileError;
|
|
defer file.close();
|
|
|
|
// OVERFLOW FIX: Use checked multiplication to prevent overflow
|
|
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
|
|
// Seek to piece position
|
|
file.seekTo(offset) catch return Error.FileError;
|
|
|
|
// Write piece data and verify all bytes written
|
|
const bytes_written = file.write(piece_data) catch return Error.FileError;
|
|
if (bytes_written != piece_data.len) {
|
|
return Error.FileError; // Partial write
|
|
}
|
|
}
|
|
|
|
/// Verify file integrity by checking all pieces
|
|
pub fn verifyFile(self: FileChunker, file_path: []const u8, metadata: FileMetadata) Error!bool {
|
|
for (0..metadata.piece_count) |i| {
|
|
const piece_index = @as(u32, @intCast(i));
|
|
const expected_hash = metadata.piece_hashes[i];
|
|
const piece_size = metadata.pieceSize(piece_index);
|
|
|
|
const piece_data = try self.readPiece(file_path, piece_index, piece_size);
|
|
defer self.allocator.free(piece_data);
|
|
|
|
const is_valid = try HashUtils.verify(piece_data, expected_hash);
|
|
if (!is_valid) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/// Calculate how many pieces a file should have
|
|
/// Returns null if piece count would overflow u32
|
|
pub fn calculatePieceCount(self: FileChunker, file_size: u64) ?u32 {
|
|
const piece_count_u64 = std.math.divCeil(u64, file_size, self.piece_size) catch return null;
|
|
if (piece_count_u64 > std.math.maxInt(u32)) return null;
|
|
return @intCast(piece_count_u64);
|
|
}
|
|
|
|
/// Calculate optimal piece count based on file size and memory constraints
|
|
pub fn calculateOptimalPieceCount(file_size: u64, max_memory: u64, _: mem.Allocator) Error!u32 {
|
|
const default_piece_size = DEFAULT_PIECE_SIZE;
|
|
const piece_count = std.math.divCeil(u64, file_size, default_piece_size) catch return Error.BufferOverflow;
|
|
|
|
// If file is small enough, use fewer, larger pieces
|
|
if (file_size <= max_memory) {
|
|
const count = @max(1, piece_count);
|
|
if (count > std.math.maxInt(u32)) return Error.BufferOverflow;
|
|
return @intCast(count);
|
|
}
|
|
|
|
// For large files, ensure we don't exceed memory limits
|
|
// Guard against division by zero
|
|
if (piece_count == 0) return 1;
|
|
const memory_based_piece_size = @min(default_piece_size, max_memory / piece_count);
|
|
if (memory_based_piece_size == 0) return Error.BufferOverflow;
|
|
const final_count = std.math.divCeil(u64, file_size, memory_based_piece_size) catch return Error.BufferOverflow;
|
|
if (final_count > std.math.maxInt(u32)) return Error.BufferOverflow;
|
|
return @intCast(final_count);
|
|
}
|
|
|
|
/// Get piece offset and size for a given piece index
|
|
pub fn getPieceInfo(self: FileChunker, file_size: u64, piece_index: u32) Error!PieceInfo {
|
|
// OVERFLOW FIX: Use checked multiplication to prevent overflow
|
|
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
|
|
// Validate offset doesn't exceed file size
|
|
if (offset > file_size) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
const remaining = file_size - offset;
|
|
const size = @min(self.piece_size, remaining);
|
|
|
|
return PieceInfo{
|
|
.offset = offset,
|
|
.size = size,
|
|
.index = piece_index,
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Information about a specific piece
|
|
pub const PieceInfo = struct {
|
|
offset: u64,
|
|
size: usize,
|
|
index: u32,
|
|
};
|
|
|
|
/// File operations utilities
|
|
pub const FileUtils = struct {
|
|
/// Format file size in human readable format
|
|
pub fn formatSize(size: u64, allocator: mem.Allocator) Error![]u8 {
|
|
const units = "BKMGTPE";
|
|
var size_copy = size;
|
|
var unit_index: usize = 0;
|
|
|
|
while (size_copy >= 1024 and unit_index < units.len - 1) {
|
|
size_copy /= 1024;
|
|
unit_index += 1;
|
|
}
|
|
|
|
return fmt.allocPrint(allocator, "{d}{c}", .{ size_copy, units[unit_index] });
|
|
}
|
|
|
|
/// Calculate SHA-256 hash of entire file
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn hashFile(file_path: []const u8, allocator: mem.Allocator) Error![32]u8 {
|
|
var file = FileSystem.openFile(file_path, .{}) catch return Error.FileError;
|
|
defer file.close();
|
|
|
|
var hasher = std.crypto.hash.sha2.Sha256.init(.{});
|
|
|
|
// Read file in chunks
|
|
const chunk_size = 64 * 1024; // 64KB chunks
|
|
const buffer = allocator.alloc(u8, chunk_size) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
while (true) {
|
|
const bytes_read = file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
hasher.update(buffer[0..bytes_read]);
|
|
}
|
|
|
|
var hash: [32]u8 = undefined;
|
|
hasher.final(&hash);
|
|
|
|
return hash;
|
|
}
|
|
|
|
/// Create directory if it doesn't exist
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn ensureDir(dir_path: []const u8) Error!void {
|
|
FileSystem.makePath(dir_path) catch return Error.FileError;
|
|
}
|
|
|
|
/// Check if file exists
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn fileExists(file_path: []const u8) bool {
|
|
return FileSystem.fileExists(file_path);
|
|
}
|
|
|
|
/// Get temporary file path for incomplete downloads
|
|
pub fn getTempPath(original_path: []const u8, allocator: mem.Allocator) Error![]u8 {
|
|
const ext = std.fs.path.extension(original_path);
|
|
const basename = std.fs.path.basename(original_path);
|
|
|
|
const temp_name = try fmt.allocPrint(allocator, "{s}.tmp{s}", .{ basename, ext });
|
|
return temp_name;
|
|
}
|
|
|
|
/// Atomically move file (if supported)
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn moveFile(source: []const u8, dest: []const u8) Error!void {
|
|
FileSystem.rename(source, dest) catch return Error.FileError;
|
|
}
|
|
|
|
/// Delete file
|
|
/// Uses FileSystem abstraction for testability with MockFS
|
|
pub fn deleteFile(file_path: []const u8) Error!void {
|
|
FileSystem.deleteFile(file_path) catch return Error.FileError;
|
|
}
|
|
|
|
/// Get file statistics
|
|
pub fn getFileStats(file_path: []const u8) Error!FileInfo {
|
|
return FileInfo.fromPath(file_path, std.heap.page_allocator);
|
|
}
|
|
|
|
/// Copy file with progress tracking
|
|
pub fn copyFileWithProgress(
|
|
source: []const u8,
|
|
dest: []const u8,
|
|
allocator: mem.Allocator,
|
|
progress_callback: *const fn (u64, u64) void,
|
|
) Error!void {
|
|
var reader = try FileReader.init(source, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
var writer = try FileWriter.init(dest, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
var total_copied: u64 = 0;
|
|
const source_stats = try getFileStats(source);
|
|
const total_size = source_stats.size;
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
try writer.writeAt(total_copied, buffer[0..bytes_read]);
|
|
total_copied += bytes_read;
|
|
progress_callback(total_copied, total_size);
|
|
}
|
|
|
|
try writer.flush();
|
|
}
|
|
|
|
/// Verify file integrity using metadata
|
|
pub fn verifyFileIntegrity(file_path: []const u8, metadata: FileMetadata) Error!bool {
|
|
const allocator = std.heap.page_allocator;
|
|
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
|
|
|
|
return chunker.verifyFile(file_path, metadata);
|
|
}
|
|
|
|
/// Create file backup
|
|
pub fn createBackup(file_path: []const u8, allocator: mem.Allocator) Error![]u8 {
|
|
const backup_path = try fmt.allocPrint(allocator, "{s}.backup", .{file_path});
|
|
|
|
var reader = try FileReader.init(file_path, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
var writer = try FileWriter.init(backup_path, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
var offset: u64 = 0;
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
try writer.writeAt(offset, buffer[0..bytes_read]);
|
|
offset += bytes_read;
|
|
}
|
|
|
|
try writer.flush();
|
|
|
|
return backup_path;
|
|
}
|
|
|
|
/// Calculate file checksum (MD5 for compatibility)
|
|
pub fn calculateChecksum(file_path: []const u8, allocator: mem.Allocator) Error![16]u8 {
|
|
var reader = try FileReader.init(file_path, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
var hasher = std.crypto.hash.Md5.init(.{});
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
hasher.update(buffer[0..bytes_read]);
|
|
}
|
|
|
|
var checksum: [16]u8 = undefined;
|
|
hasher.final(&checksum);
|
|
|
|
return checksum;
|
|
}
|
|
|
|
/// Check if file is complete based on metadata
|
|
pub fn isFileComplete(file_path: []const u8, metadata: FileMetadata) Error!bool {
|
|
const file_info = try getFileStats(file_path);
|
|
|
|
// Check basic file properties
|
|
if (file_info.size != metadata.size) {
|
|
return false;
|
|
}
|
|
|
|
// Verify integrity
|
|
return try verifyFileIntegrity(file_path, metadata);
|
|
}
|
|
|
|
/// Compression method enumeration
|
|
pub const CompressionMethod = enum {
|
|
none,
|
|
zstd,
|
|
lz4,
|
|
};
|
|
|
|
/// Compress file using specified compression method
|
|
pub fn compressFile(source: []const u8, compressed: []const u8, method: CompressionMethod, allocator: mem.Allocator) Error!void {
|
|
switch (method) {
|
|
.none => {
|
|
// Simple copy operation
|
|
var reader = try FileReader.init(source, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
var writer = try FileWriter.init(compressed, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
var offset: u64 = 0;
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
try writer.writeAt(offset, buffer[0..bytes_read]);
|
|
offset += bytes_read;
|
|
}
|
|
|
|
try writer.flush();
|
|
},
|
|
.zstd => {
|
|
// Use Zig's built-in zstd decompressor
|
|
// Note: Zig 0.15 has decompression but limited compression support
|
|
// For now, fall back to deflate (gzip) which has better support
|
|
std.log.info("Using deflate compression (zstd compression not fully available in Zig 0.15)", .{});
|
|
return compressFileDeflate(source, compressed, allocator);
|
|
},
|
|
.lz4 => {
|
|
// LZ4 is not in Zig stdlib, use deflate as fallback
|
|
std.log.info("Using deflate compression (lz4 not available in Zig stdlib)", .{});
|
|
return compressFileDeflate(source, compressed, allocator);
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Internal helper: compress file using store format with header
|
|
/// Note: Zig 0.15's flate.Compress is incomplete, so we use a simple store format
|
|
/// Format: [4-byte magic "ZP2P"] [4-byte original size LE] [raw data]
|
|
fn compressFileDeflate(source: []const u8, compressed: []const u8, allocator: mem.Allocator) Error!void {
|
|
var reader = try FileReader.init(source, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
// Read entire source file into memory
|
|
const source_size = reader.file.getEndPos() catch return Error.FileError;
|
|
const source_data = allocator.alloc(u8, source_size) catch return Error.OutOfMemory;
|
|
defer allocator.free(source_data);
|
|
|
|
const bytes_read = reader.file.readAll(source_data) catch return Error.FileError;
|
|
if (bytes_read != source_size) return Error.FileError;
|
|
|
|
// Write with simple header format
|
|
var writer_file = try FileWriter.init(compressed, allocator, null);
|
|
defer writer_file.deinit();
|
|
|
|
// Write magic header "ZP2P" to identify our format
|
|
const magic: [4]u8 = .{ 'Z', 'P', '2', 'P' };
|
|
try writer_file.writeAt(0, &magic);
|
|
|
|
// CRIT-2 FIX: Validate size fits in u32 before truncating
|
|
// Files larger than 4GB cannot be stored with this format
|
|
if (source_size > std.math.maxInt(u32)) {
|
|
std.log.err("CRIT-2: File size {d} exceeds maximum storable size (4GB)", .{source_size});
|
|
return Error.FileTooLarge;
|
|
}
|
|
|
|
// Write original size as 4-byte little-endian (safe after validation)
|
|
var size_bytes: [4]u8 = undefined;
|
|
std.mem.writeInt(u32, &size_bytes, @intCast(source_size), .little);
|
|
try writer_file.writeAt(4, &size_bytes);
|
|
|
|
// Write raw data
|
|
try writer_file.writeAt(8, source_data);
|
|
try writer_file.flush();
|
|
|
|
std.log.info("Stored {d} bytes with 8-byte header (total: {d} bytes)", .{
|
|
source_size,
|
|
source_size + 8,
|
|
});
|
|
}
|
|
|
|
/// Decompress file using specified compression method
|
|
pub fn decompressFile(compressed: []const u8, decompressed: []const u8, method: CompressionMethod, allocator: mem.Allocator) Error!void {
|
|
switch (method) {
|
|
.none => {
|
|
// Simple copy operation
|
|
var reader = try FileReader.init(compressed, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
var writer = try FileWriter.init(decompressed, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
var offset: u64 = 0;
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
try writer.writeAt(offset, buffer[0..bytes_read]);
|
|
offset += bytes_read;
|
|
}
|
|
|
|
try writer.flush();
|
|
},
|
|
.zstd, .lz4 => {
|
|
// Use deflate decompression for both zstd and lz4 fallback
|
|
std.log.info("Using deflate decompression", .{});
|
|
return decompressFileDeflate(compressed, decompressed, allocator);
|
|
},
|
|
}
|
|
}
|
|
|
|
/// Internal helper: decompress file using our store format
|
|
/// Format: [4-byte magic "ZP2P"] [4-byte original size LE] [raw data]
|
|
fn decompressFileDeflate(compressed: []const u8, decompressed: []const u8, allocator: mem.Allocator) Error!void {
|
|
var reader = try FileReader.init(compressed, allocator, 64 * 1024);
|
|
defer reader.deinit();
|
|
|
|
// Read header (8 bytes)
|
|
var header: [8]u8 = undefined;
|
|
const header_read = reader.file.read(&header) catch return Error.FileError;
|
|
if (header_read < 8) return Error.FileError;
|
|
|
|
// Verify magic header
|
|
const expected_magic: [4]u8 = .{ 'Z', 'P', '2', 'P' };
|
|
if (!std.mem.eql(u8, header[0..4], &expected_magic)) {
|
|
std.log.warn("Invalid compression header, attempting raw copy", .{});
|
|
// Fall back to raw copy if magic doesn't match
|
|
reader.file.seekTo(0) catch return Error.FileError;
|
|
|
|
var writer_file = try FileWriter.init(decompressed, allocator, null);
|
|
defer writer_file.deinit();
|
|
|
|
const buffer = allocator.alloc(u8, 64 * 1024) catch return Error.OutOfMemory;
|
|
defer allocator.free(buffer);
|
|
|
|
var offset: u64 = 0;
|
|
while (true) {
|
|
const bytes_read = reader.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
try writer_file.writeAt(offset, buffer[0..bytes_read]);
|
|
offset += bytes_read;
|
|
}
|
|
try writer_file.flush();
|
|
return;
|
|
}
|
|
|
|
// Read original size from header
|
|
const original_size = std.mem.readInt(u32, header[4..8], .little);
|
|
|
|
// Read the raw data
|
|
const raw_data = allocator.alloc(u8, original_size) catch return Error.OutOfMemory;
|
|
defer allocator.free(raw_data);
|
|
|
|
const data_read = reader.file.readAll(raw_data) catch return Error.FileError;
|
|
if (data_read != original_size) {
|
|
std.log.err("Expected {d} bytes but read {d}", .{ original_size, data_read });
|
|
return Error.FileError;
|
|
}
|
|
|
|
// Write decompressed data to output file
|
|
var writer_file = try FileWriter.init(decompressed, allocator, null);
|
|
defer writer_file.deinit();
|
|
|
|
try writer_file.writeAt(0, raw_data);
|
|
try writer_file.flush();
|
|
|
|
std.log.info("Extracted {d} bytes from stored format", .{original_size});
|
|
}
|
|
|
|
/// Get file type classification
|
|
pub fn getFileType(file_path: []const u8) FileType {
|
|
const extension = std.fs.path.extension(file_path);
|
|
|
|
if (std.mem.eql(u8, extension, ".txt") or std.mem.eql(u8, extension, ".md") or
|
|
std.mem.eql(u8, extension, ".log")) {
|
|
return .text;
|
|
} else if (std.mem.eql(u8, extension, ".jpg") or std.mem.eql(u8, extension, ".png") or
|
|
std.mem.eql(u8, extension, ".gif") or std.mem.eql(u8, extension, ".bmp")) {
|
|
return .image;
|
|
} else if (std.mem.eql(u8, extension, ".mp4") or std.mem.eql(u8, extension, ".avi") or
|
|
std.mem.eql(u8, extension, ".mkv") or std.mem.eql(u8, extension, ".mov")) {
|
|
return .video;
|
|
} else if (std.mem.eql(u8, extension, ".mp3") or std.mem.eql(u8, extension, ".wav") or
|
|
std.mem.eql(u8, extension, ".flac") or std.mem.eql(u8, extension, ".aac")) {
|
|
return .audio;
|
|
} else if (std.mem.eql(u8, extension, ".zip") or std.mem.eql(u8, extension, ".tar") or
|
|
std.mem.eql(u8, extension, ".gz") or std.mem.eql(u8, extension, ".rar")) {
|
|
return .archive;
|
|
} else {
|
|
return .binary;
|
|
}
|
|
}
|
|
|
|
/// Estimate compression ratio for file type
|
|
pub fn estimateCompressionRatio(file_path: []const u8) f32 {
|
|
const file_type = getFileType(file_path);
|
|
|
|
return switch (file_type) {
|
|
.text => 0.3, // Text files compress well
|
|
.image => 0.8, // Images usually don't compress much
|
|
.video => 0.9, // Videos are already compressed
|
|
.audio => 0.7, // Audio files compress moderately
|
|
.archive => 1.0, // Archives are already compressed
|
|
.binary => 0.6, // Binary files vary
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Check if sufficient disk space is available
|
|
pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
|
|
const dir_path = std.fs.path.dirname(path) orelse ".";
|
|
|
|
if (builtin.os.tag == .linux or builtin.os.tag == .macos) {
|
|
// Use statfs for POSIX systems
|
|
|
|
// Open the directory to get fd for fstatfs
|
|
var dir = fs.cwd().openDir(dir_path, .{}) catch {
|
|
std.log.warn("Failed to open directory {s} for disk space check", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
};
|
|
defer dir.close();
|
|
|
|
// Get file descriptor
|
|
const fd = dir.fd;
|
|
|
|
// Define statfs struct layout - must match system struct
|
|
const Statfs = switch (builtin.os.tag) {
|
|
.macos => extern struct {
|
|
f_bsize: u32, // fundamental file system block size
|
|
f_iosize: i32, // optimal transfer block size
|
|
f_blocks: u64, // total data blocks in file system
|
|
f_bfree: u64, // free blocks in fs
|
|
f_bavail: u64, // free blocks avail to non-superuser
|
|
f_files: u64, // total file nodes in file system
|
|
f_ffree: u64, // free file nodes in fs
|
|
f_fsid: [2]i32, // file system id
|
|
f_owner: u32, // user that mounted the filesystem
|
|
f_type: u32, // type of filesystem
|
|
f_flags: u32, // copy of mount exported flags
|
|
f_fssubtype: u32, // fs sub-type (flavor)
|
|
f_fstypename: [16]u8, // fs type name
|
|
f_mntonname: [1024]u8, // directory on which mounted
|
|
f_mntfromname: [1024]u8, // mounted filesystem
|
|
f_flags_ext: u32, // extended flags
|
|
f_reserved: [7]u32, // For future use
|
|
},
|
|
.linux => extern struct {
|
|
f_type: c_long, // type of filesystem
|
|
f_bsize: c_long, // optimal transfer block size
|
|
f_blocks: u64, // total data blocks in file system
|
|
f_bfree: u64, // free blocks in fs
|
|
f_bavail: u64, // free blocks available to unprivileged user
|
|
f_files: u64, // total file nodes in file system
|
|
f_ffree: u64, // free file nodes in fs
|
|
f_fsid: [2]i32, // file system id
|
|
f_namelen: c_long, // maximum length of filenames
|
|
f_frsize: c_long, // fragment size
|
|
f_flags: c_long, // mount flags of filesystem
|
|
f_spare: [4]c_long, // padding
|
|
},
|
|
else => extern struct {
|
|
f_bsize: c_long,
|
|
f_blocks: c_long,
|
|
f_bfree: c_long,
|
|
f_bavail: c_long,
|
|
f_files: c_long,
|
|
f_ffree: c_long,
|
|
},
|
|
};
|
|
|
|
var stat: Statfs = undefined;
|
|
|
|
// Use fstatfs - requires libc on Linux, always available on macOS
|
|
const result = if (builtin.os.tag == .macos or builtin.link_libc) blk: {
|
|
const fstatfs_impl = struct {
|
|
pub extern "c" fn fstatfs(fd: c_int, buf: *anyopaque) c_int;
|
|
};
|
|
break :blk fstatfs_impl.fstatfs(fd, &stat);
|
|
} else if (builtin.os.tag == .linux) blk: {
|
|
// Use Linux syscall directly when libc is not linked
|
|
const linux = std.os.linux;
|
|
const raw_result = linux.syscall2(.fstatfs, @as(usize, @bitCast(@as(isize, fd))), @intFromPtr(&stat));
|
|
break :blk if (raw_result == 0) @as(c_int, 0) else @as(c_int, -1);
|
|
} else blk: {
|
|
// Skip check on unsupported platforms
|
|
break :blk @as(c_int, -1);
|
|
};
|
|
|
|
if (result != 0) {
|
|
std.log.warn("Failed to get filesystem stats for {s}", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
}
|
|
|
|
// Convert block values to u64 (they're already u64 on macOS, but may be different on Linux)
|
|
const bavail_u64: u64 = switch (builtin.os.tag) {
|
|
.macos => stat.f_bavail,
|
|
.linux => @intCast(stat.f_bavail),
|
|
else => @intCast(stat.f_bavail),
|
|
};
|
|
|
|
const bsize_u64: u64 = switch (builtin.os.tag) {
|
|
.macos => @intCast(stat.f_bsize),
|
|
.linux => @intCast(stat.f_bsize),
|
|
else => @intCast(stat.f_bsize),
|
|
};
|
|
|
|
// Check for invalid values
|
|
if (bsize_u64 == 0) {
|
|
std.log.warn("Invalid filesystem stats for {s}", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
}
|
|
|
|
// Check for overflow before multiplying
|
|
if (bavail_u64 > 0 and bsize_u64 > std.math.maxInt(u64) / bavail_u64) {
|
|
// Overflow would occur, but that means we have plenty of space
|
|
return;
|
|
}
|
|
|
|
const available_bytes = bavail_u64 * bsize_u64;
|
|
if (available_bytes < required_bytes) {
|
|
std.log.warn("Insufficient disk space: {d} bytes available, {d} bytes required", .{ available_bytes, required_bytes });
|
|
return Error.DiskFull;
|
|
}
|
|
} else if (builtin.os.tag == .windows) {
|
|
// CRIT-7 FIX: Windows implementation using GetDiskFreeSpaceExW
|
|
const windows = std.os.windows;
|
|
|
|
// Convert path to Windows wide string format (null-terminated)
|
|
var path_buf: [std.fs.max_path_bytes:0]u16 = undefined;
|
|
const path_len = std.unicode.utf8ToUtf16Le(&path_buf, dir_path) catch |err| {
|
|
std.log.warn("Failed to convert path to Windows format: {}", .{err});
|
|
return Error.FileError;
|
|
};
|
|
path_buf[path_len] = 0; // Null terminate
|
|
|
|
var free_bytes_available: windows.ULARGE_INTEGER = undefined;
|
|
var total_bytes: windows.ULARGE_INTEGER = undefined;
|
|
var total_free_bytes: windows.ULARGE_INTEGER = undefined;
|
|
|
|
// Call GetDiskFreeSpaceExW
|
|
const result = windows.kernel32.GetDiskFreeSpaceExW(
|
|
@as([*:0]const u16, &path_buf),
|
|
&free_bytes_available,
|
|
&total_bytes,
|
|
&total_free_bytes,
|
|
);
|
|
|
|
if (result == windows.FALSE) {
|
|
const err = windows.GetLastError();
|
|
std.log.warn("Failed to get disk space for {s}: Windows error {}", .{ dir_path, err });
|
|
return Error.FileError;
|
|
}
|
|
|
|
const available = free_bytes_available.QuadPart;
|
|
if (available < required_bytes) {
|
|
std.log.warn("Insufficient disk space: {d} bytes available, {d} bytes required", .{ available, required_bytes });
|
|
return Error.DiskFull;
|
|
}
|
|
} else if (builtin.os.tag == .freebsd or builtin.os.tag == .openbsd or
|
|
builtin.os.tag == .netbsd or builtin.os.tag == .dragonfly)
|
|
{
|
|
// IMP-CRIT-1 FIX: Support BSD-family systems using statvfs
|
|
// BSD systems have slightly different statfs structures but statvfs is more portable
|
|
var dir = fs.cwd().openDir(dir_path, .{}) catch {
|
|
std.log.warn("Failed to open directory {s} for disk space check", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
};
|
|
defer dir.close();
|
|
|
|
const fd = dir.fd;
|
|
|
|
// Use statvfs which is more portable across BSD systems
|
|
const Statvfs = extern struct {
|
|
f_bsize: c_ulong, // file system block size
|
|
f_frsize: c_ulong, // fragment size
|
|
f_blocks: u64, // total blocks
|
|
f_bfree: u64, // free blocks
|
|
f_bavail: u64, // free blocks available to non-root
|
|
f_files: u64, // total inodes
|
|
f_ffree: u64, // free inodes
|
|
f_favail: u64, // free inodes available to non-root
|
|
f_fsid: c_ulong, // file system id
|
|
f_flag: c_ulong, // mount flags
|
|
f_namemax: c_ulong, // max filename length
|
|
};
|
|
|
|
const fstatvfs_impl = struct {
|
|
pub extern fn fstatvfs(fd: c_int, buf: *Statvfs) callconv(.c) c_int;
|
|
};
|
|
const fstatvfs = fstatvfs_impl.fstatvfs;
|
|
|
|
var stat: Statvfs = undefined;
|
|
const result = fstatvfs(fd, &stat);
|
|
|
|
if (result != 0) {
|
|
std.log.warn("Failed to get filesystem stats for {s}", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
}
|
|
|
|
const frsize: u64 = @intCast(stat.f_frsize);
|
|
if (frsize == 0) {
|
|
std.log.warn("Invalid filesystem stats for {s}", .{dir_path});
|
|
return; // Allow operation to proceed
|
|
}
|
|
|
|
// Check for overflow before multiplying
|
|
if (stat.f_bavail > 0 and frsize > std.math.maxInt(u64) / stat.f_bavail) {
|
|
return; // Overflow means plenty of space
|
|
}
|
|
|
|
const available_bytes = stat.f_bavail * frsize;
|
|
if (available_bytes < required_bytes) {
|
|
std.log.warn("Insufficient disk space: {d} bytes available, {d} bytes required", .{ available_bytes, required_bytes });
|
|
return Error.DiskFull;
|
|
}
|
|
} else {
|
|
// IMP-CRIT-1 FIX: For other platforms, log warning but allow operation to proceed
|
|
// This is safer than blocking all file operations on unsupported platforms.
|
|
// The same approach is used when fstatfs fails - we warn and continue.
|
|
std.log.warn("Disk space checking not implemented for platform {s} - proceeding without validation", .{@tagName(builtin.os.tag)});
|
|
// Allow operation to proceed - callers should handle DiskFull errors at write time
|
|
return;
|
|
}
|
|
}
|
|
|
|
/// Streaming file reader for efficient large file processing
|
|
pub const FileReader = struct {
|
|
allocator: mem.Allocator,
|
|
file_path: []const u8,
|
|
file: fs.File,
|
|
buffer_size: usize,
|
|
|
|
pub fn init(file_path: []const u8, allocator: mem.Allocator, buffer_size: usize) Error!FileReader {
|
|
// Validate path before opening
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
const file = fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
|
|
|
|
return FileReader{
|
|
.allocator = allocator,
|
|
.file_path = file_path,
|
|
.file = file,
|
|
.buffer_size = buffer_size,
|
|
};
|
|
}
|
|
|
|
/// Read file in chunks with proper memory management
|
|
pub fn readInChunks(self: *FileReader, chunk_callback: fn([]const u8) Error!void) Error!void {
|
|
const buffer = self.allocator.alloc(u8, self.buffer_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(buffer);
|
|
|
|
while (true) {
|
|
const bytes_read = self.file.read(buffer) catch return Error.FileError;
|
|
if (bytes_read == 0) break;
|
|
|
|
try chunk_callback(buffer[0..bytes_read]);
|
|
}
|
|
}
|
|
|
|
/// Read specific byte range from file
|
|
pub fn readRange(self: *FileReader, start: u64, length: usize) Error![]u8 {
|
|
self.file.seekTo(start) catch return Error.FileError;
|
|
|
|
const data = self.allocator.alloc(u8, length) catch return Error.OutOfMemory;
|
|
const bytes_read = self.file.read(data) catch {
|
|
self.allocator.free(data);
|
|
return Error.FileError;
|
|
};
|
|
|
|
if (bytes_read != length) {
|
|
self.allocator.free(data);
|
|
return Error.FileError;
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
pub fn close(self: *FileReader) void {
|
|
self.file.close();
|
|
}
|
|
|
|
pub fn deinit(self: *FileReader) void {
|
|
self.close();
|
|
}
|
|
};
|
|
|
|
/// File writer for assembling pieces into complete files
|
|
pub const FileWriter = struct {
|
|
allocator: mem.Allocator,
|
|
file_path: []const u8,
|
|
file: fs.File,
|
|
|
|
pub fn init(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64) Error!FileWriter {
|
|
return initInternal(file_path, allocator, file_size, true);
|
|
}
|
|
|
|
/// Initialize for resuming a download - opens existing file without truncating
|
|
pub fn initForResume(file_path: []const u8, allocator: mem.Allocator) Error!FileWriter {
|
|
return initInternal(file_path, allocator, null, false);
|
|
}
|
|
|
|
fn initInternal(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64, truncate: bool) Error!FileWriter {
|
|
// Validate path before any file operations
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Check disk space before creating file if size is known
|
|
if (file_size) |size| {
|
|
try checkDiskSpace(file_path, size);
|
|
}
|
|
|
|
// Ensure parent directory exists
|
|
if (std.fs.path.dirname(file_path)) |dir| {
|
|
// Validate parent directory path
|
|
if (!path_security.PathValidator.isPathSafe(dir)) {
|
|
return Error.InvalidData;
|
|
}
|
|
try FileUtils.ensureDir(dir);
|
|
}
|
|
|
|
// DISK VERIFY FIX: Open with read=true to allow pread for disk verification
|
|
const file = fs.cwd().createFile(file_path, .{
|
|
.truncate = truncate,
|
|
.read = true,
|
|
}) catch return Error.FileError;
|
|
|
|
// PERF: Pre-allocate file if size is known (reduces fragmentation, faster writes)
|
|
if (file_size) |size| {
|
|
preallocateFile(file, size);
|
|
}
|
|
|
|
return FileWriter{
|
|
.allocator = allocator,
|
|
.file_path = file_path,
|
|
.file = file,
|
|
};
|
|
}
|
|
|
|
/// PERF: Pre-allocate file space to avoid fragmentation and allocation during writes
|
|
fn preallocateFile(file: fs.File, size: u64) void {
|
|
// Try fallocate first (Linux) - actually allocates blocks
|
|
if (builtin.os.tag == .linux) {
|
|
// FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size
|
|
const FALLOC_FL_KEEP_SIZE = 0x01;
|
|
const fd = file.handle;
|
|
const result = std.os.linux.syscall4(.fallocate,
|
|
@as(usize, @intCast(fd)),
|
|
@as(usize, FALLOC_FL_KEEP_SIZE),
|
|
@as(usize, 0), // offset
|
|
@as(usize, @intCast(size)),
|
|
);
|
|
if (result == 0) {
|
|
std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)});
|
|
return;
|
|
}
|
|
// fallocate failed, fall through to ftruncate
|
|
}
|
|
|
|
// Fallback: use setEndPos (ftruncate) - creates sparse file
|
|
// This at least reserves the size in the filesystem
|
|
file.setEndPos(size) catch |err| {
|
|
std.log.debug("PERF: Pre-allocation failed: {}", .{err});
|
|
};
|
|
}
|
|
|
|
/// Write piece at specific position
|
|
pub fn writePiece(self: *FileWriter, piece_index: u32, piece_data: []const u8, piece_size: u64) Error!void {
|
|
// Check disk space before writing
|
|
try checkDiskSpace(self.file_path, piece_data.len);
|
|
|
|
// OVERFLOW FIX: Use checked multiplication to prevent overflow
|
|
const offset = std.math.mul(u64, piece_index, piece_size) catch return Error.BufferOverflow;
|
|
|
|
// Seek to piece position
|
|
self.file.seekTo(offset) catch return Error.FileError;
|
|
|
|
// Write piece data and verify all bytes written
|
|
const bytes_written = self.file.write(piece_data) catch return Error.FileError;
|
|
if (bytes_written != piece_data.len) {
|
|
return Error.FileError; // Partial write
|
|
}
|
|
}
|
|
|
|
/// Write data at specific offset (uses seekTo + write, NOT thread-safe)
|
|
pub fn writeAt(self: *FileWriter, offset: u64, data: []const u8) Error!void {
|
|
// Check disk space before writing
|
|
try checkDiskSpace(self.file_path, data.len);
|
|
|
|
self.file.seekTo(offset) catch return Error.FileError;
|
|
const bytes_written = self.file.write(data) catch return Error.FileError;
|
|
if (bytes_written != data.len) {
|
|
return Error.FileError; // Partial write
|
|
}
|
|
}
|
|
|
|
/// PERF: Thread-safe write at specific offset using pwrite (does not modify file position)
|
|
/// This allows concurrent writes from multiple threads without mutex contention
|
|
pub fn pwriteAt(self: *FileWriter, offset: u64, data: []const u8) Error!void {
|
|
// Check disk space before writing
|
|
try checkDiskSpace(self.file_path, data.len);
|
|
|
|
self.file.pwriteAll(data, offset) catch return Error.FileError;
|
|
}
|
|
|
|
/// Get the underlying file handle for direct pwrite operations outside mutex
|
|
pub fn getFileHandle(self: *const FileWriter) std.fs.File {
|
|
return self.file;
|
|
}
|
|
|
|
/// Flush file to disk with full sync for data persistence
|
|
/// On macOS, uses F_FULLFSYNC for guaranteed write to physical disk
|
|
pub fn flush(self: *FileWriter) Error!void {
|
|
// Standard sync first
|
|
self.file.sync() catch return Error.FileError;
|
|
|
|
// On macOS, fsync only syncs to the drive's buffer, not the physical disk.
|
|
// F_FULLFSYNC forces the drive to flush its internal cache to the platters.
|
|
if (builtin.os.tag == .macos) {
|
|
const handle = self.file.handle;
|
|
const F_FULLFSYNC = 51; // From <fcntl.h>
|
|
_ = std.c.fcntl(handle, F_FULLFSYNC, @as(c_int, 0));
|
|
// Ignore error - not all drives support F_FULLFSYNC
|
|
}
|
|
}
|
|
|
|
/// Close file
|
|
pub fn close(self: *FileWriter) void {
|
|
self.file.close();
|
|
}
|
|
|
|
pub fn deinit(self: *FileWriter) void {
|
|
// CRITICAL FIX: Sync data to disk before closing to ensure all writes are persisted.
|
|
// Without this, data may remain in OS buffer cache and verification after stop() fails.
|
|
self.file.sync() catch {};
|
|
self.close();
|
|
}
|
|
};
|
|
|
|
// ============================================================================
|
|
// Memory-Mapped File for High-Performance Reads
|
|
// ============================================================================
|
|
|
|
/// Minimum file size for mmap to be beneficial (64KB)
|
|
/// Smaller files have mmap overhead > benefit
|
|
pub const MMAP_MIN_SIZE: u64 = 64 * 1024;
|
|
|
|
/// Maximum file size for mmap (2GB default, can be overridden)
|
|
/// Very large files may exhaust address space on 32-bit systems
|
|
pub const MMAP_MAX_SIZE: u64 = 2 * 1024 * 1024 * 1024;
|
|
|
|
/// Memory-mapped file for zero-copy reads
|
|
///
|
|
/// Benefits:
|
|
/// - Zero-copy: data stays in kernel page cache, no copy to userspace buffer
|
|
/// - OS handles caching: frequently accessed pages stay in RAM
|
|
/// - Parallel reads: multiple threads can read without coordination
|
|
/// - Reduced syscalls: no read() calls, just memory access
|
|
///
|
|
/// Usage:
|
|
/// ```
|
|
/// var mapped = try MappedFile.init("large_file.bin");
|
|
/// defer mapped.deinit();
|
|
///
|
|
/// // Zero-copy slice access
|
|
/// const piece_data = mapped.getSlice(offset, length);
|
|
/// ```
|
|
pub const MappedFile = struct {
|
|
/// Pointer to mapped memory region
|
|
data: []align(std.heap.page_size_min) u8,
|
|
/// Original file size
|
|
file_size: u64,
|
|
/// File handle (kept open while mapped)
|
|
file: fs.File,
|
|
|
|
/// Initialize memory-mapped file for reading
|
|
/// Returns error if file is too small for mmap benefit or too large
|
|
pub fn init(file_path: []const u8) Error!MappedFile {
|
|
return initWithLimits(file_path, MMAP_MIN_SIZE, MMAP_MAX_SIZE);
|
|
}
|
|
|
|
/// Initialize with custom size limits
|
|
pub fn initWithLimits(file_path: []const u8, min_size: u64, max_size: u64) Error!MappedFile {
|
|
// Validate path
|
|
if (!PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Open file for reading
|
|
const file = fs.cwd().openFile(file_path, .{ .mode = .read_only }) catch {
|
|
return Error.FileError;
|
|
};
|
|
errdefer file.close();
|
|
|
|
// Get file size
|
|
const stat = file.stat() catch {
|
|
return Error.FileError;
|
|
};
|
|
const file_size = stat.size;
|
|
|
|
// Check size limits
|
|
if (file_size < min_size) {
|
|
return Error.InvalidData; // Too small for mmap benefit
|
|
}
|
|
if (file_size > max_size) {
|
|
return Error.BufferOverflow; // Too large
|
|
}
|
|
|
|
// Perform mmap
|
|
const data = mapFile(file, file_size) catch {
|
|
return Error.FileError;
|
|
};
|
|
|
|
return MappedFile{
|
|
.data = data,
|
|
.file_size = file_size,
|
|
.file = file,
|
|
};
|
|
}
|
|
|
|
/// Initialize from an already-open file handle
|
|
pub fn initFromHandle(file: fs.File, file_size: u64) Error!MappedFile {
|
|
if (file_size < MMAP_MIN_SIZE) {
|
|
return Error.InvalidData;
|
|
}
|
|
if (file_size > MMAP_MAX_SIZE) {
|
|
return Error.BufferOverflow;
|
|
}
|
|
|
|
const data = mapFile(file, file_size) catch {
|
|
return Error.FileError;
|
|
};
|
|
|
|
return MappedFile{
|
|
.data = data,
|
|
.file_size = file_size,
|
|
.file = file,
|
|
};
|
|
}
|
|
|
|
/// Get a slice of the mapped data (zero-copy)
|
|
/// Returns null if offset+length exceeds file size
|
|
pub fn getSlice(self: *const MappedFile, offset: u64, length: usize) ?[]const u8 {
|
|
// Bounds check
|
|
const end = std.math.add(u64, offset, length) catch return null;
|
|
if (end > self.file_size) {
|
|
return null;
|
|
}
|
|
|
|
const start: usize = @intCast(offset);
|
|
return self.data[start .. start + length];
|
|
}
|
|
|
|
/// Get piece data by index (zero-copy)
|
|
/// Returns the slice directly from mapped memory - no allocation!
|
|
pub fn getPiece(self: *const MappedFile, piece_index: u32, piece_size: u64) ?[]const u8 {
|
|
const offset = std.math.mul(u64, piece_index, piece_size) catch return null;
|
|
|
|
// Calculate actual piece length (last piece may be smaller)
|
|
const remaining = self.file_size -| offset;
|
|
if (remaining == 0) return null;
|
|
|
|
const length: usize = @intCast(@min(piece_size, remaining));
|
|
return self.getSlice(offset, length);
|
|
}
|
|
|
|
/// Get the entire file as a slice
|
|
pub fn getAll(self: *const MappedFile) []const u8 {
|
|
return self.data[0..@intCast(self.file_size)];
|
|
}
|
|
|
|
/// Check if a byte range is within bounds
|
|
pub fn isValidRange(self: *const MappedFile, offset: u64, length: usize) bool {
|
|
const end = std.math.add(u64, offset, length) catch return false;
|
|
return end <= self.file_size;
|
|
}
|
|
|
|
/// Advise the kernel about access patterns (optimization hint)
|
|
pub fn adviseSequential(self: *MappedFile) void {
|
|
if (builtin.os.tag == .linux) {
|
|
_ = std.posix.madvise(self.data, std.posix.MADV.SEQUENTIAL);
|
|
}
|
|
}
|
|
|
|
/// Advise random access pattern
|
|
pub fn adviseRandom(self: *MappedFile) void {
|
|
if (builtin.os.tag == .linux) {
|
|
_ = std.posix.madvise(self.data, std.posix.MADV.RANDOM);
|
|
}
|
|
}
|
|
|
|
/// Pre-fault pages into memory (reduce page faults during reads)
|
|
pub fn prefault(self: *MappedFile) void {
|
|
if (builtin.os.tag == .linux) {
|
|
_ = std.posix.madvise(self.data, std.posix.MADV.WILLNEED);
|
|
}
|
|
}
|
|
|
|
/// Release resources
|
|
pub fn deinit(self: *MappedFile) void {
|
|
// Unmap memory
|
|
std.posix.munmap(self.data);
|
|
// Close file
|
|
self.file.close();
|
|
}
|
|
|
|
/// Platform-specific mmap implementation
|
|
fn mapFile(file: fs.File, size: u64) ![]align(std.heap.page_size_min) u8 {
|
|
const len: usize = @intCast(size);
|
|
|
|
// Use mmap on POSIX systems
|
|
// CASCADE FIX: Use MAP_SHARED instead of MAP_PRIVATE for read-only access.
|
|
// MAP_SHARED ensures we see updates made via pwrite() on other file handles.
|
|
// MAP_PRIVATE could return stale data because it creates a copy-on-write view.
|
|
const ptr = try std.posix.mmap(
|
|
null,
|
|
len,
|
|
std.posix.PROT.READ,
|
|
.{ .TYPE = .SHARED },
|
|
file.handle,
|
|
0,
|
|
);
|
|
|
|
return ptr[0..len];
|
|
}
|
|
};
|
|
|
|
/// Check if mmap is beneficial for a given file size
|
|
pub fn shouldUseMmap(file_size: u64) bool {
|
|
return file_size >= MMAP_MIN_SIZE and file_size <= MMAP_MAX_SIZE;
|
|
}
|
|
|
|
// Testing functions
|
|
test "file info creation" {
|
|
const allocator = testing.allocator;
|
|
|
|
// Create a test file
|
|
const test_path = "test_file.txt";
|
|
const test_content = "This is a test file for testing file operations.";
|
|
|
|
const file = fs.cwd().createFile(test_path, .{}) catch return;
|
|
_ = file.write(test_content) catch return;
|
|
file.close();
|
|
|
|
// Test file info creation
|
|
const file_info = try FileInfo.fromPath(test_path, allocator);
|
|
defer file_info.deinit(allocator);
|
|
|
|
try testing.expectEqualSlices(u8, "test_file.txt", file_info.name);
|
|
try testing.expect(file_info.size > 0);
|
|
try testing.expectEqualSlices(u8, ".txt", file_info.extension());
|
|
|
|
// Test size formatting
|
|
const size_str = try file_info.sizeString(allocator);
|
|
defer allocator.free(size_str);
|
|
try testing.expect(size_str.len > 0);
|
|
|
|
// Clean up
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "file chunker operations" {
|
|
const allocator = testing.allocator;
|
|
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
|
|
|
|
// Create test file
|
|
const test_path = "chunked_test.bin";
|
|
const test_size = 100 * 1024; // 100KB
|
|
const test_content = [_]u8{0} ** test_size;
|
|
|
|
const file = fs.cwd().createFile(test_path, .{}) catch return;
|
|
_ = file.write(&test_content) catch return;
|
|
file.close();
|
|
|
|
// Test metadata creation
|
|
const metadata = try chunker.createMetadata(test_path);
|
|
defer allocator.free(metadata.piece_hashes);
|
|
defer allocator.free(metadata.name);
|
|
|
|
try testing.expectEqualSlices(u8, "chunked_test.bin", metadata.name);
|
|
try testing.expectEqual(@as(u64, test_size), metadata.size);
|
|
try testing.expect(metadata.piece_count > 0);
|
|
|
|
// Test piece count calculation
|
|
const piece_count = chunker.calculatePieceCount(test_size) orelse return error.CalculationFailed;
|
|
try testing.expectEqual(metadata.piece_count, piece_count);
|
|
|
|
// Test piece info
|
|
const piece_info = try chunker.getPieceInfo(test_size, 0);
|
|
try testing.expectEqual(@as(u32, 0), piece_info.index);
|
|
try testing.expectEqual(@as(u64, 0), piece_info.offset);
|
|
|
|
// Clean up
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "file writer operations" {
|
|
const allocator = testing.allocator;
|
|
|
|
// Create test file path
|
|
const test_path = "writer_test.bin";
|
|
|
|
// Test file writer creation
|
|
var writer = try FileWriter.init(test_path, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
// Write test piece
|
|
const piece_data = "Test piece data for writing";
|
|
try writer.writePiece(0, piece_data, piece_data.len);
|
|
try writer.flush();
|
|
|
|
// Clean up
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "file utilities" {
|
|
// Test file size formatting
|
|
const allocator = testing.allocator;
|
|
|
|
const size_str = try FileUtils.formatSize(1024, allocator);
|
|
defer allocator.free(size_str);
|
|
try testing.expect(size_str.len > 0);
|
|
|
|
// Test hash file (create test file first)
|
|
const test_path = "hash_test.txt";
|
|
const test_content = "Test content for hashing";
|
|
|
|
const file = fs.cwd().createFile(test_path, .{}) catch return;
|
|
_ = file.write(test_content) catch return;
|
|
file.close();
|
|
|
|
const hash = try FileUtils.hashFile(test_path, allocator);
|
|
try testing.expect(hash.len == 32);
|
|
|
|
// Clean up
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "piece info calculation" {
|
|
const allocator = testing.allocator;
|
|
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
|
|
|
|
const file_size: u64 = 50 * 1024 * 1024; // 50MB
|
|
const piece_count = chunker.calculatePieceCount(file_size) orelse return error.CalculationFailed;
|
|
|
|
// Test piece info for different pieces
|
|
for (0..piece_count) |i| {
|
|
const piece_index = @as(u32, @intCast(i));
|
|
const piece_info = try chunker.getPieceInfo(file_size, piece_index);
|
|
|
|
try testing.expectEqual(piece_index, piece_info.index);
|
|
|
|
// Calculate expected offset with overflow checking
|
|
const expected_offset = std.math.mul(u64, piece_index, DEFAULT_PIECE_SIZE) catch |err| {
|
|
std.log.err("Overflow in piece offset calculation: {}", .{err});
|
|
return error.SkipZigTest;
|
|
};
|
|
try testing.expectEqual(expected_offset, piece_info.offset);
|
|
|
|
if (i < piece_count - 1) {
|
|
try testing.expectEqual(@as(usize, DEFAULT_PIECE_SIZE), piece_info.size);
|
|
} else {
|
|
// Last piece might be smaller
|
|
try testing.expect(piece_info.size <= DEFAULT_PIECE_SIZE);
|
|
}
|
|
}
|
|
}
|
|
|
|
test "piece count calculation handles large files" {
|
|
const allocator = testing.allocator;
|
|
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
|
|
|
|
// Test with file size near u32 max * piece_size
|
|
// This should not overflow with the new implementation
|
|
const large_file_size: u64 = 1000 * DEFAULT_PIECE_SIZE;
|
|
const piece_count = chunker.calculatePieceCount(large_file_size) orelse return error.CalculationFailed;
|
|
|
|
// Verify piece count is calculated correctly
|
|
try testing.expectEqual(@as(u32, 1000), piece_count);
|
|
|
|
// Test with maximum safe file size (u32::max pieces)
|
|
const max_safe_size: u64 = @as(u64, std.math.maxInt(u32)) * DEFAULT_PIECE_SIZE;
|
|
const max_piece_count = chunker.calculatePieceCount(max_safe_size) orelse return error.CalculationFailed;
|
|
try testing.expectEqual(std.math.maxInt(u32), max_piece_count);
|
|
}
|
|
|
|
test "metadata name is properly cloned" {
|
|
const allocator = testing.allocator;
|
|
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
|
|
|
|
// Create a test file
|
|
const test_path = "test_metadata_clone.txt";
|
|
const test_content = "Test content for metadata cloning";
|
|
|
|
const file = fs.cwd().createFile(test_path, .{}) catch return;
|
|
_ = file.write(test_content) catch return;
|
|
file.close();
|
|
|
|
// Create metadata
|
|
const metadata = try chunker.createMetadata(test_path);
|
|
defer {
|
|
allocator.free(metadata.name);
|
|
allocator.free(metadata.piece_hashes);
|
|
}
|
|
|
|
// Verify name is accessible and correct
|
|
try testing.expectEqualSlices(u8, "test_metadata_clone.txt", metadata.name);
|
|
|
|
// Verify metadata is still valid after creating new metadata
|
|
// (This would fail if the name was a dangling pointer)
|
|
const metadata2 = try chunker.createMetadata(test_path);
|
|
defer {
|
|
allocator.free(metadata2.name);
|
|
allocator.free(metadata2.piece_hashes);
|
|
}
|
|
|
|
// Both names should be valid and equal
|
|
try testing.expectEqualSlices(u8, metadata.name, metadata2.name);
|
|
|
|
// Clean up
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "write operations verify all bytes written" {
|
|
const allocator = testing.allocator;
|
|
|
|
// Create test file path
|
|
const test_path = "writer_verify_test.bin";
|
|
|
|
// Test FileWriter writeAt operation
|
|
var writer = try FileWriter.init(test_path, allocator, null);
|
|
defer writer.deinit();
|
|
|
|
// Write test data
|
|
const test_data = "Test data for write verification";
|
|
try writer.writeAt(0, test_data);
|
|
try writer.flush();
|
|
|
|
// Read back and verify
|
|
const file = fs.cwd().openFile(test_path, .{}) catch return;
|
|
defer file.close();
|
|
|
|
var read_buffer: [100]u8 = undefined;
|
|
const bytes_read = file.read(&read_buffer) catch return;
|
|
|
|
try testing.expectEqual(test_data.len, bytes_read);
|
|
try testing.expectEqualSlices(u8, test_data, read_buffer[0..bytes_read]);
|
|
|
|
// Clean up - file is closed by defer writer.deinit()
|
|
fs.cwd().deleteFile(test_path) catch return;
|
|
}
|
|
|
|
test "checkDiskSpace validates available space" {
|
|
// Test that checkDiskSpace doesn't error for reasonable sizes
|
|
// This test is environment-specific and may behave differently on different systems
|
|
try checkDiskSpace(".", 1024); // 1KB should always be available in current directory
|
|
}
|
|
|
|
test "checkDiskSpace with file path" {
|
|
// Test with a file path (should check parent directory)
|
|
const test_path = "test_disk_space.txt";
|
|
try checkDiskSpace(test_path, 1024); // 1KB should be available
|
|
}
|
|
|
|
// Tests for current FileInfo API
|
|
test "FileInfo: isEmpty" {
|
|
const info = FileInfo{
|
|
.path = "/test/path.txt",
|
|
.name = "path.txt",
|
|
.size = 0,
|
|
.created_at = 0,
|
|
.modified_at = 0,
|
|
};
|
|
try std.testing.expect(info.isEmpty());
|
|
|
|
const info2 = FileInfo{
|
|
.path = "/test/path.txt",
|
|
.name = "path.txt",
|
|
.size = 100,
|
|
.created_at = 0,
|
|
.modified_at = 0,
|
|
};
|
|
try std.testing.expect(!info2.isEmpty());
|
|
}
|
|
|
|
test "FileInfo: extension" {
|
|
const info = FileInfo{
|
|
.path = "/test/document.txt",
|
|
.name = "document.txt",
|
|
.size = 100,
|
|
.created_at = 0,
|
|
.modified_at = 0,
|
|
};
|
|
try std.testing.expectEqualStrings(".txt", info.extension());
|
|
|
|
const no_ext = FileInfo{
|
|
.path = "/test/noextension",
|
|
.name = "noextension",
|
|
.size = 100,
|
|
.created_at = 0,
|
|
.modified_at = 0,
|
|
};
|
|
try std.testing.expectEqualStrings("", no_ext.extension());
|
|
}
|
|
|
|
test "FileChunker: calculatePieceCount edge cases" {
|
|
const allocator = std.testing.allocator;
|
|
const chunker = FileChunker.init(1000, allocator);
|
|
|
|
// Exactly divisible
|
|
try std.testing.expectEqual(@as(u32, 10), chunker.calculatePieceCount(10000));
|
|
|
|
// One byte over
|
|
try std.testing.expectEqual(@as(u32, 11), chunker.calculatePieceCount(10001));
|
|
|
|
// Zero size
|
|
try std.testing.expectEqual(@as(u32, 0), chunker.calculatePieceCount(0));
|
|
}
|
|
|
|
test "FileChunker: initVariable" {
|
|
const allocator = std.testing.allocator;
|
|
const chunker = FileChunker.initVariable(allocator);
|
|
// initVariable uses 32MB pieces for variable-size chunking
|
|
try std.testing.expectEqual(@as(u64, 32 * 1024 * 1024), chunker.piece_size);
|
|
}
|
|
|
|
test "getDefaultPieceSize" {
|
|
try std.testing.expectEqual(@as(u64, 1 * 1024 * 1024), getDefaultPieceSize());
|
|
try std.testing.expectEqual(DEFAULT_PIECE_SIZE, getDefaultPieceSize());
|
|
}
|
|
|
|
test "FileType: all enum values have descriptions" {
|
|
try std.testing.expect(FileType.text.description().len > 0);
|
|
try std.testing.expect(FileType.image.description().len > 0);
|
|
try std.testing.expect(FileType.video.description().len > 0);
|
|
try std.testing.expect(FileType.audio.description().len > 0);
|
|
try std.testing.expect(FileType.archive.description().len > 0);
|
|
try std.testing.expect(FileType.binary.description().len > 0);
|
|
}
|
|
|
|
test "FileType: isCompressed" {
|
|
try std.testing.expect(FileType.archive.isCompressed());
|
|
try std.testing.expect(!FileType.binary.isCompressed());
|
|
try std.testing.expect(!FileType.text.isCompressed());
|
|
}
|
|
|
|
test "FileUtils: fileExists returns false for nonexistent" {
|
|
const result = FileUtils.fileExists("/nonexistent/path/to/file/12345.txt");
|
|
try std.testing.expect(!result);
|
|
}
|
|
|
|
test "FileUtils: formatSize" {
|
|
const allocator = std.testing.allocator;
|
|
|
|
const bytes_str = try FileUtils.formatSize(500, allocator);
|
|
defer allocator.free(bytes_str);
|
|
try std.testing.expectEqualStrings("500B", bytes_str);
|
|
|
|
const kb_str = try FileUtils.formatSize(2048, allocator);
|
|
defer allocator.free(kb_str);
|
|
try std.testing.expectEqualStrings("2K", kb_str);
|
|
|
|
const mb_str = try FileUtils.formatSize(2 * 1024 * 1024, allocator);
|
|
defer allocator.free(mb_str);
|
|
try std.testing.expectEqualStrings("2M", mb_str);
|
|
}
|
|
|
|
test "CompressionMethod enum values" {
|
|
try std.testing.expectEqual(@intFromEnum(FileUtils.CompressionMethod.none), 0);
|
|
try std.testing.expectEqual(@intFromEnum(FileUtils.CompressionMethod.zstd), 1);
|
|
try std.testing.expectEqual(@intFromEnum(FileUtils.CompressionMethod.lz4), 2);
|
|
}
|