// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A `Filesystem` over a real directory: the usual thing an FTP server serves. //! //! The directory handed to `init` is the root of the virtual name space, and //! nothing outside it can be named. That is true twice over, deliberately. //! `Session` resolves the client's pathname first, so `../../../etc/shadow` //! has become `/etc/shadow` before anything here sees it and the `..` cannot //! escape. Then every operation happens relative to the open directory handle //! rather than by building a string and handing it to the operating system, //! with `resolve_beneath` set where the platform supports it — so even a //! symbolic link inside the tree that points out of it fails to open. //! //! Symbolic links are therefore reported and not followed. A client sees them //! in a listing, with their target, and cannot retrieve through one. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const listing = @import("../protocol/listing.zig"); const time = @import("../protocol/time.zig"); const path = @import("../protocol/path.zig"); const Filesystem = @import("Filesystem.zig"); const DirFilesystem = @This(); root: Io.Dir, options: Options, pub const Options = struct { /// The permissions a created file is given, before the process umask is /// applied to it. file_permissions: Io.File.Permissions = .default_file, /// The permissions a created directory is given. directory_permissions: Io.File.Permissions = .default_dir, /// The buffer a transfer reads or writes the file through. Lives on the /// stack of whatever is running the session, so it is deliberately modest: /// the data connection has a buffer of its own, and this one only has to /// be big enough that the read syscalls are not absurdly small. file_buffer_len: usize = 4096, /// How many names `STOU` tries before giving up. unique_attempts: usize = 16, }; /// Wraps an already-open directory. The directory must outlive every session /// that uses it, and is not closed by anything here. pub fn init(root: Io.Dir, options: Options) DirFilesystem { return .{ .root = root, .options = options }; } pub fn filesystem(d: *DirFilesystem) Filesystem { return .{ .userdata = d, .vtable = &vtable }; } const vtable: Filesystem.VTable = .{ .stat = stat, .list = list, .retrieve = retrieve, .store = store, .makeDirectory = makeDirectory, .removeDirectory = removeDirectory, .removeFile = removeFile, .rename = rename, }; /// Turns a resolved virtual path into one relative to `root`. /// /// `Session` guarantees the path is absolute and normalised, so this is only /// dropping the leading slash — and turning the root itself into `.`, which is /// how the operating system spells "this directory". fn relative(virtual: []const u8) []const u8 { if (path.isRoot(virtual)) return "."; return virtual[1..]; } fn from(userdata: ?*anyopaque) *DirFilesystem { return @ptrCast(@alignCast(userdata)); } fn stat(userdata: ?*anyopaque, io: Io, arena: Allocator, virtual: []const u8) Filesystem.Error!Filesystem.Entry { const d = from(userdata); const info = d.root.statFile(io, relative(virtual), .{ .follow_symlinks = false }) catch |err| return mapError(err); const name = arena.dupe(u8, path.basename(virtual)) catch return error.OutOfMemory; return entryFrom(name, info); } fn entryFrom(name: []const u8, info: Io.File.Stat) Filesystem.Entry { return .{ .name = name, .kind = kindFrom(info.kind), .size = info.size, .modified = time.secondsFromTimestamp(info.mtime), .unix = .{ .mode = modeBits(info.permissions), .link_count = linkCount(info.nlink), }, }; } /// `File.NLink` is a plain integer on some platforms and an enum on others. fn linkCount(nlink: Io.File.NLink) ?u64 { return switch (@typeInfo(Io.File.NLink)) { .@"enum" => @intCast(@intFromEnum(nlink)), .int => @intCast(nlink), else => null, }; } fn kindFrom(kind: Io.File.Kind) listing.Kind { return switch (kind) { .directory => .dir, .file => .file, .sym_link => .symlink, else => .other, }; } /// The permission bits, when the platform has any. Windows has a read-only /// flag and nothing else, so there is nothing true to report there. fn modeBits(permissions: Io.File.Permissions) ?u16 { if (!@hasDecl(Io.File.Permissions, "toMode")) return null; return @intCast(@as(u32, @intCast(permissions.toMode())) & 0o7777); } fn list( userdata: ?*anyopaque, io: Io, arena: Allocator, virtual: []const u8, entries: *std.ArrayList(Filesystem.Entry), ) Filesystem.Error!void { const d = from(userdata); var dir = d.root.openDir(io, relative(virtual), .{ .iterate = true, .follow_symlinks = false, }) catch |err| return mapError(err); defer dir.close(io); var iterator = dir.iterate(); while (iterator.next(io) catch |err| return mapError(err)) |entry| { const name = arena.dupe(u8, entry.name) catch return error.OutOfMemory; // Stat each entry for its size and time. A name that cannot be // statted -- a dangling link, a file deleted between the read and the // stat -- is still listed, with the little that is known about it, // because a directory should not become unlistable for holding one. const info = dir.statFile(io, entry.name, .{ .follow_symlinks = false }) catch { entries.append(arena, .{ .name = name, .kind = kindFrom(entry.kind), }) catch return error.OutOfMemory; continue; }; var listed = entryFrom(name, info); if (listed.kind == .symlink) { var target: [path.max_len]u8 = undefined; if (dir.readLink(io, entry.name, &target)) |len| { listed.link_target = arena.dupe(u8, target[0..len]) catch return error.OutOfMemory; } else |_| {} } entries.append(arena, listed) catch return error.OutOfMemory; } } fn retrieve( userdata: ?*anyopaque, io: Io, virtual: []const u8, offset: u64, w: *Io.Writer, ) Filesystem.Error!u64 { const d = from(userdata); const file = d.root.openFile(io, relative(virtual), .{ .mode = .read_only, // A directory opened for reading would stream its raw contents, which // is meaningless on some platforms and an error on others; refusing it // here is what turns `RETR /pub` into a 550. .allow_directory = false, .follow_symlinks = false, .resolve_beneath = true, }) catch |err| return mapError(err); defer file.close(io); var buffer: [max_file_buffer_len]u8 = undefined; const window = buffer[0..@min(d.options.file_buffer_len, buffer.len)]; var reader = file.reader(io, window); if (offset != 0) reader.seekTo(offset) catch return error.InputOutput; return reader.interface.streamRemaining(w) catch |err| switch (err) { error.ReadFailed => error.InputOutput, error.WriteFailed => error.WriteFailed, }; } /// The most a transfer will put on the stack for its file buffer. /// `Options.file_buffer_len` is clamped to this. pub const max_file_buffer_len = 64 * 1024; fn store( userdata: ?*anyopaque, io: Io, virtual: []const u8, offset: u64, mode: Filesystem.StoreMode, r: *Io.Reader, name_buffer: []u8, name: *?[]const u8, ) Filesystem.Error!u64 { const d = from(userdata); var file: Io.File = undefined; var start: u64 = 0; switch (mode) { .replace => { file = d.root.createFile(io, relative(virtual), .{ // A restart writes into the middle of what is there, so the // file must survive being opened. .truncate = offset == 0, .permissions = d.options.file_permissions, .resolve_beneath = true, }) catch |err| return mapError(err); start = offset; }, .append => { file = d.root.createFile(io, relative(virtual), .{ .truncate = false, .permissions = d.options.file_permissions, .resolve_beneath = true, }) catch |err| return mapError(err); const info = file.stat(io) catch |err| { file.close(io); return mapError(err); }; start = info.size; }, .unique => { file, const chosen = try d.createUnique(io, virtual, name_buffer); name.* = chosen; }, } defer file.close(io); var buffer: [max_file_buffer_len]u8 = undefined; const window = buffer[0..@min(d.options.file_buffer_len, buffer.len)]; var writer = file.writer(io, window); if (start != 0) writer.seekTo(start) catch return error.InputOutput; const moved = r.streamRemaining(&writer.interface) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.NoSpaceLeft, }; writer.interface.flush() catch return error.NoSpaceLeft; return moved; } /// Creates a file under a name nothing else has, inside `directory`. /// /// The name has to be found rather than computed, because the only way to know /// it is free is to create it: anything that checks first and creates second /// can lose the race. `exclusive` is what makes each attempt atomic, so a /// collision costs one more attempt and never somebody else's file. fn createUnique( d: *DirFilesystem, io: Io, directory: []const u8, name_buffer: []u8, ) Filesystem.Error!struct { Io.File, []const u8 } { const prefix = "ftp"; const digits = 16; if (name_buffer.len < directory.len + 1 + prefix.len + digits) return error.OutOfMemory; var attempt: usize = 0; while (attempt < d.options.unique_attempts) : (attempt += 1) { var random_bytes: [digits / 2]u8 = undefined; io.random(&random_bytes); var w: Io.Writer = .fixed(name_buffer); w.print("{s}", .{if (path.isRoot(directory)) "" else directory}) catch unreachable; w.print("/{s}", .{prefix}) catch unreachable; w.printHex(&random_bytes, .lower) catch unreachable; const chosen = w.buffered(); const file = d.root.createFile(io, relative(chosen), .{ .exclusive = true, .permissions = d.options.file_permissions, .resolve_beneath = true, }) catch |err| switch (err) { error.PathAlreadyExists => continue, else => return mapError(err), }; return .{ file, chosen }; } return error.AlreadyExists; } fn makeDirectory(userdata: ?*anyopaque, io: Io, virtual: []const u8) Filesystem.Error!void { const d = from(userdata); if (path.isRoot(virtual)) return error.AlreadyExists; d.root.createDir(io, relative(virtual), d.options.directory_permissions) catch |err| return mapError(err); } fn removeDirectory(userdata: ?*anyopaque, io: Io, virtual: []const u8) Filesystem.Error!void { const d = from(userdata); if (path.isRoot(virtual)) return error.AccessDenied; d.root.deleteDir(io, relative(virtual)) catch |err| return mapError(err); } fn removeFile(userdata: ?*anyopaque, io: Io, virtual: []const u8) Filesystem.Error!void { const d = from(userdata); if (path.isRoot(virtual)) return error.IsADirectory; d.root.deleteFile(io, relative(virtual)) catch |err| return mapError(err); } fn rename(userdata: ?*anyopaque, io: Io, old: []const u8, new: []const u8) Filesystem.Error!void { const d = from(userdata); if (path.isRoot(old) or path.isRoot(new)) return error.AccessDenied; d.root.rename(relative(old), d.root, relative(new), io) catch |err| return mapError(err); } /// Collapses the operating system's error into one of the few a reply code can /// be chosen from. /// /// The set is deliberately narrow, and everything not named here becomes /// `InputOutput`: a client can do nothing with the difference between /// `SymLinkLoop` and `NameTooLong` except see it in a 451, and a server that /// spelled every one of them out would be telling a stranger about its file /// system. fn mapError(err: anyerror) Filesystem.Error { return switch (err) { error.FileNotFound => error.NotFound, error.AccessDenied, error.PermissionDenied => error.AccessDenied, error.NotDir => error.NotADirectory, error.IsDir => error.IsADirectory, error.PathAlreadyExists => error.AlreadyExists, error.DirNotEmpty => error.NotEmpty, error.NoSpaceLeft, error.DiskQuota, error.FileTooBig => error.NoSpaceLeft, error.ReadOnlyFileSystem => error.ReadOnly, error.SystemResources, error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, error.OutOfMemory, => error.SystemResources, else => error.InputOutput, }; } // -- tests ---------------------------------------------------------------- const testing = std.testing; test "a directory served as a file system" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "readme.txt", .data = "hello\n" }); try tmp.dir.createDir(io, "pub", .default_dir); try tmp.dir.writeFile(io, .{ .sub_path = "pub/inner.bin", .data = "\x00\x01\x02" }); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const file = try fs.stat(io, arena.allocator(), "/readme.txt"); try testing.expectEqualStrings("readme.txt", file.name); try testing.expectEqual(listing.Kind.file, file.kind); try testing.expectEqual(@as(?u64, 6), file.size); const directory = try fs.stat(io, arena.allocator(), "/pub"); try testing.expectEqual(listing.Kind.dir, directory.kind); try testing.expectError(error.NotFound, fs.stat(io, arena.allocator(), "/nothing")); } test "listing a directory" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "a.txt", .data = "a" }); try tmp.dir.writeFile(io, .{ .sub_path = "b.txt", .data = "bb" }); try tmp.dir.createDir(io, "c", .default_dir); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var entries: std.ArrayList(Filesystem.Entry) = .empty; try fs.list(io, arena.allocator(), "/", &entries); try testing.expectEqual(@as(usize, 3), entries.items.len); var seen_directory = false; for (entries.items) |entry| { if (std.mem.eql(u8, entry.name, "a.txt")) try testing.expectEqual(@as(?u64, 1), entry.size); if (std.mem.eql(u8, entry.name, "c")) seen_directory = true; } try testing.expect(seen_directory); } test "retrieving and storing" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "source", .data = "0123456789" }); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var out: [64]u8 = undefined; var w: Io.Writer = .fixed(&out); try testing.expectEqual(@as(u64, 10), try fs.retrieve(io, "/source", 0, &w)); try testing.expectEqualStrings("0123456789", w.buffered()); // A restart offset skips what the client already has. var partial: [64]u8 = undefined; var pw: Io.Writer = .fixed(&partial); try testing.expectEqual(@as(u64, 4), try fs.retrieve(io, "/source", 6, &pw)); try testing.expectEqualStrings("6789", pw.buffered()); var source: Io.Reader = .fixed("stored bytes"); var name_buffer: [256]u8 = undefined; var name: ?[]const u8 = null; try testing.expectEqual( @as(u64, 12), try fs.store(io, "/target", 0, .replace, &source, &name_buffer, &name), ); var read_back: [64]u8 = undefined; try testing.expectEqualStrings("stored bytes", try tmp.dir.readFile(io, "target", &read_back)); } test "appending" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(io, .{ .sub_path = "log", .data = "one\n" }); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var source: Io.Reader = .fixed("two\n"); var name_buffer: [256]u8 = undefined; var name: ?[]const u8 = null; _ = try fs.store(io, "/log", 0, .append, &source, &name_buffer, &name); var read_back: [64]u8 = undefined; try testing.expectEqualStrings("one\ntwo\n", try tmp.dir.readFile(io, "log", &read_back)); } test "a unique name is chosen and reported" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var source: Io.Reader = .fixed("contents"); var name_buffer: [256]u8 = undefined; var name: ?[]const u8 = null; _ = try fs.store(io, "/", 0, .unique, &source, &name_buffer, &name); const chosen = name orelse return error.TestUnexpectedResult; try testing.expect(std.mem.startsWith(u8, chosen, "/ftp")); var read_back: [64]u8 = undefined; try testing.expectEqualStrings("contents", try tmp.dir.readFile(io, chosen[1..], &read_back)); } test "creating, renaming and removing" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try fs.makeDirectory(io, "/new"); _ = try fs.stat(io, arena.allocator(), "/new"); try fs.rename(io, "/new", "/renamed"); try testing.expectError(error.NotFound, fs.stat(io, arena.allocator(), "/new")); try fs.removeDirectory(io, "/renamed"); try testing.expectError(error.NotFound, fs.stat(io, arena.allocator(), "/renamed")); // The root is not something a client may rearrange. try testing.expectError(error.AccessDenied, fs.removeDirectory(io, "/")); try testing.expectError(error.AccessDenied, fs.rename(io, "/", "/x")); try testing.expectError(error.AlreadyExists, fs.makeDirectory(io, "/")); } test "a directory is not a file" { const io = testing.io; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.createDir(io, "pub", .default_dir); var backing: DirFilesystem = .init(tmp.dir, .{}); const fs = backing.filesystem(); var out: [16]u8 = undefined; var w: Io.Writer = .fixed(&out); try testing.expectError(error.IsADirectory, fs.retrieve(io, "/pub", 0, &w)); }