// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Spawning a child process on a pseudo-terminal. //! //! `std.process.spawn` cannot do this. A program that prompts through //! `/dev/tty` -- `ssh`, `sudo`, `passwd` -- needs the terminal to be its //! *controlling* terminal, which means the child has to call `setsid` and then //! claim the terminal with `TIOCSCTTY` between `fork` and `execve`, and the //! standard library offers no hook there. So this does its own fork and exec, //! following the shape of `std.Io.Threaded`'s: everything is allocated before //! the fork, the child makes only system calls, and a close-on-exec pipe //! carries any failure before `execve` back to the parent. //! //! On Linux this makes raw system calls and needs no libc. Other POSIX systems //! go through libc, which they link anyway. const std = @import("std"); const builtin = @import("builtin"); const posix = std.posix; const system = posix.system; const linux = std.os.linux; const Io = std.Io; const Allocator = std.mem.Allocator; const process = std.process; const native_os = builtin.os.tag; const use_libc = builtin.link_libc or native_os != .linux; /// Whether this target can spawn onto a pseudo-terminal at all. pub const supported = switch (native_os) { .windows, .wasi, .emscripten, .freestanding, .other, .uefi => false, else => true, }; /// The size of the terminal the child sees, in character cells. pub const Winsize = struct { rows: u16 = 24, cols: u16 = 80, }; pub const Options = struct { argv: []const []const u8, cwd: ?[]const u8, environ_map: *const process.Environ.Map, window: Winsize, echo: bool, }; pub const Spawned = struct { pid: posix.pid_t, /// The controlling side of the terminal: what the child writes is read /// from here, and what is written here is the child's input. master: Io.File, /// The terminal's end-of-file character (normally `^D`), read from the /// terminal's own settings rather than assumed. eof_char: u8, }; pub const Error = error{ /// The system could not allocate a pseudo-terminal. NoPseudoTerminal, NotATerminal, InputOutput, } || process.SpawnError; /// Where `argv[0]` is looked for when the child's environment has no `PATH`, /// which is the same default `std.process.spawn` uses. const default_PATH = "/usr/local/bin:/bin:/usr/bin"; pub fn spawn(gpa: Allocator, options: Options) Error!Spawned { const master = try openMaster(); errdefer closeFd(master); var name_buffer: [128]u8 = undefined; const slave_path = try slaveName(master, &name_buffer); // Opened here rather than in the child so that the terminal can be set up // before anything runs on it. The child inherits it across the fork and // `dup2`s it into place; close-on-exec takes this copy away at `execve`. const slave = try openZ(slave_path, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }); defer closeFd(slave); var term = posix.tcgetattr(slave) catch |err| switch (err) { error.NotATerminal => return error.NotATerminal, else => |e| return e, }; // Without this everything sent to the child comes back to be matched // against, which is rarely what a script is looking for. term.lflag.ECHO = options.echo; posix.tcsetattr(slave, .NOW, term) catch |err| switch (err) { error.NotATerminal => return error.NotATerminal, error.ProcessOrphaned => return error.Unexpected, else => |e| return e, }; const eof_char = term.cc[@intFromEnum(posix.V.EOF)]; try setWindowSize(slave, options.window); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); // Nothing may be allocated after the fork: the allocator may be libc's, // and a child forked from a threaded process can deadlock in it. const argv = try arena.allocSentinel(?[*:0]const u8, options.argv.len, null); for (options.argv, argv) |arg, *slot| slot.* = (try arena.dupeZ(u8, arg)).ptr; const envp = try options.environ_map.createPosixBlock(arena, .{}); const cwd: ?[*:0]const u8 = if (options.cwd) |cwd| (try arena.dupeZ(u8, cwd)).ptr else null; const PATH = options.environ_map.get("PATH") orelse default_PATH; const err_pipe = try pipe(); defer closeFd(err_pipe[0]); var err_pipe_write_open = true; defer if (err_pipe_write_open) closeFd(err_pipe[1]); const pid = try fork(); if (pid == 0) { defer comptime unreachable; child(slave, cwd, argv, envp.slice.ptr, PATH) catch |err| bail(err_pipe[1], err); unreachable; } closeFd(err_pipe[1]); err_pipe_write_open = false; // Nothing arrives if `execve` succeeded: close-on-exec shuts the pipe // without a word. Otherwise the child has sent its error and exited. var err_int: [@sizeOf(std.meta.Int(.unsigned, @bitSizeOf(anyerror)))]u8 = undefined; const n = readFull(err_pipe[0], &err_int); if (n == err_int.len) { reap(pid); const int = std.mem.readInt(std.meta.Int(.unsigned, @bitSizeOf(anyerror)), &err_int, .little); return @errorCast(@errorFromInt(int)); } return .{ .pid = pid, .master = .{ .handle = master, .flags = .{ .nonblocking = false } }, .eof_char = eof_char, }; } /// Tells the child the terminal has changed size. The kernel sends it /// `SIGWINCH`, as it would for a window being resized. pub fn setWindowSize(fd: posix.fd_t, window: Winsize) (error{NotATerminal} || posix.UnexpectedError)!void { var ws: posix.winsize = .{ .row = window.rows, .col = window.cols, .xpixel = 0, .ypixel = 0 }; switch (ioctl(fd, T.IOCSWINSZ, @intFromPtr(&ws))) { .SUCCESS => {}, .NOTTY => return error.NotATerminal, else => |e| return posix.unexpectedErrno(e), } } /// Everything the child does between `fork` and `execve`. Only system calls: /// no allocation, no locks, no `Io`. fn child( slave: posix.fd_t, cwd: ?[*:0]const u8, argv: [:null]?[*:0]const u8, envp: [*:null]const ?[*:0]const u8, PATH: []const u8, ) Error!void { // A new session has no controlling terminal, which is what lets it take // this one. switch (posix.errno(system.setsid())) { .SUCCESS => {}, .PERM => return error.PermissionDenied, else => return error.Unexpected, } switch (ioctl(slave, T.IOCSCTTY, 0)) { .SUCCESS => {}, .PERM => return error.PermissionDenied, else => return error.Unexpected, } for ([_]posix.fd_t{ posix.STDIN_FILENO, posix.STDOUT_FILENO, posix.STDERR_FILENO }) |target| { while (true) switch (posix.errno(system.dup2(slave, target))) { .SUCCESS => break, .INTR, .BUSY => continue, .MFILE => return error.ProcessFdQuotaExceeded, else => return error.Unexpected, }; } if (cwd) |path| switch (posix.errno(system.chdir(path))) { .SUCCESS => {}, .ACCES => return error.AccessDenied, .NOENT => return error.FileNotFound, .NOTDIR => return error.NotDir, .NAMETOOLONG => return error.NameTooLong, .LOOP => return error.SymLinkLoop, .IO => return error.InputOutput, .NOMEM => return error.SystemResources, else => return error.Unexpected, }; return execvp(argv, envp, PATH); } /// `execve`, searching `PATH` when `argv[0]` has no slash in it. Returns only /// on failure. fn execvp(argv: [:null]?[*:0]const u8, envp: [*:null]const ?[*:0]const u8, PATH: []const u8) Error { const file = std.mem.sliceTo(argv[0].?, 0); if (std.mem.findScalar(u8, file, '/') != null) return execve(argv[0].?, argv.ptr, envp); var path_buffer: [posix.PATH_MAX]u8 = undefined; var it = std.mem.tokenizeScalar(u8, PATH, ':'); var seen_eacces = false; var err: Error = error.FileNotFound; while (it.next()) |dir| { const len = dir.len + 1 + file.len; if (len + 1 > path_buffer.len) return error.NameTooLong; @memcpy(path_buffer[0..dir.len], dir); path_buffer[dir.len] = '/'; @memcpy(path_buffer[dir.len + 1 ..][0..file.len], file); path_buffer[len] = 0; err = execve(path_buffer[0..len :0], argv.ptr, envp); switch (err) { error.AccessDenied => seen_eacces = true, error.FileNotFound, error.NotDir => {}, else => return err, } } return if (seen_eacces) error.AccessDenied else err; } fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) Error { return switch (posix.errno(system.execve(path, argv, envp))) { .SUCCESS => unreachable, .ACCES, .PERM => error.AccessDenied, .NOENT => error.FileNotFound, .NOTDIR => error.NotDir, .NOEXEC => error.InvalidExe, .ISDIR => error.IsDir, .NAMETOOLONG => error.NameTooLong, .LOOP => error.SymLinkLoop, .NOMEM => error.SystemResources, .@"2BIG" => error.SystemResources, .IO => error.InputOutput, .TXTBSY => error.FileBusy, .MFILE => error.ProcessFdQuotaExceeded, .NFILE => error.SystemFdQuotaExceeded, else => error.Unexpected, }; } /// The child's last act on failure: say why, and go. fn bail(fd: posix.fd_t, err: Error) noreturn { var bytes: [@sizeOf(std.meta.Int(.unsigned, @bitSizeOf(anyerror)))]u8 = undefined; std.mem.writeInt(std.meta.Int(.unsigned, @bitSizeOf(anyerror)), &bytes, @intFromError(err), .little); _ = system.write(fd, &bytes, bytes.len); exit(1); } fn exit(code: u8) noreturn { if (use_libc) std.c._exit(code) else linux.exit(code); } fn fork() Error!posix.pid_t { const rc = system.fork(); return switch (posix.errno(rc)) { .SUCCESS => @intCast(rc), .AGAIN, .NOMEM => error.SystemResources, .NOSYS => error.OperationUnsupported, else => error.Unexpected, }; } /// Collects a child that is known to have exited, so that it does not linger /// as a zombie. fn reap(pid: posix.pid_t) void { var status: if (use_libc) c_int else u32 = undefined; while (true) switch (posix.errno(system.waitpid(pid, &status, 0))) { .INTR => continue, else => return, }; } fn pipe() Error![2]posix.fd_t { var fds: [2]posix.fd_t = undefined; const has_pipe2 = @TypeOf(system.pipe2) != void; const rc = if (has_pipe2) system.pipe2(&fds, .{ .CLOEXEC = true }) else system.pipe(&fds); switch (posix.errno(rc)) { .SUCCESS => {}, .MFILE => return error.ProcessFdQuotaExceeded, .NFILE => return error.SystemFdQuotaExceeded, else => return error.Unexpected, } // Darwin has no `pipe2`. Another thread forking between the two calls // would hand its child these descriptors, which is harmless here: the // pipe is only ever read until it closes, and that child's copy closes // when it execs. if (!has_pipe2) for (fds) |fd| { _ = std.c.fcntl(fd, posix.F.SETFD, @as(c_int, posix.FD_CLOEXEC)); }; return fds; } /// Reads until `buffer` is full or the other end closes. Returns how much /// arrived. fn readFull(fd: posix.fd_t, buffer: []u8) usize { var n: usize = 0; while (n < buffer.len) { const rc = system.read(fd, buffer[n..].ptr, buffer.len - n); switch (posix.errno(rc)) { .SUCCESS => { if (rc == 0) return n; n += @intCast(rc); }, .INTR => continue, else => return n, } } return n; } fn closeFd(fd: posix.fd_t) void { _ = system.close(fd); } fn openZ(path: [*:0]const u8, flags: posix.O) Error!posix.fd_t { while (true) { const rc = if (use_libc) std.c.open(path, flags) else linux.open(path, flags, 0); switch (posix.errno(rc)) { .SUCCESS => return @intCast(rc), .INTR => continue, .ACCES, .PERM => return error.AccessDenied, .NOENT, .NXIO, .NODEV => return error.NoPseudoTerminal, .MFILE => return error.ProcessFdQuotaExceeded, .NFILE => return error.SystemFdQuotaExceeded, .NOMEM => return error.SystemResources, else => return error.Unexpected, } } } /// `ioctl`, whose request argument is a `u32` to Linux, an `int` to libc, /// and a value the kernel treats as unsigned either way. fn ioctl(fd: posix.fd_t, comptime request: anytype, arg: usize) posix.E { const bits: u32 = @truncate(@as(u64, request)); if (use_libc) return posix.errno(std.c.ioctl(fd, @as(c_int, @bitCast(bits)), arg)); return posix.errno(linux.ioctl(fd, bits, arg)); } fn openMaster() Error!posix.fd_t { if (!use_libc) { // What glibc's `posix_openpt` does, without needing glibc. const fd = try openZ("/dev/ptmx", .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true }); errdefer closeFd(fd); var unlock: c_int = 0; if (ioctl(fd, linux.T.IOCSPTLCK, @intFromPtr(&unlock)) != .SUCCESS) return error.NoPseudoTerminal; return fd; } const flags: posix.O = .{ .ACCMODE = .RDWR, .NOCTTY = true }; const rc = c.posix_openpt(@bitCast(flags)); if (rc < 0) return error.NoPseudoTerminal; errdefer closeFd(rc); _ = std.c.fcntl(rc, posix.F.SETFD, @as(c_int, posix.FD_CLOEXEC)); if (c.grantpt(rc) != 0 or c.unlockpt(rc) != 0) return error.NoPseudoTerminal; return rc; } fn slaveName(master: posix.fd_t, buffer: []u8) Error![:0]const u8 { if (!use_libc) { var number: c_uint = undefined; if (ioctl(master, linux.T.IOCGPTN, @intFromPtr(&number)) != .SUCCESS) return error.NoPseudoTerminal; return std.fmt.bufPrintZ(buffer, "/dev/pts/{d}", .{number}) catch unreachable; } // Not reentrant, but it is copied out at once, and a program racing // another thread through `ptsname` is rare enough not to be worth a // per-platform `ptsname_r`, which not every one of them has. const name = std.mem.sliceTo(c.ptsname(master) orelse return error.NoPseudoTerminal, 0); if (name.len + 1 > buffer.len) return error.NameTooLong; @memcpy(buffer[0..name.len], name); buffer[name.len] = 0; return buffer[0..name.len :0]; } /// Terminal `ioctl` requests. `std.c.T` has these for everything but Darwin, /// where it declares only `TIOCGWINSZ`; the values there are the BSD ones. const T = if (builtin.os.tag.isDarwin()) struct { pub const IOCSCTTY = 0x20007461; pub const IOCSWINSZ = 0x80087467; } else system.T; /// The POSIX pseudo-terminal calls, which `std.c` does not declare. const c = struct { extern "c" fn posix_openpt(flags: c_int) c_int; extern "c" fn grantpt(fd: c_int) c_int; extern "c" fn unlockpt(fd: c_int) c_int; extern "c" fn ptsname(fd: c_int) ?[*:0]const u8; };