From 250d34c1b942cd6e3726e96f6d80a9cf98d6e20e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 18 Nov 2026 22:34:26 -0300 Subject: dev: host_io.zig into its type files (the reorganisation's tree, step 2e): Host, KindJob, Inbox, Lsp and Shell each a file of its own beside it, their declarations moved as they were (a struct's body is the file's, one indent less), each file importing what it names and host_io.zig naming each (`pub const Shell = @import("Shell.zig")`), so every caller reads as before; Shell's `setenv` is pub, host_io.zig's own code calling it; the tests inside the structs move with them (host_io.Shell.test.* now Shell.test.*); nothing else changes: the ledger, frames byte-identical, replicas and process-test the base's Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- dev/Shell.zig | 731 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 731 insertions(+) create mode 100644 dev/Shell.zig (limited to 'dev/Shell.zig') diff --git a/dev/Shell.zig b/dev/Shell.zig new file mode 100644 index 00000000..f7c0caff --- /dev/null +++ b/dev/Shell.zig @@ -0,0 +1,731 @@ +const builtin = @import("builtin"); +const std = @import("std"); +const libc = std.c; +const pardes = @import("core"); +const ninep_io = @import("runtime").ninep_io; +const host_io = @import("host_io.zig"); +const testUnsetenv = host_io.testUnsetenv; +const writeFd = host_io.writeFd; +const Shell = @This(); + +const X_OK: c_int = 1; + +extern "c" fn mkstemp(template: [*:0]u8) c_int; +pub extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; + +const path_capacity = 4096; +const max_path_files = 64; + +// Repair only the system-only PATH inherited from a macOS GUI launch. +fn adoptSystemPath() void { + if (comptime builtin.os.tag != .macos) return; + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len); + if (len == 0) return; + const system = buf[0..len]; + + const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else ""; + if (!allEntriesWithin(current, system)) return; + if (std.mem.eql(u8, current, system)) return; + + var out: [path_capacity:0]u8 = undefined; + if (len >= out.len) return; + @memcpy(out[0..len], system); + out[len] = 0; + _ = setenv("PATH", out[0..len :0].ptr, 1); +} + +// Run in the parent before forking; children borrow the completed prompt files. +pub fn prepare() PromptFiles { + adoptSystemPath(); + if (comptime builtin.os.tag.isDarwin()) + _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1); + sweepDeadRcs(); + const rcs = PromptFiles.init(); + // A private file goes at a fatal signal too, not only at Exit. + for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| { + const path = owned orelse continue; + @memcpy(fatal_rcs[i][0..path.len], path); + fatal_rcs[i][path.len] = 0; + fatal_rc_len[i] = path.len; + } + ninep_io.fatal_cleanup = unlinkOwnedRcs; + return rcs; +} + +/// This process's private prompt files, where a fatal signal's handler +/// can reach them (unlinkOwnedRcs). +var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined; +var fatal_rc_len: [2]usize = .{ 0, 0 }; + +/// Removes this process's private prompt files. Async-signal-safe (two +/// unlinks): SIGTERM and SIGHUP call it before the signal's death. +pub fn unlinkOwnedRcs() void { + for (&fatal_rc_len, 0..) |*len, i| { + const n = len.*; + if (n == 0) continue; + len.* = 0; + _ = libc.unlink(fatal_rcs[i][0..n :0].ptr); + } +} + +/// Removes /tmp's `pardes-osc133---XXXXXX` files whose pid +/// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed +/// editor left. A live pid's, one of another user's, or a name of +/// another shape is left alone. +fn sweepDeadRcs() void { + const dir = std.c.opendir("/tmp") orelse return; + defer _ = std.c.closedir(dir); + var dead: [64][64]u8 = undefined; + var dead_len: [64]usize = undefined; + var n: usize = 0; + while (std.c.readdir(dir)) |ent| { + const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); + const pid = rcPid(name) orelse continue; + // This pid's are this process's, but in an upgraded one: those + // were its old image's (upgrade.zig), and its own come after. + if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue; + if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; + if (name.len >= 64 or n == dead.len) continue; + @memcpy(dead[n][0..name.len], name); + dead_len[n] = name.len; + n += 1; + } + for (dead[0..n], dead_len[0..n]) |*entry, len| { + var path_buf: [80:0]u8 = undefined; + const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue; + const facts = ninep_io.statNoFollow(path) orelse continue; + if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue; + _ = libc.unlink(path.ptr); + } +} + +/// The pid in `pardes-osc133---XXXXXX`, or null. +fn rcPid(name: []const u8) ?std.c.pid_t { + const head = "pardes-osc133-"; + if (!std.mem.startsWith(u8, name, head)) return null; + var fields = std.mem.splitScalar(u8, name[head.len..], '-'); + _ = fields.next() orelse return null; // the shell + const digits = fields.next() orelse return null; + const rest = fields.next() orelse return null; + if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null; + for (digits) |c| if (!std.ascii.isDigit(c)) return null; + const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null; + return if (pid > 0) pid else null; +} + +fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void { + var file_buf: [path_capacity]u8 = undefined; + if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body); + + const io = std.Io.Threaded.global_single_threaded.io(); + var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return; + defer dir.close(io); + + var names: [max_path_files][256]u8 = undefined; + var name_lens: [max_path_files]usize = undefined; + var count: usize = 0; + var it = dir.iterate(); + while (count < names.len) { + const entry = (it.next(io) catch break) orelse break; + if (entry.kind == .directory) continue; + if (entry.name.len == 0 or entry.name.len > names[count].len) continue; + @memcpy(names[count][0..entry.name.len], entry.name); + name_lens[count] = entry.name.len; + count += 1; + } + var order: [max_path_files]usize = undefined; + for (0..count) |i| order[i] = i; + std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan); + + var path_buf: [512]u8 = undefined; + for (order[0..count]) |i| { + const name = names[i][0..name_lens[i]]; + const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue; + if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body); + } +} + +const Names = struct { + names: *const [max_path_files][256]u8, + lens: *const [max_path_files]usize, + + fn lessThan(self: Names, a: usize, b: usize) bool { + return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt; + } +}; + +fn appendLines(buf: []u8, len: *usize, body: []const u8) void { + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r")); +} + +fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void { + if (entry.len == 0) return; + if (hasEntry(buf[0..len.*], entry)) return; + const separator: usize = if (len.* == 0) 0 else 1; + if (len.* + separator + entry.len > buf.len) return; + if (separator == 1) { + buf[len.*] = ':'; + len.* += 1; + } + @memcpy(buf[len.*..][0..entry.len], entry); + len.* += entry.len; +} + +fn hasEntry(list: []const u8, entry: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, list, ':'); + while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true; + return false; +} + +fn allEntriesWithin(candidate: []const u8, list: []const u8) bool { + var it = std.mem.tokenizeScalar(u8, candidate, ':'); + while (it.next()) |entry| if (!hasEntry(list, entry)) return false; + return true; +} + +fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 { + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var off: usize = 0; + while (off < buf.len) { + const n = libc.read(fd, buf[off..].ptr, buf.len - off); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + return null; + } + if (n == 0) break; + off += @intCast(n); + } + return buf[0..off]; +} + +test "the launchd PATH is replaced and a configured one is left alone" { + var buf: [256]u8 = undefined; + var len: usize = 0; + appendEntry(&buf, &len, "/usr/bin"); + appendEntry(&buf, &len, "/bin"); + appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first + appendEntry(&buf, &len, ""); + try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]); + + try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin")); + try std.testing.expect(allEntriesWithin("", "/usr/bin")); + try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin")); + try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin")); +} + +test "system path files are sorted and duplicate directories keep their first position" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" }); + try tmp.dir.createDirPath(std.testing.io, "paths.d"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" }); + var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)]; + var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0); + var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root}); + var buf: [path_capacity]u8 = undefined; + var len: usize = 0; + collectSystemPath(paths_file, paths_dir, &buf, &len); + try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]); +} + +const Family = enum { bash, fish, none }; + +fn family(bin: []const u8) Family { + const slash = std.mem.lastIndexOfScalar(u8, bin, '/'); + const base = if (slash) |s| bin[s + 1 ..] else bin; + if (std.mem.startsWith(u8, base, "bash")) return .bash; + if (std.mem.startsWith(u8, base, "fish")) return .fish; + return .none; +} + +/// `family`, for a shell whose name does not say it (a renamed copy, a +/// link named otherwise): what it really is, by the name its links end +/// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's +/// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn +/// and only for a name that says nothing; a --version probe would fork. +fn familyOf(path: [*:0]const u8) Family { + const named = family(std.mem.span(path)); + if (named != .none) return named; + // A name a POSIX shell answers to is that shell, whatever the file: + // bash run as `sh` is sh, and reads no --rcfile. + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known| + if (std.mem.eql(u8, base, known)) return .none; + var real: [std.Io.Dir.max_path_bytes]u8 = undefined; + if (libc.realpath(path, &real)) |r| { + const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r)))); + if (by_link != .none) return by_link; + } + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return .none; + defer _ = libc.close(fd); + var chunk: [64 * 1024]u8 = undefined; + var carry: usize = 0; + var total: usize = 0; + while (total < 16 << 20) { + const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry); + if (n <= 0) break; + const have = carry + @as(usize, @intCast(n)); + total += @intCast(n); + // A script is no binary: its interpreter is what runs. + if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none; + if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash; + if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish; + // Keep the tail, so a marker cut by the chunk is still seen. + carry = @min(have, 16); + std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]); + } + return .none; +} + +test "a bash under another name is still told as bash" { + const bash: [:0]const u8 = "/usr/bin/bash"; + if (libc.access(bash, X_OK) != 0) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20)); + defer std.testing.allocator.free(bytes); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200:0]u8 = undefined; + const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0); + try std.testing.expectEqual(Family.bash, familyOf(p.ptr)); + try std.testing.expectEqual(Family.none, familyOf("/bin/sh")); +} + +const bash_rc = + \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc" + \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]' + \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]' + \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}" + \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then + \\ PS0='\e]133;C;aid=pardes\a'"$PS0" + \\else + \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG + \\fi + \\ +; + +// fish -C runs after config.fish; bash --rcfile must source .bashrc itself. +const fish_rc = + \\functions -c fish_prompt __pardes_user_prompt + \\function fish_prompt + \\ printf '\e]133;A;cl=line;aid=pardes\a' + \\ __pardes_user_prompt + \\ printf '\e]133;B;aid=pardes\a' + \\end + \\function __pardes_preexec --on-event fish_preexec + \\ printf '\e]133;C;aid=pardes\a' + \\end + \\function __pardes_postexec --on-event fish_postexec + \\ printf '\e]133;D;%s;aid=pardes\a' $status + \\end + \\ +; + +const rc_path_capacity = 256; + +/// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR +/// (private to the user) there is one file per content, named by its +/// hash and shared by every pardes, so none is left behind by a pardes +/// that was killed: 72K of them piled up in /tmp when each host wrote +/// its own. Without that directory each host writes private mkstemp +/// files in /tmp and removes them at teardown, as before. +pub const PromptFiles = struct { + bash_path: [rc_path_capacity:0]u8 = @splat(0), + bash_len: u16 = 0, + bash_owned: bool = false, + fish_path: [rc_path_capacity:0]u8 = @splat(0), + fish_len: u16 = 0, + fish_owned: bool = false, + fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0), + fish_command_len: u16 = 0, + + pub fn init() PromptFiles { + var rcs: PromptFiles = .{}; + const bash = place(&rcs.bash_path, "bash", bash_rc); + rcs.bash_len = bash.len; + rcs.bash_owned = bash.owned; + const fish = place(&rcs.fish_path, "fish", fish_rc); + rcs.fish_len = fish.len; + rcs.fish_owned = fish.owned; + if (rcs.fishPath()) |path| { + // Quoted for fish; a path a quote would break is not used. + const command = if (std.mem.indexOfAny(u8, path, "'\\") != null) + error.NoSpaceLeft + else + std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0); + const ok = command catch { + if (rcs.fish_owned) _ = libc.unlink(path.ptr); + rcs.fish_len = 0; + return rcs; + }; + rcs.fish_command_len = @intCast(ok.len); + } + return rcs; + } + + pub fn deinit(rcs: *PromptFiles) void { + // Removed here, not again by a signal's handler. + for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| { + if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) { + len.* = 0; + }; + }; + if (rcs.bashPath()) |path| if (rcs.bash_owned) { + _ = libc.unlink(path.ptr); + }; + if (rcs.fishPath()) |path| if (rcs.fish_owned) { + _ = libc.unlink(path.ptr); + }; + rcs.bash_len = 0; + rcs.fish_len = 0; + rcs.fish_command_len = 0; + } + + fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.bash_len == 0) return null; + return rcs.bash_path[0..rcs.bash_len :0]; + } + + fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_len == 0) return null; + return rcs.fish_path[0..rcs.fish_len :0]; + } + + fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 { + if (rcs.fish_command_len == 0) return null; + return rcs.fish_command[0..rcs.fish_command_len :0]; + } +}; + +/// The shared file for `contents` under $XDG_RUNTIME_DIR, written +/// beside it and renamed into place when missing or different, so a +/// shell never reads half of one; failing that, a private /tmp file. +fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } { + shared: { + const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared); + if (dir.len == 0 or dir[0] != '/') break :shared; + const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared; + var have: [2048]u8 = undefined; + if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false }; + var tmp_buf: [rc_path_capacity:0]u8 = @splat(0); + var template_buf: [rc_path_capacity]u8 = undefined; + const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared; + const n = stage(&tmp_buf, tmp_template, contents); + if (n == 0) break :shared; + if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) { + _ = libc.unlink(tmp_buf[0..n :0].ptr); + break :shared; + } + return .{ .len = @intCast(final.len), .owned = false }; + } + var tmp_template: [64]u8 = undefined; + // Its pid in the name: one a killed editor left is swept by the + // next (sweepDeadRcs). + const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false }; + return .{ .len = stage(path_buf, template, contents), .owned = true }; +} + +// Publish a path only after its private 0600 file is fully written and closed. +fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 { + const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0; + const fd = mkstemp(path.ptr); + if (fd < 0) return 0; + if (!writeFd(fd, contents)) { + _ = libc.close(fd); + _ = libc.unlink(path.ptr); + return 0; + } + if (libc.close(fd) != 0) { + _ = libc.unlink(path.ptr); + return 0; + } + return @intCast(path.len); +} + +test "shell family is the basename's prefix, and anything else runs unadorned" { + try std.testing.expectEqual(Family.fish, family("fish")); + try std.testing.expectEqual(Family.fish, family("/usr/bin/fish")); + try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish")); + try std.testing.expectEqual(Family.bash, family("bash")); + try std.testing.expectEqual(Family.bash, family("/bin/bash")); + try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2")); + try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7")); + try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu")); + try std.testing.expectEqual(Family.none, family("/usr/bin/zsh")); + try std.testing.expectEqual(Family.none, family("/bin/sh")); + try std.testing.expectEqual(Family.none, family("nu")); + try std.testing.expectEqual(Family.none, family("")); +} + +const bin_dirs = [_][]const u8{ + "/usr/bin/", + "/bin/", + "/usr/local/bin/", + "/opt/homebrew/bin/", + "/opt/local/bin/", + "/usr/sbin/", +}; + +const fallbacks = [_][]const u8{ + if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash", + "/bin/sh", +}; + +pub const Spawn = struct { + path: [*:0]const u8, + argv: [6:null]?[*:0]const u8, +}; + +// Resolve in the parent. The path buffer and prompt files must survive through exec. +pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn { + const path = find(bin, buf) orelse fallback(buf); + const marks: [2]?[*:0]const u8 = switch (familyOf(path)) { + .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null }, + .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null }, + .none => .{ null, null }, + }; + return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } }; +} + +/// A command pane's shell runs its one line with job control on, so a +/// job the line puts in the background has a process group of its own. +/// The shell leads the terminal's session, and when it exits the kernel +/// hangs up the terminal's foreground group: with job control off that +/// is the shell's own, the job's too, and the job died with the command +/// (nohup'd or not; only setsid got out, and not always in time). A +/// shell pardes does not know runs the line as it is. +pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 { + const bin = std.mem.span(path); + const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin; + const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" }; + for (posix_shells) |name| if (std.mem.eql(u8, base, name)) + return .{ path, "-m", "-c", line, null, null }; + if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null }; + return .{ path, "-c", line, null, null, null }; +} + +/// A shell by its path or its name in the usual directories, or null. +/// A path may be under a mount this editor serves: the turn goes out +/// with the lookups (pardes.Turn.yield). +pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 { + if (bin.len == 0 or bin.len + 1 > buf.len) return null; + pardes.turn.yield(); + defer pardes.turn.back(); + if (std.mem.indexOfScalar(u8, bin, '/') != null) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null; + } + for (bin_dirs) |dir| { + if (dir.len + bin.len + 1 > buf.len) continue; + @memcpy(buf[0..dir.len], dir); + @memcpy(buf[dir.len..][0..bin.len], bin); + buf[dir.len + bin.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return null; +} + +/// A directory passes access(X_OK) (it can be searched): no shell. +pub fn isDirectory(path: [*:0]const u8) bool { + const d = libc.opendir(path) orelse return false; + _ = libc.closedir(d); + return true; +} + +/// Why `bin` is no shell, for the words that name one (Term, Shell); +/// null when it is one. +pub fn refusal(bin: []const u8, said: []u8) ?[]const u8 { + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + if (find(bin, &buf)) |found| { + // A script whose `#!` names a program that is not there: its + // exec fails ENOENT as a missing shell's does, so told apart. + var interp: [256]u8 = undefined; + const missing = missingInterpreter(found, &interp) orelse return null; + return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found"; + } + if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) { + @memcpy(buf[0..bin.len], bin); + buf[bin.len] = 0; + if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory"; + // There, but no program: said so, not "not found". + if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable"; + } + // "not found": the words a mount reads as ENOENT. + return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell"; +} + +/// The program a script's `#!` line names, when it is not there to +/// run; null for a script whose interpreter is there, or no script. +pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 { + pardes.turn.yield(); + defer pardes.turn.back(); + const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0)); + if (fd < 0) return null; + defer _ = libc.close(fd); + var head: [256]u8 = undefined; + const n = libc.read(fd, &head, head.len); + if (n < 2) return null; + const got = head[0..@intCast(n)]; + if (!std.mem.startsWith(u8, got, "#!")) return null; + const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len]; + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const interp = words.next() orelse return null; + if (interp.len + 1 > out.len) return null; + @memcpy(out[0..interp.len], interp); + out[interp.len] = 0; + if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null; + return out[0..interp.len]; +} + +test "a script whose #! names a program not there is told apart from a missing shell" { + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } }); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path: [4200]u8 = undefined; + var said: [320]u8 = undefined; + try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?); + try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null); + try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \"")); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" }); + const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir}); + try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable")); +} + +fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 { + for (fallbacks) |f| { + @memcpy(buf[0..f.len], f); + buf[f.len] = 0; + const p: [*:0]const u8 = @ptrCast(buf); + if (libc.access(p, X_OK) == 0) return p; + } + return @ptrCast(buf); +} + +test "a command pane's line runs with job control on in the shells that have it" { + const want = struct { + fn check(path: [*:0]const u8, words: []const []const u8) !void { + const argv = commandArgv(path, "sleep 9 &"); + for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?)); + try std.testing.expect(argv[words.len] == null); + } + }; + try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" }); + try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" }); + try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" }); + try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" }); +} + +test "a path is taken at its word, a name is looked up, and both pick their own marks" { + if (builtin.os.tag == .windows) return; + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + var prompt_rcs = PromptFiles.init(); + defer prompt_rcs.deinit(); + + const sh = resolve("/bin/sh", &buf, &prompt_rcs); + try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path)); + try std.testing.expect(sh.argv[1] == null); + + const bash = resolve("bash", &buf, &prompt_rcs); + try std.testing.expect(family(std.mem.span(bash.path)) == .bash); + try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?)); + try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?)); + + const missing = resolve("zznosuchshell", &buf, &prompt_rcs); + try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path))); + try std.testing.expect(libc.access(missing.path, X_OK) == 0); + + const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs); + try std.testing.expect(libc.access(gone.path, X_OK) == 0); +} + +test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" { + if (builtin.os.tag == .windows) return; + const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf"; + var live_buf: [80:0]u8 = undefined; + const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0); + defer for ([_][:0]const u8{ dead, live }) |path| { + _ = libc.unlink(path.ptr); + }; + for ([_][:0]const u8{ dead, live }) |path| { + const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600)); + if (fd < 0) return error.SkipZigTest; + _ = libc.close(fd); + } + sweepDeadRcs(); + try std.testing.expect(libc.access(dead, 0) < 0); + try std.testing.expect(libc.access(live, 0) == 0); + // The pid is read only from that shape: an older name has none. + try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq")); + try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK")); +} + +test "prompt files are one per content under the runtime dir, or private and cleaned up without it" { + if (builtin.os.tag == .windows) return; + var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0); + const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf); + _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1); + + // Shared: the same file for every owner, left in place, rewritten + // whole when what is there is not its content. + var a = PromptFiles.init(); + var b = PromptFiles.init(); + const a_bash = a.bashPath() orelse return error.TempCreateFailed; + try std.testing.expectEqualStrings(a_bash, b.bashPath().?); + try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len])); + const fish_command = a.fishCommand() orelse return error.MissingFishCommand; + var want: [rc_path_capacity + 16]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command); + var buf: [2048]u8 = undefined; + try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed); + try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed); + const stat = try @import("core").filesystem.statPath(std.testing.io, a_bash, .{}); + try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077); + var kept: [rc_path_capacity:0]u8 = @splat(0); + @memcpy(kept[0..a_bash.len], a_bash); + a.deinit(); + b.deinit(); + try std.testing.expect(libc.access(&kept, 0) == 0); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" }); + var c = PromptFiles.init(); + defer c.deinit(); + try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); + + // No runtime dir: private files, one per owner, gone at teardown. + _ = testUnsetenv("XDG_RUNTIME_DIR"); + var d = PromptFiles.init(); + var e = PromptFiles.init(); + defer e.deinit(); + const d_bash = d.bashPath() orelse return error.TempCreateFailed; + try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?)); + try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-")); + try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash))); + @memcpy(kept[0..d_bash.len], d_bash); + kept[d_bash.len] = 0; + d.deinit(); + try std.testing.expect(libc.access(&kept, 0) < 0); +} -- cgit v1.3