summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-29 10:48:56 -0300
committerGabriel Schneider <[email protected]>2026-10-29 12:01:27 -0300
commitcb2a6cd79e443d671f5255d262ea79b7e26552a5 (patch)
treec11e04d42ca3f0f06cb9f0332ebd7d5b76823ed0 /src
parenta73697397ee3f2b7fa7cba08c96f6f81ff7ee04c (diff)
downloadpardes-cb2a6cd79e443d671f5255d262ea79b7e26552a5.tar.gz
pardes-cb2a6cd79e443d671f5255d262ea79b7e26552a5.zip
daemon.zig: one pardes daemon per user, holding pty masters and handing terminals to detached sessions
`pardes --daemon` listens 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 takes the lock, binds and listens itself and queues its own connection; the daemon is then double-forked and exec'd onto that listener and lock (fds 3 and 4), by a terminal's stub after the session's fork, so no startup waits for it: the hello sits queued, and the `ok` is the reader thread's. Another starter waits on the lock; a stale socket is the lock holder's to replace. Idle a second (no connection, no master held), it unlinks the socket and exits. It spawns nothing and is nobody's parent: a session registers on one connection (hello: kind, pid, name, attached or detached), sends a dup of every pty master it forks (`pty`), says which it closed (`close`) and when it ends (`quit`, its shells hang up), and asks for the masters of sessions that died holding them (`adopt`). A master whose shell is gone (POLLHUP, polled with no events, its output never read here) is dropped. `attach` hands a terminal and a stub's pipe (pardes --attach), or a window request (pardes-gui --attach), to the detached session of that name or the only one, and refuses in words: no such session, attached already, the other kind. SOCK_SEQPACKET datagrams, a line of words and the fds they carry. The client half: connect (starting one), register, the session's link and its reader thread, and the stub a terminal's session leaves behind (forkSession, stubWait), which passes WINCH, TERM, INT, QUIT and HUP on and ends with the session's status. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat (limited to 'src')
-rw-r--r--src/daemon.zig862
1 files changed, 862 insertions, 0 deletions
diff --git a/src/daemon.zig b/src/daemon.zig
new file mode 100644
index 00000000..c7729e59
--- /dev/null
+++ b/src/daemon.zig
@@ -0,0 +1,862 @@
+//! 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).
+const std = @import("std");
+const builtin = @import("builtin");
+const libc = std.c;
+const posix = std.posix;
+const ninep_io = @import("9p_io.zig");
+
+pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
+const version = 1;
+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;
+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));
+}
+
+pub 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;
+ }
+}
+
+pub 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.
+pub 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) {
+ const r = libc.recvmsg(fd, &msg, libc.MSG.CMSG_CLOEXEC);
+ 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)]);
+ }
+ }
+ // 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);
+ if (close_range(5, std.math.maxInt(c_uint), 0) != 0) {
+ 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} {s}", .{ version, k, pid, if (detached) "detached" else "attached", 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.
+pub 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;
+}
+
+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 return, &.{master});
+}
+
+/// 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 return, &.{});
+}
+
+pub fn setState(detached: bool) void {
+ tell(if (detached) "state detached" else "state attached", &.{});
+}
+
+/// Asks for the masters of sessions that died holding them; they come back
+/// as an `adopted` note.
+pub fn adopt() void {
+ tell("adopt", &.{});
+}
+
+pub const Note = union(enum) {
+ /// A terminal for a detached tty 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 },
+};
+
+/// 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.mem.eql(u8, verb, "ok")) {
+ up.store(true, .release);
+ } else if (std.mem.eql(u8, verb, "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);
+ } else if (std.mem.eql(u8, verb, "adopted")) {
+ var note: Note = .{ .adopted = .{ .pids = undefined, .fds = undefined, .n = 0 } };
+ const a = &note.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);
+ }
+ }
+}
+
+/// 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 ----
+
+pub const Answer = union(enum) { ok: libc.pid_t, no: []const u8 };
+
+/// 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 };
+ }
+ return .{ .no = if (std.mem.startsWith(u8, got.words, "no ")) got.words[3..] else 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;
+
+/// Detached: the stub is told (and goes), and the pipe let go.
+pub fn tellStubDetached() void {
+ if (stub < 0) return;
+ var buf: [160]u8 = undefined;
+ const said = std.fmt.bufPrint(&buf, "d{s}", .{name()}) catch "d";
+ _ = libc.write(stub, said.ptr, said.len);
+ _ = libc.close(stub);
+ stub = -1;
+}
+
+/// The session's end, `code` its exit status: the stub is told (and goes).
+pub fn tellStubExit(code: u8) void {
+ if (stub < 0) return;
+ var buf: [8]u8 = undefined;
+ const said = std.fmt.bufPrint(&buf, "x{d}", .{code}) catch "x1";
+ _ = libc.write(stub, said.ptr, said.len);
+ _ = libc.close(stub);
+ stub = -1;
+}
+
+/// A terminal refused (an attach that came too late): its stub is told why.
+pub fn refuseStub(fd: c_int, why: []const u8) void {
+ var buf: [256]u8 = undefined;
+ const said = std.fmt.bufPrint(&buf, "r{s}", .{why}) catch "r";
+ _ = 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 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();
+ 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,
+ name: [128]u8 = undefined,
+ name_len: usize = 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,
+};
+
+const Daemon = struct {
+ conns: [max_conns]Conn = @splat(.{}),
+ held: [max_held]Held = @splat(.{}),
+
+ 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 drop(d: *Daemon, h: *Held) void {
+ _ = d;
+ _ = libc.close(h.fd);
+ h.* = .{};
+ }
+
+ fn hangUp(d: *Daemon, i: u8) void {
+ const c = &d.conns[i];
+ _ = libc.close(c.fd);
+ c.* = .{};
+ // Whatever it still held, it died holding: kept for an Adopt.
+ for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) {
+ h.owner = null;
+ };
+ }
+
+ 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 = words.next() orelse return;
+ if (std.mem.eql(u8, verb, "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 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.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", &.{});
+ }
+ if (std.mem.eql(u8, verb, "state")) {
+ c.detached = std.mem.eql(u8, words.next() orelse "", "detached");
+ return;
+ }
+ if (std.mem.eql(u8, verb, "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;
+ };
+ return;
+ }
+ if (std.mem.eql(u8, verb, "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) d.drop(h);
+ return;
+ }
+ if (std.mem.eql(u8, verb, "quit")) {
+ for (&d.held) |*h| if (h.fd >= 0 and h.owner == i) d.drop(h);
+ return;
+ }
+ if (std.mem.eql(u8, verb, "adopt")) {
+ var line: [msg_max]u8 = undefined;
+ var w: std.Io.Writer = .fixed(&line);
+ w.writeAll("adopted") catch {};
+ 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;
+ return;
+ }
+ if (std.mem.eql(u8, verb, "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;
+ const target = d.find(k, wanted_name, &why) catch |err| return d.reply(i, switch (err) {
+ error.Said => 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 "ok 0", &.{});
+ }
+ }
+
+ /// The detached session of kind `k` called `wanted_name`, or the one
+ /// there is when it is empty; else why not, in `why` (0-terminated).
+ fn find(d: *Daemon, k: Kind, wanted_name: []const u8, why: *[512]u8) error{Said}!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) {
+ _ = std.fmt.bufPrint(why, "no '{s}' is {s}={s}`", .{ wanted_name, other, wanted_name }) catch {};
+ return error.Said;
+ }
+ if (!s.detached) {
+ _ = std.fmt.bufPrint(why, "no '{s}' is attached already, to another terminal or window", .{wanted_name}) catch {};
+ return error.Said;
+ }
+ return @intCast(i);
+ };
+ _ = std.fmt.bufPrint(why, "no no session called '{s}'", .{wanted_name}) catch {};
+ return error.Said;
+ }
+ 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.?;
+ if (count == 0 and others == 0) {
+ w.writeAll("no no detached session is running") catch {};
+ return error.Said;
+ }
+ 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 {};
+ return error.Said;
+ }
+ w.print("no {d} detached sessions are running; say which with --attach=<name>:", .{count}) catch {};
+ for (&d.conns) |*s| if (s.fd >= 0 and s.detached and s.kind == k) {
+ w.print(" {s}", .{s.named()}) catch {};
+ };
+ return error.Said;
+ }
+
+ 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);
+ }
+};
+
+/// `pardes --daemon`: what `spawn` started, on the listener (fd 3) and the
+/// lock (fd 4). Returns only to exit, idle.
+pub fn serve() 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);
+ var d: Daemon = .{};
+ const slots = 1 + max_conns + max_held;
+ var fds: [slots]libc.pollfd = undefined;
+ var conn_of: [slots]u8 = undefined;
+ var held_of: [slots]u16 = undefined;
+ var buf: [msg_max]u8 = undefined;
+ while (true) {
+ var n: usize = 0;
+ fds[n] = .{ .fd = listener, .events = libc.POLL.IN, .revents = 0 };
+ n += 1;
+ const conns_at = n;
+ for (&d.conns, 0..) |*c, i| if (c.fd >= 0) {
+ fds[n] = .{ .fd = c.fd, .events = libc.POLL.IN, .revents = 0 };
+ conn_of[n] = @intCast(i);
+ n += 1;
+ };
+ const held_at = n;
+ // 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 (&d.held, 0..) |*h, i| if (h.fd >= 0) {
+ fds[n] = .{ .fd = h.fd, .events = 0, .revents = 0 };
+ held_of[n] = @intCast(i);
+ n += 1;
+ };
+ const idle = d.idle();
+ const ready = libc.poll(&fds, @intCast(n), 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);
+ for (fds[conns_at..held_at], conn_of[conns_at..held_at]) |pfd, i| {
+ if (pfd.revents == 0 or d.conns[i].fd != pfd.fd) continue;
+ const got = recv(pfd.fd, &buf) orelse {
+ d.hangUp(i);
+ continue;
+ };
+ d.take(i, got);
+ }
+ for (fds[held_at..n], held_of[held_at..n]) |pfd, i| {
+ if (pfd.revents == 0 or d.held[i].fd != pfd.fd) continue;
+ d.drop(&d.held[i]);
+ }
+ }
+ var sock_buf: [sun_path_len:0]u8 = undefined;
+ _ = libc.close(listener);
+ if (place(&sock_buf, "pardes-daemon.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);
+}