summaryrefslogtreecommitdiff
path: root/runtime/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/main.zig')
-rw-r--r--runtime/main.zig146
1 files changed, 106 insertions, 40 deletions
diff --git a/runtime/main.zig b/runtime/main.zig
index 29c19bc0..0751f6b0 100644
--- a/runtime/main.zig
+++ b/runtime/main.zig
@@ -269,10 +269,12 @@ const cmds = std.EnumArray(Cmd, Doc).init(.{
.line = "the daemon's sessions, their clients and shells",
.doc =
\\What the per-user daemon lists: each session with its name, pid, kind
- \\(tty or gui) and whether it has a frontend of its own or is detached;
- \\under it its clients and its shells; then the shells no session holds,
- \\which Adopt takes. /sessions is the same list, read from inside a
- \\session (where a session with a frontend says attached).
+ \\(tty or gui) and whether it has a frontend of its own or is detached
+ \\(under PARDES_PAIR: kept, or nothing when its last client's close
+ \\ends it); under it its clients and its shells; then the shells no
+ \\session holds, which Adopt takes. /sessions is the same list, read
+ \\from inside a session (where a session with a frontend says
+ \\attached, and a pair's not kept says pair).
,
.examples = &.{.{ "pardes ps", "every session, client and shell" }},
.see = "attach, kill, /sessions",
@@ -1157,6 +1159,13 @@ fn nativeMain(std_init: std.process.Init) !void {
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;
+ // A window's pair's session (`pair`): the pardes beside a pardes-gui,
+ // exec'd in its child, its first client on the fd named, the window's
+ // arguments after it.
+ const paired: ?c_int = if (!resuming and args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.paired_flag))
+ std.fmt.parseInt(c_int, args[1][upgrade.paired_flag.len..], 10) catch badArgs(init.io, "{s}: not a descriptor", .{args[1]})
+ else
+ null;
var session_only = true;
var new_session = false;
// `pardes new`: with --detach it returns once the session runs.
@@ -1166,21 +1175,29 @@ 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 = if (resuming) 2 else 1;
+ var i: usize = if (resuming or paired != null) 2 else 1;
+ // An upgraded session's arguments are the ones it was started with: its
+ // `new` is the verb still, not a file's name (taken for one, the file
+ // after it was "the second" and the session ended at its Upgrade).
+ if (resuming and args.len > i and std.meta.stringToEnum(Cmd, args[i]) == .new) {
+ new_session = true;
+ new_verb = true;
+ i += 1;
+ }
// A command's name first: new and attach go on to start or join a
// session, with the flags after them; the rest are done in `command`.
- if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) {
+ if (!resuming and args.len > i) if (std.meta.stringToEnum(Cmd, args[i])) |cmd| switch (cmd) {
.new => {
new_session = true;
new_verb = true;
- i = 2;
+ i += 1;
},
.attach => {
- const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-';
- attach = if (named) args[2] else "";
- i = if (named) 3 else 2;
+ const named = args.len > i + 1 and args[i + 1].len > 0 and args[i + 1][0] != '-';
+ attach = if (named) args[i + 1] else "";
+ i += if (named) 2 else 1;
},
- else => runCommand(init, cmd, args[2..]),
+ else => runCommand(init, cmd, args[i + 1 ..]),
};
while (i < args.len) : (i += 1) {
const a = args[i];
@@ -1521,11 +1538,8 @@ fn nativeMain(std_init: std.process.Init) !void {
// detached session, as `pardes --detach` (`ps` says tty), its
// windows clients. Without one there, it carries on as a window's.
if (comptime pardes.platform == .gui) if (!resuming) {
- var exe: [4096]u8 = undefined;
- const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
- if (n > 0) if (std.Io.Dir.path.dirname(exe[0..@intCast(n)])) |bin| if (args.len < 64) {
- var path_buf: [4104]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+ var path_buf: [4104]u8 = undefined;
+ if (pardesBeside(&path_buf)) |path| if (args.len < 64) {
var argv: [64:null]?[*:0]const u8 = @splat(null);
argv[0] = path.ptr;
for (args[1..], 1..) |a, k| argv[k] = a.ptr;
@@ -1566,15 +1580,25 @@ fn nativeMain(std_init: std.process.Init) !void {
term = .{ .fd = .{ .fd = t.fd, .termios = t.termios } };
};
detached = if (pardes.platform == .gui) !rec.window else rec.nttys == 0;
- daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, detached);
- } else if (pardes.platform == .tui and detach == null and std.c.getenv("PARDES_PAIR") != null) {
+ daemon.resumeLink(rec.link, rec.stub, kind, opts.ninep_name, rec.state orelse if (detached) .detached else .attached);
+ } else if (paired) |fd| {
+ // A window's pair's session: its first client on `fd`, the daemon
+ // its own to dial (and to start, when none runs).
+ opts.pair = fd;
+ term = .detached;
+ detached = true;
+ if (daemon.wanted()) _ = daemon.register(null, kind, opts.ninep_name, .pair);
+ } else if (detach == null and std.c.getenv("PARDES_PAIR") != null) {
// The last step's way, behind its variable until it is the default:
- // this terminal a client of a session forked off for it (`pair`).
- pair(init, &opts);
+ // this terminal or window a client of a session forked off for it
+ // (`pair`).
+ pair(init, &opts, args);
term = .detached;
} else if (daemon.wanted()) {
if (detach != null or pardes.platform == .gui) {
- _ = daemon.register(null, kind, opts.ninep_name, detach != null);
+ // A session started detached is kept from birth: a pair's word.
+ const s: daemon.State = if (detach == null) .attached else if (std.c.getenv("PARDES_PAIR") != null) .kept else .detached;
+ _ = daemon.register(null, kind, opts.ninep_name, s);
} else if (pardes.platform == .tui) fork: {
// A terminal's session is forked off its stub, which stays the
// job the shell waits on: Detach (or the terminal's end) ends
@@ -1598,7 +1622,7 @@ fn nativeMain(std_init: std.process.Init) !void {
_ = std.c.close(conn);
break :fork;
};
- _ = daemon.register(conn, .tty, opts.ninep_name, false);
+ _ = daemon.register(conn, .tty, opts.ninep_name, .attached);
term = .{ .fd = .{ .fd = fd } };
}
}
@@ -1650,7 +1674,12 @@ fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) nore
.session => {
const kind = it.next() orelse "";
const state = it.next() orelse "";
- w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break;
+ const named = std.mem.trim(u8, it.rest(), " ");
+ // A pair's not kept: its clients are all there is to it.
+ if (std.mem.eql(u8, state, "pair"))
+ w.print(" session {s} {s} ({s})\n", .{ named, pid, kind }) catch break
+ else
+ w.print(" session {s} {s} ({s}, {s})\n", .{ named, pid, kind, if (std.mem.eql(u8, state, "attached")) "has a frontend" else state }) catch break;
},
.client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break,
.shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break,
@@ -1708,23 +1737,48 @@ fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 {
return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n");
}
-/// PARDES_PAIR: `pardes` in a terminal as a session and its first client
-/// over a socket pair (docs/next-run.md; the last step's design, 1.1). The
-/// daemon dialled first, as for a stub; then a fork: the parent the CLIENT
-/// (the shell's job, the terminal its own; signals reach what draws), its
-/// first join on its end of the pair; the child the SESSION (setsid, 0, 1
-/// and 2 on /dev/null, detached), its end of the pair its first client,
-/// taken before its first effects (runtime/session.zig). Returns in the
-/// session; the client exits. No fork to be had: returns, and this process
-/// is the session, with no terminal: said by the caller's run.
-fn pair(init: std.process.Init, opts: *pardes.Options) void {
- const conn: ?c_int = if (daemon.wanted()) daemon.connect(true) else null;
+/// The terminal's binary beside this one, as /proc names this one (Linux),
+/// in `buf`.
+fn pardesBeside(buf: *[4104]u8) ?[:0]const u8 {
+ var exe: [4096]u8 = undefined;
+ const n = std.c.readlink("/proc/self/exe", &exe, exe.len);
+ if (n <= 0) return null;
+ const bin = std.Io.Dir.path.dirname(exe[0..@intCast(n)]) orelse return null;
+ return std.fmt.bufPrintSentinel(buf, "{s}/pardes", .{bin}, 0) catch unreachable; // 4096 + 8 fits
+}
+
+/// PARDES_PAIR: `pardes` in a terminal, or `pardes-gui`, as a session and
+/// its first client over a socket pair (docs/next-run.md; the last step's
+/// design, 1.1 and 1.2). The daemon dialled first, as for a stub; then a
+/// fork: the parent the CLIENT (the shell's job, the terminal its own,
+/// signals reach what draws; or the window), its first join on its end of
+/// the pair; the child the SESSION (setsid, 0, 1 and 2 on /dev/null,
+/// detached), its end of the pair its first client, taken before its first
+/// effects (runtime/session.zig). A window's child execs the `pardes`
+/// beside it (`--paired=FD` first, its arguments after), which dials the
+/// daemon itself: a window's session loop is woken through SDL (gui.zig
+/// `sdlWake`), a terminal's needs none. Returns in a terminal's session;
+/// the client exits. No fork to be had: returns, and this process is the
+/// session, with no terminal: said by the caller's run. A window with no
+/// `pardes` beside it returns at once, its own session as before.
+fn pair(init: std.process.Init, opts: *pardes.Options, args: []const [:0]const u8) void {
+ var path_buf: [4104]u8 = undefined;
+ var fd_buf: [32]u8 = undefined;
+ var argv: [64:null]?[*:0]const u8 = @splat(null);
+ if (pardes.platform == .gui) {
+ const path = pardesBeside(&path_buf) orelse return;
+ if (args.len >= argv.len - 1 or std.c.access(path, std.c.X_OK) != 0) return;
+ argv[0] = path.ptr;
+ for (args[1..], 2..) |a, k| argv[k] = a.ptr;
+ }
+ const conn: ?c_int = if (pardes.platform == .tui and daemon.wanted()) daemon.connect(true) else null;
var fds: [2]c_int = undefined;
if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0)
die(init.io, "no socket pair for a session and its terminal", .{});
+ if (pardes.platform == .gui) argv[1] = (std.fmt.bufPrintSentinel(&fd_buf, upgrade.paired_flag ++ "{d}", .{fds[0]}, 0) catch unreachable).ptr; // an fd fits 32
// The session laid out at the terminal's size: no reflow at the join.
var ws: std.posix.winsize = undefined;
- if (std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
+ if (pardes.platform == .tui and std.c.ioctl(0, std.posix.T.IOCGWINSZ, &ws) == 0 and ws.col > 0 and ws.row > 0) {
opts.cols = ws.col;
opts.rows = ws.row;
}
@@ -1738,10 +1792,16 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
_ = std.c.dup2(null_fd, @intCast(i));
};
if (null_fd > 2) _ = std.c.close(null_fd);
+ if (pardes.platform == .gui) {
+ // Its end of the pair across the exec.
+ _ = std.c.fcntl(fds[0], std.c.F.SETFD, @as(c_int, 0));
+ _ = execvp(argv[0].?, &argv);
+ std.c._exit(127);
+ }
opts.pair = fds[0];
// The daemon is the client's to start; the hello is this one's.
daemon.startPending(false);
- if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, true);
+ if (conn) |c| _ = daemon.register(c, .tty, opts.ninep_name, .pair);
return;
}
_ = std.c.close(fds[0]);
@@ -1752,7 +1812,7 @@ fn pair(init: std.process.Init, opts: *pardes.Options) void {
var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined;
var o = opts.*;
o.pair = fds[1];
- @import("dev").tui.runClient(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
+ clientOf(init, o, daemon.replicaSocket(&sock_buf) orelse "", name, false) catch |err| die(init.io, "{t}", .{err});
std.process.exit(0);
}
@@ -1842,8 +1902,11 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
Ssh.child = pid;
Ssh.path = here;
_ = atexit(Ssh.end);
+ // Its file is there a moment before ssh listens on it: until a
+ // connect answers.
var waited: u32 = 0;
- while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) {
+ const probe = while (true) : (waited += 1) {
+ if (cloud9.transport.connectFd(.{ .unix = here }, cloud9.transport.nowMs() + 100)) |fd| break fd else |_| {}
var status: c_int = 0;
if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) {
Ssh.child = 0;
@@ -1852,7 +1915,8 @@ fn attachClient(init: std.process.Init, opts: pardes.Options, where: []const u8,
if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where});
const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms };
_ = std.c.nanosleep(&ts, null);
- }
+ };
+ _ = std.c.close(probe);
clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err});
std.process.exit(0);
}
@@ -1894,7 +1958,7 @@ fn bareAttach(list: []const u8, names: *std.Io.Writer) ?[]const u8 {
one = std.mem.trim(u8, words.rest(), " ");
n += 1;
names.print(" {s}", .{one.?}) catch {}; // cut short
- if (!std.mem.eql(u8, state, "detached")) continue;
+ if (std.mem.eql(u8, state, "attached")) continue;
detached = one;
n_detached += 1;
}
@@ -1907,6 +1971,8 @@ test "a bare attach takes the one detached session, else the one there is, else
var names: std.Io.Writer = .fixed(&buf);
try std.testing.expectEqualStrings("b", bareAttach("daemon 1\nsession 2 tty attached a\nshell 9\nsession 3 gui detached b\n", &names).?);
try std.testing.expectEqualStrings("a", bareAttach("daemon 1\nsession 2 tty attached a\n", &names).?);
+ // A pair's, kept or not, has no frontend of its own either.
+ try std.testing.expectEqualStrings("c", bareAttach("session 2 tty attached a\nsession 3 tty pair c\n", &names).?);
names = .fixed(&buf);
try std.testing.expect(bareAttach("daemon 1\norphan 4\n", &names) == null);
try std.testing.expectEqual(@as(usize, 0), names.end);