// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One spawned child process, and what it has said that nobody has yet //! matched. //! //! Output is kept in a buffer the caller supplies and the session never //! grows: `expect` reads into it, searches what it holds, and when a pattern //! matches hands back the text up to the end of the match. That text stays //! where it is until the next call that reads or discards, which drops it. //! Everything after the match is kept for the next `expect`, so output that //! arrives in one read and answers two questions is not lost. const Session = @This(); const std = @import("std"); const builtin = @import("builtin"); const zregex = @import("zregex"); const pty = @import("pty.zig"); const posix = std.posix; const Io = std.Io; const Allocator = std.mem.Allocator; const process = std.process; io: Io, /// Scratch space for the regular expression engines, and the capture groups /// each `Result` carries. gpa: Allocator, buffer: []u8, /// `buffer[start..end]` is output nobody has consumed yet. start: usize, end: usize, /// How much at the front of the live region the last `Result` covers. Kept /// until the next call so that the result's text stays valid until then. consumed: usize, /// The streams output is read from: the pseudo-terminal alone, or the pipes /// to standard output and standard error. A stream that has reached its end /// is null here, though it may still be open for writing or waiting on. sources: [2]?Io.File, backend: Backend, const Backend = union(Transport) { pty: struct { /// For `wait` and `kill` only. It holds no streams: the terminal is /// the child's input and output both, and is `master` here. child: process.Child, master: Io.File, eof_char: u8, }, pipe: process.Child, }; /// How the child is connected. pub const Transport = enum { /// A pseudo-terminal that is the child's controlling terminal, as /// classic `expect` does it. Programs behave as they would for a person: /// output is line-buffered rather than held in a block, and prompts that /// read `/dev/tty` -- `ssh`, `sudo`, `passwd` -- work. Standard output and /// standard error arrive interleaved as the child wrote them. POSIX only. pty, /// Plain pipes to standard input, output and error, through /// `std.process.spawn`. Portable, including to Windows, but many programs /// buffer their output when it is not a terminal and some refuse to read /// a password from anything else. pipe, }; pub const Winsize = pty.Winsize; pub const Options = struct { argv: []const []const u8, /// The child's environment. Zig 0.16 hands the environment to `main` /// rather than keeping it in a global, so pass `init.environ_map` to /// inherit it. `argv[0]` is looked up in this map's `PATH`, when it has no /// slash in it. environ_map: *const process.Environ.Map, transport: Transport = if (pty.supported) .pty else .pipe, cwd: ?[]const u8 = null, /// The terminal size the child sees. `.pty` only. window: Winsize = .{}, /// Whether the terminal echoes what is sent. Off by default, so that the /// input a script sends does not come back to be matched against. /// `.pty` only; a pipe never echoes. echo: bool = false, /// Whether standard error is read and searched along with standard /// output, or left connected to the parent's. `.pipe` only; on a terminal /// the two are one stream already. merge_stderr: bool = true, }; pub const SpawnError = pty.Error || Allocator.Error; /// Starts `options.argv[0]`. `buffer` holds its output until it is matched, /// and bounds how much unmatched output there can be; see /// `error.BufferFull`. It must outlive the session. pub fn spawn(io: Io, gpa: Allocator, buffer: []u8, options: Options) SpawnError!Session { std.debug.assert(buffer.len > 0); var session: Session = .{ .io = io, .gpa = gpa, .buffer = buffer, .start = 0, .end = 0, .consumed = 0, .sources = .{ null, null }, .backend = undefined, }; switch (options.transport) { .pty => if (!pty.supported) return error.OperationUnsupported else { const spawned = try pty.spawn(gpa, .{ .argv = options.argv, .cwd = options.cwd, .environ_map = options.environ_map, .window = options.window, .echo = options.echo, }); session.backend = .{ .pty = .{ .child = .{ .id = spawned.pid, .thread_handle = {}, .stdin = null, .stdout = null, .stderr = null, .request_resource_usage_statistics = false, }, .master = spawned.master, .eof_char = spawned.eof_char, } }; session.sources[0] = spawned.master; }, .pipe => { const child = try process.spawn(io, .{ .argv = options.argv, .cwd = if (options.cwd) |cwd| .{ .path = cwd } else .inherit, .environ_map = options.environ_map, .stdin = .pipe, .stdout = .pipe, .stderr = if (options.merge_stderr) .pipe else .inherit, }); session.backend = .{ .pipe = child }; session.sources = .{ child.stdout, child.stderr }; }, } return session; } /// Kills the child if it is still running, collects it, and closes /// everything. Output that was never matched is discarded. pub fn deinit(session: *Session) void { session.kill(); switch (session.backend) { .pty => |*p| p.master.close(session.io), .pipe => {}, } session.* = undefined; } /// A regular expression to look for, and what to call it when it is found. pub fn Pattern(comptime Tag: type) type { return struct { tag: Tag, regex: *const zregex.Regex, }; } /// What `expect` found. pub fn Result(comptime Tag: type) type { return struct { const Self = @This(); /// The tag of the pattern that matched. tag: Tag, /// Where the match and its capture groups are. Every span is an index /// into `text`. match: zregex.Match, /// The output from where the last match ended up to the end of this /// one. Points into the session's buffer, so it is valid only until /// the next call that reads or discards. text: []const u8, /// Capture group `i` as text, or null if it did not take part in the /// match. Group 0 is the whole match. pub fn group(result: Self, i: usize) ?[]const u8 { const span = result.match.group(i) orelse return null; return span.slice(result.text); } /// The output that came before the match. pub fn before(result: Self) []const u8 { return result.text[0..result.match.span().start]; } pub fn deinit(result: *Self, gpa: Allocator) void { result.match.deinit(gpa); result.* = undefined; } }; } pub const ReadError = Io.Operation.FileReadStreaming.UnendingError; pub const ExpectError = error{ /// The deadline passed and none of the patterns had matched. Timeout, /// The child closed its output -- usually by exiting -- and none of the /// patterns matched what it had said. `wait` gives its exit status. EndOfStream, /// The buffer is full of output none of the patterns match. `pending` /// shows it and `discard` makes room. BufferFull, } || zregex.RunError || ReadError || Io.Batch.AwaitConcurrentError; /// Waits until one of `patterns` matches the child's output, and says which. /// /// Patterns are tried in the order given, each against everything not yet /// consumed, and the first that matches wins -- which is not necessarily the /// one matching earliest in the output. Output already buffered is searched /// before anything is read, so nothing that arrived during an earlier call is /// missed. /// /// `timeout` covers the whole call, not each read: a child that keeps /// printing things nobody is waiting for does not keep it waiting longer. /// `.none` waits for as long as it takes. /// /// The caller owns the result's `match` and frees it with `Result.deinit`. pub fn expect( session: *Session, comptime Tag: type, patterns: []const Pattern(Tag), timeout: Io.Timeout, ) ExpectError!Result(Tag) { session.dropConsumed(); const deadline = timeout.toDeadline(session.io); var fresh = true; while (true) { if (fresh) { if (try session.search(Tag, patterns)) |result| return result; } if (session.atEnd()) return error.EndOfStream; if (session.end == session.buffer.len) { if (session.start == 0) return error.BufferFull; session.compact(); } fresh = session.fill(deadline) catch |err| switch (err) { // Waiting may end a little early -- `poll` counts whole // milliseconds and rounds down -- so the clock has the last word. error.Timeout => if (stillTime(session.io, deadline)) false else return err, else => |e| return e, }; } } fn stillTime(io: Io, deadline: Io.Timeout) bool { const remaining = deadline.toDurationFromNow(io) orelse return true; return remaining.raw.nanoseconds > 0; } fn search(session: *Session, comptime Tag: type, patterns: []const Pattern(Tag)) zregex.RunError!?Result(Tag) { const live = session.buffer[session.start..session.end]; for (patterns) |pattern| { const match = try pattern.regex.find(session.gpa, live) orelse continue; const end = match.span().end; session.consumed = end; return .{ .tag = pattern.tag, .match = match, .text = live[0..end] }; } return null; } /// Reads whatever the child says next into the free end of the buffer. /// Returns whether anything arrived; nothing does when a stream has just /// ended, or when a read returns empty-handed. fn fill(session: *Session, deadline: Io.Timeout) (ReadError || Io.Batch.AwaitConcurrentError)!bool { const io = session.io; const free = session.buffer[session.end..]; // Both streams read straight into the caller's buffer, into halves of // what is free, so that nothing is held anywhere else. What the second // brings is moved down to follow the first's afterwards. const both = session.sources[0] != null and session.sources[1] != null and free.len >= 2; const split = if (both) free.len / 2 else free.len; const offsets: [2]usize = if (both) .{ 0, split } else .{ 0, 0 }; var slices: [2][1][]u8 = if (both) .{ .{free[0..split]}, .{free[split..]} } else .{ .{free}, .{free} }; var storage: [2]Io.Operation.Storage = undefined; var batch: Io.Batch = .init(&storage); for (session.sources, &slices, 0..) |source, *data, i| { const file = source orelse continue; batch.addAt(@intCast(i), .{ .file_read_streaming = .{ .file = file, .data = data } }); // With room for only one read, the first stream gets it. if (!both) break; } const waited = batch.awaitConcurrent(io, deadline); // Whichever read did not finish is abandoned rather than left to land in // the buffer later. One may complete regardless, and is collected below. batch.cancel(io); var got: [2]usize = .{ 0, 0 }; var read_error: ?ReadError = null; while (batch.next()) |completion| { const i = completion.index; got[i] = completion.result.file_read_streaming catch |err| switch (err) { error.EndOfStream => { session.sources[i] = null; continue; }, // Linux says this, rather than end of file, when the last holder // of the other side of a terminal -- the child -- has gone. error.InputOutput => if (session.backend == .pty) { session.sources[i] = null; continue; } else { read_error = error.InputOutput; continue; }, else => |e| { read_error = e; continue; }, }; } for (offsets, got) |offset, n| { if (n == 0) continue; std.mem.copyForwards(u8, session.buffer[session.end..], free[offset..][0..n]); session.end += n; } const arrived = got[0] + got[1] > 0; if (read_error) |err| if (!arrived) return err; waited catch |err| switch (err) { error.Timeout => if (!arrived) return err, else => |e| return e, }; return arrived; } fn atEnd(session: *const Session) bool { return session.sources[0] == null and session.sources[1] == null; } fn dropConsumed(session: *Session) void { session.start += session.consumed; session.consumed = 0; if (session.start == session.end) { session.start = 0; session.end = 0; } } fn compact(session: *Session) void { const live = session.end - session.start; std.mem.copyForwards(u8, session.buffer[0..live], session.buffer[session.start..session.end]); session.start = 0; session.end = live; } /// Output that no `expect` has consumed yet: everything after the end of the /// last match. pub fn pending(session: *const Session) []const u8 { return session.buffer[session.start + session.consumed .. session.end]; } /// Throws away the first `n` bytes of `pending`. How to make room after /// `error.BufferFull`. pub fn discard(session: *Session, n: usize) void { session.dropConsumed(); std.debug.assert(n <= session.end - session.start); session.start += n; session.consumed = 0; if (session.start == session.end) { session.start = 0; session.end = 0; } } pub const SendError = error{ /// Input has been closed with `sendEof` on a pipe. InputClosed, } || Io.File.Writer.Error; /// Writes `bytes` to the child's input, exactly as given. pub fn send(session: *Session, bytes: []const u8) SendError!void { const file = switch (session.backend) { .pty => |p| p.master, .pipe => |child| child.stdin orelse return error.InputClosed, }; try file.writeStreamingAll(session.io, bytes); } /// Writes `line` and the end of a line: a carriage return on a terminal, /// which is what the Enter key sends and what the terminal turns into a /// newline, and a newline on a pipe. pub fn sendLine(session: *Session, line: []const u8) SendError!void { try session.send(line); try session.send(switch (session.backend) { .pty => "\r", .pipe => "\n", }); } /// Tells the child there is no more input. On a terminal this sends the /// end-of-file character, which ends input only at the start of a line; on a /// pipe it closes the child's standard input, after which `send` fails. pub fn sendEof(session: *Session) SendError!void { switch (session.backend) { .pty => |p| try session.send(&.{p.eof_char}), .pipe => |*child| if (child.stdin) |stdin| { stdin.close(session.io); child.stdin = null; }, } } pub const SignalError = error{ /// The child has already been collected by `wait` or `kill`. NotRunning, PermissionDenied, } || posix.UnexpectedError; /// Sends `sig` to the child. POSIX only. pub fn sendSignal(session: *Session, sig: posix.SIG) SignalError!void { const pid = session.childProcess().id orelse return error.NotRunning; posix.kill(pid, sig) catch |err| switch (err) { error.ProcessNotFound => return error.NotRunning, else => |e| return e, }; } /// Changes the size of the child's terminal, which sends it `SIGWINCH`. /// `.pty` only. pub fn setWindowSize(session: *Session, window: Winsize) (error{NotATerminal} || posix.UnexpectedError)!void { switch (session.backend) { .pty => |p| if (pty.supported) try pty.setWindowSize(p.master.handle, window) else unreachable, .pipe => return error.NotATerminal, } } /// Whether the child is still to be collected by `wait` or `kill`. pub fn isRunning(session: *Session) bool { return session.childProcess().id != null; } /// Waits for the child to exit and collects its status. Output it wrote /// before exiting is still there for `expect` and `pending`. /// /// Wait for `error.EndOfStream` first when the child's output is a pipe: a /// child blocked writing to a full pipe never exits while nobody reads it. pub fn wait(session: *Session) process.Child.WaitError!process.Child.Term { const c = session.childProcess(); std.debug.assert(c.id != null); // `std.process.Child.wait` closes the pipes it holds, which must not then // be read. if (session.backend == .pipe) session.sources = .{ null, null }; return c.wait(session.io); } /// Kills the child and collects it; nothing if it has already been /// collected. `SIGKILL` on POSIX rather than the `SIGTERM` of /// `std.process.Child.kill`, because an interactive shell -- the commonest /// thing to drive through a terminal -- ignores `SIGTERM`, and waiting on it /// would never return. pub fn kill(session: *Session) void { const c = session.childProcess(); if (c.id == null) return; if (builtin.os.tag == .windows) { c.kill(session.io); } else { posix.kill(c.id.?, .KILL) catch {}; _ = c.wait(session.io) catch {}; } if (session.backend == .pipe) session.sources = .{ null, null }; } fn childProcess(session: *Session) *process.Child { return switch (session.backend) { .pty => |*p| &p.child, .pipe => |*c| c, }; }