summaryrefslogtreecommitdiff
path: root/src/9p_io.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/9p_io.zig')
-rw-r--r--src/9p_io.zig1503
1 files changed, 751 insertions, 752 deletions
diff --git a/src/9p_io.zig b/src/9p_io.zig
index 62c38521..b557594a 100644
--- a/src/9p_io.zig
+++ b/src/9p_io.zig
@@ -103,7 +103,6 @@ const Runner = if (supported) cloud9.serve.Runner(pardes.ctlfs, ninep.editor, .{
.listeners = 2,
}) else void;
-
pub const Listener = struct {
io: std.Io,
/// The core that answers; `reset` puts a replacement in.
@@ -1078,182 +1077,6 @@ fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void {
const testing = std.testing;
-test "the socket name is a third prefix in the shared directory" {
- var buf: [sun_path_len]u8 = undefined;
- const p = socketPath(&buf, "/run/user/1000", "t9srv").?;
- try testing.expectEqualStrings("/run/user/1000/pardes-9p-t9srv.sock", p);
- try testing.expect(!std.mem.startsWith(u8, std.Io.Dir.path.basename(p), "pardes-detached-"));
-}
-
-test "a name that is not one path component is no address at all" {
- var buf: [sun_path_len]u8 = undefined;
- try testing.expect(socketPath(&buf, "/run", "") == null);
- try testing.expect(socketPath(&buf, "/run", "a/b") == null);
- try testing.expect(socketPath(&buf, "/run", "a\x00b") == null);
-}
-
-test "the startup sweep removes a dead pid's socket and leaves a live pid's, a named one and a plain file" {
- if (comptime !supported) return error.SkipZigTest;
- var dir_buf: [sun_path_len:0]u8 = undefined;
- const base = socketDir(&dir_buf) orelse return error.SkipZigTest;
- if (!ensureSocketDir(base)) return error.SkipZigTest;
- var sub_buf: [sun_path_len:0]u8 = undefined;
- const sub = std.fmt.bufPrintSentinel(&sub_buf, "{s}/deadsweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch return error.SkipZigTest;
- if (libc.mkdir(sub, 0o700) != 0) return error.SkipZigTest;
- var paths: [4][sun_path_len:0]u8 = undefined;
- // No process has this pid: kill(pid, 0) answers ESRCH.
- const dead = try std.fmt.bufPrintSentinel(&paths[0], "{s}/" ++ prefix ++ "2147483647.sock", .{sub}, 0);
- const live = try std.fmt.bufPrintSentinel(&paths[1], "{s}/" ++ prefix ++ "{d}.sock", .{ sub, @as(u32, @intCast(std.c.getppid())) }, 0);
- const named = try std.fmt.bufPrintSentinel(&paths[2], "{s}/" ++ prefix ++ "work.sock", .{sub}, 0);
- const plain = try std.fmt.bufPrintSentinel(&paths[3], "{s}/" ++ prefix ++ "2147483646.sock", .{sub}, 0);
- defer {
- for ([_][:0]const u8{ dead, live, named, plain }) |p| _ = libc.unlink(p);
- _ = libc.rmdir(sub);
- }
- for ([_][:0]const u8{ dead, live, named }) |p| {
- const fd = bindSocket(p);
- if (fd < 0) return error.SkipZigTest;
- _ = libc.close(fd); // closed: what a killed editor leaves
- }
- const fd = libc.open(plain, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600));
- if (fd < 0) return error.SkipZigTest;
- _ = libc.close(fd);
- sweepDeadSockets(testing.io, sub);
- try testing.expect(statNoFollow(dead) == null);
- try testing.expect(statNoFollow(live) != null);
- try testing.expect(statNoFollow(named) != null);
- try testing.expect(statNoFollow(plain) != null);
-}
-
-test "the registry sweep takes the dead entries and leaves everything else" {
- if (comptime !supported) return error.SkipZigTest;
- // Under the real runtime directory, because a sun_path is 108 bytes
- // and the test cache's temporary directories are longer than that.
- var dir_buf: [sun_path_len:0]u8 = undefined;
- const base = socketDir(&dir_buf) orelse return error.SkipZigTest;
- if (!ensureSocketDir(base)) return error.SkipZigTest;
-
- var svc_buf: [sun_path_len:0]u8 = undefined;
- const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/sweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch
- return error.SkipZigTest;
- if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest;
-
- // The sockets live where the real ones do -- beside the registry, not in
- // it, and named the way a session names them -- because the sweep only
- // follows an entry to a target of exactly that shape and place.
- var paths: [6][sun_path_len:0]u8 = undefined;
- const pid: u32 = @intCast(libc.getpid());
- const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/pardes-9p-sweeplive-{d}.sock", .{ base, pid }, 0);
- const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/pardes-9p-sweepdead-{d}.sock", .{ base, pid }, 0);
- const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0);
- const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0);
- const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0);
- // A dead entry pointing at something that is NOT one of our sockets: the
- // entry goes, the file it named must not.
- const outsider_sock = try std.fmt.bufPrintSentinel(&paths[5], "{s}/sweep-outsider-{d}.sock", .{ base, pid }, 0);
- var outsider_buf: [sun_path_len:0]u8 = undefined;
- const outsider = try std.fmt.bufPrintSentinel(&outsider_buf, "{s}/outsider", .{svc}, 0);
- // Live, its lock held, but bound and not listening: a connect is
- // refused, on every system, as FreeBSD refuses one to a live session
- // whose queue is full. Its lock is what says it lives.
- var starting_paths: [2][sun_path_len:0]u8 = undefined;
- const starting_sock = try std.fmt.bufPrintSentinel(&starting_paths[0], "{s}/pardes-9p-sweepstarting-{d}.sock", .{ base, pid }, 0);
- const starting = try std.fmt.bufPrintSentinel(&starting_paths[1], "{s}/starting", .{svc}, 0);
- var locks: [3][lock_path_len:0]u8 = undefined;
- const dead_lock = lockPath(&locks[2], dead_sock).?;
- defer {
- for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger, outsider_sock, outsider, starting_sock, starting, dead_lock }) |p| _ = libc.unlink(p);
- _ = libc.rmdir(svc);
- }
-
- const live_lock = claim(live_sock, &locks[0]) orelse return error.LockFailed;
- defer release(live_lock, std.mem.sliceTo(&locks[0], 0));
- const listening = bindSocket(live_sock);
- try testing.expect(listening >= 0);
- defer _ = libc.close(listening);
- try testing.expectEqual(@as(c_int, 0), libc.listen(listening, 1));
-
- const starting_lock = claim(starting_sock, &locks[1]) orelse return error.LockFailed;
- defer release(starting_lock, std.mem.sliceTo(&locks[1], 0));
- const bound = bindSocket(starting_sock);
- try testing.expect(bound >= 0);
- defer _ = libc.close(bound);
- try testing.expectEqual(@as(c_int, 0), libc.symlink(starting_sock, starting));
-
- // Bound and then dropped, its lock let go: the files stay, and nobody
- // answers it -- exactly what a killed session leaves behind.
- const abandoned = bindSocket(dead_sock);
- try testing.expect(abandoned >= 0);
- _ = libc.close(abandoned);
- const dropped = libc.open(dead_lock, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600));
- try testing.expect(dropped >= 0);
- try testing.expectEqual(@as(c_int, 0), libc.flock(dropped, std.posix.LOCK.EX));
- _ = libc.close(dropped);
-
- try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live));
- try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead));
- // Dead too, but its target is not one of our sockets by name, so the
- // entry must go and the file it named must survive untouched.
- const outside = bindSocket(outsider_sock);
- try testing.expect(outside >= 0);
- defer _ = libc.close(outside);
- try testing.expectEqual(@as(c_int, 0), libc.symlink(outsider_sock, outsider));
- // Not a symlink, so not this program's to reason about, even though
- // connecting to it is refused exactly like the dead socket.
- try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" });
-
- try testing.expectEqual(Probe.live, probe(live));
- try testing.expectEqual(Probe.stale, probe(dead));
-
- sweepRegistry(testing.io, svc, base);
-
- try testing.expect(statNoFollow(dead) == null);
- try testing.expect(statNoFollow(dead_sock) == null);
- try testing.expect(statNoFollow(dead_lock) == null);
- try testing.expect(statNoFollow(starting) != null);
- try testing.expect(statNoFollow(starting_sock) != null);
- try testing.expect(statNoFollow(live) != null);
- try testing.expect(statNoFollow(live_sock) != null);
- try testing.expect(statNoFollow(stranger) != null);
- try testing.expect(statNoFollow(outsider) == null);
- try testing.expect(statNoFollow(outsider_sock) != null);
- try testing.expectEqual(Probe.live, probe(live));
-}
-
-fn bindSocket(path: [:0]const u8) c_int {
- const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0);
- if (fd < 0) return fd;
- var addr: libc.sockaddr.un = .{ .path = @splat(0) };
- @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]);
- if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) {
- _ = libc.close(fd);
- return -1;
- }
- return fd;
-}
-
-test "TCP addresses are numeric and normalize mapped IPv4" {
- const loopback = try networkAddress("tcp!127.0.0.1!5640", false);
- try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:127.0.0.1!5640", false));
- try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:7f00:1!5640", false));
- try testing.expectEqualDeep(try networkAddress("tcp!::1!5640", false), try networkAddress("tcp!0:0:0:0:0:0:0:1!5640", false));
- try testing.expectEqual(@as(u16, 0), (try networkAddress("tcp!127.0.0.1!0", true)).getPort());
- for ([_][]const u8{ "tcp!localhost!5640", "tcp!127.0.0.1!0", "tcp!127.0.0.1!-1", "tcp!127.0.0.1!65536", "tcp!127.0.0.1!", "tcp!!5640" }) |dial|
- try testing.expectError(error.BadDial, networkAddress(dial, false));
- try Client.validateDial("tcp!127.0.0.1!5640");
- try Client.validateDial("/tmp/pardes-owned.sock");
- try Client.validateDial("unix!/tmp/pardes-owned.sock");
- try testing.expectError(error.BadDial, Client.validateDial("unix!work"));
- try testing.expectError(error.BadDial, Client.validateDial("nowhere!x"));
- try Client.validateDial("/tmp/odd!name.sock");
- try testing.expectError(error.BadDial, Client.validateDial("rel/dir.sock"));
- try testing.expectError(error.BadDial, Client.validateDial("unix!"));
- try testing.expectError(error.BadDial, Client.validateDial("unix!/tmp/a\x00b"));
- try testing.expectError(error.BadDial, Client.validateDial("tcp!localhost!5640"));
- try testing.expectError(error.BadDial, Client.validateDial("/tmp/a\x00b"));
- try testing.expectError(error.BadDial, Client.validateDial("quic!127.0.0.1!5640"));
-}
-
extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8;
/// A test's own runtime directory under /tmp, which XDG_RUNTIME_DIR names
@@ -1279,502 +1102,6 @@ const TempRuntime = struct {
}
};
-test "a runtime directory that makes the socket's path pass sun_path is refused in words, the editor running on" {
- if (comptime !supported) return error.SkipZigTest;
- const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- var rt: TempRuntime = .{};
- try rt.init("words");
- defer rt.deinit();
- var buf: [256]u8 = undefined;
- try testing.expect(noSocket("x", &buf) == null);
- // A directory of 91 bytes (the ledger's was 83, a pid's digits from the
- // edge): with a 1-byte name and a pid the socket's path passes sun_path.
- var long_buf: [128:0]u8 = undefined;
- const long = try std.fmt.bufPrintSentinel(&long_buf, "{s}/{s}", .{ std.mem.sliceTo(&rt.directory, 0), &@as([66]u8, @splat('d')) }, 0);
- try testing.expectEqual(@as(usize, 91), long.len);
- try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", long, 1));
- const words = noSocket("x", &buf) orelse return error.NotRefused;
- try testing.expect(std.mem.startsWith(u8, words, "9p: the socket path is "));
- try testing.expect(std.mem.endsWith(u8, words, " bytes, 108 is the most: set XDG_RUNTIME_DIR shorter"));
- // The session's own words, where its pane shows them; no listener.
- try testing.expect(start(testing.io, testing.allocator, p) == null);
- const pane = p.panes[0].?;
- try testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "9p: the socket path is "));
-}
-
-test "a runtime directory open to others is refused in words, never a silent session with no socket" {
- if (comptime !supported) return error.SkipZigTest;
- const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- var rt: TempRuntime = .{};
- try rt.init("open");
- defer rt.deinit();
- // `mkdir -m 700 -p dir/sub` leaves dir itself at the umask's 755.
- try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o755));
- var buf: [256]u8 = undefined;
- const words = noSocket("x", &buf) orelse return error.NotRefused;
- try testing.expect(std.mem.indexOf(u8, words, "must be a directory of yours alone (mode 755") != null);
- try testing.expect(start(testing.io, testing.allocator, p) == null);
- const pane = p.panes[0].?;
- try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "chmod 700 it") != null);
- try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o700));
- try testing.expect(noSocket("x", &buf) == null);
-}
-
-test "a socket path too long for sun_path is no listener, and leaves the editor's turn as it was" {
- if (comptime !supported) return error.SkipZigTest;
- const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
- defer p.deinit();
- var rt: TempRuntime = .{};
- try rt.init("long");
- defer rt.deinit();
- // A name that fits: the directory is one a listener takes.
- var fits: [sun_path_len]u8 = undefined;
- try testing.expect(socketPath(&fits, std.mem.sliceTo(&rt.directory, 0), "short") != null);
- const long = &@as([120]u8, @splat('n'));
- try testing.expectError(error.NameTooLong, listen(testing.io, testing.allocator, p, long, "", null));
- try testing.expect(pardes.turn.answer_held == null);
- try testing.expect(pardes.turn.wake_parked == null);
- try testing.expect(pardes.turn.io == null);
-}
-
-test "a listening editor posts itself into the 9P registry and unposts on stop" {
- if (comptime !supported) return error.SkipZigTest;
- const gpa = testing.allocator;
- var rt: TempRuntime = .{};
- try rt.init("post");
- defer rt.deinit();
- const dir = std.mem.sliceTo(&rt.directory, 0);
-
- var entry_buf: [sun_path_len:0]u8 = undefined;
- const entry = try std.fmt.bufPrintSentinel(&entry_buf, "{s}/9p/pardes/unit", .{dir}, 0);
- var sock_buf: [sun_path_len:0]u8 = undefined;
- const sock = try std.fmt.bufPrintSentinel(&sock_buf, "{s}/" ++ prefix ++ "unit.sock", .{dir}, 0);
-
- var link: [sun_path_len]u8 = undefined;
- {
- const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer p.deinit();
- const l = try listen(testing.io, gpa, p, "unit", "", null);
- defer l.deinit(gpa);
- // The socket stays exactly where pardes has always bound it:
- // adopting the registry moves nothing, it only advertises.
- try testing.expect(statNoFollow(sock) != null);
- // It appeared already listening, renamed into place from a name of
- // its own, which is gone; its lock held all the while.
- try testing.expect(transport.isListening(sock));
- try testing.expectEqual(Probe.live, lockState(sock));
- var tmp_buf: [sun_path_len:0]u8 = undefined;
- try testing.expect(statNoFollow(try std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ sock, libc.getpid() }, 0)) == null);
- // And the registry holds a symlink to it one directory down, so
- // several editors group under /mnt/9p/pardes/ instead of
- // crowding the registry root — the layout zmx posts its
- // sessions in.
- const n = libc.readlink(entry, &link, link.len);
- try testing.expect(n > 0);
- try testing.expectEqualStrings(sock, link[0..@intCast(n)]);
- // A host path no fid names is swept, but never while a request is
- // out in a syscall: it may be that request's, mid-walk.
- try p.fs.os_paths.append(gpa, .{ .node = @import("fs.zig").os_node | 1, .path = try gpa.dupe(u8, "/tmp") });
- pardes.turn.out = 1;
- l.collectOs();
- pardes.turn.out = 0;
- try testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len);
- l.collectOs();
- try testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len);
- }
- // Stopping takes the name back out, so the next editor of that name
- // is not refused by its own corpse; the lock goes with the socket.
- try testing.expect(libc.readlink(entry, &link, link.len) < 0);
- try testing.expectEqual(Probe.none, lockState(sock));
-}
-
-test "Unix and TCP share one listener through reads writes reconnects and reset" {
- if (comptime !supported) return error.SkipZigTest;
- const gpa = testing.allocator;
- var rt: TempRuntime = .{};
- try rt.init("tcp");
- defer rt.deinit();
- const replacement = try gpa.alloc(u8, 3 * msize + 27);
- defer gpa.free(replacement);
- @memset(replacement, 'x');
- @memcpy(replacement[0.."changed café λ\n".len], "changed café λ\n");
- replacement[replacement.len - 1] = '\n';
-
- const Worker = struct {
- dial: []const u8,
- body_path: []const u8,
- expected: []const u8,
- replacement: []const u8,
- done: std.atomic.Value(bool) = .init(false),
- failure: ?anyerror = null,
-
- fn run(w: *@This()) void {
- defer w.done.store(true, .release);
- w.check() catch |err| {
- w.failure = err;
- };
- }
-
- fn check(w: *@This()) !void {
- const before = try Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len);
- defer testing.allocator.free(before);
- try testing.expectEqualStrings(w.expected, before);
- try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len - 1));
- const listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", 128);
- defer testing.allocator.free(listing);
- const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len);
- defer testing.allocator.free(exact_listing);
- try testing.expectEqualStrings(listing, exact_listing);
- try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len - 1));
- try Client.write(testing.allocator, w.dial, w.body_path, w.replacement);
- const after = try Client.read(testing.allocator, w.dial, w.body_path, w.body_path);
- defer testing.allocator.free(after);
- try testing.expectEqualStrings(w.replacement, after);
- const screen = try Client.read(testing.allocator, w.dial, "/screen", "/screen");
- defer testing.allocator.free(screen);
- const parsed = try std.json.parseFromSlice(struct { cols: u16, rows: u16 }, testing.allocator, screen, .{ .ignore_unknown_fields = true });
- defer parsed.deinit();
- try testing.expectEqual(@as(u16, 40), parsed.value.cols);
- try testing.expectEqual(@as(u16, 12), parsed.value.rows);
- }
- };
-
- for ([_][]const u8{ "127.0.0.1", "::1" }) |host| {
- const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer p.deinit();
- const pane = try p.setTestFile("initial\n");
- while (p.nextEffect()) |_| {}
- var bind_buf: [64]u8 = undefined;
- const bind = try std.fmt.bufPrint(&bind_buf, "tcp!{s}!0", .{host});
- const l = try listen(testing.io, gpa, p, "roundtrip", "", bind);
- defer {
- l.reset(p);
- l.deinit(gpa);
- }
- try testing.expect(l.path().len != 0);
- try testing.expectEqual(@as(usize, max_conns), l.runner.conns.len);
- const port = l.tcp_address.?.getPort();
- try testing.expect(port != 0);
- var dial_buf: [64]u8 = undefined;
- const network_dial = try std.fmt.bufPrint(&dial_buf, "tcp!{s}!{d}", .{ host, port });
- var body_buf: [64]u8 = undefined;
- const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
- for ([_][]const u8{ network_dial, l.path(), network_dial }, 0..) |dial, attempt| {
- var worker: Worker = .{ .dial = dial, .body_path = body, .expected = if (attempt == 0) "initial\n" else replacement, .replacement = replacement };
- const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker});
- defer thread.join();
- // The editor rests while the client works: its requests are
- // answered on the runner's tasks, not by this thread.
- const deadline = nowMs() + 3 * Client.budget_ms;
- pardes.turn.rest();
- while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1);
- // The client has hung up, but its connection's task may not have
- // seen that yet. The releases it then owes are refused once
- // `reset` starts cutting (they name the old editor's opens), and
- // this test's "replacement" is the same editor, so they would
- // stay in `p.fs.opens`. Let the hangup pay them first, resting
- // so the task can take the turn: that is what is under test here.
- const settle_by = nowMs() + 3 * Client.budget_ms;
- while (l.runner.count() != 0 and nowMs() < settle_by) nap(1);
- pardes.turn.wake();
- try testing.expect(worker.done.load(.acquire));
- if (worker.failure) |err| return err;
- try testing.expectEqual(@as(usize, 0), l.runner.count());
- l.reset(p);
- try testing.expectEqual(@as(usize, 0), l.runner.count());
- for (p.fs.opens) |o| try testing.expect(o.node == 0);
- }
- }
-}
-
-test "a change waits while the editor is out mid-step, a read does not, and the change lands when the editor rests" {
- if (comptime !supported) return error.SkipZigTest;
- const gpa = testing.allocator;
- var rt: TempRuntime = .{};
- try rt.init("park");
- defer rt.deinit();
-
- const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer p.deinit();
- const pane = try p.setTestFile("before\n");
- while (p.nextEffect()) |_| {}
- // This thread is the editor's: it has the turn from here on.
- const l = try listen(testing.io, gpa, p, "park", "", null);
- defer {
- l.reset(p);
- l.deinit(gpa);
- }
- var body_buf: [64]u8 = undefined;
- const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
-
- const Writer = struct {
- dial: []const u8,
- path: []const u8,
- done: std.atomic.Value(bool) = .init(false),
- failure: ?anyerror = null,
- fn run(w: *@This()) void {
- defer w.done.store(true, .release);
- Client.write(testing.allocator, w.dial, w.path, "after\n") catch |err| {
- w.failure = err;
- };
- }
- };
- var writer: Writer = .{ .dial = l.path(), .path = body };
-
- // The editor goes out mid-step -- a Look resolving a path, say -- and a
- // write arrives meanwhile. It must not land: the step still holds
- // pointers into the pane. A read is answered all the same.
- pardes.turn.yield();
- const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer});
- defer thread.join();
- nap(150);
- try testing.expect(!writer.done.load(.acquire));
- const seen = try Client.readLimit(gpa, l.path(), body, body, 64);
- defer gpa.free(seen);
- try testing.expectEqualStrings("before\n", seen);
- try testing.expect(!writer.done.load(.acquire));
- pardes.turn.back();
- try testing.expectEqualStrings("before\n", pane.file.?.content);
-
- // Resting is what lets it in: the parked write is retried, served, and
- // the client hears back.
- pardes.turn.rest();
- const deadline = nowMs() + Client.budget_ms;
- while (!writer.done.load(.acquire) and nowMs() < deadline) nap(1);
- pardes.turn.wake();
- try testing.expect(writer.done.load(.acquire));
- if (writer.failure) |err| return err;
- // Its bytes are held until its open is let go (pane.zig `batchFor`), and
- // the client lets it go without waiting: rested again until that lands,
- // the body read only while the editor has the turn.
- while (!std.mem.eql(u8, pane.file.?.content, "after\n") and nowMs() < deadline) {
- pardes.turn.rest();
- nap(1);
- pardes.turn.wake();
- }
- try testing.expectEqualStrings("after\n", pane.file.?.content);
-}
-
-test "a mount's connection is kept between operations, and one the peer hung up is dialled again" {
- if (comptime !supported) return error.SkipZigTest;
- const gpa = testing.allocator;
- var rt: TempRuntime = .{};
- try rt.init("kept");
- defer rt.deinit();
-
- const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer p.deinit();
- const pane = try p.setTestFile("before\n");
- while (p.nextEffect()) |_| {}
- const l = try listen(testing.io, gpa, p, "kept", "", null);
- defer {
- l.reset(p);
- l.deinit(gpa);
- }
- var body_buf: [64]u8 = undefined;
- const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
- const long = try gpa.alloc(u8, 2 * msize + 5);
- defer gpa.free(long);
- @memset(long, 'k');
- long[long.len - 1] = '\n';
-
- const Worker = struct {
- l: *Listener,
- body: []const u8,
- long: []const u8,
- done: std.atomic.Value(bool) = .init(false),
- failure: ?anyerror = null,
- fn run(w: *@This()) void {
- defer w.done.store(true, .release);
- w.check() catch |err| {
- w.failure = err;
- };
- }
- fn read(w: *@This(), want: []const u8) !void {
- const got = try Client.readMount(testing.allocator, w.l.path(), w.body, w.body, limits.max_file_bytes);
- defer testing.allocator.free(got);
- try testing.expectEqualStrings(want, got);
- }
- fn check(w: *@This()) !void {
- defer Client.forget(w.l.path());
- try w.read("before\n");
- try w.read("before\n");
- // A write longer than a message, and a miss, on the same one.
- try Client.writeMount(testing.allocator, w.l.path(), w.body, w.long);
- try w.read(w.long);
- try testing.expectError(error.NotFound, Client.readMount(testing.allocator, w.l.path(), "/pane/no-such", "/pane/no-such", 64));
- try testing.expectEqual(@as(u64, 1), w.l.accepts.load(.acquire));
- // The peer hangs up (a Restore cuts its clients): the next
- // operation dials again and is answered.
- for (&w.l.runner.conns) |*conn| if (conn.live()) conn.close();
- const by = nowMs() + Client.budget_ms;
- while (w.l.runner.count() != 0 and nowMs() < by) nap(1);
- try w.read(w.long);
- try testing.expectEqual(@as(u64, 2), w.l.accepts.load(.acquire));
- }
- };
- var worker: Worker = .{ .l = l, .body = body, .long = long };
- pardes.turn.rest();
- const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker});
- const deadline = nowMs() + 3 * Client.budget_ms;
- while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1);
- thread.join();
- // Forgotten: the kept connection is closed, and its task sees it.
- const settle_by = nowMs() + Client.budget_ms;
- while (l.runner.count() != 0 and nowMs() < settle_by) nap(1);
- pardes.turn.wake();
- if (worker.failure) |err| return err;
- try testing.expectEqual(@as(usize, 0), l.runner.count());
-}
-
-test "a connection holds up to 128 reads, and the next is refused in words" {
- try testing.expectEqual(@as(usize, 128), ninep.max_held);
- if (comptime supported) try testing.expectEqualStrings("too many reads waiting: 128", Runner.Engine.e_waiting);
-}
-
-test "a held read is answered when the log has news, and a flushed one spends nothing" {
- if (comptime !supported) return error.SkipZigTest;
- const gpa = testing.allocator;
- var rt: TempRuntime = .{};
- try rt.init("held");
- defer rt.deinit();
-
- const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
- defer p.deinit();
- _ = try p.setTestFile("held\n");
- p.update(.tick); // the pane is logged, before the log is opened
- while (p.nextEffect()) |_| {}
- const l = try listen(testing.io, gpa, p, "held", "", null);
- defer {
- l.reset(p);
- l.deinit(gpa);
- }
- // This thread is the editor's and plays the client too, resting while
- // it does so that the runner's tasks can take the turn and answer.
- const s = try gpa.create(Client.Session);
- defer gpa.destroy(s);
- s.* = .{ .fd = -1, .deadline = nowMs() + 3 * Client.budget_ms, .display_path = "/log" };
- var sock_buf: [sun_path_len]u8 = undefined;
- pardes.turn.rest();
- defer pardes.turn.wake();
- s.fd = try Client.connect(try Client.resolve(&sock_buf, l.path()), s.deadline);
- defer _ = libc.close(s.fd);
- s.cl = .init(.{ .in = &s.in, .out = &s.out });
- var remote: Client.RemoteError = .{};
- _ = try s.ask(.{ .version = .{} }, &remote);
- _ = try s.ask(.{ .attach = .{ .fid = 0, .uname = "held" } }, &remote);
- _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"log"} } }, &remote);
- _ = try s.ask(.{ .open = .{ .fid = 1, .mode = ninep.ordwr } }, &remote);
- var frozen: u64 = 0;
- while (true) {
- const n = (try s.ask(.{ .read = .{ .fid = 1, .offset = frozen, .count = 4096 } }, &remote)).read.len;
- if (n == 0) break;
- frozen += n;
- }
- _ = try s.ask(.{ .write = .{ .fid = 1, .offset = 0, .data = "follow\n" } }, &remote);
-
- const heldNow = struct {
- /// Waits until the core holds `n` reads.
- fn count(core: *pardes.Pardes, n: usize) !void {
- const deadline = nowMs() + Client.budget_ms;
- while (nowMs() < deadline) {
- pardes.turn.wake();
- var got: usize = 0;
- for (core.fs.opens) |o| got += @intFromBool(o.held != null);
- pardes.turn.rest();
- if (got == n) return;
- nap(1);
- }
- return error.Timeout;
- }
- };
- const serial = p.panes[0].?.serial;
- var event_path: [32]u8 = undefined;
- var event_names: [3][]const u8 = .{ "pane", try std.fmt.bufPrint(&event_path, "{d}", .{serial}), "event" };
- _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 2, .names = &event_names } }, &remote);
- _ = try s.ask(.{ .open = .{ .fid = 2, .mode = ninep.oread } }, &remote);
-
- // Flushed while held, a read is gone from the engine without the core
- // hearing of it. Its tag, asked again at once for a read of the pane's
- // event, must not be answered with the log's next record, and that
- // record must reach the log's next read.
- const flushed = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
- try s.flush();
- try heldNow.count(p, 1);
- _ = try s.cl.submit(.{ .flush = .{ .oldtag = flushed } });
- const interrupted = try s.settle();
- try testing.expectEqual(flushed, interrupted.tag);
- try testing.expect(interrupted.result == .fail);
- try testing.expect((try s.settle()).result == .flush);
- const reused = try s.cl.submit(.{ .read = .{ .fid = 2, .offset = 0, .count = 4096 } });
- try testing.expectEqual(flushed, reused);
- try s.flush();
- try heldNow.count(p, 2);
- pardes.turn.wake();
- p.setMessage(0, "after the flush");
- pardes.turn.rest();
- try heldNow.count(p, 1);
- pardes.turn.wake();
- p.fs.origin = 'K';
- pardes.ctlfs.events.noteAction(p, 0, .body_exec, 0, 4, 0, "held");
- pardes.turn.rest();
- const clicked = try s.settle();
- try testing.expectEqual(reused, clicked.tag);
- try testing.expectEqualStrings("KX0 4 0 4 held\n", clicked.result.read);
- try testing.expect(std.mem.indexOf(u8, (try s.ask(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }, &remote)).read, "after the flush") != null);
-
- // Held, a read is answered by the record that arrives, on its own
- // connection, with no retry of every parked request asked for; a
- // second read on the same open meanwhile is refused, not orphaned.
- const waiting = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
- try s.flush();
- try heldNow.count(p, 1);
- const second = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
- const refused = try s.settle();
- try testing.expectEqual(second, refused.tag);
- try testing.expectEqualStrings(pardes.ctlfs.e_in_use, refused.result.fail);
- pardes.turn.wake();
- p.setMessage(0, "while held");
- const retry_all = pardes.turn.parked;
- pardes.turn.rest();
- try testing.expect(!retry_all);
- const answered = try s.settle();
- try testing.expectEqual(waiting, answered.tag);
- try testing.expect(std.mem.indexOf(u8, answered.result.read, "while held") != null);
-
- // Clunked, the log's held read is interrupted by the engine and the
- // record it would have had is spent on nobody.
- _ = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
- try s.flush();
- try heldNow.count(p, 1);
- s.drop(1);
- s.drop(2);
- try heldNow.count(p, 0);
-
- // Records queued as a Restore comes reach a follower in the answer to
- // the read it holds, all of them, before the hangup cuts it. (The
- // interrupted read above answered first: one clunk's answer is unread.)
- _ = try s.settle();
- _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 3, .names = &.{"log"} } }, &remote);
- _ = try s.ask(.{ .open = .{ .fid = 3, .mode = ninep.ordwr } }, &remote);
- _ = try s.ask(.{ .write = .{ .fid = 3, .offset = 0, .data = "follow new\n" } }, &remote);
- const last = try s.cl.submit(.{ .read = .{ .fid = 3, .offset = 0, .count = 4096 } });
- try s.flush();
- try heldNow.count(p, 1);
- pardes.turn.wake();
- p.setMessage(0, "queued one");
- p.setMessage(0, "queued two");
- p.setMessage(0, "queued three");
- l.reset(p);
- pardes.turn.rest();
- const cut = try s.settle();
- try testing.expectEqual(last, cut.tag);
- for ([_][]const u8{ "queued one", "queued two", "queued three" }) |said|
- try testing.expect(std.mem.indexOf(u8, cut.result.read, said) != null);
-}
-
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes) ?*Listener {
@@ -1843,85 +1170,6 @@ fn exportMount(sock_path: []const u8) void {
@import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null);
}
-test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" {
- const names = [_][*:0]const u8{ "NINE_MNTGEN", "NINE_MOUNT", "PARDES_MOUNT" };
- var saved: [names.len]?[:0]u8 = @splat(null);
- for (names, &saved) |name, *value| {
- if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0);
- }
- defer for (names, saved) |name, value| {
- if (value) |old| {
- _ = setenv(name, old, 1);
- testing.allocator.free(old);
- } else _ = @import("host_io.zig").testUnsetenv(name);
- };
- _ = setenv("NINE_MOUNT", "/mnt/9p", 1);
- _ = setenv("NINE_MNTGEN", "1", 1);
- exportMount("/run/user/1000/pardes-9p-work.sock");
- try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?);
- // A mount of another server (9ns --unix): not this session's.
- _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN");
- exportMount("/run/user/1000/pardes-9p-work.sock");
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null);
-}
-
-test "9P shell environment states being inside pardes apart from how to reach it" {
- const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" };
- var saved: [names.len]?[:0]u8 = @splat(null);
- for (names, &saved) |name, *value| {
- if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0);
- }
- defer for (names, saved) |name, value| {
- if (value) |old| {
- _ = setenv(name, old, 1);
- testing.allocator.free(old);
- } else _ = @import("host_io.zig").testUnsetenv(name);
- };
-
- var dir: [sun_path_len:0]u8 = undefined;
- _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1);
- try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?);
- _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR");
- _ = setenv("HOME", "/home/example", 1);
- try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?);
- _ = @import("host_io.zig").testUnsetenv("HOME");
- try testing.expect(socketDir(&dir) == null);
-
- // The socket a listener keeps while it lives.
- const path = "/tmp/pardes-example.sock";
- @memcpy(own_socket[0..path.len], path);
- own_socket[path.len] = 0;
- own_socket_len = path.len;
- defer own_socket_len = 0;
- var own: [16]u8 = undefined;
- const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))});
-
- // A `--nested` session: reachable for scripts and mounts, but nobody's
- // parent, so a pardes started in one of its shells runs a session of
- // its own instead of handing its argument over.
- exportEnv(7, false);
- try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?);
- try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null);
-
- exportEnv(8, true);
- try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?);
- try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?);
-
- // A session whose listener never came up is still the session this shell
- // is inside: the pid stands on its own, and only the address is missing.
- own_socket_len = 0;
- exportEnv(0, true);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null);
- try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?);
-
- exportEnv(0, false);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null);
- try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null);
-}
-
pub const Client = struct {
pub const budget_ms: i64 = 2000;
/// Each write of a long one has this long to be answered (transact).
@@ -2788,3 +2036,754 @@ pub const Client = struct {
try testing.expectError(Error.Timeout, session.wait(poll_in));
}
};
+
+fn bindSocket(path: [:0]const u8) c_int {
+ const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM, 0);
+ if (fd < 0) return fd;
+ var addr: libc.sockaddr.un = .{ .path = @splat(0) };
+ @memcpy(addr.path[0 .. path.len + 1], path[0 .. path.len + 1]);
+ if (libc.bind(fd, @ptrCast(&addr), @sizeOf(@TypeOf(addr))) != 0) {
+ _ = libc.close(fd);
+ return -1;
+ }
+ return fd;
+}
+
+test "the socket name is a third prefix in the shared directory" {
+ var buf: [sun_path_len]u8 = undefined;
+ const p = socketPath(&buf, "/run/user/1000", "t9srv").?;
+ try testing.expectEqualStrings("/run/user/1000/pardes-9p-t9srv.sock", p);
+ try testing.expect(!std.mem.startsWith(u8, std.Io.Dir.path.basename(p), "pardes-detached-"));
+}
+
+test "a name that is not one path component is no address at all" {
+ var buf: [sun_path_len]u8 = undefined;
+ try testing.expect(socketPath(&buf, "/run", "") == null);
+ try testing.expect(socketPath(&buf, "/run", "a/b") == null);
+ try testing.expect(socketPath(&buf, "/run", "a\x00b") == null);
+}
+
+test "the startup sweep removes a dead pid's socket and leaves a live pid's, a named one and a plain file" {
+ if (comptime !supported) return error.SkipZigTest;
+ var dir_buf: [sun_path_len:0]u8 = undefined;
+ const base = socketDir(&dir_buf) orelse return error.SkipZigTest;
+ if (!ensureSocketDir(base)) return error.SkipZigTest;
+ var sub_buf: [sun_path_len:0]u8 = undefined;
+ const sub = std.fmt.bufPrintSentinel(&sub_buf, "{s}/deadsweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch return error.SkipZigTest;
+ if (libc.mkdir(sub, 0o700) != 0) return error.SkipZigTest;
+ var paths: [4][sun_path_len:0]u8 = undefined;
+ // No process has this pid: kill(pid, 0) answers ESRCH.
+ const dead = try std.fmt.bufPrintSentinel(&paths[0], "{s}/" ++ prefix ++ "2147483647.sock", .{sub}, 0);
+ const live = try std.fmt.bufPrintSentinel(&paths[1], "{s}/" ++ prefix ++ "{d}.sock", .{ sub, @as(u32, @intCast(std.c.getppid())) }, 0);
+ const named = try std.fmt.bufPrintSentinel(&paths[2], "{s}/" ++ prefix ++ "work.sock", .{sub}, 0);
+ const plain = try std.fmt.bufPrintSentinel(&paths[3], "{s}/" ++ prefix ++ "2147483646.sock", .{sub}, 0);
+ defer {
+ for ([_][:0]const u8{ dead, live, named, plain }) |p| _ = libc.unlink(p);
+ _ = libc.rmdir(sub);
+ }
+ for ([_][:0]const u8{ dead, live, named }) |p| {
+ const fd = bindSocket(p);
+ if (fd < 0) return error.SkipZigTest;
+ _ = libc.close(fd); // closed: what a killed editor leaves
+ }
+ const fd = libc.open(plain, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600));
+ if (fd < 0) return error.SkipZigTest;
+ _ = libc.close(fd);
+ sweepDeadSockets(testing.io, sub);
+ try testing.expect(statNoFollow(dead) == null);
+ try testing.expect(statNoFollow(live) != null);
+ try testing.expect(statNoFollow(named) != null);
+ try testing.expect(statNoFollow(plain) != null);
+}
+
+test "the registry sweep takes the dead entries and leaves everything else" {
+ if (comptime !supported) return error.SkipZigTest;
+ // Under the real runtime directory, because a sun_path is 108 bytes
+ // and the test cache's temporary directories are longer than that.
+ var dir_buf: [sun_path_len:0]u8 = undefined;
+ const base = socketDir(&dir_buf) orelse return error.SkipZigTest;
+ if (!ensureSocketDir(base)) return error.SkipZigTest;
+
+ var svc_buf: [sun_path_len:0]u8 = undefined;
+ const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/sweep-{d}", .{ base, @as(u32, @intCast(libc.getpid())) }, 0) catch
+ return error.SkipZigTest;
+ if (libc.mkdir(svc, 0o700) != 0) return error.SkipZigTest;
+
+ // The sockets live where the real ones do -- beside the registry, not in
+ // it, and named the way a session names them -- because the sweep only
+ // follows an entry to a target of exactly that shape and place.
+ var paths: [6][sun_path_len:0]u8 = undefined;
+ const pid: u32 = @intCast(libc.getpid());
+ const live_sock = try std.fmt.bufPrintSentinel(&paths[0], "{s}/pardes-9p-sweeplive-{d}.sock", .{ base, pid }, 0);
+ const dead_sock = try std.fmt.bufPrintSentinel(&paths[1], "{s}/pardes-9p-sweepdead-{d}.sock", .{ base, pid }, 0);
+ const live = try std.fmt.bufPrintSentinel(&paths[2], "{s}/live", .{svc}, 0);
+ const dead = try std.fmt.bufPrintSentinel(&paths[3], "{s}/dead", .{svc}, 0);
+ const stranger = try std.fmt.bufPrintSentinel(&paths[4], "{s}/stranger", .{svc}, 0);
+ // A dead entry pointing at something that is NOT one of our sockets: the
+ // entry goes, the file it named must not.
+ const outsider_sock = try std.fmt.bufPrintSentinel(&paths[5], "{s}/sweep-outsider-{d}.sock", .{ base, pid }, 0);
+ var outsider_buf: [sun_path_len:0]u8 = undefined;
+ const outsider = try std.fmt.bufPrintSentinel(&outsider_buf, "{s}/outsider", .{svc}, 0);
+ // Live, its lock held, but bound and not listening: a connect is
+ // refused, on every system, as FreeBSD refuses one to a live session
+ // whose queue is full. Its lock is what says it lives.
+ var starting_paths: [2][sun_path_len:0]u8 = undefined;
+ const starting_sock = try std.fmt.bufPrintSentinel(&starting_paths[0], "{s}/pardes-9p-sweepstarting-{d}.sock", .{ base, pid }, 0);
+ const starting = try std.fmt.bufPrintSentinel(&starting_paths[1], "{s}/starting", .{svc}, 0);
+ var locks: [3][lock_path_len:0]u8 = undefined;
+ const dead_lock = lockPath(&locks[2], dead_sock).?;
+ defer {
+ for ([_][:0]const u8{ live_sock, dead_sock, live, dead, stranger, outsider_sock, outsider, starting_sock, starting, dead_lock }) |p| _ = libc.unlink(p);
+ _ = libc.rmdir(svc);
+ }
+
+ const live_lock = claim(live_sock, &locks[0]) orelse return error.LockFailed;
+ defer release(live_lock, std.mem.sliceTo(&locks[0], 0));
+ const listening = bindSocket(live_sock);
+ try testing.expect(listening >= 0);
+ defer _ = libc.close(listening);
+ try testing.expectEqual(@as(c_int, 0), libc.listen(listening, 1));
+
+ const starting_lock = claim(starting_sock, &locks[1]) orelse return error.LockFailed;
+ defer release(starting_lock, std.mem.sliceTo(&locks[1], 0));
+ const bound = bindSocket(starting_sock);
+ try testing.expect(bound >= 0);
+ defer _ = libc.close(bound);
+ try testing.expectEqual(@as(c_int, 0), libc.symlink(starting_sock, starting));
+
+ // Bound and then dropped, its lock let go: the files stay, and nobody
+ // answers it -- exactly what a killed session leaves behind.
+ const abandoned = bindSocket(dead_sock);
+ try testing.expect(abandoned >= 0);
+ _ = libc.close(abandoned);
+ const dropped = libc.open(dead_lock, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600));
+ try testing.expect(dropped >= 0);
+ try testing.expectEqual(@as(c_int, 0), libc.flock(dropped, std.posix.LOCK.EX));
+ _ = libc.close(dropped);
+
+ try testing.expectEqual(@as(c_int, 0), libc.symlink(live_sock, live));
+ try testing.expectEqual(@as(c_int, 0), libc.symlink(dead_sock, dead));
+ // Dead too, but its target is not one of our sockets by name, so the
+ // entry must go and the file it named must survive untouched.
+ const outside = bindSocket(outsider_sock);
+ try testing.expect(outside >= 0);
+ defer _ = libc.close(outside);
+ try testing.expectEqual(@as(c_int, 0), libc.symlink(outsider_sock, outsider));
+ // Not a symlink, so not this program's to reason about, even though
+ // connecting to it is refused exactly like the dead socket.
+ try std.Io.Dir.cwd().writeFile(testing.io, .{ .sub_path = stranger, .data = "" });
+
+ try testing.expectEqual(Probe.live, probe(live));
+ try testing.expectEqual(Probe.stale, probe(dead));
+
+ sweepRegistry(testing.io, svc, base);
+
+ try testing.expect(statNoFollow(dead) == null);
+ try testing.expect(statNoFollow(dead_sock) == null);
+ try testing.expect(statNoFollow(dead_lock) == null);
+ try testing.expect(statNoFollow(starting) != null);
+ try testing.expect(statNoFollow(starting_sock) != null);
+ try testing.expect(statNoFollow(live) != null);
+ try testing.expect(statNoFollow(live_sock) != null);
+ try testing.expect(statNoFollow(stranger) != null);
+ try testing.expect(statNoFollow(outsider) == null);
+ try testing.expect(statNoFollow(outsider_sock) != null);
+ try testing.expectEqual(Probe.live, probe(live));
+}
+
+test "TCP addresses are numeric and normalize mapped IPv4" {
+ const loopback = try networkAddress("tcp!127.0.0.1!5640", false);
+ try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:127.0.0.1!5640", false));
+ try testing.expectEqualDeep(loopback, try networkAddress("tcp!::ffff:7f00:1!5640", false));
+ try testing.expectEqualDeep(try networkAddress("tcp!::1!5640", false), try networkAddress("tcp!0:0:0:0:0:0:0:1!5640", false));
+ try testing.expectEqual(@as(u16, 0), (try networkAddress("tcp!127.0.0.1!0", true)).getPort());
+ for ([_][]const u8{ "tcp!localhost!5640", "tcp!127.0.0.1!0", "tcp!127.0.0.1!-1", "tcp!127.0.0.1!65536", "tcp!127.0.0.1!", "tcp!!5640" }) |dial|
+ try testing.expectError(error.BadDial, networkAddress(dial, false));
+ try Client.validateDial("tcp!127.0.0.1!5640");
+ try Client.validateDial("/tmp/pardes-owned.sock");
+ try Client.validateDial("unix!/tmp/pardes-owned.sock");
+ try testing.expectError(error.BadDial, Client.validateDial("unix!work"));
+ try testing.expectError(error.BadDial, Client.validateDial("nowhere!x"));
+ try Client.validateDial("/tmp/odd!name.sock");
+ try testing.expectError(error.BadDial, Client.validateDial("rel/dir.sock"));
+ try testing.expectError(error.BadDial, Client.validateDial("unix!"));
+ try testing.expectError(error.BadDial, Client.validateDial("unix!/tmp/a\x00b"));
+ try testing.expectError(error.BadDial, Client.validateDial("tcp!localhost!5640"));
+ try testing.expectError(error.BadDial, Client.validateDial("/tmp/a\x00b"));
+ try testing.expectError(error.BadDial, Client.validateDial("quic!127.0.0.1!5640"));
+}
+
+test "a runtime directory that makes the socket's path pass sun_path is refused in words, the editor running on" {
+ if (comptime !supported) return error.SkipZigTest;
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ var rt: TempRuntime = .{};
+ try rt.init("words");
+ defer rt.deinit();
+ var buf: [256]u8 = undefined;
+ try testing.expect(noSocket("x", &buf) == null);
+ // A directory of 91 bytes (the ledger's was 83, a pid's digits from the
+ // edge): with a 1-byte name and a pid the socket's path passes sun_path.
+ var long_buf: [128:0]u8 = undefined;
+ const long = try std.fmt.bufPrintSentinel(&long_buf, "{s}/{s}", .{ std.mem.sliceTo(&rt.directory, 0), &@as([66]u8, @splat('d')) }, 0);
+ try testing.expectEqual(@as(usize, 91), long.len);
+ try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", long, 1));
+ const words = noSocket("x", &buf) orelse return error.NotRefused;
+ try testing.expect(std.mem.startsWith(u8, words, "9p: the socket path is "));
+ try testing.expect(std.mem.endsWith(u8, words, " bytes, 108 is the most: set XDG_RUNTIME_DIR shorter"));
+ // The session's own words, where its pane shows them; no listener.
+ try testing.expect(start(testing.io, testing.allocator, p) == null);
+ const pane = p.panes[0].?;
+ try testing.expect(std.mem.startsWith(u8, pane.msg[0..pane.msg_len], "9p: the socket path is "));
+}
+
+test "a runtime directory open to others is refused in words, never a silent session with no socket" {
+ if (comptime !supported) return error.SkipZigTest;
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ var rt: TempRuntime = .{};
+ try rt.init("open");
+ defer rt.deinit();
+ // `mkdir -m 700 -p dir/sub` leaves dir itself at the umask's 755.
+ try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o755));
+ var buf: [256]u8 = undefined;
+ const words = noSocket("x", &buf) orelse return error.NotRefused;
+ try testing.expect(std.mem.indexOf(u8, words, "must be a directory of yours alone (mode 755") != null);
+ try testing.expect(start(testing.io, testing.allocator, p) == null);
+ const pane = p.panes[0].?;
+ try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "chmod 700 it") != null);
+ try testing.expectEqual(@as(c_int, 0), libc.chmod(&rt.directory, 0o700));
+ try testing.expect(noSocket("x", &buf) == null);
+}
+
+test "a socket path too long for sun_path is no listener, and leaves the editor's turn as it was" {
+ if (comptime !supported) return error.SkipZigTest;
+ const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true });
+ defer p.deinit();
+ var rt: TempRuntime = .{};
+ try rt.init("long");
+ defer rt.deinit();
+ // A name that fits: the directory is one a listener takes.
+ var fits: [sun_path_len]u8 = undefined;
+ try testing.expect(socketPath(&fits, std.mem.sliceTo(&rt.directory, 0), "short") != null);
+ const long = &@as([120]u8, @splat('n'));
+ try testing.expectError(error.NameTooLong, listen(testing.io, testing.allocator, p, long, "", null));
+ try testing.expect(pardes.turn.answer_held == null);
+ try testing.expect(pardes.turn.wake_parked == null);
+ try testing.expect(pardes.turn.io == null);
+}
+
+test "a listening editor posts itself into the 9P registry and unposts on stop" {
+ if (comptime !supported) return error.SkipZigTest;
+ const gpa = testing.allocator;
+ var rt: TempRuntime = .{};
+ try rt.init("post");
+ defer rt.deinit();
+ const dir = std.mem.sliceTo(&rt.directory, 0);
+
+ var entry_buf: [sun_path_len:0]u8 = undefined;
+ const entry = try std.fmt.bufPrintSentinel(&entry_buf, "{s}/9p/pardes/unit", .{dir}, 0);
+ var sock_buf: [sun_path_len:0]u8 = undefined;
+ const sock = try std.fmt.bufPrintSentinel(&sock_buf, "{s}/" ++ prefix ++ "unit.sock", .{dir}, 0);
+
+ var link: [sun_path_len]u8 = undefined;
+ {
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ const l = try listen(testing.io, gpa, p, "unit", "", null);
+ defer l.deinit(gpa);
+ // The socket stays exactly where pardes has always bound it:
+ // adopting the registry moves nothing, it only advertises.
+ try testing.expect(statNoFollow(sock) != null);
+ // It appeared already listening, renamed into place from a name of
+ // its own, which is gone; its lock held all the while.
+ try testing.expect(transport.isListening(sock));
+ try testing.expectEqual(Probe.live, lockState(sock));
+ var tmp_buf: [sun_path_len:0]u8 = undefined;
+ try testing.expect(statNoFollow(try std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ sock, libc.getpid() }, 0)) == null);
+ // And the registry holds a symlink to it one directory down, so
+ // several editors group under /mnt/9p/pardes/ instead of
+ // crowding the registry root — the layout zmx posts its
+ // sessions in.
+ const n = libc.readlink(entry, &link, link.len);
+ try testing.expect(n > 0);
+ try testing.expectEqualStrings(sock, link[0..@intCast(n)]);
+ // A host path no fid names is swept, but never while a request is
+ // out in a syscall: it may be that request's, mid-walk.
+ try p.fs.os_paths.append(gpa, .{ .node = @import("fs.zig").os_node | 1, .path = try gpa.dupe(u8, "/tmp") });
+ pardes.turn.out = 1;
+ l.collectOs();
+ pardes.turn.out = 0;
+ try testing.expectEqual(@as(usize, 1), p.fs.os_paths.items.len);
+ l.collectOs();
+ try testing.expectEqual(@as(usize, 0), p.fs.os_paths.items.len);
+ }
+ // Stopping takes the name back out, so the next editor of that name
+ // is not refused by its own corpse; the lock goes with the socket.
+ try testing.expect(libc.readlink(entry, &link, link.len) < 0);
+ try testing.expectEqual(Probe.none, lockState(sock));
+}
+
+test "Unix and TCP share one listener through reads writes reconnects and reset" {
+ if (comptime !supported) return error.SkipZigTest;
+ const gpa = testing.allocator;
+ var rt: TempRuntime = .{};
+ try rt.init("tcp");
+ defer rt.deinit();
+ const replacement = try gpa.alloc(u8, 3 * msize + 27);
+ defer gpa.free(replacement);
+ @memset(replacement, 'x');
+ @memcpy(replacement[0.."changed café λ\n".len], "changed café λ\n");
+ replacement[replacement.len - 1] = '\n';
+
+ const Worker = struct {
+ dial: []const u8,
+ body_path: []const u8,
+ expected: []const u8,
+ replacement: []const u8,
+ done: std.atomic.Value(bool) = .init(false),
+ failure: ?anyerror = null,
+
+ fn run(w: *@This()) void {
+ defer w.done.store(true, .release);
+ w.check() catch |err| {
+ w.failure = err;
+ };
+ }
+
+ fn check(w: *@This()) !void {
+ const before = try Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len);
+ defer testing.allocator.free(before);
+ try testing.expectEqualStrings(w.expected, before);
+ try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, w.body_path, w.body_path, w.expected.len - 1));
+ const listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", 128);
+ defer testing.allocator.free(listing);
+ const exact_listing = try Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len);
+ defer testing.allocator.free(exact_listing);
+ try testing.expectEqualStrings(listing, exact_listing);
+ try testing.expectError(error.FileTooLarge, Client.readLimit(testing.allocator, w.dial, "/pane", "/pane", listing.len - 1));
+ try Client.write(testing.allocator, w.dial, w.body_path, w.replacement);
+ const after = try Client.read(testing.allocator, w.dial, w.body_path, w.body_path);
+ defer testing.allocator.free(after);
+ try testing.expectEqualStrings(w.replacement, after);
+ const screen = try Client.read(testing.allocator, w.dial, "/screen", "/screen");
+ defer testing.allocator.free(screen);
+ const parsed = try std.json.parseFromSlice(struct { cols: u16, rows: u16 }, testing.allocator, screen, .{ .ignore_unknown_fields = true });
+ defer parsed.deinit();
+ try testing.expectEqual(@as(u16, 40), parsed.value.cols);
+ try testing.expectEqual(@as(u16, 12), parsed.value.rows);
+ }
+ };
+
+ for ([_][]const u8{ "127.0.0.1", "::1" }) |host| {
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ const pane = try p.setTestFile("initial\n");
+ while (p.nextEffect()) |_| {}
+ var bind_buf: [64]u8 = undefined;
+ const bind = try std.fmt.bufPrint(&bind_buf, "tcp!{s}!0", .{host});
+ const l = try listen(testing.io, gpa, p, "roundtrip", "", bind);
+ defer {
+ l.reset(p);
+ l.deinit(gpa);
+ }
+ try testing.expect(l.path().len != 0);
+ try testing.expectEqual(@as(usize, max_conns), l.runner.conns.len);
+ const port = l.tcp_address.?.getPort();
+ try testing.expect(port != 0);
+ var dial_buf: [64]u8 = undefined;
+ const network_dial = try std.fmt.bufPrint(&dial_buf, "tcp!{s}!{d}", .{ host, port });
+ var body_buf: [64]u8 = undefined;
+ const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
+ for ([_][]const u8{ network_dial, l.path(), network_dial }, 0..) |dial, attempt| {
+ var worker: Worker = .{ .dial = dial, .body_path = body, .expected = if (attempt == 0) "initial\n" else replacement, .replacement = replacement };
+ const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker});
+ defer thread.join();
+ // The editor rests while the client works: its requests are
+ // answered on the runner's tasks, not by this thread.
+ const deadline = nowMs() + 3 * Client.budget_ms;
+ pardes.turn.rest();
+ while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1);
+ // The client has hung up, but its connection's task may not have
+ // seen that yet. The releases it then owes are refused once
+ // `reset` starts cutting (they name the old editor's opens), and
+ // this test's "replacement" is the same editor, so they would
+ // stay in `p.fs.opens`. Let the hangup pay them first, resting
+ // so the task can take the turn: that is what is under test here.
+ const settle_by = nowMs() + 3 * Client.budget_ms;
+ while (l.runner.count() != 0 and nowMs() < settle_by) nap(1);
+ pardes.turn.wake();
+ try testing.expect(worker.done.load(.acquire));
+ if (worker.failure) |err| return err;
+ try testing.expectEqual(@as(usize, 0), l.runner.count());
+ l.reset(p);
+ try testing.expectEqual(@as(usize, 0), l.runner.count());
+ for (p.fs.opens) |o| try testing.expect(o.node == 0);
+ }
+ }
+}
+
+test "a change waits while the editor is out mid-step, a read does not, and the change lands when the editor rests" {
+ if (comptime !supported) return error.SkipZigTest;
+ const gpa = testing.allocator;
+ var rt: TempRuntime = .{};
+ try rt.init("park");
+ defer rt.deinit();
+
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ const pane = try p.setTestFile("before\n");
+ while (p.nextEffect()) |_| {}
+ // This thread is the editor's: it has the turn from here on.
+ const l = try listen(testing.io, gpa, p, "park", "", null);
+ defer {
+ l.reset(p);
+ l.deinit(gpa);
+ }
+ var body_buf: [64]u8 = undefined;
+ const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
+
+ const Writer = struct {
+ dial: []const u8,
+ path: []const u8,
+ done: std.atomic.Value(bool) = .init(false),
+ failure: ?anyerror = null,
+ fn run(w: *@This()) void {
+ defer w.done.store(true, .release);
+ Client.write(testing.allocator, w.dial, w.path, "after\n") catch |err| {
+ w.failure = err;
+ };
+ }
+ };
+ var writer: Writer = .{ .dial = l.path(), .path = body };
+
+ // The editor goes out mid-step -- a Look resolving a path, say -- and a
+ // write arrives meanwhile. It must not land: the step still holds
+ // pointers into the pane. A read is answered all the same.
+ pardes.turn.yield();
+ const thread = try std.Thread.spawn(.{}, Writer.run, .{&writer});
+ defer thread.join();
+ nap(150);
+ try testing.expect(!writer.done.load(.acquire));
+ const seen = try Client.readLimit(gpa, l.path(), body, body, 64);
+ defer gpa.free(seen);
+ try testing.expectEqualStrings("before\n", seen);
+ try testing.expect(!writer.done.load(.acquire));
+ pardes.turn.back();
+ try testing.expectEqualStrings("before\n", pane.file.?.content);
+
+ // Resting is what lets it in: the parked write is retried, served, and
+ // the client hears back.
+ pardes.turn.rest();
+ const deadline = nowMs() + Client.budget_ms;
+ while (!writer.done.load(.acquire) and nowMs() < deadline) nap(1);
+ pardes.turn.wake();
+ try testing.expect(writer.done.load(.acquire));
+ if (writer.failure) |err| return err;
+ // Its bytes are held until its open is let go (pane.zig `batchFor`), and
+ // the client lets it go without waiting: rested again until that lands,
+ // the body read only while the editor has the turn.
+ while (!std.mem.eql(u8, pane.file.?.content, "after\n") and nowMs() < deadline) {
+ pardes.turn.rest();
+ nap(1);
+ pardes.turn.wake();
+ }
+ try testing.expectEqualStrings("after\n", pane.file.?.content);
+}
+
+test "a mount's connection is kept between operations, and one the peer hung up is dialled again" {
+ if (comptime !supported) return error.SkipZigTest;
+ const gpa = testing.allocator;
+ var rt: TempRuntime = .{};
+ try rt.init("kept");
+ defer rt.deinit();
+
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ const pane = try p.setTestFile("before\n");
+ while (p.nextEffect()) |_| {}
+ const l = try listen(testing.io, gpa, p, "kept", "", null);
+ defer {
+ l.reset(p);
+ l.deinit(gpa);
+ }
+ var body_buf: [64]u8 = undefined;
+ const body = try std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{pane.serial});
+ const long = try gpa.alloc(u8, 2 * msize + 5);
+ defer gpa.free(long);
+ @memset(long, 'k');
+ long[long.len - 1] = '\n';
+
+ const Worker = struct {
+ l: *Listener,
+ body: []const u8,
+ long: []const u8,
+ done: std.atomic.Value(bool) = .init(false),
+ failure: ?anyerror = null,
+ fn run(w: *@This()) void {
+ defer w.done.store(true, .release);
+ w.check() catch |err| {
+ w.failure = err;
+ };
+ }
+ fn read(w: *@This(), want: []const u8) !void {
+ const got = try Client.readMount(testing.allocator, w.l.path(), w.body, w.body, limits.max_file_bytes);
+ defer testing.allocator.free(got);
+ try testing.expectEqualStrings(want, got);
+ }
+ fn check(w: *@This()) !void {
+ defer Client.forget(w.l.path());
+ try w.read("before\n");
+ try w.read("before\n");
+ // A write longer than a message, and a miss, on the same one.
+ try Client.writeMount(testing.allocator, w.l.path(), w.body, w.long);
+ try w.read(w.long);
+ try testing.expectError(error.NotFound, Client.readMount(testing.allocator, w.l.path(), "/pane/no-such", "/pane/no-such", 64));
+ try testing.expectEqual(@as(u64, 1), w.l.accepts.load(.acquire));
+ // The peer hangs up (a Restore cuts its clients): the next
+ // operation dials again and is answered.
+ for (&w.l.runner.conns) |*conn| if (conn.live()) conn.close();
+ const by = nowMs() + Client.budget_ms;
+ while (w.l.runner.count() != 0 and nowMs() < by) nap(1);
+ try w.read(w.long);
+ try testing.expectEqual(@as(u64, 2), w.l.accepts.load(.acquire));
+ }
+ };
+ var worker: Worker = .{ .l = l, .body = body, .long = long };
+ pardes.turn.rest();
+ const thread = try std.Thread.spawn(.{}, Worker.run, .{&worker});
+ const deadline = nowMs() + 3 * Client.budget_ms;
+ while (!worker.done.load(.acquire) and nowMs() < deadline) nap(1);
+ thread.join();
+ // Forgotten: the kept connection is closed, and its task sees it.
+ const settle_by = nowMs() + Client.budget_ms;
+ while (l.runner.count() != 0 and nowMs() < settle_by) nap(1);
+ pardes.turn.wake();
+ if (worker.failure) |err| return err;
+ try testing.expectEqual(@as(usize, 0), l.runner.count());
+}
+
+test "a connection holds up to 128 reads, and the next is refused in words" {
+ try testing.expectEqual(@as(usize, 128), ninep.max_held);
+ if (comptime supported) try testing.expectEqualStrings("too many reads waiting: 128", Runner.Engine.e_waiting);
+}
+
+test "a held read is answered when the log has news, and a flushed one spends nothing" {
+ if (comptime !supported) return error.SkipZigTest;
+ const gpa = testing.allocator;
+ var rt: TempRuntime = .{};
+ try rt.init("held");
+ defer rt.deinit();
+
+ const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 });
+ defer p.deinit();
+ _ = try p.setTestFile("held\n");
+ p.update(.tick); // the pane is logged, before the log is opened
+ while (p.nextEffect()) |_| {}
+ const l = try listen(testing.io, gpa, p, "held", "", null);
+ defer {
+ l.reset(p);
+ l.deinit(gpa);
+ }
+ // This thread is the editor's and plays the client too, resting while
+ // it does so that the runner's tasks can take the turn and answer.
+ const s = try gpa.create(Client.Session);
+ defer gpa.destroy(s);
+ s.* = .{ .fd = -1, .deadline = nowMs() + 3 * Client.budget_ms, .display_path = "/log" };
+ var sock_buf: [sun_path_len]u8 = undefined;
+ pardes.turn.rest();
+ defer pardes.turn.wake();
+ s.fd = try Client.connect(try Client.resolve(&sock_buf, l.path()), s.deadline);
+ defer _ = libc.close(s.fd);
+ s.cl = .init(.{ .in = &s.in, .out = &s.out });
+ var remote: Client.RemoteError = .{};
+ _ = try s.ask(.{ .version = .{} }, &remote);
+ _ = try s.ask(.{ .attach = .{ .fid = 0, .uname = "held" } }, &remote);
+ _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 1, .names = &.{"log"} } }, &remote);
+ _ = try s.ask(.{ .open = .{ .fid = 1, .mode = ninep.ordwr } }, &remote);
+ var frozen: u64 = 0;
+ while (true) {
+ const n = (try s.ask(.{ .read = .{ .fid = 1, .offset = frozen, .count = 4096 } }, &remote)).read.len;
+ if (n == 0) break;
+ frozen += n;
+ }
+ _ = try s.ask(.{ .write = .{ .fid = 1, .offset = 0, .data = "follow\n" } }, &remote);
+
+ const heldNow = struct {
+ /// Waits until the core holds `n` reads.
+ fn count(core: *pardes.Pardes, n: usize) !void {
+ const deadline = nowMs() + Client.budget_ms;
+ while (nowMs() < deadline) {
+ pardes.turn.wake();
+ var got: usize = 0;
+ for (core.fs.opens) |o| got += @intFromBool(o.held != null);
+ pardes.turn.rest();
+ if (got == n) return;
+ nap(1);
+ }
+ return error.Timeout;
+ }
+ };
+ const serial = p.panes[0].?.serial;
+ var event_path: [32]u8 = undefined;
+ var event_names: [3][]const u8 = .{ "pane", try std.fmt.bufPrint(&event_path, "{d}", .{serial}), "event" };
+ _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 2, .names = &event_names } }, &remote);
+ _ = try s.ask(.{ .open = .{ .fid = 2, .mode = ninep.oread } }, &remote);
+
+ // Flushed while held, a read is gone from the engine without the core
+ // hearing of it. Its tag, asked again at once for a read of the pane's
+ // event, must not be answered with the log's next record, and that
+ // record must reach the log's next read.
+ const flushed = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ try s.flush();
+ try heldNow.count(p, 1);
+ _ = try s.cl.submit(.{ .flush = .{ .oldtag = flushed } });
+ const interrupted = try s.settle();
+ try testing.expectEqual(flushed, interrupted.tag);
+ try testing.expect(interrupted.result == .fail);
+ try testing.expect((try s.settle()).result == .flush);
+ const reused = try s.cl.submit(.{ .read = .{ .fid = 2, .offset = 0, .count = 4096 } });
+ try testing.expectEqual(flushed, reused);
+ try s.flush();
+ try heldNow.count(p, 2);
+ pardes.turn.wake();
+ p.setMessage(0, "after the flush");
+ pardes.turn.rest();
+ try heldNow.count(p, 1);
+ pardes.turn.wake();
+ p.fs.origin = 'K';
+ pardes.ctlfs.events.noteAction(p, 0, .body_exec, 0, 4, 0, "held");
+ pardes.turn.rest();
+ const clicked = try s.settle();
+ try testing.expectEqual(reused, clicked.tag);
+ try testing.expectEqualStrings("KX0 4 0 4 held\n", clicked.result.read);
+ try testing.expect(std.mem.indexOf(u8, (try s.ask(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } }, &remote)).read, "after the flush") != null);
+
+ // Held, a read is answered by the record that arrives, on its own
+ // connection, with no retry of every parked request asked for; a
+ // second read on the same open meanwhile is refused, not orphaned.
+ const waiting = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ try s.flush();
+ try heldNow.count(p, 1);
+ const second = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ const refused = try s.settle();
+ try testing.expectEqual(second, refused.tag);
+ try testing.expectEqualStrings(pardes.ctlfs.e_in_use, refused.result.fail);
+ pardes.turn.wake();
+ p.setMessage(0, "while held");
+ const retry_all = pardes.turn.parked;
+ pardes.turn.rest();
+ try testing.expect(!retry_all);
+ const answered = try s.settle();
+ try testing.expectEqual(waiting, answered.tag);
+ try testing.expect(std.mem.indexOf(u8, answered.result.read, "while held") != null);
+
+ // Clunked, the log's held read is interrupted by the engine and the
+ // record it would have had is spent on nobody.
+ _ = try s.cl.submit(.{ .read = .{ .fid = 1, .offset = 0, .count = 4096 } });
+ try s.flush();
+ try heldNow.count(p, 1);
+ s.drop(1);
+ s.drop(2);
+ try heldNow.count(p, 0);
+
+ // Records queued as a Restore comes reach a follower in the answer to
+ // the read it holds, all of them, before the hangup cuts it. (The
+ // interrupted read above answered first: one clunk's answer is unread.)
+ _ = try s.settle();
+ _ = try s.ask(.{ .walk = .{ .fid = 0, .newfid = 3, .names = &.{"log"} } }, &remote);
+ _ = try s.ask(.{ .open = .{ .fid = 3, .mode = ninep.ordwr } }, &remote);
+ _ = try s.ask(.{ .write = .{ .fid = 3, .offset = 0, .data = "follow new\n" } }, &remote);
+ const last = try s.cl.submit(.{ .read = .{ .fid = 3, .offset = 0, .count = 4096 } });
+ try s.flush();
+ try heldNow.count(p, 1);
+ pardes.turn.wake();
+ p.setMessage(0, "queued one");
+ p.setMessage(0, "queued two");
+ p.setMessage(0, "queued three");
+ l.reset(p);
+ pardes.turn.rest();
+ const cut = try s.settle();
+ try testing.expectEqual(last, cut.tag);
+ for ([_][]const u8{ "queued one", "queued two", "queued three" }) |said|
+ try testing.expect(std.mem.indexOf(u8, cut.result.read, said) != null);
+}
+
+test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" {
+ const names = [_][*:0]const u8{ "NINE_MNTGEN", "NINE_MOUNT", "PARDES_MOUNT" };
+ var saved: [names.len]?[:0]u8 = @splat(null);
+ for (names, &saved) |name, *value| {
+ if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0);
+ }
+ defer for (names, saved) |name, value| {
+ if (value) |old| {
+ _ = setenv(name, old, 1);
+ testing.allocator.free(old);
+ } else _ = @import("host_io.zig").testUnsetenv(name);
+ };
+ _ = setenv("NINE_MOUNT", "/mnt/9p", 1);
+ _ = setenv("NINE_MNTGEN", "1", 1);
+ exportMount("/run/user/1000/pardes-9p-work.sock");
+ try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?);
+ // A mount of another server (9ns --unix): not this session's.
+ _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN");
+ exportMount("/run/user/1000/pardes-9p-work.sock");
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null);
+}
+
+test "9P shell environment states being inside pardes apart from how to reach it" {
+ const names = [_][*:0]const u8{ "XDG_RUNTIME_DIR", "HOME", "PARDES_PID", "PARDES_9P", "PARDES_PANE" };
+ var saved: [names.len]?[:0]u8 = @splat(null);
+ for (names, &saved) |name, *value| {
+ if (libc.getenv(name)) |old| value.* = try testing.allocator.dupeSentinel(u8, std.mem.span(old), 0);
+ }
+ defer for (names, saved) |name, value| {
+ if (value) |old| {
+ _ = setenv(name, old, 1);
+ testing.allocator.free(old);
+ } else _ = @import("host_io.zig").testUnsetenv(name);
+ };
+
+ var dir: [sun_path_len:0]u8 = undefined;
+ _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1);
+ try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?);
+ _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR");
+ _ = setenv("HOME", "/home/example", 1);
+ try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?);
+ _ = @import("host_io.zig").testUnsetenv("HOME");
+ try testing.expect(socketDir(&dir) == null);
+
+ // The socket a listener keeps while it lives.
+ const path = "/tmp/pardes-example.sock";
+ @memcpy(own_socket[0..path.len], path);
+ own_socket[path.len] = 0;
+ own_socket_len = path.len;
+ defer own_socket_len = 0;
+ var own: [16]u8 = undefined;
+ const own_pid = try std.fmt.bufPrint(&own, "{d}", .{@as(u32, @intCast(libc.getpid()))});
+
+ // A `--nested` session: reachable for scripts and mounts, but nobody's
+ // parent, so a pardes started in one of its shells runs a session of
+ // its own instead of handing its argument over.
+ exportEnv(7, false);
+ try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?);
+ try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null);
+
+ exportEnv(8, true);
+ try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?);
+ try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?);
+
+ // A session whose listener never came up is still the session this shell
+ // is inside: the pid stands on its own, and only the address is missing.
+ own_socket_len = 0;
+ exportEnv(0, true);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null);
+ try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?);
+
+ exportEnv(0, false);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null);
+ try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null);
+}