diff options
Diffstat (limited to 'core/fs.zig')
| -rw-r--r-- | core/fs.zig | 1522 |
1 files changed, 1522 insertions, 0 deletions
diff --git a/core/fs.zig b/core/fs.zig new file mode 100644 index 00000000..333588ce --- /dev/null +++ b/core/fs.zig @@ -0,0 +1,1522 @@ +const std = @import("std"); +const limits = @import("memory.zig").limits; +/// libc: opens with O_NONBLOCK (a FIFO must not hang the editor), which std.Io's open has no flag for, and errno mapped to fs's own errors. +const libc = std.c; +const pardes = @import("root.zig"); +const config = @import("config.zig"); +const lsp = @import("lsp/lsp.zig"); +const ninep_io = @import("runtime").ninep_io; +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const look = @import("look.zig"); +pub const tree = @import("ninep/tree.zig"); +const sources_fs = @import("ninep/sources.zig"); +const th = @import("ninep/testing.zig"); + +const Pardes = pardes.Pardes; +const MAX_PANES = pardes.MAX_PANES; +const Req = tree.Req; +const Reply = tree.Reply; +const E = tree.E; + +/// The tree's README, which tree.zig answers; a build that embeds no +/// sources lists no src/. +pub const help = help: { + const raw = @embedFile("fs-help.txt"); + if (limits.embedded_sources) break :help raw; + const both = "os/, src/ the host filesystem; the editor's own sources"; + const at = std.mem.indexOf(u8, raw, both) orelse @compileError("fs-help.txt no longer lists os/, src/"); + break :help raw[0..at] ++ "os/ the host filesystem" ++ raw[at + both.len ..]; +}; + +/// Host filesystem nodes: the root, and one hashed node per path a client walked to. +pub const os_root: u64 = (1 << 63) + 2; +pub const os_node: u64 = 1 << 62; + +pub const name_capacity: usize = 255; + +pub const Source = struct { path: []const u8, contents: []const u8 }; +pub const sources: []const Source = if (limits.embedded_sources) &source_files else &.{}; +const source_files = [_]Source{ + .{ .path = "src/pardes.zig", .contents = @embedFile("root.zig") }, + .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/Text.zig", .contents = @embedFile("Text.zig") }, + .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, + .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, + .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, + .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, + .{ .path = "src/tagline.zig", .contents = @embedFile("tagline.zig") }, + .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, + .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, + .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, + .{ .path = "src/exec.zig", .contents = @embedFile("exec.zig") }, + .{ .path = "src/Pipe.zig", .contents = @embedFile("Pipe.zig") }, + .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, + .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, + .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, + .{ .path = "src/term/terminal.zig", .contents = @embedFile("term/terminal.zig") }, + .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, + .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, + .{ .path = "src/look.zig", .contents = @embedFile("look.zig") }, + .{ .path = "src/9p.zig", .contents = @embedFile("runtime/9p.zig") }, + .{ .path = "src/9p_io.zig", .contents = @embedFile("runtime/9p_io.zig") }, + .{ .path = "src/host_io.zig", .contents = @embedFile("dev/host_io.zig") }, + .{ .path = "src/config.zig", .contents = @embedFile("config.zig") }, + .{ .path = "src/main.zig", .contents = @embedFile("runtime/main.zig") }, + .{ .path = "src/builtins.zig", .contents = @embedFile("builtins.zig") }, + .{ .path = "src/grammar_manifest.zig", .contents = @embedFile("grammar_manifest.zig") }, + .{ .path = "src/CHANGELOG.md", .contents = @embedFile("CHANGELOG.md") }, +}; + +pub fn sourceBytes(path: []const u8) ?[]const u8 { + for (sources) |entry| if (std.mem.eql(u8, entry.path, path)) return entry.contents; + return null; +} + +pub const WriteError = error{ + PathTooLong, + PermissionDenied, + IsDirectory, + ReadOnlyFilesystem, + NoSpaceLeft, + OpenFailed, + WriteFailed, + // The rest are open(2)'s errno, named so errorWords says them. + NoSuchFileOrDirectory, + NotDir, + InvalidArgument, + FileBusy, + SymLinkLoop, + NoSuchDeviceOrAddress, + FileTooBig, +}; + +/// The host takes the bytes. The caller has given the turn up (`write`), +/// because the path may be a mount this editor serves. +pub fn writeFile(path: []const u8, bytes: []const u8) WriteError!void { + var pathbuf: [4096:0]u8 = undefined; + if (path.len >= pathbuf.len) return error.PathTooLong; + if (std.mem.indexOfScalar(u8, path, 0) != null) return error.OpenFailed; + @memcpy(pathbuf[0..path.len], path); + pathbuf[path.len] = 0; + const fd = libc.open(pathbuf[0..path.len :0], .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644)); + if (fd < 0) return switch (libc.errno(fd)) { + .ACCES, .PERM => error.PermissionDenied, + .ISDIR => error.IsDirectory, + .ROFS => error.ReadOnlyFilesystem, + .NOSPC, .DQUOT => error.NoSpaceLeft, + .NAMETOOLONG => error.PathTooLong, + .NOENT => error.NoSuchFileOrDirectory, + .NOTDIR => error.NotDir, + .INVAL => error.InvalidArgument, + .BUSY, .TXTBSY => error.FileBusy, + .LOOP => error.SymLinkLoop, + .NXIO, .NODEV => error.NoSuchDeviceOrAddress, + .FBIG => error.FileTooBig, + else => error.OpenFailed, + }; + var off: usize = 0; + var wrote = true; + while (off < bytes.len) { + const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) { + wrote = false; + break; + } + off += @intCast(n); + } + const closed = libc.close(fd) == 0; + if (!wrote or !closed) return error.WriteFailed; +} + +extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8; + +pub const Mount = struct { name: []const u8, dial: []const u8 }; +pub const max_mounts = 8; +pub const Resolved = struct { path: []const u8, dir: bool = false }; +pub const OsPath = struct { node: u64, path: []const u8 }; + +fn osPath(p: *pardes.Pardes, node: u64) ?[]const u8 { + if (node == os_root) return "/"; + for (p.fs.os_paths.items) |entry| if (entry.node == node) return entry.path; + return null; +} + +fn osNode(p: *pardes.Pardes, path: []const u8) !u64 { + if (std.mem.eql(u8, path, "/")) return os_root; + const node = os_node | (std.hash.Wyhash.hash(0, path) & (os_node - 1)); + for (p.fs.os_paths.items) |entry| { + if (std.mem.eql(u8, entry.path, path)) return entry.node; + if (entry.node == node) return error.NodeCollision; + } + if (p.fs.os_paths.items.len == 4096) return error.TooManyFiles; + const saved = try p.gpa.dupe(u8, path); + errdefer p.gpa.free(saved); + try p.fs.os_paths.append(p.gpa, .{ .node = node, .path = saved }); + return node; +} + +/// The host filesystem under /os. Every syscall here may go out through a +/// mount this editor serves, so the turn is given up around each and taken +/// back before the core is touched; `path` is the table entry's own copy and +/// outlives the yield, and nothing is staged into the shared reply buffer +/// until the turn is back. +pub fn osHandle(p: *pardes.Pardes, req: Req) Reply { + if (comptime !platform_has_fs) return Reply.fail(req.tag, E.NOENT); + const path = osPath(p, req.node) orelse return Reply.fail(req.tag, E.NOENT); + if (req.op == .release) return .{ .tag = req.tag }; + const io = std.Io.Threaded.global_single_threaded.io(); + const stat = pardes.tape.site(.os_stat, null, osStat, .{ io, path }) catch return Reply.fail(req.tag, E.NOENT); + const attr: Reply.Attr = .{ .name = if (req.node == os_root) "os" else std.Io.Dir.path.basename(path), .node = req.node, .dir = stat.kind == .directory, .size = stat.size, .mode = if (stat.kind == .directory) 0o755 else 0o644, .mtime = stat.mtime }; + switch (req.op) { + .getattr => return .{ .tag = req.tag, .attr = attr }, + .open => { + if (stat.kind != .file and stat.kind != .directory) return Reply.fail(req.tag, E.PERM); + return .{ .tag = req.tag, .handle = 1 }; + }, + .lookup => { + if (stat.kind != .directory) return Reply.fail(req.tag, E.NOTDIR); + if (req.node == os_root and std.mem.eql(u8, req.data, "..")) + return tree.handle(p, .{ .tag = req.tag, .op = .getattr, .node = tree.root }); + if (req.data.len == 0 or std.mem.indexOfAny(u8, req.data, "/\x00") != null) return Reply.fail(req.tag, E.NOENT); + var buf: [4096]u8 = undefined; + const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), req.data }) catch return Reply.fail(req.tag, E.NOENT); + var normalized_buf: [4096]u8 = undefined; + const normalized = resolveOs(joined, &normalized_buf) orelse return Reply.fail(req.tag, E.NOENT); + const node = osNode(p, normalized.path) catch return Reply.fail(req.tag, E.NFILE); + return osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = node }); + }, + .readdir => { + // Listed into a buffer of this request's own first; the shared + // reply buffer is another request's to use while the turn is out. + var listing: [16 * 1024]u8 = undefined; + const listed = pardes.tape.site(.os_listing, null, osListing, .{ io, path, req.off, req.size, &listing }) catch |err| + return Reply.fail(req.tag, if (err == error.NotDir) E.NOTDIR else E.IO); + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, listed) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(out.items.len) } }; + }, + .read, .write, .setattr => { + // A rename or a mode change (`mv`, `chmod`) is refused as not + // permitted, EACCES through a mount: /os reads and writes the + // files it shows and changes nothing about them. + if (req.op == .setattr and (req.set.name or req.set.mode)) + return tree.failText(req.tag, E.PERM, "permission denied: /os renames nothing and changes no mode"); + if (stat.kind != .file) return Reply.fail(req.tag, E.PERM); + var z: [4096]u8 = undefined; + const path_z = std.fmt.bufPrintSentinel(&z, "{s}", .{path}, 0) catch return Reply.fail(req.tag, E.NOENT); + var buf: [ninep_io.msize]u8 = undefined; // a read never asks for more than a frame + const got = switch (pardes.tape.site(.os_rw, null, osReadWrite, .{ path_z, req, attr, &buf })) { + .reply => |reply| return reply, + .read => |bytes| bytes, + }; + const out = p.fs.stage(p.gpa); + out.appendSlice(p.gpa, got) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .payload = .{ .staged = @intCast(got.len) } }; + }, + else => return Reply.fail(req.tag, E.PERM), + } +} + +/// What /os keeps of a stat, as the tape carries it to a replica: the same +/// bytes on every OS, which std.Io.File.Stat is not (a FreeBSD one's +/// `nlink` and `permissions` are another width than a Linux one's). +pub const OsStat = struct { kind: std.Io.File.Kind, size: u64, mtime: u32 }; + +fn osStat(io: std.Io, path: []const u8) !OsStat { + const stat = try statPath(io, path, .{}); + return .{ .kind = stat.kind, .size = stat.size, .mtime = std.math.cast(u32, stat.mtime.toSeconds()) orelse 0 }; +} + +/// A directory's listing under /os, the entries from `off` until `size` +/// bytes of them are staged, into `listing`: the syscalls of a readdir. +fn osListing(io: std.Io, path: []const u8, off: u64, size: u32, listing: *[16 * 1024]u8) error{ NotDir, Io }![]const u8 { + var fixed: std.heap.FixedBufferAllocator = .init(listing); + var listed: std.ArrayList(u8) = .empty; + var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return error.NotDir; + defer dir.close(io); + var it = dir.iterate(); + var skip = off; + while (it.next(io) catch return error.Io) |entry| { + var buf: [4096]u8 = undefined; + const joined = std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), entry.name }) catch continue; + var normalized_buf: [4096]u8 = undefined; + const normalized = resolveOs(joined, &normalized_buf) orelse continue; + const child = dir.statFile(io, entry.name, .{}) catch continue; + if (skip > 0) { + skip -= 1; + continue; + } + const node = if (std.mem.eql(u8, normalized.path, "/")) os_root else os_node | (std.hash.Wyhash.hash(0, normalized.path) & (os_node - 1)); + // The listing's buffer is full: it ends here, the next read goes on. + tree.stageDirent(&listed, fixed.allocator(), node, child.kind == .directory, entry.name) catch break; + if (listed.items.len >= @max(size, 512)) break; + } + return listed.items; +} + +pub const OsReadWrite = union(enum) { reply: Reply, read: []const u8 }; + +/// The syscalls of an /os read, write or truncate: the reply, or the bytes +/// read into `buf`. +fn osReadWrite(path_z: [:0]const u8, req: Req, attr: Reply.Attr, buf: []u8) OsReadWrite { + const fd = libc.open(path_z, .{ .ACCMODE = if (req.op == .read) .RDONLY else .WRONLY, .NONBLOCK = true, .CLOEXEC = true }); + if (fd < 0) return .{ .reply = Reply.fail(req.tag, E.PERM) }; + defer _ = libc.close(fd); + if (req.op == .setattr) { + if (!req.truncate or req.off != 0 or libc.ftruncate(fd, 0) != 0) return .{ .reply = tree.failText(req.tag, E.INVAL, "invalid truncate: only to zero") }; + var truncated = attr; + truncated.size = 0; + return .{ .reply = .{ .tag = req.tag, .attr = truncated } }; + } + if (req.off > std.math.maxInt(i64)) return .{ .reply = tree.failText(req.tag, E.INVAL, "invalid offset: past what a file may hold") }; + if (libc.lseek(fd, @intCast(req.off), libc.SEEK.SET) < 0) return .{ .reply = Reply.fail(req.tag, E.IO) }; + if (req.op == .write) { + const written = libc.write(fd, req.data.ptr, req.data.len); + if (written < 0) return .{ .reply = Reply.fail(req.tag, E.IO) }; + return .{ .reply = .{ .tag = req.tag, .written = @intCast(written) } }; + } + const got = libc.read(fd, buf.ptr, @min(req.size, buf.len)); + if (got < 0) return .{ .reply = Reply.fail(req.tag, E.IO) }; + return .{ .read = buf[0..@intCast(got)] }; +} + +pub fn validMountName(name: []const u8) bool { + if (name.len == 0 or name.len > name_capacity or std.meta.stringToEnum(enum { @".", @"..", os, self }, name) != null) return false; + for (name) |c| if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-' and c != '.') return false; + return true; +} + +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/"); +} + +/// 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); +} + +/// 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 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; +} + +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; +} + +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 (core/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); +} + +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; +} + +/// What reading a file through the namespace fails with: the disk's, a +/// peer's (Client.readMount), the served tree's. +pub const ReadError = error{ Timeout, WriteFailed, PermissionDenied, FileNotFound, ReadFailed, OutOfMemory, Dial, BadDial, FileTooLarge, NodeCollision, TooManyFiles, OpenFailed, NotAFile, PathTooLong, IsDirectory, PathTooDeep, Hangup, Botch, Remote, NotFound }; + +pub fn read(p: *pardes.Pardes, path: []const u8) ReadError![]u8 { + return readLimit(p, path, limits.max_file_bytes); +} + +pub fn readLimit(p: *pardes.Pardes, path: []const u8, max_bytes: usize) ReadError![]u8 { + const limit = @min(max_bytes, limits.max_file_bytes); + if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + if (limit < "/n/os/\n/n/self/\n".len) return error.FileTooLarge; + try out.writer.writeAll("/n/os/\n/n/self/\n"); + for (p.fs.mounts.items) |mount| { + if (mount.name.len + 5 > limit - out.written().len) return error.FileTooLarge; + try out.writer.print("/n/{s}/\n", .{mount.name}); + } + return out.toOwnedSlice(); + } + if (std.mem.eql(u8, path, "/virtual")) return readNode(p, tree.root, path, limit); + if (std.mem.startsWith(u8, path, "/n/")) { + const explicit = path[3..]; + const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; + const name = explicit[0..cut]; + const remote_path = if (cut < explicit.len) explicit[cut..] else "/"; + if (std.mem.eql(u8, name, "os")) { + var native_buf: [4096]u8 = undefined; + const native = resolveOs(remote_path, &native_buf) orelse return readFileLimit(p.gpa, path, limit); + if (!native.dir) return readFileLimit(p.gpa, path, limit); + // The node stays in the table until no connection names it either + // (runtime/9p_io.zig, collectOs): a client may have walked to it too. + const node = try osNode(p, native.path); + return readNode(p, node, path, limit); + } + if (std.mem.eql(u8, name, "self")) { + const node = tree.resolveSelf(p, remote_path) orelse return error.FileNotFound; + return readNode(p, node, path, limit); + } + for (p.fs.mounts.items) |mount| { + if (!std.mem.eql(u8, name, mount.name)) continue; + // A peer answers on its own time, and the peer may be this very + // editor: the turn goes out with the request. + return pardes.tape.site(.read_mount, p.gpa, ninep_io.Client.readMount, .{ p.gpa, mount.dial, remote_path, path, limit }); + } + return error.FileNotFound; + } + if (std.mem.startsWith(u8, path, "/virtual/")) { + const name = path[9..]; + if (tree.resolveSelf(p, name)) |node| return readNode(p, node, path, limit); + } + return readFileLimit(p.gpa, path, limit); +} + +fn readNode(p: *pardes.Pardes, initial_node: u64, path: []const u8, limit: usize) ![]u8 { + var node = initial_node; + const attr = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + if (attr.status != .ok) return error.FileNotFound; + if (attr.attr.dir) { + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + var index: u64 = 0; + const max_bytes = @min(limit, limits.max_stream_bytes); + const prefix = std.mem.trimEnd(u8, path, "/"); + while (true) { + const reply = tree.handle(p, .{ .tag = 0, .op = .readdir, .node = node, .off = index, .size = 8192 }); + if (reply.status != .ok) return error.ReadFailed; + const entries = p.fsPayload(reply); + if (entries.len == 0) return out.toOwnedSlice(); + var off: usize = 0; + while (off + 10 <= entries.len) { + const len: usize = entries[off + 9]; + if (off + 10 + len > entries.len) return error.ReadFailed; + const row_len = prefix.len + len + 2 + @as(usize, @intFromBool(entries[off + 8] != 0)); + if (row_len > max_bytes - out.written().len) return error.FileTooLarge; + try out.writer.print("{s}/{s}", .{ prefix, entries[off + 10 ..][0..len] }); + if (entries[off + 8] != 0) try out.writer.writeByte('/'); + try out.writer.writeByte('\n'); + off += 10 + len; + index += 1; + } + if (off != entries.len) return error.ReadFailed; + } + } + if (attr.attr.size > limit) return error.FileTooLarge; + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); + if (opened.status != .ok) return error.OpenFailed; + if (opened.attr.node != 0) node = opened.attr.node; + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + while (true) { + const want: u32 = @intCast(@min(8192, limit + 1 - out.written().len)); + const reply = tree.handle(p, .{ .tag = 0, .op = .read, .node = node, .handle = opened.handle, .off = out.written().len, .size = want }); + if (reply.status == .again) return error.NotAFile; + if (reply.status != .ok) return error.ReadFailed; + const bytes = p.fsPayload(reply); + if (bytes.len == 0) return out.toOwnedSlice(); + if (bytes.len > limit - out.written().len) return error.FileTooLarge; + try out.writer.writeAll(bytes); + } +} + +/// The editor's, between steps: a save or a dump the shell is performing, +/// never a step of the core. +pub fn write(p: *pardes.Pardes, path: []const u8, bytes: []const u8) !void { + if (std.mem.eql(u8, std.mem.trimEnd(u8, path, "/"), "/n")) return error.IsDirectory; + if (std.mem.eql(u8, path, "/virtual")) return writeSelf(p, "", bytes); + if (std.mem.startsWith(u8, path, "/virtual/")) return writeSelf(p, path[9..], bytes); + if (!std.mem.startsWith(u8, path, "/n/")) return writeOut(p, null, path, bytes); + const explicit = path[3..]; + const cut = std.mem.indexOfScalar(u8, explicit, '/') orelse explicit.len; + const name = explicit[0..cut]; + const remote_path = if (cut < explicit.len) explicit[cut..] else "/"; + if (std.mem.eql(u8, name, "os")) return writeOut(p, null, remote_path, bytes); + if (std.mem.eql(u8, name, "self")) return writeSelf(p, remote_path, bytes); + for (p.fs.mounts.items) |mount| { + if (std.mem.eql(u8, name, mount.name)) return writeOut(p, mount.dial, remote_path, bytes); + } + return error.FileNotFound; +} + +/// The host, or the peer at `dial`, takes the bytes with the turn given up +/// entirely -- the peer may be this very editor, and a write it serves may +/// change any pane -- so they are copied first: `bytes` is usually a pane's +/// own text. +fn writeOut(p: *pardes.Pardes, dial: ?[]const u8, path: []const u8, bytes: []const u8) !void { + const copy = try p.gpa.dupe(u8, bytes); + defer p.gpa.free(copy); + pardes.turn.rest(); + defer pardes.turn.wake(); + if (dial) |d| return ninep_io.Client.writeMount(p.gpa, d, path, copy); + return writeFile(path, copy); +} + +/// This editor's own tree, written in place. +fn writeSelf(p: *pardes.Pardes, name: []const u8, bytes: []const u8) !void { + var node = tree.resolveSelf(p, name) orelse return error.FileNotFound; + const attributes = tree.handle(p, .{ .tag = 0, .op = .getattr, .node = node }); + if (attributes.status != .ok) return error.FileNotFound; + if (attributes.attr.dir) return error.IsDirectory; + if (attributes.attr.mode & 0o200 == 0) return error.ReadOnlyFilesystem; + const opened = tree.handle(p, .{ .tag = 0, .op = .open, .node = node }); + if (opened.status != .ok) return error.OpenFailed; + if (opened.attr.node != 0) node = opened.attr.node; + defer _ = tree.handle(p, .{ .tag = 0, .op = .release, .node = node, .handle = opened.handle }); + var preserved: ?[]u8 = null; + defer if (preserved) |copy| p.gpa.free(copy); + const target = tree.Node.target(node); + if (target != null and target.? == .pane and target.?.pane.file == .body) { + preserved = try p.gpa.dupe(u8, bytes); + const trunc = tree.handle(p, .{ .tag = 0, .op = .setattr, .node = node, .truncate = true }); + if (trunc.status != .ok) return error.WriteFailed; + } + const contents = preserved orelse bytes; + var off: usize = 0; + while (off < contents.len) { + const reply = tree.handle(p, .{ .tag = 0, .op = .write, .node = node, .off = off, .data = contents[off..] }); + if (reply.status != .ok or reply.written == 0) return error.WriteFailed; + off += reply.written; + } +} + +fn resolveEmbedded(word: []const u8, cwd: []const u8, scratch: *[4096]u8) ?Source { + var wordbuf: [4096]u8 = undefined; + const normalized_word = normalizeVirtualPath(word, &wordbuf) orelse return null; + if (word.len > 0 and word[0] == '/') return findEmbeddedSource(normalized_word, true); + + var joined: [4096]u8 = undefined; + if (std.fmt.bufPrint(&joined, "{s}/{s}", .{ cwd, word }) catch null) |candidate| + if (normalizeVirtualPath(candidate, scratch)) |normalized| + if (findEmbeddedSource(normalized, true)) |source| return source; + return findEmbeddedSource(normalized_word, false); +} + +pub fn normalizeVirtualPath(path: []const u8, out: *[4096]u8) ?[]const u8 { + if (std.mem.indexOfScalar(u8, path, 0) != null) return null; + var len: usize = 0; + var parts = std.mem.tokenizeAny(u8, path, "/\\"); + while (parts.next()) |part| { + if (std.mem.eql(u8, part, ".")) continue; + if (std.mem.eql(u8, part, "..")) { + while (len > 0 and out[len - 1] != '/') len -= 1; + if (len > 0) len -= 1; + continue; + } + const extra = part.len + @intFromBool(len != 0); + if (len + extra > out.len) return null; + if (len != 0) { + out[len] = '/'; + len += 1; + } + @memcpy(out[len..][0..part.len], part); + len += part.len; + } + return out[0..len]; +} + +fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source { + for (sources) |source| + if (std.mem.eql(u8, source.path, path)) return source; + if (!allow_root_suffix) return null; + for (sources) |source| { + if (path.len <= source.path.len or path[path.len - source.path.len - 1] != '/') continue; + if (std.mem.endsWith(u8, path, source.path)) return source; + } + return null; +} + +pub const platform_has_fs = !pardes.isolated; + +fn isDir(path: [*:0]const u8) bool { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .DIRECTORY = true, .CLOEXEC = true }); + if (fd < 0) return false; + _ = libc.close(fd); + return true; +} + +pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { + return readFileLimit(gpa, path, limits.max_file_bytes); +} + +/// The file a Restore of `typed` reads (restorePath), whole. +pub fn readRestore(gpa: std.mem.Allocator, typed: []const u8, dir_setting: []const u8) ![]u8 { + var buf: [4096]u8 = undefined; + return readFile(gpa, restorePath(typed, dir_setting, &buf)); +} + +/// The file a Restore of `typed` reads, whole: `~` expanded, a relative name +/// the DumpDir's when one is there, else the current directory's. What the +/// log and the message say, not the name as typed. `typed` itself (home +/// expanded) when nothing resolves: the read then says why. +pub fn restorePath(typed: []const u8, dir_setting: []const u8, out: *[4096]u8) []const u8 { + var home_buf: [4096]u8 = undefined; + const path = expandHome(typed, &home_buf); + if (!std.Io.Dir.path.isAbsolute(path)) { + var dir_buf: [4096]u8 = undefined; + if (@import("dump.zig").directory(&dir_buf, dir_setting)) |base| { + var buf: [4096]u8 = undefined; + if (std.fmt.bufPrint(&buf, "{s}/{s}", .{ base, path })) |candidate| { + if (resolveOs(candidate, out)) |r| if (!r.dir) return r.path; + } else |_| {} + } + } + if (resolveOs(path, out)) |r| return r.path; + const n = @min(path.len, out.len); + @memcpy(out[0..n], path[0..n]); + return out[0..n]; +} + +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/")) { + const archive_path = if (std.mem.startsWith(u8, path, "/virtual/")) path[9..] else path; + var normalized_buf: [4096]u8 = undefined; + const normalized = normalizeVirtualPath(archive_path, &normalized_buf) orelse return error.OpenFailed; + const source = findEmbeddedSource(normalized, true) orelse return error.OpenFailed; + if (source.contents.len > limit) return error.FileTooLarge; + return gpa.dupe(u8, source.contents); + } + var pathbuf: [4096]u8 = undefined; + const native = localPath(path) orelse return error.OpenFailed; + const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{native}, 0) catch return error.PathTooLong; + // The path may be a mount this editor serves: the turn goes out with the + // syscalls, and the bytes come back into memory of the caller's own. + return pardes.tape.site(.read_file, gpa, readHost, .{ gpa, path_z, limit }); +} + +/// The disk's file at `path_z`, whole: the session's read, and a replica +/// client's of a read it was sent by hash (tape.zig `byHash`). +pub fn readHost(gpa: std.mem.Allocator, path_z: [:0]const u8, limit: usize) ![]u8 { + const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .NONBLOCK = true }); + if (fd < 0) return switch (libc.errno(fd)) { + .ACCES, .PERM => error.PermissionDenied, + .NOENT => error.FileNotFound, + .ISDIR => error.IsDirectory, + .NAMETOOLONG => error.PathTooLong, + else => error.OpenFailed, + }; + defer _ = libc.close(fd); + // What it is before its bytes are read, for a watch armed over them. + const before = (std.Io.File{ .handle = fd, .flags = .{ .nonblocking = true } }).stat(std.Io.Threaded.global_single_threaded.io()) catch null; + + // A device (/dev/zero, a tty) is no file to read whole: said so, not + // read to the stream limit and called too large. + if (ninep_io.statNoFollow(path_z)) |facts| { + const kind = facts.mode & 0o170000; + if (kind == 0o040000) return error.IsDirectory; + if (kind == 0o020000 or kind == 0o060000) return error.NotAFile; + } + const end = libc.lseek(fd, 0, libc.SEEK.END); + // Not seekable: a pipe or a FIFO is no file; a regular file that is a + // stream (a 9ns mount's log or screen, opened nonseekable) is read to + // its end, as one with no length is. + if (end < 0 and libc.errno(end) == .SPIPE) { + const facts = ninep_io.statNoFollow(path_z) orelse return error.NotAFile; + if (facts.mode & 0o170000 != 0o100000) return error.NotAFile; + } + const size: usize = if (end < 0) 0 else @intCast(end); + if (end >= 0 and libc.lseek(fd, 0, libc.SEEK.SET) < 0) return error.ReadFailed; + if (size == 0) { + const max_bytes = @min(limit, limits.max_stream_bytes); + var stream: std.Io.Writer.Allocating = .init(gpa); + errdefer stream.deinit(); + var chunk: [16 * 1024]u8 = undefined; + while (true) { + const n = libc.read(fd, &chunk, @min(chunk.len, max_bytes - stream.written().len + 1)); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + if (libc.errno(n) == .AGAIN) { + if (stream.written().len == 0) return error.NotAFile; + return stream.toOwnedSlice(); + } + return error.ReadFailed; + } + if (n == 0) return stream.toOwnedSlice(); + const received: usize = @intCast(n); + if (received > max_bytes - stream.written().len) return error.FileTooLarge; + try stream.writer.writeAll(chunk[0..received]); + } + } + if (size > limit) return error.FileTooLarge; + var buf = try gpa.alloc(u8, size); + errdefer gpa.free(buf); + var len: usize = 0; + while (len < buf.len) { + const n = libc.read(fd, buf[len..].ptr, buf.len - len); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return error.ReadFailed; + } + if (n == 0) break; + len += @intCast(n); + } + if (len != buf.len) buf = try gpa.realloc(buf, len); + if (before) |st| if (st.kind == .file) { + last_reads[last_read % last_reads.len] = .{ .path = std.hash.Wyhash.hash(0, path_z), .bytes = buf.ptr, .len = buf.len, .file = .{ .inode = st.inode, .size = st.size, .mtime_ns = st.mtime.nanoseconds, .ctime_ns = st.ctime.nanoseconds } }; + last_read +%= 1; + }; + return buf; +} + +/// The last files `readHost` read whole, each its path's hash, the buffer +/// it returned and what the file was before the read: a watch armed over a +/// text whose content is that very buffer (file_watch.applyEffect) finds the +/// disk the same without reading it again. +pub var last_reads: [8]struct { path: u64 = 0, bytes: [*]const u8 = undefined, len: usize = 0, file: @import("dev").file_watch.Identity = undefined } = @splat(.{}); +var last_read: usize = 0; + +/// A 9P write of an Edit held while its commands run (Namespace.edit_hold). +pub const EditHold = struct { + /// The listener's: the connection that asked, and its park. + asker: *anyopaque, + slot: u16, + seq: u64, + tag: u64, + node: u64, + handle: u32, + written: u32, + /// The Edit is done: applied, or failed with `said`. + done: bool = false, + errno: u16 = 0, + said: [256]u8 = undefined, + said_len: u16 = 0, + + pub fn names(h: *const EditHold, req: tree.Req) bool { + return req.op == .write and req.tag == h.tag and req.node == h.node and req.handle == h.handle; + } + + /// Its answer, the held record let go: the words copied out first. + pub fn answer(ns: *Namespace) tree.Reply { + const h = ns.edit_hold.?; + ns.edit_hold = null; + if (h.errno == 0) return .{ .tag = h.tag, .written = h.written }; + @memcpy(ns.edit_said[0..h.said_len], h.said[0..h.said_len]); + return tree.failText(h.tag, h.errno, ns.edit_said[0..h.said_len]); + } +}; + +pub const Namespace = struct { + socket_path: []const u8 = "", + tcp_address: ?std.Io.net.IpAddress = null, + mounts: std.ArrayList(Mount) = .empty, + node_name: [16]u8 = undefined, + os_paths: std.ArrayList(OsPath) = .empty, + /// What each open holds between its open and its release. + opens: [tree.open_slots]tree.Open = @splat(.{}), + out: std.ArrayList(u8) = .empty, + listeners: u16 = 0, + origin: u8 = 'K', + /// A ctl write is running builtins: one that would open a prompt for + /// its argument refuses (`refused`), since nobody is at the prompt, and + /// the first error one reports (`failure`) fails the write, as acme's + /// ctl answers a command's error (editors/acme/xfid.c:700). + no_prompt: bool = false, + /// The root ctl is running a session builtin: its messages are the + /// session's, logged `msg -`, though shown on the active pane. + session_write: bool = false, + /// A ctl write's failure is being said: its err record logs it, so + /// no msg does (Messages.reportFailure). + unlogged: bool = false, + /// A 9P write of clicks (look, exec, tagexec, a column's exec) is running + /// one: a builtin's failure is the write's, as a ctl line's is (no_prompt, + /// which also refuses prompts, which a click may open). + capturing: bool = false, + /// A 9P request is being served (Pardes.serveFs): a prompt it opens is + /// a question for the log (`ask`), answered with `answer`. + serving: bool = false, + refused: bool = false, + failure: [256]u8 = undefined, + failure_len: u16 = 0, + /// A header tag truncated by an open not yet released (ninep/cols.zig): + /// 0 the workspace's, a column's its serial; and whether the newline + /// that ended its last write is held back. + header_rewrite: ?u32 = null, + /// A column's or the workspace's tag truncated, not yet done (as a + /// pane tag's `tag_trunc_pending`): its key, the workspace's 0. + header_trunc_pending: ?u32 = null, + /// A look or exec a 9P write made found every pane slot taken; the + /// write fails with what was said, kept at the head of `ename`. + no_pane_slot: bool = false, + no_pane_slot_len: u16 = 0, + header_held: bool = false, + /// The newest failure said (reportFailure), fitted as an err is: its + /// path cut in the middle, never its reason, which the message row's + /// first 256 bytes lose. `said_at` is the `failures` count it was. + said: [256]u8 = undefined, + said_len: u16 = 0, + said_at: u32 = 0, + /// What went wrong performing a write's effects after it was answered + /// by the core (a save the host could not do): the 9P write, which + /// waits for them, fails with it (runtime/9p_io.zig). + late_failure: [256]u8 = undefined, + late_failure_len: u16 = 0, + /// A 9P write asked a language server something: the answer count it + /// waits to change (`turn.lsp_answers`), so its failure is the write's. + lsp_answer_at: ?u64 = null, + /// The request being served started an Edit whose `<`, `|` or `>` + /// commands run off the loop (edit_cmd.zig): the listener holds it. + edit_started: bool = false, + /// That write, held: answered once `done` (9p_io answerHeld), or + /// asked again by a retry of its park (Pardes.serveFs); a flush or a + /// hang-up stops the Edit (9p_io watchEdit). + edit_hold: ?EditHold = null, + /// The words a held Edit write was refused with, kept for its answer. + edit_said: [256]u8 = undefined, + /// The pane a language answer filled (a Rename's preview): what the + /// waiting 9P write answers once it is in (9p_io). + lsp_result: ?u32 = null, + /// The most a Twrite of the request being served can carry (msize less + /// its header), 0 when unknown: a write shorter than it is the whole of + /// what its client wrote, one that fills it may be cut and go on. + write_room: u32 = 0, + /// A 9P write waits on what the editor performs for it (a Save's disk + /// write, a shell, a language server): a failure said meanwhile is that + /// write's err, so it posts no msg (Messages.reportFailure). + write_waits: bool = false, + /// The whole text of the newest counted log record, hashed: its record + /// may be cut, and a repeat is only the same whole text again. + log_full_hash: u64 = 0, + /// The text of /pager opens closed before a read put it in, each with + /// its +Pager's serial, for the editor's step to put in (ctl.fillPager): + /// a close through a mount may not wait for the editor to be quiet, + /// as 9ns answers nothing else on that mount while a clunk is out. + pages: std.ArrayList(struct { serial: u32, bytes: std.ArrayList(u8) }) = .empty, + /// The last line each closed open wrote with no newline after it, with + /// the node it was written to, for the editor's step to run + /// (tree.runClosedLines): a close is answered at once, for the same + /// reason as `pages`. + closed_lines: std.ArrayList(struct { node: u64, bytes: std.ArrayList(u8) }) = .empty, + /// Writes one open made in a row into one place of a pane's body (an + /// append to `body`, an insert at `data`'s address), held and put in + /// as one edit when anything else comes (ninep/pane.zig flushBatch): a + /// 10 MB write in 8 KB pieces is one copy and one undo step, not 1280. + batch: struct { + serial: u32 = 0, + node: u64 = 0, + handle: u32 = 0, + at: usize = 0, + bytes: std.ArrayList(u8) = .empty, + /// The editor's clock at the last write held: its step puts them in + /// once the writes have paused (`batch_pause_ns`). + last_ns: u64 = 0, + } = .{}, + /// The serial of the pane the root's exec or look last ran a line at + /// (the keyboard's), 0 before one: its err record names that pane. + ran_at: u32 = 0, + /// The output pane a search just filled again rather than made + /// (Output.fillResults): what an exec reads back. + refilled: ?u32 = null, + /// Every failure said (Messages.reportFailure), counted: a builtin + /// that said one while it ran failed. + failures: u32 = 0, + /// A refusal that quotes the message it refuses, as Plan 9's cmderror + /// does (kernel/misc/parse.c:82); answered at once (runtime/9p_io.zig). + ename: [320]u8 = undefined, + /// Something a held read may be waiting on changed since they were last + /// answered: a record queued, a run answered, a pane gone. + news: bool = false, + /// A Restore is about to hang every client up: a follower's held read + /// of /log takes every queued record that fits, not one (events.readLog). + hanging_up: bool = false, + /// The editor-wide event ring: panes made, renamed, saved and closed, and + /// what the editor said. Recorded whether or not anyone reads /log. + log: tree.events.Queue = .{ .cap = limits.log_bytes }, + /// Messages a plumbing rule's `client` holds for a port no one reads + /// yet (Plumb.zig), each its port's index then the message packed: the + /// port's first reader takes them (plumber(4)'s queueheld). + plumb_held: tree.events.Queue = .{}, + /// What the last look or exec created or touched, answered by reading + /// either of those files. + results: [MAX_PANES]u32 = undefined, + results_len: u8 = 0, + /// Process start, the mtime of everything that has no edit time of its own. + started: u32 = 0, + + pub fn deinit(st: *Namespace, gpa: std.mem.Allocator) void { + for (st.mounts.items) |entry| { + gpa.free(entry.name); + gpa.free(entry.dial); + } + st.mounts.deinit(gpa); + for (st.os_paths.items) |entry| gpa.free(entry.path); + st.os_paths.deinit(gpa); + for (&st.opens) |*o| o.deinit(gpa); + for (st.pages.items) |*page| page.bytes.deinit(gpa); + st.pages.deinit(gpa); + for (st.closed_lines.items) |*line| line.bytes.deinit(gpa); + st.closed_lines.deinit(gpa); + st.log.deinit(gpa); + st.plumb_held.deinit(gpa); + st.out.deinit(gpa); + } + + pub fn mount(st: *Namespace, gpa: std.mem.Allocator, name: []const u8, dial: []const u8) !void { + if (!validMountName(name)) return error.BadMountName; + try ninep_io.Client.validateDial(dial); + if (dial.len == 0 or std.mem.indexOfScalar(u8, dial, 0) != null) return error.BadDial; + for (st.mounts.items) |entry| if (std.mem.eql(u8, name, entry.name)) return error.AlreadyMounted; + if (st.mounts.items.len == max_mounts) return error.TooManyMounts; + const saved_name = try gpa.dupe(u8, name); + errdefer gpa.free(saved_name); + const saved_dial = try gpa.dupe(u8, dial); + errdefer gpa.free(saved_dial); + try st.mounts.append(gpa, .{ .name = saved_name, .dial = saved_dial }); + } + + pub fn stage(st: *Namespace, gpa: std.mem.Allocator) *std.ArrayList(u8) { + st.out.clearRetainingCapacity(); + st.out.ensureTotalCapacity(gpa, tree.out_reserve) catch {}; + return &st.out; + } +}; + +pub fn unmount(p: *Pardes, name: []const u8) !void { + for (p.fs.mounts.items, 0..) |entry, index| { + if (!std.mem.eql(u8, name, entry.name)) continue; + var prefix_buf: [name_capacity + 4]u8 = undefined; + const prefix = try std.fmt.bufPrint(&prefix_buf, "/n/{s}", .{name}); + for (p.panes) |slot| { + const pane = slot orelse continue; + const paths = [_][]const u8{ + if (pane.file) |file| file.path else "", + if (pane.addon) |k| k.path else "", + Pardes.paneDir(pane), + }; + for (paths) |path| if (std.mem.startsWith(u8, path, prefix) and + (path.len == prefix.len or path[prefix.len] == '/')) return error.MountInUse; + } + for (0..p.effects_len) |i| { + const effect = p.effects[(p.effects_head + i) % p.effects.len]; + if (effect != .save_text) continue; + const path = effect.save_text.path.slice(); + if (std.mem.startsWith(u8, path, prefix) and + (path.len == prefix.len or path[prefix.len] == '/')) return error.MountInUse; + } + const removed = p.fs.mounts.orderedRemove(index); + ninep_io.Client.forget(removed.dial); + p.gpa.free(removed.name); + p.gpa.free(removed.dial); + return; + } + 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" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + 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 (runtime/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; +} + +test "the tree's README lists src/ only when the build serves it" { + try std.testing.expectEqual(limits.embedded_sources, std.mem.indexOf(u8, help, "src/") != null); +} + +test "a write open(2) refuses says its errno in words" { + if (comptime @import("builtin").os.tag != .linux) return error.SkipZigTest; + // /proc takes no new file: ENOENT, which used to read "open failed". + try std.testing.expectError(error.NoSuchFileOrDirectory, writeFile("/proc/pardes-no-such-file", "x")); + var words: [128]u8 = undefined; + try std.testing.expectEqualStrings("no such file or directory", pardes.Messages.errorWords(error.NoSuchFileOrDirectory, &words)); +} |
