diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-18 20:52:50 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-18 21:22:58 -0300 |
| commit | a75956bb3443aa8aac778d2ff12c42f5ef99e0e9 (patch) | |
| tree | 17547cbf6606c8bd05be313cd8f835cb85d13e57 /runtime | |
| parent | 5b33c88476054fffc1044fff0526f7f0b28563cf (diff) | |
| download | pardes-a75956bb3443aa8aac778d2ff12c42f5ef99e0e9.tar.gz pardes-a75956bb3443aa8aac778d2ff12c42f5ef99e0e9.zip | |
runtime: main, daemon, upgrade, crash, addon_test, 9p_io, 9p and macos.zig into runtime/ (the reorganisation's tree, step 2a), skill.txt with main.zig, its one reader: module `runtime` (runtime/root.zig) and the core, each naming the other, a product's root (main.zig, macos.zig) a module of its own over both; the files name across by module (`@import("runtime").daemon`, `@import("core").look`), pardes.zig exporting what they name (ctl, edit_cmd, tracy, selection_pipe, and the frontends until they move); core-test and shell-test run each module's test program, so the same tests run (the ledger: every named test of every suite the base's, tui and gui); nothing else changes: frames byte-identical, the same counts (tui core-test 822/963, the one more an anonymous collector)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/9p.zig | 72 | ||||
| -rw-r--r-- | runtime/9p_io.zig | 2789 | ||||
| -rw-r--r-- | runtime/addon_test.zig | 253 | ||||
| -rw-r--r-- | runtime/crash.zig | 256 | ||||
| -rw-r--r-- | runtime/daemon.zig | 1251 | ||||
| -rw-r--r-- | runtime/macos.zig | 2669 | ||||
| -rw-r--r-- | runtime/main.zig | 1926 | ||||
| -rw-r--r-- | runtime/root.zig | 26 | ||||
| -rw-r--r-- | runtime/skill.txt | 47 | ||||
| -rw-r--r-- | runtime/upgrade.zig | 510 |
10 files changed, 9799 insertions, 0 deletions
diff --git a/runtime/9p.zig b/runtime/9p.zig new file mode 100644 index 00000000..61715750 --- /dev/null +++ b/runtime/9p.zig @@ -0,0 +1,72 @@ +//! The editor's 9P surface. The wire protocol, the client, the transports +//! and the file-server engine (`cloud9.fs.Server`) live in cloud9; this +//! module names the engine configuration Pardes builds, the editor's, and +//! re-exports what the transports use. +const cloud9 = @import("cloud9"); +pub const fs = cloud9.fs; +pub const Server = cloud9.fs.Server; +pub const header_len = cloud9.header_len; +pub const notag = cloud9.notag; +pub const nofid = cloud9.nofid; +pub const max_welem = cloud9.max_welem; +pub const Qid = cloud9.Qid; +pub const Stat = cloud9.Stat; +pub const Msg = cloud9.Msg; +pub const Decoded = cloud9.Decoded; +pub const frameLen = cloud9.frameLen; +pub const encode = cloud9.encode; +pub const decode = cloud9.decode; +pub const qtdir = cloud9.qtdir; +pub const Client = cloud9.Client; +pub const oread = cloud9.oread; +pub const owrite = cloud9.owrite; +pub const ordwr = cloud9.ordwr; +pub const otrunc = cloud9.otrunc; +pub const errmax = cloud9.fs.errmax; +pub const errString = cloud9.fs.errString; +pub const msize_min = cloud9.fs.msize_min; + +/// The smallest msize a native listener offers (src/9p_io.zig). +pub const min_msize: u32 = 4096; +/// What a native listener negotiates. +pub const msize: u32 = 65536; + +/// The editor's engine: native fid count, native file names, and room to +/// park a write of any size a frame can carry -- a request that would change +/// a pane while the editor is out in a syscall waits in the engine +/// (src/9p_io.zig, `serve`), and a write it cannot keep would fail instead. +/// The largest write is msize less the Twrite header, 23 bytes (the test +/// below asks a client), one byte more than `iohdrsz` allows for. +/// Up to 128 reads held on one connection (a follower each of the log or +/// an event file); the next is refused `too many reads waiting: 128`. A +/// mount (9ns) keeps a wider window, 256, so held reads never take every +/// one of its workers. +pub const editor: cloud9.fs.Options = .{ .fid_capacity = max_fids, .name_capacity = 255, .park_data_max = msize - 23, .slot_capacity = max_held }; + +pub const max_held: usize = 128; +pub const max_fids: usize = 256; + +const std = @import("std"); +const testing = std.testing; + +const Stub = struct { + pub const Req = cloud9.fs.Req; + pub const Reply = cloud9.fs.Reply; +}; + +test "9p server: the editor's engine can park the largest write a client sends" { + var in: [4096]u8 = undefined; + var out: [4096]u8 = undefined; + var client: Client = .init(.{ .in = &in, .out = &out }); + client.msize = msize; + try testing.expect(editor.park_data_max >= client.maxWrite()); +} + +test "9p server: the editor's capacities size the actual fid storage" { + const Native = Server(Stub, editor); + const NativeFids = @FieldType(Native, "fids"); + try testing.expectEqual(256, @typeInfo(NativeFids).array.len); + try testing.expectEqual(255, @sizeOf(@FieldType(Native.Fid, "name"))); + try testing.expectEqual(256 * @sizeOf(Native.Fid), @sizeOf(NativeFids)); + try testing.expect(min_msize >= msize_min); +} diff --git a/runtime/9p_io.zig b/runtime/9p_io.zig new file mode 100644 index 00000000..acc851c4 --- /dev/null +++ b/runtime/9p_io.zig @@ -0,0 +1,2789 @@ +const std = @import("std"); +/// libc: sockets, flock'd lock files, and the registry's symlinks, judged with readlink's own truncation and unlinked from signal handlers. +const libc = std.c; +const builtin = @import("builtin"); +const ninep = @import("9p.zig"); +const cloud9 = @import("cloud9"); +const transport = cloud9.transport; +const pardes = @import("core"); +const limits = @import("core").memory.limits; +const log = std.log.scoped(.ninep); + +const nowMs = transport.nowMs; + +fn nap(ms: c_int) void { + _ = libc.poll(&[0]libc.pollfd{}, 0, ms); +} + +pub const darwin = builtin.os.tag.isDarwin(); +pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd or darwin; +pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; + +pub fn setCloexec(fd: c_int) void { + _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, 1)); +} + +pub fn socketDir(buf: []u8) ?[:0]const u8 { + if (libc.getenv("XDG_RUNTIME_DIR")) |path| + return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(path)}, 0) catch null; + const home = libc.getenv("HOME") orelse return null; + return std.fmt.bufPrintSentinel(buf, "{s}/.local/state/pardes", .{std.mem.span(home)}, 0) catch null; +} + +pub const FileFacts = struct { mode: u32, uid: libc.uid_t }; + +pub fn statNoFollow(path: [:0]const u8) ?FileFacts { + if (comptime builtin.os.tag != .linux) { + var stat: libc.Stat = undefined; + if (libc.fstatat(libc.AT.FDCWD, path, &stat, libc.AT.SYMLINK_NOFOLLOW) != 0) return null; + return .{ .mode = stat.mode, .uid = stat.uid }; + } else { + const linux = std.os.linux; + var stat: linux.Statx = undefined; + const fields: linux.STATX = .{ .TYPE = true, .MODE = true, .UID = true }; + if (libc.statx(linux.AT.FDCWD, path, linux.AT.SYMLINK_NOFOLLOW, fields, &stat) != 0) return null; + return .{ .mode = stat.mode, .uid = stat.uid }; + } +} + +pub fn ensureSocketDir(dir: [:0]const u8) bool { + if (dir.len == 0) return false; + // A failure shows in the stat below. + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o700)) catch {}; + const stat = statNoFollow(dir) orelse return false; + return stat.mode & 0o170000 == 0o040000 and stat.uid == libc.getuid() and stat.mode & 0o077 == 0; +} + +const prefix = "pardes-9p-"; + +pub const msize = ninep.msize; + +/// Scripts, a mount and an agent or two at once; each slot holds its +/// buffers (a few msize) whether used or not. +pub const max_conns = 16; + +extern "c" fn inet_pton(family: c_int, src: [*:0]const u8, dst: *anyopaque) c_int; + +pub fn networkAddress(dial: []const u8, allow_zero_port: bool) error{BadDial}!std.Io.net.IpAddress { + if (comptime !supported) return error.BadDial; + const host_start: usize = if (std.mem.startsWith(u8, dial, "tcp!")) 4 else return error.BadDial; + const split = std.mem.lastIndexOfScalar(u8, dial, '!') orelse return error.BadDial; + if (split <= host_start or split + 1 == dial.len) return error.BadDial; + const port_text = dial[split + 1 ..]; + for (port_text) |c| if (c < '0' or c > '9') return error.BadDial; + const port = std.fmt.parseInt(u16, port_text, 10) catch return error.BadDial; + if (port == 0 and !allow_zero_port) return error.BadDial; + const host = dial[host_start..split]; + if (std.mem.indexOfScalar(u8, host, 0) != null) return error.BadDial; + var host_buf: [46]u8 = undefined; + const host_z = std.fmt.bufPrintSentinel(&host_buf, "{s}", .{host}, 0) catch return error.BadDial; + var ip4: std.Io.net.Ip4Address = .{ .port = port, .bytes = undefined }; + if (inet_pton(libc.AF.INET, host_z, &ip4.bytes) == 1) return .{ .ip4 = ip4 }; + var ip6: std.Io.net.Ip6Address = .{ .port = port, .bytes = undefined }; + if (inet_pton(libc.AF.INET6, host_z, &ip6.bytes) == 1) return canonicalIp(.{ .ip6 = ip6 }); + return error.BadDial; +} + +fn canonicalIp(address: std.Io.net.IpAddress) std.Io.net.IpAddress { + if (address == .ip6) { + if (std.Io.net.Ip4Address.fromIp6(address.ip6)) |ip4| return .{ .ip4 = ip4 }; + } + return address; +} + +/// The Unix and TCP listeners run on cloud9's `std.Io` runner: it accepts, +/// reads frames, steps each connection's engine and writes replies on its +/// own tasks, and every backend request is answered right there, on the +/// connection's task, by taking the editor's turn (`pardes.turn`): while the +/// editor waits for input, or while a step of it is out in a syscall -- +/// which is what lets the editor read its own tree through a mount. +const Runner = if (supported) cloud9.serve.Runner(pardes.ctlfs, ninep.editor, .{ + .msize = msize, + .connections = max_conns, + .listeners = 2, +}) else void; + +pub const Listener = struct { + io: std.Io, + /// The core that answers; `reset` puts a replacement in. + core: *pardes.Pardes, + /// cloud9's runner, sized for every connection's buffers and parks (some + /// 136 MiB): pages of its own (`allocRunner`), written only as clients + /// take slots, so an idle session does not hold them resident. + runner: *Runner = undefined, + stopping: std.atomic.Value(bool) = .init(false), + /// The watchers of held Edit writes (watchEdit): canceled and awaited + /// by `deinit`, once the turn lets a waiting one through, so none wakes + /// into a freed Listener. + edit_watchers: std.Io.Group = .init, + /// A connection wrote the Restore and has yet to answer it. + restore_writer: std.atomic.Value(bool) = .init(false), + /// Clients turned away with every slot taken, since the log last said so. + refused: std.atomic.Value(u32) = .init(0), + /// Writes being served right now, a retry of a parked one included: a + /// held Edit write a retry has taken out of its park is not flushed + /// (watchEdit). + writes_out: std.atomic.Value(u32) = .init(0), + /// Connections accepted so far, and the count each slot's connection + /// was accepted at: a Restore cuts those accepted before it (`reset`), + /// and a new client in a freed slot has a later stamp. Written on the + /// connection's task as it opens, read with the turn. + accepts: std.atomic.Value(u64) = .init(0), + accepted: [max_conns]std.atomic.Value(u64) = @splat(.init(0)), + /// Connections accepted before this count are being cut by a Restore. + cut_before: u64 = 0, + tcp_address: ?std.Io.net.IpAddress = null, + path_buf: [sun_path_len]u8 = undefined, + path_len: usize = 0, + /// The socket's lock (`claim`), held for the listener's life; -1 when none. + lock: c_int = -1, + lock_buf: [lock_path_len:0]u8 = undefined, + /// The registry entry this editor posted + /// (`$XDG_RUNTIME_DIR/9p/pardes/<name>`), zero when it did not. + posted_buf: [sun_path_len]u8 = undefined, + posted_len: usize = 0, + wake_ctx: ?*anyopaque = null, + wake: ?*const fn (?*anyopaque) void = null, + + pub fn path(l: *const Listener) []const u8 { + return l.path_buf[0..l.path_len]; + } + + /// The runner's handler, on the connection's task: takes the turn and + /// answers. A request that would change a pane while the editor is out + /// in a syscall mid-step is parked in the engine instead, and retried + /// when the turn is next given up between steps (`wakeParked`). + /// On the accepting task, without the turn: counted, and logged with + /// the turn (`answerHeld`). + fn onRefused(ctx: ?*anyopaque) void { + const l: *Listener = @ptrCast(@alignCast(ctx.?)); + _ = l.refused.fetchAdd(1, .acq_rel); + l.kick(); + } + + fn onOpened(ctx: ?*anyopaque, conn: *Runner.Conn) void { + const l: *Listener = @ptrCast(@alignCast(ctx.?)); + l.accepted[conn.index].store(l.accepts.fetchAdd(1, .acq_rel) + 1, .release); + } + + /// A live connection accepted before the Restore under way. + fn cutting(l: *Listener, conn: *Runner.Conn) bool { + return conn.live() and l.accepted[conn.index].load(.acquire) <= l.cut_before and l.cut_before != 0; + } + + fn onServe(ctx: ?*anyopaque, conn: *Runner.Conn, req: pardes.ctlfs.Req) void { + const l: *Listener = @ptrCast(@alignCast(ctx.?)); + if (req.op == .write) _ = l.writes_out.fetchAdd(1, .acq_rel); + defer if (req.op == .write) { + _ = l.writes_out.fetchSub(1, .acq_rel); + }; + // Once `stop` has begun the editor is tearing down and may never + // rest again: answer without waiting on it. + if (l.stopping.load(.acquire)) { + const refused = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); + return conn.reply(&refused, ""); + } + const quiet = pardes.turn.take(); + defer pardes.turn.give(); + // A connection a Restore is cutting (`reset`) is the old editor's + // client: its fids name the old editor's panes and opens. + if (l.cutting(conn)) { + const refused = pardes.ctlfs.Reply.fail(req.tag, pardes.ctlfs.E.IO); + return conn.reply(&refused, ""); + } + if (!quiet and pardes.ctlfs.needsQuiet(l.core, req)) { + pardes.turn.parked = true; + const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; + return conn.reply(&later, ""); + } + const core = l.core; + core.fs.write_room = if (conn.engine.protocol.msize > 24) conn.engine.protocol.msize - 24 else 0; + const epoch = pardes.turn.epoch; + const restores = pardes.turn.restores; + // Asked first: a release that runs a held line has none after. + const changes = pardes.ctlfs.changesPane(core, req); + const fills = pardes.ctlfs.handsOff(core, req); + const reply = core.serveFs(req); + const edit_started = core.fs.edit_started; + core.fs.edit_started = false; + // The held Edit write asked again by a retry, its Edit still + // running: parked again, as it was. + if (reply.status == .again and req.op == .write) return conn.reply(&reply, ""); + if (req.op == .release and quiet) l.collectOs(); + // A close's held last line runs now when no step is out, so its err + // is logged before the close is answered, as before; with a step + // out (perhaps through a mount this close came by) it waits for + // that step, and the close is answered at once all the same. + if (req.op == .release and quiet) pardes.ctlfs.runClosedLines(core); + // A read with nothing yet stays parked in the engine, and the core + // keeps its ticket to answer it when what it waits on has something. + if (reply.status == .again and req.op == .read) { + // Only an open's record can hold a read; one that waits with + // none would sit parked until some unrelated write parks. + const o = pardes.ctlfs.openOf(core, req) orelse { + log.err("a read of node {x} waits with no open record to hold it", .{req.node}); + std.debug.assert(false); + return conn.reply(&reply, ""); + }; + // One read waits on an open at a time, as acme's window keeps + // one `eventx`; a second is refused rather than left parked + // where nothing would ever answer it. The first asked again by + // a retry is the same request, and holds its place. + if (o.held) |held| if (held.req.tag != req.tag) { + const other: *Runner.Conn = @ptrCast(@alignCast(held.asker)); + if (other.waiting(held.ticket)) + return conn.reply(&pardes.ctlfs.failText(req.tag, pardes.ctlfs.E.BUSY, pardes.ctlfs.e_in_use), ""); + }; + o.held = null; + const ticket = conn.hold(&reply) orelse return; + o.held = .{ .asker = conn, .req = req, .ticket = ticket }; + return; + } + if (!changes) return conn.reply(&reply, core.fsPayload(reply)); + // The editor draws the change and performs what it asked for; when + // it asked for something -- a save, a shell, a watch -- the answer + // waits until that is done, so `echo Save > exec` returns with the + // file written. A change carries no payload, so the reply is still + // whole after the wait. + l.kick(); + // A read that put a /pager open's text in (ctl.fillPager), or a + // close that handed its text or last line to the editor's step + // (ctl.fillClosedPagers, tree.runClosedLines), waits on nothing the + // editor performs: its answer goes now, while the turn still keeps + // a read's payload whole. Waiting would hang a close through a + // mount: 9ns answers nothing else on it while a clunk is out, and + // the editor's step may be out opening a file through that mount. + if (fills) return conn.reply(&reply, core.fsPayload(reply)); + // A refusal that left saves going (Putall's one refused among the + // rest) is answered once they have landed, its words copied out of + // the core's one buffer for them, which a request run meanwhile + // could write over. + if (reply.status == .err and core.effects_len != 0 and !core.quit) { + var kept: [320]u8 = undefined; + const words = kept[0..@min(reply.ename.len, kept.len)]; + @memcpy(words, reply.ename[0..words.len]); + var waited = reply; + waited.ename = words; + pardes.turn.awaitPast(&pardes.turn.epoch, epoch); + return conn.reply(&waited, ""); + } + // Any other refusal answers at once, for the same buffer's sake. + if (reply.status == .err) return conn.reply(&reply, ""); + // A write that quits the editor (Kill) is answered now: the editor + // is on its way out and will settle nothing this could wait for, + // and `deinit` lets the answer out before it cuts the connections. + if (core.quit) return conn.reply(&reply, ""); + // An Edit whose `<`, `|` or `>` commands run off the loop: the write + // is held, as a read with nothing yet is, and answered when the Edit + // is done (answerHeld), so the connection serves on meanwhile -- a + // filter that reads this session through a mount among what it + // serves. A flush of it, or a hang-up, stops the Edit (watchEdit). + if (edit_started and core.pipe.edit_run != null) { + const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; + const ticket = conn.hold(&later) orelse return; + core.fs.edit_hold = .{ .asker = conn, .slot = ticket.slot, .seq = ticket.seq, .tag = req.tag, .node = req.node, .handle = req.handle, .written = reply.written }; + l.edit_watchers.concurrent(l.io, watchEdit, .{ l, conn, ticket }) catch {}; + return; + } + const restoring = core.restore_req != null; + // Set with the turn still held, so `reset` sees it and waits. + if (restoring) l.restore_writer.store(true, .release); + defer if (restoring) l.restore_writer.store(false, .release); + core.fs.late_failure_len = 0; + // What fails while this waits is this write's err, never a msg too. + core.fs.write_waits = true; + if (core.effects_len != 0) pardes.turn.awaitPast(&pardes.turn.epoch, epoch); + if (core.fs.lsp_answer_at) |n| { + core.fs.lsp_answer_at = null; + core.fs.lsp_result = null; + pardes.turn.awaitPast(&pardes.turn.lsp_answers, n); + // The answer filled a pane (a Rename's preview): that is what + // this write's open reads back, as look and exec answer. + if (l.core == core) if (core.fs.lsp_result) |serial| { + core.fs.lsp_result = null; + core.fs.results[0] = serial; + core.fs.results_len = 1; + if (pardes.ctlfs.openOf(core, req)) |o| { + o.results.list[0] = serial; + o.results.len = 1; + o.results.read = 0; + } + }; + } + core.fs.write_waits = false; + // ponytail: one slot, so a failure of another client's effects that + // settle in the same wait is told to this write too. + if (l.core == core and core.fs.late_failure_len != 0) { + const late = core.fs.late_failure[0..core.fs.late_failure_len]; + // The errno a builtin's failure in the same words has; what + // that leaves EIO and says `no space` (a full disk under a + // Save) is ENOSPC. + const said = @import("core").ctl.failureErrno(late); + const errno = if (said == pardes.ctlfs.E.IO and std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else said; + const failed = pardes.ctlfs.failText(req.tag, errno, late); + // Its err record says it (the path in it), the one record: it + // was said with no msg while this waited (fs.write_waits). + pardes.ctlfs.events.noteError(core, req, failed); + return conn.reply(&failed, ""); + } + // The Restore's own write is answered once it is done, and before + // `reset` hangs every connection up, this one too, so the writer + // hears that it happened rather than a cut; a failed one leaves the + // connection and says why on the message row and in the log. + if (restoring) { + if (l.core == core) pardes.turn.awaitPast(&pardes.turn.restores, restores); + return conn.reply(&reply, ""); + } + // Once a wait returns `core` may be gone: a Restore meanwhile put a + // replacement in and is hanging this connection up. + if (l.core != core) return; + conn.reply(&reply, ""); + } + + /// With the turn, as it is given up: answers each read the core holds + /// whose file now has something, on the connection that asked, with no + /// retry of anything else parked there. Only while its ticket still + /// waits, asked in the same hold of the engine as the answer: Tflush + /// and clunk drop a park without a word to the backend, a `retry` takes + /// one out to ask again (and that asking answers it), and a record spent + /// on any of them would be lost to the reader that comes next. + fn answerHeld(ctx: ?*anyopaque) void { + if (comptime !supported) return; + const l: *Listener = @ptrCast(@alignCast(ctx.?)); + if (l.stopping.load(.acquire)) return; + const core = l.core; + const refused = l.refused.swap(0, .acq_rel); + if (refused != 0) { + var why: pardes.Kind.Buf(64) = .{}; + pardes.ctlfs.events.notePath(core, "err -", why.print("9p: too many connections ({d} turned away)", .{refused})); + } + if (!core.fs.news) return; + core.fs.news = false; + for (&core.fs.opens) |*o| { + const held = o.held orelse continue; + const conn: *Runner.Conn = @ptrCast(@alignCast(held.asker)); + if (!conn.answerWith(held.ticket, Held{ .core = core, .req = held.req }, Held.make)) o.held = null; + } + // An Edit's held write, its Edit done. Not waiting: a retry has it + // out, and its asking answers it (Pardes.serveFs); or it was + // flushed, and watchEdit lets the record go. + if (core.fs.edit_hold) |h| if (h.done) { + const conn: *Runner.Conn = @ptrCast(@alignCast(h.asker)); + _ = conn.answerWith(.{ .slot = h.slot, .seq = h.seq }, core, struct { + fn make(c: *pardes.Pardes) ?Runner.Conn.Answer { + return .{ .reply = pardes.filesystem.EditHold.answer(&c.fs) }; + } + }.make); + }; + } + + /// While an Edit's write is held: when nobody waits for it any more -- + /// flushed (an interrupted writer), its fid clunked, its connection + /// hung up -- the Edit is stopped, its commands killed, nothing + /// changed (edit_cmd.cancel). The engine tells the backend nothing of a + /// flush, so it is looked for, every 100 ms; a park out for a retry is + /// not waiting either, so only three looks in a row with no write being + /// served count. + fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) error{Canceled}!void { + var misses: u8 = 0; + while (!l.stopping.load(.acquire)) { + try l.io.sleep(.fromMilliseconds(100), .awake); + _ = pardes.turn.take(); + defer pardes.turn.give(); + if (l.stopping.load(.acquire)) return; + const core = l.core; + const h = core.fs.edit_hold orelse return; + if (h.slot != ticket.slot or h.seq != ticket.seq or h.asker != @as(*anyopaque, conn)) return; + if (conn.waiting(ticket) or l.writes_out.load(.acquire) != 0) { + misses = 0; + continue; + } + misses += 1; + if (misses < 3) continue; + if (h.done) core.fs.edit_hold = null else @import("core").edit_cmd.cancel(core); + l.kick(); + return; + } + } + + /// A held read asked again, to make its answer while its park waits. + const Held = struct { + core: *pardes.Pardes, + req: pardes.ctlfs.Req, + + fn make(h: Held) ?Runner.Conn.Answer { + const reply = h.core.serveFs(h.req); + if (reply.status == .again) return null; + return .{ .reply = reply, .bytes = h.core.fsPayload(reply) }; + } + }; + + /// The turn was given up quiet with a request parked: every connection + /// retries what it parked. + fn wakeParked(ctx: ?*anyopaque) void { + const l: *Listener = @ptrCast(@alignCast(ctx.?)); + if (l.stopping.load(.acquire)) return; + if (comptime supported) l.runner.wakeAll(); + } + + /// A request changed the core: the editor wakes to draw it and perform + /// what it asked for. + fn kick(l: *Listener) void { + if (l.stopping.load(.acquire)) return; + if (l.wake) |f| f(l.wake_ctx); + } + + pub const greet_deadline_ms: i64 = 5000; + + /// What a frontend's poll of the listener did; the runner's own tasks + /// serve every connection, so there is never more to do at once. + pub const Polled = struct { count: usize = 0, pending: bool = false }; + + /// Between the editor's steps, which is when the host paths may be + /// swept: the editor's own directory listings leave nodes in it too. + pub fn tick(l: *Listener) Polled { + l.collectOs(); + return .{}; + } + + /// Hangs every connection up, so that `replacement` starts with no + /// client holding anything. From here requests are answered from the + /// replacement -- a client that connects meanwhile is a client of the + /// replacement -- and every task waiting on the old core is let go: the + /// Restore's own writer answers, the rest find the core changed and + /// answer nothing, their connections being hung up. The connections pay their releases on their own tasks, so + /// the editor rests while they do. + pub fn reset(l: *Listener, replacement: *pardes.Pardes) void { + // A follower of the log hears every record queued before the cut, in + // the answer to the read it holds; the read after it is cut. + l.core.fs.hanging_up = true; + l.core.fs.news = true; + answerHeld(l); + l.core.fs.hanging_up = false; + l.core = replacement; + replacement.fs.socket_path = l.path(); + replacement.fs.tcp_address = l.tcp_address; + if (comptime supported) { + // The Restore's writer answers as it wakes (`onServe`), and its + // answer gets 200 ms to leave before the cut; every other request + // from the old editor's clients meanwhile is refused, since the + // fids it names are the old editor's. A client that connects now + // is the replacement's, and stays. + l.cut_before = l.accepts.load(.acquire); + pardes.turn.bump(&pardes.turn.epoch); + pardes.turn.bump(&pardes.turn.restores); + pardes.turn.rest(); + l.flushOut(); + for (&l.runner.conns) |*conn| if (l.cutting(conn)) conn.close(); + const deadline = nowMs() +| 2000; + while (nowMs() < deadline) { + const left = for (&l.runner.conns) |*conn| { + if (l.cutting(conn)) break true; + } else false; + if (!left) break; + nap(1); + } + pardes.turn.wake(); + l.cut_before = 0; + } + l.collectOs(); + } + + /// Forgets the host paths no connection names any more. With the turn, + /// and only between the editor's steps: a step out in a syscall may be + /// reading one of these entries. + fn collectOs(l: *Listener) void { + // A request out in a host syscall may be using an entry's path, or + // made one that no fid names yet (a walk's next element): swept at + // the next quiet instead. Taken back after a step of its own, the + // editor's frame (tty pollFrame) came here with one out, and a walk + // of a directory just made was answered ENOENT. + if (pardes.turn.out != 0) return; + const core = l.core; + var i: usize = 0; + while (i < core.fs.os_paths.items.len) { + const entry = core.fs.os_paths.items[i]; + if (l.references(entry.node)) { + i += 1; + } else { + core.gpa.free(entry.path); + _ = core.fs.os_paths.swapRemove(i); + } + } + } + + /// Whether any connection names `node`. + fn references(l: *Listener, node: u64) bool { + if (comptime supported) { + for (&l.runner.conns) |*conn| { + if (!conn.live()) continue; + conn.lock(); + defer conn.unlock(); + if (conn.engine.references(node)) return true; + } + } + return false; + } + + /// Where the runner's tasks report that a request changed the core. + pub fn watch(l: *Listener, ctx: ?*anyopaque, wake: *const fn (?*anyopaque) void) !void { + l.wake_ctx = ctx; + l.wake = wake; + } + + /// Advertises this editor in the posted-9P registry so a + /// `9ns --mntgen` mount lists it and dials it on a walk: + /// `$XDG_RUNTIME_DIR/9p/pardes/<name>` is a symlink to the socket + /// pardes already binds. One directory for the program, one entry + /// per running editor — the layout zmx uses for its sessions, so + /// several editors group instead of crowding the registry root. + /// + /// Only the runtime-directory socket posts: an instance that fell + /// back to `~/.local/state/pardes` stays out of the user's + /// registry, the way a private `ZMX_DIR` does for zmx. + /// + /// The socket itself is still bound by `listen` above, not by + /// `cloud9.post`: `post` claims flat names only, and its claim + /// protocol derives its lock directory from the registry path, so + /// a name inside a subdirectory cannot go through it yet. See + /// docs/typ/building.typ. + fn postToRegistry(l: *Listener, name: []const u8) void { + if (comptime !supported) return; + if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) return; + const xdg_c = libc.getenv("XDG_RUNTIME_DIR") orelse return; + const xdg = std.mem.span(xdg_c); + if (xdg.len == 0) return; + + var reg_buf: [sun_path_len:0]u8 = undefined; + const reg = std.fmt.bufPrintSentinel(®_buf, "{s}/9p", .{xdg}, 0) catch return; + _ = libc.mkdir(reg, 0o750); + var svc_buf: [sun_path_len:0]u8 = undefined; + const svc = std.fmt.bufPrintSentinel(&svc_buf, "{s}/9p/pardes", .{xdg}, 0) catch return; + if (libc.mkdir(svc, 0o750) != 0 and statNoFollow(svc) == null) { + log.warn("registry post skipped: cannot create {s}", .{svc}); + return; + } + sweepRegistry(l.io, svc, xdg); + var entry_buf: [sun_path_len:0]u8 = undefined; + const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch { + log.warn("registry post skipped: name too long: {s}", .{name}); + return; + }; + const target = l.path_buf[0..l.path_len]; + + // Replace only what is provably not live: our own entry, or a + // dead predecessor's symlink. `probe` treats uncertainty as + // live, so it is only asked about an entry that *is* a symlink; + // anything else is left strictly alone and the symlink below + // simply fails. + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(entry, &link_buf, link_buf.len); + if (n >= 0) { + const had = link_buf[0..@intCast(n)]; + if (!std.mem.eql(u8, had, target) and probe(entry) == .live) { + log.warn("registry entry pardes/{s} is live; not re-posted", .{name}); + return; + } + _ = libc.unlink(entry); + } + var target_z: [sun_path_len:0]u8 = undefined; + const target_zs = std.fmt.bufPrintSentinel(&target_z, "{s}", .{target}, 0) catch return; + if (libc.symlink(target_zs, entry) != 0) { + log.warn("registry post skipped: pardes/{s} is occupied", .{name}); + return; + } + @memcpy(l.posted_buf[0..entry.len], entry); + l.posted_len = entry.len; + log.info("posted pardes/{s} -> {s}", .{ name, target }); + } + + /// Removes the registry entry, but only while it is still ours: a + /// name another editor has since claimed is never unlinked. + fn unpostFromRegistry(l: *Listener) void { + if (comptime !supported) return; + if (l.posted_len == 0) return; + var z: [sun_path_len:0]u8 = undefined; + @memcpy(z[0..l.posted_len], l.posted_buf[0..l.posted_len]); + z[l.posted_len] = 0; + const entry = z[0..l.posted_len :0]; + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(entry, &link_buf, link_buf.len); + if (n >= 0 and std.mem.eql(u8, link_buf[0..@intCast(n)], l.path_buf[0..l.path_len])) { + _ = libc.unlink(entry); + } + l.posted_len = 0; + } + + /// What the connections have still to send let go, 200 ms at most, + /// before they are cut (a quit, an Upgrade's exec, a Restore: its + /// write's answer, which a Restore's writer has yet to give while + /// `restore_writer` says so). + pub fn flushOut(l: *Listener) void { + if (comptime !supported) return; + const deadline = nowMs() +| 200; + while (nowMs() < deadline) { + const pending = l.restore_writer.load(.acquire) or for (&l.runner.conns) |*conn| { + if (!conn.live()) continue; + conn.lock(); + const n = conn.engine.output().len; + conn.unlock(); + if (n != 0) break true; + } else false; + if (!pending) break; + nap(1); + } + nap(1); // the last bytes leave the stream's own buffer + } + + pub fn deinit(l: *Listener, gpa: std.mem.Allocator) void { + l.stopping.store(true, .release); + l.unpostFromRegistry(); + if (comptime supported) { + // A connection task may be waiting for the turn; it answers + // nothing more once stopping, but the wait itself must end. + pardes.turn.rest(); + l.edit_watchers.cancel(l.io); + // An answer given as the editor quit (a Kill written to /ctl) + // may still be on its way out: let it go before the cut. + l.flushOut(); + l.runner.stop(); + pardes.turn.wake(); + } + pardes.turn.wake_parked = null; + pardes.turn.answer_held = null; + pardes.turn.stop(); + own_socket_len = 0; // removed here, not again by a signal + if (l.path_len != 0) { + var z: [sun_path_len:0]u8 = undefined; + @memcpy(z[0..l.path_len], l.path_buf[0..l.path_len]); + z[l.path_len] = 0; + _ = libc.unlink(z[0..l.path_len :0]); + } + // The lock after the socket: a socket there never lacks a held lock. + if (l.lock >= 0) release(l.lock, std.mem.sliceTo(&l.lock_buf, 0)); + freeRunner(l.runner); + gpa.destroy(l); + } +}; + +/// The runner's memory, from the page allocator with no fill: an Allocator's +/// `create` writes `undefined` over all of it in a safe build, which would make +/// every page resident at startup. +fn allocRunner() ?*Runner { + if (comptime !supported) return @constCast(&@as(Runner, {})); + const bytes = std.heap.page_allocator.rawAlloc(@sizeOf(Runner), .of(Runner), @returnAddress()) orelse return null; + @import("core").memory.sparse(bytes[0..@sizeOf(Runner)]); + return @ptrCast(@alignCast(bytes)); +} + +fn freeRunner(runner: *Runner) void { + if (comptime !supported) return; + std.heap.page_allocator.rawFree(@as([*]u8, @ptrCast(runner))[0..@sizeOf(Runner)], .of(Runner), @returnAddress()); +} + +/// The socket this process listens on, kept where a fatal signal's handler +/// can reach it without allocating (unlinkOwnSocket); empty when none. +var own_socket: [lock_path_len:0]u8 = undefined; +var own_socket_len: usize = 0; + +/// Removes the socket this process listens on, then its lock (the death +/// lets go of it). Async-signal-safe (two unlinks): SIGTERM and SIGHUP call +/// it before the signal's own death, so a killed editor leaves no socket +/// behind. +pub fn unlinkOwnSocket() void { + if (comptime !supported) return; + const n = own_socket_len; + if (n == 0) return; + own_socket_len = 0; + _ = libc.unlink(own_socket[0..n :0]); + own_socket[n..][0..lock_suffix.len].* = lock_suffix.*; + own_socket[n + lock_suffix.len] = 0; + _ = libc.unlink(own_socket[0 .. n + lock_suffix.len :0]); +} + +/// SIGTERM, SIGHUP and SIGINT with no handler of their own (a GUI's, a +/// detached session's): the socket goes, then the signal's own death. A +/// host that handles them itself (the terminal's Killed, SDL's quit) +/// removes it its own way. +fn armSocketCleanup() void { + const sig = std.posix.SIG; + const on: std.posix.Sigaction = .{ .handler = .{ .handler = onFatalSignal }, .mask = std.posix.sigemptyset(), .flags = std.posix.SA.RESETHAND }; + for ([_]std.posix.SIG{ sig.TERM, sig.HUP, sig.INT }) |s| { + var was: std.posix.Sigaction = undefined; + std.posix.sigaction(s, null, &was); + if (was.handler.handler == sig.DFL) std.posix.sigaction(s, &on, null); + } +} + +/// What else a fatal signal's handler removes (host_io's private prompt +/// files); async-signal-safe. +pub var fatal_cleanup: ?*const fn () void = null; + +fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { + unlinkOwnSocket(); + if (fatal_cleanup) |cleanup| cleanup(); + // Its shells go with it, the daemon's dups let go. + @import("daemon.zig").hangUp(); + // SA_RESETHAND put the default back: the same signal, now fatal. + _ = std.c.raise(s); +} + +/// Removes `pardes-9p-<pid>.sock` files under `dir` whose pid is gone +/// (kill(pid, 0) answers ESRCH): what an editor killed by a signal it could +/// not catch, or a crash, left behind. A live pid's socket, a named +/// session's, anything not a socket of this user's, and one something +/// still answers on are left alone. +pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { + if (comptime !supported) return; + var names: [8192]u8 = undefined; + const staged = stageNames(io, dir, &names, struct { + fn keep(name: []const u8) bool { + return deadSocketPid(name) != null; + } + }.keep); + var i: usize = 0; + while (i < staged) { + const name = names[i + 1 ..][0..names[i]]; + i += 1 + name.len; + const pid = deadSocketPid(name).?; + if (pid == libc.getpid()) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; + var path_buf: [sun_path_len:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0) catch continue; + const facts = statNoFollow(path) orelse continue; + if (facts.mode & 0o170000 != 0o140000 or facts.uid != libc.getuid()) continue; + if (probe(path) == .live) continue; + removeDead(path); + } +} + +/// A socket's lock, `<socket>.lock` beside it: flocked by the socket's owner +/// from before it binds to after it unlinks (`claim`, `release`), so held +/// is alive and free is dead. A connect cannot say that: FreeBSD refuses one +/// to a listener whose queue is full exactly as to a socket nobody listens +/// on, and a starting owner's socket refuses until it listens. +const lock_suffix = ".lock"; +const lock_path_len = sun_path_len + lock_suffix.len; + +fn lockPath(buf: *[lock_path_len:0]u8, sock: []const u8) ?[:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "{s}" ++ lock_suffix, .{sock}, 0) catch null; +} + +/// `sock`'s lock taken (its path in `buf`), made when it is missing: null +/// while someone else holds it. A probe holds it shared for a moment, so a +/// refusal is asked again for a while before it counts. One taken on a file +/// its owner unlinked as it let go is taken again on the one at the path. +fn claim(sock: []const u8, buf: *[lock_path_len:0]u8) ?c_int { + const path = lockPath(buf, sock) orelse return null; + var tries: u32 = 0; + while (tries < 50) : (tries += 1) { + const fd = libc.open(path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); + if (fd < 0) return null; + if (libc.flock(fd, std.posix.LOCK.EX | std.posix.LOCK.NB) != 0) { + _ = libc.close(fd); + nap(1); + continue; + } + const io = std.Io.Threaded.global_single_threaded.io(); + const held = (std.Io.File{ .handle = fd, .flags = .{ .nonblocking = false } }).stat(io) catch null; + const named = std.Io.Dir.cwd().statFile(io, path, .{ .follow_symlinks = false }) catch null; + if (held != null and named != null and held.?.inode == named.?.inode) return fd; + _ = libc.close(fd); + } + return null; +} + +/// A claim let go, its lock file removed while still held: nobody else +/// unlinks it, and a claim on the unlinked file is taken again (`claim`). +fn release(fd: c_int, path: [:0]const u8) void { + _ = libc.unlink(path); + _ = libc.close(fd); +} + +/// What `sock`'s lock says of its owner: held is `.live`, free `.stale`, and +/// none at all `.none`. Anything unclear is `.live`. +fn lockState(sock: []const u8) Probe { + var buf: [lock_path_len:0]u8 = undefined; + const path = lockPath(&buf, sock) orelse return .live; + const fd = libc.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(libc.mode_t, 0)); + if (fd < 0) return if (libc.errno(fd) == .NOENT) .none else .live; + defer _ = libc.close(fd); + return if (libc.flock(fd, std.posix.LOCK.SH | std.posix.LOCK.NB) == 0) .stale else .live; +} + +/// A dead owner's socket removed, and its lock, under that lock: no new +/// owner can come between the judging and the unlink, and one that took +/// it is gone. +fn removeDead(sock: [:0]const u8) void { + var buf: [lock_path_len:0]u8 = undefined; + const fd = claim(sock, &buf) orelse return; + _ = libc.unlink(sock); + release(fd, std.mem.sliceTo(&buf, 0)); +} + +/// The names in `dir` that `keep` takes (all with none), into `names` as a length byte and +/// the name each, until it is full; the bytes staged. They are staged +/// before anything is unlinked, so a sweep never asks a directory to keep +/// reading while it is being edited. +fn stageNames(io: std.Io, dir: [:0]const u8, names: []u8, comptime keep: ?fn ([]const u8) bool) usize { + const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(d, &read_buf); + var staged: usize = 0; + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (keep) |takes| if (!takes(listed.name)) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + return staged; +} + +/// The pid a `pardes-9p-<pid>.sock` name carries, or null for any other. +fn deadSocketPid(name: []const u8) ?std.c.pid_t { + if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) return null; + const digits = name[prefix.len .. name.len - ".sock".len]; + if (digits.len == 0 or digits.len > 10) return null; + for (digits) |c| if (!std.ascii.isDigit(c)) return null; + const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null; + return if (pid > 0) pid else null; +} + +pub fn socketPath(buf: *[sun_path_len]u8, dir: []const u8, name: []const u8) ?[:0]const u8 { + if (name.len == 0) return null; + if (std.mem.indexOfAny(u8, name, "/\x00") != null) return null; + return std.fmt.bufPrintSentinel(buf, "{s}/" ++ prefix ++ "{s}.sock", .{ dir, name }, 0) catch null; +} + +/// Serves `core`. From here on the calling thread has the editor's turn +/// (`pardes.turn`) and must give it up while it waits. +pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: []const u8, fallback: []const u8, tcp_dial: ?[]const u8) !*Listener { + if (comptime !supported) return error.Unsupported; + const entry_name = if (named.len != 0) named else fallback; + // Checked before anything is made: the turn's hooks point at the + // listener from here on, and a path too long for sun_path used to free + // it with them still set, so the editor's next rest called into freed + // memory. The name the socket is first bound at, `<path>.<pid>` (it is + // renamed into place once it listens), must fit too. + refusal = ""; + if (noSocket(entry_name, &refusal_buf)) |words| { + log.warn("{s}", .{words}); + refusal = words; + return error.NameTooLong; + } + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse { + log.warn("no runtime directory for the socket", .{}); + return error.NoRuntimeDir; + }; + if (!ensureSocketDir(dir)) return error.NoRuntimeDir; + // What dead editors left behind goes first, never a live one's. + sweepDeadSockets(io, dir); + var tmp_buf: [sun_path_len]u8 = undefined; + if (std.mem.indexOfAny(u8, entry_name, "/\x00") != null or entry_name.len == 0) { + log.warn("no socket for {s}: not one path component", .{entry_name}); + return error.NameTooLong; + } + const l = try gpa.create(Listener); + l.* = .{ .io = io, .core = core }; + l.runner = allocRunner() orelse { + gpa.destroy(l); + return error.OutOfMemory; + }; + pardes.turn.start(io); + pardes.turn.wake_parked = Listener.wakeParked; + pardes.turn.answer_held = Listener.answerHeld; + pardes.turn.wake_ctx = l; + l.runner.init(.{ + .io = io, + .root = pardes.ctlfs.root, + .handler = .{ .ctx = l, .serve = Listener.onServe, .opened = Listener.onOpened, .refused = Listener.onRefused }, + .greet_timeout_ms = Listener.greet_deadline_ms, + }); + errdefer l.deinit(gpa); + const p = socketPath(&l.path_buf, dir, entry_name).?; + // The name's lock first, held from here to the end: whoever else holds + // it is alive, however its socket answers a connect. Held, a socket + // there is a dead owner's. + l.lock = claim(p, &l.lock_buf) orelse { + log.warn("something is already listening on {s}", .{p}); + return error.InUse; + }; + // Listened on under a name of its own, then renamed into place: a client + // that waits for the socket to appear finds it listening already. Bound + // at its own name, it was there a moment before listen(2), and a connect + // then was refused. + // unreachable: checked above, before anything was made + const tmp = std.fmt.bufPrintSentinel(&tmp_buf, "{s}.{d}", .{ p, libc.getpid() }, 0) catch unreachable; + const existing = @import("core").filesystem.statPath(io, p, .{ .follow_symlinks = false }) catch null; + if (existing != null and existing.?.kind != .unix_domain_socket) { + log.warn("something is already listening on {s}", .{p}); + return error.InUse; + } + _ = libc.unlink(tmp); + _ = try l.runner.listen(.{ .unix = tmp }, max_conns); + if (libc.chmod(tmp, 0o600) != 0 or libc.rename(tmp, p) != 0) { + _ = libc.unlink(tmp); + return error.ListenFailed; + } + l.path_len = p.len; + if (libc.chmod(p, 0o600) != 0) return error.ListenFailed; + @memcpy(own_socket[0..p.len], p); + own_socket[p.len] = 0; + own_socket_len = p.len; + armSocketCleanup(); + l.postToRegistry(entry_name); + if (tcp_dial) |dial| { + if (!std.mem.startsWith(u8, dial, "tcp!")) return error.BadDial; + const address = networkAddress(dial, true) catch { + log.warn("invalid TCP address {s}", .{dial}); + return error.BadDial; + }; + const bound = l.runner.listen(.{ .tcp = address }, max_conns) catch |err| { + log.warn("cannot listen on {s}: {s}", .{ dial, @errorName(err) }); + return err; + }; + l.tcp_address = canonicalIp(bound); + log.info("serving 9P2000 over TCP on {f}", .{l.tcp_address.?}); + } + log.info("serving 9P2000 on {s}", .{p}); + core.fs.socket_path = l.path(); + core.fs.tcp_address = l.tcp_address; + return l; +} + +/// `noSocket`'s words, kept for `start`'s message. +var refusal_buf: [256]u8 = undefined; +var refusal: []const u8 = ""; + +/// Why a session named `name` gets no socket, in words in `buf` (null: it +/// gets one, or there is no directory, said where it is looked for): the +/// name it is first bound at, `<socketDir>/pardes-9p-<name>.sock.<pid>` and +/// its 0, must fit sun_path, and the directory (made here when missing) +/// must be the user's alone. Asked at a detached start too, whose stderr +/// is the only place anyone reads it. +pub fn noSocket(name: []const u8, buf: []u8) ?[]const u8 { + var dir_buf: [4096]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return null; + var digits: [16]u8 = undefined; + const pid = std.fmt.bufPrint(&digits, "{d}", .{libc.getpid()}) catch unreachable; // a pid fits 16 + const n = dir.len + "/".len + prefix.len + name.len + ".sock.".len + pid.len + 1; + if (n > sun_path_len) + return std.fmt.bufPrint(buf, "9p: the socket path is {d} bytes, {d} is the most: set XDG_RUNTIME_DIR shorter", .{ n, sun_path_len }) catch unreachable; // two numbers fit 256 + if (ensureSocketDir(dir)) return null; + const facts = statNoFollow(dir) orelse return std.fmt.bufPrint(buf, "9p: no socket: {s} is not there and could not be made", .{dir[0..@min(dir.len, 120)]}) catch unreachable; // 120 bytes of path fit 256 + return std.fmt.bufPrint(buf, "9p: no socket: {s} must be a directory of yours alone (mode {o}, owner {d}): chmod 700 it", .{ dir[0..@min(dir.len, 120)], facts.mode & 0o7777, facts.uid }) catch unreachable; // 120 bytes of path and three numbers fit 256 +} + +/// Whether a live session listens under `name` already: a second +/// `--detach=<name>` is refused before anything is made. +pub fn taken(name: []const u8) bool { + if (comptime !supported) return false; + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return false; + var buf: [sun_path_len]u8 = undefined; + const p = socketPath(&buf, dir, name) orelse return false; + return probe(p) == .live; +} + +/// What a socket's lock says of its owner (`lockState`): `.live`, `.stale`, +/// or `.none`, no lock at all. Uncertainty belongs to the server that owns +/// the socket, never to a sweeper deciding what to delete: anything unclear +/// is `.live`. +const Probe = enum { none, stale, live }; + +/// Whether whoever made the socket at `path` (or the one a registry entry +/// there names) is alive: its lock decides. With none, no owner holds one, +/// since each claims it before it binds and lets it go after it unlinks: +/// a socket there is a dead one's (a pardes from before the locks, +/// e9328a417, is one to restart). +fn probe(path: [:0]const u8) Probe { + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(path, &link_buf, link_buf.len); + const sock = if (n > 0 and n < link_buf.len and link_buf[0] == '/') link_buf[0..@intCast(n)] else path; + const locked = lockState(sock); + return if (locked == .none) .stale else locked; +} + +/// Reaps the registry entries whose editor is gone, once per post. +/// +/// A clean exit unposts itself (`unpostFromRegistry`), so everything +/// left behind comes from an exit that could not: an aborted test, a +/// kill, a crash. No code in the dead process can ever run, so the cure +/// has to be somebody else's readdir, and the next editor to start is +/// the somebody. It is only ever a symlink that is followed or +/// unlinked, because that is the only thing `postToRegistry` makes and +/// anything else under a name belongs to whoever put it there; and only +/// a lock let go, or none at all, counts as gone (`probe`). The socket a stale entry points +/// at goes too, but not before a stat agrees it is a socket of ours: a +/// plain file answers a connect with the same refusal. +/// Is this the kind of path this editor is allowed to delete? A registry +/// entry is a symlink we wrote, but its target is just bytes on disk that +/// anyone could have pointed anywhere, so the sweep only ever follows one +/// into the directory our own sockets live in, and only to a name of the +/// shape we give them. Everything else gets its entry removed and its target +/// left strictly alone. +fn ourSocket(target: []const u8, sockets: []const u8) bool { + if (sockets.len == 0 or !std.mem.startsWith(u8, target, sockets)) return false; + if (target.len <= sockets.len or target[sockets.len] != '/') return false; + const base = target[sockets.len + 1 ..]; + if (std.mem.indexOfScalar(u8, base, '/') != null) return false; + return std.mem.startsWith(u8, base, "pardes-9p-") and std.mem.endsWith(u8, base, ".sock"); +} + +fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { + if (comptime !supported) return; + + var names: [4096]u8 = undefined; + const staged = stageNames(io, svc, &names, null); + + var reaped: usize = 0; + var i: usize = 0; + while (i < staged) { + const name = names[i + 1 ..][0..names[i]]; + i += 1 + name.len; + var entry_buf: [sun_path_len:0]u8 = undefined; + const entry = std.fmt.bufPrintSentinel(&entry_buf, "{s}/{s}", .{ svc, name }, 0) catch continue; + const facts = statNoFollow(entry) orelse continue; + if (facts.mode & 0o170000 != 0o120000) continue; // not a symlink: not ours to judge + const state = probe(entry); + if (state == .live) continue; + var link_buf: [sun_path_len]u8 = undefined; + const n = libc.readlink(entry, &link_buf, link_buf.len); + if (libc.unlink(entry) != 0) continue; + reaped += 1; + // A relative target would resolve against this editor's working + // directory, which says nothing about what the entry named, and a + // readlink that exactly filled the buffer was truncated, so the path + // it produced is some other file's. + if (state != .stale or n <= 0 or link_buf[0] != '/') continue; + if (@as(usize, @intCast(n)) >= link_buf.len) continue; + var target_buf: [sun_path_len:0]u8 = undefined; + const target = std.fmt.bufPrintSentinel(&target_buf, "{s}", .{link_buf[0..@intCast(n)]}, 0) catch continue; + if (!ourSocket(target, sockets)) continue; + const t = statNoFollow(target) orelse continue; + if (t.mode & 0o170000 != 0o140000 or t.uid != libc.getuid()) continue; + // Judged again, under its lock: the first probe was of the ENTRY and + // is by now several syscalls old, and a new owner may have claimed + // the name since. + removeDead(target); + } + if (reaped != 0) log.info("reaped {d} stale registry entries under {s}", .{ reaped, svc }); +} + +const testing = std.testing; + +extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; + +/// A test's own runtime directory under /tmp, which XDG_RUNTIME_DIR names +/// until `deinit` puts the old value back and removes it, with what the +/// listener left in it. +const TempRuntime = struct { + directory: [64:0]u8 = undefined, + old: ?[:0]u8 = null, + + fn init(t: *TempRuntime, comptime name: []const u8) !void { + _ = try std.fmt.bufPrintSentinel(&t.directory, "/tmp/pardes-" ++ name ++ "-XXXXXX", .{}, 0); + if (mkdtemp(&t.directory) == null) return error.TempDirectoryFailed; + if (libc.getenv("XDG_RUNTIME_DIR")) |v| t.old = try testing.allocator.dupeSentinel(u8, std.mem.span(v), 0); + try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &t.directory, 1)); + } + + fn deinit(t: *TempRuntime) void { + if (t.old) |v| { + _ = setenv("XDG_RUNTIME_DIR", v, 1); + testing.allocator.free(v); + } else _ = @import("core").host_io.testUnsetenv("XDG_RUNTIME_DIR"); + std.Io.Dir.cwd().deleteTree(testing.io, std.mem.sliceTo(&t.directory, 0)) catch |err| std.debug.print("deleteTree: {s}\n", .{@errorName(err)}); + } +}; + +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 { + var name: [16]u8 = undefined; + // unreachable: a u32 is at most 10 digits + const fallback = std.fmt.bufPrint(&name, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable; + return listen(io, gpa, core, core.opts.ninep_name, fallback, core.opts.ninep_tcp) catch { + if (refusal.len > 0) core.setMessage(0, refusal) else core.reportError(0, "9p listener", error.ListenFailed); + return null; + }; +} + +/// What a pane shell is told about the editor above it, set into this +/// process's environment just before `forkpty` so the child inherits it. +/// +/// Two independent facts, and they are separate variables because they answer +/// separate questions. `PARDES_PID` says "you are inside this editor, and it +/// will take a Look from you": a session whose 9P listener never came up still +/// owns its children, so the child says so rather than looking, from its own +/// side, exactly like no pardes at all. `PARDES_9P` and `PARDES_PANE` say how +/// to reach it, and a `--nested` session exports them too — its socket stays +/// open to scripts and to mounted shells — while withholding `PARDES_PID`, +/// which is the whole of what `--nested` means. +/// +/// The socket is this process's own (`listen` keeps it, its listener's +/// path, until `deinit`), for a pane's shell and for a command run off the +/// loop (an Edit's filter) alike. Told to children through +/// host_io.ChildEnv, never set into this process's own environment (see +/// ChildEnv.exportVar for why). +pub fn exportEnv(serial: u32, adopts: bool) void { + const socket: ?[]const u8 = if (own_socket_len > 0) own_socket[0..own_socket_len] else null; + const ChildEnv = @import("core").host_io.ChildEnv; + var pid_buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable else null); // a u32 fits 16 + if (socket) |own| { + var buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_9P", own); + exportMount(own); + ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); + return; + } + ChildEnv.exportVar("PARDES_9P", null); + ChildEnv.exportVar("PARDES_PANE", null); + ChildEnv.exportVar("PARDES_MOUNT", null); +} + +/// $PARDES_MOUNT, the session's own directory, when the environment says +/// where it is -- never by looking at the mount, which this editor serves +/// (the self-mount deadlock). Under `9ns --mntgen` (NINE_MNTGEN=1) it is +/// `$NINE_MOUNT/pardes/<name>`, the name the registry gives the socket. +/// Any other $NINE_MOUNT is a mount of another server, made before this +/// session had a socket: unknown, so unset, and a script falls back to +/// `9p -a "unix!$PARDES_9P"`. +fn exportMount(sock_path: []const u8) void { + const mntgen = if (libc.getenv("NINE_MNTGEN")) |v| std.mem.eql(u8, std.mem.span(v), "1") else false; + const root = if (libc.getenv("NINE_MOUNT")) |v| std.mem.span(v) else ""; + const base = std.Io.Dir.path.basename(sock_path); + const sock_prefix = "pardes-9p-"; + const suffix = ".sock"; + if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { + var buf: [4096]u8 = undefined; + if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { + return @import("core").host_io.ChildEnv.exportVar("PARDES_MOUNT", mount); + } else |_| {} + } + @import("core").host_io.ChildEnv.exportVar("PARDES_MOUNT", null); +} + +pub const Client = struct { + pub const budget_ms: i64 = 2000; + /// Each write of a long one has this long to be answered (transact). + pub const write_budget_ms: i64 = 30_000; + + pub const max_depth: usize = 2 * ninep.max_welem; + + const uname = "pardes"; + + const Dial = union(enum) { unix: [:0]const u8, tcp: std.Io.net.IpAddress }; + + pub const Error = error{ + PathTooDeep, + BadDial, + Dial, + Hangup, + Timeout, + Botch, + Remote, + IsDirectory, + NotFound, + FileTooLarge, + }; + + pub fn read(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8) ![]u8 { + return readLimit(gpa, dial, path, display_path, limits.max_file_bytes); + } + + pub fn readLimit(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { + return fetch(false, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); + } + + /// readLimit through a mount: its connection kept for the next (`kept`). + pub fn readMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, max_bytes: usize) ![]u8 { + return fetch(true, gpa, dial, path, display_path, null, @min(max_bytes, limits.max_file_bytes)); + } + + /// One operation on `path`, a read of up to `read_limit` or a write of + /// `write_bytes`, on the connection kept for `dial` when `keep`: the + /// peer's words, when it refuses, kept for lastSaid. + fn fetch(keep: bool, gpa: std.mem.Allocator, dial: []const u8, path: []const u8, display_path: []const u8, write_bytes: ?[]const u8, read_limit: usize) ![]u8 { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + return fetchBytes(gpa, dial, names[0..n], &remote, write_bytes, display_path, read_limit, keep) catch |err| { + if (err == error.Remote) said = remote; + return err; + }; + } + + /// The peer's own words for the last error.Remote a read or write here + /// got (its Rerror), for a caller that says why: this thread's, as the + /// editor's mounts and a Handover job each ask from their own. + threadlocal var said: RemoteError = .{}; + pub fn lastSaid() []const u8 { + return said.buf[0..said.len]; + } + + /// Whether a peer answers at `dial`: a version and attach, and its root + /// read. Any answer from the peer, an error of its own included, is one. + pub fn probe(gpa: std.mem.Allocator, dial: []const u8) !void { + return probeWith(false, gpa, dial); + } + + /// probe for a Mount: the connection kept as the mount's. + pub fn probeMount(gpa: std.mem.Allocator, dial: []const u8) !void { + return probeWith(true, gpa, dial); + } + + fn probeWith(keep: bool, gpa: std.mem.Allocator, dial: []const u8) !void { + const got = fetch(keep, gpa, dial, "", "", null, 0) catch |err| switch (err) { + error.IsDirectory, error.NotFound, error.Remote, error.FileTooLarge => return, + else => return err, + }; + gpa.free(got); + } + + pub fn write(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { + gpa.free(try fetch(false, gpa, dial, path, path, bytes, limits.max_file_bytes)); + } + + /// write through a mount: its connection kept for the next (`kept`). + pub fn writeMount(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, bytes: []const u8) !void { + gpa.free(try fetch(true, gpa, dial, path, path, bytes, limits.max_file_bytes)); + } + + const RemoteError = struct { + buf: [ninep.errmax]u8 = undefined, + len: usize = 0, + + fn set(r: *RemoteError, msg: []const u8) error{Remote} { + r.keep(msg); + return error.Remote; + } + + fn keep(r: *RemoteError, msg: []const u8) void { + r.len = @min(msg.len, r.buf.len); + @memcpy(r.buf[0..r.len], msg[0..r.len]); + } + }; + + fn elements(path: []const u8, out: *[max_depth][]const u8) Error!usize { + var n: usize = 0; + var it = std.mem.tokenizeScalar(u8, path, '/'); + while (it.next()) |name| { + if (n == out.len) return Error.PathTooDeep; + out[n] = name; + n += 1; + } + return n; + } + + fn resolve(buf: *[sun_path_len]u8, dial: []const u8) error{BadDial}!Dial { + if (dial.len == 0) return error.BadDial; + if (std.mem.startsWith(u8, dial, "tcp!")) return .{ .tcp = try networkAddress(dial, false) }; + const explicit_unix = std.mem.startsWith(u8, dial, "unix!"); + // A network this does not dial (`nowhere!x`) is a malformed address, + // not a session named so. + if (!explicit_unix and std.mem.indexOfScalar(u8, dial, '/') == null and std.mem.indexOfScalar(u8, dial, '!') != null) return error.BadDial; + const path = if (explicit_unix) dial[5..] else dial; + if (explicit_unix and !std.mem.startsWith(u8, path, "/")) return error.BadDial; + if (std.mem.indexOfScalar(u8, path, '/') != null) { + // A socket's path is absolute: a relative one would mean wherever + // the editor happens to run. + if (path[0] != '/') return error.BadDial; + if (std.mem.indexOfScalar(u8, path, 0) != null) return error.BadDial; + return .{ .unix = std.fmt.bufPrintSentinel(buf, "{s}", .{path}, 0) catch return error.BadDial }; + } + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf) orelse return error.BadDial; + return .{ .unix = socketPath(buf, dir, dial) orelse return error.BadDial }; + } + + pub fn validateDial(dial: []const u8) error{BadDial}!void { + var buf: [sun_path_len]u8 = undefined; + _ = try resolve(&buf, dial); + } + + const Session = struct { + fd: c_int, + deadline: i64, + display_path: []const u8, + cl: ninep.Client = undefined, + in: [msize]u8 = undefined, + out: [msize]u8 = undefined, + stage: [msize]u8 = undefined, + /// Version and attach answered: fid 0 is the peer's root, and each + /// operation walks a fid of its own from it, so a kept connection + /// (`kept`) pays for neither again. + attached: bool = false, + root_qid: ninep.Qid = undefined, + next_fid: u32 = 1, + /// Tags whose answers nobody waits for (a clunk's): dropped by + /// whoever settles next. + unwaited: u32 = 0, + /// The dial a kept connection answers for. + dial_buf: [sun_path_len + 32]u8 = undefined, + dial_len: usize = 0, + + fn wait(s: *Session, events: i16) Error!void { + if (s.deadline - nowMs() <= 0) return Error.Timeout; + return transport.wait(s.fd, events, s.deadline) catch |err| switch (err) { + error.Timeout => Error.Timeout, + else => Error.Hangup, + }; + } + + fn flush(s: *Session) Error!void { + while (s.cl.output().len != 0) { + if (nowMs() >= s.deadline) return Error.Timeout; + const bytes = s.cl.output(); + try s.wait(poll_out); + const sent = (transport.write(s.fd, bytes) catch return Error.Hangup) orelse continue; + s.cl.wrote(@intCast(sent)); + } + } + + fn settle(s: *Session) Error!ninep.Client.Done { + while (true) { + if (nowMs() >= s.deadline) return Error.Timeout; + try s.flush(); + if (s.cl.take()) |done| { + if (done.tag < 32 and s.unwaited & bit(done.tag) != 0) { + s.unwaited &= ~bit(done.tag); + continue; + } + return done; + } + if (s.cl.dead) return Error.Botch; + const room = s.cl.in.len - s.cl.in_len; + if (room == 0) return Error.Botch; + try s.wait(poll_in); + const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return Error.Hangup) orelse continue; + if (got == 0) return Error.Hangup; + const n = s.cl.push(s.stage[0..@intCast(got)]); + std.debug.assert(n == @as(usize, @intCast(got))); + } + } + + fn ask(s: *Session, req: ninep.Client.Request, remote: *RemoteError) Error!ninep.Client.Result { + _ = s.cl.submit(req) catch return Error.Botch; + const done = try s.settle(); + if (done.result == .fail) return remote.set(done.result.fail); + if (std.mem.eql(u8, @tagName(done.result), @tagName(std.meta.activeTag(req)))) return done.result; + return Error.Botch; + } + + fn drop(s: *Session, fid: u32) void { + _ = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; + _ = s.settle() catch {}; + } + + fn dropNoWait(s: *Session, fid: u32) void { + const tag = s.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; + s.unwaited |= bit(tag); + s.flush() catch {}; + } + + fn send(s: *Session, req: ninep.Client.Request) Error!u16 { + return s.cl.submit(req) catch Error.Botch; + } + + fn newFid(s: *Session) u32 { + const fid = s.next_fid; + s.next_fid = if (fid >= 1 << 20) 1 else fid + 1; + return fid; + } + + /// A new connection's Tversion and Tattach, sent with the first + /// operation's requests behind them in one flight (`land`). + fn greet(s: *Session, f: *Flight) Error!void { + if (s.attached) return; + _ = f.add(.version, try s.send(.{ .version = .{} })); + // ponytail: cloud9's client submits nothing while a Tversion is + // out, so its msize is taken as asked until the Rversion lands + // (`land` puts it back); only a pardes is dialled here, and every + // one offers ninep.msize. A Twrite in this flight stays under the + // least a listener offers (`flight_write`). The fix is cloud9's + // client taking requests while it versions. + s.cl.versioning = false; + s.cl.msize = s.cl.asked; + _ = f.add(.attach, try s.send(.{ .attach = .{ .fid = 0, .uname = uname } })); + } + + /// The walk to a new fid at `names` (two Twalks past 16 names, the + /// second from the fid to itself), from the root. + fn walkNew(s: *Session, f: *Flight, names: []const []const u8) Error!u32 { + const fid = s.newFid(); + const first = names[0..@min(names.len, ninep.max_welem)]; + f.add(.walk, try s.send(.{ .walk = .{ .fid = 0, .newfid = fid, .names = first } })).asked = @intCast(first.len); + if (names.len > first.len) + f.add(.walk, try s.send(.{ .walk = .{ .fid = fid, .newfid = fid, .names = names[first.len..] } })).asked = @intCast(names.len - first.len); + return fid; + } + + /// Sends the flight and takes every answer of it, a read's bytes + /// into `taker` as they come (each valid only until the next), so + /// that the connection is left with nothing out but its clunks. A + /// refused Tversion is its words at once: nothing after it is + /// answered. + fn land(s: *Session, f: *Flight, taker: ?*Taker, remote: *RemoteError) Error!void { + if (f.get(.version) != null) s.cl.versioning = true; + while (f.open()) { + const done = try s.settle(); + const item = f.find(done.tag) orelse return Error.Botch; + item.done = true; + switch (done.result) { + .fail => |words| { + item.failed = true; + item.said.keep(words); + if (item.step == .version) return remote.set(words); + }, + .version => { + if (item.step != .version or s.cl.msize == 0) return Error.Botch; + }, + .attach => |qid| { + if (item.step != .attach) return Error.Botch; + s.root_qid = qid; + s.attached = true; + }, + .walk => |w| { + if (item.step != .walk) return Error.Botch; + item.n = w.nwqid; + if (w.nwqid > 0) item.qid = w.wqid[w.nwqid - 1]; + }, + .stat => |st| { + if (item.step != .stat) return Error.Botch; + item.n = st.length; + }, + .open => |o| { + if (item.step != .open) return Error.Botch; + item.qid = o.qid; + }, + .read => |data| { + if (item.step != .read) return Error.Botch; + item.n = data.len; + if (taker) |t| t.take(item, data); + // A read is timed by its progress, as a long write + // is: each answer gives the rest the budget again, so + // a large file over a slow link is not cut off. + s.deadline = @max(s.deadline, nowMs() +| budget_ms); + }, + .write => |count| { + if (item.step != .write) return Error.Botch; + item.n = count; + }, + else => return Error.Botch, + } + } + } + }; + + fn bit(tag: u16) u32 { + return @as(u32, 1) << @intCast(tag); + } + + /// The requests of one flight, each its own tag, sent back to back: a + /// pardes takes one connection's requests in order (cloud9's engine + /// starts a request once the one before it is answered or parked), so + /// a walk, the open of its fid and the first read or write need no + /// answer between them, and an operation costs one round trip. + const Flight = struct { + items: [ninep.Client.window]Item = undefined, + len: usize = 0, + + const Step = enum { version, attach, walk, stat, open, read, write }; + const Item = struct { + step: Step, + tag: u16, + done: bool = false, + failed: bool = false, + said: RemoteError = .{}, + /// walk: names asked; read: its offset and count. + asked: u16 = 0, + off: u64 = 0, + count: u32 = 0, + /// walk: qids answered; stat: the length; read, write: bytes. + n: u64 = 0, + qid: ninep.Qid = undefined, + }; + + fn add(f: *Flight, step: Step, tag: u16) *Item { + f.items[f.len] = .{ .step = step, .tag = tag }; + f.len += 1; + return &f.items[f.len - 1]; + } + + fn find(f: *Flight, tag: u16) ?*Item { + for (f.items[0..f.len]) |*item| if (item.tag == tag and !item.done) return item; + return null; + } + + fn get(f: *Flight, step: Step) ?*Item { + for (f.items[0..f.len]) |*item| if (item.step == step) return item; + return null; + } + + fn open(f: *const Flight) bool { + for (f.items[0..f.len]) |item| if (!item.done) return true; + return false; + } + + /// The first refusal in the order asked: a version's or an attach's + /// words, a walk short of its names, an open's refusal. + fn check(f: *Flight, remote: *RemoteError) Error!void { + for (f.items[0..f.len]) |*item| switch (item.step) { + .version, .attach, .open => if (item.failed) return remote.set(item.said.buf[0..item.said.len]), + .walk => { + if (item.failed) return remote.set(item.said.buf[0..item.said.len]); + if (item.n != item.asked) return Error.NotFound; + }, + .stat, .read, .write => {}, + }; + } + + /// The walked file's qid: the last walk's, or the root's for none. + fn qid(f: *Flight, root: ninep.Qid) ninep.Qid { + var at = root; + for (f.items[0..f.len]) |item| if (item.step == .walk and item.n > 0) { + at = item.qid; + }; + return at; + } + + /// Whether the walk made the fid, so that it is owed a clunk. + fn made(f: *Flight) bool { + const first = f.get(.walk) orelse return false; + return !first.failed and first.n == first.asked; + } + }; + + /// A write in a new connection's first flight is sent before the msize + /// is known: no larger than the least a pardes listener offers. + const flight_write = ninep.min_msize - 23; + + /// Reads ahead this many Treads at once (the window, less a clunk + /// still out and one spare). + const read_ahead = ninep.Client.window - 2; + + /// Version and attach on a new connection, and a walk to `names`, in + /// one flight: the fid there. + fn walkTo(s: *Session, names: []const []const u8, remote: *RemoteError) !u32 { + var f: Flight = .{}; + try s.greet(&f); + const fid = try s.walkNew(&f, names); + try s.land(&f, null, remote); + f.check(remote) catch |err| { + if (f.made()) s.dropNoWait(fid); + return err; + }; + return fid; + } + + /// A read's bytes taken in order: a file's as they are, a directory's + /// entries as rows of names. A read ahead that came back out of order, + /// or past one that came back short, is not taken: what it held is + /// read again from where the taken bytes end. + const Taker = struct { + out: *std.Io.Writer.Allocating, + display_path: []const u8, + limit: usize, + /// The flight with the walk, whose answer says what was reached: + /// it lands before any read (a walk never parks). + flight: *Flight, + s: *const Session, + /// Bytes taken from the start; a directory's next offset. + end: u64 = 0, + /// The read that ended at `end` came back short, or empty (the end). + short: bool = false, + empty: bool = false, + /// What taking said (too large, a bad entry): the operation's + /// answer once every read out has landed. + err: ?Error = null, + + fn take(t: *Taker, item: *Flight.Item, data: []const u8) void { + if (t.err != null or item.off != t.end or t.short) return; + t.put(data) catch |err| { + t.err = err; + return; + }; + t.end += data.len; + t.short = data.len < item.count; + t.empty = data.len == 0; + } + + fn directory(t: *const Taker) bool { + return t.flight.qid(t.s.root_qid).type & ninep.qtdir != 0; + } + + fn maxBytes(t: *const Taker) u64 { + return @min(t.limit, @as(usize, if (t.directory()) limits.max_stream_bytes else limits.max_file_bytes)); + } + + fn wireLimit(t: *const Taker) u64 { + return if (t.directory()) limits.max_stream_bytes else t.maxBytes(); + } + + fn put(t: *Taker, data: []const u8) Error!void { + if (t.end + data.len > t.wireLimit()) return Error.FileTooLarge; + if (t.directory()) { + var pos: usize = 0; + while (pos < data.len) { + if (data.len - pos < 2) return Error.Botch; + const len: usize = 2 + @as(usize, std.mem.readInt(u16, data[pos..][0..2], .little)); + if (len > data.len - pos) return Error.Botch; + const entry = ninep.Stat.decode(data[pos..][0..len]) catch return Error.Botch; + const display_dir = std.mem.trimEnd(u8, t.display_path, "/"); + const row_len = display_dir.len + entry.name.len + 2 + @as(usize, @intFromBool(entry.qid.type & ninep.qtdir != 0)); + if (row_len > t.maxBytes() - t.out.written().len) return Error.FileTooLarge; + t.out.writer.print("{s}/{s}", .{ display_dir, entry.name }) catch return Error.Botch; + if (entry.qid.type & ninep.qtdir != 0) t.out.writer.writeByte('/') catch return Error.Botch; + t.out.writer.writeByte('\n') catch return Error.Botch; + pos += len; + } + } else t.out.writer.writeAll(data) catch return Error.Botch; + } + }; + + /// One operation in as few round trips as its answers allow: the walk, + /// a read's stat, the open and the first read or write go in one flight + /// (behind a new connection's version and attach). A file of the + /// length its stat said is whole when a read comes back short at that + /// length; a longer one is read ahead, the Treads for the rest sent at + /// once. Anything else (a directory, a file of no stated length) reads + /// on until a read comes back empty, the only end 9P has. + fn transact( + s: *Session, + names: []const []const u8, + out: *std.Io.Writer.Allocating, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + ) !void { + const writing = write_bytes != null; + const mode: u8 = if (writing) ninep.owrite else ninep.oread; + const truncate = writing and names.len > 0 and + (std.mem.eql(u8, names[0], "os") or std.mem.eql(u8, names[names.len - 1], "body")); + const fresh = !s.attached; + var f: Flight = .{}; + try s.greet(&f); + const fid = try s.walkNew(&f, names); + if (!writing) _ = f.add(.stat, try s.send(.{ .stat = .{ .fid = fid } })); + _ = f.add(.open, try s.send(.{ .open = .{ .fid = fid, .mode = mode | if (truncate) ninep.otrunc else 0 } })); + const chunk_max: usize = if (fresh) flight_write else s.cl.maxWrite(); + const first: []const u8 = if (write_bytes) |bytes| bytes[0..@min(bytes.len, chunk_max)] else ""; + if (writing and first.len != 0) { + // Out of the client's buffer first (it holds one msize): still + // sent without waiting. + try s.flush(); + _ = f.add(.write, try s.send(.{ .write = .{ .fid = fid, .offset = 0, .data = first } })); + } + // A read's count before the msize is known is the asked msize's. + if (!writing) { + const item = f.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } })); + item.count = s.cl.maxRead(); + } + var taker: Taker = .{ .out = out, .display_path = s.display_path, .limit = read_limit, .flight = &f, .s = s }; + try s.land(&f, &taker, remote); + defer if (f.made()) s.dropNoWait(fid); + try f.check(remote); + if (taker.err) |err| return err; + const directory = taker.directory(); + + if (write_bytes) |bytes| { + if (directory) return Error.IsDirectory; + var written: usize = 0; + if (f.get(.write)) |w| { + // Refused unopened, the open parked (a truncating one while + // the editor is out): sent again below, after it. + if (w.failed and !std.mem.eql(u8, w.said.buf[0..w.said.len], ninep.fs.e_bad_use)) return remote.set(w.said.buf[0..w.said.len]); + if (!w.failed) { + if (w.n == 0 or w.n > first.len) return Error.Botch; + written = w.n; + } + } + while (written < bytes.len) { + s.deadline = nowMs() +| write_budget_ms; + const chunk = bytes[written..][0..@min(bytes.len - written, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + // A long write is timed by its progress: each answer gives + // the next its own budget, so a large body (`pardes -`) goes + // in through one open, whole, however long it takes. The + // budget is a write's: a server putting in tens of MiB it + // held (pane.zig batchFor) answers that one write late. + } + return; + } + + if (f.get(.read)) |r| if (r.failed and !std.mem.eql(u8, r.said.buf[0..r.said.len], ninep.fs.e_bad_use)) + return remote.set(r.said.buf[0..r.said.len]); + const length: u64 = if (f.get(.stat)) |st| (if (st.failed or directory) 0 else st.n) else 0; + const step: u64 = s.cl.maxRead(); + while (true) { + if (taker.empty) return; + if (taker.short and length != 0 and taker.end == length) return; + // The rest of a file of known length at once; a directory, a + // file of none, or the end to be seen, a read at a time. + // ponytail: a file of no stated length is not read ahead. + const want: u64 = if (directory or taker.short or length <= taker.end) 1 else @min(read_ahead, (length - taker.end) / step + 1); + var batch: Flight = .{}; + var off = taker.end; + for (0..want) |_| { + if (off > taker.wireLimit()) break; + const count: u32 = @intCast(@min(step, taker.wireLimit() + 1 - off)); + const item = batch.add(.read, try s.send(.{ .read = .{ .fid = fid, .offset = off, .count = count } })); + item.off = off; + item.count = count; + off += count; + } + taker.short = false; + try s.land(&batch, &taker, remote); + if (taker.err) |err| return err; + for (batch.items[0..batch.len]) |item| if (item.failed and item.off == taker.end and !taker.short) + return remote.set(item.said.buf[0..item.said.len]); + } + } + + fn fetchBytes( + gpa: std.mem.Allocator, + dial: []const u8, + names: []const []const u8, + remote: *RemoteError, + write_bytes: ?[]const u8, + display_path: []const u8, + read_limit: usize, + keep: bool, + ) ![]u8 { + if (comptime !supported) return Error.Dial; + if (keep) if (kept.take(dial)) |s| { + if (fetchOn(s, gpa, names, remote, write_bytes, read_limit, display_path, true)) |bytes| return bytes else |err| switch (err) { + // Let go of by the peer since (its hangup still on the way): + // a read is asked again on a new connection. A write is not, + // as it may have been done. + error.Hangup, error.Botch => if (write_bytes != null) return err, + else => return err, + } + }; + return fetchOn(try startSession(dial, display_path), gpa, names, remote, write_bytes, read_limit, display_path, keep); + } + + fn fetchOn( + s: *Session, + gpa: std.mem.Allocator, + names: []const []const u8, + remote: *RemoteError, + write_bytes: ?[]const u8, + read_limit: usize, + display_path: []const u8, + keep: bool, + ) ![]u8 { + s.deadline = nowMs() +| budget_ms; + s.display_path = display_path; + var clean = false; + defer endSession(s, keep and clean); + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + transact(s, names, &out, remote, write_bytes, read_limit) catch |err| { + // Refused with every answer in: the connection is as good as before. + clean = switch (err) { + error.Remote, error.NotFound, error.IsDirectory, error.FileTooLarge => true, + else => false, + }; + return err; + }; + clean = true; + return out.toOwnedSlice(); + } + + /// A new connection at `dial` whose requests have the usual deadline. + fn startSession(dial: []const u8, display_path: []const u8) !*Session { + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); + const deadline = nowMs() +| budget_ms; + // Not the caller's allocator: a kept one outlives the call (an arena's). + const s = try std.heap.page_allocator.create(Session); + s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; + errdefer endSession(s, false); + s.fd = try connect(sock, deadline); + s.cl = .init(.{ .in = &s.in, .out = &s.out }); + if (dial.len <= s.dial_buf.len) { + @memcpy(s.dial_buf[0..dial.len], dial); + s.dial_len = dial.len; + } + return s; + } + + fn endSession(s: *Session, keep: bool) void { + if (keep and s.attached and s.dial_len != 0 and kept.put(s)) return; + if (s.fd >= 0) _ = libc.close(s.fd); + std.heap.page_allocator.destroy(s); + } + + /// Connections kept open between operations, a few dials' (a mount's, + /// as Plan 9's mount keeps its channel): each costs the peer one of its + /// `max_conns` while kept, so only mounts and the Mount probe keep one. + const kept = struct { + const max = 8; + var lock: std.atomic.Mutex = .unlocked; + var slots: [max]?*Session = @splat(null); + + fn hold() void { + while (!lock.tryLock()) std.atomic.spinLoopHint(); + } + + /// The session kept for `dial`, out of the table, if it is still + /// there: what came while it waited (a clunk's answer) taken, and + /// a hangup or anything else seen as its end. + fn take(dial: []const u8) ?*Session { + hold(); + const s = for (&slots) |*slot| { + const got = slot.* orelse continue; + if (std.mem.eql(u8, got.dial_buf[0..got.dial_len], dial)) { + slot.* = null; + break got; + } + } else null; + lock.unlock(); + const found = s orelse return null; + if (usable(found)) return found; + endSession(found, false); + return null; + } + + fn usable(s: *Session) bool { + while (true) { + var fds = [1]libc.pollfd{.{ .fd = s.fd, .events = poll_in, .revents = 0 }}; + if (libc.poll(&fds, 1, 0) < 0) return false; + if (fds[0].revents == 0) return true; + if (fds[0].revents & poll_in == 0) return false; + const room = s.cl.in.len - s.cl.in_len; + if (room == 0) return false; + const got = (transport.read(s.fd, s.stage[0..@min(room, s.stage.len)]) catch return false) orelse return true; + if (got == 0) return false; + _ = s.cl.push(s.stage[0..got]); + while (s.cl.take()) |done| { + if (done.tag >= 32 or s.unwaited & bit(done.tag) == 0) return false; + s.unwaited &= ~bit(done.tag); + } + if (s.cl.dead) return false; + } + } + + fn put(s: *Session) bool { + hold(); + defer lock.unlock(); + for (&slots) |*slot| if (slot.* == null) { + slot.* = s; + return true; + }; + return false; + } + }; + + /// Lets go of a connection kept for `dial` (an Unmount): its mount is gone. + pub fn forget(dial: []const u8) void { + if (comptime !supported) return; + while (kept.take(dial)) |s| endSession(s, false); + } + + /// Writes `request`, then `more`, to `path` and reads the answer on the + /// same open, as /pane/new answers its own open: a session's last + /// answer, from another client, can never be what comes back. `exec + /// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in + /// Twrites at rising offsets, each answer giving the next its budget. + pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + errdefer said = remote; + const s = try startSession(dial, path); + defer endSession(s, false); + const fid = try walkTo(s, names[0..n], &remote); + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + var written: usize = 0; + while (written < request.len + more.len) { + const from = if (written < request.len) request[written..] else more[written - request.len ..]; + const chunk = from[0..@min(from.len, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + s.deadline = nowMs() +| write_budget_ms; + } + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = out.items.len, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return out.toOwnedSlice(gpa); + if (out.items.len + data.len > 4096) return Error.FileTooLarge; + try out.appendSlice(gpa, data); + } + } + + /// Opens `path` on one connection and writes `first` to it (/log's + /// `follow new`), all with the usual deadline; then, once `ready(ctx)` + /// has said it is not done already, reads it with no deadline, a read at + /// a time, until `record(ctx, bytes)` says done. An end of file or a + /// dropped connection is Hangup. What `pardes --wait` blocks on. + pub fn follow( + dial: []const u8, + path: []const u8, + first: []const u8, + ctx: anytype, + comptime ready: fn (@TypeOf(ctx)) bool, + comptime record: fn (@TypeOf(ctx), []const u8) bool, + ) !void { + if (comptime !supported) return error.Unsupported; + var names: [max_depth][]const u8 = undefined; + const n = try elements(path, &names); + var remote: RemoteError = .{}; + const s = try startSession(dial, path); + defer endSession(s, false); + const fid = try walkTo(s, names[0..n], &remote); + _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); + _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = first } }, &remote); + if (ready(ctx)) return; + s.deadline = std.math.maxInt(i64); + while (true) { + const data = (try s.ask(.{ .read = .{ .fid = fid, .offset = 0, .count = s.cl.maxRead() } }, &remote)).read; + if (data.len == 0) return Error.Hangup; + if (record(ctx, data)) return; + } + } + + fn connect(sock: Dial, deadline: i64) Error!c_int { + const address: transport.Address = switch (sock) { + .unix => |path| .{ .unix = path }, + .tcp => |ip| .{ .tcp = ip }, + }; + return transport.connectFd(address, deadline) catch return Error.Dial; + } + + const poll_in: i16 = @intCast(libc.POLL.IN); + const poll_out: i16 = @intCast(libc.POLL.OUT); + + test "a path becomes walk elements, normalised the way a shell would" { + var out: [max_depth][]const u8 = undefined; + try testing.expectEqual(@as(usize, 3), try elements("/pane/1/body", &out)); + try testing.expectEqualStrings("pane", out[0]); + try testing.expectEqualStrings("1", out[1]); + try testing.expectEqualStrings("body", out[2]); + + try testing.expectEqual(@as(usize, 3), try elements("pane/1/body", &out)); + try testing.expectEqual(@as(usize, 3), try elements("//pane//1//body//", &out)); + try testing.expectEqual(@as(usize, 1), try elements("/index", &out)); + + try testing.expectEqual(@as(usize, 0), try elements("/", &out)); + + var deep: [8 * max_depth]u8 = @splat('/'); + for (0..max_depth + 1) |i| deep[i * 2 + 1] = 'a'; + try testing.expectError(Error.PathTooDeep, elements(deep[0 .. (max_depth + 1) * 2], &out)); + } + + test "a bare dial resolves to the socket --9p binds, and a path is taken as given" { + if (comptime !supported) return error.SkipZigTest; + var buf: [sun_path_len]u8 = undefined; + + const named = (try resolve(&buf, "work")).unix; + try testing.expect(std.mem.endsWith(u8, named, "/pardes-9p-work.sock")); + var expect: [sun_path_len]u8 = undefined; + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = socketDir(&dir_buf).?; + try testing.expectEqualStrings(socketPath(&expect, dir, "work").?, named); + + const path = (try resolve(&buf, "/tmp/somewhere.sock")).unix; + try testing.expectEqualStrings("/tmp/somewhere.sock", path); + try testing.expectEqualStrings("/tmp/somewhere.sock", (try resolve(&buf, "unix!/tmp/somewhere.sock")).unix); + + try testing.expectError(error.BadDial, resolve(&buf, "")); + try testing.expectError(error.BadDial, resolve(&buf, "/tmp/a\x00b")); + } + + test "a dial with nothing listening is one error and not a wait" { + if (comptime !supported) return error.SkipZigTest; + var names: [max_depth][]const u8 = undefined; + const n = try elements("/pane/1/body", &names); + var remote: RemoteError = .{}; + const before = nowMs(); + try testing.expectError( + Error.Dial, + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes, false), + ); + try testing.expect(nowMs() - before < budget_ms); + } + + test "one fetch has three msize buffers and bounded transport metadata" { + try testing.expectEqual(@as(usize, msize), @as(usize, (Session{ .fd = -1, .deadline = 0, .display_path = "" }).in.len)); + try testing.expect(@sizeOf(Session) <= 3 * msize + @sizeOf(ninep.Client) + 128 + @sizeOf(@FieldType(Session, "dial_buf"))); + try testing.expect(@sizeOf(ninep.Client) <= 512); + } + + test "expired sessions do not send or consume buffered protocol work" { + var session: Session = .{ .fd = -1, .deadline = 0, .display_path = "" }; + session.cl = .init(.{ .in = &session.in, .out = &session.out }); + _ = try session.cl.submit(.{ .version = .{} }); + const queued = session.cl.output().len; + try testing.expect(queued > 0); + try testing.expectError(Error.Timeout, session.flush()); + try testing.expectEqual(queued, session.cl.output().len); + try testing.expectError(Error.Timeout, session.settle()); + 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("core").filesystem.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("core").host_io.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("core").host_io.ChildEnv.exported("PARDES_MOUNT").?); + // A mount of another server (9ns --unix): not this session's. + _ = @import("core").host_io.testUnsetenv("NINE_MNTGEN"); + exportMount("/run/user/1000/pardes-9p-work.sock"); + try testing.expect(@import("core").host_io.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("core").host_io.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("core").host_io.testUnsetenv("XDG_RUNTIME_DIR"); + _ = setenv("HOME", "/home/example", 1); + try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); + _ = @import("core").host_io.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("core").host_io.ChildEnv.exported("PARDES_9P").?); + try testing.expectEqualStrings("7", @import("core").host_io.ChildEnv.exported("PARDES_PANE").?); + try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PID") == null); + + exportEnv(8, true); + try testing.expectEqualStrings("8", @import("core").host_io.ChildEnv.exported("PARDES_PANE").?); + try testing.expectEqualStrings(own_pid, @import("core").host_io.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("core").host_io.ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, @import("core").host_io.ChildEnv.exported("PARDES_PID").?); + + exportEnv(0, false); + try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PANE") == null); + try testing.expect(@import("core").host_io.ChildEnv.exported("PARDES_PID") == null); +} diff --git a/runtime/addon_test.zig b/runtime/addon_test.zig new file mode 100644 index 00000000..a08237fc --- /dev/null +++ b/runtime/addon_test.zig @@ -0,0 +1,253 @@ +//! `pardes --addon-test <addon.so> <script>`: an addon's author's test. +//! The addon is loaded into a session of its own (80x24, no terminal, no +//! disk, its jobs run at once, its clock virtual, starting at 1 s and moved +//! by `tick` and `settle` alone), a pane of it opened, and the script's +//! lines run in turn, each printed with the start of the pane's tag (the +//! kind's prefix, the core's art words, the path), cells and placements +//! after it; a script compares the output with what it wants as a snapshot +//! script does (`diff`). A call into the kind over its budget (16 ms in a +//! Debug pardes) is said, and fails the script. +//! +//! open [path] a pane of the kind (the first step opens one bare) +//! key hjkl<up> keys, a character or <up> <down> <left> <right> +//! <enter> <tab> <bs> <esc> <space> each +//! tick 100 the clock 100 ms on, the kind's ticks run +//! settle ticks until the kind asks for none (at most 1000): +//! a kind that asks for ticks while idle fails it +//! size 60 20 the session's terminal, the pane's share of it +//! (`window CxR` says what the kind paints) +//! seed 7 what every pane's seed is made from (before open) +//! click 3 1 a left click at the body's column 3, row 1 +//! focus, blur the view's window takes the keyboard, or loses it +//! graphics on|off the view's frontend shows pictures, or not +//! (glyph art, the start's) +//! view 2 on|off into view 2 (1 is the start's; one opened as the +//! first is), its frontend with pictures or not +//! dump the pane's record (its length) loaded into a +//! fresh pane, which the script goes on with +//! body, ctl the pane's body, or its ctl file's read +//! Word arg one of the kind's words, at its pane +//! # anything a comment, not printed +const std = @import("std"); +const pardes = @import("core"); +const Kind = @import("core").Kind; +const Pardes = pardes.Pardes; + +pub fn main(io: std.Io, gpa: std.mem.Allocator, lib: []const u8, script_path: ?[]const u8) u8 { + var out_buf: [4096]u8 = undefined; + var out_file = std.Io.File.stdout().writer(io, &out_buf); + const out = &out_file.interface; + defer out.flush() catch {}; + run(io, gpa, lib, script_path, out) catch |err| { + out.print("addon-test: {t}\n", .{err}) catch {}; + return 1; + }; + return 0; +} + +fn run(io: std.Io, gpa: std.mem.Allocator, lib: []const u8, script_path: ?[]const u8, out: *std.Io.Writer) !void { + const script = try std.Io.Dir.cwd().readFileAlloc(io, script_path orelse return error.NoScript, gpa, .limited(1 << 20)); + defer gpa.free(script); + // The regions and the C libraries' allocators a frontend sets up. + const allocs = pardes.memory.init(gpa); + defer pardes.memory.deinit(); + pardes.syntax.start(allocs.tree_sitter); + defer pardes.syntax.stop(); + // A terminal's view on every build: what a script prints is the same + // from a window's binary (a picture's raster is a view's, Kind.viewOf). + const p = try Pardes.init(gpa, .{ .tty_only = true, .windowed = false, .cols = 80, .rows = 24, .state = .memory, .image_allocator = allocs.image, .tree_sitter_allocator = allocs.tree_sitter, .frame_allocator = allocs.frame }); + defer p.deinit(); + // Loaded as `Addon load` loads it, the host's half here. + pardes.Addon.perform(p, .load, 0, lib); + const last = &p.kinds.kinds[p.kinds.n - 1]; + if (last.refused) { + try out.print("addon-test: {s}\n", .{last.why.slice()}); + return error.KindRefused; + } + const k = p.kinds.n - 1; + var now: u64 = std.time.ns_per_s; + p.advance(now); + var id: ?usize = null; + var said = false; + var lines = std.mem.splitScalar(u8, script, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (line.len == 0 or line[0] == '#') continue; + try out.print("> {s}\n", .{line}); + const verb_end = std.mem.indexOfScalar(u8, line, ' ') orelse line.len; + const verb = line[0..verb_end]; + const arg = std.mem.trim(u8, line[verb_end..], " "); + const is = struct { + fn is(v: []const u8, w: []const u8) bool { + return std.mem.eql(u8, v, w); + } + }.is; + if (is(verb, "seed")) { + Kind.seed_base = std.fmt.parseInt(u64, arg, 10) catch 0; + continue; + } + const opened = id == null or is(verb, "open"); + if (opened) id = try open(p, k, if (is(verb, "open") and arg.len > 0) arg else null); + const at = id.?; + if (is(verb, "key")) { + try keys(p, arg); + } else if (is(verb, "tick")) { + now += (std.fmt.parseInt(u64, arg, 10) catch 0) * std.time.ns_per_ms; + p.advance(now); + } else if (is(verb, "settle")) { + var n: usize = 0; + while (Kind.wake(p) != null and n < 1000) : (n += 1) { + now = @max(now + 1, p.nextWake() orelse break); + p.advance(now); + } + if (n == 1000) try out.writeAll("settle: still asking for frames after 1000 ticks\n"); + } else if (is(verb, "size")) { + var it = std.mem.tokenizeScalar(u8, arg, ' '); + const cols = std.fmt.parseInt(u16, it.next() orelse "80", 10) catch 80; + const rows = std.fmt.parseInt(u16, it.next() orelse "24", 10) catch 24; + p.update(.{ .resize = .{ .cols = cols, .rows = rows } }); + } else if (is(verb, "click")) { + var it = std.mem.tokenizeScalar(u8, arg, ' '); + const col = std.fmt.parseInt(u16, it.next() orelse "0", 10) catch 0; + const row = std.fmt.parseInt(u16, it.next() orelse "0", 10) catch 0; + const body = window(p, at) orelse continue; + for ([_]pardes.Mouse.Kind{ .press, .release }) |mk| + p.update(.{ .mouse = .{ .button = .left, .kind = mk, .col = body.x + col, .row = body.y + row } }); + } else if (is(verb, "focus") or is(verb, "blur")) { + p.update(.{ .focus = is(verb, "focus") }); + } else if (is(verb, "graphics") or is(verb, "view")) { + // Into view N (another client's), then its frontend: with + // pictures (`on`), or glyph art. + if (is(verb, "view")) { + const n = std.fmt.parseInt(u8, arg[0..@min(1, arg.len)], 10) catch 1; + while (n > 1 and !pardes.views.isOpen(p, n - 1)) _ = p.openView() orelse break; + if (pardes.views.isOpen(p, n -| 1)) p.toView(n -| 1); + } + p.update(.{ .frontend = .{ .windowed = false, .native_images = std.mem.endsWith(u8, arg, "on") } }); + } else if (is(verb, "dump")) { + id = try reloaded(p, gpa, at, out); + } else if (is(verb, "body") or is(verb, "ctl")) { + drain(p); + var fields: [4096]u8 = undefined; + const text = if (is(verb, "body")) try Kind.body(p.panes[at].?, p.scratch.allocator()) else Kind.ctlRead(p.panes[at].?, &fields); + var rows = std.mem.splitScalar(u8, std.mem.trimEnd(u8, text, "\n"), '\n'); + while (rows.next()) |row| try out.print("={s}\n", .{row}); + continue; + } else if (!is(verb, "open")) { + p.view().active = at; + if (!p.executeBuiltinLine(at, line)) try out.print("not a word here: {s}\n", .{verb}); + } + drain(p); + // The session's own steps owed (a tick asked outside a step, a view + // whose facts moved, a focus), as a host's pump takes them (17.2). + var owed: usize = 0; + while (owed < 4 and window(p, id.?) != null and (Kind.wake(p) orelse std.math.maxInt(u64)) <= @max(1, p.clock.stepped_ns)) : (owed += 1) { + p.update(.tick); + drain(p); + } + try show(p, gpa, id.?, out, opened or is(verb, "size")); + if (Kind.breach.len > 0 and !said) try out.print("addon-test: {s}\n", .{Kind.breach.slice()}); + said = Kind.breach.len > 0; + } + if (said) return error.OverBudget; +} + +fn open(p: *Pardes, k: u8, path: ?[]const u8) !usize { + const free = p.freeSlot() orelse return error.NoPaneSlots; + _ = if (path) |at| try Kind.openFile(p, free, k, at) else try Kind.open(p, free, k, null, null); + pardes.layout.placeNew(p, p.view().active, null, free, .doc); + p.view().active = free; + drain(p); + return free; +} + +/// The pane's record loaded into a fresh pane in its place, as a Restore +/// would: what the script goes on with. +fn reloaded(p: *Pardes, gpa: std.mem.Allocator, at: usize, out: *std.Io.Writer) !usize { + const slot = p.panes[at].?.addon.?; + const record = try pardes.dump.slotRecord(slot); + defer if (record) |r| slot.gpa.free(r); + try out.print("dump {d} bytes\n", .{if (record) |r| r.len else 0}); + var bytes: std.Io.Writer.Allocating = .init(gpa); + defer bytes.deinit(); + try pardes.dump.slotWrite(slot, gpa, &bytes.writer); + const fresh = try slot.gpa.create(Kind.Slot); + try pardes.dump.slotRead(fresh, slot.gpa, bytes.written()); + try p.removePane(at, null); + const free = p.freeSlot() orelse return error.NoPaneSlots; + const pane = try p.newDocPane(free); + pane.addon = fresh; + pardes.dump.reviveSlot(p, free, fresh); + pardes.layout.placeNew(p, p.view().active, null, free, .doc); + p.view().active = free; + drain(p); + return free; +} + +/// Its effects done as a host does them: its jobs here, at once. +fn drain(p: *Pardes) void { + while (p.nextEffect()) |e| if (e == .job) p.perform(e); +} + +fn keys(p: *Pardes, text: []const u8) !void { + const Key = pardes.Key; + const names = [_]struct { []const u8, u21 }{ + .{ "<up>", Key.up }, .{ "<down>", Key.down }, .{ "<left>", Key.left }, .{ "<right>", Key.right }, + .{ "<enter>", Key.enter }, .{ "<tab>", Key.tab }, .{ "<bs>", Key.backspace }, .{ "<esc>", Key.escape }, + .{ "<space>", ' ' }, + }; + var i: usize = 0; + while (i < text.len) { + const cp: u21 = for (names) |n| { + if (std.mem.startsWith(u8, text[i..], n[0])) { + i += n[0].len; + break n[1]; + } + } else blk: { + const len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; + const c = std.unicode.utf8Decode(text[i..@min(text.len, i + len)]) catch text[i]; + i += len; + break :blk c; + }; + p.update(.{ .key = .{ .cp = cp } }); + drain(p); + } +} + +/// The cells the kind paints: its body less the notices over it. +fn window(p: *Pardes, id: usize) ?pardes.Rect { + var arena: std.heap.ArenaAllocator = .init(p.gpa); + defer arena.deinit(); + const s = p.render(arena.allocator()) catch return null; + var r = (s.region(.body, id) orelse return null).rect; + const shown = p.panes[id].?.notices.span(); + r.y += shown; + r.h -|= shown; + return r; +} + +/// The pane's body, a line a row (an unpainted cell a space), then each +/// placement over it; `window CxR` first when asked. +fn show(p: *Pardes, gpa: std.mem.Allocator, id: usize, out: *std.Io.Writer, size: bool) !void { + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const pane = p.panes[id] orelse return out.writeAll("(the pane is gone)\n"); + if (size) if (window(p, id)) |w| try out.print("window {d}x{d}\n", .{ w.w, w.h }); + try out.print("tag {s}\n", .{try Kind.prefix(p, arena.allocator(), pane)}); + const r = (s.region(.body, id) orelse return).rect; + for (r.y..r.y + r.h) |y| { + var row: std.ArrayList(u8) = .empty; + for (r.x..r.x + r.w) |x| { + const c = s.at(@intCast(x), @intCast(y)); + try row.appendSlice(arena.allocator(), if (c.default) " " else c.grapheme()); + } + try out.print("|{s}\n", .{std.mem.trimEnd(u8, row.items, " ")}); + } + for (s.placements.items) |pl| if (pl.pane == id) { + try out.print("placement {d}x{d} src {d},{d} {d}x{d} over {d},{d} {d}x{d} key {x}", .{ pl.raster.w, pl.raster.h, pl.src.x, pl.src.y, pl.src.w, pl.src.h, pl.dst.x - r.x, pl.dst.y - r.y, pl.dst.w, pl.dst.h, pl.key }); + if (pl.at) |at| try out.print(" at {d},{d} {d}x{d}", .{ at.x, at.y, at.w, at.h }); + if (pl.dirty) |d| try out.print(" rows {d}+{d} of {x}", .{ d.y, d.h, d.from }); + try out.writeAll("\n"); + }; +} diff --git a/runtime/crash.zig b/runtime/crash.zig new file mode 100644 index 00000000..2ce43353 --- /dev/null +++ b/runtime/crash.zig @@ -0,0 +1,256 @@ +//! The crash file: what a panic leaves behind for the human who has to report it. +//! +//! stderr is where a panic has always gone, and stderr is the worst place this +//! program has. In the tui shell stderr IS the screen — the trace lands on the +//! grid the terminal is being reset out of, and the next redraw or the next +//! `clear` takes it with it. The GUI and the AppKit shells have no terminal at +//! all, so it goes to a console nobody has open. A detached session's goes +//! wherever the launcher left it, which is usually /dev/null. So a record is +//! appended to `<config dir>/crashes` as well, under one line naming the build +//! that produced it: a bug report needs the version and the commit, and a user +//! who runs pardes already knows where its config lives. +//! +//! The record is the metadata line and the panic message, and NOT the frames: +//! every way of collecting those from out here can wedge the process instead of +//! ending it. `record` says exactly why, at length, because the reasoning is +//! not visible from the call it does not make. +//! +//! Panics only. A SIGSEGV never reaches a panic handler (main.zig `debug` +//! hooks that path separately) and unwinding one needs the signal's saved cpu +//! context, which is a different job than this one. + +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("core"); + +/// The crash log's name, beside `init` in the configuration directory. +pub const name = "crashes"; + +/// The config directory `config.User.load` resolved, COPIED rather than +/// borrowed: main.zig hands over an arena slice that outlives the process, but +/// the AppKit host's lives in a `config_arena` its own `errdefer` frees on a +/// failed init and its teardown frees at quit — and a panic after either would +/// have built a path out of freed memory and then created a directory at it. +/// A panic handler is the one caller that cannot check whether its input is +/// still alive, so it does not borrow. +var dir_buf: [1024]u8 = undefined; + +/// The crash file's bound (see `record`). +const max_log_bytes = 256 * 1024; +var dir_len: usize = 0; + +/// Called where the launcher sets `Options.config_dir`. Ignores a path too long +/// to hold, which is a crash file that never appears rather than a truncated +/// path pointing somewhere real. +pub fn setDir(path: []const u8) void { + if (path.len == 0 or path.len > dir_buf.len) return; + @memcpy(dir_buf[0..path.len], path); + dir_len = path.len; +} + +/// Built at comptime out of the two halves main.zig's `--version` prints, and +/// for the same reason: there is nothing here to format at runtime. A build +/// from a tarball says `pardes 0.1` rather than inventing a revision. +const build_id = if (pardes.commit) |c| + "pardes " ++ pardes.version ++ " (" ++ c ++ ")" +else + "pardes " ++ pardes.version; + +/// The whole record is formatted here before a byte of it is written, because +/// the fd is opened `O_APPEND` and one `write(2)` of the lot is what keeps two +/// crashing processes from interleaving their records line by line. Static +/// rather than a local: a panic handler may be running on a thread stack of a +/// few pages. Two lines fit several times over — the panic message is the only +/// part with no bound of its own, and a longer one is simply cut. +var scratch: [8 << 10]u8 = undefined; + +/// One record per process, taken by whoever panics first. `defaultPanic` gets +/// the same property from a private `panic_stage` and from the stderr lock, and +/// neither is reachable from out here: two threads panicking at once would +/// interleave `@memcpy`s into one `scratch` and each write out the mixture, and +/// the nested panic `defaultPanic`'s own trace printer can raise comes back +/// through the handler and appends its wreckage under the real message. Both +/// end here instead, and the loser falls through to `defaultPanic`, which still +/// says everything on stderr. +var recording: std.atomic.Value(bool) = .init(false); + +/// Append one crash record, or silently do nothing. Called FROM the panic +/// handler, so it takes no lock of this program's, allocates nothing of its +/// own, and does its own file I/O: a static buffer, one `open`, one `write`. +/// Every failure is swallowed — a crash file that could not be written must not +/// become the crash, and stderr is about to get the message either way. +pub fn record(msg: []const u8) void { + if (dir_len == 0) return; + // ONCE PER PROCESS, and never released. A process panics once and dies; a + // SECOND record is always the wreckage of the first. Observed with the + // flag released on the way out: `defaultPanic`'s own trace printing raised + // a nested panic, which came back through the handler and appended + // "panic: reached unreachable code" under the real message — burying the + // one line the file exists to keep. A test resets it deliberately. + if (recording.swap(true, .seq_cst)) return; + const config_dir = dir_buf[0..dir_len]; + var path_buf: [1024:0]u8 = undefined; + if (config_dir.len + 1 + name.len >= path_buf.len) return; + + // The directory is where the config WOULD be, not where it is: a user who + // never wrote an init file has no config directory, and the first thing + // they have to report is this. Parents are assumed and EEXIST is the + // normal answer, exactly as dump.zig bets for its own directory. + @memcpy(path_buf[0..config_dir.len], config_dir); + path_buf[config_dir.len] = 0; + _ = std.c.mkdir(path_buf[0..config_dir.len :0], 0o755); + + path_buf[config_dir.len] = '/'; + @memcpy(path_buf[config_dir.len + 1 ..][0..name.len], name); + path_buf[config_dir.len + 1 + name.len] = 0; + const path = path_buf[0 .. config_dir.len + 1 + name.len :0]; + + const fd = std.c.open(path, .{ + .ACCMODE = .WRONLY, + .CREAT = true, + .APPEND = true, + }, @as(std.c.mode_t, 0o600)); + if (fd < 0) return; + defer _ = std.c.close(fd); + // Bounded: a file past `max_log_bytes` starts over, so it keeps the + // newest records rather than every crash since it was first made. + if (std.c.lseek(fd, 0, std.c.SEEK.END) > max_log_bytes) _ = std.c.ftruncate(fd, 0); + + var w: std.Io.Writer = .fixed(&scratch); + + // The metadata line. Same clock and the same civil-time arithmetic as + // dump.zig's filename, printed as UTC because a crash file is read by + // whoever the reporter sends it to and their zone is not the reporter's. + // + // The return IS checked, unlike dump.zig's, because this one runs where a + // panic cannot be afforded: a failed `clock_gettime` leaves `ts` undefined, + // and an undefined large-positive `sec` walks `calculateYearDay`'s `u16` + // year past 65535 and overflow-panics INSIDE the panic handler. Debug fills + // it with 0xaa and lands in 1970, which is why it reads as harmless. + var ts: std.c.timespec = .{ .sec = 0, .nsec = 0 }; + if (std.c.clock_gettime(.REALTIME, &ts) != 0) ts = .{ .sec = 0, .nsec = 0 }; + const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; + const yd = es.getEpochDay().calculateYearDay(); + const md = yd.calculateMonthDay(); + const ds = es.getDaySeconds(); + w.print("\n" ++ build_id ++ " {d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z {s}-{s} pid {d}\n", .{ + yd.year, + md.month.numeric(), + @as(u8, md.day_index) + 1, + ds.getHoursIntoDay(), + ds.getMinutesIntoHour(), + ds.getSecondsIntoMinute(), + @tagName(builtin.os.tag), + @tagName(builtin.cpu.arch), + // Unsigned: `{d}` prints a leading '+' for a positive SIGNED int, which + // is the same note main.zig makes where it names a `--detach` session + // after this pid. + @as(u32, @intCast(std.c.getpid())), + }) catch {}; + + // ...and under it the line stderr is about to print. + // + // NO STACK TRACE, AND NOT EVEN THE RAW RETURN ADDRESSES. This is the whole + // design decision in this file, and it was arrived at by measurement, so it + // is written down here rather than left to be rediscovered. + // + // `std.debug.writeCurrentStackTrace` — the call `defaultPanic` makes a + // moment later, into a writer of its own — HANGS THE PROCESS when it is + // made from a panic handler BEFORE `defaultPanic` has run. Observed at 0% + // CPU in `futex_do_wait` with libc's debug info half-open, identically in a + // test binary and in a standalone build carrying this program's + // `std_options_debug_io`. Calling `debug_io.vtable.crashHandler` first does + // not help, and neither does holding `lockStderr` around it. + // + // `captureCurrentStackTrace` looks like the safe half of that and is NOT. + // `StackIterator.init` picks the `.di` strategy whenever `SelfInfo` can + // unwind, `stratOk` accepts `.di` no matter what `allow_unsafe_unwind` + // says, and `.di` unwinding takes `SelfInfo`'s rwlock EXCLUSIVELY on its + // first call — the only kind of call a panic record ever makes — while it + // runs `dl_iterate_phdr` and a DWARF CFI machine and allocates. A panic in + // there (a smashed stack is a leading cause of getting here at all) leaves + // that lock held forever, because the unlock is a `defer` in a frame that + // never returns. `defaultPanic` then asks for the same lock and waits on it + // for the life of the process: A CRASH BECOMES A HANG, which is strictly + // worse than the behaviour this file was added to improve on. What makes + // `defaultPanic` itself survive that is its own PRIVATE `panic_stage`, + // reachable from nowhere out here. + // + // So the frames stay on stderr, where `defaultPanic` prints them under the + // staging that makes them safe, and this file keeps what it can gather + // without asking the process any questions: which build, when, where, and + // what it said. That is the half a reporter cannot reconstruct afterwards. + w.print("panic: {s}\n", .{msg}) catch {}; + var in_addon: [160]u8 = undefined; + if (@import("core").Kind.calling(&in_addon)) |where| w.print("{s}\n", .{where}) catch {}; + + // One `write(2)`, and the loop is for a short write rather than for a + // second record: `O_APPEND` puts it at the end whatever else is writing, + // and nothing above here can fail in a way that leaves it half-built. + const written = w.buffered(); + var off: usize = 0; + while (off < written.len) { + const n = std.c.write(fd, written.ptr + off, written.len - off); + if (n <= 0) break; // including EINTR: the record is best effort + off += @intCast(n); + } +} + +test "a crash record names the build, appends, and carries the panic message" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var base_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const base_len = try tmp.dir.realPath(io, &base_buf); + + // A directory that does NOT exist yet, which is the case that matters: the + // user who has never written an init file is the likeliest reporter. + const config_dir = try std.Io.Dir.path.join(gpa, &.{ base_buf[0..base_len], "pardes" }); + defer gpa.free(config_dir); + const saved_len = dir_len; + defer dir_len = saved_len; + setDir(config_dir); + + record("first boom"); + // Deliberately released, which the panic path never does — see `recording`. + // Two records is how the APPEND is proved, and this is the only caller + // allowed to ask for a second one. + recording.store(false, .seq_cst); + record("second boom"); + + const path = try std.Io.Dir.path.join(gpa, &.{ config_dir, name }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(bytes); + + // The metadata line, then the message, for each of the two panics: the + // file is appended to, never rewritten. + try std.testing.expect(std.mem.count(u8, bytes, build_id ++ " ") == 2); + try std.testing.expect(std.mem.indexOf(u8, bytes, "panic: first boom\n") != null); + const second = std.mem.indexOf(u8, bytes, "panic: second boom\n").?; + try std.testing.expect(std.mem.indexOf(u8, bytes, "panic: first boom\n").? < second); + // ...and the platform and a UTC stamp on that line, which is the half a + // version string cannot give: `1970-` would mean the clock read failed. + const stamp = std.mem.indexOf(u8, bytes, @tagName(builtin.os.tag) ++ "-" ++ @tagName(builtin.cpu.arch)).?; + try std.testing.expect(stamp < second); + try std.testing.expect(std.mem.indexOf(u8, bytes, "1970-") == null); + + // Two lines per record and no third: the frames deliberately do NOT come + // here (see `record`), and a future edit that starts collecting them again + // is the thing this pins. Counted rather than pattern-matched, because the + // failure being guarded is "something extra appeared", which no assertion + // about known content can see. + // Three newlines a record: the blank one that separates records, the end of + // the metadata line, and the end of the `panic:` line. + try std.testing.expectEqual(@as(usize, 6), std.mem.count(u8, bytes, "\n")); + + // No directory, no file: a core that never resolved a config directory + // panics exactly as it did before this existed. + dir_len = 0; + recording.store(false, .seq_cst); + record("unrecorded"); + const again = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 20)); + defer gpa.free(again); + try std.testing.expectEqual(bytes.len, again.len); +} diff --git a/runtime/daemon.zig b/runtime/daemon.zig new file mode 100644 index 00000000..6d96708d --- /dev/null +++ b/runtime/daemon.zig @@ -0,0 +1,1251 @@ +//! The per-user daemon (docs/next-daemon.md, "Phase 3 notes"): one +//! `pardes --daemon` per user per machine, on `pardes-daemon.sock` in the +//! runtime directory (ninep_io.socketDir), its `.lock` flocked for its life +//! so two never run. The first session that finds none starts it (a double +//! fork and an exec), and it exits once it holds nothing: no session +//! connected, no pty master kept. +//! +//! It spawns nothing and is nobody's parent. A session registers on one +//! connection and tells it, over that connection: +//! - a dup of every pty master it forks (`pty`), so a session killed +//! outright never hangs its shells up, and which ones it closed; +//! - whether a terminal or a window shows it (`state`). +//! It hands a terminal (`pardes --attach`) or a window request +//! (`pardes-gui --attach`) to a detached session, and a crashed session's +//! masters to the one that asks for them (Adopt). +//! +//! Messages are SOCK_SEQPACKET datagrams: a line of words, and the fds it +//! carries (SCM_RIGHTS). +//! +//! A replica (docs/next-daemon.md, phase 5) comes in on a stream socket of +//! its own, `pardes-replica.sock`, which `ssh -L` can forward: its hello +//! (wire.zig) names a session, and once its build is the session's +//! the connection is handed to that session, which it talks to from then on. +const std = @import("std"); +const builtin = @import("builtin"); +/// libc: sockets passing fds (SCM_RIGHTS), fork and setsid, and unlinks a signal handler or a forked child makes. +const libc = std.c; +const posix = std.posix; +const ninep_io = @import("9p_io.zig"); +const wire = @import("core").wire; +const upgrade = @import("upgrade.zig"); +const log = std.log.scoped(.replica); + +pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd; +/// 2: a session's hello carries its semantics hash (wire.semantics). +const version = 2; +pub const max_fds = 64; +const msg_max = 4096; +/// Idle this long, it exits: long enough for the session that started it to +/// say hello, short enough that nothing lingers. +const linger_ms = 1000; +const max_conns = 64; +const max_held = 256; +/// Replicas whose hello is still on its way. ponytail: one that never sends +/// it holds its slot until it hangs up; past 16 a new one is closed at once. +const max_replicas = 16; +const sun_path_len = ninep_io.sun_path_len; +const nosignal: u32 = if (builtin.os.tag == .linux) libc.MSG.NOSIGNAL else 0; + +pub const Kind = enum { tty, gui }; + +/// Off for a harness that kills what it starts by its pid and closes its +/// terminal (`PARDES_DAEMON=off`, the snapshot harness's): a session there +/// is the process it started, and a hung-up terminal ends it, as before +/// the daemon. A GUI test window (PARDES_TEST) has none unless asked +/// (`PARDES_DAEMON=on`). +pub fn wanted() bool { + if (comptime !supported) return false; + const v = std.mem.span(libc.getenv("PARDES_DAEMON") orelse return libc.getenv("PARDES_TEST") == null); + return !std.mem.eql(u8, v, "off"); +} + +fn place(buf: *[sun_path_len:0]u8, comptime leaf: []const u8) ?[:0]const u8 { + var dir_buf: [sun_path_len:0]u8 = undefined; + const dir = ninep_io.socketDir(&dir_buf) orelse return null; + _ = libc.mkdir(dir, 0o700); + return std.fmt.bufPrintSentinel(buf, "{s}/" ++ leaf, .{dir}, 0) catch null; +} + +// ---- one message: words and fds ---- + +const data_off = std.mem.alignForward(usize, @sizeOf(libc.cmsghdr), @sizeOf(usize)); +fn cmsgSpace(n: usize) usize { + return data_off + std.mem.alignForward(usize, n * @sizeOf(c_int), @sizeOf(usize)); +} + +fn send(fd: c_int, words: []const u8, fds: []const c_int) bool { + std.debug.assert(words.len > 0 and fds.len <= max_fds); + var iov = [_]posix.iovec_const{.{ .base = words.ptr, .len = words.len }}; + var cbuf: [cmsgSpace(max_fds)]u8 align(@alignOf(libc.cmsghdr)) = undefined; + var msg: libc.msghdr_const = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = null, .controllen = 0, .flags = 0 }; + if (fds.len > 0) { + const hdr: *libc.cmsghdr = @ptrCast(&cbuf); + hdr.* = .{ .len = @intCast(data_off + fds.len * @sizeOf(c_int)), .level = libc.SOL.SOCKET, .type = libc.SCM.RIGHTS }; + @memcpy(cbuf[data_off..][0 .. fds.len * @sizeOf(c_int)], std.mem.sliceAsBytes(fds)); + msg.control = &cbuf; + msg.controllen = @intCast(cmsgSpace(fds.len)); + } + while (true) { + // Never blocks: a peer that does not read loses its link instead. + const n = libc.sendmsg(fd, &msg, nosignal | libc.MSG.DONTWAIT); + if (n >= 0) return true; + if (libc.errno(n) != .INTR) return false; + } +} + +const Got = struct { words: []const u8, fds: [max_fds]c_int = undefined, nfds: usize = 0 }; + +/// The next message, its fds close-on-exec; null at the end of the link. +fn recv(fd: c_int, buf: []u8) ?Got { + var iov = [_]posix.iovec{.{ .base = buf.ptr, .len = buf.len }}; + var cbuf: [cmsgSpace(max_fds)]u8 align(@alignOf(libc.cmsghdr)) = undefined; + var msg: libc.msghdr = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = &cbuf, .controllen = cbuf.len, .flags = 0 }; + const n = while (true) { + // Darwin has no MSG_CMSG_CLOEXEC: its fds are marked below. + const r = libc.recvmsg(fd, &msg, if (builtin.os.tag == .linux) libc.MSG.CMSG_CLOEXEC else 0); + if (r >= 0) break r; + if (libc.errno(r) != .INTR) return null; + }; + var got: Got = .{ .words = buf[0..@intCast(n)] }; + if (msg.controllen >= data_off) { + const hdr: *const libc.cmsghdr = @ptrCast(&cbuf); + if (hdr.level == libc.SOL.SOCKET and hdr.type == libc.SCM.RIGHTS and hdr.len >= data_off) { + got.nfds = @min((hdr.len - data_off) / @sizeOf(c_int), max_fds); + @memcpy(std.mem.sliceAsBytes(got.fds[0..got.nfds]), cbuf[data_off..][0 .. got.nfds * @sizeOf(c_int)]); + if (builtin.os.tag != .linux) for (got.fds[0..got.nfds]) |f| { + _ = libc.fcntl(f, libc.F.SETFD, @as(c_int, 1)); // FD_CLOEXEC + }; + } + } + // A zero-length datagram is never sent: it is the peer's end. + if (n == 0) { + for (got.fds[0..got.nfds]) |f| _ = libc.close(f); + return null; + } + return got; +} + +fn socket() c_int { + return libc.socket(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0); +} + +fn address(path: [:0]const u8) libc.sockaddr.un { + var addr: libc.sockaddr.un = .{ .path = @splat(0) }; + @memcpy(addr.path[0..path.len], path); + return addr; +} + +/// Connected without ever waiting on a daemon that does not accept (a full +/// backlog parks a blocking connect for good), then blocking again. +fn dial(path: [:0]const u8) ?c_int { + const fd = socket(); + if (fd < 0) return null; + const addr = address(path); + const flags = libc.fcntl(fd, libc.F.GETFL, @as(c_int, 0)); + const nonblock: c_int = @bitCast(@as(u32, @bitCast(libc.O{ .NONBLOCK = true }))); + _ = libc.fcntl(fd, libc.F.SETFL, flags | nonblock); + if (libc.connect(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) != 0) { + _ = libc.close(fd); + return null; + } + _ = libc.fcntl(fd, libc.F.SETFL, flags); + return fd; +} + +/// Waits `ms` for `fd` to be readable. +fn readable(fd: c_int, ms: c_int) bool { + var fds = [_]libc.pollfd{.{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }}; + while (true) { + const n = libc.poll(&fds, 1, ms); + if (n >= 0) return n > 0; + if (libc.errno(n) != .INTR) return false; + } +} + +fn sleepMs(ms: u32) void { + const ts: libc.timespec = .{ .sec = 0, .nsec = @as(c_long, ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); +} + +// ---- a client's half ---- + +/// A connection to the daemon. When none answers and `start`, the +/// connection is queued on a socket this process binds, and the daemon is +/// still to be started on it (`startPending`): a terminal's stub does that +/// after its fork, off the session's way; every other caller at once. +pub fn connect(start: bool) ?c_int { + if (comptime !supported) return null; + var sock_buf: [sun_path_len:0]u8 = undefined; + const sock = place(&sock_buf, "pardes-daemon.sock") orelse return null; + if (dial(sock)) |fd| return fd; + if (!start) return null; + var lock_buf: [sun_path_len:0]u8 = undefined; + const lock_path = place(&lock_buf, "pardes-daemon.lock") orelse return null; + // Another starter, or a daemon on its way out, holds the lock: it is + // asked again until the lock is free or the socket answers. + var waited: u32 = 0; + while (waited < 500) : (waited += 2) { + if (begin(sock, lock_path)) |fd| return fd; + sleepMs(2); + if (dial(sock)) |fd| return fd; + } + return null; +} + +/// The listener and lock a daemon is still to be started on (`begin`). +var pending: ?struct { listener: c_int, lock: c_int } = null; + +/// With the lock taken: the socket bound and listening here and this +/// process's connection queued on it, so it is answered as soon as the +/// daemon runs; the daemon itself is `startPending`'s. +fn begin(sock: [:0]const u8, lock_path: [:0]const u8) ?c_int { + const lock = libc.open(lock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, @as(libc.mode_t, 0o600)); + if (lock < 0) return null; + if (libc.flock(lock, posix.LOCK.EX | posix.LOCK.NB) != 0) { + _ = libc.close(lock); + return null; + } + // Ours to replace: whatever is at the path was a daemon that died. + _ = libc.unlink(sock); + const listener = socket(); + const addr = address(sock); + const conn = if (listener >= 0 and libc.bind(listener, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) == 0 and + libc.chmod(sock, 0o600) == 0 and libc.listen(listener, max_conns) == 0) dial(sock) else null; + if (conn == null) { + if (listener >= 0) _ = libc.close(listener); + _ = libc.close(lock); + return null; + } + pending = .{ .listener = listener, .lock = lock }; + return conn; +} + +/// The daemon `connect` left to start, started (or, `start` false, let go +/// of: a forked session's copies). +pub fn startPending(start: bool) void { + const p = pending orelse return; + pending = null; + if (start and !spawn(p.listener, p.lock)) { + var sock_buf: [sun_path_len:0]u8 = undefined; + if (place(&sock_buf, "pardes-daemon.sock")) |sock| _ = libc.unlink(sock); + } + _ = libc.close(p.listener); + _ = libc.close(p.lock); +} + +extern "c" fn close_range(first: c_uint, last: c_uint, flags: c_int) c_int; + +/// `pardes --daemon`, in a session of its own and nobody's child (forked +/// twice), on the listener and the lock as fds 3 and 4. +fn spawn(listener: c_int, lock: c_int) bool { + var exe_buf: [4096:0]u8 = undefined; + const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch return false; + exe_buf[n] = 0; + const argv = [_:null]?[*:0]const u8{ &exe_buf, "--daemon", null }; + const first = libc.fork(); + if (first < 0) return false; + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + if (libc.fork() != 0) libc._exit(0); + const l = libc.fcntl(listener, libc.F.DUPFD, @as(c_int, 10)); + const k = libc.fcntl(lock, libc.F.DUPFD, @as(c_int, 10)); + if (l < 0 or k < 0 or libc.dup2(l, 3) < 0 or libc.dup2(k, 4) < 0) libc._exit(127); + // Linux's by its syscall: musl (a static pardes) has no close_range; + // nor has Darwin, which closes them one by one. + const shut = if (comptime builtin.os.tag == .linux) + std.os.linux.close_range(5, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 + else if (comptime builtin.os.tag.isDarwin()) false else close_range(5, std.math.maxInt(c_uint), 0) == 0; + if (!shut) { + var fd: c_int = 5; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + } + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = libc.dup2(null_fd, @intCast(i)); + }; + if (null_fd > 4) _ = libc.close(null_fd); + _ = libc.chdir("/"); + _ = libc.execve(&exe_buf, &argv, @ptrCast(libc.environ)); + libc._exit(127); + } + var status: c_int = 0; + while (libc.waitpid(first, &status, 0) < 0 and libc.errno(-1) == .INTR) {} + return true; +} + +/// Says who this session is. Its answer is not waited for: a daemon just +/// started is still being exec'd, and no startup waits on it. The reader +/// (`watch`) takes the `ok`, and only then is the session kept (`kept`). +fn hello(fd: c_int, k: Kind, pid: libc.pid_t, named: []const u8, detached: bool) bool { + var buf: [256]u8 = undefined; + const words = std.fmt.bufPrint(&buf, "hello {d} {t} {d} {s} {x} {s}", .{ version, k, pid, if (detached) "detached" else "attached", wire.semantics, named }) catch return false; + return send(fd, words, &.{}); +} + +// ---- the session's link, process-wide ---- + +/// This session's registration (`register`), which forkShell and the hosts +/// tell of their ptys; -1 with none (no daemon, or PARDES_DAEMON=off). +pub var link: c_int = -1; +/// The daemon said `ok` to the hello, and the link has not ended since; +/// `gone` once it has ended. +var up = std.atomic.Value(bool).init(false); +var gone = std.atomic.Value(bool).init(false); +/// What it is called (its 9P name). +var name_buf: [128]u8 = undefined; +var name_len: usize = 0; +var reader: ?std.Thread = null; + +pub fn name() []const u8 { + return name_buf[0..name_len]; +} + +/// Whether a daemon keeps this session: what Detach, and a terminal's end, +/// need, or the session would be left where nothing can attach to it. A +/// daemon just started answers the hello once it runs, so this waits for +/// that answer (up to 2 s): never on a startup's path, only on those two. +pub fn kept() bool { + if (link < 0) return false; + var waited: u32 = 0; + while (!up.load(.acquire) and !gone.load(.acquire) and waited < 2000) : (waited += 1) sleepMs(1); + return up.load(.acquire); +} + +/// The name a session goes by: its 9P socket's (`--9p=`, `--detach=`), else +/// its pid, as ninep_io.start names it. +fn setName(named: []const u8) void { + const n = if (named.len != 0) + std.fmt.bufPrint(&name_buf, "{s}", .{named[0..@min(named.len, name_buf.len)]}) catch unreachable + else + std.fmt.bufPrint(&name_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch unreachable; + name_len = n.len; +} + +/// Registers this session on `fd` (connected already, as a terminal's +/// stub does before it forks), or on a new connection when `fd` is null. +pub fn register(fd: ?c_int, k: Kind, named: []const u8, detached: bool) bool { + if (comptime !supported) return false; + setName(named); + const c = fd orelse connect(true) orelse return false; + startPending(true); + if (!hello(c, k, libc.getpid(), name(), detached)) { + _ = libc.close(c); + return false; + } + link = c; + return true; +} + +/// A session's replica clients at once (replica.Peers): `--ps` lists them. +const max_clients = 4; + +fn tell(words: []const u8, fds: []const c_int) void { + if (link < 0) return; + _ = send(link, words, fds); +} + +/// A shell forked on `master` (host_io.forkShell): the daemon keeps a dup. +pub fn pty(pid: libc.pid_t, master: c_int) void { + var buf: [32]u8 = undefined; + tell(std.fmt.bufPrint(&buf, "pty {d}", .{pid}) catch unreachable, &.{master}); // a pid fits 32 +} + +/// The pty of `pid` closed here: the daemon lets its dup go too. +pub fn closed(pid: libc.pid_t) void { + if (pid <= 0) return; + var buf: [32]u8 = undefined; + tell(std.fmt.bufPrint(&buf, "close {d}", .{pid}) catch unreachable, &.{}); // a pid fits 32 +} + +pub fn setState(detached: bool) void { + tell(if (detached) "state detached" else "state attached", &.{}); +} + +/// This session's replica clients now, each its process's pid (0 when its +/// socket's peer is not known), for `--ps`. +pub fn clients(pids: []const libc.pid_t) void { + var buf: ["clients".len + max_clients * " -2147483648".len]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + w.writeAll("clients") catch unreachable; // a literal, its .len in buf's + for (pids[0..@min(pids.len, max_clients)]) |pid| w.print(" {d}", .{pid}) catch unreachable; // max_clients i32s, in buf's type + tell(w.buffered(), &.{}); +} + +/// Asks for the masters of sessions that died holding them; they come back +/// as an `adopted` note. +pub fn adopt() void { + tell("adopt", &.{}); +} + +/// This session is about to exec another build (upgrade.zig): the daemon +/// is asked to move too. Its replica clients were told why they are let go +/// (replica.zig `Peers.refuseAll`). +pub fn upgraded() void { + tell("upgrade", &.{}); +} + +/// An upgraded session's link and stub as its old process left them: its +/// build's hello said again on the link (the daemon keeps its masters as +/// they were), and the stub's death a HUP again. +pub fn resumeLink(fd: c_int, stub_fd: c_int, k: Kind, named: []const u8, detached: bool) void { + if (comptime !supported) return; + stub = stub_fd; + if (stub >= 0) hupOnStubDeath(true); + setName(named); + if (fd >= 0 and hello(fd, k, libc.getpid(), name(), detached)) link = fd else if (fd >= 0) _ = libc.close(fd); +} + +pub const Note = union(enum) { + /// A terminal for a detached tui session (`pardes --attach`), and the + /// stub's pipe; for a window session, both -1: open a window. + attach: struct { tty: c_int, stub: c_int }, + adopted: struct { pids: [max_fds]libc.pid_t, fds: [max_fds]c_int, n: usize }, + /// A replica's connection, its hello taken (src/replica.zig `Peers`), + /// and the view it joins again for, if it does. + replica: Joining, +}; + +pub const Joining = struct { fd: c_int, view: ?u8 = null }; + +/// Hands every note the daemon sends on to `deliver`, on a thread of its +/// own, until the link ends (`quit`). Called each loop: started once. +pub fn watch(ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { + if (link < 0 or reader != null) return; + reader = std.Thread.spawn(.{}, readNotes, .{ link, ctx, deliver }) catch null; +} + +fn readNotes(fd: c_int, ctx: *anyopaque, deliver: *const fn (ctx: *anyopaque, note: Note) void) void { + var buf: [msg_max]u8 = undefined; + // The end of the link (a daemon gone, a hello refused): not kept. + defer { + up.store(false, .release); + gone.store(true, .release); + } + while (recv(fd, &buf)) |got| { + var words = std.mem.tokenizeScalar(u8, got.words, ' '); + const verb = words.next() orelse ""; + if (std.meta.stringToEnum(enum { ok, attach, replica, adopted }, verb)) |v| switch (v) { + .ok => up.store(true, .release), + .attach => { + deliver(ctx, .{ .attach = .{ + .tty = if (got.nfds >= 2) got.fds[0] else -1, + .stub = if (got.nfds >= 2) got.fds[1] else -1, + } }); + for (got.fds[@min(got.nfds, 2)..got.nfds]) |f| _ = libc.close(f); + }, + .replica => { + const view = std.fmt.parseInt(u8, words.next() orelse "", 10) catch null; + if (got.nfds >= 1) deliver(ctx, .{ .replica = .{ .fd = got.fds[0], .view = view } }); + for (got.fds[@min(got.nfds, 1)..got.nfds]) |f| _ = libc.close(f); + }, + .adopted => { + var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } }; + const a = ¬e.adopted; + for (got.fds[0..got.nfds]) |f| { + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch { + _ = libc.close(f); + continue; + }; + a.pids[a.n] = pid; + a.fds[a.n] = f; + a.n += 1; + } + deliver(ctx, note); + }, + } else for (got.fds[0..got.nfds]) |f| { + _ = libc.close(f); + } + } +} + +/// `bytes` sent whole on a socket, never raising SIGPIPE: false when the +/// peer is gone. +pub fn writeAll(fd: c_int, bytes: []const u8) bool { + var at: usize = 0; + while (at < bytes.len) { + const n = libc.send(fd, bytes[at..].ptr, bytes.len - at, nosignal); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) return false; + at += @intCast(n); + } + return true; +} + +/// A replica's connection refused in words, and closed: by the daemon at +/// its hello, or by its session. A fresh connection's buffer is empty, so +/// this never blocks. +pub fn refuseReplica(fd: c_int, why: []const u8) void { + var out: [600]u8 = undefined; + if (wire.encodeServer(&out, .{ .refused = why[0..@min(why.len, 512)] })) |bytes| _ = writeAll(fd, bytes) else |_| {} + _ = libc.close(fd); +} + +/// A session ended by a signal (TERM, HUP, INT): its shells go with it, as +/// at a quit. Async-signal-safe: one send. One killed outright (KILL) or +/// crashed says nothing, and its shells live on for an Adopt. +pub fn hangUp() void { + if (link >= 0) _ = send(link, "quit", &.{}); +} + +/// The session's end: its masters are let go (its shells hang up), the +/// link closed, the reader joined. +pub fn quit() void { + if (link < 0) return; + tell("quit", &.{}); + _ = libc.shutdown(link, 2); + if (reader) |r| r.join(); + reader = null; + _ = libc.close(link); + link = -1; +} + +// ---- `pardes --attach`: a terminal, or a window, for a detached session ---- + +/// `other`: the session is the other kind (a window's for a terminal, or a +/// terminal's for a window), named so: joined as a replica client instead +/// (`replicaSocket`). +pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8, other: []const u8 }; + +/// This machine's replica socket, which joins a session of either kind. +pub fn replicaSocket(buf: *[sun_path_len:0]u8) ?[:0]const u8 { + return place(buf, "pardes-replica.sock"); +} + +/// Asks the daemon to hand `fds` (a terminal and a stub's pipe, or none for +/// a window) to the detached session `named` (any one, when empty), and +/// answers how it went; the words are `buf`'s. +pub fn attach(k: Kind, named: []const u8, fds: []const c_int, buf: []u8) Answer { + const fd = connect(false) orelse return .{ .no = "no detached session is running" }; + defer _ = libc.close(fd); + var line: [256]u8 = undefined; + const words = std.fmt.bufPrint(&line, "attach {t} {s}", .{ k, named }) catch return .{ .no = "that name is too long" }; + if (!send(fd, words, fds) or !readable(fd, 2000)) return .{ .no = "the daemon does not answer" }; + const got = recv(fd, buf) orelse return .{ .no = "the daemon hung up" }; + for (got.fds[0..got.nfds]) |f| _ = libc.close(f); + if (std.mem.startsWith(u8, got.words, "ok ")) { + const pid = std.fmt.parseInt(libc.pid_t, got.words[3..], 10) catch return .{ .no = "the daemon answered nonsense" }; + return .{ .ok = pid }; + } + if (std.mem.startsWith(u8, got.words, "other ")) return .{ .other = got.words["other ".len..] }; + return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else got.words }; +} + +/// The daemon's answer to `words` (`list`, `kill <name>`, `killall`), in +/// `buf`; null with no daemon running, or none answering. +pub fn ask(words: []const u8, buf: []u8) ?[]const u8 { + const fd = connect(false) orelse return null; + defer _ = libc.close(fd); + if (!send(fd, words, &.{}) or !readable(fd, 2000)) return null; + const got = recv(fd, buf) orelse return null; + for (got.fds[0..got.nfds]) |f| _ = libc.close(f); + return got.words; +} + +// ---- a terminal's stub ---- + +var stub_child: libc.pid_t = 0; + +fn forward(sig: posix.SIG) callconv(.c) void { + if (stub_child > 0) _ = libc.kill(stub_child, sig); + // The terminal's hangup: the session, told, carries on detached, and + // this job ends as a hung-up one does. + if (sig == .HUP) { + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(.HUP, &default, null); + _ = libc.raise(.HUP); + } +} + +/// The job the shell waits on, for a session that is not its child any +/// more (`pardes --attach`) or that it forked (`child`, reaped here): what +/// a terminal sends the job goes on to the session (its size, an end +/// asked for), and it ends when the session is gone from the terminal -- +/// detached (`d<name>`), exited (`x<code>`, or the pipe's end and the +/// child's status), or refused (`r<why>`). +pub fn stubWait(session: libc.pid_t, child: bool, pipe: c_int) noreturn { + stub_child = session; + const on: posix.Sigaction = .{ .handler = .{ .handler = forward }, .mask = posix.sigemptyset(), .flags = posix.SA.RESTART }; + for ([_]posix.SIG{ .WINCH, .TERM, .INT, .QUIT, .HUP }) |sig| posix.sigaction(sig, &on, null); + // Ctrl-Z is a key in the raw terminal (the pane's), as before; a TSTP + // sent here would stop the job under a session still drawing, so it is + // not taken. + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(.TSTP, &ignore, null); + var buf: [512]u8 = undefined; + var len: usize = 0; + while (len < buf.len) { + const n = libc.read(pipe, buf[len..].ptr, buf.len - len); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) break; + len += @intCast(n); + } + const said = buf[0..len]; + const out = std.Io.File.stderr(); + const io = std.Io.Threaded.global_single_threaded.io(); + if (said.len > 0 and said[0] == 'd') { + var text: [700]u8 = undefined; + const who = said[1..]; + out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: detached from '{s}', which is still running; come back with `pardes --attach={s}`\n", .{ who, who }) catch "pardes: detached\n") catch {}; + libc._exit(0); + } + if (said.len > 0 and said[0] == 'r') { + var text: [700]u8 = undefined; + out.writeStreamingAll(io, std.fmt.bufPrint(&text, "pardes: --attach: {s}\n", .{said[1..]}) catch "pardes: --attach refused\n") catch {}; + libc._exit(1); + } + if (child) { + var status: c_int = 0; + while (libc.waitpid(session, &status, 0) < 0) { + if (libc.errno(-1) != .INTR) libc._exit(1); + } + const s: u32 = @bitCast(status); + if (libc.W.IFEXITED(s)) libc._exit(@intCast(libc.W.EXITSTATUS(s))); + if (libc.W.IFSIGNALED(s)) { + const sig = libc.W.TERMSIG(s); + const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; + posix.sigaction(sig, &default, null); + _ = libc.raise(sig); + } + libc._exit(1); + } + if (said.len > 0 and said[0] == 'x') libc._exit(std.fmt.parseInt(u8, said[1..], 10) catch 1); + out.writeStreamingAll(io, "pardes: the session ended without a word\n") catch {}; + libc._exit(1); +} + +/// The session's half of its stub: what `stubWait` reads. +pub var stub: c_int = -1; + +extern "c" fn procctl(idtype: c_int, id: i64, cmd: c_int, data: ?*anyopaque) c_int; + +/// A HUP when this process's parent dies (a forked session's stub, an +/// --attach client's ssh), or no longer. Linux keeps it per thread: set and +/// cleared on the main one. +pub fn hupOnStubDeath(on: bool) void { + var sig: c_int = if (on) @backingInt(posix.SIG.HUP) else 0; + switch (builtin.os.tag) { + .linux => _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_PDEATHSIG), @intCast(sig), 0, 0, 0), + // procctl(P_PID, 0, PROC_PDEATHSIG_CTL, &sig) + .freebsd => _ = procctl(0, 0, 11, &sig), + else => {}, + } +} + +/// Detached: the stub is told (and goes), and the pipe let go. Its end is +/// no hangup now (hupOnStubDeath). +pub fn tellStubDetached() void { + if (stub < 0) return; + hupOnStubDeath(false); + tellStub(stub, "d{s}", .{name()}); + stub = -1; +} + +/// The session's end, `code` its exit status: the stub is told (and goes). +pub fn tellStubExit(code: u8) void { + tellStub(stub, "x{d}", .{code}); + stub = -1; +} + +/// The stub on `fd` told how its terminal's session went, what stubWait +/// reads, and its pipe let go: `d<name>` detached (one of a session's +/// several terminals, views.zig), `x<code>` exited, `r<why>` refused (an +/// attach that came too late). +pub fn tellStub(fd: c_int, comptime fmt: []const u8, args: anytype) void { + if (fd < 0) return; + var buf: [256]u8 = undefined; + const said = std.fmt.bufPrint(&buf, fmt, args) catch fmt[0..1]; + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); +} + +/// `pardes` in a terminal: the session forked off as a process of its own, +/// in a session of its own (setsid), which is what lets it outlive the +/// terminal's job, and this process left as its stub (`stubWait`). Returns +/// in the session; null (nothing forked) when it cannot be done, and the +/// session then runs here, as before the daemon. +pub fn forkSession(conn: c_int) ?void { + var pipe: [2]c_int = undefined; + if (libc.pipe(&pipe) != 0) return null; + ninep_io.setCloexec(pipe[0]); + ninep_io.setCloexec(pipe[1]); + const parent = libc.getpid(); + const pid = libc.fork(); + if (pid < 0) { + _ = libc.close(pipe[0]); + _ = libc.close(pipe[1]); + return null; + } + if (pid == 0) { + _ = libc.close(pipe[0]); + _ = libc.setsid(); + // The stub's death, however it comes (a SIGKILL too), is a HUP: + // the terminal's end, which the session's signal thread takes and + // detaches on. One already dead hangs up at once. + hupOnStubDeath(true); + if (libc.getppid() != parent) _ = libc.raise(.HUP); + stub = pipe[1]; + // The listener and lock are the daemon's, which the stub starts. + startPending(false); + return {}; + } + _ = libc.close(pipe[1]); + _ = libc.close(conn); + // Off the session's way: it is drawing already, its hello queued. + startPending(true); + stubWait(pid, true, pipe[0]); +} + +// ---- the daemon ---- + +const Conn = struct { + fd: c_int = -1, + kind: ?Kind = null, + pid: libc.pid_t = 0, + detached: bool = false, + /// Its build's wire.semantics: a replica's must be the same. + semantics: u64 = 0, + /// `pardes --kill` asked its end: its shells go with it, not kept. + killed: bool = false, + name: [128]u8 = undefined, + name_len: usize = 0, + /// Its replica clients' pids, as it says them (`clients`); 0 not known. + clients: [max_clients]libc.pid_t = undefined, + nclients: u8 = 0, + + fn named(c: *const Conn) []const u8 { + return c.name[0..c.name_len]; + } +}; + +const Held = struct { + fd: c_int = -1, + pid: libc.pid_t = 0, + /// The conn whose session holds it; null: that session died with it. + owner: ?u8 = null, +}; + +fn drop(h: *Held) void { + _ = libc.close(h.fd); + h.* = .{}; +} + +/// A replica's connection until its hello is whole: read no further than +/// the hello, so what follows it is the session's to read. +const Replica = struct { + fd: c_int = -1, + buf: [wire.hello_max]u8 = undefined, + len: usize = 0, +}; + +const Daemon = struct { + conns: [max_conns]Conn = @splat(.{}), + held: [max_held]Held = @splat(.{}), + replicas: [max_replicas]Replica = @splat(.{}), + /// A session asked it to move onto the build installed since (`reexec`). + upgrade_asked: bool = false, + + fn idle(d: *const Daemon) bool { + for (d.conns) |c| if (c.fd >= 0) return false; + for (d.held) |h| if (h.fd >= 0) return false; + return true; + } + + fn hangUp(d: *Daemon, i: u8) void { + const c = &d.conns[i]; + const killed = c.killed; + _ = libc.close(c.fd); + c.* = .{}; + // Whatever it still held, it died holding: kept for an Adopt, unless + // it was killed on purpose, when its shells hang up with it. + for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) { + if (killed) drop(h) else h.owner = null; + }; + } + + /// `pardes --kill`: each session named (every one, for null) sent a + /// TERM and marked, its pids answered; the shells of none kept, for + /// all of them. + fn kill(d: *Daemon, i: u8, named: ?[]const u8) void { + var line: ["ok".len + max_conns * " -2147483648".len]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.writeAll("ok") catch unreachable; // a literal, its .len in line's + var n: usize = 0; + for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) { + if (named) |want| if (!std.mem.eql(u8, s.named(), want)) continue; + s.killed = true; + _ = libc.kill(s.pid, .TERM); + w.print(" {d}", .{s.pid}) catch unreachable; // one i32 a conn, max_conns in line's type + n += 1; + }; + if (named == null) { + for (&d.held) |*h| if (h.fd >= 0 and h.owner == null) drop(h); + } else if (n == 0) { + var why: [256]u8 = undefined; + return d.reply(i, std.fmt.bufPrint(&why, "no no session called '{s}'", .{named.?}) catch "no no such session", &.{}); + } + d.reply(i, w.buffered(), &.{}); + } + + /// `pardes --ps`: a line a session (pid, kind, state, name), a line + /// for each shell it holds after it, then the shells nobody holds. + /// ponytail: one message, so a registry past msg_max is cut short. + fn list(d: *Daemon, i: u8) void { + var line: [msg_max]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.print("daemon {d}\n", .{libc.getpid()}) catch unreachable; // a pid fits msg_max + for (&d.conns, 0..) |*s, k| if (s.fd >= 0 and s.kind != null) { + w.print("session {d} {t} {s} {s}\n", .{ s.pid, s.kind.?, if (s.detached) "detached" else "attached", s.named() }) catch break; + for (s.clients[0..s.nclients]) |pid| w.print("client {d}\n", .{pid}) catch break; + for (d.held) |h| if (h.fd >= 0 and h.owner == @as(u8, @intCast(k))) w.print("shell {d}\n", .{h.pid}) catch break; + }; + for (d.held) |h| if (h.fd >= 0 and h.owner == null) w.print("orphan {d}\n", .{h.pid}) catch break; + d.reply(i, w.buffered(), &.{}); + } + + fn reply(d: *Daemon, i: u8, words: []const u8, fds: []const c_int) void { + if (!send(d.conns[i].fd, words, fds)) d.hangUp(i); + } + + fn take(d: *Daemon, i: u8, got: Got) void { + var fds_used: usize = 0; + defer for (got.fds[fds_used..got.nfds]) |f| { + _ = libc.close(f); + }; + const c = &d.conns[i]; + var words = std.mem.tokenizeScalar(u8, got.words, ' '); + const Verb = enum { hello, state, clients, pty, close, quit, upgrade, list, kill, killall, adopt, attach }; + switch (std.meta.stringToEnum(Verb, words.next() orelse return) orelse return) { + .hello => { + const v = std.fmt.parseInt(u32, words.next() orelse "", 10) catch 0; + const k = std.meta.stringToEnum(Kind, words.next() orelse ""); + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; + const state = words.next() orelse ""; + const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0; + const rest = std.mem.trim(u8, words.rest(), " "); + if (v != version or k == null or pid <= 0) { + // Another build's: it runs without a daemon. + d.reply(i, "version " ++ std.fmt.comptimePrint("{d}", .{version}), &.{}); + return if (d.conns[i].fd >= 0) d.hangUp(i); + } + c.kind = k; + c.pid = pid; + c.detached = std.mem.eql(u8, state, "detached"); + c.semantics = semantics; + c.nclients = 0; + c.name_len = @min(rest.len, c.name.len); + @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); + return d.reply(i, "ok", &.{}); + }, + .state => c.detached = std.mem.eql(u8, words.next() orelse "", "detached"), + .clients => { + c.nclients = 0; + while (words.next()) |w| if (c.nclients < max_clients) { + c.clients[c.nclients] = std.fmt.parseInt(libc.pid_t, w, 10) catch 0; + c.nclients += 1; + }; + }, + .pty => { + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch return; + if (got.nfds < 1) return; + for (&d.held) |*h| if (h.fd < 0) { + h.* = .{ .fd = got.fds[0], .pid = pid, .owner = i }; + fds_used = 1; + return; + }; + }, + .close => { + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch return; + for (&d.held) |*h| if (h.fd >= 0 and h.pid == pid and h.owner == i) drop(h); + }, + .quit => for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) drop(h), + .upgrade => d.upgrade_asked = true, + .list => d.list(i), + .kill => d.kill(i, std.mem.trim(u8, words.rest(), " ")), + .killall => d.kill(i, null), + .adopt => { + var line: [msg_max]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.writeAll("adopted") catch unreachable; // a literal fits msg_max + var fds: [max_fds]c_int = undefined; + var given: [max_fds]*Held = undefined; + var n: usize = 0; + for (&d.held) |*h| if (h.fd >= 0 and h.owner == null and n < max_fds) { + w.print(" {d}", .{h.pid}) catch break; + fds[n] = h.fd; + given[n] = h; + n += 1; + }; + if (!send(c.fd, w.buffered(), fds[0..n])) return d.hangUp(i); + for (given[0..n]) |h| h.owner = i; + }, + .attach => { + const k = std.meta.stringToEnum(Kind, words.next() orelse "") orelse return d.reply(i, "no bad attach", &.{}); + const wanted_name = std.mem.trim(u8, words.rest(), " "); + var why: [512]u8 = undefined; + // "other <name>": the client joins it through the replica socket. + const target = d.find(k, wanted_name, &why) orelse return d.reply(i, std.mem.sliceTo(&why, 0), &.{}); + const t = &d.conns[target]; + if (!send(t.fd, "attach", got.fds[0..got.nfds])) { + d.hangUp(target); + return d.reply(i, "no that session does not answer", &.{}); + } + t.detached = false; + var line: [32]u8 = undefined; + return d.reply(i, std.fmt.bufPrint(&line, "ok {d}", .{t.pid}) catch unreachable, &.{}); // a pid fits 32 + }, + } + } + + /// The detached session of kind `k` called `wanted_name`, or the one + /// there is when it is empty; else null, and why not in `why` + /// (0-terminated): "other <its name>" for one to join as a replica + /// client (of the other kind, or attached already: a session shows one + /// frontend of its own). + fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) ?u8 { + @memset(why, 0); + const other: []const u8 = switch (k) { + .tty => "a window: attach it with `pardes-gui --attach", + .gui => "a terminal session: attach it with `pardes --attach", + }; + if (wanted_name.len != 0) { + for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind != null and std.mem.eql(u8, s.named(), wanted_name)) { + if (s.kind.? != k or !s.detached) { + _ = std.fmt.bufPrint(why, "other {s}", .{wanted_name}) catch {}; + return null; + } + return @as(u8, @intCast(i)); + }; + _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {}; + return null; + } + var found: ?u8 = null; + var count: usize = 0; + var others: usize = 0; + var w: std.Io.Writer = .fixed(why[0 .. why.len - 1]); + for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.detached and s.kind != null) { + if (s.kind.? != k) { + others += 1; + continue; + } + count += 1; + found = @intCast(i); + }; + if (count == 1) return found.?; + // None detached: the one session there is, joined as a client. + if (count == 0) { + for (&d.conns, 0..) |*s, i| if (s.fd >= 0 and s.kind == k) { + count += 1; + found = @intCast(i); + }; + if (count == 1) { + _ = std.fmt.bufPrint(why, "other {s}", .{d.conns[found.?].named()}) catch unreachable; // a [128]u8 field's name fits 512 + return null; + } + count = 0; + // None of this kind at all: the one session there is, the other kind's. + var only: ?*Conn = null; + var sessions: usize = 0; + for (&d.conns) |*s| if (s.fd >= 0 and s.kind != null) { + sessions += 1; + only = s; + }; + if (found == null and sessions == 1) { + _ = std.fmt.bufPrint(why, "other {s}", .{only.?.named()}) catch unreachable; // a [128]u8 field's name fits 512 + return null; + } + } + if (count == 0 and others == 0) { + w.writeAll("no no detached session is running") catch unreachable; // a literal fits 511 + return null; + } + if (count == 0) { + w.print("no the detached session{s} running {s} {s}=<name>`", .{ if (others == 1) " is" else "s are", if (others == 1) "is" else "are each", other }) catch {}; // cut short, still 0-terminated + return null; + } + w.print("no {d} detached sessions are running; say which with --attach=<name>:", .{count}) catch unreachable; // a usize fits 511 + for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) { + w.print(" {s}", .{s.named()}) catch {}; + }; + return null; + } + + /// More of a replica's hello; once it is whole, the connection refused + /// in words or handed to its session. + fn hear(d: *Daemon, r: *Replica) void { + const want = if (r.len < wire.header_len) wire.header_len else wire.header_len + @as(usize, std.mem.readInt(u32, r.buf[1..5], .little)); + if (want > r.buf.len) return refuse(r, "the first message is not a hello"); + const n = libc.read(r.fd, r.buf[r.len..want].ptr, want - r.len); + if (n < 0 and libc.errno(n) == .INTR) return; + if (n <= 0) { + _ = libc.close(r.fd); + r.* = .{}; + return; + } + r.len += @intCast(n); + if (r.len < wire.header_len or r.len < wire.header_len + std.mem.readInt(u32, r.buf[1..5], .little)) return; + const f = (wire.framed(r.buf[0..r.len]) catch null) orelse return refuse(r, "the first message is not a hello"); + if (f.tag != @backingInt(wire.ClientTag.hello)) return refuse(r, "the first message is not a hello"); + var why: [512]u8 = undefined; + const v = wire.helloVersion(f.payload) catch 0; + if (v != wire.version) return refuse(r, std.fmt.bufPrint(&why, "this client speaks replica protocol {d}, and this daemon {d}: run the same pardes at both ends", .{ v, wire.version }) catch unreachable); // two numbers fit 512 + const h = (wire.decodeClient(f.tag, f.payload) catch return refuse(r, "a malformed hello")).hello; + const target = for (&d.conns, 0..) |*c, i| { + if (c.fd >= 0 and c.kind != null and std.mem.eql(u8, c.named(), h.session)) break i; + } else return refuse(r, std.fmt.bufPrint(&why, "no session called '{s}'", .{h.session}) catch "no such session"); + const t = &d.conns[target]; + if (t.semantics != h.semantics) return refuse(r, std.fmt.bufPrint(&why, "session '{s}' runs another build of pardes (semantics {x:0>16}, this client's {x:0>16}): a replica needs the same build at both ends, as `pardes --version` shows", .{ h.session, t.semantics, h.semantics }) catch "another build"); + var words: [16]u8 = undefined; + const note = if (h.view) |k| std.fmt.bufPrint(&words, "replica {d}", .{k}) catch unreachable else "replica"; + if (!send(t.fd, note, &.{r.fd})) { + d.hangUp(@intCast(target)); + return refuse(r, "that session does not answer"); + } + log.info("a replica handed to '{s}'", .{h.session}); + _ = libc.close(r.fd); + r.* = .{}; + } + + fn refuse(r: *Replica, why: []const u8) void { + refuseReplica(r.fd, why); + r.* = .{}; + } + + fn acceptReplica(d: *Daemon, listener: c_int) void { + const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC); + if (fd < 0) return; + for (&d.replicas) |*r| if (r.fd < 0) { + r.* = .{ .fd = fd }; + return; + }; + _ = libc.close(fd); + } + + /// Upgrade: this daemon exec'd as the pardes now at the path it was + /// started from, on the same listeners and lock, every session's link + /// and every master kept open, its registry on the new command line + /// (`restore`). A replica whose hello is still on its way is let go: it + /// dials again. Returns when it cannot be done, as it was. + fn reexec(d: *Daemon, replicas: c_int) void { + const path = upgrade.exe() orelse return; + var why: [700]u8 = undefined; + switch (upgrade.check(path, &why)) { + .no => |w| return log.warn("{s}", .{w}), + .ok => {}, + } + var text: [flag_room]u8 = undefined; + var w: std.Io.Writer = .fixed(&text); + w.print("{s}replicas {d}\n", .{ upgrade.flag, replicas }) catch return; + for (&d.conns, 0..) |*c, i| if (c.fd >= 0) { + const k: []const u8 = if (c.kind) |k| @tagName(k) else "-"; + w.print("c {d} {d} {s} {d} {d} {x} {s}\n", .{ i, c.fd, k, c.pid, @intFromBool(c.detached), c.semantics, c.named() }) catch return; + }; + for (&d.held) |*h| if (h.fd >= 0) { + w.print("h {d} {d} {d}\n", .{ h.fd, h.pid, h.owner orelse 255 }) catch return; + }; + w.writeByte(0) catch return; + for (&d.replicas) |*r| if (r.fd >= 0) { + _ = libc.close(r.fd); + r.* = .{}; + }; + const keep = struct { + fn all(dd: *Daemon, rep: c_int, on: bool) void { + const v: c_int = if (on) 0 else 1; + for ([_]c_int{ 3, 4, rep }) |fd| if (fd >= 0) { + _ = libc.fcntl(fd, libc.F.SETFD, v); + }; + for (&dd.conns) |*c| if (c.fd >= 0) { + _ = libc.fcntl(c.fd, libc.F.SETFD, v); + }; + for (&dd.held) |*h| if (h.fd >= 0) { + _ = libc.fcntl(h.fd, libc.F.SETFD, v); + }; + } + }.all; + const argv = [_:null]?[*:0]const u8{ path, "--daemon", @ptrCast(&text), null }; + keep(d, replicas, true); + _ = libc.execve(path, &argv, @ptrCast(libc.environ)); + keep(d, replicas, false); + log.warn("upgrade: {s} would not start", .{path}); + } + + /// The registry an upgraded daemon was exec'd with (`reexec`); the + /// replicas' listener, its fd, or -1. + fn restore(d: *Daemon, text: []const u8) c_int { + var replicas: c_int = -1; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + var words = std.mem.tokenizeScalar(u8, line, ' '); + const what = words.next() orelse continue; + switch (std.meta.stringToEnum(enum { replicas, c, h }, what) orelse continue) { + .replicas => { + replicas = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch -1; + if (replicas >= 0) ninep_io.setCloexec(replicas); + }, + .c => { + const i = std.fmt.parseInt(u8, words.next() orelse "", 10) catch continue; + const fd = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch continue; + if (i >= max_conns) continue; + const k = std.meta.stringToEnum(Kind, words.next() orelse ""); + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; + const detached = std.mem.eql(u8, words.next() orelse "", "1"); + const semantics = std.fmt.parseInt(u64, words.next() orelse "", 16) catch 0; + const rest = std.mem.trim(u8, words.rest(), " "); + ninep_io.setCloexec(fd); + const c = &d.conns[i]; + c.* = .{ .fd = fd, .kind = k, .pid = pid, .detached = detached, .semantics = semantics }; + c.nclients = 0; + c.name_len = @min(rest.len, c.name.len); + @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); + }, + .h => { + const fd = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch continue; + const pid = std.fmt.parseInt(libc.pid_t, words.next() orelse "", 10) catch 0; + const owner = std.fmt.parseInt(u8, words.next() orelse "", 10) catch 255; + ninep_io.setCloexec(fd); + for (&d.held) |*h| if (h.fd < 0) { + h.* = .{ .fd = fd, .pid = pid, .owner = if (owner < max_conns) owner else null }; + break; + }; + }, + } + } + return replicas; + } + + fn accept(d: *Daemon, listener: c_int) void { + const fd = libc.accept4(listener, null, null, libc.SOCK.CLOEXEC); + if (fd < 0) return; + for (&d.conns) |*c| if (c.fd < 0) { + c.* = .{ .fd = fd }; + return; + }; + _ = libc.close(fd); + } +}; + +/// The replicas' stream socket, bound and listening; -1 when it cannot be +/// (a runtime directory too long for a socket's path: 104 bytes on FreeBSD). +/// Ours to replace: the daemon's lock is held. +fn listenReplicas() c_int { + var sock_buf: [sun_path_len:0]u8 = undefined; + const sock = place(&sock_buf, "pardes-replica.sock") orelse return -1; + _ = libc.unlink(sock); + const fd = libc.socket(libc.AF.UNIX, libc.SOCK.STREAM | libc.SOCK.CLOEXEC, 0); + if (fd < 0) return -1; + const addr = address(sock); + if (libc.bind(fd, @ptrCast(&addr), @sizeOf(libc.sockaddr.un)) == 0 and libc.chmod(sock, 0o600) == 0 and libc.listen(fd, max_replicas) == 0) return fd; + _ = libc.close(fd); + return -1; +} + +/// Room for an upgrade's registry on a command line (`reexec`): every +/// connection and master, each a line. +const flag_room = 64 * 1024; + +/// `pardes --daemon`: what `spawn` started, on the listener (fd 3) and the +/// lock (fd 4), or (`state`) an upgrade of one, its registry. Returns only +/// to exit, idle. +pub fn serve(state: ?[]const u8) noreturn { + const listener: c_int = 3; + ninep_io.setCloexec(3); + ninep_io.setCloexec(4); + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + for ([_]posix.SIG{ .PIPE, .HUP, .INT }) |sig| posix.sigaction(sig, &ignore, null); + upgrade.locate(); + var d: Daemon = .{}; + const given = if (state) |text| d.restore(text) else -1; + const replicas = if (given >= 0) given else listenReplicas(); + // Every slot in its own place, an empty one's fd -1: poll passes over + // a negative fd. + var fds: [2 + max_conns + max_replicas + max_held]libc.pollfd = undefined; + const conns = fds[2..][0..max_conns]; + const held = fds[2 + max_conns ..][0..max_held]; + const reps = fds[2 + max_conns + max_held ..][0..max_replicas]; + var buf: [msg_max]u8 = undefined; + while (true) { + fds[0] = .{ .fd = listener, .events = libc.POLL.IN, .revents = 0 }; + fds[1] = .{ .fd = replicas, .events = libc.POLL.IN, .revents = 0 }; + for (conns, &d.conns) |*pfd, *c| pfd.* = .{ .fd = c.fd, .events = libc.POLL.IN, .revents = 0 }; + for (reps, &d.replicas) |*pfd, *r| pfd.* = .{ .fd = r.fd, .events = libc.POLL.IN, .revents = 0 }; + // No events asked of a master: its hangup (every slave closed, the + // shell and all it ran gone) is reported anyway, and its output is + // the session's to read, never this one's. + for (held, &d.held) |*pfd, *h| pfd.* = .{ .fd = h.fd, .events = 0, .revents = 0 }; + const idle = d.idle(); + const ready = libc.poll(&fds, fds.len, if (idle) linger_ms else -1); + if (ready < 0) { + if (libc.errno(ready) == .INTR) continue; + break; + } + if (ready == 0) { + if (!idle) continue; + // Idle for the whole linger: one last look for a connection + // just made, then the socket goes, then this process (and its + // lock with it). + if (readable(listener, 0)) { + d.accept(listener); + continue; + } + break; + } + if (fds[0].revents & libc.POLL.IN != 0) d.accept(listener); + if (fds[1].revents & libc.POLL.IN != 0) d.acceptReplica(replicas); + // A slot an earlier handler emptied or filled again is passed over. + for (reps, &d.replicas) |pfd, *r| if (pfd.revents != 0 and r.fd == pfd.fd) d.hear(r); + for (conns, 0..) |pfd, i| { + if (pfd.revents == 0 or d.conns[i].fd != pfd.fd) continue; + const got = recv(pfd.fd, &buf) orelse { + d.hangUp(@intCast(i)); + continue; + }; + d.take(@intCast(i), got); + } + for (held, &d.held) |pfd, *h| if (pfd.revents != 0 and h.fd == pfd.fd) drop(h); + if (d.upgrade_asked) { + d.upgrade_asked = false; + d.reexec(replicas); + } + } + var sock_buf: [sun_path_len:0]u8 = undefined; + _ = libc.close(listener); + if (place(&sock_buf, "pardes-daemon.sock")) |sock| _ = libc.unlink(sock); + if (replicas >= 0) { + if (place(&sock_buf, "pardes-replica.sock")) |sock| _ = libc.unlink(sock); + } + libc._exit(0); +} + +test "a message carries its words and its fds, and the peer's end is null" { + if (comptime !supported) return error.SkipZigTest; + var pair: [2]c_int = undefined; + try std.testing.expectEqual(@as(c_int, 0), libc.socketpair(libc.AF.UNIX, libc.SOCK.SEQPACKET | libc.SOCK.CLOEXEC, 0, &pair)); + defer _ = libc.close(pair[0]); + var pipe: [2]c_int = undefined; + try std.testing.expectEqual(@as(c_int, 0), libc.pipe(&pipe)); + defer _ = libc.close(pipe[0]); + try std.testing.expect(send(pair[1], "pty 42", &.{pipe[1]})); + _ = libc.close(pipe[1]); + var buf: [64]u8 = undefined; + const got = recv(pair[0], &buf).?; + try std.testing.expectEqualStrings("pty 42", got.words); + try std.testing.expectEqual(@as(usize, 1), got.nfds); + // The fd that came is the pipe's write end: what goes in comes out. + try std.testing.expectEqual(@as(isize, 1), libc.write(got.fds[0], "z", 1)); + _ = libc.close(got.fds[0]); + var one: [1]u8 = undefined; + try std.testing.expectEqual(@as(isize, 1), libc.read(pipe[0], &one, 1)); + _ = libc.close(pair[1]); + try std.testing.expect(recv(pair[0], &buf) == null); +} + +test "an attach by a name longer than any session's is refused in words, never an empty reason" { + var d: Daemon = .{}; + var why: [512]u8 = undefined; + const long: []const u8 = &@as([600]u8, @splat('n')); + try std.testing.expect(d.find(.tty, long, &why) == null); + const said = std.mem.sliceTo(&why, 0); + try std.testing.expect(std.mem.startsWith(u8, said, "no ")); + try std.testing.expect(said.len > "no ".len); +} diff --git a/runtime/macos.zig b/runtime/macos.zig new file mode 100644 index 00000000..f968597b --- /dev/null +++ b/runtime/macos.zig @@ -0,0 +1,2669 @@ +const filesystem = @import("core").filesystem; +const ninep_io = @import("runtime").ninep_io; + +const std = @import("std"); +const builtin = @import("builtin"); +const posix = std.posix; +const libc = std.c; +const pardes = @import("core"); +const dump = @import("core").dump; +const mouse = @import("core").mouse; +const colors = @import("core").colors; +const look = @import("core").look; +const message = pardes.Messages.Message; +const layout = @import("core").layout; +const file_watch = @import("core").file_watch; +const host_io = @import("core").host_io; +const fonts = @import("core").fonts; // the shared fallback preference order +const tracy = @import("core").tracy; // no-op unless -Dtracy names a checkout +const selection_pipe = @import("core").selection_pipe; // start, Response and Tasks +const crash = @import("runtime").crash; + +pub const panic = std.debug.FullPanic(struct { + fn call(msg: []const u8, ret_addr: ?usize) noreturn { + crash.record(msg); + std.debug.defaultPanic(msg, ret_addr); + } +}.call); + +extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + +extern "c" fn pardes_host_watch_file( + pane: u8, + generation: u32, + path: ?[*]const u8, + path_len: usize, +) void; + +fn hostWatchFile(pane: u8, generation: u32, path: ?[*]const u8, path_len: usize) void { + if (comptime builtin.is_test) return; + pardes_host_watch_file(pane, generation, path, path_len); +} + +const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); + +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; + +fn logFn( + comptime level: std.log.Level, + comptime scope: @EnumLiteral(), + comptime format: []const u8, + args: anytype, +) void { + if (scope != .macos and std.c.getenv("PARDES_LOG") == null) return; + std.log.defaultLog(level, scope, format, args); +} + +const log = std.log.scoped(.macos); + +pub const Cell = extern struct { + text: [8]u8, + fg: u32, + bg: u32, + attrs: u16, + len: u8, + flags: u8, +}; + +pub const Scene = extern struct { + flags: u32 = 0, + time_seconds: f32 = 0, + frame: u32 = 0, +}; + +/// pardes.h's pane transition, which the core no longer makes (its motion +/// is the frontends' since animation.zig went): the list stays, empty. +pub const PanelBox = extern struct { x: f32, y: f32, w: f32, h: f32 }; +pub const PanelTrack = extern struct { serial: u32, pane: u8, phase: u8, effect: u8, motion: u8, frame: u16, frame_count: u16, from: PanelBox, to: PanelBox, launch: f32 }; + +pub const Image = extern struct { + serial: u32, + page: u32, + revision: u32, + cell_x: u16, + cell_y: u16, + cell_w: u16, + cell_h: u16, + dst_x: u32, + dst_y: u32, + dst_w: u32, + dst_h: u32, + src_x: u32, + src_y: u32, + src_w: u32, + src_h: u32, + offset_y: f32, + iw: u32, + ih: u32, + rgba: [*]const u8, + paper_bg: u32, +}; + +pub const Runtime = extern struct { + userdata: ?*anyopaque = null, + wakeup: ?*const fn (?*anyopaque) callconv(.c) void = null, + set_clipboard: ?*const fn (?*anyopaque, [*]const u8, usize) callconv(.c) void = null, + read_clipboard: ?*const fn (?*anyopaque) callconv(.c) void = null, +}; + +const color_default: u32 = 0x01000000; +const color_indexed: u32 = 0x02000000; +const cell_flag_default: u8 = 1; +const cell_flag_tagline: u8 = 2; +const cell_flag_hover: u8 = 4; + +const max_tick_catch_up_ns: u64 = 4 * pardes.frame_ns; +const theme_watch_pane: u8 = @intCast(pardes.MAX_PANES); +const watch_slot_count = pardes.MAX_PANES + 1; + +const Pty = struct { + file: std.Io.File, + pid: posix.pid_t, + gen: u32, + reader: std.Io.Future(void), + /// A command pane's child, watched to its exit (host_io.watchExit); + /// the pty stays open until both its end of file and its exit. + cmd: host_io.CommandWatch = .{}, +}; + +/// A watched child exited: wake the host, which takes it (`takeExits`). +/// Called on a watcher thread holding host_io's exit lock, which +/// pardes_deinit takes to clear the wake: safe only because the runtime's +/// wakeup never waits for the main thread (AppDelegate's is a +/// DispatchQueue.main.async); one that did would deadlock the quit. +fn wakeForExit(ctx: ?*anyopaque) void { + const st: *State = @ptrCast(@alignCast(ctx orelse return)); + wake(st); +} + +/// The command panes' exits, told once their output is in (host_io). +fn takeExits(st: *State) void { + host_io.takeExits(st.core, &st.ptys, st, closeWatched); +} + +fn closeWatched(st: *State, id: usize) void { + reap(st, @intCast(id)); +} + +const WatchedFile = struct { + path: []u8, + serial: u32, + generation_on_disk: file_watch.Generation, + generation: u32, + retries_left: u8 = 1, +}; + +const FileWatches = struct { + entries: [watch_slot_count]?WatchedFile = @splat(null), + generations: [watch_slot_count]u32 = @splat(0), + dirty: [watch_slot_count]bool = @splat(false), + + fn nextGeneration(watches: *FileWatches, pane: u8) u32 { + watches.generations[pane] +%= 1; + if (watches.generations[pane] == 0) watches.generations[pane] = 1; + return watches.generations[pane]; + } + + fn replace( + watches: *FileWatches, + gpa: std.mem.Allocator, + pane: u8, + path: []const u8, + serial: u32, + generation_on_disk: file_watch.Generation, + ) !u32 { + const owned = try gpa.dupe(u8, path); + if (watches.entries[pane]) |old| gpa.free(old.path); + const generation = watches.nextGeneration(pane); + watches.entries[pane] = .{ + .path = owned, + .serial = serial, + .generation_on_disk = generation_on_disk, + .generation = generation, + }; + watches.dirty[pane] = false; + return generation; + } + + fn stop(watches: *FileWatches, gpa: std.mem.Allocator, pane: u8) u32 { + if (watches.entries[pane]) |old| gpa.free(old.path); + watches.entries[pane] = null; + watches.dirty[pane] = false; + return watches.nextGeneration(pane); + } + + fn notify(watches: *FileWatches, pane: u8, generation: u32) bool { + const watched = if (watches.entries[pane]) |*entry| entry else return false; + if (watched.generation != generation) return false; + watched.retries_left = 1; + const first = !watches.dirty[pane]; + watches.dirty[pane] = true; + return first; + } + + fn retry(watches: *FileWatches, pane: u8, generation: u32) bool { + const watched = if (watches.entries[pane]) |*entry| entry else return false; + if (watched.generation != generation or watched.retries_left == 0) return false; + watched.retries_left -= 1; + const first = !watches.dirty[pane]; + watches.dirty[pane] = true; + return first; + } + + fn takeDirty(watches: *FileWatches, pane: u8) bool { + const value = watches.dirty[pane]; + watches.dirty[pane] = false; + return value; + } + + fn restampText(watches: *FileWatches, pane: u8, path: []const u8, hash: u64) void { + const watched = if (watches.entries[pane]) |*entry| entry else return; + if (!std.mem.eql(u8, watched.path, path)) return; + switch (watched.generation_on_disk) { + .text => watched.generation_on_disk = .{ .text = hash }, + .kind => {}, + } + } + + fn deinit(watches: *FileWatches, gpa: std.mem.Allocator) void { + for (&watches.entries) |*entry| { + if (entry.*) |old| gpa.free(old.path); + entry.* = null; + } + watches.dirty = @splat(false); + } +}; + +const file_watcher_swift = @embedFile("macos/Sources/FileWatcher.swift"); + +const Inbox = host_io.Inbox; +const Msg = Inbox.Msg; + +const State = struct { + ninep: ?*ninep_io.Listener = null, + gpa: std.mem.Allocator, + threaded: *std.Io.Threaded, + io: std.Io, + core: *pardes.Pardes, + started: bool = false, + runtime: Runtime, + tag_cells: [pardes.MAX_TAG_LAYERS][]Cell = @splat(&.{}), + layer_cells: [pardes.MAX_PANES][]Cell = @splat(&.{}), + cells: []Cell = &.{}, + frame_len: usize = 0, + frame_cols: u16 = 0, + frame_rows: u16 = 0, + images: []Image = &.{}, + images_len: usize = 0, + ptys: [pardes.MAX_PANES]?Pty = @splat(null), + inbox: Inbox = undefined, + /// A wakeup is on its way to the runtime: the next ones are not sent. + wake_pending: std.atomic.Value(bool) = .init(false), + pipe_tasks: selection_pipe.Tasks = .{}, + file_watches: FileWatches = .{}, + gens: [pardes.MAX_PANES]u32 = @splat(0), + scroll_lag: f32 = 0, + scroll_lag_x: f32 = 0, + scroll_velocity: f32 = 0, + scroll_velocity_x: f32 = 0, + scroll_last_ns: i128 = 0, + /// Where the gesture turned. A coast keeps delivering THERE rather than + /// wherever the pointer has drifted to since — the same rule the SDL + /// shell keeps in scroll_col/scroll_row. + scroll_col: u16 = 0, + scroll_row: u16 = 0, + scroll_coasting: bool = false, + rotate_lag: f32 = 0, + rotate_velocity: f32 = 0, + rotate_last_ns: i128 = 0, + rotate_coasting: bool = false, + last_tick_ns: u64 = 0, + tick_bank_ns: u64 = 0, + cwd_stale: [pardes.MAX_PANES]bool = @splat(false), + config_arena: std.heap.ArenaAllocator, + prompt_rcs: host_io.Shell.PromptFiles, +}; + +var state: ?State = null; + +export fn pardes_init(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) c_int { + if (state != null) return 1; // already up; deinit first + initCore(runtime, cols_arg, rows_arg) catch |err| { + log.err("init failed: {t}", .{err}); + return 2; + }; + return 0; +} + +/// The shell's gpa in a Debug build, as std.start's is for the others. +var debug_gpa: std.heap.DebugAllocator(.{}) = .init; + +fn initCore(runtime: ?*const Runtime, cols_arg: u16, rows_arg: u16) !void { + // The allocator every other shell gets from std.start: a DebugAllocator + // in Debug, libc's malloc otherwise. libc's measured at least as fast as + // std.heap.smp_allocator everywhere and faster on MuPDF's page-sized + // rasters, so this shell no longer differs. + const gpa = if (builtin.mode == .debug) debug_gpa.allocator() else std.heap.c_allocator; + + const allocs = pardes.memory.init(gpa); + errdefer pardes.memory.deinit(); + + const threaded = try gpa.create(std.Io.Threaded); + errdefer gpa.destroy(threaded); + threaded.* = .init(gpa, .{}); + errdefer threaded.deinit(); + const io = threaded.io(); + + var config_arena: std.heap.ArenaAllocator = .init(gpa); + errdefer config_arena.deinit(); + + var opts: pardes.Options = .{ + .tty_only = true, + // The app is a real bare-tty startup, like the terminal and SDL + // shells, so it names the same layout rather than the bare shell a + // core booted for a test gets. + .boot = .tty, + .frame_allocator = allocs.frame, + .image_allocator = allocs.image, + + .tree_sitter_allocator = allocs.tree_sitter, + }; + if (captureEnv(config_arena.allocator())) |*env| { + const found = pardes.config.User.load(io, config_arena.allocator(), env); + opts.startup_config = found.bytes; + opts.startup_config_path = found.path; + opts.config_dir = found.dir; + if (found.dir) |d| crash.setDir(d); + } + + pardes.Term.start(allocs.image); + pardes.Kind.heap = allocs.addon; + // Its addons are compiled in (no loader runs here): image and PDF panes. + opts.addons = pardes.Addon.scan(); + errdefer pardes.Term.stop(); + pardes.syntax.start(allocs.tree_sitter); + errdefer pardes.syntax.stop(); + + const core = try pardes.Pardes.init(allocs.pardes, opts); + errdefer core.deinit(); + // The workspace tag row is the macOS menu bar's business here (see + // docs/macos.md): the build option says whether this shell keeps the + // acme topbar or hands its commands to native chrome. The e2e harness + // opts back in with PARDES_WORKSPACE_TAG=1 — its scripts speak to a + // grid that has the row. Applied before the first resize so the layout + // has never seen it the other way. + core.settings.workspace_tag = if (std.c.getenv("PARDES_WORKSPACE_TAG")) |v| + std.mem.eql(u8, std.mem.span(v), "1") + else + @import("pardes_config").workspace_tag; + core.view().frontend.native_images = true; + + var prompt_rcs = host_io.Shell.prepare(); + errdefer prompt_rcs.deinit(); + + state = .{ + .gpa = gpa, + .threaded = threaded, + .io = io, + .core = core, + .config_arena = config_arena, + .prompt_rcs = prompt_rcs, + .runtime = if (runtime) |r| r.* else .{}, + }; + const st = &state.?; + st.inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io, .wake_fn = wakeHost, .wake_ctx = st }; + st.ninep = ninep_io.start(io, gpa, core); + core.host = hostFor(st); + + const cols = @max(1, cols_arg); + const rows = @max(1, rows_arg); + core.update(.{ .resize = .{ .cols = cols, .rows = rows } }); + + while (core.nextEffect()) |effect| core.perform(effect); + st.started = true; + if (st.ninep) |listener| listener.watch(st, wakeNinep) catch |err| core.reportError(0, "9p wake", err); + for (&st.ptys, 0..) |*slot, id| if (slot.*) |*pt| startReader(st, pt, @intCast(id)); + + pardes.lsp.setStatusSink(&st.inbox, Inbox.lspStatus); + host_io.setExitWake(st, wakeForExit); + // From here the core is touched only inside the entry points above, + // each of which takes the turn for its own duration; between them the + // 9P connections have it. + pardes.turn.rest(); +} + +fn wakeNinep(ctx: ?*anyopaque) void { + const st: *State = @ptrCast(@alignCast(ctx orelse return)); + wake(st); +} + +export fn pardes_deinit() void { + pardes.turn.wake(); + const st = &(state orelse return); + if (st.ninep) |listener| { + listener.deinit(st.gpa); + st.ninep = null; + } + pardes.lsp.setStatusSink(null, null); + host_io.setExitWake(null, null); + if (st.inbox.lsp_task) |*t| { + t.future.cancel(st.io); + st.inbox.lsp_task = null; + } + st.pipe_tasks.cancelAll(st.io); + for (0..pardes.MAX_PANES) |pane| if (st.file_watches.entries[pane] != null) { + const id: u8 = @intCast(pane); + const generation = st.file_watches.stop(st.gpa, id); + hostWatchFile(id, generation, null, 0); + }; + if (st.file_watches.entries[theme_watch_pane] != null) { + const generation = st.file_watches.stop(st.gpa, theme_watch_pane); + hostWatchFile(theme_watch_pane, generation, null, 0); + } + for (0..pardes.MAX_PANES) |pane| reap(st, @intCast(pane)); + st.inbox.close(); + st.file_watches.deinit(st.gpa); + if (st.cells.len > 0) st.gpa.free(st.cells); + for (st.layer_cells) |cells| st.gpa.free(cells); + for (st.tag_cells) |cells| st.gpa.free(cells); + if (st.images.len > 0) st.gpa.free(st.images); + st.core.deinit(); + pardes.Term.stop(); + pardes.syntax.stop(); + st.config_arena.deinit(); + st.prompt_rcs.deinit(); + st.threaded.deinit(); + st.gpa.destroy(st.threaded); + pardes.memory.deinit(); + // Leaks are logged and do not fail, as std.start treats the others'. + if (builtin.mode == .debug) { + _ = debug_gpa.deinit(); + debug_gpa = .init; + } + state = null; +} + +export fn pardes_should_quit() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return true); + return st.core.quit; +} + +const TickSpend = struct { elapsed_ns: u64, steps: u32, bank_ns: u64 }; + +fn spendTickTime(previous_ns: u64, now_ns: u64, bank_ns: u64) TickSpend { + const measured = if (previous_ns == 0 or now_ns <= previous_ns) + pardes.frame_ns + else + now_ns - previous_ns; + const elapsed = @min(measured, max_tick_catch_up_ns); + var bank = bank_ns +| elapsed; + var steps: u32 = 0; + while (bank >= pardes.frame_ns) : (steps += 1) bank -= pardes.frame_ns; + return .{ .elapsed_ns = elapsed, .steps = steps, .bank_ns = bank }; +} + +export fn pardes_animating() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + return st.core.animationActive() or st.rotate_coasting or st.scroll_coasting; +} + +export fn pardes_theme_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const th = if (state) |*st| st.core.theme() else &pardes.themes[0]; + const bg = th.bg orelse return color_default; + return @as(u32, bg[0]) << 16 | @as(u32, bg[1]) << 8 | bg[2]; +} + +/// The percentage the shell must paint window backgrounds at, read once per +/// pump beside pardes_theme_bg(). +/// +/// Reading it also ACKNOWLEDGES whatever `WindowOpacity` asked for. The SDL +/// shell has to answer that request because an SDL surface can arrive without +/// an alpha channel and the core must not claim a value the compositor +/// refused; an AppKit window always composites per pixel, so there is nothing +/// here to refuse and no rollback for the core to perform. +/// +/// The theme's own decision stays separate: a theme with no background of its +/// own (pardes_theme_bg == PARDES_COLOR_DEFAULT) drops the ground entirely, +/// whatever percentage is set here. +export fn pardes_window_opacity() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 100); + st.core.settings.window_opacity_pending = false; + return st.core.settings.window_opacity; +} + +fn taglineFontPercent(core: ?*const pardes.Pardes) u8 { + return if (core) |p| p.settings.font.tagline_percent else pardes.config.gui_tagline_font_percent; +} + +export fn pardes_gui_tagline_font_percent() u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); + return taglineFontPercent(if (state) |*st| st.core else null); +} + +export fn pardes_tagline_band_offset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + return pardes.Layer.taglineBandOffset(row, canvas_h, cell_h, tagline_h); +} + +export fn pardes_topbar_pane_border_px(cell_h: u32, tagline_h: u32) u32 { + return pardes.Layer.topbarPaneBorderPixels(cell_h, tagline_h); +} + +export fn pardes_tagline_origin_col(col: u16, row: u16) f32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return @floatFromInt(col)); + return pardes.taglineOriginCol(st.core, col, row); +} + +export fn pardes_grid_col_at(x: f32, row: u16, body_w: f32, tagline_w: f32) u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return pardes.gridColAt(null, x, row, body_w, tagline_w)); + return pardes.gridColAt(st.core, x, row, body_w, tagline_w); +} + +export fn pardes_topbar_pane_border_rgb() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const rgb = pardes.config.gui_topbar_pane_border_rgb orelse fromTheme: { + const st = state orelse return color_default; + break :fromTheme st.core.chromeTheme().border; + }; + return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; +} + +export fn pardes_tag_active_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = state orelse return color_default; + const rgb = st.core.chromeTheme().tag_active_bg; + return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; +} +export fn pardes_tagline_bg() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = state orelse return color_default; + const rgb = st.core.chromeTheme().tag_bg; + return @as(u32, rgb[0]) << 16 | @as(u32, rgb[1]) << 8 | rgb[2]; +} + +export fn pardes_fallback_font_count() u32 { + return fonts.fallback_names.len; +} + +export fn pardes_fallback_font_name(index: u32, len: *u32) ?[*]const u8 { + if (index >= fonts.fallback_names.len) { + len.* = 0; + return null; + } + const name = fonts.fallback_names[index]; + len.* = @intCast(name.len); + return name.ptr; +} + +// The core has no post pass (CRT) and no pane transitions since the +// rewrite: the scene is always still and these three say so to the shell. +export fn pardes_scene() Scene { + return .{}; +} + +export fn pardes_postprocessor_unavailable() void {} + +export fn pardes_panel_animation_failed() void {} + +fn refreshCwds(ctx: ?*anyopaque) void { + const st = hostState(ctx); + for (&st.cwd_stale, 0..) |*stale, id| { + if (!stale.*) continue; + stale.* = false; + const pt = st.ptys[id] orelse continue; + var buf: [1024]u8 = undefined; + if (host_io.ttyCwd(pt.pid, pt.file.handle, st.core.settings.shell.effective.get(), &buf)) |wd| st.core.setCwd(id, wd); + } +} + +fn paneWatchPath(core: *const pardes.Pardes, pane: u8) ?[]const u8 { + const value = core.panes[pane] orelse return null; + if (value.file) |file| return file.path; + if (value.addon) |k| if (k.path.len > 0) return k.path; + return null; +} + +fn watchInitialGeneration(st: *State, pane: u8, path: []const u8) ?file_watch.Generation { + const value = st.core.panes[pane] orelse return null; + if (value.file) |file| if (std.mem.eql(u8, file.path, path)) + return .{ .text = std.hash.Wyhash.hash(0, file.content) }; + if (value.addon) |k| if (std.mem.eql(u8, k.path, path)) + return .{ .kind = null }; + return null; +} + +fn setFileWatch(st: *State, pane: u8, path: []const u8, mode: pardes.WatchMode) void { + const native = filesystem.localPath(path) orelse return; + const value = st.core.panes[pane] orelse return; + const generation_on_disk = watchInitialGeneration(st, pane, path) orelse return; + const generation = st.file_watches.replace( + st.gpa, + pane, + path, + value.serial, + generation_on_disk, + ) catch { + const stopped = st.file_watches.stop(st.gpa, pane); + hostWatchFile(pane, stopped, null, 0); + return; + }; + hostWatchFile(pane, generation, native.ptr, native.len); + if (mode == .baseline_disk and value.file != null) { + const bytes = filesystem.read(st.core, path) catch return; + defer st.core.gpa.free(bytes); + st.file_watches.restampText(pane, path, std.hash.Wyhash.hash(0, bytes)); + return; + } + _ = reloadWatchedFile(st, pane, false); +} + +fn setThemeFileWatch(st: *State, request_generation: u32, on: bool) void { + const stopped = st.file_watches.stop(st.gpa, theme_watch_pane); + hostWatchFile(theme_watch_pane, stopped, null, 0); + if (!on) return; + const request = colors.themeFileRequest(st.core, request_generation) orelse return; + const bytes = filesystem.readFile(st.gpa, request.path) catch |err| { + colors.failThemeFile(st.core, request_generation, err); + return; + }; + defer st.gpa.free(bytes); + if (!colors.loadThemeFile(st.core, request_generation, bytes)) return; + const callback_generation = st.file_watches.replace( + st.gpa, + theme_watch_pane, + request.path, + request_generation, + .{ .text = std.hash.Wyhash.hash(0, bytes) }, + ) catch return; + const watched = st.file_watches.entries[theme_watch_pane].?; + hostWatchFile(theme_watch_pane, callback_generation, watched.path.ptr, watched.path.len); + _ = reloadWatchedTheme(st, false); +} + +fn reloadWatchedTheme(st: *State, announce: bool) bool { + const watched = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; + const request = colors.themeFileRequest(st.core, watched.serial) orelse return false; + if (!std.mem.eql(u8, watched.path, request.path)) return false; + const bytes = filesystem.readFile(st.gpa, watched.path) catch |err| { + colors.failThemeFile(st.core, watched.serial, err); + return false; + }; + defer st.gpa.free(bytes); + const hash = std.hash.Wyhash.hash(0, bytes); + switch (watched.generation_on_disk) { + .text => |accepted| if (accepted == hash) return false, + .kind => unreachable, + } + if (!colors.loadThemeFile(st.core, watched.serial, bytes)) return false; + const live = if (st.file_watches.entries[theme_watch_pane]) |*entry| entry else return false; + if (live.serial != watched.serial) return false; + live.generation_on_disk = .{ .text = hash }; + live.retries_left = 0; + if (announce) { + var mbuf: [256]u8 = undefined; + st.core.setMessage(request.pane, message.stamp(&mbuf, "reloaded theme", request.path)); + } + return true; +} + +const WatchReload = enum { no_change, committed, changed_uncommitted }; + +fn retryWatchedFile(st: *State, pane: u8, generation: u32) void { + if (st.file_watches.retry(pane, generation)) wake(st); +} + +fn reloadWatchedFile(st: *State, pane: u8, announce: bool) bool { + const watched = if (st.file_watches.entries[pane]) |*entry| entry else return false; + const generation = watched.generation; + const current_path = paneWatchPath(st.core, pane) orelse return false; + if (!std.mem.eql(u8, watched.path, current_path)) return false; + const current = st.core.panes[pane] orelse return false; + if (current.serial != watched.serial) return false; + + const result: WatchReload = switch (watched.generation_on_disk) { + .text => |old_hash| text: { + if (current.file == null) break :text .no_change; + const bytes = filesystem.read(st.core, watched.path) catch { + retryWatchedFile(st, pane, generation); + break :text .no_change; + }; + defer st.core.gpa.free(bytes); + const hash = std.hash.Wyhash.hash(0, bytes); + if (hash == old_hash) break :text .no_change; + if (!st.core.reloadWatchedFile(pane, bytes)) { + retryWatchedFile(st, pane, generation); + break :text .no_change; + } + + const after = st.core.panes[pane] orelse break :text .no_change; + const active = if (st.file_watches.entries[pane]) |*entry| entry else break :text .no_change; + if (active.generation != generation or after.serial != active.serial) + break :text .no_change; + active.generation_on_disk = .{ .text = hash }; + active.retries_left = 0; + break :text .committed; + }, + .kind => |old_identity| pdf: { + const state_before = if (current.addon) |k| k else break :pdf .no_change; + if (!std.mem.eql(u8, state_before.path, watched.path)) break :pdf .no_change; + const before = file_watch.identify(st.io, watched.path) catch { + retryWatchedFile(st, pane, generation); + break :pdf .no_change; + }; + if (old_identity) |old| if (old.eql(before)) break :pdf .no_change; + if (!st.core.reloadWatchedFile(pane, &.{})) { + retryWatchedFile(st, pane, generation); + break :pdf .no_change; + } + + const after = st.core.panes[pane] orelse break :pdf .changed_uncommitted; + if (after.serial != watched.serial) break :pdf .changed_uncommitted; + const pdf_state = if (after.addon) |k| k else break :pdf .changed_uncommitted; + if (!std.mem.eql(u8, pdf_state.path, watched.path)) break :pdf .changed_uncommitted; + const after_identity = file_watch.identify(st.io, watched.path) catch { + retryWatchedFile(st, pane, generation); + break :pdf .changed_uncommitted; + }; + if (!before.eql(after_identity)) { + retryWatchedFile(st, pane, generation); + break :pdf .changed_uncommitted; + } + const active = if (st.file_watches.entries[pane]) |*entry| entry else break :pdf .changed_uncommitted; + if (active.generation != generation or active.serial != after.serial) + break :pdf .changed_uncommitted; + active.generation_on_disk = .{ .kind = after_identity }; + active.retries_left = 0; + break :pdf .committed; + }, + }; + if (result == .committed and announce) { + var mbuf: [256]u8 = undefined; + st.core.setMessage(pane, message.stamp(&mbuf, "reloaded", watched.path)); + } + return result != .no_change; +} + +export fn pardes_watch_changed(pane: u8, generation: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + if (pane >= watch_slot_count) return; + if (st.file_watches.notify(pane, generation)) wake(st); +} + +fn drainInbox(st: *State) bool { + var batch = st.inbox.take(); + // After this batch's output, which an exit is told behind. + defer takeExits(st); + var did = batch.len > 0; + for (batch.slice()) |msg| { + defer msg.deinit(st.gpa, st.gpa); + switch (msg) { + .output => |o| { + if (st.gens[o.pane] != o.gen) continue; + st.cwd_stale[o.pane] = true; + st.core.update(.{ .output = .{ .pane = o.pane, .bytes = o.bytes } }); + }, + .eof => |e| { + if (st.gens[e.pane] != e.gen) continue; + if (st.ptys[e.pane]) |*pt| { + // A command's pty stays open until its child has exited: + // closing it would hang up one that runs on without it. + // Its exit, if it came first, is told now its output is in. + if (pt.cmd.watched) { + host_io.commandEof(st.core, &st.ptys, e.pane, st, closeWatched); + continue; + } + // Unwatched, a command's exit is read here, as its end, + // and a shell's, for a run waiting on it and the log. + const command = if (st.core.panes[e.pane]) |pane| pane.command != null else false; + const status = host_io.exitStatus(pt.pid, 100); + if (status != null) pt.pid = 0; // reaped: no shell to retire + reap(st, e.pane); + if (command or status != null) st.core.update(.{ .exited = .{ .pane = e.pane, .status = status } }); + st.core.update(.{ .eof = .{ .pane = e.pane } }); + continue; + } + reap(st, e.pane); + st.core.update(.{ .eof = .{ .pane = e.pane } }); + }, + .lsp => |d| { + st.core.update(.{ .lsp_resp = .{ .id = d.id, .rows = d.rows } }); + if (st.inbox.lsp_task) |*t| if (t.id == d.id) { + t.future.await(st.io); + st.inbox.lsp_task = null; + }; + }, + .lsp_status => |text| { + var mbuf: [256]u8 = undefined; + st.core.setStatus(st.core.view().active, message.stamp(&mbuf, "lsp", text)); + }, + .pipe => |value| { + st.core.update(.{ .pipe_resp = .{ + .id = value.id, + .success = value.success, + .outputs = value.outputs, + .failure = value.failure, + } }); + st.pipe_tasks.finish(st.io, value.id); + }, + // ponytail: no `search` host entry here, so Stream runs on the loop. + .search => |b| st.core.update(.{ .search = b }), + // The SDL shell's: this one's file watches and 9P are its own. + // ponytail: no hand_over host entry on macOS yet, so none comes. + // No daemon on macOS (daemon.supported): neither ever comes. + // ponytail: no `job` host entry here either: a kind's jobs run + // on the loop (host_io.KindJob.runHere), so none comes. + .files_changed, .fs_ready, .handed, .window, .adopted, .kind_job => {}, + } + } + for (0..pardes.MAX_PANES) |pane| { + const id: u8 = @intCast(pane); + if (!st.file_watches.takeDirty(id)) continue; + if (reloadWatchedFile(st, id, true)) did = true; + } + if (st.file_watches.takeDirty(theme_watch_pane)) { + if (reloadWatchedTheme(st, true)) did = true; + } + return did; +} + +export fn pardes_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + st.wake_pending.store(false, .release); + var did = drainInbox(st); + if (st.ninep) |listener| { + const drained = listener.tick(); + did = did or drained.count != 0; + if (drained.pending) wake(st); + } + while (st.core.nextEffect()) |effect| { + did = true; + st.core.perform(effect); + } + pardes.turn.bump(&pardes.turn.epoch); + if (restoreCore(st)) did = true; + pardes.turn.bump(&pardes.turn.restores); + return did; +} + +fn restoreCore(st: *State) bool { + if (st.core.quit) return false; + const path = st.core.takeRestore() orelse return false; + const bytes = dump.restoreBytes(st.core, st.gpa, path) catch |err| { + st.core.reportError(st.core.view().active, "Restore", err); + return false; + }; + defer st.gpa.free(bytes); + const replacement = dump.restore(st.core, bytes, path) catch |err| { + st.core.reportError(st.core.view().active, "Restore", err); + return false; + }; + if (st.inbox.lsp_task) |*task| { + task.future.cancel(st.io); + st.inbox.lsp_task = null; + } + st.pipe_tasks.cancelAll(st.io); + for (0..pardes.MAX_PANES) |pane| { + reap(st, @intCast(pane)); + st.gens[pane] +%= 1; + } + var stale = st.inbox.take(); + for (stale.slice()) |msg| msg.deinit(st.gpa, st.gpa); + for (0..watch_slot_count) |pane| if (st.file_watches.entries[pane] != null) { + const id: u8 = @intCast(pane); + const generation = st.file_watches.stop(st.gpa, id); + hostWatchFile(id, generation, null, 0); + }; + if (st.ninep) |listener| listener.reset(replacement); + replacement.host = hostFor(st); + st.core.deinit(); + st.core = replacement; + clearFrame(st); + st.cwd_stale = @splat(false); + st.scroll_lag = 0; + st.scroll_lag_x = 0; + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_last_ns = 0; + st.scroll_coasting = false; + st.rotate_lag = 0; + st.rotate_velocity = 0; + st.rotate_last_ns = 0; + st.rotate_coasting = false; + st.last_tick_ns = 0; + st.tick_bank_ns = 0; + return true; +} + +export fn pardes_animation_tick() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + + const now: u64 = @intCast(std.Io.Clock.awake.now(st.io).nanoseconds); + const spend = spendTickTime(st.last_tick_ns, now, st.tick_bank_ns); + st.last_tick_ns = now; + st.tick_bank_ns = spend.bank_ns; + + var changed = false; + + for (0..spend.steps) |_| { + if (st.core.animationActive()) { + st.core.update(.tick); + changed = true; + } + if (st.scroll_coasting) { + const spent_now = spendScroll( + st, + st.scroll_velocity * scroll_fling_step, + st.scroll_velocity_x * scroll_fling_step, + st.scroll_col, + st.scroll_row, + ); + st.scroll_velocity *= scroll_fling_decay; + st.scroll_velocity_x *= scroll_fling_decay; + const decayed = @abs(st.scroll_velocity) < scroll_fling_stop and + @abs(st.scroll_velocity_x) < scroll_fling_stop; + // Only a step that actually delivered a press can report an edge; + // the many steps between two rows cross nothing and say nothing. + const at_edge = spent_now.ticks != 0 and !spent_now.moved; + if (decayed or at_edge) { + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_coasting = false; + st.scroll_lag = 0; + st.scroll_lag_x = 0; + } + changed = true; + } + if (st.rotate_coasting) { + spendRotation(st, st.rotate_velocity * rotation_fling_step); + st.rotate_velocity *= rotation_fling_decay; + if (@abs(st.rotate_velocity) < rotation_fling_stop) { + st.rotate_velocity = 0; + st.rotate_coasting = false; + st.rotate_lag = 0; + } + changed = true; + } + } + if (!changed) { + st.tick_bank_ns = 0; + st.last_tick_ns = 0; + } + return changed; +} + +export fn pardes_key(cp_arg: u32, text_ptr: ?[*]const u8, len: usize, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + if (cp_arg > std.math.maxInt(u21)) return; + const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; + st.core.update(.{ .key = .{ + .cp = @intCast(cp_arg), + .text = text, + .ctrl = mods & 1 != 0, + .alt = mods & 2 != 0, + .shift = mods & 4 != 0, + } }); +} + +export fn pardes_paste(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; + st.core.update(.{ .paste = text }); +} + +export fn pardes_mouse(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + mouseWithHit(button_arg, kind_arg, col, row, mods, null, null); +} + +export fn pardes_mouse_pixel(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32, x: f32, y: f32, bw: f32, bh: f32, tw: f32, th: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + // The layers are asked only over the grid, as the gui's onGrid. + const v = st.core.view(); + const on_grid = std.math.isFinite(x) and std.math.isFinite(y) and x >= 0 and y >= 0 and + x < @as(f32, @floatFromInt(v.screen_w)) * @max(1, bw) and y < @as(f32, @floatFromInt(v.screen_h)) * @max(1, bh); + var hit: ?pardes.Mouse.BodyHit = null; + if (on_grid) for (&st.core.surface.body_layers) |*layer| { + hit = layer.bodyHit(x, y, bw, bh, tw, th); + if (hit != null) break; + }; + var tag_hit: ?pardes.TagHit = null; + if (on_grid) for (&st.core.surface.tag_layers) |*layer| { + tag_hit = layer.tagHit(x, y, bw, bh, tw, th); + if (tag_hit != null) break; + }; + mouseWithHit(button_arg, kind_arg, col, row, mods, hit, tag_hit); +} + +fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u32, hit: ?pardes.Mouse.BodyHit, tag_hit: ?pardes.TagHit) void { + const st = &(state orelse return); + const button: pardes.Mouse.Button = switch (button_arg) { + 0 => .left, + 1 => .middle, + 2 => .right, + 3 => .wheel_up, + 4 => .wheel_down, + 5 => .wheel_left, + 6 => .wheel_right, + 7 => .none, + 8 => .back, + 9 => .forward, + else => return, + }; + const kind: pardes.Mouse.Kind = switch (kind_arg) { + 0 => .press, + 1 => .release, + 2 => .motion, + 3 => .drag, + else => return, + }; + st.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = col, + .row = row, + .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); +} + +export fn pardes_pointer_leave() void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + st.core.update(.pointer_leave); +} + +export fn pardes_scroll(delta_rows: f32, delta_cols: f32, col: u16, row: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + st.scroll_col = col; + st.scroll_row = row; + noteScrollVelocity(st, delta_rows, delta_cols); + _ = spendScroll(st, delta_rows, delta_cols, col, row); +} + +/// A finger back on the pad, which catches a coast the way a hand catches a +/// spinning dial. Also drops whatever the last gesture left banked, so the +/// first millimetre of a new swipe cannot inherit a nearly-complete row. +export fn pardes_scroll_begin() void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + st.scroll_lag = 0; + st.scroll_lag_x = 0; + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + st.scroll_coasting = false; + st.scroll_last_ns = std.Io.Clock.awake.now(st.io).nanoseconds; +} + +/// Fingers lifted. A swipe that was still moving when it ended becomes a +/// fling, measured from the speed of the last events rather than from any one +/// of them, exactly as pardes_rotate_end measures the dial. +/// +/// A host whose windowing system flings for it need do nothing to suppress +/// this: its first momentum event is an ordinary pardes_scroll, and every +/// pardes_scroll cancels the coast before spending its own travel. The system's +/// momentum simply takes the gesture over, and the tail of that momentum is +/// below the fling floor, so its end arms nothing. +export fn pardes_scroll_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + const last = st.scroll_last_ns; + st.scroll_last_ns = 0; + st.scroll_coasting = false; + // A hand that came to rest before lifting is not throwing anything. + if (last == 0 or std.Io.Clock.awake.now(st.io).nanoseconds - last > 90 * std.time.ns_per_ms) { + st.scroll_velocity = 0; + st.scroll_velocity_x = 0; + return; + } + st.scroll_velocity = scrollFling(st.scroll_velocity); + st.scroll_velocity_x = scrollFling(st.scroll_velocity_x); + st.scroll_coasting = st.scroll_velocity != 0 or st.scroll_velocity_x != 0; +} + +export fn pardes_rotate(degrees: f32) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + if (degrees == 0) { + st.rotate_lag = 0; + st.rotate_velocity = 0; + st.rotate_coasting = false; + st.rotate_last_ns = std.Io.Clock.awake.now(st.io).nanoseconds; + return; + } + noteRotationVelocity(st, degrees); + spendRotation(st, degrees); +} + +export fn pardes_rotate_end() void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + const last = st.rotate_last_ns; + st.rotate_last_ns = 0; + st.rotate_coasting = false; + if (last == 0 or std.Io.Clock.awake.now(st.io).nanoseconds - last > 90 * std.time.ns_per_ms) { + st.rotate_velocity = 0; + return; + } + st.rotate_velocity = rotationFling(st.rotate_velocity); + st.rotate_coasting = st.rotate_velocity != 0; +} + +fn noteRotationVelocity(st: *State, degrees: f32) void { + const now = std.Io.Clock.awake.now(st.io).nanoseconds; + const last = st.rotate_last_ns; + st.rotate_last_ns = now; + st.rotate_coasting = false; + if (last == 0 or now == 0) return; + const dt_ns = now - last; + if (dt_ns <= 0 or dt_ns > 200 * std.time.ns_per_ms) return; + const seconds: f32 = @floatCast(@as(f64, @floatFromInt(dt_ns)) / @as(f64, std.time.ns_per_s)); + const sample = degrees / seconds; + if (!std.math.isFinite(sample)) return; + st.rotate_velocity = st.rotate_velocity * 0.35 + sample * 0.65; +} + +fn spendRotation(st: *State, degrees: f32) void { + var left = takeRotationNotches(&st.rotate_lag, degrees); + while (left != 0) { + const back = left > 0; // counterclockwise + left += if (back) -1 else 1; + st.core.update(.{ .key = .{ .cp = if (back) 'N' else 'n' } }); + } +} + +export fn pardes_command(text_ptr: ?[*]const u8, len: usize) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + const text: []const u8 = if (text_ptr) |p| p[0..len] else ""; + if (text.len == 0) return; + st.core.update(.{ .command = text }); +} + +export fn pardes_resize(cols_arg: u16, rows_arg: u16, cell_w: u16, cell_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + const cols = @max(1, cols_arg); + const rows = @max(1, rows_arg); + st.core.update(.{ .resize = .{ + .cols = cols, + .rows = rows, + .cell_pixels = .{ .w = @max(1, cell_w), .h = @max(1, cell_h) }, + } }); +} + +export fn pardes_frame() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + const tz = tracy.zone(@src(), "pardes_frame"); + defer tz.end(); + _ = restoreCore(st); + st.core.pump(hostFor(st)) catch |err| { + log.err("render failed: {t}", .{err}); + clearFrame(st); + return 0; + }; + if (restoreCore(st)) { + st.core.pump(hostFor(st)) catch |err| { + log.err("render failed: {t}", .{err}); + clearFrame(st); + return 0; + }; + } + tracy.frameMark(); + return @intCast(st.frame_len); +} + +fn clearFrame(st: *State) void { + st.frame_len = 0; + st.frame_cols = 0; + st.frame_rows = 0; + st.images_len = 0; +} + +fn blankTagCells(cells: []Cell, cols: u16, rows: u16, source: []const pardes.Cell, layers: []const pardes.Layer) void { + for (layers) |layer| { + if (layer.rows == 0 or layer.viewport.y >= rows or layer.viewport.x >= cols) continue; + const start = @as(usize, layer.viewport.y) * cols + layer.viewport.x; + const count = @min(layer.viewport.w, cols - layer.viewport.x); + // The tag text is the layer's to draw. (The look-hover's glass + // rect went with the core's hover bit, stage 8's follow-up.) + _ = source; + for (cells[start..][0..count]) |*cell| cell.* = encodeCell(.{}); + } +} + +fn tagCursorCovered(core: *const pardes.Pardes) bool { + const cursor = core.surface.cursor orelse return false; + for (core.surface.tag_layers) |layer| { + if (layer.rows != 0 and cursor.y == layer.viewport.y and cursor.x >= layer.viewport.x and + cursor.x - layer.viewport.x < layer.viewport.w) return true; + } + return false; +} + +fn presentFrame(ctx: ?*anyopaque, surface: *const pardes.Surface) void { + const st = hostState(ctx); + const tz = tracy.zone(@src(), "presentFrame"); + defer tz.end(); + clearFrame(st); + const count: usize = @as(usize, surface.cols) * surface.rows; + if (count != st.cells.len) { + if (count == 0) { + if (st.cells.len > 0) st.gpa.free(st.cells); + st.cells = &.{}; + } else { + const resized = if (st.cells.len == 0) + st.gpa.alloc(Cell, count) + else + st.gpa.realloc(st.cells, count); + st.cells = resized catch return; + } + } + st.frame_len = count; + st.frame_cols = surface.cols; + st.frame_rows = surface.rows; + { + const tz_cells = tracy.zone(@src(), "encodeCells"); + defer tz_cells.end(); + for (surface.cells, st.cells[0..count]) |cell, *out| out.* = encodeCell(cell); + } + blankTagCells(st.cells[0..count], surface.cols, surface.rows, surface.cells, &surface.tag_layers); + collectImages(st, surface); +} + +fn collectImages(st: *State, surface: *const pardes.Surface) void { + const placements = surface.placements.items; + if (placements.len == 0) return; + if (st.images.len < placements.len) { + const resized = if (st.images.len == 0) + st.gpa.alloc(Image, placements.len) + else + st.gpa.realloc(st.images, placements.len); + st.images = resized catch return; + } + for (placements) |place| { + if (place.raster.w == 0 or place.raster.h == 0) continue; + const dst = place.at orelse pardes.RectPx{ + .w = @as(u32, place.dst.w) * st.core.view().cell_pixels.w, + .h = @as(u32, place.dst.h) * st.core.view().cell_pixels.h, + }; + if (dst.w == 0 or dst.h == 0 or place.src.w == 0 or place.src.h == 0) continue; + var scroll: f64 = 0; + for (surface.regionList()) |r| if (r.kind == .body and r.owner == place.pane) { + scroll = r.scroll_px; + break; + }; + st.images[st.images_len] = .{ + // The shell keys its textures by these three: the placement's + // key in two halves keeps them one picture each. + .serial = if (st.core.panes[place.pane]) |pane| pane.serial else 0, + .page = @truncate(place.key), + .revision = @truncate(place.key >> 32), + .cell_x = place.dst.x, + .cell_y = place.dst.y, + .cell_w = place.dst.w, + .cell_h = place.dst.h, + .dst_x = dst.x, + .dst_y = dst.y, + .dst_w = dst.w, + .dst_h = dst.h, + .src_x = place.src.x, + .src_y = place.src.y, + .src_w = place.src.w, + .src_h = place.src.h, + .offset_y = -@as(f32, @floatCast(scroll - @floor(scroll))), + .iw = place.raster.w, + .ih = place.raster.h, + .rgba = place.raster.ptr, + .paper_bg = color_default, + }; + st.images_len += 1; + } +} + +export fn pardes_frame_images() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + return @intCast(st.images_len); +} + +export fn pardes_frame_image_list() ?[*]const Image { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + return if (st.images_len == 0) null else st.images.ptr; +} + +// No pane transitions: no tracks, no previous frame to blend from, and a +// presented frame starts no clock. +export fn pardes_frame_panel_tracks() u32 { + return 0; +} + +export fn pardes_frame_panel_track_list() ?[*]const PanelTrack { + return null; +} + +export fn pardes_frame_presented(_: bool) bool { + return false; +} + +export fn pardes_frame_cells() ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + return if (st.frame_len == 0) null else st.cells.ptr; +} + +export fn pardes_frame_previous_cells() ?[*]const Cell { + return null; +} + +export fn pardes_frame_changed_cells() ?[*]const u8 { + return null; +} + +export fn pardes_frame_cols() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + return st.frame_cols; +} + +export fn pardes_frame_rows() u16 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + return st.frame_rows; +} + +export fn pardes_cursor_x() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return -1); + if (tagCursorCovered(st.core)) return -1; + return if (st.core.surface.cursor) |c| c.x else -1; +} + +export fn pardes_tag_text_inset() u32 { + return pardes.TAG_TEXT_INSET; +} + +export fn pardes_grip_columns() u32 { + return @import("core").config.GUTTER; +} + +export fn pardes_tag_layer_limit() u32 { + return pardes.MAX_TAG_LAYERS; +} + +export fn pardes_tag_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + if (index >= pardes.MAX_TAG_LAYERS) return 0; + const layer = &st.core.surface.tag_layers[index]; + return switch (field) { + 0 => layer.cols, + 1 => @backingInt(layer.kind), + 2 => layer.id, + 3 => layer.serial, + 4 => layer.viewport.x, + 5 => layer.viewport.y, + 6 => layer.viewport.w, + 7 => layer.viewport.h, + 8 => if (layer.cursor) |c| c.x else 65535, + 9 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, + 10 => @as(u32, layer.bg[0]) << 16 | @as(u32, layer.bg[1]) << 8 | layer.bg[2], + // A tag at its pane's foot: there is no Tagbottom now. + 11 => 0, + 12 => rgb: { + const border = st.core.chromeTheme().border; + break :rgb @as(u32, border[0]) << 16 | @as(u32, border[1]) << 8 | border[2]; + }, + else => 0, + }; +} + +export fn pardes_tag_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + if (index >= pardes.MAX_TAG_LAYERS) return null; + const layer = &st.core.surface.tag_layers[index]; + if (layer.rows == 0) return null; + const cells = &st.tag_cells[index]; + if (cells.len != layer.cells.len) cells.* = st.gpa.realloc(cells.*, layer.cells.len) catch return null; + for (layer.cells, cells.*) |source, *out| out.* = encodeCell(source); + return cells.ptr; +} + +export fn pardes_body_layer_value(index: u32, field: u32) u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + if (index >= pardes.MAX_PANES) return 0; + const layer = &st.core.surface.body_layers[index]; + return switch (field) { + 0 => layer.rows, + 1 => layer.cols, + 2 => layer.context_rows, + 3 => layer.viewport.x, + 4 => layer.viewport.y, + 5 => layer.viewport.w, + 6 => layer.viewport.h, + 7 => layer.serial, + 8 => if (layer.cursor) |c| c.x else 65535, + 9 => if (layer.cursor) |c| c.y else 65535, + 10 => if (layer.cursor) |c| @intFromBool(c.bar) else 0, + else => @intFromBool(layer.hasContextBorderAfter(field - 11)), + }; +} + +export fn pardes_body_layer_cells(index: u32) ?[*]const Cell { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + if (index >= pardes.MAX_PANES) return null; + const layer = &st.core.surface.body_layers[index]; + if (layer.rows == 0) return null; + const cells = &st.layer_cells[index]; + if (cells.len != layer.cells.len) cells.* = st.gpa.realloc(cells.*, layer.cells.len) catch return null; + for (layer.cells, cells.*) |cell, *out| out.* = encodeCell(cell); + return cells.ptr; +} + +export fn pardes_body_layer_limit() u32 { + return pardes.MAX_PANES; +} + +export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h: u16) void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + st.core.update(.{ .resize = .{ .cols = st.core.view().screen_w, .rows = st.core.view().screen_h, .cell_pixels = st.core.view().cell_pixels, .row_metrics = .{ .body_w = @max(1, body_w), .body_h = @max(1, body_h), .tagline_w = @max(1, tagline_w), .tagline_h = @max(1, tagline_h) } } }); +} + +export fn pardes_pointer_shape() u32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + return @backingInt(st.core.surface.pointer_shape); +} + +export fn pardes_cursor_y() i32 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return -1); + if (tagCursorCovered(st.core)) return -1; + return if (st.core.surface.cursor) |c| c.y else -1; +} + +export fn pardes_cursor_bar() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + return if (st.core.surface.cursor) |c| c.bar else false; +} + +export fn pardes_take_haptic() c_int { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return 0); + return switch (st.core.takeHaptic()) { + .none => 0, + .exec => 1, + .look => 2, + }; +} + +var font_path_z: [4096:0]u8 = undefined; + +export fn pardes_font_take(size_hundredths: *u16) ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + if (comptime !pardes.font_picker) return null; + const want = st.core.takeFontRequest() orelse return null; + size_hundredths.* = st.core.settings.font.requested_size_hundredths; + if (want.len >= font_path_z.len) return null; + @memcpy(font_path_z[0..want.len], want); + font_path_z[want.len] = 0; + return &font_path_z; +} + +export fn pardes_font_observe( + effective_name: ?[*]const u8, + len: usize, + point_hundredths: u16, +) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + const ptr = effective_name orelse return false; + if (len == 0 or len > 255 or point_hundredths == 0) return false; + return st.core.observeFont(ptr[0..len], point_hundredths, .points); +} + +export fn pardes_font_ack( + effective_name: ?[*]const u8, + len: usize, + point_hundredths: u16, +) bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + const ptr = effective_name orelse return false; + if (len == 0 or len > 255 or point_hundredths == 0) return false; + return st.core.acknowledgeFont(ptr[0..len], point_hundredths, .points); +} + +export fn pardes_font_reject() void { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return); + st.core.rejectFont(); +} + +var active_path_z: [4096:0]u8 = undefined; + +export fn pardes_active_path() ?[*:0]const u8 { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return null); + const path = activeFilePath(st) orelse return null; + if (path.len == 0 or path.len >= active_path_z.len) return null; + @memcpy(active_path_z[0..path.len], path); + active_path_z[path.len] = 0; + return &active_path_z; +} + +export fn pardes_active_dirty() bool { + pardes.turn.wake(); + defer pardes.turn.rest(); + const st = &(state orelse return false); + const pane = st.core.panes[st.core.view().active] orelse return false; + const f = if (pane.file) |*x| x else return false; + if (f.output != null) return false; + return f.revision != f.saved_revision; +} + +fn activeFilePath(st: *State) ?[]const u8 { + const pane = st.core.panes[st.core.view().active] orelse return null; + if (pane.file) |*f| return if (f.output == null) f.path else null; + if (pane.addon) |k| return k.path; + return null; +} + +const vtable: pardes.Host.VTable = .{ + .present = presentFrame, + .poll_frame = refreshCwds, + .spawn = spawnShell, + .pty_write = ptyWrite, + .pty_resize = ptyResize, + .pty_signal = ptySignal, + .close_pty = closePty, + .tty_taken = ttyTaken, + .kill_job = killJob, + .write_file = writeFile, + .write_dump = writeDump, + .watch_file = watchFile, + .watch_theme = watchTheme, + .dump_themes = dumpThemes, + .set_clipboard = setClipboard, + .read_clipboard = readClipboard, + .open_link = openLink, + .start = host_io.startDetached, + .lsp = lspRequest, + .pipe = pipeRequest, +}; + +fn hostFor(st: *State) pardes.Host { + return .{ .ctx = st, .vtable = &vtable }; +} + +fn lspRequest(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { + const st = hostState(ctx); + st.inbox.startLsp(st.core, req); +} + +fn pipeRequest(ctx: ?*anyopaque, id: u32) void { + const st = hostState(ctx); + selection_pipe.start(st.io, st.gpa, st.core, &st.pipe_tasks, id, &st.inbox, Inbox.pushPipe); +} + +fn hostState(ctx: ?*anyopaque) *State { + return @ptrCast(@alignCast(ctx.?)); +} + +fn spawnShell(ctx: ?*anyopaque, pane: u8, cwd: []const u8) void { + const st = hostState(ctx); + const core = st.core; + // The new shell starts before a running one goes: one that cannot + // start leaves the running one be (pty/ctl's exec). + const running = st.ptys[pane] != null; + const child = host_io.forkShell(core, pane, &st.prompt_rcs, core.shellBin(), cwd, core.view().screen_h, core.view().screen_w) catch |err| { + if (running) return core.restartFailed(pane, err); + return core.shellFailed(pane, err); + }; + reap(st, pane); + st.gens[pane] +%= 1; + const gen = st.gens[pane]; + + st.ptys[pane] = .{ + .file = child.file, + .pid = child.pid, + .gen = gen, + .reader = .{ .any_future = null, .result = {} }, + .cmd = .{ .watched = (if (core.panes[pane]) |pn| pn.command != null else false) and host_io.watchExit(child.pid), .fd = child.file.handle }, + }; + var lbuf: [1024]u8 = undefined; + // Only a shell given no directory is asked where it is: one given a + // directory is named by it already (newShell), and asked now, before + // its chdir, it would answer this process's, a rename to undo. + if (cwd.len == 0) if (host_io.shellCwd(child.pid, &lbuf)) |wd| core.setCwd(pane, wd); + if (st.started) if (st.ptys[pane]) |*pt| startReader(st, pt, pane); +} + +fn ptyWrite(ctx: ?*anyopaque, pane: u8, bytes: []const u8) void { + const st = hostState(ctx); + if (st.ptys[pane]) |pt| _ = host_io.writeFd(pt.file.handle, bytes); +} + +fn ptyResize(ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void { + const st = hostState(ctx); + const pt = st.ptys[pane] orelse return; + const ws: posix.winsize = .{ .row = rows, .col = cols, .xpixel = 0, .ypixel = 0 }; + _ = posix.system.ioctl(pt.file.handle, TIOCSWINSZ, @intFromPtr(&ws)); +} + +fn ptySignal(ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void { + const st = hostState(ctx); + // A command whose exit is recorded is reaped: its group may be another's. + if (st.ptys[pane]) |pt| if (!pt.cmd.exited) host_io.signalTty(pt.pid, pt.file.handle, sig, pt.cmd.watched); +} + +fn ttyTaken(ctx: ?*anyopaque, pane: u8) bool { + const st = hostState(ctx); + const pt = st.ptys[pane] orelse return false; + return host_io.ttyTaken(pt.pid, pt.file.handle); +} + +fn killJob(ctx: ?*anyopaque, pane: u8) bool { + const st = hostState(ctx); + const pt = st.ptys[pane] orelse return false; + return host_io.killJob(pt.pid, pt.file.handle); +} + +fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void { + const st = hostState(ctx); + filesystem.write(st.core, path, bytes) catch |err| + return st.core.saveFailed(pane, path, err); + st.file_watches.restampText(pane, path, std.hash.Wyhash.hash(0, bytes)); + var mbuf: [256]u8 = undefined; + st.core.setMessage(pane, message.stamp(&mbuf, "saved", path)); +} + +fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { + host_io.writeDump(hostState(ctx).core, bytes); +} + +fn watchFile(ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void { + const st = hostState(ctx); + if (!on or path.len == 0) { + const generation = st.file_watches.stop(st.gpa, pane); + hostWatchFile(pane, generation, null, 0); + return; + } + setFileWatch(st, pane, path, mode); +} + +fn watchTheme(ctx: ?*anyopaque, generation: u32, on: bool) void { + const st = hostState(ctx); + setThemeFileWatch(st, generation, on); +} + +fn dumpThemes(ctx: ?*anyopaque, pane: u8) void { + const st = hostState(ctx); + const config_dir = st.core.opts.config_dir orelse return; + const out_dir = pardes.config.User.dumpThemes(st.io, st.gpa, config_dir, pardes.themes) catch |err| { + st.core.reportError(pane, "dump themes", err); + return; + }; + defer st.gpa.free(out_dir); + var mbuf: [256]u8 = undefined; + st.core.setMessage(pane, message.stamp(&mbuf, "dumped themes", out_dir)); +} + +fn setClipboard(ctx: ?*anyopaque, text: []const u8) void { + const st = hostState(ctx); + const cb = st.runtime.set_clipboard orelse return; + cb(st.runtime.userdata, text.ptr, text.len); +} + +fn readClipboard(ctx: ?*anyopaque) void { + const st = hostState(ctx); + const cb = st.runtime.read_clipboard orelse return; + cb(st.runtime.userdata); +} + +fn openLink(_: ?*anyopaque, url: []const u8) void { + look.openLink(url); +} + +fn startReader(st: *State, pt: *Pty, id: u8) void { + pt.reader = st.inbox.startReader(pt.file, id, pt.gen) catch |err| { + log.err("pane {d} has no reader ({t}); it will not show output", .{ id, err }); + return; + }; +} + +/// The pane is gone: its shell goes with it. +fn closePty(ctx: ?*anyopaque, pane: u8) void { + const st = hostState(ctx); + if (st.ptys[pane] == null) return; + reap(st, pane); + st.gens[pane] +%= 1; +} + +fn reap(st: *State, pane: u8) void { + var pt = st.ptys[pane] orelse return; + st.ptys[pane] = null; + // The inbox first: a reader waiting for space there wakes and returns. + st.inbox.cancelReader(pane, pt.gen); + pt.reader.cancel(st.io); + _ = libc.close(pt.file.handle); + host_io.retireShell(pt.pid); +} + +fn wakeHost(ctx: ?*anyopaque) void { + wake(@ptrCast(@alignCast(ctx.?))); +} + +fn wake(st: *State) void { + const cb = st.runtime.wakeup orelse return; + if (st.wake_pending.swap(true, .acq_rel)) return; + cb(st.runtime.userdata); +} + +fn captureEnv(arena: std.mem.Allocator) ?std.process.Environ.Map { + var map: std.process.Environ.Map = .init(arena); + const environ = std.c.environ; + var i: usize = 0; + while (environ[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue; + map.put(line[0..eq], line[eq + 1 ..]) catch return null; + } + return map; +} + +fn encodeColor(color: pardes.Color) u32 { + return switch (color) { + .default => color_default, + .index => |index| color_indexed | @as(u32, index), + .rgb => |rgb| (@as(u32, rgb[0]) << 16) | (@as(u32, rgb[1]) << 8) | rgb[2], + }; +} + +fn encodeCell(cell: pardes.Cell) Cell { + var out: Cell = .{ + .text = @splat(0), + .fg = encodeColor(cell.style.fg), + .bg = encodeColor(cell.style.bg), + .attrs = encodeAttrs(cell.style), + .flags = encodeCellFlags(cell.default, cell.style.font_role, false), + .len = if (cell.default) 1 else cell.len, + }; + if (cell.default) + out.text[0] = ' ' + else + @memcpy(out.text[0..cell.len], cell.grapheme()); + return out; +} + +fn encodeAttrs(style: pardes.CellStyle) u16 { + var attrs: u16 = 0; + attrs |= @as(u16, @intFromBool(style.bold)) << 0; + attrs |= @as(u16, @intFromBool(style.dim)) << 1; + attrs |= @as(u16, @intFromBool(style.italic)) << 2; + attrs |= @as(u16, @intFromBool(style.blink)) << 3; + attrs |= @as(u16, @intFromBool(style.reverse)) << 4; + attrs |= @as(u16, @intFromBool(style.invisible)) << 5; + attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; + attrs |= @as(u16, @backingInt(style.ul)) << 8; + return attrs; +} + +fn encodeCellFlags(default: bool, role: pardes.FontRole, hover: bool) u8 { + return @as(u8, @intFromBool(default)) * cell_flag_default | + @as(u8, @intFromBool(role == .tagline)) * cell_flag_tagline | + @as(u8, @intFromBool(hover)) * cell_flag_hover; +} + +fn noteScrollVelocity(st: *State, delta_rows: f32, delta_cols: f32) void { + const now = std.Io.Clock.awake.now(st.io).nanoseconds; + const last = st.scroll_last_ns; + st.scroll_last_ns = now; + // Any real travel ends a coast: that is what lets a host with momentum of + // its own take the gesture over without either side knowing about it. + st.scroll_coasting = false; + if (last == 0 or now == 0) return; + const dt_ns = now - last; + // A gap this long is a new gesture, not a fast one. Without the guard the + // pause between two separate swipes would read as enormous speed. + if (dt_ns <= 0 or dt_ns > 200 * std.time.ns_per_ms) return; + const seconds: f32 = @floatCast(@as(f64, @floatFromInt(dt_ns)) / @as(f64, std.time.ns_per_s)); + const rows = delta_rows / seconds; + const cols = delta_cols / seconds; + if (!std.math.isFinite(rows) or !std.math.isFinite(cols)) return; + // Weighted toward the newest sample: a flick is decided by how the hand was + // moving when it left, not by how the swipe started. + st.scroll_velocity = st.scroll_velocity * 0.35 + rows * 0.65; + st.scroll_velocity_x = st.scroll_velocity_x * 0.35 + cols * 0.65; +} + +/// Spend accumulated travel as wheel presses, and report whether the pane under +/// the gesture actually moved. +/// +/// A coast has to stop at the end of a document instead of spinning the rest of +/// its velocity against the edge — the SDL shell stops for the same reason in +/// stepScroll. Only the vertical axis can be measured that way (a pane's +/// horizontal position is not Pane.scroll()), so sideways travel counts as +/// movement; a purely horizontal fling therefore rides its decay out, which is +/// what it would do anyway once the drift guard has swallowed it. +const Spent = struct { + /// Whole wheel presses delivered. Most coast steps cross no row at all, + /// which is why "did not move" cannot be read off `moved` alone. + ticks: u32 = 0, + moved: bool = false, +}; + +fn spendScroll(st: *State, delta_rows: f32, delta_cols: f32, col: u16, row: u16) Spent { + const pane = if (mouse.paneAt(st.core, col, row)) |id| st.core.panes[id] else null; + var out: Spent = .{}; + var down_left = takeScrollTicks(&st.scroll_lag, delta_rows); + while (down_left != 0) { + const down = down_left > 0; + down_left += if (down) -1 else 1; + out.ticks += 1; + const was = if (pane) |p| p.scroll() else 0; + st.core.update(.{ .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = col, + .row = row, + } }); + if (pane) |p| { + if (p.scroll() != was) out.moved = true; + } else out.moved = true; + } + var right_left = takeScrollTicks(&st.scroll_lag_x, delta_cols); + while (right_left != 0) { + const right = right_left > 0; + right_left += if (right) -1 else 1; + st.core.update(.{ .mouse = .{ + .button = if (right) .wheel_right else .wheel_left, + .kind = .press, + .col = col, + .row = row, + } }); + out.ticks += 1; + out.moved = true; + } + return out; +} + +// Rows per second. The floor is what separates a flick from a swipe that +// merely ended while still in contact; the ceiling stops a jab from launching +// the page past anything the eye can follow. Step and decay are stated at +// 60 Hz and spent by the same measured display clock the rotation fling uses, +// so a 120 Hz screen coasts the same distance in the same time. +const scroll_fling_floor: f32 = 8; +const scroll_fling_max: f32 = 90; +const scroll_fling_step: f32 = 1.0 / 60.0; +const scroll_fling_decay: f32 = 0.94; +const scroll_fling_stop: f32 = 2; + +fn scrollFling(speed: f32) f32 { + if (!std.math.isFinite(speed)) return 0; + const excess = @min(@abs(speed) - scroll_fling_floor, scroll_fling_max); + if (excess < scroll_fling_stop) return 0; + return std.math.copysign(excess, speed); +} + +fn takeScrollTicks(lag: *f32, delta_rows: f32) i32 { + if (!std.math.isFinite(delta_rows)) return 0; + const next = std.math.clamp(lag.* + delta_rows, -256, 256); + if (!std.math.isFinite(next)) return 0; + const whole: i32 = @intFromFloat(@trunc(next)); + lag.* = next - @as(f32, @floatFromInt(whole)); + return whole; +} + +const rotation_notch_degrees: f32 = 10; + +const rotation_fling_floor: f32 = 70; +const rotation_fling_max: f32 = 400; +const rotation_fling_step: f32 = 1.0 / 60.0; +const rotation_fling_decay: f32 = 0.94; +const rotation_fling_stop: f32 = 18; + +fn rotationFling(speed: f32) f32 { + const excess = @min(@abs(speed) - rotation_fling_floor, rotation_fling_max); + if (excess < rotation_fling_stop) return 0; + return std.math.copysign(excess, speed); +} + +fn takeRotationNotches(lag: *f32, degrees: f32) i32 { + if (!std.math.isFinite(degrees)) return 0; + const limit = rotation_notch_degrees * 64; + const next = std.math.clamp(lag.* + degrees, -limit, limit); + if (!std.math.isFinite(next)) return 0; + const whole: i32 = @intFromFloat(@trunc(next / rotation_notch_degrees)); + lag.* = next - @as(f32, @floatFromInt(whole)) * rotation_notch_degrees; + return whole; +} + +fn expectSameAbi(comptime C: type, comptime Z: type) !void { + const c_fn = @typeInfo(C).@"fn"; + const z_fn = @typeInfo(Z).@"fn"; + try std.testing.expectEqual(c_fn.param_types.len, z_fn.param_types.len); + inline for (c_fn.param_types, z_fn.param_types) |cp, zp| + try std.testing.expectEqual(@sizeOf(cp.?), @sizeOf(zp.?)); + try std.testing.expectEqual(@sizeOf(c_fn.return_type.?), @sizeOf(z_fn.return_type.?)); +} + +test "mac file watch generations own paths, coalesce, and reject stale callbacks" { + var watches: FileWatches = .{}; + defer watches.deinit(std.testing.allocator); + + var first_path = [_]u8{ '/', 't', 'm', 'p', '/', 'a' }; + const first = try watches.replace( + std.testing.allocator, + 3, + &first_path, + 41, + .{ .text = 11 }, + ); + first_path[first_path.len - 1] = 'x'; + try std.testing.expectEqualStrings("/tmp/a", watches.entries[3].?.path); + try std.testing.expect(watches.notify(3, first)); + try std.testing.expect(!watches.notify(3, first)); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(!watches.takeDirty(3)); + + const second = try watches.replace( + std.testing.allocator, + 3, + "/tmp/b", + 42, + .{ .text = 22 }, + ); + try std.testing.expect(second != first); + try std.testing.expect(!watches.notify(3, first)); + try std.testing.expect(watches.notify(3, second)); + try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(watches.retry(3, second)); + try std.testing.expect(!watches.retry(3, second)); + try std.testing.expect(watches.takeDirty(3)); + try std.testing.expect(watches.notify(3, second)); + try std.testing.expectEqual(@as(u8, 1), watches.entries[3].?.retries_left); + try std.testing.expect(watches.takeDirty(3)); + watches.restampText(3, "/tmp/not-b", 99); + try std.testing.expectEqual(@as(u64, 22), watches.entries[3].?.generation_on_disk.text); + watches.restampText(3, "/tmp/b", 33); + try std.testing.expectEqual(@as(u64, 33), watches.entries[3].?.generation_on_disk.text); + + const stopped = watches.stop(std.testing.allocator, 3); + try std.testing.expect(stopped != second); + try std.testing.expect(!watches.notify(3, second)); + try std.testing.expect(!watches.retry(3, second)); + try std.testing.expect(watches.entries[3] == null); + + _ = try watches.replace(std.testing.allocator, 4, "/tmp/book.pdf", 77, .{ .kind = null }); + watches.restampText(4, "/tmp/book.pdf", 123); + try std.testing.expect(watches.entries[4].?.generation_on_disk.kind == null); +} + +test "mac queued results never cancel a newer LSP request" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = std.testing.io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, + }; + defer st.config_arena.deinit(); + defer st.inbox.close(); + core.lspRequest(0, .status, ""); + const old_id = core.lsp_ask.wait.?.id; + core.lspRequest(0, .status, ""); + const current_id = core.lsp_ask.wait.?.id; + st.inbox.lsp_id = current_id; + st.inbox.lsp_task = .{ .id = current_id, .future = .{ .any_future = null, .result = {} } }; + // The inbox turns the superseded answer away. + st.inbox.push(.{ .lsp = .{ .id = old_id, .rows = try gpa.dupe(u8, "stale result\n") } }); + try std.testing.expectEqual(@as(usize, 0), st.inbox.completion_len); + _ = drainInbox(&st); + try std.testing.expect(st.inbox.lsp_task != null); + try std.testing.expectEqual(current_id, st.inbox.lsp_task.?.id); + try std.testing.expectEqual(current_id, core.lsp_ask.wait.?.id); + st.inbox.push(.{ .lsp = .{ .id = current_id, .rows = try gpa.dupe(u8, "") } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(core.lsp_ask.wait == null); +} + +test "mac worker setup failures finish matching LSP and pipe requests" { + const gpa = std.testing.allocator; + var failing_vtable = std.testing.io.vtable.*; + failing_vtable.concurrent = std.Io.failingConcurrent; + const failing_io: std.Io = .{ .userdata = std.testing.io.userdata, .vtable = &failing_vtable }; + for (0..2) |failure| { + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer core.deinit(); + const pane = try core.setTestFile("abc"); + var failing = std.testing.FailingAllocator.init(gpa, .{ + .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), + }); + var st: State = .{ + .gpa = failing.allocator(), + .threaded = undefined, + .io = failing_io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = failing.allocator(), .lsp_allocator = failing.allocator(), .io = failing_io }, + }; + defer st.config_arena.deinit(); + defer st.inbox.close(); + core.lspRequest(core.view().active, .status, ""); + const req: host_io.Lsp.Request = .{ + .id = core.lsp_ask.wait.?.id, + .kind = .status, + .pane = @intCast(core.view().active), + .offset = 0, + .arg = "", + }; + lspRequest(&st, req); + try std.testing.expect(core.lsp_ask.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + core.update(.{ .key = .{ .cp = '|' } }); + core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = core.pipe.wait.?.id; + pipeRequest(&st, pipe_id); + try std.testing.expect(core.pipe.wait == null); + try std.testing.expectEqualStrings("abc", pane.file.?.content); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + } +} + +test "mac host watcher covers file and directory vnode events, debounce, and generation callback" { + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "deletingLastPathComponent()", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "self.reopenFileSource()", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "DispatchQueue.main.asyncAfter", + ) != null); + try std.testing.expect(std.mem.indexOf( + u8, + file_watcher_swift, + "pardes_watch_changed(self.pane, self.generation)", + ) != null); +} + +test "the animation clock spends real time, not callbacks" { + const frame = pardes.frame_ns; + const expectEqual = std.testing.expectEqual; + + const first = spendTickTime(0, 999 * std.time.ns_per_s, 0); + try expectEqual(@as(u32, 1), first.steps); + try expectEqual(frame, first.elapsed_ns); + + const on_time = spendTickTime(1_000, 1_000 + frame, 0); + try expectEqual(@as(u32, 1), on_time.steps); + try expectEqual(@as(u64, 0), on_time.bank_ns); + + const late = spendTickTime(1_000, 1_000 + 2 * frame, 0); + try expectEqual(@as(u32, 2), late.steps); + + var bank: u64 = 0; + var steps: u32 = 0; + for (0..3) |_| { + const partial = spendTickTime(1_000, 1_000 + 6 * std.time.ns_per_ms, bank); + bank = partial.bank_ns; + steps += partial.steps; + } + try expectEqual(@as(u32, 1), steps); + try expectEqual(@as(u64, 2 * std.time.ns_per_ms), bank); + + const stall = spendTickTime(1_000, 1_000 + 10 * std.time.ns_per_s, 0); + try expectEqual(max_tick_catch_up_ns, stall.elapsed_ns); + try expectEqual(@as(u32, @intCast(max_tick_catch_up_ns / frame)), stall.steps); + + try expectEqual(@as(u32, 1), spendTickTime(5_000, 4_000, 0).steps); +} + +test "tagline percent falls back before init and follows live core state" { + try std.testing.expectEqual(pardes.config.gui_tagline_font_percent, taglineFontPercent(null)); + + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + const changed: u8 = if (pardes.config.gui_tagline_font_percent == 37) 38 else 37; + core.settings.font.tagline_percent = changed; + try std.testing.expectEqual(changed, taglineFontPercent(core)); +} + +test "the fallback preference order crosses the ABI intact and ends at the boundary" { + try std.testing.expectEqual(@as(u32, fonts.fallback_names.len), pardes_fallback_font_count()); + try std.testing.expect(pardes_fallback_font_count() > 0); + + for (fonts.fallback_names, 0..) |want, i| { + var len: u32 = 0; + const got = pardes_fallback_font_name(@intCast(i), &len) orelse return error.MissingFallbackName; + try std.testing.expectEqualStrings(want, got[0..len]); + } + + var len: u32 = 12345; + try std.testing.expect(pardes_fallback_font_name(pardes_fallback_font_count(), &len) == null); + try std.testing.expectEqual(@as(u32, 0), len); +} + +test "mac Restore keeps host state and rejects callbacks from the old core" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = std.testing.io, + .core = core, + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = std.testing.io }, + .frame_len = 7, + .rotate_coasting = true, + }; + defer st.core.deinit(); + defer st.config_arena.deinit(); + defer st.file_watches.deinit(gpa); + defer st.inbox.close(); + const marker = try st.config_arena.allocator().dupe(u8, "host configuration"); + _ = try core.setTestFile("saved body\n"); + const old_serial = core.panes[0].?.serial; + st.gens[0] = 23; + const old_watch = try st.file_watches.replace(gpa, 0, "/test.txt", old_serial, .{ .text = 0 }); + try dump.dumpState(core); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "restore.zon", .data = core.dump_out.? }); + while (core.nextEffect()) |_| {} + + var command: [512]u8 = undefined; + core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/missing.zon", .{tmp.sub_path}) }); + try std.testing.expect(!restoreCore(&st)); + try std.testing.expectEqual(core, st.core); + try std.testing.expectEqual(old_watch, st.file_watches.entries[0].?.generation); + try std.testing.expect(st.rotate_coasting); + + core.lspRequest(0, .status, ""); + const old_request = core.lsp_ask.wait.?.id; + st.inbox.lsp_id = old_request; + st.inbox.lsp_task = .{ .id = old_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = old_request, .rows = try gpa.dupe(u8, "old result") } }); + for (0..selection_pipe.Tasks.capacity) |index| { + const id: u32 = @intCast(index); + try std.testing.expect(st.pipe_tasks.add(.{ .id = id, .future = .{ .any_future = null, .result = {} } })); + st.inbox.push(.{ .pipe = .{ + .id = id, + .success = false, + .outputs = &.{}, + .failure = .{ .kind = .exit, .code = 1, .stderr = try gpa.dupe(u8, "old filter failure") }, + } }); + } + st.inbox.acceptReader(0, 23); + _ = st.inbox.pushOutput(0, 23, try gpa.dupe(u8, "old PTY output")); + core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); + try std.testing.expect(restoreCore(&st)); + try std.testing.expect(st.core != core); + try std.testing.expect(st.core.panes[0].?.serial > old_serial); + try std.testing.expectEqualStrings("saved body\n", st.core.panes[0].?.file.?.content); + try std.testing.expectEqualStrings("host configuration", marker); + try std.testing.expectEqual(@as(usize, 0), st.frame_len); + try std.testing.expect(!st.rotate_coasting); + try std.testing.expectEqual(@as(u32, 24), st.gens[0]); + try std.testing.expect(!st.file_watches.notify(0, old_watch)); + try std.testing.expect(st.file_watches.generations[0] > old_watch); + try std.testing.expectEqual(@as(usize, 0), st.inbox.len); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(!drainInbox(&st)); + try std.testing.expect(!st.cwd_stale[0]); + + st.core.lspRequest(0, .status, ""); + const new_request = st.core.lsp_ask.wait.?.id; + try std.testing.expect(new_request > old_request); + st.inbox.lsp_id = new_request; + st.inbox.lsp_task = .{ .id = new_request, .future = .{ .any_future = null, .result = {} } }; + st.inbox.push(.{ .lsp = .{ .id = new_request, .rows = &.{} } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.inbox.lsp_task == null); + try std.testing.expect(st.core.lsp_ask.wait == null); + + const pane = st.core.panes[0].?; + pane.body.cur_col = 4; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + st.core.update(.{ .key = .{ .cp = '|' } }); + st.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + st.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); + const pipe_id = st.core.pipe.wait.?.id; + try std.testing.expect(st.pipe_tasks.add(.{ .id = pipe_id, .future = .{ .any_future = null, .result = {} } })); + const output = try gpa.dupe(u8, "FRESH"); + const outputs = gpa.dupe([]u8, &.{output}) catch |err| { + gpa.free(output); + return err; + }; + st.inbox.push(.{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); + try std.testing.expect(drainInbox(&st)); + try std.testing.expect(st.core.pipe.wait == null); + try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); + try std.testing.expectEqualStrings("FRESH body\n", pane.file.?.content); +} + +test "mac Restore cancels a PTY reader waiting for output capacity" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var st: State = .{ + .gpa = gpa, + .threaded = undefined, + .io = io, + .core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }), + .runtime = .{}, + .config_arena = .init(gpa), + .prompt_rcs = .{}, + .inbox = .{ .gpa = gpa, .lsp_allocator = gpa, .io = io }, + }; + defer st.core.deinit(); + defer st.config_arena.deinit(); + defer st.file_watches.deinit(gpa); + defer st.inbox.close(); + try dump.dumpState(st.core); + try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? }); + while (st.core.nextEffect()) |_| {} + st.inbox.acceptReader(1, 1); + for (0..Inbox.output_capacity) |_| _ = st.inbox.pushOutput(1, 1, try gpa.dupe(u8, "retained output")); + const child = try host_io.forkShell(null, 0, &st.prompt_rcs, "/bin/sh", "", 12, 40); + st.gens[0] = 1; + st.ptys[0] = .{ .file = child.file, .pid = child.pid, .gen = 1, .reader = .{ .any_future = null, .result = {} } }; + defer { + if (st.ptys[0]) |pt| if (pt.pid == child.pid) reap(&st, 0); + if (libc.waitpid(child.pid, null, posix.W.NOHANG) == 0) { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + } + } + startReader(&st, &st.ptys[0].?, 0); + try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); + for (0..1000) |_| { + if (st.inbox.space.state.load(.acquire).waiters != 0) break; + try io.sleep(.fromMilliseconds(1), .awake); + } + try std.testing.expectEqual(@as(u16, 1), st.inbox.space.state.load(.acquire).waiters); + var command: [512]u8 = undefined; + st.core.update(.{ .command = try std.fmt.bufPrint(&command, "Restore .zig-cache/tmp/{s}/restore.zon", .{tmp.sub_path}) }); + try std.testing.expect(restoreCore(&st)); + try std.testing.expect(st.ptys[0] == null); + try std.testing.expectEqual(@as(usize, 0), st.inbox.len); + try std.testing.expectEqual(@as(u16, 0), st.inbox.space.state.load(.acquire).waiters); + st.inbox.acceptReader(0, st.gens[0]); + _ = st.inbox.pushOutput(0, st.gens[0], try gpa.dupe(u8, "fresh output")); + var batch = st.inbox.take(); + defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); + try std.testing.expectEqual(@as(usize, 1), batch.len); + try std.testing.expectEqualStrings("fresh output", batch.items[0].output.bytes); +} + +test "pardes.h declares every export the way it is defined" { + const c = @import("pardes.h"); + try expectSameAbi(@TypeOf(c.pardes_init), @TypeOf(pardes_init)); + try expectSameAbi(@TypeOf(c.pardes_deinit), @TypeOf(pardes_deinit)); + try expectSameAbi(@TypeOf(c.pardes_tick), @TypeOf(pardes_tick)); + try expectSameAbi(@TypeOf(c.pardes_animation_tick), @TypeOf(pardes_animation_tick)); + try expectSameAbi(@TypeOf(c.pardes_should_quit), @TypeOf(pardes_should_quit)); + try expectSameAbi(@TypeOf(c.pardes_animating), @TypeOf(pardes_animating)); + try expectSameAbi(@TypeOf(c.pardes_gui_tagline_font_percent), @TypeOf(pardes_gui_tagline_font_percent)); + try expectSameAbi(@TypeOf(c.pardes_tagline_band_offset), @TypeOf(pardes_tagline_band_offset)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_px), @TypeOf(pardes_topbar_pane_border_px)); + try expectSameAbi(@TypeOf(c.pardes_tag_active_bg), @TypeOf(pardes_tag_active_bg)); + try expectSameAbi(@TypeOf(c.pardes_tagline_origin_col), @TypeOf(pardes_tagline_origin_col)); + try expectSameAbi(@TypeOf(c.pardes_grid_col_at), @TypeOf(pardes_grid_col_at)); + try expectSameAbi(@TypeOf(c.pardes_topbar_pane_border_rgb), @TypeOf(pardes_topbar_pane_border_rgb)); + try expectSameAbi(@TypeOf(c.pardes_tagline_bg), @TypeOf(pardes_tagline_bg)); + try expectSameAbi(@TypeOf(c.pardes_fallback_font_count), @TypeOf(pardes_fallback_font_count)); + try expectSameAbi(@TypeOf(c.pardes_fallback_font_name), @TypeOf(pardes_fallback_font_name)); + try expectSameAbi(@TypeOf(c.pardes_scene), @TypeOf(pardes_scene)); + try expectSameAbi(@TypeOf(c.pardes_postprocessor_unavailable), @TypeOf(pardes_postprocessor_unavailable)); + try expectSameAbi(@TypeOf(c.pardes_panel_animation_failed), @TypeOf(pardes_panel_animation_failed)); + try expectSameAbi(@TypeOf(c.pardes_key), @TypeOf(pardes_key)); + try expectSameAbi(@TypeOf(c.pardes_paste), @TypeOf(pardes_paste)); + try expectSameAbi(@TypeOf(c.pardes_mouse), @TypeOf(pardes_mouse)); + try expectSameAbi(@TypeOf(c.pardes_pointer_leave), @TypeOf(pardes_pointer_leave)); + try expectSameAbi(@TypeOf(c.pardes_watch_changed), @TypeOf(pardes_watch_changed)); + try expectSameAbi(@TypeOf(c.pardes_scroll), @TypeOf(pardes_scroll)); + try expectSameAbi(@TypeOf(c.pardes_scroll_begin), @TypeOf(pardes_scroll_begin)); + try expectSameAbi(@TypeOf(c.pardes_scroll_end), @TypeOf(pardes_scroll_end)); + try expectSameAbi(@TypeOf(c.pardes_rotate), @TypeOf(pardes_rotate)); + try expectSameAbi(@TypeOf(c.pardes_rotate_end), @TypeOf(pardes_rotate_end)); + try expectSameAbi(@TypeOf(c.pardes_command), @TypeOf(pardes_command)); + try expectSameAbi(@TypeOf(c.pardes_resize), @TypeOf(pardes_resize)); + try expectSameAbi(@TypeOf(c.pardes_frame), @TypeOf(pardes_frame)); + try expectSameAbi(@TypeOf(c.pardes_frame_cells), @TypeOf(pardes_frame_cells)); + try expectSameAbi(@TypeOf(c.pardes_frame_previous_cells), @TypeOf(pardes_frame_previous_cells)); + try expectSameAbi(@TypeOf(c.pardes_frame_changed_cells), @TypeOf(pardes_frame_changed_cells)); + try expectSameAbi(@TypeOf(c.pardes_frame_cols), @TypeOf(pardes_frame_cols)); + try expectSameAbi(@TypeOf(c.pardes_frame_rows), @TypeOf(pardes_frame_rows)); + try expectSameAbi(@TypeOf(c.pardes_frame_images), @TypeOf(pardes_frame_images)); + try expectSameAbi(@TypeOf(c.pardes_frame_image_list), @TypeOf(pardes_frame_image_list)); + try expectSameAbi(@TypeOf(c.pardes_frame_panel_tracks), @TypeOf(pardes_frame_panel_tracks)); + try expectSameAbi(@TypeOf(c.pardes_frame_panel_track_list), @TypeOf(pardes_frame_panel_track_list)); + try expectSameAbi(@TypeOf(c.pardes_frame_presented), @TypeOf(pardes_frame_presented)); + try expectSameAbi(@TypeOf(c.pardes_cursor_x), @TypeOf(pardes_cursor_x)); + try expectSameAbi(@TypeOf(c.pardes_cursor_y), @TypeOf(pardes_cursor_y)); + try expectSameAbi(@TypeOf(c.pardes_cursor_bar), @TypeOf(pardes_cursor_bar)); + try expectSameAbi(@TypeOf(c.pardes_pointer_shape), @TypeOf(pardes_pointer_shape)); + try expectSameAbi(@TypeOf(c.pardes_mouse_pixel), @TypeOf(pardes_mouse_pixel)); + try expectSameAbi(@TypeOf(c.pardes_row_metrics), @TypeOf(pardes_row_metrics)); + try expectSameAbi(@TypeOf(c.pardes_tag_text_inset), @TypeOf(pardes_tag_text_inset)); + try expectSameAbi(@TypeOf(c.pardes_grip_columns), @TypeOf(pardes_grip_columns)); + try expectSameAbi(@TypeOf(c.pardes_tag_layer_limit), @TypeOf(pardes_tag_layer_limit)); + try expectSameAbi(@TypeOf(c.pardes_tag_layer_value), @TypeOf(pardes_tag_layer_value)); + try expectSameAbi(@TypeOf(c.pardes_tag_layer_cells), @TypeOf(pardes_tag_layer_cells)); + try expectSameAbi(@TypeOf(c.pardes_body_layer_value), @TypeOf(pardes_body_layer_value)); + try expectSameAbi(@TypeOf(c.pardes_body_layer_cells), @TypeOf(pardes_body_layer_cells)); + try expectSameAbi(@TypeOf(c.pardes_take_haptic), @TypeOf(pardes_take_haptic)); + try expectSameAbi(@TypeOf(c.pardes_font_take), @TypeOf(pardes_font_take)); + try expectSameAbi(@TypeOf(c.pardes_font_observe), @TypeOf(pardes_font_observe)); + try expectSameAbi(@TypeOf(c.pardes_font_ack), @TypeOf(pardes_font_ack)); + try expectSameAbi(@TypeOf(c.pardes_font_reject), @TypeOf(pardes_font_reject)); + try expectSameAbi(@TypeOf(c.pardes_active_path), @TypeOf(pardes_active_path)); + try expectSameAbi(@TypeOf(c.pardes_active_dirty), @TypeOf(pardes_active_dirty)); + try expectSameAbi(@TypeOf(c.pardes_theme_bg), @TypeOf(pardes_theme_bg)); + try expectSameAbi(@TypeOf(c.pardes_window_opacity), @TypeOf(pardes_window_opacity)); +} + +test "pardes.h matches the Zig boundary" { + const c = @import("pardes.h"); + const expectEqual = std.testing.expectEqual; + + try expectEqual(@sizeOf(c.pardes_cell_s), @sizeOf(Cell)); + try expectEqual(@offsetOf(c.pardes_cell_s, "text"), @offsetOf(Cell, "text")); + try expectEqual(@offsetOf(c.pardes_cell_s, "fg"), @offsetOf(Cell, "fg")); + try expectEqual(@offsetOf(c.pardes_cell_s, "bg"), @offsetOf(Cell, "bg")); + try expectEqual(@offsetOf(c.pardes_cell_s, "attrs"), @offsetOf(Cell, "attrs")); + try expectEqual(@offsetOf(c.pardes_cell_s, "len"), @offsetOf(Cell, "len")); + try expectEqual(@offsetOf(c.pardes_cell_s, "flags"), @offsetOf(Cell, "flags")); + try expectEqual(@sizeOf(c.pardes_scene_s), @sizeOf(Scene)); + inline for (@typeInfo(Scene).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_scene_s, name), @offsetOf(Scene, name)); + try expectEqual(@sizeOf(c.pardes_panel_box_s), @sizeOf(PanelBox)); + inline for (@typeInfo(PanelBox).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_box_s, name), @offsetOf(PanelBox, name)); + try expectEqual(@sizeOf(c.pardes_panel_track_s), @sizeOf(PanelTrack)); + inline for (@typeInfo(PanelTrack).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_panel_track_s, name), @offsetOf(PanelTrack, name)); + try expectEqual(@sizeOf(c.pardes_image_s), @sizeOf(Image)); + inline for (@typeInfo(Image).@"struct".field_names) |name| + try expectEqual(@offsetOf(c.pardes_image_s, name), @offsetOf(Image, name)); + try expectEqual(@sizeOf(c.pardes_runtime_s), @sizeOf(Runtime)); + + try expectEqual(@as(u32, c.PARDES_COLOR_DEFAULT), color_default); + try expectEqual(@as(u32, c.PARDES_COLOR_INDEXED), color_indexed); + try expectEqual(@as(u8, c.PARDES_CELL_DEFAULT), cell_flag_default); + try expectEqual(@as(u8, c.PARDES_CELL_TAGLINE), cell_flag_tagline); + try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); + try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); + + try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter); + try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape); + try expectEqual(@as(u21, c.PARDES_KEY_TAB), pardes.Key.tab); + try expectEqual(@as(u21, c.PARDES_KEY_BACKSPACE), pardes.Key.backspace); + try expectEqual(@as(u21, c.PARDES_KEY_UP), pardes.Key.up); + try expectEqual(@as(u21, c.PARDES_KEY_DOWN), pardes.Key.down); + try expectEqual(@as(u21, c.PARDES_KEY_LEFT), pardes.Key.left); + try expectEqual(@as(u21, c.PARDES_KEY_RIGHT), pardes.Key.right); + try expectEqual(@as(u21, c.PARDES_KEY_HOME), pardes.Key.home); + try expectEqual(@as(u21, c.PARDES_KEY_END), pardes.Key.end); + try expectEqual(@as(u21, c.PARDES_KEY_PAGE_UP), pardes.Key.page_up); + try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down); + try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete); + + try expectEqual(c.PARDES_MOUSE_LEFT, @backingInt(pardes.Mouse.Button.left)); + try expectEqual(c.PARDES_MOUSE_MIDDLE, @backingInt(pardes.Mouse.Button.middle)); + try expectEqual(c.PARDES_MOUSE_RIGHT, @backingInt(pardes.Mouse.Button.right)); + try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @backingInt(pardes.Mouse.Button.wheel_up)); + try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @backingInt(pardes.Mouse.Button.wheel_down)); + try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @backingInt(pardes.Mouse.Button.wheel_left)); + try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @backingInt(pardes.Mouse.Button.wheel_right)); + try expectEqual(c.PARDES_MOUSE_NONE, @backingInt(pardes.Mouse.Button.none)); + try expectEqual(c.PARDES_MOUSE_BACK, @backingInt(pardes.Mouse.Button.back)); + try expectEqual(c.PARDES_MOUSE_FORWARD, @backingInt(pardes.Mouse.Button.forward)); + try expectEqual(c.PARDES_MOUSE_PRESS, @backingInt(pardes.Mouse.Kind.press)); + try expectEqual(c.PARDES_MOUSE_RELEASE, @backingInt(pardes.Mouse.Kind.release)); + try expectEqual(c.PARDES_MOUSE_MOTION, @backingInt(pardes.Mouse.Kind.motion)); + try expectEqual(c.PARDES_MOUSE_DRAG, @backingInt(pardes.Mouse.Kind.drag)); + + try expectEqual(c.PARDES_HAPTIC_NONE, @backingInt(pardes.Haptic.none)); + try expectEqual(c.PARDES_HAPTIC_EXEC, @backingInt(pardes.Haptic.exec)); + try expectEqual(c.PARDES_HAPTIC_LOOK, @backingInt(pardes.Haptic.look)); + + try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_ITALIC), encodeAttrs(.{ .italic = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_BLINK), encodeAttrs(.{ .blink = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_REVERSE), encodeAttrs(.{ .reverse = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_INVISIBLE), encodeAttrs(.{ .invisible = true })); + try expectEqual(@as(u16, c.PARDES_ATTR_STRIKETHROUGH), encodeAttrs(.{ .strikethrough = true })); + try expectEqual( + @as(u16, c.PARDES_UL_CURLY) << c.PARDES_ATTR_UL_SHIFT, + encodeAttrs(.{ .ul = .curly }), + ); + + try expectEqual(@as(u8, 0), encodeCellFlags(false, .body, false)); + try expectEqual(cell_flag_hover, encodeCellFlags(false, .body, true)); + try expectEqual(cell_flag_tagline, encodeCellFlags(false, .tagline, false)); + try expectEqual(cell_flag_default | cell_flag_tagline, encodeCellFlags(true, .tagline, false)); + try expectEqual(pardes.config.gui_tagline_font_percent, pardes_gui_tagline_font_percent()); +} + +test "mac panel ABI has the documented compact byte layout" { + try std.testing.expectEqual(@as(usize, 16), @sizeOf(PanelBox)); + try std.testing.expectEqual(@as(usize, 48), @sizeOf(PanelTrack)); + try std.testing.expectEqual(@as(usize, 0), @offsetOf(PanelTrack, "serial")); + try std.testing.expectEqual(@as(usize, 4), @offsetOf(PanelTrack, "pane")); + try std.testing.expectEqual(@as(usize, 5), @offsetOf(PanelTrack, "phase")); + try std.testing.expectEqual(@as(usize, 6), @offsetOf(PanelTrack, "effect")); + try std.testing.expectEqual(@as(usize, 7), @offsetOf(PanelTrack, "motion")); + try std.testing.expectEqual(@as(usize, 8), @offsetOf(PanelTrack, "frame")); + try std.testing.expectEqual(@as(usize, 10), @offsetOf(PanelTrack, "frame_count")); + try std.testing.expectEqual(@as(usize, 12), @offsetOf(PanelTrack, "from")); + try std.testing.expectEqual(@as(usize, 28), @offsetOf(PanelTrack, "to")); +} + +test "colors encode to the three tags the host decodes" { + const expectEqual = std.testing.expectEqual; + try expectEqual(@as(u32, 0x01000000), encodeColor(.default)); + try expectEqual(@as(u32, 0x02000021), encodeColor(.{ .index = 33 })); + try expectEqual(@as(u32, 0x00112233), encodeColor(.{ .rgb = .{ 0x11, 0x22, 0x33 } })); +} + +test "sub-row scroll spends whole notches and keeps the remainder" { + const expectEqual = std.testing.expectEqual; + var lag: f32 = 0; + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25)); + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25)); + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25)); + try expectEqual(@as(i32, 1), takeScrollTicks(&lag, 0.25)); + try expectEqual(@as(f32, 0), lag); + + try expectEqual(@as(i32, -2), takeScrollTicks(&lag, -2.5)); + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, 0.25)); + + lag = 0; + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, std.math.nan(f32))); + try expectEqual(@as(i32, 0), takeScrollTicks(&lag, std.math.inf(f32))); + try expectEqual(@as(f32, 0), lag); + try expectEqual(@as(i32, 256), takeScrollTicks(&lag, 1e9)); +} + +test "trackpad rotation spends whole search steps and keeps the remainder" { + const expectEqual = std.testing.expectEqual; + var lag: f32 = 0; + try expectEqual(@as(i32, 0), takeRotationNotches(&lag, 7)); + try expectEqual(@as(i32, 1), takeRotationNotches(&lag, 5)); + try expectEqual(@as(f32, 2), lag); + + try expectEqual(@as(i32, -1), takeRotationNotches(&lag, -12)); + try expectEqual(@as(f32, 0), lag); + + lag = 0; + try expectEqual(@as(i32, 18), takeRotationNotches(&lag, 180)); + + lag = 0; + try expectEqual(@as(i32, 0), takeRotationNotches(&lag, std.math.nan(f32))); + try expectEqual(@as(i32, 0), takeRotationNotches(&lag, -std.math.inf(f32))); + try expectEqual(@as(f32, 0), lag); + try expectEqual(@as(i32, 64), takeRotationNotches(&lag, 1e9)); +} + +test "the dial flings in proportion to the release, and not at all when placed" { + try std.testing.expectEqual(@as(f32, 0), rotationFling(0)); + try std.testing.expectEqual(@as(f32, 0), rotationFling(40)); + try std.testing.expectEqual(@as(f32, 0), rotationFling(rotation_fling_floor)); + try std.testing.expectEqual(@as(f32, 0), rotationFling(rotation_fling_floor + 5)); + + try std.testing.expectEqual(@as(f32, 130), rotationFling(200)); + try std.testing.expectEqual(@as(f32, -130), rotationFling(-200)); + + try std.testing.expectEqual(rotation_fling_max, rotationFling(100_000)); + try std.testing.expectEqual(-rotation_fling_max, rotationFling(-100_000)); + + const travel = struct { + fn of(speed: f32) f32 { + return @abs(rotationFling(speed)) * rotation_fling_step / (1 - rotation_fling_decay); + } + }.of; + try std.testing.expect(travel(200) / rotation_notch_degrees < 5); + try std.testing.expect(travel(200) / rotation_notch_degrees >= 3); + try std.testing.expect(travel(100_000) / rotation_notch_degrees < 12); + try std.testing.expect(travel(100_000) / rotation_notch_degrees > 8); +} + +test "a live session renders on the draw" { + try std.testing.expectEqual(@as(c_int, 0), pardes_init(null, 80, 24)); + defer pardes_deinit(); + const st = &state.?; + + try std.testing.expect(st.ptys[0] != null); + _ = pardes_tick(); + _ = pardes_tick(); + try std.testing.expectEqual(@as(u16, 0), pardes_frame_cols()); + try std.testing.expect(pardes_frame_cells() == null); + + try std.testing.expectEqual(@as(u32, 80 * 24), pardes_frame()); + try std.testing.expectEqual(@as(u16, 80), pardes_frame_cols()); + try std.testing.expectEqual(@as(u16, 24), pardes_frame_rows()); + try std.testing.expect(pardes_frame_cells() != null); +} + +test "mac row metrics ABI preserves PDF cell dimensions and the unrendered grid" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer core.deinit(); + state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} }; + defer { + state.?.config_arena.deinit(); + state = null; + } + core.view().cell_pixels = .{ .w = 22, .h = 39 }; + const pixels = core.view().cell_pixels; + try std.testing.expectEqual(@as(u16, 0), core.surface.cols); + pardes_row_metrics(22, 39, 17, 30); + try std.testing.expectEqualDeep(pixels, core.view().cell_pixels); + try std.testing.expectEqual(@as(u16, 80), core.view().screen_w); + try std.testing.expectEqual(@as(u16, 24), core.view().screen_h); + try std.testing.expectEqualDeep(pardes.RowMetrics{ .body_w = 22, .body_h = 39, .tagline_w = 17, .tagline_h = 30 }, core.view().row_metrics); +} + +test "mac tag layer ABI preserves logical capacity and physical grip" { + const gpa = std.testing.allocator; + const core = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 8, .rows = 3 }); + defer core.deinit(); + state = .{ .gpa = gpa, .threaded = undefined, .io = std.testing.io, .core = core, .runtime = .{}, .config_arena = .init(gpa), .prompt_rcs = .{} }; + defer { + for (state.?.tag_cells) |cells| gpa.free(cells); + state.?.config_arena.deinit(); + state = null; + } + var logical: [12]pardes.Cell = @splat(.{}); + logical[11].text[0] = 'Z'; + logical[11].len = 1; + logical[11].default = false; + core.surface.tag_layers[0] = .{ .kind = .pane, .id = 1, .serial = 42, .viewport = .{ .x = 2, .y = 1, .w = 6, .h = 1 }, .cols = 12, .rows = 1, .cells = &logical, .bg = .{ 0x12, 0x34, 0x56 }, .cursor = .{ .x = 11, .y = 0, .bar = true } }; + defer core.surface.tag_layers[0] = .{}; + try std.testing.expectEqual(@as(u32, 12), pardes_tag_layer_value(0, 0)); + try std.testing.expectEqual(@as(u32, 0x123456), pardes_tag_layer_value(0, 10)); + try std.testing.expectEqual(@as(u32, 0), pardes_tag_layer_value(0, 11)); + const border = core.chromeTheme().border; + const border_rgb = @as(u32, border[0]) << 16 | @as(u32, border[1]) << 8 | border[2]; + try std.testing.expectEqual(border_rgb, pardes_tag_layer_value(0, 12)); + try std.testing.expectEqual(pardes.config.gui_topbar_pane_border_rgb orelse border, .{ + @as(u8, @intCast(pardes_topbar_pane_border_rgb() >> 16)), + @as(u8, @truncate(pardes_topbar_pane_border_rgb() >> 8)), + @as(u8, @truncate(pardes_topbar_pane_border_rgb())), + }); + try std.testing.expectEqual(@as(u32, 11), pardes_tag_layer_value(0, 8)); + try std.testing.expectEqual(@as(u8, 'Z'), pardes_tag_layer_cells(0).?[11].text[0]); + var canonical: [24]Cell = @splat(encodeCell(.{ .text = .{ 'G', 0, 0, 0, 0, 0, 0 }, .len = 1, .default = false })); + var source: [24]pardes.Cell = @splat(.{}); + blankTagCells(&canonical, 8, 3, &source, &core.surface.tag_layers); + try std.testing.expectEqual(@as(u8, 'G'), canonical[9].text[0]); + try std.testing.expectEqual(@as(u8, 'G'), canonical[18].text[0]); + try std.testing.expectEqual(encodeCell(.{}).len, canonical[10].len); +} diff --git a/runtime/main.zig b/runtime/main.zig new file mode 100644 index 00000000..85b3e249 --- /dev/null +++ b/runtime/main.zig @@ -0,0 +1,1926 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const pardes = @import("core"); +const ninep_io = @import("runtime").ninep_io; +const daemon = @import("runtime").daemon; +const upgrade = @import("runtime").upgrade; +const cloud9 = @import("cloud9"); + +pub const std_options_debug_threaded_io: ?*std.Io.Threaded = std.Io.Threaded.global_single_threaded; +pub const std_options_debug_io: std.Io = std_options_debug_threaded_io.?.io(); + +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +// +// FreeBSD answers a write to a terminal that is gone with ENXIO, an errno std +// does not expect: a Debug build traced it to stderr, that same terminal, +// and recursed until the stack ran out (a session whose ssh dropped hung). +pub const std_options: std.Options = .{ + .logFn = logFn, + .signal_stack_size = 64 * 1024, + .unexpected_error_tracing = (std.Options{}).unexpected_error_tracing and builtin.os.tag != .freebsd, +}; + +fn logFn( + comptime level: std.log.Level, + comptime scope: @EnumLiteral(), + comptime format: []const u8, + args: anytype, +) void { + if (scope != .gui and std.c.getenv("PARDES_LOG") == null) return; + std.log.defaultLog(level, scope, format, args); +} + +pub const panic = std.debug.FullPanic(struct { + fn call(msg: []const u8, ret_addr: ?usize) noreturn { + if (!recovering.swap(true, .seq_cst)) { + pardes.replica.dying(); + @import("vaxis").recover(); + } + @import("runtime").crash.record(msg); + std.debug.defaultPanic(msg, ret_addr); + } +}.call); + +var recovering: std.atomic.Value(bool) = .init(false); + +pub const debug = struct { + pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn { + if (!recovering.swap(true, .seq_cst)) { + pardes.replica.dying(); + @import("vaxis").recover(); + } + return std.debug.defaultHandleSegfault(addr, name, opt_ctx); + } +}; + +/// `pardes -` inside a session: `text`, stdin as it came, escapes and all, +/// into a new +Pager of the directory (/pager): +/// written after the directory on that one open, the session parses it +/// (Term.page) and puts it in as one undo step, left clean. A text the +/// session would not take is never lost: it goes to stderr, a terminal, +/// with why, and the exit is 1. +fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { + const Fail = struct { + fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { + var words_buf: [128]u8 = undefined; + const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf); + var buf: [512]u8 = undefined; + const head = std.fmt.bufPrint(&buf, "pardes: -: {s}: {s}; the text follows\n", .{ what, why }) catch "pardes: -: refused; the text follows\n"; + std.Io.File.stderr().writeStreamingAll(o, head) catch {}; + std.Io.File.stderr().writeStreamingAll(o, t) catch {}; + std.process.exit(1); + } + }; + // The pane's directory: this one, unless its name could not be one line + // of a ctl (a newline, a control byte): then the session's. + var cwd_buf: [4096]u8 = undefined; + const cwd: []const u8 = cwd_buf[0 .. std.process.currentPath(io, &cwd_buf) catch 0]; + // ...or the session's when this one may not be written (`git log` in + // /usr/src), which /pager refuses: the text is paged all the same. + const plain = for (cwd) |c| { + if (c < ' ' or c == 0x7f) break false; + } else !pardes.filesystem.deniedAbove(cwd); + var line_buf: [cwd_buf.len + 1]u8 = undefined; + const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch unreachable; // a cwd out of cwd_buf and "\n" fit + // Its serial read back on the open that asked, once the text is in: + // another client's exec meanwhile can never send it into that + // client's pane. + const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err); + _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); +} + +/// Stdin to its end, as it came (its escapes are the session's to parse, +/// Term.page), at most a file's limit, a longer one cut there and said so +/// at its end. +fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { + const limit = pardes.memory.limits.max_file_bytes; + var raw: std.ArrayList(u8) = .empty; + var chunk: [64 * 1024]u8 = undefined; + var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); + // One byte past the limit says there is more. + stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { + error.StreamTooLong => { + raw.shrinkRetainingCapacity(limit); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); + }, + else => |e| return e, + }; + return raw.toOwnedSlice(gpa); +} + +/// A forwarding failure in words, never an error's name: the ones this +/// file raises said outright, any other as its name's words (`NotFound`, +/// `not found`), a dial's as Messages says it. +fn forwardWords(err: anyerror, buf: []u8) []const u8 { + return switch (err) { + error.NotOneLine => "a file name is one line, and this one holds a newline", + error.NotAFileName => "names a directory, not a file", + error.NoWorkingDirectory => "this shell's working directory is gone", + error.DirectoryNotWritable => "permission denied: its directory may not be read or written, so it could never be saved", + error.NotAPaneAddress => "not a pane address: @p and a pane's number", + error.NoSuchPane => "this session has no such pane", + else => if (pardes.Messages.dialReason(err)) |why| why else words: { + var n: usize = 0; + for (@errorName(err), 0..) |c, i| { + if (n + 2 > buf.len) break; + if (std.ascii.isUpper(c) and i > 0) { + buf[n] = ' '; + n += 1; + } + buf[n] = std.ascii.toLower(c); + n += 1; + } + break :words buf[0..n]; + }, + }; +} + +/// `--wait` after a forwarded look, as plan9port's E reads acme's log: the +/// pane `path` landed in (the one it already had, if open), then /log +/// followed on one connection until that pane's `del` -- exit 0 -- or the +/// connection ends with the session -- exit 1. +fn waitForDel(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, known: ?u32) noreturn { + // The pane this launch made (a name not there yet), or the one its + // look answered, is known by its serial; one the look answered none + // for is found by its file. Found by none after the look went there, + // it was closed already: that is the end being waited for, not a + // failure (a pane closed between the look and this read made `--wait` + // exit 1 before). + const serial = known orelse found: { + const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); + defer gpa.free(first); + break :found paneShowing(first, path) orelse std.process.exit(0); + }; + const Wait = struct { + gpa: std.mem.Allocator, + dial: []const u8, + serial: u32, + /// Deleted between the look and the follow: /index, read once the + /// follow stands, says so, and a `del` after it is followed. + fn gone(w: *const @This()) bool { + const index = ninep_io.Client.read(w.gpa, w.dial, "/index", "/index") catch return false; + defer w.gpa.free(index); + return !hasPane(index, w.serial); + } + fn deleted(w: *const @This(), bytes: []const u8) bool { + return isDel(bytes, w.serial); + } + }; + const w: Wait = .{ .gpa = gpa, .dial = dial, .serial = serial }; + ninep_io.Client.follow(dial, "/log", "follow new", &w, Wait.gone, Wait.deleted) catch std.process.exit(1); + std.process.exit(0); +} + +/// Whether log records `bytes` hold `del <serial> ...`. +fn isDel(bytes: []const u8, serial: u32) bool { + var records = std.mem.splitScalar(u8, bytes, '\n'); + while (records.next()) |rec| { + if (!std.mem.startsWith(u8, rec, "del ")) continue; + const word = rec[4 .. std.mem.indexOfScalarPos(u8, rec, 4, ' ') orelse rec.len]; + if ((std.fmt.parseInt(u32, word, 10) catch continue) == serial) return true; + } + return false; +} + +/// The serial of /index's first row named `path` (`serial kind dirty name col`). +fn paneShowing(index: []const u8, path: []const u8) ?u32 { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + var words = std.mem.splitScalar(u8, row, ' '); + const serial = std.fmt.parseInt(u32, words.first(), 10) catch continue; + _ = words.next() orelse continue; // kind + _ = words.next() orelse continue; // dirty + const rest = words.rest(); + const end = std.mem.lastIndexOfScalar(u8, rest, ' ') orelse continue; + if (std.mem.eql(u8, rest[0..end], path)) return serial; + } + return null; +} + +fn hasPane(index: []const u8, serial: u32) bool { + var rows = std.mem.splitScalar(u8, index, '\n'); + while (rows.next()) |row| { + const first = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]; + if ((std.fmt.parseInt(u32, first, 10) catch continue) == serial) return true; + } + return false; +} + +fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + die(io, fmt ++ "\nTry 'pardes help', or 'pardes help new' for the flags.", args); +} + +/// `pardes: <words>` on stderr, and exit 1. +fn die(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { + var buf: [8192]u8 = undefined; + const line = std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\n", args) catch "pardes: refused\n"; + std.Io.File.stderr().writeStreamingAll(io, line) catch {}; + std.process.exit(1); +} + +/// The second line is what a replica's build must share with its session's +/// (wire.zig `semantics`). +const version_text = upgrade.version_line ++ "\n" ++ std.fmt.comptimePrint("semantics {x:0>16}\n", .{@import("core").wire.semantics}); + +const nested_text = + \\pardes: this shell is already inside pardes, and a pardes inside a pardes + \\is spicy. Name a file or a directory and the outer session opens it, or + \\pass --nested if you really want a second one in here. + \\ +; + +// ---- the command line ---- +// +// `pardes [flags] [FILE]` opens, starts or pages, as it always has; a first +// word that names a `Cmd` is that command instead (a file called so is +// `./ps`, or after `--`). `cmds` and `flags` are each both the parser and the +// help: `pardes help` prints them, and `pardes help --all` prints them whole +// with the tree's README, which is docs/typ/command-line.txt (the build's +// builtins-json step writes it; a test below says when it is stale). What a +// word or a file does is the tree's to say: `words`, `help WORD`, `help +// PATH`, `fs` and the completions read /commands and /README, from the +// session over 9P or, with none, from a core made in this process (`Here`). + +const Cmd = enum { ps, attach, kill, new, do, words, fs, help, completion, skill, version }; + +const Group = enum { Sessions, Words, Files, Self }; + +const Doc = struct { + group: Group, + args: []const u8 = "", + /// Its line on the first screen. + line: []const u8, + /// `pardes help CMD`: what it does. + doc: []const u8, + /// A command line and what it does, each. + examples: []const [2][]const u8, + see: []const u8 = "", +}; + +const cmds = std.EnumArray(Cmd, Doc).init(.{ + .ps = .{ + .group = .Sessions, + .line = "the daemon's sessions, their clients and shells", + .doc = + \\What the per-user daemon lists: each session with its name, pid, kind + \\(tty or gui) and whether it has a frontend of its own or is detached; + \\under it its clients and its shells; then the shells no session holds, + \\which Adopt takes. /sessions is the same list, read from inside a + \\session (where a session with a frontend says attached). + , + .examples = &.{.{ "pardes ps", "every session, client and shell" }}, + .see = "attach, kill, /sessions", + }, + .attach = .{ + .group = .Sessions, + .args = "[NAME]", + .line = "show a detached session here (HOST:NAME: over ssh)", + .doc = + \\Show a detached session here: in this terminal for pardes, a window + \\for pardes-gui. Bare, the one detached session (with none, the one + \\session). One with a frontend already, or of the other kind, is joined + \\as a client. HOST:NAME is a client of session NAME on another machine, + \\over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh + \\command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory, + \\if not this one's path); SOCK:NAME goes through a socket forwarded + \\already (a path, with a '/'). Returns when the session detaches or + \\ends. + , + .examples = &.{ + .{ "pardes attach", "the one detached session" }, + .{ "pardes attach notes", "the one started with --detach=notes" }, + .{ "pardes attach box:notes", "on host box, over ssh -L" }, + .{ "pardes attach /run/x.sock:notes", "through a socket forwarded already" }, + }, + .see = "ps, kill, new --detach, the Detach word", + }, + .kill = .{ + .group = .Sessions, + .args = "NAME", + .line = "end a session and its shells (--all: every one)", + .doc = + \\End session NAME (its --9p or --detach name, else its pid) and its + \\shells: TERM, then KILL 2 s later. Unsaved changes are lost. --all + \\ends every session and every shell the daemon keeps. + , + .examples = &.{ + .{ "pardes kill notes", "the session started with --detach=notes" }, + .{ "pardes kill --all", "every session and shell" }, + }, + .see = "ps, attach", + }, + .new = .{ + .group = .Sessions, + .args = "[flags] [FILE]", + .line = "start one: --detach=NAME --9p=NAME -n 3 (help new)", + .doc = + \\Start a session here, even in a pane of another: in this terminal for + \\pardes, a window for pardes-gui, or with --detach none until one + \\attaches. Bare `pardes` takes the same flags, and starts one unless + \\it is in a pane (where it hands its FILE to that session). + , + .examples = &.{ + .{ "pardes new", "a session here, its shell pane in tty mode" }, + .{ "pardes new --detach=notes", "one with no terminal, named notes" }, + .{ "pardes new -n 3 src/", "three shell panes in src/" }, + .{ "pardes new --mount=peer=notes", "with session notes under /n/peer" }, + }, + .see = "attach, kill, --nested", + }, + .do = .{ + .group = .Words, + .args = "WORD [ARG]", + .line = "run a builtin at this pane, or the session's: do Newcol", + .doc = + \\Write WORD and its ARG to the ctl that takes it, as the session's + \\/commands says: the root's /ctl for a session's word, a pane's + \\pane/N/ctl for a pane's, that pane being this shell's ($PARDES_PANE) + \\or -p N. A refusal prints the session's own words, and the exit is 1. + \\The session is -s NAME, else $PARDES_9P, else the only one running. + , + .examples = &.{ + .{ "pardes do Newcol", "an empty column" }, + .{ "pardes do Save -p 3", "save pane 3" }, + .{ "pardes do Edit ',x/foo/c/bar/' -p 3", "sam's Edit on pane 3" }, + .{ "pardes do Wrap -s notes", "at session notes" }, + }, + .see = "words, help WORD, /commands", + }, + .words = .{ + .group = .Words, + .args = "[GROUP]", + .line = "the builtins by group, or one group's: words column", + .doc = + \\The session's builtins, as its /commands lists them, grouped by the + \\first key after the leader (SPC f is file, SPC c column): with no key, + \\a setting, a session's word (its root ctl's) or a text word (a + \\pane's). An addon's words are the addon group. With no session, the + \\ones this build has. + , + .examples = &.{ + .{ "pardes words", "every builtin, by group" }, + .{ "pardes words column", "the column words" }, + }, + .see = "do, help WORD, /commands", + }, + .fs = .{ + .group = .Files, + .args = "VERB [PATH]", + .line = "ls read write ask follow stat help complete, on the session's tree", + .doc = + \\The session's file tree, through a 9P client in this binary: the + \\files a mount or 9p(1) reaches, with a refusal in the session's own + \\words (a mount says only EINVAL). With no session, ls, stat, help and + \\complete, and a read of README, commands or ctl, ask a core made in + \\this process; the rest are a running session's, and say so. + , + .examples = &.{ + .{ "pardes fs ls pane/1", "what a pane serves" }, + .{ "pardes fs read index", "a line per pane" }, + .{ "pardes fs write pane/3/ctl 'Edit ,x/foo/c/bar/'", "a write, refused in words" }, + .{ "pardes fs ask pane/3/pty/run make", "exit N, then the output" }, + .{ "pardes fs follow log follow", "events as they come" }, + }, + .see = "help PATH, /README", + }, + .help = .{ + .group = .Self, + .args = "[CMD|WORD|PATH]", + .line = "this, a command, a builtin, or a file of the tree", + .doc = + \\Bare, this map. A command: what it does, with examples. A builtin: + \\its /commands line, its key, and how to run it. A path of the tree: + \\what the tree's README says of it and of what is under it. --all: + \\every command's help and the README whole, as this build has them + \\(never a session's), which the reference prints. + , + .examples = &.{ + .{ "pardes help attach", "a command" }, + .{ "pardes help Newcol", "a builtin" }, + .{ "pardes help pane/3/addr", "a file of the tree" }, + }, + .see = "words, fs help", + }, + .completion = .{ + .group = .Self, + .args = "SHELL", + .line = "bash, fish or zsh", + .doc = + \\A completion script for SHELL, printed, never installed. It asks this + \\binary back for each word (`pardes completion -- WORDS`): commands, + \\the builtins after do, sessions after attach and kill, the tree's + \\paths after fs. + , + .examples = &.{ + .{ "pardes completion fish | source", "in fish, for this shell" }, + .{ "source <(pardes completion bash)", "in bash" }, + .{ "source <(pardes completion zsh)", "in zsh" }, + }, + }, + .skill = .{ + .group = .Self, + .line = "the guide an agent reads", + .doc = + \\The guide for an agent that drives pardes, from this binary, so it + \\matches what it runs: recipes and traps. What is there it leaves to + \\`pardes help`. + , + .examples = &.{.{ "pardes skill", "" }}, + }, + .version = .{ + .group = .Self, + .line = "this build, its session wire and its 9P", + .doc = + \\This build's version; the semantics a replica must share with its + \\session; the 9P its tree speaks. + , + .examples = &.{.{ "pardes version", "" }}, + }, +}); + +/// The flags of `pardes [flags] [FILE]` and `pardes new`, and the spellings +/// the commands had before (one release more). +const Flag = enum { @"--tty", @"-n", @"--tty-toggle", @"-l", @"--nested", @"--9p", @"--9p-tcp", @"--mount", @"--geometry", @"--detach", @"-w", @"--wait", @"--", @"--attach", @"--ps", @"--kill", @"--kill-all", @"-h", @"--help", @"--version" }; + +const FlagDoc = struct { + /// What follows it: ` COUNT` (the next argument, or after `=`), `=NAME` + /// (after `=` only), `[=NAME]` (maybe). + arg: []const u8 = "", + takes: enum { none, next, eq, maybe } = .none, + /// Empty: a short spelling of the flag after it, printed with it. + doc: []const u8 = "", + group: enum { session, open, old } = .session, +}; + +const flags = std.EnumArray(Flag, FlagDoc).init(.{ + .@"--tty" = .{ .doc = "start as one shell pane already in tty mode" }, + .@"-n" = .{ .arg = " COUNT", .takes = .next, .doc = "shell panes to start with: 1 (default) or 3 (classic); a FILE boots just that file" }, + .@"--tty-toggle" = .{ .arg = " KEY", .takes = .next, .doc = "Ctrl-KEY toggles tty and editor mode" }, + .@"-l" = .{ .arg = " DUMP", .takes = .next, .doc = "load a dump of another instance (see Dump)" }, + .@"--nested" = .{ .doc = "a session of its own in a pane of another, serving none of its children" }, + .@"--9p" = .{ .arg = "=NAME", .takes = .eq, .doc = "name the 9P socket (else the --detach name, else the pid); under $XDG_RUNTIME_DIR, else ~/.local/state/pardes: a directory of yours alone" }, + .@"--9p-tcp" = .{ .arg = "=tcp!IP!PORT", .takes = .eq, .doc = "also serve 9P there, a numeric address" }, + .@"--mount" = .{ .arg = "=NAME=DIAL", .takes = .eq, .doc = "a 9P session or Unix/TCP endpoint under /n/NAME; repeat for more; os and self are reserved" }, + .@"--geometry" = .{ .arg = "=WxH[+X+Y]", .takes = .eq, .doc = "the window's size in points, and where it goes where the display lets a window say (X11)" }, + .@"--detach" = .{ .arg = "[=NAME]", .takes = .maybe, .doc = "no terminal (no window) until one attaches; panes, shells and files stay; NAME (one path component) rather than the pid. One pardes --daemon per user lists them, for attach (PARDES_DAEMON=off: none)" }, + .@"-w" = .{ .group = .open }, + .@"--wait" = .{ .group = .open, .doc = "in a pane, hand FILE to its session and return once its pane is deleted: 0, or 1 if the session goes (EDITOR='pardes --wait')" }, + .@"--" = .{ .group = .open, .doc = "the end of the flags: pardes -- -name opens -name" }, + .@"--attach" = .{ .arg = "[=NAME]", .takes = .maybe, .group = .old, .doc = "pardes attach NAME" }, + .@"--ps" = .{ .group = .old, .doc = "pardes ps" }, + .@"--kill" = .{ .arg = "=NAME", .takes = .eq, .group = .old, .doc = "pardes kill NAME" }, + .@"--kill-all" = .{ .group = .old, .doc = "pardes kill --all" }, + .@"-h" = .{ .group = .old }, + .@"--help" = .{ .group = .old, .doc = "pardes help" }, + .@"--version" = .{ .group = .old, .doc = "pardes version" }, +}); + +const first_screen_head = + \\pardes: an editor, a terminal multiplexer, and the file tree that scripts both. + \\ + \\Usage: + \\ pardes [flags] [FILE[:LINE] | DIR | -] open, start a session, or page stdin + \\ pardes COMMAND [ARGS] [-s NAME] a file named like a command: pardes ./ps + \\ + \\Open: + \\ FILE[:LINE] open it; in a pane, in that pane's session + \\ -w, --wait FILE open it, return when its pane closes (EDITOR='pardes -w') + \\ - stdin into a +Pager, its colours kept + \\ DIR start in it + \\ +; + +const first_screen_tail = + \\ + \\Flags: + \\ -s, --session NAME the session to act on ($PARDES_9P, else the only one) + \\ -p N the pane, for do ($PARDES_PANE) + \\ + \\The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and + \\--version still work, for a release. + \\ +; + +/// The left column of the first screen and the flag lists. +const left_width = 23; + +fn writeFirstScreen(w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.writeAll(first_screen_head); + for (std.enums.values(Group)) |g| { + try w.print("\n{t}:\n", .{g}); + for (std.enums.values(Cmd)) |c| { + const d = cmds.get(c); + if (d.group != g) continue; + var buf: [64]u8 = undefined; + const left = std.fmt.bufPrint(&buf, "{t}{s}{s}", .{ c, if (d.args.len == 0) "" else " ", d.args }) catch unreachable; // the table's names fit + try w.print(" {s}", .{left}); + try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2); + try w.print("{s}\n", .{d.line}); + } + } + try w.writeAll(first_screen_tail); +} + +fn writeFlags(w: *std.Io.Writer, group: @FieldType(FlagDoc, "group")) std.Io.Writer.Error!void { + var short: ?Flag = null; + for (std.enums.values(Flag)) |f| { + const d = flags.get(f); + if (d.group != group) continue; + if (d.doc.len == 0) { + short = f; + continue; + } + var buf: [64]u8 = undefined; + const left = if (short) |s| + std.fmt.bufPrint(&buf, "{t}, {t}{s}", .{ s, f, d.arg }) catch unreachable // the table's names fit + else + std.fmt.bufPrint(&buf, "{t}{s}", .{ f, d.arg }) catch unreachable; // the table's names fit + short = null; + try w.print(" {s}", .{left}); + try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2); + try w.print("{s}\n", .{d.doc}); + } +} + +fn writeLeaf(w: *std.Io.Writer, c: Cmd) std.Io.Writer.Error!void { + const d = cmds.get(c); + try w.print("{s}\n\nUsage:\n pardes {t}{s}{s}\n", .{ d.doc, c, if (d.args.len == 0) "" else " ", d.args }); + switch (c) { + .new => { + try w.writeAll("\nFlags:\n"); + try writeFlags(w, .session); + try writeFlags(w, .open); + }, + .fs => try w.print("\n{s}", .{cloud9.verbs.usage}), + else => {}, + } + try w.writeAll("\nExamples:\n"); + for (d.examples) |e| { + try w.print(" {s}", .{e[0]}); + if (e[1].len != 0) { + try w.splatByteAll(' ', if (e[0].len < 37) 38 - e[0].len else 2); + try w.writeAll(e[1]); + } + try w.writeByte('\n'); + } + if (d.see.len != 0) try w.print("\nSee also: {s}\n", .{d.see}); +} + +/// Everything: the first screen, every command's help, the old spellings +/// and the tree's README, as this build has them. +fn writeHelpAll(w: *std.Io.Writer, t: *Tree) !void { + try writeFirstScreen(w); + for (std.enums.values(Cmd)) |c| { + try w.print("\n== pardes help {t}\n\n", .{c}); + try writeLeaf(w, c); + } + try w.writeAll("\n== the old spellings\n\n"); + try writeFlags(w, .old); + try w.writeAll("\n== pardes help /: the tree's README\n\n"); + try t.f.readFile("README", w); +} + +/// A core made in this process and served on one end of a socket pair, an +/// `Fsys` on the other: with no session, `help`, `words`, `completion` and +/// `fs` ask the same tree a session serves, through the same client. Never +/// stepped and never performing an effect: no shell, no file, no socket. +const Here = struct { + const Engine = cloud9.fs.Server(pardes.ctlfs, .{ .fid_capacity = 32, .name_capacity = 255, .park_data_max = @import("runtime").ninep.msize - 23, .slot_capacity = 1 }); + core: *pardes.Pardes, + engine: Engine, + fd: c_int, + in: [@import("runtime").ninep.msize]u8, + out: [2 * @import("runtime").ninep.msize]u8, + buf: [@import("runtime").ninep.msize]u8, + + /// Answers what comes until the other end hangs up. A request the core + /// parks (a read of /log) stays parked: the client's deadline ends it. + fn serve(h: *Here) void { + while (true) { + const got = std.c.read(h.fd, &h.buf, h.buf.len); + if (got <= 0) return; + var bytes: []const u8 = h.buf[0..@intCast(got)]; + while (true) { + bytes = bytes[h.engine.push(bytes)..]; + while (h.engine.next()) |req| { + const r = h.core.serveFs(req); + h.engine.reply(&r, h.core.fsPayload(r)); + } + const out = h.engine.output(); + var sent: usize = 0; + while (sent < out.len) { + const n = std.c.write(h.fd, out[sent..].ptr, out.len - sent); + if (n <= 0) return; + sent += @intCast(n); + } + h.engine.wrote(out.len); + if (bytes.len == 0) break; + } + } + } +}; + +extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]std.c.fd_t) c_int; + +/// The tree a command reads: a session's, over its socket, or one made here. +const Tree = struct { + f: cloud9.Fsys, + /// The core this process made, there being no session to ask. + here: ?*Here = null, + + /// The session at `dial` (`Found.one`), or with none a core made here. + fn open(io: std.Io, gpa: std.mem.Allocator, dial: ?[]const u8) !*Tree { + const t = try gpa.create(Tree); + t.here = null; + if (dial) |d| { + const no_env = [_:null]?[*:0]const u8{}; + try t.f.dial(io, &no_env, d, "pardes"); + return t; + } + const h = try gpa.create(Here); + h.core = try pardes.Pardes.create(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory }); + h.engine = .init(.{ .in = &h.in, .out = &h.out, .root = pardes.ctlfs.root }); + var fds: [2]std.c.fd_t = undefined; + if (socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocketPair; + h.fd = fds[1]; + (try std.Thread.spawn(.{}, Here.serve, .{h})).detach(); + t.here = h; + try t.f.init(io, .{ .socket = .{ .handle = fds[0], .address = undefined } }, "pardes"); + return t; + } + + /// The whole file at `path`. + fn read(t: *Tree, gpa: std.mem.Allocator, path: []const u8) ![]const u8 { + var out: std.Io.Writer.Allocating = .init(gpa); + try t.f.readFile(path, &out.writer); + return out.written(); + } +}; + +/// The session a command acts on: `-s NAME` (a name, a socket's path or a +/// dial), else $PARDES_9P, else the only one whose socket answers. +const Found = union(enum) { none, one: []const u8, many: []const []const u8 }; + +fn findSession(io: std.Io, arena: std.mem.Allocator, named: ?[]const u8) Found { + if (named) |n| { + if (std.mem.indexOfAny(u8, n, "/!") != null) return .{ .one = n }; + var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; + var buf: [ninep_io.sun_path_len]u8 = undefined; + const dir = ninep_io.socketDir(&dir_buf) orelse return .{ .one = n }; + return .{ .one = arena.dupe(u8, ninep_io.socketPath(&buf, dir, n) orelse n) catch n }; + } + if (std.c.getenv("PARDES_9P")) |d| return .{ .one = std.mem.span(d) }; + const names = sessionNames(io, arena); + return switch (names.len) { + 0 => .none, + 1 => findSession(io, arena, names[0]), + else => .{ .many = names }, + }; +} + +/// The names of the sessions whose sockets answer, in the socket directory. +fn sessionNames(io: std.Io, arena: std.mem.Allocator) []const []const u8 { + var names: std.ArrayList([]const u8) = .empty; + var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const path = ninep_io.socketDir(&dir_buf) orelse return &.{}; + var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return &.{}; + defer dir.close(io); + var it = dir.iterate(); + while (it.next(io) catch null) |e| { + const prefix = "pardes-9p-"; + if (!std.mem.startsWith(u8, e.name, prefix) or !std.mem.endsWith(u8, e.name, ".sock")) continue; + const name = e.name[prefix.len .. e.name.len - ".sock".len]; + if (name.len == 0 or !ninep_io.taken(name)) continue; + names.append(arena, arena.dupe(u8, name) catch continue) catch continue; + } + return names.items; +} + +/// What a core made here can say of itself; the rest of the tree is a +/// running session's. +const offline = [_][]const u8{ "README", "commands", "ctl" }; + +/// A /commands line: `Word[ arg] root|pane|both[ choices] -- what it does`. +const Word = struct { + name: []const u8, + arg: bool, + scope: []const u8, + choices: []const u8, + doc: []const u8, + + fn parse(line: []const u8) ?Word { + const cut = std.mem.indexOf(u8, line, " -- "); + var it = std.mem.tokenizeScalar(u8, line[0 .. cut orelse line.len], ' '); + var w: Word = .{ .name = it.next() orelse return null, .arg = false, .scope = "", .choices = "", .doc = if (cut) |c| line[c + 4 ..] else "" }; + var next = it.next() orelse return null; + if (std.mem.eql(u8, next, "arg")) { + w.arg = true; + next = it.next() orelse return null; + } + w.scope = next; + w.choices = it.next() orelse ""; + return w; + } + + fn find(commands: []const u8, name: []const u8) ?Word { + var lines = std.mem.tokenizeScalar(u8, commands, '\n'); + while (lines.next()) |line| if (parse(line)) |w| if (std.mem.eql(u8, w.name, name)) return w; + return null; + } + + const groups = [_][]const u8{ "file", "column", "session", "jump", "text", "language", "theme", "help", "setting", "addon" }; + + /// Its group: the first key after the leader, else what it is. + fn group(w: Word) []const u8 { + if (std.mem.indexOf(u8, w.doc, " (addon ") != null and std.mem.endsWith(u8, w.doc, ")")) return "addon"; + if (pardes.config.Runtime.find(w.name) != null) return "setting"; + if (std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name)) |b| if (pardes.config.leader_path.get(b)) |p| switch (p[0]) { + 'f' => return "file", + 'c' => return "column", + 's' => return "session", + 'j' => return "jump", + 'l' => return "language", + 't' => return "theme", + 'h' => return "help", + else => {}, + }; + return if (std.mem.eql(u8, w.scope, "root")) "session" else "text"; + } + + /// `SPC c n`, its leader key, or empty. + fn leader(w: Word, buf: []u8) []const u8 { + const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name) orelse return ""; + const path = pardes.config.leader_path.get(b) orelse return ""; + var out: std.Io.Writer = .fixed(buf); + out.writeAll("SPC") catch return ""; + for (path) |c| out.print(" {c}", .{c}) catch return ""; + return out.buffered(); + } +}; + +/// A command but new and attach, which go on to start or join a session. +fn runCommand(init: std.process.Init, cmd: Cmd, all: []const [:0]const u8) noreturn { + const io = init.io; + const arena = init.arena.allocator(); + var out_buf: [4096]u8 = undefined; + var stdout = std.Io.File.stdout().writer(io, &out_buf); + const out = &stdout.interface; + // Its words as the shell has them: `-s` there is a word typed. + if (cmd == .completion) { + const status = completion(init, out, all, null); + out.flush() catch {}; + std.process.exit(status); + } + // -s NAME and -p N anywhere after the command, but after `--`. + var session: ?[]const u8 = null; + var pane: ?[]const u8 = if (std.c.getenv("PARDES_PANE")) |p| std.mem.span(p) else null; + var rest: std.ArrayList([]const u8) = .empty; + var i: usize = 0; + while (i < all.len) : (i += 1) { + const a = all[i]; + const value = i + 1 < all.len; + if (std.mem.eql(u8, a, "--")) { + for (all[i + 1 ..]) |r| rest.append(arena, r) catch die(io, "out of memory", .{}); + break; + } else if ((std.mem.eql(u8, a, "-s") or std.mem.eql(u8, a, "--session")) and value) { + i += 1; + session = all[i]; + } else if (std.mem.startsWith(u8, a, "--session=")) { + session = a["--session=".len..]; + } else if (std.mem.eql(u8, a, "-p") and value and cmd == .do) { + i += 1; + pane = all[i]; + } else rest.append(arena, a) catch die(io, "out of memory", .{}); + } + const args = rest.items; + const status: u8 = switch (cmd) { + .new, .attach => unreachable, + .ps => manage(io, .list, ""), + .kill => { + if (args.len == 1 and std.mem.eql(u8, args[0], "--all")) manage(io, .killall, ""); + if (args.len != 1 or args[0].len == 0) die(io, "kill needs a session's name (pardes ps lists them), or --all", .{}); + manage(io, .kill, args[0]); + }, + .version => version: { + out.writeAll(version_text) catch {}; + out.print("9p 9P2000 msize {d}\n", .{@import("runtime").ninep.msize}) catch {}; + break :version 0; + }, + .skill => skill: { + out.writeAll(@embedFile("skill.txt")) catch {}; + break :skill 0; + }, + .help => help(init, out, args, session), + .words => listWords(init, out, args, session), + .do => doWord(init, args, session, pane), + .fs => fsVerb(init, out, args, session), + .completion => unreachable, + }; + out.flush() catch {}; + std.process.exit(status); +} + +/// The tree a command that reads reads: a session's when one is named, +/// inside, or the only one, else a core made here. +fn readTree(init: std.process.Init, session: ?[]const u8) *Tree { + const io = init.io; + const arena = init.arena.allocator(); + const dial: ?[]const u8 = switch (findSession(io, arena, session)) { + .one => |d| d, + .none, .many => null, + }; + return Tree.open(io, arena, dial) catch |err| { + if (dial) |d| die(io, "no session answers at {s} ({t}): pardes ps lists them", .{ d, err }); + die(io, "a core made here would not start: {t}", .{err}); + }; +} + +fn help(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { + const io = init.io; + const arena = init.arena.allocator(); + if (args.len == 0) { + writeFirstScreen(out) catch {}; + return 0; + } + if (args.len > 1) die(io, "help takes one thing to say: a command, a builtin or a path", .{}); + const what = args[0]; + if (std.mem.eql(u8, what, "--all")) { + // This build's, never a session's: the reference prints it. + const t = Tree.open(io, arena, null) catch |err| die(io, "a core made here would not start: {t}", .{err}); + writeHelpAll(out, t) catch |err| die(io, "help --all: {t}", .{err}); + return 0; + } + if (std.meta.stringToEnum(Cmd, what)) |c| { + writeLeaf(out, c) catch {}; + return 0; + } + const t = readTree(init, session); + const commands = t.read(arena, "commands") catch ""; + if (Word.find(commands, what)) |w| { + var key_buf: [32]u8 = undefined; + const key = w.leader(&key_buf); + const scope = if (std.mem.eql(u8, w.scope, "root")) "the root ctl" else if (std.mem.eql(u8, w.scope, "both")) "a pane's ctl, or the root's" else "a pane's ctl"; + out.print("{s} ({s}{s}{s}; {s})\n {s}\n", .{ w.name, scope, if (key.len == 0) "" else "; ", key, w.group(), w.doc }) catch {}; + if (w.choices.len != 0) out.print(" one of: {s}\n", .{w.choices}) catch {}; + out.print("\n pardes do {s}{s}\n", .{ w.name, if (w.arg) " [ARG]" else "" }) catch {}; + return 0; + } + var err_buf: [1024]u8 = undefined; + var stderr = std.Io.File.stderr().writer(io, &err_buf); + var in: std.Io.Reader = .fixed(""); + var said: std.Io.Writer.Allocating = .init(arena); + const status = cloud9.verbs.run(&t.f, &.{ "help", what }, &in, out, &said.writer); + if (status != 0) { + stderr.interface.print("pardes: help: {s} is not a command, a builtin (pardes words) or a file of the tree (pardes fs ls)\n", .{what}) catch {}; + stderr.interface.flush() catch {}; + } + return status; +} + +fn listWords(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { + const io = init.io; + const arena = init.arena.allocator(); + if (args.len > 1) die(io, "words takes one group: {s}", .{"file column session jump text language theme help setting addon"}); + const only: ?[]const u8 = if (args.len == 1) args[0] else null; + if (only) |g| for (Word.groups) |name| { + if (std.mem.eql(u8, name, g)) break; + } else die(io, "words: no group {s}: file column session jump text language theme help setting addon", .{g}); + const t = readTree(init, session); + const commands = t.read(arena, "commands") catch |err| die(io, "words: /commands: {t}: {s}", .{ err, t.f.said() }); + for (Word.groups) |g| { + if (only) |o| if (!std.mem.eql(u8, o, g)) continue; + var first = true; + var lines = std.mem.tokenizeScalar(u8, commands, '\n'); + while (lines.next()) |line| { + const w = Word.parse(line) orelse continue; + if (!std.mem.eql(u8, w.group(), g)) continue; + if (first and only == null) out.print("{s}{s}:\n", .{ if (std.mem.eql(u8, g, Word.groups[0])) "" else "\n", g }) catch {}; + first = false; + var buf: [64]u8 = undefined; + const left = std.fmt.bufPrint(&buf, "{s}{s}", .{ w.name, if (w.arg) " [ARG]" else "" }) catch w.name; + out.print(" {s}", .{left}) catch {}; + out.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2) catch {}; + out.print("{s}\n", .{w.doc}) catch {}; + } + } + return 0; +} + +fn doWord(init: std.process.Init, args: []const []const u8, session: ?[]const u8, pane: ?[]const u8) u8 { + const io = init.io; + const arena = init.arena.allocator(); + if (args.len == 0) die(io, "do needs a word: pardes do Newcol (pardes words lists them)", .{}); + const dial = switch (findSession(io, arena, session)) { + .one => |d| d, + .none => die(io, "do: no session runs: start one (pardes new --detach=NAME), or name one (-s NAME)", .{}), + .many => |names| die(io, "do: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }), + }; + const t = Tree.open(io, arena, dial) catch |err| die(io, "do: no session answers at {s} ({t}): pardes ps lists them", .{ dial, err }); + const commands = t.read(arena, "commands") catch |err| die(io, "do: /commands: {t}: {s}", .{ err, t.f.said() }); + const w = Word.find(commands, args[0]) orelse die(io, "do: no word {s} in this session: pardes words lists them", .{args[0]}); + const at_pane = !std.mem.eql(u8, w.scope, "root") and pane != null; + if (std.mem.eql(u8, w.scope, "pane") and pane == null) die(io, "do: {s} is a pane's word: name the pane with -p N (pardes fs read index lists them)", .{w.name}); + const ctl = if (at_pane) std.fmt.allocPrint(arena, "pane/{s}/ctl", .{pane.?}) catch unreachable else "ctl"; + const line = std.mem.concat(arena, u8, &.{ std.mem.join(arena, " ", args) catch unreachable, "\n" }) catch unreachable; + t.f.writeFile(ctl, line) catch |err| switch (err) { + error.Refused => die(io, "do {s}: {s}", .{ w.name, t.f.said() }), + else => die(io, "do {s}: {s}: {t}", .{ w.name, ctl, err }), + }; + return 0; +} + +fn fsVerb(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { + const io = init.io; + const arena = init.arena.allocator(); + var err_buf: [1024]u8 = undefined; + var stderr = std.Io.File.stderr().writer(io, &err_buf); + defer stderr.interface.flush() catch {}; + var in_buf: [64 * 1024]u8 = undefined; + var stdin = std.Io.File.stdin().readerStreaming(io, &in_buf); + const dial: ?[]const u8 = switch (findSession(io, arena, session)) { + .one => |d| d, + .none => null, + .many => |names| die(io, "fs: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }), + }; + if (dial == null and args.len > 0) { + const verb = args[0]; + const path = std.mem.trim(u8, if (args.len > 1) args[1] else "", "/"); + const reads = std.mem.eql(u8, verb, "read"); + if (std.mem.eql(u8, verb, "write") or std.mem.eql(u8, verb, "ask") or std.mem.eql(u8, verb, "follow")) + die(io, "fs {s}: no session runs to {s}: start one (pardes new --detach=NAME), then -s NAME", .{ verb, verb }); + if (reads) for (offline) |name| { + if (std.mem.eql(u8, name, path)) break; + } else die(io, "fs read {s}: that is a running session's, and none runs: start one (pardes new --detach=NAME), then -s NAME; with none, README, commands and ctl say what they would", .{path}); + } + const t = Tree.open(io, arena, dial) catch |err| { + if (dial) |d| die(io, "fs: no session answers at {s} ({t}): pardes ps lists them", .{ d, err }); + die(io, "fs: a core made here would not start: {t}", .{err}); + }; + return cloud9.verbs.run(&t.f, args, &stdin.interface, out, &stderr.interface); +} + +/// `pardes completion SHELL`: the script; `pardes completion -- WORDS`: +/// what may follow, the last word being the one typed so far, a line each +/// (`word\twhat it is`). +fn completion(init: std.process.Init, out: *std.Io.Writer, args: []const [:0]const u8, session: ?[]const u8) u8 { + const io = init.io; + const arena = init.arena.allocator(); + if (args.len == 1) { + const Shell = enum { bash, fish, zsh }; + const shell = std.meta.stringToEnum(Shell, args[0]) orelse die(io, "completion: no shell {s}: bash, fish or zsh", .{args[0]}); + out.writeAll(switch (shell) { + .fish => + \\# pardes completion fish: each word asked of pardes itself. + \\complete -c pardes -f -a '(pardes completion -- (commandline -opc)[2..-1] (commandline -ct))' + \\complete -c pardes -n 'test (count (commandline -opc)) -eq 1' -F + \\ + , + .bash => + \\# pardes completion bash: each word asked of pardes itself. + \\_pardes() { + \\ local IFS=$'\n' line + \\ COMPREPLY=() + \\ while read -r line; do COMPREPLY+=("${line%%$'\t'*}"); done < <(pardes completion -- "${COMP_WORDS[@]:1:COMP_CWORD}") + \\ [ "$COMP_CWORD" -eq 1 ] && COMPREPLY+=($(compgen -f -- "${COMP_WORDS[COMP_CWORD]}")) + \\} + \\complete -o filenames -F _pardes pardes + \\ + , + .zsh => + \\# pardes completion zsh: each word asked of pardes itself. + \\_pardes() { + \\ local -a said + \\ said=("${(@f)$(pardes completion -- "${(@)words[2,CURRENT]}")}") + \\ said=("${(@)said//:/\\:}") + \\ said=("${(@)said//$'\t'/:}") + \\ _describe pardes said + \\ (( CURRENT == 2 )) && _files + \\} + \\compdef _pardes pardes + \\ + , + }) catch {}; + return 0; + } + if (args.len < 2 or !std.mem.eql(u8, args[0], "--")) + die(io, "completion needs a shell: bash, fish or zsh", .{}); + const typed = args[1..]; + const cur = typed[typed.len - 1]; + const before = typed[0 .. typed.len - 1]; + const Offer = struct { + fn one(w: *std.Io.Writer, prefix: []const u8, word: []const u8, what: []const u8) void { + if (!std.mem.startsWith(u8, word, prefix)) return; + w.print("{s}{s}{s}\n", .{ word, if (what.len == 0) "" else "\t", what }) catch {}; + } + }; + if (before.len == 0) { + for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line); + if (cur.len != 0 and cur[0] == '-') for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old) Offer.one(out, cur, @tagName(f), flags.get(f).doc); + return 0; + } + const cmd = std.meta.stringToEnum(Cmd, before[0]) orelse return 0; + switch (cmd) { + .new => for (std.enums.values(Flag)) |f| if (flags.get(f).group == .session) Offer.one(out, cur, @tagName(f), flags.get(f).doc), + .attach, .kill => if (before.len == 1) for (sessionNames(io, arena)) |name| Offer.one(out, cur, name, "a session"), + .completion => if (before.len == 1) for ([_][]const u8{ "bash", "fish", "zsh" }) |s| Offer.one(out, cur, s, ""), + .words => if (before.len == 1) for (Word.groups) |g| Offer.one(out, cur, g, ""), + .do, .help => if (before.len == 1) { + if (cmd == .help) for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line); + const t = readTree(init, session); + var lines = std.mem.tokenizeScalar(u8, t.read(arena, "commands") catch "", '\n'); + while (lines.next()) |line| if (Word.parse(line)) |w| Offer.one(out, cur, w.name, w.doc); + if (cmd == .help) { + var said: std.Io.Writer.Allocating = .init(arena); + var in: std.Io.Reader = .fixed(""); + _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer); + } + } else if (cmd == .do) { + const t = readTree(init, session); + if (Word.find(t.read(arena, "commands") catch "", before[1])) |w| if (w.choices.len != 0) { + var it = std.mem.tokenizeScalar(u8, w.choices, ','); + while (it.next()) |c| Offer.one(out, cur, c, ""); + }; + }, + .fs => if (before.len == 1) { + var verbs = std.mem.tokenizeAny(u8, "ls read write ask follow stat help complete", " "); + while (verbs.next()) |v| Offer.one(out, cur, v, ""); + } else if (before.len == 2) { + const t = readTree(init, session); + var said: std.Io.Writer.Allocating = .init(arena); + var in: std.Io.Reader = .fixed(""); + _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer); + }, + .ps, .skill, .version => {}, + } + return 0; +} + +pub const main = nativeMain; + +// glibc's struct termios is 60 bytes, Zig 0.17's std.c.termios the kernel's +// 44: libc's tcgetattr wrote 16 bytes past every Zig caller's (vaxis's +// makeRaw, the stub's, the GUI's), and a ReleaseSafe build trapped at its +// first terminal. These take libc's place in the process: the kernel's own +// ioctls, which read and write only the 36 bytes both layouts begin with +// (the flags, the line, the kernel's 19 cc), so a caller of either size +// stays within its struct. +comptime { + if (builtin.os.tag == .linux and builtin.abi.isGnu()) { + @export(&kernelTcgetattr, .{ .name = "tcgetattr" }); + @export(&kernelTcsetattr, .{ .name = "tcsetattr" }); + } +} + +fn kernelTcgetattr(fd: c_int, t: *std.os.linux.termios) callconv(.c) c_int { + return libcResult(std.os.linux.tcgetattr(fd, t)); +} + +fn kernelTcsetattr(fd: c_int, how: c_int, t: *const std.os.linux.termios) callconv(.c) c_int { + return libcResult(std.os.linux.tcsetattr(fd, @fromBackingInt(@bitCast(how)), t)); +} + +fn libcResult(rc: usize) c_int { + const e = std.os.linux.errno(rc); + if (e == .SUCCESS) return 0; + std.c._errno().* = @intCast(@backingInt(e)); + return -1; +} + +fn parseCtrlKey(raw: []const u8) ?u21 { + var value = std.mem.trim(u8, raw, " \t\r\n"); + if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl-")) { + value = value[5..]; + } else if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl+")) { + value = value[5..]; + } else if (value.len == 2 and value[0] == '^') { + value = value[1..]; + } + if (value.len != 1) return null; + const c = std.ascii.toLower(value[0]); + if (c < 'a' or c > 'z' or c == 'c') return null; + return c; +} + +// init.gpa, what the tui, gui and detached shells allocate from, is their +// own fixed arena (memory.host) in a release build, spilling to libc's +// malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start +// gives a safe build a SafeAllocator over the page allocator instead. +fn nativeMain(std_init: std.process.Init) !void { + var init = std_init; + if (builtin.mode != .debug) init.gpa = pardes.memory.host(std.heap.c_allocator); + // A recorded session's tape replayed, no session of its own (src/tape.zig). + if (init.environ_map.get("PARDES_REPLAY")) |tape| std.process.exit(pardes.tape.replayMain(tape)); + var stderr_probe: [64]u8 = undefined; + _ = std.debug.lockStderr(&stderr_probe); + std.debug.unlockStderr(); + + var opts: pardes.Options = .{}; + var mounts: [pardes.filesystem.max_mounts]pardes.filesystem.Mount = undefined; + var mounts_len: usize = 0; + const arena = init.arena.allocator(); + const args = try init.minimal.args.toSlice(arena); + // An addon's author's test (addon_test.zig): nothing else. + if (args.len >= 3 and std.mem.eql(u8, args[1], "--addon-test")) + std.process.exit(@import("runtime").addon_test.main(init.io, init.gpa, args[2], if (args.len > 3) args[3] else null)); + // The per-user daemon a session started (daemon.zig), or an upgrade of + // one with its registry: nothing else. + if (comptime daemon.supported) if (args.len >= 2 and args.len <= 3 and std.mem.eql(u8, args[1], "--daemon")) + daemon.serve(if (args.len == 3 and std.mem.startsWith(u8, args[2], upgrade.flag)) args[2][upgrade.flag.len..] else null); + // An upgraded session's new process (upgrade.zig): its record, then the + // arguments it was started with, which configure it as before; its + // file, stdin, directory and daemon come from the record instead. + const upgraded = comptime upgrade.supported and (pardes.platform == .tui or pardes.platform == .gui); + if (upgraded) if (args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.flag)) { + upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{}); + }; + const resuming = upgrade.resumed != null; + var session_only = true; + var new_session = false; + var explicit_tty = false; + var detach: ?[]const u8 = null; + var attach: ?[]const u8 = null; + var positional: ?[:0]const u8 = null; + var wait = false; + var i: usize = if (resuming) 2 else 1; + // A command's name first: new and attach go on to start or join a + // session, with the flags after them; the rest are done in `command`. + if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) { + .new => { + new_session = true; + i = 2; + }, + .attach => { + const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-'; + attach = if (named) args[2] else ""; + i = if (named) 3 else 2; + }, + else => runCommand(init, cmd, args[2..]), + }; + while (i < args.len) : (i += 1) { + const a = args[i]; + if (a.len < 2 or a[0] != '-') { + // `-` is stdin, as for cat and vim: a text to show. + if (a.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); + if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{a}); + session_only = false; + positional = a; + continue; + } + // `flags` says what each takes: nothing, the next argument (or + // after `=`), a value after `=`, or maybe one. + const eq = std.mem.indexOfScalar(u8, a, '='); + const flag = std.meta.stringToEnum(Flag, a[0 .. eq orelse a.len]) orelse badArgs(init.io, "no such option: {s}", .{a}); + var value: ?[]const u8 = if (eq) |e| a[e + 1 ..] else null; + switch (flags.get(flag).takes) { + .none => if (value != null) badArgs(init.io, "{t} takes no value: {s}", .{ flag, a }), + .next => if (value == null and i + 1 < args.len) { + i += 1; + value = args[i]; + }, + .eq, .maybe => {}, + } + switch (flag) { + .@"--tty" => explicit_tty = true, + .@"-n" => { + session_only = false; + new_session = true; + const count = value orelse badArgs(init.io, "-n needs a count after it: 1 or 3", .{}); + opts.shells = std.fmt.parseInt(u8, count, 10) catch + badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{count}); + }, + .@"-l" => { + session_only = false; + new_session = true; + opts.load_path = value orelse badArgs(init.io, "-l needs the path of a dump to load", .{}); + }, + .@"--tty-toggle" => { + session_only = false; + new_session = true; + const key = value orelse badArgs(init.io, "--tty-toggle needs a letter after it", .{}); + opts.tty_toggle = parseCtrlKey(key) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{key}); + }, + .@"--nested" => opts.nested = true, + .@"-w", .@"--wait" => wait = true, + .@"--9p" => { + new_session = true; + const name = value orelse badArgs(init.io, "--9p needs a socket name: --9p=<name>", .{}); + if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) + badArgs(init.io, "invalid 9P socket name: '{s}'", .{name}); + opts.ninep_name = name; + }, + .@"--9p-tcp" => { + new_session = true; + const dial = value orelse badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{}); + if (!std.mem.startsWith(u8, dial, "tcp!")) + badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{}); + _ = @import("runtime").ninep_io.networkAddress(dial, true) catch + badArgs(init.io, "--9p-tcp needs tcp!<numeric-ip>!<port>", .{}); + if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{}); + opts.ninep_tcp = dial; + }, + .@"--mount" => { + new_session = true; + const mount = value orelse badArgs(init.io, "--mount needs name=dial", .{}); + const split = std.mem.indexOfScalar(u8, mount, '=') orelse + badArgs(init.io, "--mount needs name=dial", .{}); + const name = mount[0..split]; + const dial = mount[split + 1 ..]; + if (dial.len == 0 or !@import("core").filesystem.validMountName(name)) + badArgs(init.io, "invalid mount name or dial: '{s}'", .{mount}); + @import("runtime").ninep_io.Client.validateDial(dial) catch + badArgs(init.io, "invalid mount dial: '{s}'", .{dial}); + for (mounts[0..mounts_len]) |existing| if (std.mem.eql(u8, existing.name, name)) + badArgs(init.io, "duplicate mount name: '{s}'", .{name}); + if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len}); + mounts[mounts_len] = .{ .name = name, .dial = dial }; + mounts_len += 1; + }, + .@"--geometry" => opts.geometry = value orelse badArgs(init.io, "--geometry needs WxH[+X+Y]", .{}), + .@"--detach" => detach = value orelse "", + .@"--attach" => attach = value orelse "", + .@"--ps" => manage(init.io, .list, ""), + .@"--kill" => { + const name = value orelse ""; + if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{}); + manage(init.io, .kill, name); + }, + .@"--kill-all" => manage(init.io, .killall, ""), + .@"-h", .@"--help" => runCommand(init, .help, &.{}), + .@"--version" => runCommand(init, .version, &.{}), + .@"--" => { + // The end of options: what follows is a name, `-dash.txt` too. + for (args[i + 1 ..]) |name| { + if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); + if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name}); + session_only = false; + positional = name; + } + break; + }, + } + } + opts.tty_only = explicit_tty or session_only; + opts.mounts = mounts[0..mounts_len]; + // `zig build run-isolated` with nothing named: something to look at on + // arrival, read out of the binary itself. + if (pardes.isolated and positional == null) { + session_only = false; + positional = "src/pardes.zig"; + } + if (detach != null and attach != null) + badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); + // --wait waits on the pane a FILE opens: with none there is nothing to + // wait for (EDITOR=pardes --wait is given the file). + if (wait and positional == null) + badArgs(init.io, "--wait needs a FILE: it returns when that file's pane is closed", .{}); + if (opts.ninep_name.len != 0 and attach != null) + badArgs(init.io, "--9p names a session's own socket, and --attach has none of its own", .{}); + if (opts.ninep_tcp != null and attach != null) + badArgs(init.io, "--9p-tcp opens a session's own listener, and --attach has none of its own", .{}); + if (opts.mounts.len != 0 and attach != null) + badArgs(init.io, "--mount configures a session's own core, and --attach has none of its own", .{}); + if (!new_session and !opts.nested and detach == null and attach == null and !resuming) forwarding: { + // Am I inside a pardes at all? That is $PARDES_PID and nothing else — + // one variable, exported by every session that means to take its + // children's Looks, so a session that could not open a socket is still + // recognisably the session this shell is inside. A pid naming no live + // process is a shell that outlived its editor (a daemon started from a + // pane, a stale environment carried into a new terminal), which is not + // nested at all. + // `--wait` with only $PARDES_9P (a script or agent that talks to a + // session from outside its panes, EDITOR='pardes --wait') is asked + // of that session too: what it waits on is a pane there. + const outside = wait and std.c.getenv("PARDES_PID") == null and std.c.getenv("PARDES_9P") != null; + if (!outside) { + const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); + const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; + if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding; + } + + // Can I reach it? That is the other two, and it is a separate answer. + const Parent = struct { dial: []const u8, serial: u32 }; + const found: ?Parent = reaching: { + const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null); + ninep_io.Client.validateDial(dial) catch break :reaching null; + // No pane of its own (`outside`): the session's root look, 0. + const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse if (outside) break :reaching .{ .dial = dial, .serial = 0 } else break :reaching null); + for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null; + const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null; + if (serial == 0) break :reaching null; + break :reaching .{ .dial = dial, .serial = serial }; + }; + // A pid we cannot reach is a session that is not answering: the shell + // says it is inside one, but there is nothing there to take the file. + // Starting an ordinary editor is what this did before the pid existed + // and is the more useful of the two answers -- refusing to start would + // leave a stale environment variable able to lock someone out of their + // own editor. + const parent = found orelse break :forwarding; + // Does it answer? One that answers takes the file or says why not, + // as acme's B does: from here on never a nested editor, whose + // screen would be drawn inside the pane that asked. + ninep_io.Client.probe(arena, parent.dial) catch { + // `--wait` is someone's EDITOR waiting on that session: a screen + // of its own drawn in their terminal is no answer. Said, exit 1. + if (wait) die(init.io, "--wait: the session at {s} does not answer; it is gone", .{parent.dial[0..@min(parent.dial.len, 4096)]}); + break :forwarding; + }; + const Refuse = struct { + fn with(io: std.Io, what: []const u8, err: anyerror) noreturn { + var words_buf: [128]u8 = undefined; + die(io, "{s}: {s}", .{ what[0..@min(what.len, 4096)], if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf) }); + } + }; + // The pane's `look` file: one line, and the line is the clicked text + // itself, which is what a right click in that pane would have been. + var look_buf: [64]u8 = undefined; + const look = if (parent.serial == 0) "/look" else try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); + // `pardes -`: stdin read to its end, a +Pager pane of the session + // made of it (as acme's `B` has no stdin, through pane/new, a name + // and the body), and back at once: the PAGER a pane's shell gets. + if (positional) |word| if (std.mem.eql(u8, word, "-")) { + const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); + // Nothing paged: no pane, and done. + if (text.len == 0) return; + pageInto(init.io, arena, parent.dial, text); + return; + }; + // From outside the session's panes there is no pane to say it is + // nested in: `--wait` with no file opens nothing there. + if (parent.serial == 0 and positional == null) break :forwarding; + const typed_word = positional orelse { + var tag_buf: [64]u8 = undefined; + const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); + const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err); + arena.free(contents); + try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); + std.process.exit(1); + }; + // Named as it was given, its newline shown `\n`, so the refusal says + // which name and why once. + if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) { + var shown_buf: [4 * 4096]u8 = undefined; + Refuse.with(init.io, pardes.ctlfs.events.shown(typed_word[0..@min(typed_word.len, 4096)], &shown_buf), error.NotOneLine); + } + // `pardes '~/x'`, quoted so the shell left it: home, as a look's. + var home_buf: [4096]u8 = undefined; + const word = pardes.filesystem.expandHome(typed_word, &home_buf); + const target = @import("core").look.parsePathLine(word); + // `@pN[:addr]` addresses a pane of this session: one it has is + // looked at, one it has not is refused, never a file of that name. + if (std.mem.startsWith(u8, target.path, pardes.config.pane_addr)) { + const digits = word[pardes.config.pane_addr.len .. std.mem.indexOfScalar(u8, word, ':') orelse word.len]; + const serial = std.fmt.parseInt(u32, digits, 10) catch Refuse.with(init.io, word, error.NotAPaneAddress); + var name_buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); + const named = ninep_io.Client.read(arena, parent.dial, name, name) catch Refuse.with(init.io, word, error.NoSuchPane); + arena.free(named); + var command_buf: [4200]u8 = undefined; + const command = std.fmt.bufPrint(&command_buf, "{s}\n", .{word}) catch |err| Refuse.with(init.io, word, err); + ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + return; + } + var realbuf: [4096]u8 = undefined; + var newbuf: [4096]u8 = undefined; + const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null; + const path = found_path orelse named: { + // A name not there yet, as acme's B takes one: its directory + // resolved and the name kept, a pane made for it that Save + // creates the file from. + const base = std.Io.Dir.path.basename(target.path); + if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) Refuse.with(init.io, word, error.NotAFileName); + const dir = pardes.filesystem.resolveOs(std.Io.Dir.path.dirname(target.path) orelse ".", &realbuf) orelse { + // Its directory not there either: the name made absolute as + // written, and the pane's Save makes the directories. + var cwd_buf: [4096]u8 = undefined; + const cwd = cwd_buf[0 .. std.process.currentPath(init.io, &cwd_buf) catch Refuse.with(init.io, word, error.NoWorkingDirectory)]; + const absolute = std.Io.Dir.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); + // Missing because one above may not be searched or written: + // its Save could never make it, so refused now. + if (pardes.filesystem.deniedAbove(std.Io.Dir.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable); + break :named absolute; + }; + // A directory that is there but may not be read or written: a + // pane for the name could only fail at its Save, so refused now. + std.Io.Dir.cwd().access(init.io, dir.path, .{ .read = true, .write = true, .execute = true }) catch Refuse.with(init.io, word, error.DirectoryNotWritable); + break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); + }; + var made_serial: ?u32 = null; + if (found_path != null) { + var command_buf: [8192]u8 = undefined; + const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); + // The pane it went to, read on the open that asked (another + // client's look meanwhile is not this one's): what --wait waits on. + const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err); + var rows = std.mem.tokenizeAny(u8, went, " \n"); + if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; + } else { + const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err); + const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err); + made_serial = serial; + var name_buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); + var line_buf: [4200]u8 = undefined; + const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch |err| Refuse.with(init.io, word, err); + ninep_io.Client.write(arena, parent.dial, name, line) catch |err| { + // The name refused: the pane made for it goes too, no + // stray +New left behind. + var ctl_buf: [64]u8 = undefined; + const ctl = std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable; + var why_buf: [256]u8 = undefined; + const said = ninep_io.Client.lastSaid(); + const why = why_buf[0..@min(said.len, why_buf.len)]; + @memcpy(why, said[0..why.len]); + ninep_io.Client.write(arena, parent.dial, ctl, "delete\n") catch {}; + if (err == error.Remote) die(init.io, "{s}: {s}", .{ word[0..@min(word.len, 4096)], why }); + Refuse.with(init.io, word, err); + }; + } + if (wait) waitForDel(arena, parent.dial, path, made_serial); + return; + } + if (resuming) positional = null; + // `pardes -` outside a session: an editor whose first pane holds stdin, + // as `vim -` does; the terminal is /dev/tty, never stdin. + if (positional) |a| if (std.mem.eql(u8, a, "-")) { + opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + // Nothing paged: nothing to show. + if (opts.stdin_text.?.len == 0) return; + positional = null; + }; + if (positional) |a| { + const target = @import("core").look.parsePathLine(a); + if (std.mem.eql(u8, target.path, "/n") or std.mem.startsWith(u8, target.path, "/n/") or + std.mem.eql(u8, target.path, "/virtual") or std.mem.startsWith(u8, target.path, "/virtual/")) + { + opts.file = try arena.dupe(u8, target.path); + opts.file_line = target.at.line; + } else if (std.meta.isError(std.process.setCurrentPath(init.io, a))) { + var cwdbuf: [4096]u8 = undefined; + const cwd = cwdbuf[0 .. std.process.currentPath(init.io, &cwdbuf) catch + badArgs(init.io, "this shell's working directory is gone; cd somewhere that exists", .{})]; + var realbuf: [4096]u8 = undefined; + switch (@import("core").look.resolve(null, a, cwd, &realbuf)) { + .file => |t| { + opts.file = try arena.dupe(u8, t.path); + opts.file_line = t.at.line; + }, + .kind => |t| opts.file = try arena.dupe(u8, t.path), + .none => opts.missing = .{ + .word = try arena.dupe(u8, a), + .dir = try arena.dupe(u8, cwd), + }, + .url => badArgs(init.io, "a URL is not something a launch can open; start pardes and click it", .{}), + .pane => badArgs(init.io, "@pN addresses a pane of a running pardes, so there is none yet", .{}), + else => badArgs(init.io, "cannot enter that directory: {s}", .{a}), + } + } + } + // The real bare-tty startup wants the editor half present from the first + // frame, so it names that layout; a core booted for a test names none and + // gets the raw shell by itself. This has to come AFTER the positional is + // resolved: naming a layout short-circuits `Boot.of`, so choosing it any + // earlier threw away a file argument, and the error pane for one that does + // not exist, without a word. + if (opts.tty_only and opts.file == null and opts.missing == null) opts.boot = .tty; + const found = pardes.config.User.load(init.io, arena, init.environ_map); + opts.startup_config = found.bytes; + opts.startup_config_path = found.path; + opts.config_dir = found.dir; + opts.state = .disk; + opts.recent_import = oldRecentDir(arena, init.environ_map); + if (found.dir) |d| @import("runtime").crash.setDir(d); + if (attach) |name| if (std.mem.lastIndexOfScalar(u8, name, ':')) |colon| { + attachClient(init, opts, name[0..colon], name[colon + 1 ..]); + }; + if (attach) |name| if (!resuming) attachTo(init, opts, name); + if (detach) |name| { + // A window's binary would start SDL, a GPU device and its fonts for + // a window nobody sees (638M instructions, its socket at 255 ms, + // 1.2% of a CPU idle): the terminal's binary beside it is the + // detached session, as `pardes --detach` (`ps` says tty), its + // windows clients. Without one there, it carries on as a window's. + if (comptime pardes.platform == .gui) if (!resuming) { + var exe: [4096]u8 = undefined; + const n = std.c.readlink("/proc/self/exe", &exe, exe.len); + if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) { + var path_buf: [4104]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits + var argv: [64:null]?[*:0]const u8 = @splat(null); + argv[0] = path.ptr; + for (args[1..], 1..) |a, k| argv[k] = a.ptr; + _ = execvp(path.ptr, &argv); + }; + }; + // Said plainly, never a Zig error trace: a name a live session's + // socket holds already (a plain session is named by its pid too). + if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name}); + if (opts.ninep_name.len == 0) opts.ninep_name = name; + // Said where it was started (stderr, as the log says it): no pane + // anyone sees would show it. The session runs on, with no 9P. + var pid_buf: [16]u8 = undefined; + var words_buf: [256]u8 = undefined; + const entry = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&pid_buf, "{d}", .{std.c.getpid()}) catch unreachable; // a pid fits 16 + if (ninep_io.noSocket(entry, &words_buf)) |words| { + var line_buf: [300]u8 = undefined; + std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&line_buf, "pardes: {s}\n", .{words}) catch unreachable) catch {}; // 256 fits 300 + } + // Nobody's size yet: one roomy enough for a script's panes; `size` + // sets another, and an attached terminal or window its own. + opts.cols = 160; + opts.rows = 50; + } + const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty; + var term: @import("core").tui.Term = if (detach != null) .detached else .open; + var detached = detach != null; + upgrade.remember(args); + if (upgrade.resumed) |*rec| { + // Close-on-exec again: a shell forked from here inherits none. + rec.closeOnExec(true); + opts.load_path = rec.dump; + term = .detached; + for (rec.ttys[0..rec.nttys]) |t| if (t.primary) { + term = .{ .fd = .{ .fd = t.fd, .termios = t.termios } }; + }; + detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0; + daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached); + } else if (daemon.wanted()) { + if (detach != null or pardes.platform == .gui) { + _ = daemon.register(null, kind, opts.ninep_name, detach != null); + } else if (pardes.platform == .tui) fork: { + // A terminal's session is forked off its stub, which stays the + // job the shell waits on: Detach (or the terminal's end) ends + // the job and leaves the session running (daemon.forkSession). + // The daemon is reached or started first, from this small + // process, and the terminal opened while it is this one's. + const conn = daemon.connect(true) orelse break :fork; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) { + daemon.startPending(true); + _ = std.c.close(conn); + break :fork; + } + // Started in the background, the job stops here until it is + // brought to the foreground, as one making its terminal raw does. + // std.posix's termios, not std.c's: glibc's is the bigger struct. + if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} + daemon.forkSession(conn) orelse { + daemon.startPending(true); + _ = std.c.close(fd); + _ = std.c.close(conn); + break :fork; + }; + _ = daemon.register(conn, .tty, opts.ninep_name, false); + term = .{ .fd = .{ .fd = fd } }; + } + } + defer daemon.quit(); + errdefer daemon.tellStubExit(1); + switch (pardes.platform) { + .tui => @import("core").tui.run(init, opts, term) catch |err| switch (err) { + // No controlling terminal (a detached pty, a daemon): said, not + // an error trace. + error.NoDevice => { + std.Io.File.stderr().writeStreamingAll(init.io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {}; + std.process.exit(1); + }, + else => return err, + }, + .gui => try @import("core").gui.run(init, opts, detached), + .macos => unreachable, + } + daemon.tellStubExit(0); +} + +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; +extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; + +/// `pardes --ps`: what the per-user daemon keeps, as a tree; `--kill=<name>` +/// and `--kill-all`: those sessions ended with their shells, a TERM and, +/// for one still there 2 s later, a KILL. +fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) noreturn { + if (comptime !daemon.supported) die(io, "this system has no pardes daemon", .{}); + var words_buf: [300]u8 = undefined; + const words = if (verb == .kill) + std.fmt.bufPrint(&words_buf, "kill {s}", .{name}) catch die(io, "that name is too long", .{}) + else + @tagName(verb); + var buf: [4096]u8 = undefined; + const said = daemon.ask(words, &buf) orelse die(io, "no pardes daemon is running", .{}); + if (std.mem.startsWith(u8, said, "no ")) die(io, "{s}", .{said[3..]}); + if (verb == .list) { + var out: [8192]u8 = undefined; + var w: std.Io.Writer = .fixed(&out); + var lines = std.mem.tokenizeScalar(u8, said, '\n'); + var orphans = false; + while (lines.next()) |line| { + var it = std.mem.tokenizeScalar(u8, line, ' '); + const what = it.next() orelse continue; + const pid = it.next() orelse continue; + var comm_buf: [64]u8 = undefined; + const comm = commOf(io, pid, &comm_buf); + switch (std.meta.stringToEnum(enum { daemon, session, client, shell, orphan }, what) orelse continue) { + .daemon => w.print("pardes daemon {s}\n", .{pid}) catch break, + .session => { + const kind = it.next() orelse ""; + const state = it.next() orelse ""; + w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break; + }, + .client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break, + .shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break, + .orphan => { + if (!orphans) w.writeAll(" shells no session holds (Adopt takes them, --kill-all ends them)\n") catch break; + orphans = true; + w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; + }, + } + } + std.Io.File.stdout().writeStreamingAll(io, w.buffered()) catch {}; + std.process.exit(0); + } + var pids: [64]std.c.pid_t = undefined; + var n: usize = 0; + var it = std.mem.tokenizeScalar(u8, said, ' '); + _ = it.next(); // ok + while (it.next()) |p| if (n < pids.len) { + pids[n] = std.fmt.parseInt(std.c.pid_t, p, 10) catch continue; + n += 1; + }; + // Gone once the daemon no longer lists them: a session's link ends with + // its process, a zombie's too, which kill(pid, 0) would call alive. + const Gone = struct { + fn all(list: []const std.c.pid_t, ms: u32) bool { + var waited: u32 = 0; + while (true) : (waited += 20) { + var reply: [4096]u8 = undefined; + const now = daemon.ask("list", &reply) orelse return true; + var lines = std.mem.tokenizeScalar(u8, now, '\n'); + const left = while (lines.next()) |line| { + var fields = std.mem.tokenizeScalar(u8, line, ' '); + if (!std.mem.eql(u8, fields.next() orelse "", "session")) continue; + const pid = std.fmt.parseInt(std.c.pid_t, fields.next() orelse "", 10) catch continue; + if (std.mem.indexOfScalar(std.c.pid_t, list, pid) != null) break true; + } else false; + if (!left) return true; + if (waited >= ms) return false; + const ts: std.c.timespec = .{ .sec = 0, .nsec = 20 * std.time.ns_per_ms }; + _ = std.c.nanosleep(&ts, null); + } + } + }; + if (!Gone.all(pids[0..n], 2000)) { + for (pids[0..n]) |p| _ = std.c.kill(p, .KILL); + if (!Gone.all(pids[0..n], 1000)) die(io, "a session would not end, even killed", .{}); + } + std.process.exit(0); +} + +/// The command `pid` runs, as /proc says it (Linux); empty where it does not. +fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 { + var path_buf: [64]u8 = undefined; + const path = std.fmt.bufPrint(&path_buf, "/proc/{s}/comm", .{pid}) catch return ""; + return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n"); +} + +/// The replica client of this build's frontend: a terminal's (tui.zig) or a +/// window's (gui.zig). +fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void { + switch (pardes.platform) { + .tui => try @import("core").tui.runClient(init, opts, path, name, far), + .gui => try @import("core").gui.runClient(init, opts, path, name, far), + else => unreachable, + } +} + +/// `pardes --attach=<where>:<name>` (`pardes-gui` too): a replica client +/// (tui.zig and gui.zig `runClient`), through the socket `where` names, or +/// through `ssh -L` of host `where`'s replica socket to one of this +/// process's. +fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8, name: []const u8) noreturn { + const io = init.io; + if (comptime pardes.platform != .tui and pardes.platform != .gui) unreachable; + if (std.mem.indexOfScalar(u8, where, '/') != null) { + clientOf(init, opts, where, name, false) catch |err| die(io, "--attach: {t}", .{err}); + std.process.exit(0); + } + // ssh -L <here>:<there> <host>, until the socket here answers. + var here_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const tmp = std.mem.span(std.c.getenv("TMPDIR") orelse "/tmp"); + const here = std.fmt.bufPrintSentinel(&here_buf, "{s}/pardes-ssh-{d}.sock", .{ tmp, std.c.getpid() }, 0) catch die(io, "--attach: TMPDIR is too long for a socket's path", .{}); + var there_buf: [ninep_io.sun_path_len + 64:0]u8 = undefined; + var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const dir = if (std.c.getenv("PARDES_REMOTE_RUNTIME")) |d| std.mem.span(d) else ninep_io.socketDir(&dir_buf) orelse die(io, "--attach: no runtime directory to name the far socket by: set PARDES_REMOTE_RUNTIME", .{}); + var forward_buf: [2 * ninep_io.sun_path_len + 64]u8 = undefined; + const there = std.fmt.bufPrintSentinel(&there_buf, "{s}/pardes-replica.sock", .{dir}, 0) catch unreachable; + const forward = std.fmt.bufPrintSentinel(&forward_buf, "{s}:{s}", .{ here, there }, 0) catch unreachable; + var host_buf: [256]u8 = undefined; + const host = std.fmt.bufPrintSentinel(&host_buf, "{s}", .{where}, 0) catch die(io, "--attach: that host's name is too long", .{}); + var argv: [48:null]?[*:0]const u8 = @splat(null); + var n: usize = 0; + var words_buf: [1024]u8 = undefined; + // Not `ssh -C`: what the session sends a far client is zstd already + // (replica.zig), and zlib over it costs both ends' time for nothing. + // ponytail: what the client sends goes as it is, keys and a paste + // alike; a big paste through a slow link is the ceiling, and would be + // an envelope of its own. $PARDES_SSH, when set, is the whole command. + var words = std.mem.tokenizeScalar(u8, std.mem.span(std.c.getenv("PARDES_SSH") orelse "ssh"), ' '); + var at: usize = 0; + while (words.next()) |w| { + if (n >= 40 or at + w.len + 1 > words_buf.len) die(io, "--attach: PARDES_SSH has too many words", .{}); + @memcpy(words_buf[at..][0..w.len], w); + words_buf[at + w.len] = 0; + argv[n] = @ptrCast(&words_buf[at]); + n += 1; + at += w.len + 1; + } + // A terminal asked for and a command that waits, not -N: only an + // interactive connection gets TCP_NODELAY from ssh and sshd, and with + // Nagle each key in a burst waited for the last one's ACK, a round trip. + for ([_][*:0]const u8{ "-tt", "-q", "-o", "ExitOnForwardFailure=yes", "-L", forward.ptr, host.ptr, "exec sleep 2147483647" }) |a| { + argv[n] = a; + n += 1; + } + _ = std.c.unlink(here); + const pid = std.c.fork(); + if (pid < 0) die(io, "--attach: no fork for ssh", .{}); + if (pid == 0) { + // A client killed outright takes its ssh with it. + daemon.hupOnStubDeath(true); + const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDONLY }, @as(std.c.mode_t, 0)); + if (null_fd >= 0) _ = std.c.dup2(null_fd, 0); + _ = execvp(argv[0].?, &argv); + std.c._exit(127); + } + // Ended at the client's exit, whatever path it takes there (its own + // words on a refused redial exit from inside it). ponytail: a client + // that crashes leaves its socket's file behind; its ssh goes. + const Ssh = struct { + var child: std.c.pid_t = 0; + var path: [:0]const u8 = ""; + fn end() callconv(.c) void { + if (child > 0) { + _ = std.c.kill(child, .TERM); + _ = std.c.waitpid(child, null, 0); + } + _ = std.c.unlink(path); + } + }; + Ssh.child = pid; + Ssh.path = here; + _ = atexit(Ssh.end); + var waited: u32 = 0; + while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) { + var status: c_int = 0; + if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) { + Ssh.child = 0; + die(io, "--attach: ssh to {s} ended before its forward was up", .{where}); + } + if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where}); + const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; + _ = std.c.nanosleep(&ts, null); + } + clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err}); + std.process.exit(0); +} + +/// `pardes --attach[=name]` in a terminal: this terminal handed (through +/// the daemon) to the detached session of that name, or the only one, and +/// this process its stub until the session leaves it. `pardes-gui +/// --attach`: the session asked to open its window again, and done. A +/// session attached already, or of the other kind, is joined as a replica +/// client, through this machine's replica socket. +fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { + const io = init.io; + var words: [600]u8 = undefined; + if (comptime !daemon.supported) die(io, "--attach: this system has no pardes daemon to attach through", .{}); + if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) { + .ok => std.process.exit(0), + .no => |why| die(io, "--attach: {s}", .{why}), + .other => |named| crossAttach(init, opts, named), + }; + const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); + if (fd < 0) die(io, "--attach: no terminal to attach: /dev/tty will not open", .{}); + if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} + var pipe: [2]std.c.fd_t = undefined; + if (std.c.pipe(&pipe) != 0) die(io, "--attach: no pipe for the session to say when it leaves", .{}); + ninep_io.setCloexec(pipe[0]); + ninep_io.setCloexec(pipe[1]); + switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) { + .ok => |pid| { + _ = std.c.close(fd); + _ = std.c.close(pipe[1]); + daemon.stubWait(pid, false, pipe[0]); + }, + .no => |why| die(io, "--attach: {s}", .{why}), + .other => |named| { + _ = std.c.close(fd); + _ = std.c.close(pipe[0]); + _ = std.c.close(pipe[1]); + crossAttach(init, opts, named); + }, + } +} + +/// A session attached already or of the other kind (`--attach`'s): a +/// replica client of it here. +fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { + var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; + const sock = daemon.replicaSocket(&sock_buf) orelse die(init.io, "--attach: no runtime directory for the replica socket", .{}); + attachClient(init, opts, sock, name); +} + +/// Where Recent's file (0.24) and the store before it were kept: +/// $XDG_STATE_HOME/pardes, else ~/.local/state/pardes. A state file that +/// holds no Recent yet reads them once (Db.zig). +fn oldRecentDir(arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { + if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.Io.Dir.path.isAbsolute(base)) + return std.Io.Dir.path.join(arena, &.{ base, "pardes" }) catch null; + const home = env.get("HOME") orelse return null; + if (home.len == 0) return null; + return std.Io.Dir.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch null; +} + +test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { + const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; + try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); + try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); + try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); + try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); + try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); +} + +test "cli: docs/typ/command-line.txt is what pardes help --all prints" { + if (comptime !ninep_io.supported) return error.SkipZigTest; + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + const t = try Tree.open(std.testing.io, a, null); + defer t.f.close(); + var out: std.Io.Writer.Allocating = .init(a); + try writeHelpAll(&out.writer, t); + var dir = try std.Io.Dir.cwd().openDir(std.testing.io, @import("doc_typ").dir, .{}); + defer dir.close(std.testing.io); + const committed = try dir.readFileAlloc(std.testing.io, "command-line.txt", a, .limited(1 << 20)); + if (!std.mem.eql(u8, committed, out.written())) { + std.debug.print("docs/typ/command-line.txt is stale: run `zig build builtins-json -Dplatform=tui --prefix <dir>`\n", .{}); + return error.StaleCommandLine; + } +} + +test "cli: the first screen names every command, and every flag has its help" { + var buf: [8192]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try writeFirstScreen(&w); + for (std.enums.values(Cmd)) |c| { + var name: [32]u8 = undefined; + try std.testing.expect(std.mem.indexOf(u8, w.buffered(), try std.fmt.bufPrint(&name, "\n {t}", .{c})) != null); + } + w = .fixed(&buf); + try writeLeaf(&w, .new); + for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old) + try std.testing.expect(std.mem.indexOf(u8, w.buffered(), @tagName(f)) != null); +} + +test "cli: a /commands line parses into its word" { + const w = Word.parse("Wrap root on,off -- Wrap long lines.").?; + try std.testing.expectEqualStrings("Wrap", w.name); + try std.testing.expect(!w.arg); + try std.testing.expectEqualStrings("root", w.scope); + try std.testing.expectEqualStrings("on,off", w.choices); + try std.testing.expectEqualStrings("Wrap long lines.", w.doc); + const e = Word.parse("Edit arg both -- Run sam's Edit.").?; + try std.testing.expect(e.arg); + try std.testing.expectEqualStrings("both", e.scope); + try std.testing.expectEqualStrings("addon", Word.parse("PdfFit arg pane -- Fit. (addon pdf)").?.group()); + try std.testing.expectEqual(@as(?Word, null), Word.parse("Lonely")); +} + +test "tcgetattr writes nothing past a Zig termios" { + if (comptime !(builtin.os.tag == .linux and builtin.abi.isGnu())) return error.SkipZigTest; + const master = std.c.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(std.c.mode_t, 0)); + if (master < 0) return error.SkipZigTest; + defer _ = std.c.close(master); + var s: extern struct { t: std.c.termios, canary: [32]u8 } = .{ .t = undefined, .canary = @splat(0xAA) }; + try std.testing.expectEqual(0, std.c.tcgetattr(master, &s.t)); + try std.testing.expectEqualSlices(u8, &@as([32]u8, @splat(0xAA)), &s.canary); + try std.testing.expectEqual(0, std.c.tcsetattr(master, .NOW, &s.t)); + try std.testing.expectEqual(-1, std.c.tcgetattr(-1, &s.t)); +} + +test { + _ = pardes.config.User; + // The rest this block collected is collected where it lives now: the + // runtime's files by runtime/root.zig's test block, the core's (the + // frontends among them) by pardes.zig's. The window stays named: its + // C's allocator (ui_malloc and the rest) is gui.zig's. + if (comptime pardes.platform == .tui) { + _ = @import("core").tui; + } + if (comptime pardes.platform == .gui) _ = @import("core").gui; +} diff --git a/runtime/root.zig b/runtime/root.zig new file mode 100644 index 00000000..86fd9a75 --- /dev/null +++ b/runtime/root.zig @@ -0,0 +1,26 @@ +//! What runs a session: the daemon and a session's link to it, the +//! upgrade, the crash file, `--addon-test`, the 9P listener and client +//! (9p_io) over cloud9's options (9p). Module `runtime`; a product's root +//! (main.zig, macos.zig) sits beside it as a module of its own, naming it +//! and `core`. +pub const daemon = @import("daemon.zig"); +pub const upgrade = @import("upgrade.zig"); +pub const crash = @import("crash.zig"); +pub const addon_test = @import("addon_test.zig"); +pub const ninep_io = @import("9p_io.zig"); +pub const ninep = @import("9p.zig"); + +test { + _ = daemon; + _ = upgrade; + _ = ninep_io; + _ = ninep_io.Client; + _ = ninep; + // main.zig's test block collected the crash file's: a shell's build + // (shell-test); the core without a terminal (core-test) never compiled it. + if (comptime @import("term_options").terminal) _ = crash; + // A window's build links the window's C (font.c over FreeType and + // HarfBuzz) into each of its programs, and their allocator (ui_malloc + // and the rest) is gui.zig's. + if (comptime @import("term_options").terminal and @import("pardes_config").platform == .gui) _ = @import("core").gui; +} diff --git a/runtime/skill.txt b/runtime/skill.txt new file mode 100644 index 00000000..8ae6a15a --- /dev/null +++ b/runtime/skill.txt @@ -0,0 +1,47 @@ +pardes, for an agent +==================== + +pardes is an editor (acme's mouse, helix's keys) and a terminal multiplexer, +and every session is a file tree served over 9P: panes, columns, tags and +the session are files. This guide is the judgement; the inventory is the +binary's own and the session's, and it is always the one to trust: + + pardes help the commands + pardes help PATH what the tree's README says of a file (pane, log...) + pardes words every builtin; pardes help WORD for one + pardes fs ls PATH what a session serves now + +Find the session + In a pane's shell, $PARDES_9P is its socket and $PARDES_PANE the pane: + every command below acts there. From outside, `pardes ps` lists the + sessions and -s NAME picks one. Never act on a session you did not start + or were not asked to touch: start your own, detached, and end it by name. + + pardes new --detach=work & a session with no terminal, named work + pardes fs read index -s work a line per pane + pardes kill work done with it + +Recipes + n=$(pardes fs read pane/new -s work) make a pane, take its serial + pardes fs write pane/$n/name /tmp/x.txt -s work name it + printf 'text\n' | pardes fs write pane/$n/body -s work replace its text + pardes do Save -p $n -s work a pane's builtin + pardes do Newcol -s work a session's builtin + pardes fs write pane/$n/ctl 'Edit ,x/foo/c/bar/' -s work sam's Edit, one undo step + pardes fs ask pane/$n/look /etc/hosts:3 -s work open a file there; answers the pane it went to + pardes fs ask pane/$n/pty/run make -s work on a terminal pane: exit N, then the output + pardes fs follow log follow -s work events as they come (Ctrl-C ends it) + pardes fs read screen -s work what is drawn, as JSON + +Traps + A refusal is printed in the session's words and the exit is 1; through a + mount the same refusal is only EINVAL or EIO (grep '^err' log says why). + Pane words (Save Undo Del) go to a pane's ctl, settings and session words + to the root's: pardes do picks the ctl, pardes help WORD says which. + The root's look and exec act at the pane with the keyboard, which a person + may be using: write a pane's own look and exec instead. + addr is the pane's and moves on: each /re/ searches from the last. + Exit, Restore, Del and get refuse once over unsaved text; the same word + again discards it. + A read the session holds (log follow, an event file) waits for ever only + under fs follow; other calls give up after 30 s, saying so. diff --git a/runtime/upgrade.zig b/runtime/upgrade.zig new file mode 100644 index 00000000..e145eb70 --- /dev/null +++ b/runtime/upgrade.zig @@ -0,0 +1,510 @@ +//! Upgrade (docs/next-daemon.md, "Phase 6: upgrade notes"): a running +//! session, and the daemon, moved onto the pardes installed since they +//! started, in place. +//! +//! At a step boundary a session commits its dump to the state file +//! (Db.zig, as `upgrade-<pid>`) and execs the path it was started from. Its pty masters, terminals, stubs and daemon +//! link stay open across the exec, named in a record on the new command +//! line: `--upgraded=<record>` ahead of the arguments it was started with. +//! The pid stays, so its shells stay its children; the new process loads +//! the dump and takes those fds back (each host's `resume`). A new build +//! that cannot load the dump execs the old one again, from the copy this +//! process left open (Linux), and with none it starts afresh with the +//! shells adopted, the dump left for a Restore by hand. A record of an older +//! build names a `.dump` file instead (0.24 reads one, and deletes it once +//! loaded). +const std = @import("std"); +const builtin = @import("builtin"); +/// libc: exec of the new build with fds held across it, and /proc/self/exe opened before it. +const libc = std.c; +const posix = std.posix; +const pardes = @import("core"); + +pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd; +pub const flag = "--upgraded="; + +/// What this build says it is (`pardes --version`'s first line). +pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version; + +// ---- the path it was started from ---- + +/// The path this process was started from, what Upgrade execs: a reinstall +/// puts the new build there, while /proc/self/exe names the old file, +/// deleted by then. +var exe_buf: [4096:0]u8 = undefined; +var exe_len: usize = 0; +/// The arguments it was started with (an upgrade's record left out). +var given: []const [:0]const u8 = &.{}; +/// The file at that path when it started, and the newer one last said. +var started_inode: ?u64 = null; +var told_inode: ?u64 = null; + +var located = false; + +/// Its arguments kept, at its start; an upgraded process's path is the one +/// its record names (the system would name a fallback's old binary, +/// deleted). +pub fn remember(args: []const [:0]const u8) void { + given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{}; + if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) { + @memcpy(exe_buf[0..rec.exe.len], rec.exe); + exe_buf[rec.exe.len] = 0; + exe_len = rec.exe.len; + }; +} + +/// Its path asked of the system (a readlink) and the file there now (a +/// stat), once: after the first frame, off a startup's way (the hosts' +/// loops; nothing is reinstalled within a frame of a start). +pub fn locate() void { + if (located) return; + located = true; + if (exe_len == 0) { + const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), &exe_buf) catch 0; + exe_buf[n] = 0; + exe_len = n; + } + if (exe()) |path| started_inode = inodeOf(path); +} + +fn inodeOf(path: [:0]const u8) ?u64 { + const st = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{}) catch return null; + return @intCast(st.inode); +} + +/// A newer build installed at that path since this process started, said +/// in a line, once a build: asked at a focus-in, where one comes back from +/// rebuilding (a stat). ponytail: explicit only, no watch and no automatic +/// upgrade. +pub fn noticeNewer(core: *pardes.Pardes) void { + if (newer()) core.setMessage(core.view().active, pardes.newer_build_words); +} + +/// Whether to say a newer build is installed now (`noticeNewer`): the +/// tty's Host answers the core's focus step with it, so its replica +/// clients take the line from the tape. +pub fn newer() bool { + const was = started_inode orelse return false; + const now = inodeOf(exe() orelse return false) orelse return false; + if (now == was or told_inode == now) return false; + told_inode = now; + return true; +} + +pub fn exe() ?[:0]const u8 { + return if (exe_len == 0) null else exe_buf[0..exe_len :0]; +} + +// ---- the record ---- + +pub const Pty = struct { pane: u8, pid: libc.pid_t, fd: c_int }; +/// A terminal and its view: the primary one's stub is daemon.stub; its +/// termios is the cooked one it is put back to at the end (it is raw now). +pub const Tty = struct { view: u8, fd: c_int, stub: c_int, primary: bool, termios: posix.termios }; + +pub const Record = struct { + /// daemon.link and daemon.stub. + link: c_int = -1, + stub: c_int = -1, + /// The binary being replaced, open (Linux): a new one that cannot load + /// the dump execs it again. + old: c_int = -1, + /// A window was open (the GUI). + window: bool = false, + ptys: [pardes.MAX_PANES]Pty = undefined, + nptys: usize = 0, + ttys: [pardes.views.max]Tty = undefined, + nttys: usize = 0, + /// The path exec'd, the one a later Upgrade execs again. + exe: []const u8 = "", + /// The state file the session's dump is in (an older build's: the + /// `.dump` file it is). + dump: []const u8 = "", + /// The dump's label there; none, `dump` is a file of its own. + label: []const u8 = "", + /// Why the new build could not load it: a start that went back to the + /// old binary says so. + refused: []const u8 = "", + /// This process's own: its dump would not load, so it started afresh + /// and adopts the shells. + fresh: bool = false, + + pub fn addPty(rec: *Record, pane: usize, pid: libc.pid_t, fd: c_int) void { + if (rec.nptys == rec.ptys.len or fd < 0) return; + rec.ptys[rec.nptys] = .{ .pane = @intCast(pane), .pid = pid, .fd = fd }; + rec.nptys += 1; + } + + pub fn addTty(rec: *Record, t: Tty) void { + if (rec.nttys == rec.ttys.len or t.fd < 0) return; + rec.ttys[rec.nttys] = t; + rec.nttys += 1; + } + + /// Every fd it names, close-on-exec (`on`) or kept across one. + pub fn closeOnExec(rec: *const Record, on: bool) void { + const set = struct { + fn f(fd: c_int, cloexec: bool) void { + if (fd >= 0) _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, if (cloexec) 1 else 0)); + } + }.f; + set(rec.link, on); + set(rec.stub, on); + set(rec.old, on); + for (rec.ptys[0..rec.nptys]) |p| set(p.fd, on); + for (rec.ttys[0..rec.nttys]) |t| { + set(t.fd, on); + set(t.stub, on); + } + } + + /// One `word value` a line, the dump's path last (its line is all of it). + pub fn encode(rec: *const Record, w: *std.Io.Writer) !void { + try w.print("link {d}\nstub {d}\nold {d}\nwindow {d}\n", .{ rec.link, rec.stub, rec.old, @intFromBool(rec.window) }); + for (rec.ptys[0..rec.nptys]) |p| try w.print("pty {d} {d} {d}\n", .{ p.pane, p.pid, p.fd }); + for (rec.ttys[0..rec.nttys]) |t| try w.print("tty {d} {d} {d} {d} {x}\n", .{ t.view, t.fd, t.stub, @intFromBool(t.primary), std.mem.asBytes(&t.termios) }); + if (rec.refused.len > 0) try w.print("refused {s}\n", .{rec.refused}); + if (rec.label.len > 0) try w.print("label {s}\n", .{rec.label}); + try w.print("exe {s}\ndump {s}\n", .{ rec.exe, rec.dump }); + } + + /// `text`'s record; its strings are slices of it. + pub fn decode(text: []const u8) !Record { + var rec: Record = .{}; + var lines = std.mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (line.len == 0) continue; + const sp = std.mem.indexOfScalar(u8, line, ' ') orelse return error.BadRecord; + const word = line[0..sp]; + const rest = line[sp + 1 ..]; + var it = std.mem.tokenizeScalar(u8, rest, ' '); + // A word of a later build's record is passed over. + switch (std.meta.stringToEnum(enum { link, stub, old, window, pty, tty, refused, label, exe, dump }, word) orelse continue) { + .link => rec.link = try std.fmt.parseInt(c_int, rest, 10), + .stub => rec.stub = try std.fmt.parseInt(c_int, rest, 10), + .old => rec.old = try std.fmt.parseInt(c_int, rest, 10), + .window => rec.window = std.mem.eql(u8, rest, "1"), + .pty => { + if (rec.nptys == rec.ptys.len) return error.BadRecord; + const pane = try std.fmt.parseInt(u8, it.next() orelse return error.BadRecord, 10); + if (pane >= pardes.MAX_PANES) return error.BadRecord; + rec.ptys[rec.nptys] = .{ + .pane = pane, + .pid = try std.fmt.parseInt(libc.pid_t, it.next() orelse return error.BadRecord, 10), + .fd = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10), + }; + rec.nptys += 1; + }, + .tty => { + if (rec.nttys == rec.ttys.len) return error.BadRecord; + var t: Tty = .{ + .view = try std.fmt.parseInt(u8, it.next() orelse return error.BadRecord, 10), + .fd = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10), + .stub = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10), + .primary = std.mem.eql(u8, it.next() orelse return error.BadRecord, "1"), + .termios = undefined, + }; + const hex = it.next() orelse return error.BadRecord; + // Another build's termios is the kernel's, of one size. + if (hex.len != 2 * @sizeOf(posix.termios) or t.view >= pardes.views.max) return error.BadRecord; + _ = try std.fmt.hexToBytes(std.mem.asBytes(&t.termios), hex); + rec.ttys[rec.nttys] = t; + rec.nttys += 1; + }, + .refused => rec.refused = rest, + .label => rec.label = rest, + .exe => rec.exe = rest, + .dump => rec.dump = rest, + } + } + if (rec.dump.len == 0) return error.BadRecord; + return rec; + } +}; + +/// The record this process was started with (`--upgraded=`), set by main. +pub var resumed: ?Record = null; + +// ---- before: asking the new binary, and the exec ---- + +pub const Checked = union(enum) { ok: []const u8, no: []const u8 }; + +/// `path --version` run as it is: a binary not there, not a pardes, or one +/// that cannot start, found before anything is let go. Its first line +/// (`pardes <version>`), or why not, in `buf`. +pub fn check(path: [:0]const u8, buf: []u8) Checked { + var pipe: [2]c_int = undefined; + if (libc.pipe(&pipe) != 0) return .{ .no = "Upgrade: no pipe to ask the new pardes its version" }; + const argv = [_:null]?[*:0]const u8{ path, "--version", null }; + const pid = libc.fork(); + if (pid < 0) { + _ = libc.close(pipe[0]); + _ = libc.close(pipe[1]); + return .{ .no = "Upgrade: no process to ask the new pardes its version" }; + } + if (pid == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.dup2(pipe[1], 1); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) { + _ = libc.dup2(null_fd, 0); + _ = libc.dup2(null_fd, 2); + } + _ = libc.execve(path, &argv, @ptrCast(libc.environ)); + libc._exit(127); + } + _ = libc.close(pipe[1]); + var len: usize = 0; + var waited = false; + while (len < buf.len) { + // A pardes answers --version in milliseconds; 10 s is one that hangs. + var fds = [_]libc.pollfd{.{ .fd = pipe[0], .events = libc.POLL.IN, .revents = 0 }}; + const ready = libc.poll(&fds, 1, 10_000); + if (ready < 0 and libc.errno(ready) == .INTR) continue; + if (ready <= 0) { + _ = libc.kill(pid, .KILL); + waited = true; + break; + } + const n = libc.read(pipe[0], buf[len..].ptr, buf.len - len); + if (n < 0 and libc.errno(n) == .INTR) continue; + if (n <= 0) break; + len += @intCast(n); + } + _ = libc.close(pipe[0]); + var status: c_int = 0; + while (libc.waitpid(pid, &status, 0) < 0 and libc.errno(-1) == .INTR) {} + const s: u32 = @bitCast(status); + const said = buf[0..len]; + const first = said[0 .. std.mem.indexOfScalar(u8, said, '\n') orelse said.len]; + if (!waited and libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) == 0 and std.mem.startsWith(u8, first, "pardes ")) return .{ .ok = first }; + // The words go where the line was: the rest of `buf`. + var tail: [96]u8 = undefined; + const how = if (waited) + "did not answer --version in 10 s" + else if (libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) == 127) + "would not start" + else if (libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) != 0) + std.fmt.bufPrint(&tail, "exited {d} at --version", .{libc.W.EXITSTATUS(s)}) catch unreachable // a status number fits 96 + else if (libc.W.IFSIGNALED(s)) + std.fmt.bufPrint(&tail, "died of signal {d} at --version", .{libc.W.TERMSIG(s)}) catch unreachable // a signal number fits 96 + else + "does not answer --version as a pardes does"; + return .{ .no = std.fmt.bufPrint(buf, "Upgrade: {s} {s}; this session stays as it is", .{ path[0..@min(path.len, 400)], how }) catch "Upgrade: the new pardes would not start; this session stays as it is" }; +} + +/// The binary this process runs, open, for a new one to fall back to: on +/// Linux the file even once deleted. ponytail: FreeBSD has no /proc by +/// default, so a new build there that cannot load a dump starts afresh. +fn openSelf() c_int { + if (comptime builtin.os.tag != .linux) return -1; + return libc.open("/proc/self/exe", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(libc.mode_t, 0)); +} + +/// This process exec'd as `path` (or the binary open on `old`), the record +/// on its command line and the fds it names kept open. Returns only when +/// the exec failed, those fds close-on-exec again: why, in words. +pub fn exec(gpa: std.mem.Allocator, path: ?[:0]const u8, old: c_int, rec: *const Record) []const u8 { + var text: std.Io.Writer.Allocating = .init(gpa); + defer text.deinit(); + text.writer.writeAll(flag) catch return "no memory for its record"; + rec.encode(&text.writer) catch return "no memory for its record"; + text.writer.writeByte(0) catch return "no memory for its record"; + const record: [*:0]const u8 = @ptrCast(text.written().ptr); + const argv = gpa.allocSentinel(?[*:0]const u8, given.len + 2, null) catch return "no memory for its arguments"; + defer gpa.free(argv); + argv[0] = if (path) |p| p.ptr else if (exe()) |e| e.ptr else "pardes"; + argv[1] = record; + for (given, argv[2..]) |a, *slot| slot.* = a.ptr; + rec.closeOnExec(false); + const envp: [*:null]const ?[*:0]const u8 = @ptrCast(libc.environ); + // execveat by its syscall: musl (a static pardes) has no wrapper. + const e = if (path) |p| + libc.errno(libc.execve(p, argv.ptr, envp)) + else if (comptime builtin.os.tag == .linux) + std.os.linux.errno(std.os.linux.execveat(old, "", argv.ptr, envp, .{ .SYMLINK_NOFOLLOW = false, .EMPTY_PATH = true })) + else + libc.errno(@as(c_int, -1)); + rec.closeOnExec(true); + return switch (e) { + .NOENT => "it is not there", + .ACCES, .PERM => "it may not be run", + .NOEXEC => "it is not a program this system runs", + .@"2BIG" => "its record and arguments are too long", + .NOMEM => "no memory for it", + .TXTBSY => "it is still being written", + else => "the exec failed", + }; +} + +/// The state file's path an upgrade's record names (`dumpInto`'s). +var state_path: [4200]u8 = undefined; + +/// An Upgrade's dump, the terminal's and the window's alike: committed to +/// the state file as `upgrade-<pid>` (its label kept in `at`), where a +/// Restore finds it, and named in `rec`, the binary it replaces held open +/// for a new build that cannot load it. Null when it is, else why in words +/// (`why`'s). +pub fn dumpInto(core: *pardes.Pardes, rec: *Record, at: *[1024:0]u8, why: []u8) ?[]const u8 { + const path = pardes.Db.statePath(&state_path, core.settings.dump_dir.get()) orelse return "Upgrade: no directory for the session's dump; this session stays as it is"; + var name: [64]u8 = undefined; + const label = std.fmt.bufPrint(&name, "upgrade-{d}", .{std.c.getpid()}) catch unreachable; + const bytes = pardes.dump.image(core, label) catch |err| { + var words: [128]u8 = undefined; + return std.fmt.bufPrint(why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump"; + }; + defer core.gpa.free(bytes); + const put = core.db.putDump(core, bytes, label, at[0 .. at.len - 1]) catch |err| { + var words: [128]u8 = undefined; + return std.fmt.bufPrint(why, "Upgrade: the session's dump could not be written to {s} ({s}); it stays as it is", .{ path[0..@min(path.len, 600)], pardes.Messages.errorWords(err, &words) }) catch "Upgrade: its dump could not be written"; + }; + at[put.len] = 0; + rec.dump = path; + rec.label = at[0..put.len]; + rec.old = openSelf(); + return null; +} + +/// The daemon told, 9P's last answers sent (`fs`), and this process +/// exec'd as `path` with `rec`, whose dump `dumpInto` labelled `at`. +/// Returns only when the exec failed, the binary it replaces let go (the +/// dump stays, a dump among the state file's): why, in words (`why`'s). +pub fn execAs(gpa: std.mem.Allocator, path: [:0]const u8, rec: *const Record, at: [*:0]const u8, fs: ?*@import("9p_io.zig").Listener, why: []u8) []const u8 { + _ = at; + @import("daemon.zig").upgraded(); + if (fs) |f| f.flushOut(); + const err_words = exec(gpa, path, -1, rec); + // Still here: the exec failed. + if (rec.old >= 0) _ = libc.close(rec.old); + return std.fmt.bufPrint(why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start"; +} + +// ---- after: the new process ---- + +/// The core an upgraded process starts with: the session its dump is. A +/// build that cannot load it execs the binary it replaced to load it; with +/// none, a fresh session (`fresh`) the host adopts the shells into, the +/// dump left where a Restore finds it. `PARDES_TEST_UPGRADE_REFUSE` refuses +/// a load as such a build would (test/daemon.py's failing upgrade), in the +/// first start only, or (`all`) in the start it falls back to as well. +pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Options, rec: *Record) !*pardes.Pardes { + var kept: [pardes.MAX_PANES]bool = @splat(false); + for (rec.ptys[0..rec.nptys]) |p| kept[p.pane] = true; + const loaded = loaded: { + if (libc.getenv("PARDES_TEST_UPGRADE_REFUSE")) |how| if (rec.refused.len == 0 or std.mem.eql(u8, std.mem.span(how), "all")) + break :loaded error.RefusedByTest; + const bytes = (if (rec.label.len > 0) pardes.Db.readDumpAt(gpa, rec.dump, rec.label) else pardes.filesystem.readFile(gpa, rec.dump)) catch |err| break :loaded err; + defer gpa.free(bytes); + break :loaded pardes.dump.resumeFromDump(core_gpa, opts, bytes, &kept); + }; + var buf: [700]u8 = undefined; + // Restore's word for the dump left behind: its label, or its file. + const again_name = if (rec.label.len > 0) rec.label else rec.dump; + if (loaded) |p| { + // An older build's dump, a file of its own, goes once loaded; a + // label stays among the state file's dumps. + if (rec.label.len == 0) { + // fs.readFile read it by this path, 0-terminated in 4096 bytes: + // a longer one was refused there (error.PathTooLong), kept. + var path_buf: [4096]u8 = undefined; + _ = libc.unlink(std.fmt.bufPrintSentinel(&path_buf, "{s}", .{rec.dump}, 0) catch unreachable); + } + // The binary it replaced, let go: held, its file (deleted) would + // keep its blocks for as long as this session runs. + if (rec.old >= 0) _ = libc.close(rec.old); + rec.old = -1; + p.setMessage(p.view().active, if (rec.refused.len > 0) + std.fmt.bufPrint(&buf, "Upgrade: the new build could not load this session ({s}); it goes on as {s}", .{ rec.refused[0..@min(rec.refused.len, 200)], version_line }) catch "Upgrade: the new build could not load this session; it goes on as before" + else + "Upgrade: now " ++ version_line); + return p; + } else |err| { + var words_buf: [128]u8 = undefined; + const why = if (err == error.RefusedByTest) "refused by PARDES_TEST_UPGRADE_REFUSE" else pardes.Messages.errorWords(err, &words_buf); + // The binary it replaced loads its own dump: tried once, never from + // a start that is that fallback already. + if (rec.old >= 0 and rec.refused.len == 0) { + var again = rec.*; + again.refused = why; + again.old = -1; + _ = exec(gpa, null, rec.old, &again); + } + if (rec.old >= 0) _ = libc.close(rec.old); + rec.old = -1; + rec.fresh = true; + var o = opts; + o.load_path = null; + const p = try pardes.Pardes.init(core_gpa, o); + p.setMessage(p.view().active, std.fmt.bufPrint(&buf, "Upgrade: no build could load the session ({s}); its shells are here, and Restore {s} brings the rest back", .{ why, again_name[0..@min(again_name.len, 400)] }) catch "Upgrade: no build could load the session; its dump is kept for a Restore"); + return p; + } +} + +test "an upgrade's record reads back as it was written, and refuses one cut short" { + var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1" }; + rec.addPty(3, 1234, 11); + rec.addPty(0, 99, 12); + var tio: posix.termios = std.mem.zeroes(posix.termios); + std.mem.asBytes(&tio)[0] = 0x5a; + rec.addTty(.{ .view = 2, .fd = 13, .stub = 14, .primary = true, .termios = tio }); + var buf: [4096]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + try rec.encode(&w); + const back = try Record.decode(w.buffered()); + try std.testing.expectEqual(@as(c_int, 5), back.link); + try std.testing.expectEqual(@as(c_int, 9), back.old); + try std.testing.expect(back.window); + try std.testing.expectEqual(@as(usize, 2), back.nptys); + try std.testing.expectEqual(Pty{ .pane = 3, .pid = 1234, .fd = 11 }, back.ptys[0]); + try std.testing.expectEqual(@as(usize, 1), back.nttys); + try std.testing.expect(back.ttys[0].primary and back.ttys[0].view == 2 and back.ttys[0].stub == 14); + try std.testing.expectEqual(@as(u8, 0x5a), std.mem.asBytes(&back.ttys[0].termios)[0]); + try std.testing.expectEqualStrings("/a b/pardes", back.exe); + try std.testing.expectEqualStrings("/home/u/.local/share/pardes/pardes.xitdb", back.dump); + try std.testing.expectEqualStrings("upgrade-1", back.label); + // An older build's: its dump a file, no label. + const older = try Record.decode("link 5\nexe /a\ndump /run/u/pardes-upgrade-1.dump\n"); + try std.testing.expectEqualStrings("/run/u/pardes-upgrade-1.dump", older.dump); + try std.testing.expectEqualStrings("", older.label); + try std.testing.expectError(error.BadRecord, Record.decode("link 5\n")); + try std.testing.expectError(error.BadRecord, Record.decode("tty 0 1 2 1 abc\ndump x\n")); +} + +test "an upgrade from the build before reads the dump file its record names, and deletes it once loaded" { + const gpa = std.testing.allocator; + const p = try pardes.Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("before the upgrade\n"); + const bytes = try pardes.dump.byteDump(p); + defer gpa.free(bytes); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-upgrade-1.dump", .data = bytes }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var text_buf: [4300]u8 = undefined; + // The build before's record: its dump a file, no label. + var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}/pardes-upgrade-1.dump\n", .{dir})); + const q = try load(gpa, gpa, .{ .tty_only = true }, &rec); + defer q.deinit(); + try std.testing.expect(!rec.fresh); + const text = for (q.panes) |slot| { + if (slot) |pane| if (pane.file) |f| if (f.output == null) break f.content; + } else return error.FileLost; + try std.testing.expectEqualStrings("before the upgrade\n", text); + try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(std.testing.io, "pardes-upgrade-1.dump", .{})); +} + +test "an older build's dump named by a path past 4096 bytes is refused in words and kept for a Restore" { + const gpa = std.testing.allocator; + var text_buf: [4200]u8 = undefined; + var long: [4096]u8 = undefined; + @memset(&long, 'd'); + long[0] = '/'; + var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}\n", .{&long})); + const q = try load(gpa, gpa, .{ .tty_only = true }, &rec); + defer q.deinit(); + try std.testing.expect(rec.fresh); + const pane = q.panes[q.view().active].?; + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "Upgrade: no build could load the session") != null); +} |
