From 5157579ff7f9ae0cfc3c7629e953da05bce340fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 9 Nov 2026 00:52:52 -0300 Subject: tests: at the end of their files: every top-level test block of the 46 files that had one mid-file (the locality analysis's 45 and test/hxdiff.zig; gui.zig, macos.zig, look, host_io, 9p_io, terminal, tui, mouse, fs, replica, layout among them, 11,429 test lines), with the functions only tests call, moved after the file's code in their order, a mechanical move (.scratch/suites/tests_to_end.py), zig fmt'd; the unit suites pass as before (tui 1486/1487, gui 1536/1537, core 956/956 on both), macos.zig only parse-checked here Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/fs.zig | 1190 ++++++++++++++++++++++++++++++------------------------------ 1 file changed, 595 insertions(+), 595 deletions(-) (limited to 'src/fs.zig') diff --git a/src/fs.zig b/src/fs.zig index 67986a81..5e4f181a 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -287,604 +287,177 @@ pub fn validMountName(name: []const u8) bool { return true; } -test "/os refuses a rename or a mode change as not permitted, in words, and still truncates to zero" { - const p = try th.withFile(std.testing.allocator, "x\n"); - defer p.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "kept.txt", .data = "kept\n" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var node: u64 = os_root; - var parts = std.mem.tokenizeScalar(u8, dir, '/'); - while (parts.next()) |part| node = th.look_up(p, node, part).reply.attr.node; - node = th.look_up(p, node, "kept.txt").reply.attr.node; - for ([_]Req{ - .{ .tag = 1, .op = .setattr, .node = node, .set = .{ .mode = true } }, - .{ .tag = 2, .op = .setattr, .node = node, .set = .{ .name = true }, .data = "moved.txt" }, - }) |req| { - const r = th.call(p, req); - try std.testing.expectEqual(E.PERM, r.errno()); - try std.testing.expectStringStartsWith(r.reply.ename, "permission denied"); - } - try std.testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 3, .op = .setattr, .node = node, .truncate = true }).reply.status); +pub fn isVirtual(path: []const u8) bool { + return std.mem.eql(u8, path, "/virtual") or std.mem.startsWith(u8, path, "/virtual/") or + std.mem.eql(u8, path, "/n") or std.mem.startsWith(u8, path, "/n/"); } -test "mounts own their names and dials and reject duplicate or reserved names" { - const gpa = std.testing.allocator; - var ns: Namespace = .{}; - defer ns.deinit(gpa); - var name = "peer".*; - var dial = "/tmp/peer.sock".*; - try ns.mount(gpa, &name, &dial); - @memset(&name, 'x'); - @memset(&dial, 'x'); - try std.testing.expectEqualStrings("peer", ns.mounts.items[0].name); - try std.testing.expectEqualStrings("/tmp/peer.sock", ns.mounts.items[0].dial); - try std.testing.expectError(error.AlreadyMounted, ns.mount(gpa, "peer", "/tmp/other.sock")); - for ([_][]const u8{ "", ".", "..", "os", "self", "a/b", "with space" }) |bad| - try std.testing.expectError(error.BadMountName, ns.mount(gpa, bad, "/tmp/peer.sock")); - for ([_][]const u8{ "", "a\x00b", "tcp!127.0.0.1!0", "tcp!localhost!564" }) |bad| - try std.testing.expectError(error.BadDial, ns.mount(gpa, "valid", bad)); - for (1..max_mounts) |i| { - var buf: [16]u8 = undefined; - try ns.mount(gpa, try std.fmt.bufPrint(&buf, "peer{d}", .{i}), "/tmp/peer.sock"); - } - try std.testing.expectEqual(max_mounts, ns.mounts.items.len); - try std.testing.expectError(error.TooManyMounts, ns.mount(gpa, "full", "/tmp/peer.sock")); +/// std's `statFile`, but a name with a part over 255 bytes is NameTooLong: +/// std's own takes the kernel's ENAMETOOLONG for that for a bug and panics +/// (Io.Threaded dirStatFileLinux), and such a name comes from anyone who +/// writes one to `name`, `look` or DumpDir. +pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOptions) !std.Io.File.Stat { + var parts = std.mem.tokenizeScalar(u8, path, '/'); + while (parts.next()) |part| if (part.len > 255) return error.NameTooLong; + return std.Io.Dir.cwd().statFile(io, path, options); } -test "mount allocation failures preserve prior mounts and release partial copies" { - const Check = struct { - fn run(gpa: std.mem.Allocator) !void { - var ns: Namespace = .{}; - defer ns.deinit(gpa); - try ns.mount(gpa, "first", "/tmp/first.sock"); - ns.mount(gpa, "second", "/tmp/second.sock") catch |err| { - try std.testing.expectEqual(@as(usize, 1), ns.mounts.items.len); - try std.testing.expectEqualStrings("first", ns.mounts.items[0].name); - try std.testing.expectEqualStrings("/tmp/first.sock", ns.mounts.items[0].dial); - return err; - }; - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{}); +/// Make `dir` and each directory above it that is missing, as `mkdir -p` +/// does: one already there is no failure. A failure shows at the open +/// that follows. +pub fn makeDirs(dir: []const u8) void { + if (comptime !platform_has_fs) return; + if (dir.len == 0) return; + pardes.tape.site(.make_dirs, null, makeDirsHost, .{dir}); } -test "unmount refuses pane paths inherited directories and queued save targets" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try p.fs.mount(gpa, "peer", "/tmp/peer.sock"); - const pane = try p.setTestFile("unsaved\n"); - for ([_][]const u8{ "/n/peer", "/n/peer/file", "/n/peer/dir/file" }) |path| { - gpa.free(pane.file.?.path); - pane.file.?.path = try gpa.dupe(u8, path); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - } - gpa.free(pane.file.?.path); - pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); - const slot = p.freeSlot().?; - const shell = try p.newShell(slot, "/n/peer/dir"); - p.setCwd(slot, "/n/peer/dir"); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - pane.cwd = .{ .inherited = shell }; - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - p.setCwd(slot, "/"); - while (p.nextEffect()) |_| {} - p.emit(.{ .save_text = .{ .pane = 0, .serial = pane.serial, .path = .from("/n/peer/pending") } }); - try std.testing.expectError(error.MountInUse, unmount(p, "peer")); - while (p.nextEffect()) |_| {} - try unmount(p, "peer"); - try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try std.testing.expectError(error.NotMounted, unmount(p, "peer")); - try p.fs.mount(gpa, "peer", "/tmp/other.sock"); - try std.testing.expectEqualStrings("/tmp/other.sock", p.fs.mounts.items[0].dial); +fn makeDirsHost(dir: []const u8) void { + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; } -test "virtual writes enforce permissions even when contents are empty" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - for ([_][]const u8{ "", "bytes" }) |bytes| { - for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README" }) |path| - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - // /log takes one word, `follow`, and only on the open it changes. - if (bytes.len > 0) if (write(p, "/n/self/log", bytes)) |_| return error.TestUnexpectedResult else |_| {}; - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/pane", bytes)); - try std.testing.expectError(error.FileNotFound, write(p, "/virtual/missing", bytes)); - try std.testing.expectError(error.FileNotFound, write(p, "/virtual/cons", bytes)); - if (limits.embedded_sources) { - for ([_][]const u8{ "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); - } else try std.testing.expectError(error.FileNotFound, write(p, "/virtual/src/fs.zig", bytes)); +/// Whether `dir` is not there to make because one above it refuses: its +/// nearest ancestor that is there may not be searched or written (EACCES: +/// `noperm/a/b`, `/proc/1/root/x`). +pub fn deniedAbove(dir: []const u8) bool { + if (comptime !platform_has_fs) return false; + var at: ?[]const u8 = dir; + while (at) |d| : (at = std.Io.Dir.path.dirname(d)) { + var z: [4096]u8 = undefined; + const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{d}, 0) catch return false; + if (libc.access(dz.ptr, 0) != 0) continue; // F_OK + return libc.access(dz.ptr, 2 | 1) != 0; // W_OK | X_OK } - for (p.fs.opens) |o| try std.testing.expect(o.node == 0); + return false; } -test "direct self reads and writes use the same dot paths as Look" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("old contents\n"); - var path_buf: [256]u8 = undefined; - for ([_][]const u8{ "/virtual", "/n/self" }) |root| { - const path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/{d}/../{d}/body/./", .{ root, pane.serial, pane.serial }); - try write(p, path, "replacement\n"); - try std.testing.expectEqualStrings("replacement\n", pane.file.?.content); - const bytes = try read(p, path); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(pane.file.?.content, bytes); - var resolved: [4096]u8 = undefined; - const canonical = resolve(p, path, "/", &resolved).?; - try std.testing.expectEqual(tree.resolveSelf(p, canonical.path[9..]), tree.resolveSelf(p, path[root.len..])); - try std.testing.expectEqual(@as(?u64, tree.root), tree.resolveSelf(p, "./pane/../../")); - const index_path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/../index", .{root}); - try std.testing.expectError(error.ReadOnlyFilesystem, write(p, index_path, "")); - const index = try read(p, index_path); - defer gpa.free(index); - try std.testing.expect(std.mem.indexOf(u8, index, "/test.txt") != null); - } - var overlong: [4110]u8 = @splat('x'); - @memcpy(overlong[0..9], "/virtual/"); - var resolved: [4096]u8 = undefined; - try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); - try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); - try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); +pub fn localPath(path: []const u8) ?[]const u8 { + if (std.mem.eql(u8, path, "/n/os")) return "/"; + if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; + if (isVirtual(path)) return null; + return path; } -test "self files share the regular file limit without preallocating it" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const contents = try gpa.alloc(u8, limits.max_stream_bytes + 17); - defer gpa.free(contents); - @memset(contents, 'x'); - const pane = try p.setTestFile(contents); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); - const bytes = try read(p, path); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, contents, bytes); -} +pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[4096]u8) ?Resolved { + if (word.len == 0 or std.mem.indexOfScalar(u8, word, 0) != null) return null; + var joined_buf: [4096]u8 = undefined; + const joined = if (word[0] == '/') word else std.fmt.bufPrint(&joined_buf, "{s}/{s}", .{ cwd, word }) catch return null; + if (std.mem.eql(u8, std.mem.trimEnd(u8, joined, "/"), "/n")) return .{ .path = "/n" }; -test "bounded reads accept exact OS file lengths and empty files" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - var contents: [8209]u8 = @splat('x'); - contents[contents.len - 1] = '\n'; - for ([_][]const u8{ &contents, "" }) |expected| { - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "limited.txt", .data = expected }); - var path_buf: [4096]u8 = undefined; - const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "limited.txt", &path_buf)]; - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); - for ([_][]const u8{ native, explicit }) |path| { - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, expected, bytes); - if (expected.len > 0) { - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } + if (std.mem.startsWith(u8, joined, "/n/")) { + const explicit = joined[3..]; + const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; + const name = explicit[0..cut]; + const path = if (cut < explicit.len) explicit[cut..] else "/"; + if (std.mem.eql(u8, name, "os")) { + var native_buf: [4096]u8 = undefined; + const native = resolveOs(path, &native_buf) orelse return null; + return .{ .path = std.fmt.bufPrint(out, "/n/os{s}", .{native.path}) catch return null }; + } + if (std.mem.eql(u8, name, "self")) return resolveVirtual(p, path, out); + const core = p orelse return null; + for (core.fs.mounts.items) |mount| { + if (!std.mem.eql(u8, mount.name, name)) continue; + const normalized = normalizeVirtualPath(path, out) orelse return null; + var remote_path: [4096]u8 = undefined; + const saved = std.fmt.bufPrint(&remote_path, "/n/{s}/{s}", .{ name, normalized }) catch return null; + @memcpy(out[0..saved.len], saved); + return .{ .path = out[0..saved.len] }; } + return null; } - try tmp.dir.createDir(std.testing.io, "empty", .default_dir); - var path_buf: [4096]u8 = undefined; - const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "empty", &path_buf)]; - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); - const empty = try readLimit(p, explicit, 0); - defer gpa.free(empty); - try std.testing.expectEqual(@as(usize, 0), empty.len); - // The directory's node stays in the table for the listener to collect - // once no connection names it (src/9p_io.zig, collectOs): a client may - // have walked to the same directory meanwhile and hold it by that node. - try std.testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); - try std.testing.expectEqualStrings(native, p.fs.os_paths.items[0].path); -} - -test "bounded reads apply the same limits to self bodies and embedded sources" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - var contents: [8209]u8 = @splat('x'); - contents[contents.len - 1] = '\n'; - for ([_][]const u8{ &contents, "" }) |expected| { - const pane = try p.setTestFile(expected); - for ([_][]const u8{ "/virtual", "/n/self" }) |prefix| { - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/pane/{d}/body", .{ prefix, pane.serial }); - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualSlices(u8, expected, bytes); - if (expected.len > 0) { - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } - try std.testing.expectEqualSlices(u8, expected, pane.file.?.content); - } - } - if (limits.embedded_sources) { - const source = findEmbeddedSource("src/look.zig", false).?; - for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig" }) |path| { - const bytes = try readLimit(p, path, source.contents.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(source.contents, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, source.contents.len - 1)); - } - const bytes = try readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(source.contents, bytes); - try std.testing.expectError(error.FileTooLarge, readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len - 1)); - } -} - -test "bounded reads count rendered directory paths and unknown self lengths" { - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; // so listeners has a line - for ([_][]const u8{ "/n", "/virtual", "/n/self", "/virtual/pane", "/virtual/listeners", "/virtual/README" }) |path| { - const expected = try read(p, path); - defer gpa.free(expected); - try std.testing.expect(expected.len > 0); - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); + if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); + if (resolveOs(joined, out)) |found| return found; + if (resolveVirtual(p, joined, out)) |found| return found; + // `.`, `..` and `./x` name the pane's directory, never the served tree: + // with that directory gone they name nothing (`.` would be /virtual/). + if (!dotRelative(word)) if (resolveVirtual(p, word, out)) |found| return found; + if (resolveEmbedded(word, cwd, out)) |source| { + const path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null; + return .{ .path = path }; } - try std.testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); -} - -test "bounded reads release terminal snapshots after success and size refusal" { - const gpa = std.testing.allocator; - const p = try th.withTerm(gpa); - defer p.deinit(); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{th.serialOf(p)}); - const empty = try readLimit(p, path, 0); - defer gpa.free(empty); - try std.testing.expectEqual(@as(usize, 0), empty.len); - p.update(.{ .output = .{ .pane = 0, .bytes = "limited terminal output" } }); - const expected = "limited terminal output\n"; // a line ends with its newline - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - for (p.fs.opens) |o| try std.testing.expectEqual(@as(u64, 0), o.node); + return null; } -test "bounded reads probe size-unknown proc files at the exact limit" { - if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const expected = read(p, "/proc/version") catch |err| return switch (err) { - error.FileNotFound, error.PermissionDenied => error.SkipZigTest, - else => err, - }; - defer gpa.free(expected); - try std.testing.expect(expected.len > 0); - var storage: [256 * 1024]u8 = undefined; - var fixed = std.heap.FixedBufferAllocator.init(&storage); - const bounded = try readFileLimit(fixed.allocator(), "/proc/version", limits.max_stream_bytes); - try std.testing.expectEqualStrings(expected, bounded); - fixed.allocator().free(bounded); - for ([_][]const u8{ "/proc/version", "/n/os/proc/version" }) |path| { - const bytes = try readLimit(p, path, expected.len); - defer gpa.free(bytes); - try std.testing.expectEqualStrings(expected, bytes); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); - try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); - } +/// Whether `word` is spelled relative to the directory it is looked from: +/// `.`, `..`, `./x`, `../x`. +pub fn dotRelative(word: []const u8) bool { + const w = std.mem.trimEnd(u8, word, "/"); + return std.mem.eql(u8, w, ".") or std.mem.eql(u8, w, "..") or + std.mem.startsWith(u8, word, "./") or std.mem.startsWith(u8, word, "../"); } -test "self file reads release partial allocations when memory runs out" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const contents = try gpa.alloc(u8, 65537); - defer gpa.free(contents); - @memset(contents, 'x'); - const pane = try p.setTestFile(contents); - var path_buf: [128]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); - const Read = struct { - fn run(allocator: std.mem.Allocator, core: *Pardes, name: []const u8) !void { - const original = core.gpa; - core.gpa = allocator; - defer core.gpa = original; - const bytes = read(core, name) catch |err| return switch (err) { - error.WriteFailed => error.OutOfMemory, - else => err, - }; - defer allocator.free(bytes); - try std.testing.expectEqual(@as(usize, 65537), bytes.len); - } - }; - try std.testing.checkAllAllocationFailures(gpa, Read.run, .{ p, path }); - try std.testing.expectEqualSlices(u8, contents, pane.file.?.content); +/// Where a path really is on the host, and whether it is a directory. The +/// path may lie in a mount this editor serves, so the turn is given up for +/// the syscalls: another thread answers them. +/// A path's leading `~` -- alone, or before `/` or `:` (`~/x:12`) -- is the +/// home directory: $HOME, else the passwd entry's. `~user/...` is that +/// user's. As in a shell, `~` is home even beside a file named `~` in the +/// current directory. Every entry point that takes a path the user typed +/// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, +/// Restore, a forwarded `pardes ~/x`. The path itself when there is no +/// `~` to expand, or no home for it. +pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { + if (path.len == 0 or path[0] != '~') return path; + // Home as the session that recorded found it (src/tape.zig). + return pardes.tape.value(.env, expandHomeHost, .{ path, out }); } -test "oversized OS files fail before allocating their contents" { - if (!platform_has_fs) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const file = try tmp.dir.createFile(std.testing.io, "oversized", .{}); - defer file.close(std.testing.io); - try file.setLength(std.testing.io, limits.max_file_bytes + 1); - var path_buf: [4096]u8 = undefined; - const path_len = try tmp.dir.realPathFile(std.testing.io, "oversized", &path_buf); - var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); - try std.testing.expectError(error.FileTooLarge, readFile(failing.allocator(), path_buf[0..path_len])); - try std.testing.expectEqual(@as(usize, 0), failing.allocations); +fn expandHomeHost(path: []const u8, out: *[4096]u8) []const u8 { + return expandHomeFrom(path, out, std.c.getenv("HOME")); } -test "filesystem roots list their namespaces without dialing remote mounts" { - const gpa = std.testing.allocator; - const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - try p.fs.mount(gpa, "peer", "unavailable-session"); - for ([_][]const u8{ "/n", "/n/", "/n///" }) |path| { - const contents = try read(p, path); - defer gpa.free(contents); - try std.testing.expectEqualStrings("/n/os/\n/n/self/\n/n/peer/\n", contents); - var buf: [4096]u8 = undefined; - try std.testing.expectEqualStrings("/n", resolve(p, path, "/", &buf).?.path); - try std.testing.expectError(error.IsDirectory, write(p, path, "")); - } - const bare = try read(p, "/virtual"); - defer gpa.free(bare); - const slashed = try read(p, "/virtual/"); - defer gpa.free(slashed); - try std.testing.expectEqualStrings(bare, slashed); - try std.testing.expect(std.mem.indexOf(u8, bare, "/virtual/index\n") != null); - try std.testing.expectError(error.IsDirectory, write(p, "/virtual", "")); +/// expandHome with HOME given (null: unset), so a test need not change the +/// process's environment, which a child spawned later reads. +fn expandHomeFrom(path: []const u8, out: *[4096]u8, env_home: ?[*:0]const u8) []const u8 { + if (path.len == 0 or path[0] != '~') return path; + const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; + const home = (if (end == 1) homeDir(env_home) else userHome(path[1..end])) orelse return path; + const trimmed = std.mem.trimEnd(u8, home, "/"); + const rest = path[end..]; + if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; + return std.fmt.bufPrint(out, "{s}{s}", .{ trimmed, rest }) catch path; } -test "virtual body writes can read their input from the same pane" { - const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("same pane contents\n"); - const event_node = tree.Node.of(pane.serial, .event); - _ = tree.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); - defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = event_node }); - var path_buffer: [64]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buffer, "/virtual/pane/{d}/body", .{pane.serial}); - try write(p, path, pane.file.?.content); - try std.testing.expectEqualStrings("same pane contents\n", pane.file.?.content); - // The truncation and the write are one undo step. - try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); - const events = &p.panes[p.view().active].?.fs.events; - try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "ED")); - events.pop(); - try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "EI")); - events.pop(); - try std.testing.expect(events.empty()); - try write(p, path, pane.file.?.content[5..]); - try std.testing.expectEqualStrings("pane contents\n", pane.file.?.content); +fn homeDir(env_home: ?[*:0]const u8) ?[]const u8 { + if (env_home) |h| if (h[0] != 0) return std.mem.span(h); + const pw = std.c.getpwuid(std.c.getuid()) orelse return null; + return std.mem.span(pw.dir orelse return null); } -pub fn isVirtual(path: []const u8) bool { - return std.mem.eql(u8, path, "/virtual") or std.mem.startsWith(u8, path, "/virtual/") or - std.mem.eql(u8, path, "/n") or std.mem.startsWith(u8, path, "/n/"); +fn userHome(name: []const u8) ?[]const u8 { + var z: [256]u8 = undefined; + const name_z = std.fmt.bufPrintSentinel(&z, "{s}", .{name}, 0) catch return null; + const pw = std.c.getpwnam(name_z) orelse return null; + return std.mem.span(pw.dir orelse return null); } -/// std's `statFile`, but a name with a part over 255 bytes is NameTooLong: -/// std's own takes the kernel's ENAMETOOLONG for that for a bug and panics -/// (Io.Threaded dirStatFileLinux), and such a name comes from anyone who -/// writes one to `name`, `look` or DumpDir. -pub fn statPath(io: std.Io, path: []const u8, options: std.Io.Dir.StatFileOptions) !std.Io.File.Stat { - var parts = std.mem.tokenizeScalar(u8, path, '/'); - while (parts.next()) |part| if (part.len > 255) return error.NameTooLong; - return std.Io.Dir.cwd().statFile(io, path, options); +pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { + if (comptime !platform_has_fs) return null; + var z: [4096]u8 = undefined; + const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; + return pardes.tape.site(.resolve, null, resolveHost, .{ path_z, out }); } -test "a path with a part over 255 bytes is NameTooLong, never a panic" { - const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; - try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); +fn resolveHost(path_z: [:0]const u8, out: *[4096]u8) ?Resolved { + const resolved = realpath(path_z, out) orelse return null; + return .{ .path = std.mem.span(resolved), .dir = isDir(resolved) }; } -/// Make `dir` and each directory above it that is missing, as `mkdir -p` -/// does: one already there is no failure. A failure shows at the open -/// that follows. -pub fn makeDirs(dir: []const u8) void { - if (comptime !platform_has_fs) return; - if (dir.len == 0) return; - pardes.tape.site(.make_dirs, null, makeDirsHost, .{dir}); +fn resolveVirtual(p: ?*pardes.Pardes, path: []const u8, out: *[4096]u8) ?Resolved { + var normalized_buf: [4096]u8 = undefined; + const normalized = normalizeVirtualPath(path, &normalized_buf) orelse return null; + if (p) |core| if (tree.resolveSelf(core, normalized) != null) + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; + if (findEmbeddedSource(normalized, false)) |source| + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null }; + if (sources_fs.node(normalized) != null) + return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; + return null; } -fn makeDirsHost(dir: []const u8) void { - _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; -} - -/// Whether `dir` is not there to make because one above it refuses: its -/// nearest ancestor that is there may not be searched or written (EACCES: -/// `noperm/a/b`, `/proc/1/root/x`). -pub fn deniedAbove(dir: []const u8) bool { - if (comptime !platform_has_fs) return false; - var at: ?[]const u8 = dir; - while (at) |d| : (at = std.Io.Dir.path.dirname(d)) { - var z: [4096]u8 = undefined; - const dz = std.fmt.bufPrintSentinel(&z, "{s}", .{d}, 0) catch return false; - if (libc.access(dz.ptr, 0) != 0) continue; // F_OK - return libc.access(dz.ptr, 2 | 1) != 0; // W_OK | X_OK - } - return false; -} - -test "a directory under one that may not be searched or written is denied, one merely missing is not" { - // The refusing directory is Linux's /proc/1/root. - if (comptime @import("builtin").os.tag == .linux) try std.testing.expect(deniedAbove("/proc/1/root/x/y")); - try std.testing.expect(!deniedAbove("/tmp/pardes-surely-missing-dir/a/b")); -} - -pub fn localPath(path: []const u8) ?[]const u8 { - if (std.mem.eql(u8, path, "/n/os")) return "/"; - if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; - if (isVirtual(path)) return null; - return path; -} - -test "explicit OS paths retain their namespace until an OS boundary" { - for ([_]struct { declared: []const u8, native: ?[]const u8 }{ - .{ .declared = "/n/os", .native = "/" }, - .{ .declared = "/n/os/project/file", .native = "/project/file" }, - .{ .declared = "/n/os/virtual/index", .native = "/virtual/index" }, - .{ .declared = "/n/os/n/self/index", .native = "/n/self/index" }, - .{ .declared = "/n/self/index", .native = null }, - .{ .declared = "/n/peer/os/project/file", .native = null }, - .{ .declared = "/virtual/index", .native = null }, - .{ .declared = "/project/file", .native = "/project/file" }, - }) |case| { - const native = localPath(case.declared); - if (case.native) |expected| try std.testing.expectEqualStrings(expected, native.?) else try std.testing.expect(native == null); - } -} - -pub fn resolve(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, out: *[4096]u8) ?Resolved { - if (word.len == 0 or std.mem.indexOfScalar(u8, word, 0) != null) return null; - var joined_buf: [4096]u8 = undefined; - const joined = if (word[0] == '/') word else std.fmt.bufPrint(&joined_buf, "{s}/{s}", .{ cwd, word }) catch return null; - if (std.mem.eql(u8, std.mem.trimEnd(u8, joined, "/"), "/n")) return .{ .path = "/n" }; - - if (std.mem.startsWith(u8, joined, "/n/")) { - const explicit = joined[3..]; - const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; - const name = explicit[0..cut]; - const path = if (cut < explicit.len) explicit[cut..] else "/"; - if (std.mem.eql(u8, name, "os")) { - var native_buf: [4096]u8 = undefined; - const native = resolveOs(path, &native_buf) orelse return null; - return .{ .path = std.fmt.bufPrint(out, "/n/os{s}", .{native.path}) catch return null }; - } - if (std.mem.eql(u8, name, "self")) return resolveVirtual(p, path, out); - const core = p orelse return null; - for (core.fs.mounts.items) |mount| { - if (!std.mem.eql(u8, mount.name, name)) continue; - const normalized = normalizeVirtualPath(path, out) orelse return null; - var remote_path: [4096]u8 = undefined; - const saved = std.fmt.bufPrint(&remote_path, "/n/{s}/{s}", .{ name, normalized }) catch return null; - @memcpy(out[0..saved.len], saved); - return .{ .path = out[0..saved.len] }; - } - return null; - } - if (std.mem.eql(u8, joined, "/virtual")) return resolveVirtual(p, "/", out); - if (std.mem.startsWith(u8, joined, "/virtual/")) return resolveVirtual(p, joined[8..], out); - if (resolveOs(joined, out)) |found| return found; - if (resolveVirtual(p, joined, out)) |found| return found; - // `.`, `..` and `./x` name the pane's directory, never the served tree: - // with that directory gone they name nothing (`.` would be /virtual/). - if (!dotRelative(word)) if (resolveVirtual(p, word, out)) |found| return found; - if (resolveEmbedded(word, cwd, out)) |source| { - const path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null; - return .{ .path = path }; - } - return null; -} - -/// Whether `word` is spelled relative to the directory it is looked from: -/// `.`, `..`, `./x`, `../x`. -pub fn dotRelative(word: []const u8) bool { - const w = std.mem.trimEnd(u8, word, "/"); - return std.mem.eql(u8, w, ".") or std.mem.eql(u8, w, "..") or - std.mem.startsWith(u8, word, "./") or std.mem.startsWith(u8, word, "../"); -} - -/// Where a path really is on the host, and whether it is a directory. The -/// path may lie in a mount this editor serves, so the turn is given up for -/// the syscalls: another thread answers them. -/// A path's leading `~` -- alone, or before `/` or `:` (`~/x:12`) -- is the -/// home directory: $HOME, else the passwd entry's. `~user/...` is that -/// user's. As in a shell, `~` is home even beside a file named `~` in the -/// current directory. Every entry point that takes a path the user typed -/// runs it through here: look (B3 and 9P), name, Save, ThemeFile, DumpDir, -/// Restore, a forwarded `pardes ~/x`. The path itself when there is no -/// `~` to expand, or no home for it. -pub fn expandHome(path: []const u8, out: *[4096]u8) []const u8 { - if (path.len == 0 or path[0] != '~') return path; - // Home as the session that recorded found it (src/tape.zig). - return pardes.tape.value(.env, expandHomeHost, .{ path, out }); -} - -fn expandHomeHost(path: []const u8, out: *[4096]u8) []const u8 { - return expandHomeFrom(path, out, std.c.getenv("HOME")); -} - -/// expandHome with HOME given (null: unset), so a test need not change the -/// process's environment, which a child spawned later reads. -fn expandHomeFrom(path: []const u8, out: *[4096]u8, env_home: ?[*:0]const u8) []const u8 { - if (path.len == 0 or path[0] != '~') return path; - const end = std.mem.indexOfAny(u8, path, "/:") orelse path.len; - const home = (if (end == 1) homeDir(env_home) else userHome(path[1..end])) orelse return path; - const trimmed = std.mem.trimEnd(u8, home, "/"); - const rest = path[end..]; - if (trimmed.len == 0 and (rest.len == 0 or rest[0] != '/')) return std.fmt.bufPrint(out, "/{s}", .{rest}) catch path; - return std.fmt.bufPrint(out, "{s}{s}", .{ trimmed, rest }) catch path; -} - -fn homeDir(env_home: ?[*:0]const u8) ?[]const u8 { - if (env_home) |h| if (h[0] != 0) return std.mem.span(h); - const pw = std.c.getpwuid(std.c.getuid()) orelse return null; - return std.mem.span(pw.dir orelse return null); -} - -fn userHome(name: []const u8) ?[]const u8 { - var z: [256]u8 = undefined; - const name_z = std.fmt.bufPrintSentinel(&z, "{s}", .{name}, 0) catch return null; - const pw = std.c.getpwnam(name_z) orelse return null; - return std.mem.span(pw.dir orelse return null); -} - -test "a leading ~ is home, from HOME or else the passwd entry" { - var out: [4096]u8 = undefined; - const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; - var want: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); - try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); - try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); - try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); - try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); - - // HOME unset: the passwd entry's home. - const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; - var from_passwd: [4096]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, null)); -} - -pub fn resolveOs(path: []const u8, out: *[4096]u8) ?Resolved { - if (comptime !platform_has_fs) return null; - var z: [4096]u8 = undefined; - const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return null; - return pardes.tape.site(.resolve, null, resolveHost, .{ path_z, out }); -} - -fn resolveHost(path_z: [:0]const u8, out: *[4096]u8) ?Resolved { - const resolved = realpath(path_z, out) orelse return null; - return .{ .path = std.mem.span(resolved), .dir = isDir(resolved) }; -} - -fn resolveVirtual(p: ?*pardes.Pardes, path: []const u8, out: *[4096]u8) ?Resolved { - var normalized_buf: [4096]u8 = undefined; - const normalized = normalizeVirtualPath(path, &normalized_buf) orelse return null; - if (p) |core| if (tree.resolveSelf(core, normalized) != null) - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; - if (findEmbeddedSource(normalized, false)) |source| - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{source.path}) catch return null }; - if (sources_fs.node(normalized) != null) - return .{ .path = std.fmt.bufPrint(out, "/virtual/{s}", .{normalized}) catch return null }; - return null; -} - -pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { - return readLimit(p, path, limits.max_file_bytes); +pub fn read(p: *pardes.Pardes, path: []const u8) ![]u8 { + return readLimit(p, path, limits.max_file_bytes); } pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ![]u8 { @@ -1135,40 +708,6 @@ pub fn restorePath(typed: []const u8, dir_setting: []const u8, out: *[4096]u8) [ return out[0..n]; } -test "Restore prefers default directory then falls back to original path" { - if (!platform_has_fs) return error.SkipZigTest; - const gpa = std.testing.allocator; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const relative = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/a.dump", .{tmp.sub_path}); - defer gpa.free(relative); - const base = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/dumps", .{tmp.sub_path}); - defer gpa.free(base); - const nested = try std.fmt.allocPrint(gpa, "dumps/.zig-cache/tmp/{s}", .{tmp.sub_path}); - defer gpa.free(nested); - try tmp.dir.createDirPath(std.testing.io, nested); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "dumps/a.dump", .data = "short name" }); - const short = try readRestore(gpa, "a.dump", base); - defer gpa.free(short); - try std.testing.expectEqualStrings("short name", short); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.dump", .data = "original" }); - const fallback = try readRestore(gpa, relative, base); - defer gpa.free(fallback); - try std.testing.expectEqualStrings("original", fallback); - const candidate = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, relative }); - defer gpa.free(candidate); - try writeFile(candidate, "default"); - const preferred = try readRestore(gpa, relative, base); - defer gpa.free(preferred); - try std.testing.expectEqualStrings("default", preferred); - const absolute = try tmp.dir.realPathFileAlloc(std.testing.io, "a.dump", gpa); - defer gpa.free(absolute); - const direct = try readRestore(gpa, absolute, base); - defer gpa.free(direct); - try std.testing.expectEqualStrings("original", direct); - try std.testing.expectError(error.FileNotFound, readRestore(gpa, "missing-restore-test.dump", base)); -} - fn readFileLimit(gpa: std.mem.Allocator, path: []const u8, limit: usize) ![]u8 { if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; if (!platform_has_fs or std.mem.startsWith(u8, path, "/virtual/")) { @@ -1484,6 +1023,467 @@ pub fn unmount(p: *Pardes, name: []const u8) !void { return error.NotMounted; } +test "/os refuses a rename or a mode change as not permitted, in words, and still truncates to zero" { + const p = try th.withFile(std.testing.allocator, "x\n"); + defer p.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "kept.txt", .data = "kept\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var node: u64 = os_root; + var parts = std.mem.tokenizeScalar(u8, dir, '/'); + while (parts.next()) |part| node = th.look_up(p, node, part).reply.attr.node; + node = th.look_up(p, node, "kept.txt").reply.attr.node; + for ([_]Req{ + .{ .tag = 1, .op = .setattr, .node = node, .set = .{ .mode = true } }, + .{ .tag = 2, .op = .setattr, .node = node, .set = .{ .name = true }, .data = "moved.txt" }, + }) |req| { + const r = th.call(p, req); + try std.testing.expectEqual(E.PERM, r.errno()); + try std.testing.expectStringStartsWith(r.reply.ename, "permission denied"); + } + try std.testing.expectEqual(tree.Status.ok, th.call(p, .{ .tag = 3, .op = .setattr, .node = node, .truncate = true }).reply.status); +} + +test "mounts own their names and dials and reject duplicate or reserved names" { + const gpa = std.testing.allocator; + var ns: Namespace = .{}; + defer ns.deinit(gpa); + var name = "peer".*; + var dial = "/tmp/peer.sock".*; + try ns.mount(gpa, &name, &dial); + @memset(&name, 'x'); + @memset(&dial, 'x'); + try std.testing.expectEqualStrings("peer", ns.mounts.items[0].name); + try std.testing.expectEqualStrings("/tmp/peer.sock", ns.mounts.items[0].dial); + try std.testing.expectError(error.AlreadyMounted, ns.mount(gpa, "peer", "/tmp/other.sock")); + for ([_][]const u8{ "", ".", "..", "os", "self", "a/b", "with space" }) |bad| + try std.testing.expectError(error.BadMountName, ns.mount(gpa, bad, "/tmp/peer.sock")); + for ([_][]const u8{ "", "a\x00b", "tcp!127.0.0.1!0", "tcp!localhost!564" }) |bad| + try std.testing.expectError(error.BadDial, ns.mount(gpa, "valid", bad)); + for (1..max_mounts) |i| { + var buf: [16]u8 = undefined; + try ns.mount(gpa, try std.fmt.bufPrint(&buf, "peer{d}", .{i}), "/tmp/peer.sock"); + } + try std.testing.expectEqual(max_mounts, ns.mounts.items.len); + try std.testing.expectError(error.TooManyMounts, ns.mount(gpa, "full", "/tmp/peer.sock")); +} + +test "mount allocation failures preserve prior mounts and release partial copies" { + const Check = struct { + fn run(gpa: std.mem.Allocator) !void { + var ns: Namespace = .{}; + defer ns.deinit(gpa); + try ns.mount(gpa, "first", "/tmp/first.sock"); + ns.mount(gpa, "second", "/tmp/second.sock") catch |err| { + try std.testing.expectEqual(@as(usize, 1), ns.mounts.items.len); + try std.testing.expectEqualStrings("first", ns.mounts.items[0].name); + try std.testing.expectEqualStrings("/tmp/first.sock", ns.mounts.items[0].dial); + return err; + }; + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{}); +} + +test "unmount refuses pane paths inherited directories and queued save targets" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try p.fs.mount(gpa, "peer", "/tmp/peer.sock"); + const pane = try p.setTestFile("unsaved\n"); + for ([_][]const u8{ "/n/peer", "/n/peer/file", "/n/peer/dir/file" }) |path| { + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, path); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + } + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/n/peer2/file"); + const slot = p.freeSlot().?; + const shell = try p.newShell(slot, "/n/peer/dir"); + p.setCwd(slot, "/n/peer/dir"); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + pane.cwd = .{ .inherited = shell }; + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + p.setCwd(slot, "/"); + while (p.nextEffect()) |_| {} + p.emit(.{ .save_text = .{ .pane = 0, .serial = pane.serial, .path = .from("/n/peer/pending") } }); + try std.testing.expectError(error.MountInUse, unmount(p, "peer")); + while (p.nextEffect()) |_| {} + try unmount(p, "peer"); + try std.testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); + try std.testing.expectError(error.NotMounted, unmount(p, "peer")); + try p.fs.mount(gpa, "peer", "/tmp/other.sock"); + try std.testing.expectEqualStrings("/tmp/other.sock", p.fs.mounts.items[0].dial); +} + +test "virtual writes enforce permissions even when contents are empty" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + for ([_][]const u8{ "", "bytes" }) |bytes| { + for ([_][]const u8{ "/virtual/index", "/virtual/screen", "/virtual/README" }) |path| + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); + // /log takes one word, `follow`, and only on the open it changes. + if (bytes.len > 0) if (write(p, "/n/self/log", bytes)) |_| return error.TestUnexpectedResult else |_| {}; + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/pane", bytes)); + try std.testing.expectError(error.FileNotFound, write(p, "/virtual/missing", bytes)); + try std.testing.expectError(error.FileNotFound, write(p, "/virtual/cons", bytes)); + if (limits.embedded_sources) { + for ([_][]const u8{ "/virtual/src/fs.zig", "/n/self/src/fs.zig" }) |path| + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, path, bytes)); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual/src", bytes)); + } else try std.testing.expectError(error.FileNotFound, write(p, "/virtual/src/fs.zig", bytes)); + } + for (p.fs.opens) |o| try std.testing.expect(o.node == 0); +} + +test "direct self reads and writes use the same dot paths as Look" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("old contents\n"); + var path_buf: [256]u8 = undefined; + for ([_][]const u8{ "/virtual", "/n/self" }) |root| { + const path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/{d}/../{d}/body/./", .{ root, pane.serial, pane.serial }); + try write(p, path, "replacement\n"); + try std.testing.expectEqualStrings("replacement\n", pane.file.?.content); + const bytes = try read(p, path); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(pane.file.?.content, bytes); + var resolved: [4096]u8 = undefined; + const canonical = resolve(p, path, "/", &resolved).?; + try std.testing.expectEqual(tree.resolveSelf(p, canonical.path[9..]), tree.resolveSelf(p, path[root.len..])); + try std.testing.expectEqual(@as(?u64, tree.root), tree.resolveSelf(p, "./pane/../../")); + const index_path = try std.fmt.bufPrint(&path_buf, "{s}/./pane/../index", .{root}); + try std.testing.expectError(error.ReadOnlyFilesystem, write(p, index_path, "")); + const index = try read(p, index_path); + defer gpa.free(index); + try std.testing.expect(std.mem.indexOf(u8, index, "/test.txt") != null); + } + var overlong: [4110]u8 = @splat('x'); + @memcpy(overlong[0..9], "/virtual/"); + var resolved: [4096]u8 = undefined; + try std.testing.expect(resolve(p, &overlong, "/", &resolved) == null); + try std.testing.expect(tree.resolveSelf(p, overlong[9..]) == null); + try std.testing.expectError(error.FileNotFound, write(p, &overlong, "")); +} + +test "self files share the regular file limit without preallocating it" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const contents = try gpa.alloc(u8, limits.max_stream_bytes + 17); + defer gpa.free(contents); + @memset(contents, 'x'); + const pane = try p.setTestFile(contents); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); + const bytes = try read(p, path); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, contents, bytes); +} + +test "bounded reads accept exact OS file lengths and empty files" { + if (!platform_has_fs) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var contents: [8209]u8 = @splat('x'); + contents[contents.len - 1] = '\n'; + for ([_][]const u8{ &contents, "" }) |expected| { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "limited.txt", .data = expected }); + var path_buf: [4096]u8 = undefined; + const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "limited.txt", &path_buf)]; + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); + for ([_][]const u8{ native, explicit }) |path| { + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, expected, bytes); + if (expected.len > 0) { + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + } + } + try tmp.dir.createDir(std.testing.io, "empty", .default_dir); + var path_buf: [4096]u8 = undefined; + const native = path_buf[0..try tmp.dir.realPathFile(std.testing.io, "empty", &path_buf)]; + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{native}); + const empty = try readLimit(p, explicit, 0); + defer gpa.free(empty); + try std.testing.expectEqual(@as(usize, 0), empty.len); + // The directory's node stays in the table for the listener to collect + // once no connection names it (src/9p_io.zig, collectOs): a client may + // have walked to the same directory meanwhile and hold it by that node. + try std.testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len); + try std.testing.expectEqualStrings(native, p.fs.os_paths.items[0].path); +} + +test "bounded reads apply the same limits to self bodies and embedded sources" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + var contents: [8209]u8 = @splat('x'); + contents[contents.len - 1] = '\n'; + for ([_][]const u8{ &contents, "" }) |expected| { + const pane = try p.setTestFile(expected); + for ([_][]const u8{ "/virtual", "/n/self" }) |prefix| { + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/pane/{d}/body", .{ prefix, pane.serial }); + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualSlices(u8, expected, bytes); + if (expected.len > 0) { + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + try std.testing.expectEqualSlices(u8, expected, pane.file.?.content); + } + } + if (limits.embedded_sources) { + const source = findEmbeddedSource("src/look.zig", false).?; + for ([_][]const u8{ "/virtual/src/look.zig", "/n/self/src/look.zig" }) |path| { + const bytes = try readLimit(p, path, source.contents.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(source.contents, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, source.contents.len - 1)); + } + const bytes = try readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(source.contents, bytes); + try std.testing.expectError(error.FileTooLarge, readFileLimit(gpa, "/virtual/src/look.zig", source.contents.len - 1)); + } +} + +test "bounded reads count rendered directory paths and unknown self lengths" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + p.fs.socket_path = "/tmp/pardes-limited-in-process.sock"; // so listeners has a line + for ([_][]const u8{ "/n", "/virtual", "/n/self", "/virtual/pane", "/virtual/listeners", "/virtual/README" }) |path| { + const expected = try read(p, path); + defer gpa.free(expected); + try std.testing.expect(expected.len > 0); + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } + try std.testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len); +} + +test "bounded reads release terminal snapshots after success and size refusal" { + const gpa = std.testing.allocator; + const p = try th.withTerm(gpa); + defer p.deinit(); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{th.serialOf(p)}); + const empty = try readLimit(p, path, 0); + defer gpa.free(empty); + try std.testing.expectEqual(@as(usize, 0), empty.len); + p.update(.{ .output = .{ .pane = 0, .bytes = "limited terminal output" } }); + const expected = "limited terminal output\n"; // a line ends with its newline + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + for (p.fs.opens) |o| try std.testing.expectEqual(@as(u64, 0), o.node); +} + +test "bounded reads probe size-unknown proc files at the exact limit" { + if (!platform_has_fs or @import("builtin").os.tag != .linux) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const expected = read(p, "/proc/version") catch |err| return switch (err) { + error.FileNotFound, error.PermissionDenied => error.SkipZigTest, + else => err, + }; + defer gpa.free(expected); + try std.testing.expect(expected.len > 0); + var storage: [256 * 1024]u8 = undefined; + var fixed = std.heap.FixedBufferAllocator.init(&storage); + const bounded = try readFileLimit(fixed.allocator(), "/proc/version", limits.max_stream_bytes); + try std.testing.expectEqualStrings(expected, bounded); + fixed.allocator().free(bounded); + for ([_][]const u8{ "/proc/version", "/n/os/proc/version" }) |path| { + const bytes = try readLimit(p, path, expected.len); + defer gpa.free(bytes); + try std.testing.expectEqualStrings(expected, bytes); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, expected.len - 1)); + try std.testing.expectError(error.FileTooLarge, readLimit(p, path, 0)); + } +} + +test "self file reads release partial allocations when memory runs out" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const contents = try gpa.alloc(u8, 65537); + defer gpa.free(contents); + @memset(contents, 'x'); + const pane = try p.setTestFile(contents); + var path_buf: [128]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{pane.serial}); + const Read = struct { + fn run(allocator: std.mem.Allocator, core: *Pardes, name: []const u8) !void { + const original = core.gpa; + core.gpa = allocator; + defer core.gpa = original; + const bytes = read(core, name) catch |err| return switch (err) { + error.WriteFailed => error.OutOfMemory, + else => err, + }; + defer allocator.free(bytes); + try std.testing.expectEqual(@as(usize, 65537), bytes.len); + } + }; + try std.testing.checkAllAllocationFailures(gpa, Read.run, .{ p, path }); + try std.testing.expectEqualSlices(u8, contents, pane.file.?.content); +} + +test "oversized OS files fail before allocating their contents" { + if (!platform_has_fs) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const file = try tmp.dir.createFile(std.testing.io, "oversized", .{}); + defer file.close(std.testing.io); + try file.setLength(std.testing.io, limits.max_file_bytes + 1); + var path_buf: [4096]u8 = undefined; + const path_len = try tmp.dir.realPathFile(std.testing.io, "oversized", &path_buf); + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 }); + try std.testing.expectError(error.FileTooLarge, readFile(failing.allocator(), path_buf[0..path_len])); + try std.testing.expectEqual(@as(usize, 0), failing.allocations); +} + +test "filesystem roots list their namespaces without dialing remote mounts" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + try p.fs.mount(gpa, "peer", "unavailable-session"); + for ([_][]const u8{ "/n", "/n/", "/n///" }) |path| { + const contents = try read(p, path); + defer gpa.free(contents); + try std.testing.expectEqualStrings("/n/os/\n/n/self/\n/n/peer/\n", contents); + var buf: [4096]u8 = undefined; + try std.testing.expectEqualStrings("/n", resolve(p, path, "/", &buf).?.path); + try std.testing.expectError(error.IsDirectory, write(p, path, "")); + } + const bare = try read(p, "/virtual"); + defer gpa.free(bare); + const slashed = try read(p, "/virtual/"); + defer gpa.free(slashed); + try std.testing.expectEqualStrings(bare, slashed); + try std.testing.expect(std.mem.indexOf(u8, bare, "/virtual/index\n") != null); + try std.testing.expectError(error.IsDirectory, write(p, "/virtual", "")); +} + +test "virtual body writes can read their input from the same pane" { + const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("same pane contents\n"); + const event_node = tree.Node.of(pane.serial, .event); + _ = tree.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = event_node }); + var path_buffer: [64]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buffer, "/virtual/pane/{d}/body", .{pane.serial}); + try write(p, path, pane.file.?.content); + try std.testing.expectEqualStrings("same pane contents\n", pane.file.?.content); + // The truncation and the write are one undo step. + try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.journal.done); + const events = &p.panes[p.view().active].?.fs.events; + try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "ED")); + events.pop(); + try std.testing.expect(std.mem.startsWith(u8, events.peek().?, "EI")); + events.pop(); + try std.testing.expect(events.empty()); + try write(p, path, pane.file.?.content[5..]); + try std.testing.expectEqualStrings("pane contents\n", pane.file.?.content); +} + +test "a path with a part over 255 bytes is NameTooLong, never a panic" { + const long = "/tmp/" ++ &@as([300]u8, @splat('x')) ++ "/f"; + try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); +} + +test "a directory under one that may not be searched or written is denied, one merely missing is not" { + // The refusing directory is Linux's /proc/1/root. + if (comptime @import("builtin").os.tag == .linux) try std.testing.expect(deniedAbove("/proc/1/root/x/y")); + try std.testing.expect(!deniedAbove("/tmp/pardes-surely-missing-dir/a/b")); +} + +test "explicit OS paths retain their namespace until an OS boundary" { + for ([_]struct { declared: []const u8, native: ?[]const u8 }{ + .{ .declared = "/n/os", .native = "/" }, + .{ .declared = "/n/os/project/file", .native = "/project/file" }, + .{ .declared = "/n/os/virtual/index", .native = "/virtual/index" }, + .{ .declared = "/n/os/n/self/index", .native = "/n/self/index" }, + .{ .declared = "/n/self/index", .native = null }, + .{ .declared = "/n/peer/os/project/file", .native = null }, + .{ .declared = "/virtual/index", .native = null }, + .{ .declared = "/project/file", .native = "/project/file" }, + }) |case| { + const native = localPath(case.declared); + if (case.native) |expected| try std.testing.expectEqualStrings(expected, native.?) else try std.testing.expect(native == null); + } +} + +test "a leading ~ is home, from HOME or else the passwd entry" { + var out: [4096]u8 = undefined; + const home = homeDir(std.c.getenv("HOME")) orelse return error.SkipZigTest; + var want: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "{s}/x:12", .{std.mem.trimEnd(u8, home, "/")}), expandHome("~/x:12", &out)); + try std.testing.expectEqualStrings(std.mem.trimEnd(u8, home, "/"), expandHome("~", &out)); + try std.testing.expectEqualStrings("a/~/b", expandHome("a/~/b", &out)); + try std.testing.expectEqualStrings("~no-such-user-pardes/x", expandHome("~no-such-user-pardes/x", &out)); + try std.testing.expectEqualStrings("/", expandHome("~root", &out)[0..1]); + + // HOME unset: the passwd entry's home. + const pw = std.c.getpwuid(std.c.getuid()) orelse return error.SkipZigTest; + var from_passwd: [4096]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&from_passwd, "{s}/y", .{std.mem.trimEnd(u8, std.mem.span(pw.dir.?), "/")}), expandHomeFrom("~/y", &out, null)); +} + +test "Restore prefers default directory then falls back to original path" { + if (!platform_has_fs) return error.SkipZigTest; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const relative = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/a.dump", .{tmp.sub_path}); + defer gpa.free(relative); + const base = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}/dumps", .{tmp.sub_path}); + defer gpa.free(base); + const nested = try std.fmt.allocPrint(gpa, "dumps/.zig-cache/tmp/{s}", .{tmp.sub_path}); + defer gpa.free(nested); + try tmp.dir.createDirPath(std.testing.io, nested); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "dumps/a.dump", .data = "short name" }); + const short = try readRestore(gpa, "a.dump", base); + defer gpa.free(short); + try std.testing.expectEqualStrings("short name", short); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "a.dump", .data = "original" }); + const fallback = try readRestore(gpa, relative, base); + defer gpa.free(fallback); + try std.testing.expectEqualStrings("original", fallback); + const candidate = try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, relative }); + defer gpa.free(candidate); + try writeFile(candidate, "default"); + const preferred = try readRestore(gpa, relative, base); + defer gpa.free(preferred); + try std.testing.expectEqualStrings("default", preferred); + const absolute = try tmp.dir.realPathFileAlloc(std.testing.io, "a.dump", gpa); + defer gpa.free(absolute); + const direct = try readRestore(gpa, absolute, base); + defer gpa.free(direct); + try std.testing.expectEqualStrings("original", direct); + try std.testing.expectError(error.FileNotFound, readRestore(gpa, "missing-restore-test.dump", base)); +} + test { _ = tree; } -- cgit v1.3