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 cloud9 = @import("cloud9"); pub const std_options_debug_threaded_io: ?*std.Io.Threaded = std.Io.Threaded.global_single_threaded; pub const std_options_debug_io: std.Io = std_options_debug_threaded_io.?.io(); // Every thread's alternate signal stack is a threadlocal that libc zeroes as // the thread starts, so std's 256 KiB made each 9P connection's thread cost // that much resident. A stack-overflow segfault on a thread still printed its // whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. // // FreeBSD answers a write to a terminal that is gone with ENXIO, an errno std // does not expect: a Debug build traced it to stderr, that same terminal, // and recursed until the stack ran out (a session whose ssh dropped hung). pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024, .unexpected_error_tracing = (std.Options{}).unexpected_error_tracing and builtin.os.tag != .freebsd, }; fn logFn( comptime level: std.log.Level, comptime scope: @EnumLiteral(), comptime format: []const u8, args: anytype, ) void { if (scope != .gui and std.c.getenv("PARDES_LOG") == null) return; std.log.defaultLog(level, scope, format, args); } pub const panic = std.debug.FullPanic(struct { fn call(msg: []const u8, ret_addr: ?usize) noreturn { if (!recovering.swap(true, .seq_cst)) { pardes.replica.dying(); @import("vaxis").recover(); } @import("crash.zig").record(msg); std.debug.defaultPanic(msg, ret_addr); } }.call); var recovering: std.atomic.Value(bool) = .init(false); pub const debug = struct { pub fn handleSegfault(addr: ?usize, name: []const u8, opt_ctx: anytype) noreturn { if (!recovering.swap(true, .seq_cst)) { pardes.replica.dying(); @import("vaxis").recover(); } return std.debug.defaultHandleSegfault(addr, name, opt_ctx); } }; /// `pardes -` inside a session: `text`, stdin as it came, escapes and all, /// into a new +Pager of the directory (/pager): /// written after the directory on that one open, the session parses it /// (Term.page) and puts it in as one undo step, left clean. A text the /// session would not take is never lost: it goes to stderr, a terminal, /// with why, and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { const Fail = struct { fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { var words_buf: [128]u8 = undefined; const why = if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf); var buf: [512]u8 = undefined; const head = std.fmt.bufPrint(&buf, "pardes: -: {s}: {s}; the text follows\n", .{ what, why }) catch "pardes: -: refused; the text follows\n"; std.Io.File.stderr().writeStreamingAll(o, head) catch {}; std.Io.File.stderr().writeStreamingAll(o, t) catch {}; std.process.exit(1); } }; // The pane's directory: this one, unless its name could not be one line // of a ctl (a newline, a control byte): then the session's. var cwd_buf: [4096]u8 = undefined; const cwd: []const u8 = cwd_buf[0 .. std.process.currentPath(io, &cwd_buf) catch 0]; // ...or the session's when this one may not be written (`git log` in // /usr/src), which /pager refuses: the text is paged all the same. const plain = for (cwd) |c| { if (c < ' ' or c == 0x7f) break false; } else !pardes.filesystem.deniedAbove(cwd); var line_buf: [cwd_buf.len + 1]u8 = undefined; const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch unreachable; // a cwd out of cwd_buf and "\n" fit // Its serial read back on the open that asked, once the text is in: // another client's exec meanwhile can never send it into that // client's pane. const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err); _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); } /// Stdin to its end, as it came (its escapes are the session's to parse, /// Term.page), at most a file's limit, a longer one cut there and said so /// at its end. fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; var chunk: [64 * 1024]u8 = undefined; var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); // One byte past the limit says there is more. stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { error.StreamTooLong => { raw.shrinkRetainingCapacity(limit); // CAN ends an escape the cut left half sent, and SGR 0 its colour, // so the note is never swallowed or tinted. const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; try raw.appendSlice(gpa, said); }, else => |e| return e, }; return raw.toOwnedSlice(gpa); } /// A forwarding failure in words, never an error's name: the ones this /// file raises said outright, any other as its name's words (`NotFound`, /// `not found`), a dial's as Messages says it. fn forwardWords(err: anyerror, buf: []u8) []const u8 { return switch (err) { error.NotOneLine => "a file name is one line, and this one holds a newline", error.NotAFileName => "names a directory, not a file", error.NoWorkingDirectory => "this shell's working directory is gone", error.DirectoryNotWritable => "permission denied: its directory may not be read or written, so it could never be saved", error.NotAPaneAddress => "not a pane address: @p and a pane's number", error.NoSuchPane => "this session has no such pane", else => if (pardes.Messages.dialReason(err)) |why| why else words: { var n: usize = 0; for (@errorName(err), 0..) |c, i| { if (n + 2 > buf.len) break; if (std.ascii.isUpper(c) and i > 0) { buf[n] = ' '; n += 1; } buf[n] = std.ascii.toLower(c); n += 1; } break :words buf[0..n]; }, }; } /// `--wait` after a forwarded look, as plan9port's E reads acme's log: the /// pane `path` landed in (the one it already had, if open), then /log /// followed on one connection until that pane's `del` -- exit 0 -- or the /// connection ends with the session -- exit 1. fn waitForDel(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, known: ?u32) noreturn { // The pane this launch made (a name not there yet), or the one its // look answered, is known by its serial; one the look answered none // for is found by its file. Found by none after the look went there, // it was closed already: that is the end being waited for, not a // failure (a pane closed between the look and this read made `--wait` // exit 1 before). const serial = known orelse found: { const first = ninep_io.Client.read(gpa, dial, "/index", "/index") catch std.process.exit(1); defer gpa.free(first); break :found paneShowing(first, path) orelse std.process.exit(0); }; const Wait = struct { gpa: std.mem.Allocator, dial: []const u8, serial: u32, /// Deleted between the look and the follow: /index, read once the /// follow stands, says so, and a `del` after it is followed. fn gone(w: *const @This()) bool { const index = ninep_io.Client.read(w.gpa, w.dial, "/index", "/index") catch return false; defer w.gpa.free(index); return !hasPane(index, w.serial); } fn deleted(w: *const @This(), bytes: []const u8) bool { return isDel(bytes, w.serial); } }; const w: Wait = .{ .gpa = gpa, .dial = dial, .serial = serial }; ninep_io.Client.follow(dial, "/log", "follow new", &w, Wait.gone, Wait.deleted) catch std.process.exit(1); std.process.exit(0); } /// Whether log records `bytes` hold `del ...`. fn isDel(bytes: []const u8, serial: u32) bool { var records = std.mem.splitScalar(u8, bytes, '\n'); while (records.next()) |rec| { if (!std.mem.startsWith(u8, rec, "del ")) continue; const word = rec[4 .. std.mem.indexOfScalarPos(u8, rec, 4, ' ') orelse rec.len]; if ((std.fmt.parseInt(u32, word, 10) catch continue) == serial) return true; } return false; } /// The serial of /index's first row named `path` (`serial kind dirty name col`). fn paneShowing(index: []const u8, path: []const u8) ?u32 { var rows = std.mem.splitScalar(u8, index, '\n'); while (rows.next()) |row| { var words = std.mem.splitScalar(u8, row, ' '); const serial = std.fmt.parseInt(u32, words.first(), 10) catch continue; _ = words.next() orelse continue; // kind _ = words.next() orelse continue; // dirty const rest = words.rest(); const end = std.mem.lastIndexOfScalar(u8, rest, ' ') orelse continue; if (std.mem.eql(u8, rest[0..end], path)) return serial; } return null; } fn hasPane(index: []const u8, serial: u32) bool { var rows = std.mem.splitScalar(u8, index, '\n'); while (rows.next()) |row| { const first = row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]; if ((std.fmt.parseInt(u32, first, 10) catch continue) == serial) return true; } return false; } fn badArgs(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { die(io, fmt ++ "\nTry 'pardes help', or 'pardes help new' for the flags.", args); } /// `pardes: ` on stderr, and exit 1. fn die(io: std.Io, comptime fmt: []const u8, args: anytype) noreturn { var buf: [8192]u8 = undefined; const line = std.fmt.bufPrint(&buf, "pardes: " ++ fmt ++ "\n", args) catch "pardes: refused\n"; std.Io.File.stderr().writeStreamingAll(io, line) catch {}; std.process.exit(1); } /// The second line is what a replica's build must share with its session's /// (wire.zig `semantics`). const version_text = upgrade.version_line ++ "\n" ++ std.fmt.comptimePrint("semantics {x:0>16}\n", .{@import("wire.zig").semantics}); const nested_text = \\pardes: this shell is already inside pardes, and a pardes inside a pardes \\is spicy. Name a file or a directory and the outer session opens it, or \\pass --nested if you really want a second one in here. \\ ; // ---- the command line ---- // // `pardes [flags] [FILE]` opens, starts or pages, as it always has; a first // word that names a `Cmd` is that command instead (a file called so is // `./ps`, or after `--`). `cmds` and `flags` are each both the parser and the // help: `pardes help` prints them, and `pardes help --all` prints them whole // with the tree's README, which is docs/typ/command-line.txt (the build's // builtins-json step writes it; a test below says when it is stale). What a // word or a file does is the tree's to say: `words`, `help WORD`, `help // PATH`, `fs` and the completions read /commands and /README, from the // session over 9P or, with none, from a core made in this process (`Here`). const Cmd = enum { ps, attach, kill, new, do, words, fs, help, completion, skill, version }; const Group = enum { Sessions, Words, Files, Self }; const Doc = struct { group: Group, args: []const u8 = "", /// Its line on the first screen. line: []const u8, /// `pardes help CMD`: what it does. doc: []const u8, /// A command line and what it does, each. examples: []const [2][]const u8, see: []const u8 = "", }; const cmds = std.EnumArray(Cmd, Doc).init(.{ .ps = .{ .group = .Sessions, .line = "the daemon's sessions, their clients and shells", .doc = \\What the per-user daemon keeps: each session with its name, pid, kind \\(tty or gui) and whether one is attached; 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. , .examples = &.{.{ "pardes ps", "every session, client and shell" }}, .see = "attach, kill, /sessions", }, .attach = .{ .group = .Sessions, .args = "[NAME]", .line = "show a detached session here (HOST:NAME: over ssh)", .doc = \\Show a detached session here: in this terminal for pardes, a window \\for pardes-gui. Bare, the one detached session (with none, the one \\session). One attached already, or of the other kind, is joined as a \\client. HOST:NAME is a client of session NAME on another machine, \\over `ssh -L` to its pardes-replica.sock ($PARDES_SSH: the ssh \\command, default ssh; $PARDES_REMOTE_RUNTIME: its runtime directory, \\if not this one's path); SOCK:NAME goes through a socket forwarded \\already (a path, with a '/'). Returns when the session detaches or \\ends. , .examples = &.{ .{ "pardes attach", "the one detached session" }, .{ "pardes attach notes", "the one started with --detach=notes" }, .{ "pardes attach box:notes", "on host box, over ssh -L" }, .{ "pardes attach /run/x.sock:notes", "through a socket forwarded already" }, }, .see = "ps, kill, new --detach, the Detach word", }, .kill = .{ .group = .Sessions, .args = "NAME", .line = "end a session and its shells (--all: every one)", .doc = \\End session NAME (its --9p or --detach name, else its pid) and its \\shells: TERM, then KILL 2 s later. Unsaved changes are lost. --all \\ends every session and every shell the daemon keeps. , .examples = &.{ .{ "pardes kill notes", "the session started with --detach=notes" }, .{ "pardes kill --all", "every session and shell" }, }, .see = "ps, attach", }, .new = .{ .group = .Sessions, .args = "[flags] [FILE]", .line = "start one: --detach=NAME --9p=NAME -n 3 (help new)", .doc = \\Start a session here, even in a pane of another: in this terminal for \\pardes, a window for pardes-gui, or with --detach none until one \\attaches. Bare `pardes` takes the same flags, and starts one unless \\it is in a pane (where it hands its FILE to that session). , .examples = &.{ .{ "pardes new", "a session here, its shell pane in tty mode" }, .{ "pardes new --detach=notes", "one with no terminal, named notes" }, .{ "pardes new -n 3 src/", "three shell panes in src/" }, .{ "pardes new --mount=peer=notes", "with session notes under /n/peer" }, }, .see = "attach, kill, --nested", }, .do = .{ .group = .Words, .args = "WORD [ARG]", .line = "run a builtin at this pane, or the session's: do Newcol", .doc = \\Write WORD and its ARG to the ctl that takes it, as the session's \\/commands says: the root's /ctl for a session's word, a pane's \\pane/N/ctl for a pane's, that pane being this shell's ($PARDES_PANE) \\or -p N. A refusal prints the session's own words, and the exit is 1. \\The session is -s NAME, else $PARDES_9P, else the only one running. , .examples = &.{ .{ "pardes do Newcol", "an empty column" }, .{ "pardes do Save -p 3", "save pane 3" }, .{ "pardes do Edit ',x/foo/c/bar/' -p 3", "sam's Edit on pane 3" }, .{ "pardes do Wrap -s notes", "at session notes" }, }, .see = "words, help WORD, /commands", }, .words = .{ .group = .Words, .args = "[GROUP]", .line = "the builtins by group, or one group's: words column", .doc = \\The session's builtins, as its /commands lists them, grouped by the \\first key after the leader (SPC f is file, SPC c column): with no key, \\a setting, a session's word (its root ctl's) or a text word (a \\pane's). An addon's words are the addon group. With no session, the \\ones this build has. , .examples = &.{ .{ "pardes words", "every builtin, by group" }, .{ "pardes words column", "the column words" }, }, .see = "do, help WORD, /commands", }, .fs = .{ .group = .Files, .args = "VERB [PATH]", .line = "ls read write ask follow stat help complete, on the session's tree", .doc = \\The session's file tree, through a 9P client in this binary: the \\files a mount or 9p(1) reaches, with a refusal in the session's own \\words (a mount says only EINVAL). With no session, ls, stat, help and \\complete, and a read of README, commands or ctl, ask a core made in \\this process; the rest are a running session's, and say so. , .examples = &.{ .{ "pardes fs ls pane/1", "what a pane serves" }, .{ "pardes fs read index", "a line per pane" }, .{ "pardes fs write pane/3/ctl 'Edit ,x/foo/c/bar/'", "a write, refused in words" }, .{ "pardes fs ask pane/3/pty/run make", "exit N, then the output" }, .{ "pardes fs follow log follow", "events as they come" }, }, .see = "help PATH, /README", }, .help = .{ .group = .Self, .args = "[CMD|WORD|PATH]", .line = "this, a command, a builtin, or a file of the tree", .doc = \\Bare, this map. A command: what it does, with examples. A builtin: \\its /commands line, its key, and how to run it. A path of the tree: \\what the tree's README says of it and of what is under it. --all: \\every command's help and the README whole, as this build has them \\(never a session's), which the reference prints. , .examples = &.{ .{ "pardes help attach", "a command" }, .{ "pardes help Newcol", "a builtin" }, .{ "pardes help pane/3/addr", "a file of the tree" }, }, .see = "words, fs help", }, .completion = .{ .group = .Self, .args = "SHELL", .line = "bash, fish or zsh", .doc = \\A completion script for SHELL, printed, never installed. It asks this \\binary back for each word (`pardes completion -- WORDS`): commands, \\the builtins after do, sessions after attach and kill, the tree's \\paths after fs. , .examples = &.{ .{ "pardes completion fish | source", "in fish, for this shell" }, .{ "source <(pardes completion bash)", "in bash" }, .{ "source <(pardes completion zsh)", "in zsh" }, }, }, .skill = .{ .group = .Self, .line = "the guide an agent reads", .doc = \\The guide for an agent that drives pardes, from this binary, so it \\matches what it runs: recipes and traps. What is there it leaves to \\`pardes help`. , .examples = &.{.{ "pardes skill", "" }}, }, .version = .{ .group = .Self, .line = "this build, its session wire and its 9P", .doc = \\This build's version; the semantics a replica must share with its \\session; the 9P its tree speaks. , .examples = &.{.{ "pardes version", "" }}, }, }); /// The flags of `pardes [flags] [FILE]` and `pardes new`, and the spellings /// the commands had before (one release more). const Flag = enum { @"--tty", @"-n", @"--tty-toggle", @"-l", @"--nested", @"--9p", @"--9p-tcp", @"--mount", @"--geometry", @"--detach", @"-w", @"--wait", @"--", @"--attach", @"--ps", @"--kill", @"--kill-all", @"-h", @"--help", @"--version" }; const FlagDoc = struct { /// What follows it: ` COUNT` (the next argument, or after `=`), `=NAME` /// (after `=` only), `[=NAME]` (maybe). arg: []const u8 = "", takes: enum { none, next, eq, maybe } = .none, /// Empty: a short spelling of the flag after it, printed with it. doc: []const u8 = "", group: enum { session, open, old } = .session, }; const flags = std.EnumArray(Flag, FlagDoc).init(.{ .@"--tty" = .{ .doc = "start as one shell pane already in tty mode" }, .@"-n" = .{ .arg = " COUNT", .takes = .next, .doc = "shell panes to start with: 1 (default) or 3 (classic); a FILE boots just that file" }, .@"--tty-toggle" = .{ .arg = " KEY", .takes = .next, .doc = "Ctrl-KEY toggles tty and editor mode" }, .@"-l" = .{ .arg = " DUMP", .takes = .next, .doc = "load a dump of another instance (see Dump)" }, .@"--nested" = .{ .doc = "a session of its own in a pane of another, serving none of its children" }, .@"--9p" = .{ .arg = "=NAME", .takes = .eq, .doc = "name the 9P socket (else the --detach name, else the pid); under $XDG_RUNTIME_DIR, else ~/.local/state/pardes: a directory of yours alone" }, .@"--9p-tcp" = .{ .arg = "=tcp!IP!PORT", .takes = .eq, .doc = "also serve 9P there, a numeric address" }, .@"--mount" = .{ .arg = "=NAME=DIAL", .takes = .eq, .doc = "a 9P session or Unix/TCP endpoint under /n/NAME; repeat for more; os and self are reserved" }, .@"--geometry" = .{ .arg = "=WxH[+X+Y]", .takes = .eq, .doc = "the window's size in points, and where it goes where the display lets a window say (X11)" }, .@"--detach" = .{ .arg = "[=NAME]", .takes = .maybe, .doc = "no terminal (no window) until one attaches; panes, shells and files stay; NAME (one path component) rather than the pid. One pardes --daemon per user keeps sessions (PARDES_DAEMON=off: none)" }, .@"-w" = .{ .group = .open }, .@"--wait" = .{ .group = .open, .doc = "in a pane, hand FILE to its session and return once its pane is deleted: 0, or 1 if the session goes (EDITOR='pardes --wait')" }, .@"--" = .{ .group = .open, .doc = "the end of the flags: pardes -- -name opens -name" }, .@"--attach" = .{ .arg = "[=NAME]", .takes = .maybe, .group = .old, .doc = "pardes attach NAME" }, .@"--ps" = .{ .group = .old, .doc = "pardes ps" }, .@"--kill" = .{ .arg = "=NAME", .takes = .eq, .group = .old, .doc = "pardes kill NAME" }, .@"--kill-all" = .{ .group = .old, .doc = "pardes kill --all" }, .@"-h" = .{ .group = .old }, .@"--help" = .{ .group = .old, .doc = "pardes help" }, .@"--version" = .{ .group = .old, .doc = "pardes version" }, }); const first_screen_head = \\pardes: an editor, a terminal multiplexer, and the file tree that scripts both. \\ \\Usage: \\ pardes [flags] [FILE[:LINE] | DIR | -] open, start a session, or page stdin \\ pardes COMMAND [ARGS] [-s NAME] a file named like a command: pardes ./ps \\ \\Open: \\ FILE[:LINE] open it; in a pane, in that pane's session \\ -w, --wait FILE open it, return when its pane closes (EDITOR='pardes -w') \\ - stdin into a +Pager, its colours kept \\ DIR start in it \\ ; const first_screen_tail = \\ \\Flags: \\ -s, --session NAME the session to act on ($PARDES_9P, else the only one) \\ -p N the pane, for do ($PARDES_PANE) \\ \\The old spellings --ps, --attach[=NAME], --kill=NAME, --kill-all, -h and \\--version still work, for a release. \\ ; /// The left column of the first screen and the flag lists. const left_width = 23; fn writeFirstScreen(w: *std.Io.Writer) std.Io.Writer.Error!void { try w.writeAll(first_screen_head); for (std.enums.values(Group)) |g| { try w.print("\n{t}:\n", .{g}); for (std.enums.values(Cmd)) |c| { const d = cmds.get(c); if (d.group != g) continue; var buf: [64]u8 = undefined; const left = std.fmt.bufPrint(&buf, "{t}{s}{s}", .{ c, if (d.args.len == 0) "" else " ", d.args }) catch unreachable; // the table's names fit try w.print(" {s}", .{left}); try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2); try w.print("{s}\n", .{d.line}); } } try w.writeAll(first_screen_tail); } fn writeFlags(w: *std.Io.Writer, group: @FieldType(FlagDoc, "group")) std.Io.Writer.Error!void { var short: ?Flag = null; for (std.enums.values(Flag)) |f| { const d = flags.get(f); if (d.group != group) continue; if (d.doc.len == 0) { short = f; continue; } var buf: [64]u8 = undefined; const left = if (short) |s| std.fmt.bufPrint(&buf, "{t}, {t}{s}", .{ s, f, d.arg }) catch unreachable // the table's names fit else std.fmt.bufPrint(&buf, "{t}{s}", .{ f, d.arg }) catch unreachable; // the table's names fit short = null; try w.print(" {s}", .{left}); try w.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2); try w.print("{s}\n", .{d.doc}); } } fn writeLeaf(w: *std.Io.Writer, c: Cmd) std.Io.Writer.Error!void { const d = cmds.get(c); try w.print("{s}\n\nUsage:\n pardes {t}{s}{s}\n", .{ d.doc, c, if (d.args.len == 0) "" else " ", d.args }); switch (c) { .new => { try w.writeAll("\nFlags:\n"); try writeFlags(w, .session); try writeFlags(w, .open); }, .fs => try w.print("\n{s}", .{cloud9.verbs.usage}), else => {}, } try w.writeAll("\nExamples:\n"); for (d.examples) |e| { try w.print(" {s}", .{e[0]}); if (e[1].len != 0) { try w.splatByteAll(' ', if (e[0].len < 37) 38 - e[0].len else 2); try w.writeAll(e[1]); } try w.writeByte('\n'); } if (d.see.len != 0) try w.print("\nSee also: {s}\n", .{d.see}); } /// Everything: the first screen, every command's help, the old spellings /// and the tree's README, as this build has them. fn writeHelpAll(w: *std.Io.Writer, t: *Tree) !void { try writeFirstScreen(w); for (std.enums.values(Cmd)) |c| { try w.print("\n== pardes help {t}\n\n", .{c}); try writeLeaf(w, c); } try w.writeAll("\n== the old spellings\n\n"); try writeFlags(w, .old); try w.writeAll("\n== pardes help /: the tree's README\n\n"); try t.f.readFile("README", w); } /// A core made in this process and served on one end of a socket pair, an /// `Fsys` on the other: with no session, `help`, `words`, `completion` and /// `fs` ask the same tree a session serves, through the same client. Never /// stepped and never performing an effect: no shell, no file, no socket. const Here = struct { const Engine = cloud9.fs.Server(pardes.ctlfs, .{ .fid_capacity = 32, .name_capacity = 255, .park_data_max = @import("9p.zig").msize - 23, .slot_capacity = 1 }); core: *pardes.Pardes, engine: Engine, fd: c_int, in: [@import("9p.zig").msize]u8, out: [2 * @import("9p.zig").msize]u8, buf: [@import("9p.zig").msize]u8, /// Answers what comes until the other end hangs up. A request the core /// parks (a read of /log) stays parked: the client's deadline ends it. fn serve(h: *Here) void { while (true) { const got = std.c.read(h.fd, &h.buf, h.buf.len); if (got <= 0) return; var bytes: []const u8 = h.buf[0..@intCast(got)]; while (true) { bytes = bytes[h.engine.push(bytes)..]; while (h.engine.next()) |req| { const r = h.core.serveFs(req); h.engine.reply(&r, h.core.fsPayload(r)); } const out = h.engine.output(); var sent: usize = 0; while (sent < out.len) { const n = std.c.write(h.fd, out[sent..].ptr, out.len - sent); if (n <= 0) return; sent += @intCast(n); } h.engine.wrote(out.len); if (bytes.len == 0) break; } } } }; extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]std.c.fd_t) c_int; /// The tree a command reads: a session's, over its socket, or one made here. const Tree = struct { f: cloud9.Fsys, /// The core this process made, there being no session to ask. here: ?*Here = null, /// The session at `dial` (`Found.one`), or with none a core made here. fn open(io: std.Io, gpa: std.mem.Allocator, dial: ?[]const u8) !*Tree { const t = try gpa.create(Tree); t.here = null; if (dial) |d| { const no_env = [_:null]?[*:0]const u8{}; try t.f.dial(io, &no_env, d, "pardes"); return t; } const h = try gpa.create(Here); h.core = try pardes.Pardes.create(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory }); h.engine = .init(.{ .in = &h.in, .out = &h.out, .root = pardes.ctlfs.root }); var fds: [2]std.c.fd_t = undefined; if (socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.NoSocketPair; h.fd = fds[1]; (try std.Thread.spawn(.{}, Here.serve, .{h})).detach(); t.here = h; try t.f.init(io, .{ .socket = .{ .handle = fds[0], .address = undefined } }, "pardes"); return t; } /// The whole file at `path`. fn read(t: *Tree, gpa: std.mem.Allocator, path: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(gpa); try t.f.readFile(path, &out.writer); return out.written(); } }; /// The session a command acts on: `-s NAME` (a name, a socket's path or a /// dial), else $PARDES_9P, else the only one whose socket answers. const Found = union(enum) { none, one: []const u8, many: []const []const u8 }; fn findSession(io: std.Io, arena: std.mem.Allocator, named: ?[]const u8) Found { if (named) |n| { if (std.mem.indexOfAny(u8, n, "/!") != null) return .{ .one = n }; var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; var buf: [ninep_io.sun_path_len]u8 = undefined; const dir = ninep_io.socketDir(&dir_buf) orelse return .{ .one = n }; return .{ .one = arena.dupe(u8, ninep_io.socketPath(&buf, dir, n) orelse n) catch n }; } if (std.c.getenv("PARDES_9P")) |d| return .{ .one = std.mem.span(d) }; const names = sessionNames(io, arena); return switch (names.len) { 0 => .none, 1 => findSession(io, arena, names[0]), else => .{ .many = names }, }; } /// The names of the sessions whose sockets answer, in the socket directory. fn sessionNames(io: std.Io, arena: std.mem.Allocator) []const []const u8 { var names: std.ArrayList([]const u8) = .empty; var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; const path = ninep_io.socketDir(&dir_buf) orelse return &.{}; var dir = std.Io.Dir.cwd().openDir(io, path, .{ .iterate = true }) catch return &.{}; defer dir.close(io); var it = dir.iterate(); while (it.next(io) catch null) |e| { const prefix = "pardes-9p-"; if (!std.mem.startsWith(u8, e.name, prefix) or !std.mem.endsWith(u8, e.name, ".sock")) continue; const name = e.name[prefix.len .. e.name.len - ".sock".len]; if (name.len == 0 or !ninep_io.taken(name)) continue; names.append(arena, arena.dupe(u8, name) catch continue) catch continue; } return names.items; } /// What a core made here can say of itself; the rest of the tree is a /// running session's. const offline = [_][]const u8{ "README", "commands", "ctl" }; /// A /commands line: `Word[ arg] root|pane|both[ choices] -- what it does`. const Word = struct { name: []const u8, arg: bool, scope: []const u8, choices: []const u8, doc: []const u8, fn parse(line: []const u8) ?Word { const cut = std.mem.indexOf(u8, line, " -- "); var it = std.mem.tokenizeScalar(u8, line[0 .. cut orelse line.len], ' '); var w: Word = .{ .name = it.next() orelse return null, .arg = false, .scope = "", .choices = "", .doc = if (cut) |c| line[c + 4 ..] else "" }; var next = it.next() orelse return null; if (std.mem.eql(u8, next, "arg")) { w.arg = true; next = it.next() orelse return null; } w.scope = next; w.choices = it.next() orelse ""; return w; } fn find(commands: []const u8, name: []const u8) ?Word { var lines = std.mem.tokenizeScalar(u8, commands, '\n'); while (lines.next()) |line| if (parse(line)) |w| if (std.mem.eql(u8, w.name, name)) return w; return null; } const groups = [_][]const u8{ "file", "column", "session", "jump", "text", "language", "theme", "help", "setting", "addon" }; /// Its group: the first key after the leader, else what it is. fn group(w: Word) []const u8 { if (std.mem.indexOf(u8, w.doc, " (addon ") != null and std.mem.endsWith(u8, w.doc, ")")) return "addon"; if (pardes.config.Runtime.find(w.name) != null) return "setting"; if (std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name)) |b| if (pardes.config.leader_path.get(b)) |p| switch (p[0]) { 'f' => return "file", 'c' => return "column", 's' => return "session", 'j' => return "jump", 'l' => return "language", 't' => return "theme", 'h' => return "help", else => {}, }; return if (std.mem.eql(u8, w.scope, "root")) "session" else "text"; } /// `SPC c n`, its leader key, or empty. fn leader(w: Word, buf: []u8) []const u8 { const b = std.meta.stringToEnum(pardes.builtins.registry.Builtin(), w.name) orelse return ""; const path = pardes.config.leader_path.get(b) orelse return ""; var out: std.Io.Writer = .fixed(buf); out.writeAll("SPC") catch return ""; for (path) |c| out.print(" {c}", .{c}) catch return ""; return out.buffered(); } }; /// A command but new and attach, which go on to start or join a session. fn runCommand(init: std.process.Init, cmd: Cmd, all: []const [:0]const u8) noreturn { const io = init.io; const arena = init.arena.allocator(); var out_buf: [4096]u8 = undefined; var stdout = std.Io.File.stdout().writer(io, &out_buf); const out = &stdout.interface; // Its words as the shell has them: `-s` there is a word typed. if (cmd == .completion) { const status = completion(init, out, all, null); out.flush() catch {}; std.process.exit(status); } // -s NAME and -p N anywhere after the command, but after `--`. var session: ?[]const u8 = null; var pane: ?[]const u8 = if (std.c.getenv("PARDES_PANE")) |p| std.mem.span(p) else null; var rest: std.ArrayList([]const u8) = .empty; var i: usize = 0; while (i < all.len) : (i += 1) { const a = all[i]; const value = i + 1 < all.len; if (std.mem.eql(u8, a, "--")) { for (all[i + 1 ..]) |r| rest.append(arena, r) catch die(io, "out of memory", .{}); break; } else if ((std.mem.eql(u8, a, "-s") or std.mem.eql(u8, a, "--session")) and value) { i += 1; session = all[i]; } else if (std.mem.startsWith(u8, a, "--session=")) { session = a["--session=".len..]; } else if (std.mem.eql(u8, a, "-p") and value and cmd == .do) { i += 1; pane = all[i]; } else rest.append(arena, a) catch die(io, "out of memory", .{}); } const args = rest.items; const status: u8 = switch (cmd) { .new, .attach => unreachable, .ps => manage(io, .list, ""), .kill => { if (args.len == 1 and std.mem.eql(u8, args[0], "--all")) manage(io, .killall, ""); if (args.len != 1 or args[0].len == 0) die(io, "kill needs a session's name (pardes ps lists them), or --all", .{}); manage(io, .kill, args[0]); }, .version => version: { out.writeAll(version_text) catch {}; out.print("9p 9P2000 msize {d}\n", .{@import("9p.zig").msize}) catch {}; break :version 0; }, .skill => skill: { out.writeAll(@embedFile("skill.txt")) catch {}; break :skill 0; }, .help => help(init, out, args, session), .words => listWords(init, out, args, session), .do => doWord(init, args, session, pane), .fs => fsVerb(init, out, args, session), .completion => unreachable, }; out.flush() catch {}; std.process.exit(status); } /// The tree a command that reads reads: a session's when one is named, /// inside, or the only one, else a core made here. fn readTree(init: std.process.Init, session: ?[]const u8) *Tree { const io = init.io; const arena = init.arena.allocator(); const dial: ?[]const u8 = switch (findSession(io, arena, session)) { .one => |d| d, .none, .many => null, }; return Tree.open(io, arena, dial) catch |err| { if (dial) |d| die(io, "no session answers at {s} ({t}): pardes ps lists them", .{ d, err }); die(io, "a core made here would not start: {t}", .{err}); }; } fn help(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { const io = init.io; const arena = init.arena.allocator(); if (args.len == 0) { writeFirstScreen(out) catch {}; return 0; } if (args.len > 1) die(io, "help takes one thing to say: a command, a builtin or a path", .{}); const what = args[0]; if (std.mem.eql(u8, what, "--all")) { // This build's, never a session's: the reference prints it. const t = Tree.open(io, arena, null) catch |err| die(io, "a core made here would not start: {t}", .{err}); writeHelpAll(out, t) catch |err| die(io, "help --all: {t}", .{err}); return 0; } if (std.meta.stringToEnum(Cmd, what)) |c| { writeLeaf(out, c) catch {}; return 0; } const t = readTree(init, session); const commands = t.read(arena, "commands") catch ""; if (Word.find(commands, what)) |w| { var key_buf: [32]u8 = undefined; const key = w.leader(&key_buf); const scope = if (std.mem.eql(u8, w.scope, "root")) "the root ctl" else if (std.mem.eql(u8, w.scope, "both")) "a pane's ctl, or the root's" else "a pane's ctl"; out.print("{s} ({s}{s}{s}; {s})\n {s}\n", .{ w.name, scope, if (key.len == 0) "" else "; ", key, w.group(), w.doc }) catch {}; if (w.choices.len != 0) out.print(" one of: {s}\n", .{w.choices}) catch {}; out.print("\n pardes do {s}{s}\n", .{ w.name, if (w.arg) " [ARG]" else "" }) catch {}; return 0; } var err_buf: [1024]u8 = undefined; var stderr = std.Io.File.stderr().writer(io, &err_buf); var in: std.Io.Reader = .fixed(""); var said: std.Io.Writer.Allocating = .init(arena); const status = cloud9.verbs.run(&t.f, &.{ "help", what }, &in, out, &said.writer); if (status != 0) { stderr.interface.print("pardes: help: {s} is not a command, a builtin (pardes words) or a file of the tree (pardes fs ls)\n", .{what}) catch {}; stderr.interface.flush() catch {}; } return status; } fn listWords(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { const io = init.io; const arena = init.arena.allocator(); if (args.len > 1) die(io, "words takes one group: {s}", .{"file column session jump text language theme help setting addon"}); const only: ?[]const u8 = if (args.len == 1) args[0] else null; if (only) |g| for (Word.groups) |name| { if (std.mem.eql(u8, name, g)) break; } else die(io, "words: no group {s}: file column session jump text language theme help setting addon", .{g}); const t = readTree(init, session); const commands = t.read(arena, "commands") catch |err| die(io, "words: /commands: {t}: {s}", .{ err, t.f.said() }); for (Word.groups) |g| { if (only) |o| if (!std.mem.eql(u8, o, g)) continue; var first = true; var lines = std.mem.tokenizeScalar(u8, commands, '\n'); while (lines.next()) |line| { const w = Word.parse(line) orelse continue; if (!std.mem.eql(u8, w.group(), g)) continue; if (first and only == null) out.print("{s}{s}:\n", .{ if (std.mem.eql(u8, g, Word.groups[0])) "" else "\n", g }) catch {}; first = false; var buf: [64]u8 = undefined; const left = std.fmt.bufPrint(&buf, "{s}{s}", .{ w.name, if (w.arg) " [ARG]" else "" }) catch w.name; out.print(" {s}", .{left}) catch {}; out.splatByteAll(' ', if (left.len < left_width - 1) left_width - left.len else 2) catch {}; out.print("{s}\n", .{w.doc}) catch {}; } } return 0; } fn doWord(init: std.process.Init, args: []const []const u8, session: ?[]const u8, pane: ?[]const u8) u8 { const io = init.io; const arena = init.arena.allocator(); if (args.len == 0) die(io, "do needs a word: pardes do Newcol (pardes words lists them)", .{}); const dial = switch (findSession(io, arena, session)) { .one => |d| d, .none => die(io, "do: no session runs: start one (pardes new --detach=NAME), or name one (-s NAME)", .{}), .many => |names| die(io, "do: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }), }; const t = Tree.open(io, arena, dial) catch |err| die(io, "do: no session answers at {s} ({t}): pardes ps lists them", .{ dial, err }); const commands = t.read(arena, "commands") catch |err| die(io, "do: /commands: {t}: {s}", .{ err, t.f.said() }); const w = Word.find(commands, args[0]) orelse die(io, "do: no word {s} in this session: pardes words lists them", .{args[0]}); const at_pane = !std.mem.eql(u8, w.scope, "root") and pane != null; if (std.mem.eql(u8, w.scope, "pane") and pane == null) die(io, "do: {s} is a pane's word: name the pane with -p N (pardes fs read index lists them)", .{w.name}); const ctl = if (at_pane) std.fmt.allocPrint(arena, "pane/{s}/ctl", .{pane.?}) catch unreachable else "ctl"; const line = std.mem.concat(arena, u8, &.{ std.mem.join(arena, " ", args) catch unreachable, "\n" }) catch unreachable; t.f.writeFile(ctl, line) catch |err| switch (err) { error.Refused => die(io, "do {s}: {s}", .{ w.name, t.f.said() }), else => die(io, "do {s}: {s}: {t}", .{ w.name, ctl, err }), }; return 0; } fn fsVerb(init: std.process.Init, out: *std.Io.Writer, args: []const []const u8, session: ?[]const u8) u8 { const io = init.io; const arena = init.arena.allocator(); var err_buf: [1024]u8 = undefined; var stderr = std.Io.File.stderr().writer(io, &err_buf); defer stderr.interface.flush() catch {}; var in_buf: [64 * 1024]u8 = undefined; var stdin = std.Io.File.stdin().readerStreaming(io, &in_buf); const dial: ?[]const u8 = switch (findSession(io, arena, session)) { .one => |d| d, .none => null, .many => |names| die(io, "fs: {d} sessions run ({s}): name one with -s NAME", .{ names.len, std.mem.join(arena, " ", names) catch "" }), }; if (dial == null and args.len > 0) { const verb = args[0]; const path = std.mem.trim(u8, if (args.len > 1) args[1] else "", "/"); const reads = std.mem.eql(u8, verb, "read"); if (std.mem.eql(u8, verb, "write") or std.mem.eql(u8, verb, "ask") or std.mem.eql(u8, verb, "follow")) die(io, "fs {s}: no session runs to {s}: start one (pardes new --detach=NAME), then -s NAME", .{ verb, verb }); if (reads) for (offline) |name| { if (std.mem.eql(u8, name, path)) break; } else die(io, "fs read {s}: that is a running session's, and none runs: start one (pardes new --detach=NAME), then -s NAME; with none, README, commands and ctl say what they would", .{path}); } const t = Tree.open(io, arena, dial) catch |err| { if (dial) |d| die(io, "fs: no session answers at {s} ({t}): pardes ps lists them", .{ d, err }); die(io, "fs: a core made here would not start: {t}", .{err}); }; return cloud9.verbs.run(&t.f, args, &stdin.interface, out, &stderr.interface); } /// `pardes completion SHELL`: the script; `pardes completion -- WORDS`: /// what may follow, the last word being the one typed so far, a line each /// (`word\twhat it is`). fn completion(init: std.process.Init, out: *std.Io.Writer, args: []const [:0]const u8, session: ?[]const u8) u8 { const io = init.io; const arena = init.arena.allocator(); if (args.len == 1) { const Shell = enum { bash, fish, zsh }; const shell = std.meta.stringToEnum(Shell, args[0]) orelse die(io, "completion: no shell {s}: bash, fish or zsh", .{args[0]}); out.writeAll(switch (shell) { .fish => \\# pardes completion fish: each word asked of pardes itself. \\complete -c pardes -f -a '(pardes completion -- (commandline -opc)[2..-1] (commandline -ct))' \\complete -c pardes -n 'test (count (commandline -opc)) -eq 1' -F \\ , .bash => \\# pardes completion bash: each word asked of pardes itself. \\_pardes() { \\ local IFS=$'\n' line \\ COMPREPLY=() \\ while read -r line; do COMPREPLY+=("${line%%$'\t'*}"); done < <(pardes completion -- "${COMP_WORDS[@]:1:COMP_CWORD}") \\ [ "$COMP_CWORD" -eq 1 ] && COMPREPLY+=($(compgen -f -- "${COMP_WORDS[COMP_CWORD]}")) \\} \\complete -o filenames -F _pardes pardes \\ , .zsh => \\# pardes completion zsh: each word asked of pardes itself. \\_pardes() { \\ local -a said \\ said=("${(@f)$(pardes completion -- "${(@)words[2,CURRENT]}")}") \\ said=("${(@)said//:/\\:}") \\ said=("${(@)said//$'\t'/:}") \\ _describe pardes said \\ (( CURRENT == 2 )) && _files \\} \\compdef _pardes pardes \\ , }) catch {}; return 0; } if (args.len < 2 or !std.mem.eql(u8, args[0], "--")) die(io, "completion needs a shell: bash, fish or zsh", .{}); const typed = args[1..]; const cur = typed[typed.len - 1]; const before = typed[0 .. typed.len - 1]; const Offer = struct { fn one(w: *std.Io.Writer, prefix: []const u8, word: []const u8, what: []const u8) void { if (!std.mem.startsWith(u8, word, prefix)) return; w.print("{s}{s}{s}\n", .{ word, if (what.len == 0) "" else "\t", what }) catch {}; } }; if (before.len == 0) { for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line); if (cur.len != 0 and cur[0] == '-') for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old) Offer.one(out, cur, @tagName(f), flags.get(f).doc); return 0; } const cmd = std.meta.stringToEnum(Cmd, before[0]) orelse return 0; switch (cmd) { .new => for (std.enums.values(Flag)) |f| if (flags.get(f).group == .session) Offer.one(out, cur, @tagName(f), flags.get(f).doc), .attach, .kill => if (before.len == 1) for (sessionNames(io, arena)) |name| Offer.one(out, cur, name, "a session"), .completion => if (before.len == 1) for ([_][]const u8{ "bash", "fish", "zsh" }) |s| Offer.one(out, cur, s, ""), .words => if (before.len == 1) for (Word.groups) |g| Offer.one(out, cur, g, ""), .do, .help => if (before.len == 1) { if (cmd == .help) for (std.enums.values(Cmd)) |c| Offer.one(out, cur, @tagName(c), cmds.get(c).line); const t = readTree(init, session); var lines = std.mem.tokenizeScalar(u8, t.read(arena, "commands") catch "", '\n'); while (lines.next()) |line| if (Word.parse(line)) |w| Offer.one(out, cur, w.name, w.doc); if (cmd == .help) { var said: std.Io.Writer.Allocating = .init(arena); var in: std.Io.Reader = .fixed(""); _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer); } } else if (cmd == .do) { const t = readTree(init, session); if (Word.find(t.read(arena, "commands") catch "", before[1])) |w| if (w.choices.len != 0) { var it = std.mem.tokenizeScalar(u8, w.choices, ','); while (it.next()) |c| Offer.one(out, cur, c, ""); }; }, .fs => if (before.len == 1) { var verbs = std.mem.tokenizeAny(u8, "ls read write ask follow stat help complete", " "); while (verbs.next()) |v| Offer.one(out, cur, v, ""); } else if (before.len == 2) { const t = readTree(init, session); var said: std.Io.Writer.Allocating = .init(arena); var in: std.Io.Reader = .fixed(""); _ = cloud9.verbs.run(&t.f, &.{ "complete", cur }, &in, out, &said.writer); }, .ps, .skill, .version => {}, } return 0; } pub const main = nativeMain; // glibc's struct termios is 60 bytes, Zig 0.17's std.c.termios the kernel's // 44: libc's tcgetattr wrote 16 bytes past every Zig caller's (vaxis's // makeRaw, the stub's, the GUI's), and a ReleaseSafe build trapped at its // first terminal. These take libc's place in the process: the kernel's own // ioctls, which read and write only the 36 bytes both layouts begin with // (the flags, the line, the kernel's 19 cc), so a caller of either size // stays within its struct. comptime { if (builtin.os.tag == .linux and builtin.abi.isGnu()) { @export(&kernelTcgetattr, .{ .name = "tcgetattr" }); @export(&kernelTcsetattr, .{ .name = "tcsetattr" }); } } fn kernelTcgetattr(fd: c_int, t: *std.os.linux.termios) callconv(.c) c_int { return libcResult(std.os.linux.tcgetattr(fd, t)); } fn kernelTcsetattr(fd: c_int, how: c_int, t: *const std.os.linux.termios) callconv(.c) c_int { return libcResult(std.os.linux.tcsetattr(fd, @fromBackingInt(@bitCast(how)), t)); } fn libcResult(rc: usize) c_int { const e = std.os.linux.errno(rc); if (e == .SUCCESS) return 0; std.c._errno().* = @intCast(@backingInt(e)); return -1; } fn parseCtrlKey(raw: []const u8) ?u21 { var value = std.mem.trim(u8, raw, " \t\r\n"); if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl-")) { value = value[5..]; } else if (value.len >= 5 and std.ascii.eqlIgnoreCase(value[0..5], "ctrl+")) { value = value[5..]; } else if (value.len == 2 and value[0] == '^') { value = value[1..]; } if (value.len != 1) return null; const c = std.ascii.toLower(value[0]); if (c < 'a' or c > 'z' or c == 'c') return null; return c; } // init.gpa, what the tui, gui and detached shells allocate from, is their // own fixed arena (memory.host) in a release build, spilling to libc's // malloc, and std.start's DebugAllocator in Debug. Zig 0.17's std.start // gives a safe build a SafeAllocator over the page allocator instead. fn nativeMain(std_init: std.process.Init) !void { var init = std_init; if (builtin.mode != .debug) init.gpa = pardes.memory.host(std.heap.c_allocator); // A recorded session's tape replayed, no session of its own (src/tape.zig). if (init.environ_map.get("PARDES_REPLAY")) |tape| std.process.exit(pardes.tape.replayMain(tape)); var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); var opts: pardes.Options = .{}; var mounts: [pardes.filesystem.max_mounts]pardes.filesystem.Mount = undefined; var mounts_len: usize = 0; const arena = init.arena.allocator(); const args = try init.minimal.args.toSlice(arena); // An addon's author's test (addon_test.zig): nothing else. if (args.len >= 3 and std.mem.eql(u8, args[1], "--addon-test")) std.process.exit(@import("addon_test.zig").main(init.io, init.gpa, args[2], if (args.len > 3) args[3] else null)); // The per-user daemon a session started (daemon.zig), or an upgrade of // one with its registry: nothing else. if (comptime daemon.supported) if (args.len >= 2 and args.len <= 3 and std.mem.eql(u8, args[1], "--daemon")) daemon.serve(if (args.len == 3 and std.mem.startsWith(u8, args[2], upgrade.flag)) args[2][upgrade.flag.len..] else null); // An upgraded session's new process (upgrade.zig): its record, then the // arguments it was started with, which configure it as before; its // file, stdin, directory and daemon come from the record instead. const upgraded = comptime upgrade.supported and (pardes.platform == .tui or pardes.platform == .gui); if (upgraded) if (args.len > 1 and std.mem.startsWith(u8, args[1], upgrade.flag)) { upgrade.resumed = upgrade.Record.decode(args[1][upgrade.flag.len..]) catch badArgs(init.io, "--upgraded: a record this build cannot read", .{}); }; const resuming = upgrade.resumed != null; var session_only = true; var new_session = false; var explicit_tty = false; var detach: ?[]const u8 = null; var attach: ?[]const u8 = null; var positional: ?[:0]const u8 = null; var wait = false; var i: usize = if (resuming) 2 else 1; // A command's name first: new and attach go on to start or join a // session, with the flags after them; the rest are done in `command`. if (!resuming and args.len > 1) if (std.meta.stringToEnum(Cmd, args[1])) |cmd| switch (cmd) { .new => { new_session = true; i = 2; }, .attach => { const named = args.len > 2 and args[2].len > 0 and args[2][0] != '-'; attach = if (named) args[2] else ""; i = if (named) 3 else 2; }, else => runCommand(init, cmd, args[2..]), }; while (i < args.len) : (i += 1) { const a = args[i]; if (a.len < 2 or a[0] != '-') { // `-` is stdin, as for cat and vim: a text to show. if (a.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{a}); session_only = false; positional = a; continue; } // `flags` says what each takes: nothing, the next argument (or // after `=`), a value after `=`, or maybe one. const eq = std.mem.indexOfScalar(u8, a, '='); const flag = std.meta.stringToEnum(Flag, a[0 .. eq orelse a.len]) orelse badArgs(init.io, "no such option: {s}", .{a}); var value: ?[]const u8 = if (eq) |e| a[e + 1 ..] else null; switch (flags.get(flag).takes) { .none => if (value != null) badArgs(init.io, "{t} takes no value: {s}", .{ flag, a }), .next => if (value == null and i + 1 < args.len) { i += 1; value = args[i]; }, .eq, .maybe => {}, } switch (flag) { .@"--tty" => explicit_tty = true, .@"-n" => { session_only = false; new_session = true; const count = value orelse badArgs(init.io, "-n needs a count after it: 1 or 3", .{}); opts.shells = std.fmt.parseInt(u8, count, 10) catch badArgs(init.io, "-n takes 1 or 3, not '{s}'", .{count}); }, .@"-l" => { session_only = false; new_session = true; opts.load_path = value orelse badArgs(init.io, "-l needs the path of a dump to load", .{}); }, .@"--tty-toggle" => { session_only = false; new_session = true; const key = value orelse badArgs(init.io, "--tty-toggle needs a letter after it", .{}); opts.tty_toggle = parseCtrlKey(key) orelse badArgs(init.io, "--tty-toggle wants one letter, not '{s}'", .{key}); }, .@"--nested" => opts.nested = true, .@"-w", .@"--wait" => wait = true, .@"--9p" => { new_session = true; const name = value orelse badArgs(init.io, "--9p needs a socket name: --9p=", .{}); if (name.len == 0 or std.mem.indexOfAny(u8, name, "/\x00") != null) badArgs(init.io, "invalid 9P socket name: '{s}'", .{name}); opts.ninep_name = name; }, .@"--9p-tcp" => { new_session = true; const dial = value orelse badArgs(init.io, "--9p-tcp needs tcp!!", .{}); if (!std.mem.startsWith(u8, dial, "tcp!")) badArgs(init.io, "--9p-tcp needs tcp!!", .{}); _ = @import("9p_io.zig").networkAddress(dial, true) catch badArgs(init.io, "--9p-tcp needs tcp!!", .{}); if (opts.ninep_tcp != null) badArgs(init.io, "--9p-tcp was specified twice", .{}); opts.ninep_tcp = dial; }, .@"--mount" => { new_session = true; const mount = value orelse badArgs(init.io, "--mount needs name=dial", .{}); const split = std.mem.indexOfScalar(u8, mount, '=') orelse badArgs(init.io, "--mount needs name=dial", .{}); const name = mount[0..split]; const dial = mount[split + 1 ..]; if (dial.len == 0 or !@import("fs.zig").validMountName(name)) badArgs(init.io, "invalid mount name or dial: '{s}'", .{mount}); @import("9p_io.zig").Client.validateDial(dial) catch badArgs(init.io, "invalid mount dial: '{s}'", .{dial}); for (mounts[0..mounts_len]) |existing| if (std.mem.eql(u8, existing.name, name)) badArgs(init.io, "duplicate mount name: '{s}'", .{name}); if (mounts_len == mounts.len) badArgs(init.io, "too many mounts (maximum {d})", .{mounts.len}); mounts[mounts_len] = .{ .name = name, .dial = dial }; mounts_len += 1; }, .@"--geometry" => opts.geometry = value orelse badArgs(init.io, "--geometry needs WxH[+X+Y]", .{}), .@"--detach" => detach = value orelse "", .@"--attach" => attach = value orelse "", .@"--ps" => manage(init.io, .list, ""), .@"--kill" => { const name = value orelse ""; if (name.len == 0) badArgs(init.io, "--kill needs a session's name; --kill-all ends every one", .{}); manage(init.io, .kill, name); }, .@"--kill-all" => manage(init.io, .killall, ""), .@"-h", .@"--help" => runCommand(init, .help, &.{}), .@"--version" => runCommand(init, .version, &.{}), .@"--" => { // The end of options: what follows is a name, `-dash.txt` too. for (args[i + 1 ..]) |name| { if (name.len == 0) badArgs(init.io, "an empty argument names nothing", .{}); if (positional != null) badArgs(init.io, "one file or directory at a time, and '{s}' is the second", .{name}); session_only = false; positional = name; } break; }, } } opts.tty_only = explicit_tty or session_only; opts.mounts = mounts[0..mounts_len]; // `zig build run-isolated` with nothing named: something to look at on // arrival, read out of the binary itself. if (pardes.isolated and positional == null) { session_only = false; positional = "src/pardes.zig"; } if (detach != null and attach != null) badArgs(init.io, "--detach and --attach are opposites: one runs the session, the other joins one", .{}); // --wait waits on the pane a FILE opens: with none there is nothing to // wait for (EDITOR=pardes --wait is given the file). if (wait and positional == null) badArgs(init.io, "--wait needs a FILE: it returns when that file's pane is closed", .{}); if (opts.ninep_name.len != 0 and attach != null) badArgs(init.io, "--9p names a session's own socket, and --attach has none of its own", .{}); if (opts.ninep_tcp != null and attach != null) badArgs(init.io, "--9p-tcp opens a session's own listener, and --attach has none of its own", .{}); if (opts.mounts.len != 0 and attach != null) badArgs(init.io, "--mount configures a session's own core, and --attach has none of its own", .{}); if (!new_session and !opts.nested and detach == null and attach == null and !resuming) forwarding: { // Am I inside a pardes at all? That is $PARDES_PID and nothing else — // one variable, exported by every session that means to take its // children's Looks, so a session that could not open a socket is still // recognisably the session this shell is inside. A pid naming no live // process is a shell that outlived its editor (a daemon started from a // pane, a stale environment carried into a new terminal), which is not // nested at all. // `--wait` with only $PARDES_9P (a script or agent that talks to a // session from outside its panes, EDITOR='pardes --wait') is asked // of that session too: what it waits on is a pane there. const outside = wait and std.c.getenv("PARDES_PID") == null and std.c.getenv("PARDES_9P") != null; if (!outside) { const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding; } // Can I reach it? That is the other two, and it is a separate answer. const Parent = struct { dial: []const u8, serial: u32 }; const found: ?Parent = reaching: { const dial = std.mem.span(std.c.getenv("PARDES_9P") orelse break :reaching null); ninep_io.Client.validateDial(dial) catch break :reaching null; // No pane of its own (`outside`): the session's root look, 0. const pane_text = std.mem.span(std.c.getenv("PARDES_PANE") orelse if (outside) break :reaching .{ .dial = dial, .serial = 0 } else break :reaching null); for (pane_text) |byte| if (!std.ascii.isDigit(byte)) break :reaching null; const serial = std.fmt.parseInt(u32, pane_text, 10) catch break :reaching null; if (serial == 0) break :reaching null; break :reaching .{ .dial = dial, .serial = serial }; }; // A pid we cannot reach is a session that is not answering: the shell // says it is inside one, but there is nothing there to take the file. // Starting an ordinary editor is what this did before the pid existed // and is the more useful of the two answers -- refusing to start would // leave a stale environment variable able to lock someone out of their // own editor. const parent = found orelse break :forwarding; // Does it answer? One that answers takes the file or says why not, // as acme's B does: from here on never a nested editor, whose // screen would be drawn inside the pane that asked. ninep_io.Client.probe(arena, parent.dial) catch { // `--wait` is someone's EDITOR waiting on that session: a screen // of its own drawn in their terminal is no answer. Said, exit 1. if (wait) die(init.io, "--wait: the session at {s} does not answer; it is gone", .{parent.dial[0..@min(parent.dial.len, 4096)]}); break :forwarding; }; const Refuse = struct { fn with(io: std.Io, what: []const u8, err: anyerror) noreturn { var words_buf: [128]u8 = undefined; die(io, "{s}: {s}", .{ what[0..@min(what.len, 4096)], if (err == error.Remote) ninep_io.Client.lastSaid() else forwardWords(err, &words_buf) }); } }; // The pane's `look` file: one line, and the line is the clicked text // itself, which is what a right click in that pane would have been. var look_buf: [64]u8 = undefined; const look = if (parent.serial == 0) "/look" else try std.fmt.bufPrint(&look_buf, "/pane/{d}/look", .{parent.serial}); // `pardes -`: stdin read to its end, a +Pager pane of the session // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); // Nothing paged: no pane, and done. if (text.len == 0) return; pageInto(init.io, arena, parent.dial, text); return; }; // From outside the session's panes there is no pane to say it is // nested in: `--wait` with no file opens nothing there. if (parent.serial == 0 and positional == null) break :forwarding; const typed_word = positional orelse { var tag_buf: [64]u8 = undefined; const tag = try std.fmt.bufPrint(&tag_buf, "/pane/{d}/tag", .{parent.serial}); const contents = ninep_io.Client.read(arena, parent.dial, tag, tag) catch |err| Refuse.with(init.io, tag, err); arena.free(contents); try std.Io.File.stderr().writeStreamingAll(init.io, nested_text); std.process.exit(1); }; // Named as it was given, its newline shown `\n`, so the refusal says // which name and why once. if (std.mem.indexOfAny(u8, typed_word, "\r\n") != null) { var shown_buf: [4 * 4096]u8 = undefined; Refuse.with(init.io, pardes.ctlfs.events.shown(typed_word[0..@min(typed_word.len, 4096)], &shown_buf), error.NotOneLine); } // `pardes '~/x'`, quoted so the shell left it: home, as a look's. var home_buf: [4096]u8 = undefined; const word = pardes.filesystem.expandHome(typed_word, &home_buf); const target = @import("look.zig").parsePathLine(word); // `@pN[:addr]` addresses a pane of this session: one it has is // looked at, one it has not is refused, never a file of that name. if (std.mem.startsWith(u8, target.path, pardes.config.pane_addr)) { const digits = word[pardes.config.pane_addr.len .. std.mem.indexOfScalar(u8, word, ':') orelse word.len]; const serial = std.fmt.parseInt(u32, digits, 10) catch Refuse.with(init.io, word, error.NotAPaneAddress); var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); const named = ninep_io.Client.read(arena, parent.dial, name, name) catch Refuse.with(init.io, word, error.NoSuchPane); arena.free(named); var command_buf: [4200]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}\n", .{word}) catch |err| Refuse.with(init.io, word, err); ninep_io.Client.write(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); return; } var realbuf: [4096]u8 = undefined; var newbuf: [4096]u8 = undefined; const found_path: ?[]const u8 = if (pardes.filesystem.isVirtual(target.path)) target.path else if (pardes.filesystem.resolveOs(target.path, &realbuf)) |r| r.path else null; const path = found_path orelse named: { // A name not there yet, as acme's B takes one: its directory // resolved and the name kept, a pane made for it that Save // creates the file from. const base = std.Io.Dir.path.basename(target.path); if (base.len == 0 or std.mem.eql(u8, base, ".") or std.mem.eql(u8, base, "..")) Refuse.with(init.io, word, error.NotAFileName); const dir = pardes.filesystem.resolveOs(std.Io.Dir.path.dirname(target.path) orelse ".", &realbuf) orelse { // Its directory not there either: the name made absolute as // written, and the pane's Save makes the directories. var cwd_buf: [4096]u8 = undefined; const cwd = cwd_buf[0 .. std.process.currentPath(init.io, &cwd_buf) catch Refuse.with(init.io, word, error.NoWorkingDirectory)]; const absolute = std.Io.Dir.path.resolvePosix(arena, &.{ cwd, target.path }) catch |err| Refuse.with(init.io, word, err); // Missing because one above may not be searched or written: // its Save could never make it, so refused now. if (pardes.filesystem.deniedAbove(std.Io.Dir.path.dirname(absolute) orelse "/")) Refuse.with(init.io, word, error.DirectoryNotWritable); break :named absolute; }; // A directory that is there but may not be read or written: a // pane for the name could only fail at its Save, so refused now. std.Io.Dir.cwd().access(init.io, dir.path, .{ .read = true, .write = true, .execute = true }) catch Refuse.with(init.io, word, error.DirectoryNotWritable); break :named std.fmt.bufPrint(&newbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir.path, "/"), base }) catch |err| Refuse.with(init.io, word, err); }; var made_serial: ?u32 = null; if (found_path != null) { var command_buf: [8192]u8 = undefined; const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); // The pane it went to, read on the open that asked (another // client's look meanwhile is not this one's): what --wait waits on. const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err); var rows = std.mem.tokenizeAny(u8, went, " \n"); if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; } else { const made = ninep_io.Client.read(arena, parent.dial, "/pane/new", "/pane/new") catch |err| Refuse.with(init.io, word, err); const serial = std.fmt.parseInt(u32, std.mem.trim(u8, made, " \n"), 10) catch |err| Refuse.with(init.io, word, err); made_serial = serial; var name_buf: [64]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "/pane/{d}/name", .{serial}); var line_buf: [4200]u8 = undefined; const line = std.fmt.bufPrint(&line_buf, "{s}\n", .{path}) catch |err| Refuse.with(init.io, word, err); ninep_io.Client.write(arena, parent.dial, name, line) catch |err| { // The name refused: the pane made for it goes too, no // stray +New left behind. var ctl_buf: [64]u8 = undefined; const ctl = std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable; var why_buf: [256]u8 = undefined; const said = ninep_io.Client.lastSaid(); const why = why_buf[0..@min(said.len, why_buf.len)]; @memcpy(why, said[0..why.len]); ninep_io.Client.write(arena, parent.dial, ctl, "delete\n") catch {}; if (err == error.Remote) die(init.io, "{s}: {s}", .{ word[0..@min(word.len, 4096)], why }); Refuse.with(init.io, word, err); }; } if (wait) waitForDel(arena, parent.dial, path, made_serial); return; } if (resuming) positional = null; // `pardes -` outside a session: an editor whose first pane holds stdin, // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); // Nothing paged: nothing to show. if (opts.stdin_text.?.len == 0) return; positional = null; }; if (positional) |a| { const target = @import("look.zig").parsePathLine(a); if (std.mem.eql(u8, target.path, "/n") or std.mem.startsWith(u8, target.path, "/n/") or std.mem.eql(u8, target.path, "/virtual") or std.mem.startsWith(u8, target.path, "/virtual/")) { opts.file = try arena.dupe(u8, target.path); opts.file_line = target.at.line; } else if (std.meta.isError(std.process.setCurrentPath(init.io, a))) { var cwdbuf: [4096]u8 = undefined; const cwd = cwdbuf[0 .. std.process.currentPath(init.io, &cwdbuf) catch badArgs(init.io, "this shell's working directory is gone; cd somewhere that exists", .{})]; var realbuf: [4096]u8 = undefined; switch (@import("look.zig").resolve(null, a, cwd, &realbuf)) { .file => |t| { opts.file = try arena.dupe(u8, t.path); opts.file_line = t.at.line; }, .kind => |t| opts.file = try arena.dupe(u8, t.path), .none => opts.missing = .{ .word = try arena.dupe(u8, a), .dir = try arena.dupe(u8, cwd), }, .url => badArgs(init.io, "a URL is not something a launch can open; start pardes and click it", .{}), .pane => badArgs(init.io, "@pN addresses a pane of a running pardes, so there is none yet", .{}), else => badArgs(init.io, "cannot enter that directory: {s}", .{a}), } } } // The real bare-tty startup wants the editor half present from the first // frame, so it names that layout; a core booted for a test names none and // gets the raw shell by itself. This has to come AFTER the positional is // resolved: naming a layout short-circuits `Boot.of`, so choosing it any // earlier threw away a file argument, and the error pane for one that does // not exist, without a word. if (opts.tty_only and opts.file == null and opts.missing == null) opts.boot = .tty; const found = pardes.config.User.load(init.io, arena, init.environ_map); opts.startup_config = found.bytes; opts.startup_config_path = found.path; opts.config_dir = found.dir; opts.state = .disk; opts.recent_import = oldRecentDir(arena, init.environ_map); if (found.dir) |d| @import("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, opts, name); if (detach) |name| { // Said plainly, never a Zig error trace: a name a live session's // socket holds already (a plain session is named by its pid too). if (name.len != 0 and !resuming and ninep_io.taken(name)) die(init.io, "a session named {s} is already running", .{name}); if (opts.ninep_name.len == 0) opts.ninep_name = name; // Said where it was started (stderr, as the log says it): no pane // anyone sees would show it. The session runs on, with no 9P. var pid_buf: [16]u8 = undefined; var words_buf: [256]u8 = undefined; const entry = if (opts.ninep_name.len != 0) opts.ninep_name else std.fmt.bufPrint(&pid_buf, "{d}", .{std.c.getpid()}) catch unreachable; // a pid fits 16 if (ninep_io.noSocket(entry, &words_buf)) |words| { var line_buf: [300]u8 = undefined; std.Io.File.stderr().writeStreamingAll(init.io, std.fmt.bufPrint(&line_buf, "pardes: {s}\n", .{words}) catch unreachable) catch {}; // 256 fits 300 } // Nobody's size yet: one roomy enough for a script's panes; `size` // sets another, and an attached terminal or window its own. opts.cols = 160; opts.rows = 50; } const kind: daemon.Kind = if (pardes.platform == .gui) .gui else .tty; var term: @import("tui/tui.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 == .tui) fork: { // A terminal's session is forked off its stub, which stays the // job the shell waits on: Detach (or the terminal's end) ends // the job and leaves the session running (daemon.forkSession). // The daemon is reached or started first, from this small // process, and the terminal opened while it is this one's. const conn = daemon.connect(true) orelse break :fork; const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); if (fd < 0) { daemon.startPending(true); _ = std.c.close(conn); break :fork; } // Started in the background, the job stops here until it is // brought to the foreground, as one making its terminal raw does. // std.posix's termios, not std.c's: glibc's is the bigger struct. if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} daemon.forkSession(conn) orelse { daemon.startPending(true); _ = std.c.close(fd); _ = std.c.close(conn); break :fork; }; _ = daemon.register(conn, .tty, opts.ninep_name, false); term = .{ .fd = .{ .fd = fd } }; } } defer daemon.quit(); errdefer daemon.tellStubExit(1); switch (pardes.platform) { .tui => @import("tui/tui.zig").run(init, opts, term) catch |err| switch (err) { // No controlling terminal (a detached pty, a daemon): said, not // an error trace. error.NoDevice => { std.Io.File.stderr().writeStreamingAll(init.io, "pardes: no terminal to draw on: /dev/tty will not open; run it in a terminal, or --detach\n") catch {}; std.process.exit(1); }, else => return err, }, .gui => try @import("gui/gui.zig").run(init, opts, headless), .macos => unreachable, } daemon.tellStubExit(0); } extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; /// `pardes --ps`: what the per-user daemon keeps, as a tree; `--kill=` /// and `--kill-all`: those sessions ended with their shells, a TERM and, /// for one still there 2 s later, a KILL. fn manage(io: std.Io, verb: enum { list, kill, killall }, name: []const u8) noreturn { if (comptime !daemon.supported) die(io, "this system has no pardes daemon", .{}); var words_buf: [300]u8 = undefined; const words = if (verb == .kill) std.fmt.bufPrint(&words_buf, "kill {s}", .{name}) catch die(io, "that name is too long", .{}) else @tagName(verb); var buf: [4096]u8 = undefined; const said = daemon.ask(words, &buf) orelse die(io, "no pardes daemon is running", .{}); if (std.mem.startsWith(u8, said, "no ")) die(io, "{s}", .{said[3..]}); if (verb == .list) { var out: [8192]u8 = undefined; var w: std.Io.Writer = .fixed(&out); var lines = std.mem.tokenizeScalar(u8, said, '\n'); var orphans = false; while (lines.next()) |line| { var it = std.mem.tokenizeScalar(u8, line, ' '); const what = it.next() orelse continue; const pid = it.next() orelse continue; var comm_buf: [64]u8 = undefined; const comm = commOf(io, pid, &comm_buf); switch (std.meta.stringToEnum(enum { daemon, session, client, shell, orphan }, what) orelse continue) { .daemon => w.print("pardes daemon {s}\n", .{pid}) catch break, .session => { const kind = it.next() orelse ""; const state = it.next() orelse ""; w.print(" session {s} {s} ({s}, {s})\n", .{ std.mem.trim(u8, it.rest(), " "), pid, kind, state }) catch break; }, .client => w.print(" client {s} {s}\n", .{ pid, comm }) catch break, .shell => w.print(" shell {s} {s}\n", .{ pid, comm }) catch break, .orphan => { if (!orphans) w.writeAll(" shells no session holds (Adopt takes them, --kill-all ends them)\n") catch break; orphans = true; w.print(" shell {s} {s}\n", .{ pid, comm }) catch break; }, } } std.Io.File.stdout().writeStreamingAll(io, w.buffered()) catch {}; std.process.exit(0); } var pids: [64]std.c.pid_t = undefined; var n: usize = 0; var it = std.mem.tokenizeScalar(u8, said, ' '); _ = it.next(); // ok while (it.next()) |p| if (n < pids.len) { pids[n] = std.fmt.parseInt(std.c.pid_t, p, 10) catch continue; n += 1; }; // Gone once the daemon no longer lists them: a session's link ends with // its process, a zombie's too, which kill(pid, 0) would call alive. const Gone = struct { fn all(list: []const std.c.pid_t, ms: u32) bool { var waited: u32 = 0; while (true) : (waited += 20) { var reply: [4096]u8 = undefined; const now = daemon.ask("list", &reply) orelse return true; var lines = std.mem.tokenizeScalar(u8, now, '\n'); const left = while (lines.next()) |line| { var fields = std.mem.tokenizeScalar(u8, line, ' '); if (!std.mem.eql(u8, fields.next() orelse "", "session")) continue; const pid = std.fmt.parseInt(std.c.pid_t, fields.next() orelse "", 10) catch continue; if (std.mem.indexOfScalar(std.c.pid_t, list, pid) != null) break true; } else false; if (!left) return true; if (waited >= ms) return false; const ts: std.c.timespec = .{ .sec = 0, .nsec = 20 * std.time.ns_per_ms }; _ = std.c.nanosleep(&ts, null); } } }; if (!Gone.all(pids[0..n], 2000)) { for (pids[0..n]) |p| _ = std.c.kill(p, .KILL); if (!Gone.all(pids[0..n], 1000)) die(io, "a session would not end, even killed", .{}); } std.process.exit(0); } /// The command `pid` runs, as /proc says it (Linux); empty where it does not. fn commOf(io: std.Io, pid: []const u8, buf: *[64]u8) []const u8 { var path_buf: [64]u8 = undefined; const path = std.fmt.bufPrint(&path_buf, "/proc/{s}/comm", .{pid}) catch return ""; return std.mem.trimEnd(u8, std.Io.Dir.cwd().readFile(io, path, buf) catch return "", "\n"); } /// The replica client of this build's frontend: a terminal's (tui.zig) or a /// window's (gui.zig). fn clientOf(init: std.process.Init, opts: pardes.Options, path: []const u8, name: []const u8, far: bool) !void { switch (pardes.platform) { .tui => try @import("tui/tui.zig").remote(init, opts, path, name, far), .gui => try @import("gui/gui.zig").remote(init, opts, path, name, far), else => unreachable, } } /// `pardes --attach=:` (`pardes-gui` too): a replica client /// (tui.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 != .tui and pardes.platform != .gui) unreachable; if (std.mem.indexOfScalar(u8, where, '/') != null) { clientOf(init, opts, where, name, false) catch |err| die(io, "--attach: {t}", .{err}); std.process.exit(0); } // ssh -L : , until the socket here answers. var here_buf: [ninep_io.sun_path_len:0]u8 = undefined; const tmp = std.mem.span(std.c.getenv("TMPDIR") orelse "/tmp"); const here = std.fmt.bufPrintSentinel(&here_buf, "{s}/pardes-ssh-{d}.sock", .{ tmp, std.c.getpid() }, 0) catch die(io, "--attach: TMPDIR is too long for a socket's path", .{}); var there_buf: [ninep_io.sun_path_len + 64:0]u8 = undefined; var dir_buf: [ninep_io.sun_path_len:0]u8 = undefined; const dir = if (std.c.getenv("PARDES_REMOTE_RUNTIME")) |d| std.mem.span(d) else ninep_io.socketDir(&dir_buf) orelse die(io, "--attach: no runtime directory to name the 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 die(io, "--attach: that host's name is too long", .{}); var argv: [48:null]?[*:0]const u8 = @splat(null); var n: usize = 0; var words_buf: [1024]u8 = undefined; // Not `ssh -C`: what the session sends a far client is zstd already // (replica.zig), and zlib over it costs both ends' time for nothing. // ponytail: what the client sends goes as it is, keys and a paste // alike; a big paste through a slow link is the ceiling, and would be // an envelope of its own. $PARDES_SSH, when set, is the whole command. var words = std.mem.tokenizeScalar(u8, std.mem.span(std.c.getenv("PARDES_SSH") orelse "ssh"), ' '); var at: usize = 0; while (words.next()) |w| { if (n >= 40 or at + w.len + 1 > words_buf.len) die(io, "--attach: PARDES_SSH has too many words", .{}); @memcpy(words_buf[at..][0..w.len], w); words_buf[at + w.len] = 0; argv[n] = @ptrCast(&words_buf[at]); n += 1; at += w.len + 1; } // A terminal asked for and a command that waits, not -N: only an // interactive connection gets TCP_NODELAY from ssh and sshd, and with // Nagle each key in a burst waited for the last one's ACK, a round trip. for ([_][*:0]const u8{ "-tt", "-q", "-o", "ExitOnForwardFailure=yes", "-L", forward.ptr, host.ptr, "exec sleep 2147483647" }) |a| { argv[n] = a; n += 1; } _ = std.c.unlink(here); const pid = std.c.fork(); if (pid < 0) die(io, "--attach: no fork for ssh", .{}); if (pid == 0) { // A client killed outright takes its ssh with it. daemon.hupOnStubDeath(true); const null_fd = std.c.open("/dev/null", .{ .ACCMODE = .RDONLY }, @as(std.c.mode_t, 0)); if (null_fd >= 0) _ = std.c.dup2(null_fd, 0); _ = execvp(argv[0].?, &argv); std.c._exit(127); } // Ended at the client's exit, whatever path it takes there (its own // words on a refused redial exit from inside it). ponytail: a client // that crashes leaves its socket's file behind; its ssh goes. const Ssh = struct { var child: std.c.pid_t = 0; var path: [:0]const u8 = ""; fn end() callconv(.c) void { if (child > 0) { _ = std.c.kill(child, .TERM); _ = std.c.waitpid(child, null, 0); } _ = std.c.unlink(path); } }; Ssh.child = pid; Ssh.path = here; _ = atexit(Ssh.end); var waited: u32 = 0; while (std.meta.isError(std.Io.Dir.cwd().access(io, here, .{}))) : (waited += 1) { var status: c_int = 0; if (std.c.waitpid(pid, &status, std.c.W.NOHANG) == pid) { Ssh.child = 0; die(io, "--attach: ssh to {s} ended before its forward was up", .{where}); } if (waited > 3000) die(io, "--attach: ssh to {s} set up no forward in 30 s", .{where}); const ts: std.c.timespec = .{ .sec = 0, .nsec = 10 * std.time.ns_per_ms }; _ = std.c.nanosleep(&ts, null); } clientOf(init, opts, here, name, true) catch |err| die(io, "--attach: {t}", .{err}); std.process.exit(0); } /// `pardes --attach[=name]` in a terminal: this terminal handed (through /// the daemon) to the detached session of that name, or the only one, and /// this process its stub until the session leaves it. `pardes-gui /// --attach`: the session asked to open its window again, and done. A /// session attached already, or of the other kind, is joined as a replica /// client, through this machine's replica socket. fn attachTo(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { const io = init.io; var words: [600]u8 = undefined; if (comptime !daemon.supported) die(io, "--attach: this system has no pardes daemon to attach through", .{}); if (pardes.platform == .gui) switch (daemon.attach(.gui, name, &.{}, &words)) { .ok => std.process.exit(0), .no => |why| die(io, "--attach: {s}", .{why}), .other => |named| crossAttach(init, opts, named), }; const fd = std.c.open("/dev/tty", .{ .ACCMODE = .RDWR, .CLOEXEC = true, .NOCTTY = true }, @as(std.c.mode_t, 0)); if (fd < 0) die(io, "--attach: no terminal to attach: /dev/tty will not open", .{}); if (std.posix.tcgetattr(fd)) |tio| std.posix.tcsetattr(fd, .NOW, tio) catch {} else |_| {} var pipe: [2]std.c.fd_t = undefined; if (std.c.pipe(&pipe) != 0) die(io, "--attach: no pipe for the session to say when it leaves", .{}); ninep_io.setCloexec(pipe[0]); ninep_io.setCloexec(pipe[1]); switch (daemon.attach(.tty, name, &.{ fd, pipe[1] }, &words)) { .ok => |pid| { _ = std.c.close(fd); _ = std.c.close(pipe[1]); daemon.stubWait(pid, false, pipe[0]); }, .no => |why| die(io, "--attach: {s}", .{why}), .other => |named| { _ = std.c.close(fd); _ = std.c.close(pipe[0]); _ = std.c.close(pipe[1]); crossAttach(init, opts, named); }, } } /// A session attached already or of the other kind (`--attach`'s): a /// replica client of it here. fn crossAttach(init: std.process.Init, opts: pardes.Options, name: []const u8) noreturn { var sock_buf: [ninep_io.sun_path_len:0]u8 = undefined; const sock = daemon.replicaSocket(&sock_buf) orelse die(init.io, "--attach: no runtime directory for the replica socket", .{}); remoteAttach(init, opts, sock, name); } /// Where Recent's file (0.24) and the store before it were kept: /// $XDG_STATE_HOME/pardes, else ~/.local/state/pardes. A state file that /// holds no Recent yet reads them once (Db.zig). fn oldRecentDir(arena: std.mem.Allocator, env: *const std.process.Environ.Map) ?[]const u8 { if (env.get("XDG_STATE_HOME")) |base| if (base.len != 0 and std.Io.Dir.path.isAbsolute(base)) return std.Io.Dir.path.join(arena, &.{ base, "pardes" }) catch null; const home = env.get("HOME") orelse return null; if (home.len == 0) return null; return std.Io.Dir.path.join(arena, &.{ home, ".local", "state", "pardes" }) catch null; } test "--wait finds the pane /index names a file by, spaces and all, and sees it gone" { const index = "1 term 0 /home/u 1\n4 text 1 /tmp/a b.txt 2\n"; try std.testing.expectEqual(@as(?u32, 4), paneShowing(index, "/tmp/a b.txt")); try std.testing.expectEqual(@as(?u32, null), paneShowing(index, "/tmp/a")); try std.testing.expect(hasPane(index, 4) and !hasPane(index, 2)); try std.testing.expect(isDel("new 5 /x\ndel 4 /tmp/a b.txt\n", 4)); try std.testing.expect(!isDel("del 41 /x\n", 4) and !isDel("undel 4\n", 4)); } test "cli: docs/typ/command-line.txt is what pardes help --all prints" { if (comptime !ninep_io.supported) return error.SkipZigTest; var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer arena.deinit(); const a = arena.allocator(); const t = try Tree.open(std.testing.io, a, null); defer t.f.close(); var out: std.Io.Writer.Allocating = .init(a); try writeHelpAll(&out.writer, t); var dir = try std.Io.Dir.cwd().openDir(std.testing.io, @import("doc_typ").dir, .{}); defer dir.close(std.testing.io); const committed = try dir.readFileAlloc(std.testing.io, "command-line.txt", a, .limited(1 << 20)); if (!std.mem.eql(u8, committed, out.written())) { std.debug.print("docs/typ/command-line.txt is stale: run `zig build builtins-json -Dplatform=tui --prefix `\n", .{}); return error.StaleCommandLine; } } test "cli: the first screen names every command, and every flag has its help" { var buf: [8192]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try writeFirstScreen(&w); for (std.enums.values(Cmd)) |c| { var name: [32]u8 = undefined; try std.testing.expect(std.mem.indexOf(u8, w.buffered(), try std.fmt.bufPrint(&name, "\n {t}", .{c})) != null); } w = .fixed(&buf); try writeLeaf(&w, .new); for (std.enums.values(Flag)) |f| if (flags.get(f).group != .old) try std.testing.expect(std.mem.indexOf(u8, w.buffered(), @tagName(f)) != null); } test "cli: a /commands line parses into its word" { const w = Word.parse("Wrap root on,off -- Wrap long lines.").?; try std.testing.expectEqualStrings("Wrap", w.name); try std.testing.expect(!w.arg); try std.testing.expectEqualStrings("root", w.scope); try std.testing.expectEqualStrings("on,off", w.choices); try std.testing.expectEqualStrings("Wrap long lines.", w.doc); const e = Word.parse("Edit arg both -- Run sam's Edit.").?; try std.testing.expect(e.arg); try std.testing.expectEqualStrings("both", e.scope); try std.testing.expectEqualStrings("addon", Word.parse("PdfFit arg pane -- Fit. (addon pdf)").?.group()); try std.testing.expectEqual(@as(?Word, null), Word.parse("Lonely")); } test "tcgetattr writes nothing past a Zig termios" { if (comptime !(builtin.os.tag == .linux and builtin.abi.isGnu())) return error.SkipZigTest; const master = std.c.open("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }, @as(std.c.mode_t, 0)); if (master < 0) return error.SkipZigTest; defer _ = std.c.close(master); var s: extern struct { t: std.c.termios, canary: [32]u8 } = .{ .t = undefined, .canary = @splat(0xAA) }; try std.testing.expectEqual(0, std.c.tcgetattr(master, &s.t)); try std.testing.expectEqualSlices(u8, &@as([32]u8, @splat(0xAA)), &s.canary); try std.testing.expectEqual(0, std.c.tcsetattr(master, .NOW, &s.t)); try std.testing.expectEqual(-1, std.c.tcgetattr(-1, &s.t)); } test { _ = pardes.config.User; _ = @import("crash.zig"); _ = @import("memory.zig"); _ = @import("locations.zig"); _ = @import("fs.zig"); _ = @import("wire.zig"); _ = @import("vaxis_input.zig"); _ = @import("daemon.zig"); _ = @import("9p_io.zig"); _ = @import("9p_io.zig").Client; _ = @import("host_io.zig"); _ = @import("host_io.zig").Shell; _ = @import("host_io.zig").Lsp; // Its tests too: imported by the hosts only, it was never collected. _ = @import("file_watch.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("lsp/lsp.zig"); if (comptime pardes.platform == .tui) { _ = @import("tui/tui.zig"); } if (comptime pardes.platform == .gui) _ = @import("gui/gui.zig"); if (comptime pardes.font_picker) _ = @import("fonts.zig"); }