diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-10-31 06:28:48 -0300 |
| commit | a479792a1ab2b593642d7f648194bfa23ce01dba (patch) | |
| tree | 96ddee7d879a9084daa07db43b0b7910b072a785 /src/daemon.zig | |
| parent | e179cc44fe5060c76a5b00c41e53f11209f5acd9 (diff) | |
| parent | 4c761893e5b3fdae422622cfa02104ab36633045 (diff) | |
| download | pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.tar.gz pardes-a479792a1ab2b593642d7f648194bfa23ce01dba.zip | |
Merge the upstream daemon and replicated client/server refactor
Diffstat (limited to 'src/daemon.zig')
| -rw-r--r-- | src/daemon.zig | 1221 |
1 files changed, 1221 insertions, 0 deletions
diff --git a/src/daemon.zig b/src/daemon.zig new file mode 100644 index 00000000..b93f5d43 --- /dev/null +++ b/src/daemon.zig @@ -0,0 +1,1221 @@ +//! 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 +//! (detached/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"); +const libc = std.c; +const posix = std.posix; +const ninep_io = @import("9p_io.zig"); +const wire = @import("detached/wire.zig"); +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)); +} + +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} {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. +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", &.{}); +} + +/// 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 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 }, + /// 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.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, "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); + } else if (std.mem.eql(u8, verb, "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); + } + } +} + +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 refused by a session that takes none (a window's, so far). +pub fn refuseReplica(fd: c_int, why: []const u8) void { + var out: [600]u8 = undefined; + if (wire.encodeServer(&out, .{ .refused = why })) |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 ---- + +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 }; +} + +/// 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); + tellDetached(stub); + stub = -1; +} + +/// The stub on `fd` told its terminal is detached (one of a session's +/// several, views.zig), and the pipe let go. +pub fn tellDetached(fd: c_int) void { + if (fd < 0) return; + var buf: [160]u8 = undefined; + const said = std.fmt.bufPrint(&buf, "d{s}", .{name()}) catch "d"; + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); +} + +/// The session's end, `code` its exit status: the stub is told (and goes). +pub fn tellStubExit(code: u8) void { + tellExit(stub, code); + stub = -1; +} + +pub fn tellExit(fd: c_int, code: u8) void { + if (fd < 0) return; + var buf: [8]u8 = undefined; + const said = std.fmt.bufPrint(&buf, "x{d}", .{code}) catch "x1"; + _ = libc.write(fd, said.ptr, said.len); + _ = libc.close(fd); +} + +/// 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 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, + + 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, +}; + +/// 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 drop(d: *Daemon, h: *Held) void { + _ = d; + _ = libc.close(h.fd); + h.* = .{}; + } + + 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) d.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: [msg_max]u8 = undefined; + var w: std.Io.Writer = .fixed(&line); + w.writeAll("ok") catch {}; + 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 {}; + n += 1; + }; + if (named == null) { + for (&d.held) |*h| if (h.fd >= 0 and h.owner == null) d.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 {}; + 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 (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 = 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 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.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, "upgrade")) { + d.upgrade_asked = true; + return; + } + if (std.mem.eql(u8, verb, "list")) return d.list(i); + if (std.mem.eql(u8, verb, "kill")) return d.kill(i, std.mem.trim(u8, words.rest(), " ")); + if (std.mem.eql(u8, verb, "killall")) return d.kill(i, null); + 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; + } + // Attached already: the session takes another view. + 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.?; + // None detached: the one session there is, as another view of it. + 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) return found.?; + count = 0; + } + 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; + } + + /// 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 "another protocol"); + 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 { + var out: [600]u8 = undefined; + // A fresh connection's buffer is empty: this never blocks. + if (wire.encodeServer(&out, .{ .refused = why[0..@min(why.len, 512)] })) |bytes| _ = writeAll(r.fd, bytes) else |_| {} + _ = libc.close(r.fd); + 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; + if (std.mem.eql(u8, what, "replicas")) { + replicas = std.fmt.parseInt(c_int, words.next() orelse "", 10) catch -1; + if (replicas >= 0) ninep_io.setCloexec(replicas); + } else if (std.mem.eql(u8, what, "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.name_len = @min(rest.len, c.name.len); + @memcpy(c.name[0..c.name_len], rest[0..c.name_len]); + } else if (std.mem.eql(u8, what, "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(); + const slots = 2 + max_conns + max_replicas + max_held; + var fds: [slots]libc.pollfd = undefined; + var conn_of: [slots]u8 = undefined; + var held_of: [slots]u16 = undefined; + var replica_of: [slots]u8 = 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; + // -1 when there is none: poll skips a negative fd. + fds[n] = .{ .fd = replicas, .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 replicas_at = n; + for (&d.replicas, 0..) |*r, i| if (r.fd >= 0) { + fds[n] = .{ .fd = r.fd, .events = libc.POLL.IN, .revents = 0 }; + replica_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); + if (fds[1].revents & libc.POLL.IN != 0) d.acceptReplica(replicas); + for (fds[replicas_at..held_at], replica_of[replicas_at..held_at]) |pfd, i| { + if (pfd.revents == 0 or d.replicas[i].fd != pfd.fd) continue; + d.hear(&d.replicas[i]); + } + for (fds[conns_at..replicas_at], conn_of[conns_at..replicas_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]); + } + 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); +} |
