summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig472
1 files changed, 426 insertions, 46 deletions
diff --git a/src/main.zig b/src/main.zig
index 4e6b49bb..f9118dfc 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -2,6 +2,8 @@ const std = @import("std");
const builtin = @import("builtin");
const pardes = @import("pardes.zig");
const ninep_io = @import("9p_io.zig");
+const daemon = @import("daemon.zig");
+const upgrade = @import("upgrade.zig");
const is_emscripten = builtin.os.tag == .emscripten;
@@ -20,7 +22,15 @@ else
// 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 };
+//
+// 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,
@@ -28,13 +38,16 @@ fn logFn(
comptime format: []const u8,
args: anytype,
) void {
- if (scope != .gui and scope != .dump and std.c.getenv("PARDES_LOG") == null) return;
+ if (scope != .gui and std.c.getenv("PARDES_LOG") == null) return;
std.log.defaultLog(level, scope, format, args);
}
pub const panic = if (is_emscripten) std.debug.FullPanic(std.debug.defaultPanic) else std.debug.FullPanic(struct {
fn call(msg: []const u8, ret_addr: ?usize) noreturn {
- if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover();
+ if (!recovering.swap(true, .seq_cst)) {
+ pardes.replica.dying();
+ @import("vaxis").recover();
+ }
@import("crash.zig").record(msg);
std.debug.defaultPanic(msg, ret_addr);
}
@@ -44,7 +57,10 @@ var recovering: std.atomic.Value(bool) = .init(false);
pub const debug = if (is_emscripten) struct {} else struct {
pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn {
- if (!recovering.swap(true, .seq_cst)) @import("vaxis").recover();
+ if (!recovering.swap(true, .seq_cst)) {
+ pardes.replica.dying();
+ @import("vaxis").recover();
+ }
return std.debug.defaultHandleSegfault(addr, name, opt_ctx);
}
};
@@ -64,7 +80,7 @@ const help_text =
\\ -n <count> initial shell panes: 1 (default) or 3 (classic).
\\ A FILE argument boots just that file instead.
\\ --tty-toggle <key> use Ctrl-<key> to toggle tty/editor mode
- \\ -l <dump.zon> load a dump of another instance (see Dump)
+ \\ -l <dump> load a dump of another instance (see Dump)
\\ -w, --wait inside a pardes pane, hand FILE to the outer
\\ session and return only once the pane it opened
\\ (or already had) is deleted: 0 then, 1 if the
@@ -84,22 +100,35 @@ const help_text =
\\ --9p-quic=<dial> also serve at quic!<numeric-ip>!<port> (-Dquic=true).
\\ --mount=<name>=<dial> mount a 9P session or Unix/TCP/QUIC endpoint under /n/<name>.
\\ Repeat for more mounts; os and self are reserved.
- \\ --detach run this session with NO terminal of its own,
- \\ serving frontends over a unix socket beside its
- \\ 9P socket. The core, the panes and the
- \\ undo history outlive every frontend that attaches
- \\ --detach=<name> ...named <name> rather than this process's pid, so
- \\ a frontend can say which session it wants. One
- \\ path component: no '/' and nothing empty
- \\ --attach become a frontend of the one detached session
- \\ that is running: draw its screen and send it
- \\ input, and nothing else — the session owns its
- \\ pane shells, its files and its watches. Works in
- \\ both the terminal and the SDL window build.
- \\ Several frontends may be attached at once and all
- \\ see the same screen
- \\ --attach=<name> ...of the session called <name>, which is what to
- \\ use when more than one is running
+ \\ --detach run this session with no terminal (no window)
+ \\ until one attaches; its panes, shells and files
+ \\ stay. Detach, or a terminal that closes, leaves
+ \\ any session so. One `pardes --daemon` per user
+ \\ keeps them (PARDES_DAEMON=off: none)
+ \\ --detach=<name> ...named <name> rather than this process's pid,
+ \\ as --9p names it. One path component: no '/'
+ \\ and nothing empty
+ \\ --attach show the one detached session here: this
+ \\ terminal for `pardes`, a window again for
+ \\ `pardes-gui`, each of its own kind. Returns when
+ \\ the session detaches or ends
+ \\ --attach=<name> ...the session called <name> (its --9p or
+ \\ --detach name, else its pid)
+ \\ --attach=<host>:<name> a client of session <name> on another machine,
+ \\ a terminal's or a window's (either kind's
+ \\ session), over `ssh -L` to its pardes-replica.sock
+ \\ ($PARDES_SSH: the ssh command, words, default
+ \\ `ssh`; and
+ \\ $PARDES_REMOTE_RUNTIME: its runtime directory,
+ \\ if not this one's path). Its keys show at once
+ \\ --attach=<sock>:<name> ...through that socket (a path, with a '/'),
+ \\ one forwarded already, or this machine's
+ \\ --ps what the pardes daemon keeps: each session (its
+ \\ pid, kind, whether attached) and its shells, then
+ \\ the shells no session holds
+ \\ --kill=<name> end session <name> and its shells (TERM, then
+ \\ KILL 2 s later); unsaved changes are lost
+ \\ --kill-all end every session and every shell the daemon keeps
\\ --geometry=WxH[+X+Y] the window's size in points, and where it goes
\\ where the display lets a window say (X11)
\\ -h, --help show this help and exit
@@ -281,10 +310,12 @@ fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
std.process.exit(1);
}
-const version_text = if (pardes.commit) |c|
+/// The second line is what a replica's build must share with its session's
+/// (detached/wire.zig `semantics`).
+const version_text = (if (pardes.commit) |c|
"pardes " ++ pardes.version ++ " (" ++ c ++ ")\n"
else
- "pardes " ++ pardes.version ++ "\n";
+ "pardes " ++ pardes.version ++ "\n") ++ std.fmt.comptimePrint("semantics {x:0>16}\n", .{@import("detached/wire.zig").semantics});
const nested_text =
\\pardes: this shell is already inside pardes, and a pardes inside a pardes
@@ -297,6 +328,47 @@ const nested_text =
// the std.process.Init entry.
pub const main = if (is_emscripten) webMain else 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;
+}
+
+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));
+}
+
comptime {
if (is_emscripten) @export(&emscriptenMain, .{ .name = "main" });
}
@@ -316,7 +388,7 @@ fn emscriptenMain(argc: c_int, argv: [*]?[*:0]u8) callconv(.c) c_int {
// no argv in the browser: options stay default, state comes from the dump, and
// there is no session to attach to — a browser tab has no unix socket.
fn webMain() !void {
- try @import("gui/gui.zig").run(.{}, .{}, null);
+ try @import("gui/gui.zig").run(.{}, .{}, false);
}
// init.gpa, what the tty, gui and detached shells allocate from, is their
@@ -326,6 +398,8 @@ fn webMain() !void {
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(init.io, tape));
var stderr_probe: [64]u8 = undefined;
_ = std.debug.lockStderr(&stderr_probe);
std.debug.unlockStderr();
@@ -335,6 +409,18 @@ fn nativeMain(std_init: std.process.Init) !void {
var mounts_len: usize = 0;
const arena = init.arena.allocator();
const args = try init.minimal.args.toSlice(arena);
+ // 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 == .tty 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;
@@ -342,7 +428,7 @@ fn nativeMain(std_init: std.process.Init) !void {
var attach: ?[]const u8 = null;
var positional: ?[:0]const u8 = null;
var wait = false;
- var i: usize = 1;
+ var i: usize = if (resuming) 2 else 1;
while (i < args.len) : (i += 1) {
const a = args[i];
if (std.mem.eql(u8, a, "--tty")) {
@@ -434,6 +520,14 @@ fn nativeMain(std_init: std.process.Init) !void {
attach = "";
} else if (std.mem.startsWith(u8, a, "--attach=")) {
attach = a["--attach=".len..];
+ } else if (std.mem.eql(u8, a, "--ps")) {
+ manage(init.io, "list", "");
+ } else if (std.mem.startsWith(u8, a, "--kill=")) {
+ const name = a["--kill=".len..];
+ if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{});
+ manage(init.io, "kill", name);
+ } else if (std.mem.eql(u8, a, "--kill-all")) {
+ manage(init.io, "killall", "");
} else if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) {
try std.Io.File.stdout().writeStreamingAll(init.io, help_text);
return;
@@ -483,7 +577,7 @@ fn nativeMain(std_init: std.process.Init) !void {
badArgs(init.io, "--9p-quic 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) forwarding: {
+ 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
@@ -664,6 +758,7 @@ fn nativeMain(std_init: std.process.Init) !void {
if (wait) waitForDel(init.io, 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, "-")) {
@@ -713,30 +808,72 @@ fn nativeMain(std_init: std.process.Init) !void {
opts.config_dir = found.dir;
opts.store_path = storePath(init.io, arena, init.environ_map);
if (found.dir) |d| @import("crash.zig").setDir(d);
+ if (attach) |name| if (std.mem.lastIndexOfScalar(u8, name, ':')) |colon| {
+ remoteAttach(init, opts, name[0..colon], name[colon + 1 ..]);
+ };
+ if (attach) |name| if (!resuming) attachTo(init.io, name);
if (detach) |name| {
- const named = if (name.len != 0)
- name
- else
- try std.fmt.allocPrint(arena, "{d}", .{@as(u32, @intCast(std.c.getpid()))});
- // Said plainly, never a Zig error trace: a name another session's
+ // 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).
- return @import("detached/server.zig").run(init, opts, named) catch |err| {
- var words: [128]u8 = undefined;
+ if (name.len != 0 and !resuming and ninep_io.taken(name)) {
var said: [512]u8 = undefined;
- const why = if (err == error.ListenFailed)
- "its socket is taken: another session (a plain one is named by its pid) holds that name; choose another"
- else
- pardes.Messages.errorWords(err, &words);
- std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: --detach={s}: {s}\n", .{ named, why }) catch "pardes: --detach failed\n") catch {};
+ std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&said, "pardes: a session named {s} is already running\n", .{name}) catch "pardes: a session of that name is already running\n") catch {};
std.process.exit(1);
- };
+ }
+ if (opts.ninep_name.len == 0) opts.ninep_name = name;
+ // 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;
}
- if (attach != null and pardes.platform != .tty and pardes.platform != .gui) {
- try std.Io.File.stderr().writeStreamingAll(init.io, "pardes: --attach needs the tty or gui shell\n");
- std.process.exit(1);
+ const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty;
+ var term: @import("tty/tty.zig").Term = if (detach != null) .none else .open;
+ var headless = 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 = .none;
+ for (rec.ttys[0..rec.nttys]) |t| if (t.primary) {
+ term = .{ .fd = .{ .fd = t.fd, .termios = t.termios } };
+ };
+ headless = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
+ daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, headless);
+ } else if (daemon.wanted()) {
+ if (detach != null or pardes.platform == .gui) {
+ _ = daemon.register(null, kind, opts.ninep_name, detach != null);
+ } else if (pardes.platform == .tty) 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) {
- .tty => @import("tty/tty.zig").run(init, opts, attach) catch |err| switch (err) {
+ .tty => @import("tty/tty.zig").run(init, opts, term) catch |err| switch (err) {
// No controlling terminal (a detached pty, a daemon): said, not
// an error trace.
error.NoDevice => {
@@ -745,9 +882,253 @@ fn nativeMain(std_init: std.process.Init) !void {
},
else => return err,
},
- .gui => try @import("gui/gui.zig").run(init, opts, attach),
+ .gui => try @import("gui/gui.zig").run(init, opts, headless),
.web, .macos, .esp32p4 => 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: []const u8, name: []const u8) noreturn {
+ const Say = struct {
+ fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
+ var buf: [700]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\n", args) catch "pardes: failed\n") catch {};
+ std.process.exit(1);
+ }
+ };
+ if (comptime !daemon.supported) Say.no(io, "this system has no pardes daemon", .{});
+ var words_buf: [300]u8 = undefined;
+ const words = if (std.mem.eql(u8, verb, "kill"))
+ std.fmt.bufPrint(&words_buf, "kill {s}", .{name}) catch Say.no(io, "that name is too long", .{})
+ else
+ verb;
+ var buf: [4096]u8 = undefined;
+ const said = daemon.ask(words, &buf) orelse Say.no(io, "no pardes daemon is running", .{});
+ if (std.mem.startsWith(u8, said, "no ")) Say.no(io, "{s}", .{said[3..]});
+ if (std.mem.eql(u8, 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(pid, &comm_buf);
+ if (std.mem.eql(u8, what, "daemon")) {
+ w.print("pardes daemon {s}\n", .{pid}) catch break;
+ } else if (std.mem.eql(u8, what, "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, state }) catch break;
+ } else if (std.mem.eql(u8, what, "shell")) {
+ w.print(" shell {s} {s}\n", .{ pid, comm }) catch break;
+ } else if (std.mem.eql(u8, what, "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)) Say.no(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(pid: []const u8, buf: *[64]u8) []const u8 {
+ var path_buf: [64]u8 = undefined;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "/proc/{s}/comm", .{pid}, 0) catch return "";
+ const fd = std.c.open(path, .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(std.c.mode_t, 0));
+ if (fd < 0) return "";
+ defer _ = std.c.close(fd);
+ const got = std.c.read(fd, buf, buf.len);
+ if (got <= 0) return "";
+ return std.mem.trimEnd(u8, buf[0..@intCast(got)], "\n");
+}
+
+/// The replica client of this build's frontend: a terminal's (tty.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) {
+ .tty => try @import("tty/tty.zig").remote(init, opts, path, name, far),
+ .gui => try @import("gui/gui.zig").remote(init, opts, path, name, far),
+ else => unreachable,
+ }
+}
+
+/// `pardes --attach=<where>:<name>` (`pardes-gui` too): a replica client
+/// (tty.zig and gui.zig `remote`), through the socket `where` names, or
+/// through `ssh -L` of host `where`'s replica socket to one of this
+/// process's.
+fn remoteAttach(init: std.process.Init, opts: pardes.Options, where: []const u8, name: []const u8) noreturn {
+ const io = init.io;
+ if (comptime pardes.platform != .tty and pardes.platform != .gui) unreachable;
+ const Say = struct {
+ fn no(o: std.Io, comptime fmt: []const u8, args: anytype) noreturn {
+ var buf: [700]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: --attach: " ++ fmt ++ "\n", args) catch "pardes: --attach failed\n") catch {};
+ std.process.exit(1);
+ }
+ };
+ if (std.mem.indexOfScalar(u8, where, '/') != null) {
+ clientOf(init, opts, where, name, false) catch |err| Say.no(io, "{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 Say.no(io, "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 Say.no(io, "no runtime directory to name the remote 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 Say.no(io, "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) Say.no(io, "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) Say.no(io, "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.c.access(here, std.c.F_OK) != 0) : (waited += 1) {
+ var status: c_int = 0;
+ if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
+ Ssh.child = 0;
+ Say.no(io, "ssh to {s} ended before its forward was up", .{where});
+ }
+ if (waited > 3000) Say.no(io, "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| Say.no(io, "{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.
+fn attachTo(io: std.Io, name: []const u8) noreturn {
+ var words: [600]u8 = undefined;
+ const Say = struct {
+ fn no(o: std.Io, why: []const u8) noreturn {
+ var buf: [700]u8 = undefined;
+ std.Io.File.stderr().writeStreamingAll(o, std.fmt.bufPrint(&buf, "pardes: --attach: {s}\n", .{why}) catch "pardes: --attach failed\n") catch {};
+ std.process.exit(1);
+ }
+ };
+ if (comptime !daemon.supported) Say.no(io, "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| Say.no(io, why),
+ };
+ const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0));
+ if (fd < 0) Say.no(io, "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) Say.no(io, "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| Say.no(io, why),
+ }
}
fn parseCtrlKey(raw: []const u8) ?u21 {
@@ -774,8 +1155,7 @@ test {
_ = @import("detached/wire.zig");
_ = @import("ShaderBuild.zig");
_ = @import("vaxis_input.zig");
- _ = @import("detached/server.zig");
- _ = @import("detached/client.zig");
+ _ = @import("daemon.zig");
_ = @import("9p_io.zig");
_ = @import("9p_io.zig").Client;
_ = @import("host_io.zig");