Skip to main content

ai6_terminal_pty/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `ai6-terminal-pty`: the `pty` terminal provider, on `portable-pty`, which is
6//! `openpty` on Unix and ConPTY on Windows. The run logic is shared; what differs
7//! per platform (owning the child's process tree, the terminal's mode, translating input) is
8//! in `unix.rs` and `windows.rs` behind one `os` interface.
9//!
10//! Output is read on a thread into a channel, so `read` can time out: a blocking
11//! master read is not reliably interrupted by killing the child. The child's exit
12//! is asked of the child itself, never inferred from EOF, because a pseudo-console
13//! can stay readable after its program has exited. For the same reason the end of the
14//! output is not left to the master: once the child has exited and nothing more has arrived
15//! for 200 ms, `read` reports it.
16//!
17//! On Windows the reading thread also removes cursor position queries (`ESC[6n`) from the
18//! output, and another thread answers them, so the reader never waits on the writer. ConPTY
19//! sends one before its program's first output and holds that output until it is answered
20//! (`portable-pty` creates every pseudo-console with `PSEUDOCONSOLE_INHERIT_CURSOR`), and
21//! nothing else is there to answer it. On Unix queries pass through, for whoever reads.
22
23#![doc = include_str!("../README.md")]
24
25ai6::guatiao::providers!(Pty);
26
27#[cfg(unix)]
28#[path = "unix.rs"]
29mod os;
30#[cfg(windows)]
31#[path = "windows.rs"]
32mod os;
33
34use std::io::{Read, Write};
35use std::sync::atomic::{AtomicBool, Ordering};
36use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
37use std::sync::{Arc, Mutex};
38use std::time::{Duration, Instant};
39
40use ai6::directorates::q::terminal::{ExitInfo, READ_TIMED_OUT, Spec, Terminal, TerminalRun};
41use ai6::guatiao::library::{Object, ProviderError};
42use ai6::guatiao::{FromValue, Schema, Status, ToValue, Value};
43use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
44
45use os::ProcessTree;
46
47const EXIT_POLL: Duration = Duration::from_millis(10);
48/// How often a waiting `read` asks whether the child has exited.
49const EXIT_CHECK: Duration = Duration::from_millis(50);
50/// ConPTY takes rows and columns as signed 16-bit numbers.
51const MAX_DIMENSION: u16 = i16::MAX as u16;
52/// A cursor position query (DSR 6).
53#[cfg(any(windows, test))]
54const CURSOR_QUERY: &[u8] = b"\x1b[6n";
55/// The answer to [`CURSOR_QUERY`]: row 1, column 1, where a fresh terminal's cursor is.
56#[cfg(windows)]
57const CURSOR_REPORT: &[u8] = b"\x1b[1;1R";
58
59/// `pty` provider configuration; every field has a default.
60#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
61#[map(crate = ::ai6::guatiao)]
62pub struct PtyConfig {
63    /// Bytes of one read of the program's output. At least 1. Default 65536.
64    #[map(default = 65536)]
65    pub read_chunk_bytes: u64,
66    /// Milliseconds the output must stay quiet after the program has exited before `read`
67    /// reports its end: ConPTY can deliver the last of a program's output after the program has
68    /// exited, and keeps the output open until the pseudo-console is closed. Default 200.
69    #[map(default = 200)]
70    pub drain_quiet_ms: u64,
71    /// Milliseconds `kill` waits for the program and its process tree to have exited. Default
72    /// 2000.
73    #[map(default = 2_000)]
74    pub kill_wait_ms: u64,
75    /// How many times the process table is read again for processes started meanwhile when a
76    /// tree is adopted (Windows) or killed (Unix). Default 8 on Windows and 32 elsewhere.
77    #[map(default = DEFAULT_TREE_SCANS)]
78    pub tree_scans: u64,
79    /// Lets a Station that runs as root start programs as root: the operator's weakening, which the
80    /// startup log names. A terminal cannot drop privileges for a program (the pseudo-terminal
81    /// library offers no hook between fork and exec), so a Station that runs as root either allows
82    /// it here or starts harnesses on the `pipe` terminal with `run_as`. Default false.
83    #[map(default = false)]
84    pub allow_root: bool,
85}
86
87/// The default of [`PtyConfig::tree_scans`].
88const DEFAULT_TREE_SCANS: u64 = if cfg!(windows) { 8 } else { 32 };
89
90impl Default for PtyConfig {
91    fn default() -> Self {
92        Self {
93            read_chunk_bytes: 65536,
94            drain_quiet_ms: 200,
95            kill_wait_ms: 2_000,
96            tree_scans: DEFAULT_TREE_SCANS,
97            allow_root: false,
98        }
99    }
100}
101
102/// Starts programs on a pseudo-terminal.
103#[derive(Debug, Clone, Default, ai6::guatiao::Provider)]
104#[provider(
105    Terminal,
106    id = "pty",
107    name = "pty",
108    crate = ::ai6::guatiao,
109    config = PtyConfig
110)]
111pub struct Pty {
112    config: PtyConfig,
113}
114
115impl Pty {
116    /// A provider with `config`.
117    pub fn new(config: PtyConfig) -> Self {
118        if config.allow_root {
119            eprintln!(
120                "ai6: terminal provider pty: allow_root = true: a Station that runs as root starts \
121                 harnesses as root"
122            );
123        }
124        Self { config }
125    }
126}
127
128impl TryFrom<PtyConfig> for Pty {
129    type Error = ProviderError;
130
131    fn try_from(config: PtyConfig) -> Result<Self, Self::Error> {
132        if config.read_chunk_bytes == 0 {
133            return Err(refuse(
134                Status::GUATIAO_ERR_BAD_VALUE,
135                "read_chunk_bytes is 0: a read of no bytes never sees any output",
136            ));
137        }
138        Ok(Self::new(config))
139    }
140}
141
142impl Terminal for Pty {
143    fn spawn(&self, spec: &Value) -> Result<Object<dyn TerminalRun>, ProviderError> {
144        let spec = Spec::from_value(spec).map_err(|e| refuse(Status::GUATIAO_ERR_BAD_VALUE, e))?;
145        os::refuse_root(self.config.allow_root)
146            .map_err(|reason| refuse(Status::GUATIAO_ERR_BAD_VALUE, reason))?;
147        Ok(PtyRun::start(&spec, &self.config)?.into_object())
148    }
149}
150
151/// Held while a terminal is opened and its program started.
152static STARTING: Mutex<()> = Mutex::new(());
153
154struct PtyRun {
155    pid: i64,
156    chunks: Mutex<Receiver<Vec<u8>>>,
157    /// The part of a chunk that did not fit the caller's buffer.
158    pending: Mutex<Vec<u8>>,
159    eof: AtomicBool,
160    /// Since when the child has been seen exited with no output arriving.
161    quiet_since: Mutex<Option<Instant>>,
162    writer: Arc<Mutex<Box<dyn Write + Send>>>,
163    master: Mutex<Box<dyn MasterPty + Send>>,
164    child: Mutex<Box<dyn Child + Send + Sync>>,
165    tree: ProcessTree,
166    exit: Mutex<Option<ExitInfo>>,
167    /// Ends the thread that started the program when the run is dropped.
168    _starter: std::sync::mpsc::Sender<()>,
169    /// How long the output must stay quiet after the child has exited, and how long `kill`
170    /// waits for it to have gone.
171    drain_quiet: Duration,
172    kill_wait: Duration,
173}
174
175impl PtyRun {
176    fn start(spec: &Spec, config: &PtyConfig) -> Result<Self, ProviderError> {
177        let read_chunk = usize::try_from(config.read_chunk_bytes).unwrap_or(usize::MAX);
178        let (program, args) = spec
179            .argv
180            .split_first()
181            .ok_or_else(|| refuse(Status::GUATIAO_ERR_BAD_VALUE, "argv is empty"))?;
182        // Opening a terminal and forking the program that holds it are one step across the
183        // process: FreeBSD fails either (`EPERM`, `EISDIR`) when two threads do it at once.
184        let starting = lock(&STARTING)?;
185        let pair = native_pty_system()
186            .openpty(size(spec.rows, spec.cols))
187            .map_err(internal)?;
188        os::set_terminal_mode(&*pair.master).map_err(internal)?;
189        let mut cmd = CommandBuilder::new(program);
190        cmd.args(args);
191        if let Some(env) = &spec.env {
192            cmd.env_clear();
193            for (k, v) in env {
194                cmd.env(k, v);
195            }
196        }
197        if cmd.get_env("TERM").is_none() {
198            cmd.env("TERM", "xterm-256color");
199        }
200        if let Some(dir) = &spec.cwd {
201            cmd.cwd(dir);
202        }
203        // A program may ask to be signalled when the thread that started it ends (Linux's
204        // PR_SET_PDEATHSIG, which the Grok CLI sets), and the caller's thread can end at any
205        // time, so the start happens on a thread of its own that lasts as long as the run.
206        let (started, start) = channel();
207        let (starter, keep) = channel::<()>();
208        let slave = pair.slave;
209        std::thread::Builder::new()
210            .name("pty-start".to_owned())
211            .spawn(move || {
212                let child = slave.spawn_command(cmd);
213                let _ = started.send(child.map(|child| (child, slave)));
214                let _ = keep.recv();
215            })
216            .map_err(internal)?;
217        let (child, slave) = start.recv().map_err(internal)?.map_err(internal)?;
218        let tree = match os::adopt(
219            child.process_id(),
220            usize::try_from(config.tree_scans).unwrap_or(usize::MAX),
221        ) {
222            Ok(tree) => tree,
223            Err(error) => {
224                let mut child = child;
225                let _ = child.kill();
226                let _ = child.wait();
227                return Err(internal(error));
228            }
229        };
230        // The child owns the slave now; holding it here would keep the pty open past its exit.
231        drop(slave);
232        drop(starting);
233        let pid = child.process_id().map(i64::from).unwrap_or(-1);
234
235        let mut reader = pair.master.try_clone_reader().map_err(internal)?;
236        let writer = Arc::new(Mutex::new(pair.master.take_writer().map_err(internal)?));
237        #[cfg(windows)]
238        let asks = {
239            // A write can block while ConPTY is not reading, holding the writer: the reader
240            // only asks, so the program's output keeps draining meanwhile.
241            let (asks, asked) = channel::<()>();
242            let answers = writer.clone();
243            std::thread::Builder::new()
244                .name(format!("pty-{pid}-answers"))
245                .spawn(move || {
246                    for () in asked {
247                        answer(&answers);
248                    }
249                })
250                .map_err(internal)?;
251            asks
252        };
253        let (tx, rx) = channel();
254        std::thread::Builder::new()
255            .name(format!("pty-{pid}"))
256            .spawn(move || {
257                let mut buf = vec![0u8; read_chunk];
258                #[cfg(windows)]
259                let mut queries = CursorQueries::default();
260                loop {
261                    match reader.read(&mut buf) {
262                        Ok(0) | Err(_) => {
263                            #[cfg(windows)]
264                            {
265                                let held = queries.finish();
266                                if !held.is_empty() {
267                                    let _ = tx.send(held);
268                                }
269                            }
270                            break;
271                        }
272                        Ok(n) => {
273                            #[cfg(windows)]
274                            let output = {
275                                let (output, asked) = queries.filter(&buf[..n]);
276                                for _ in 0..asked {
277                                    let _ = asks.send(());
278                                }
279                                output
280                            };
281                            #[cfg(not(windows))]
282                            let output = buf[..n].to_vec();
283                            if !output.is_empty() && tx.send(output).is_err() {
284                                break;
285                            }
286                        }
287                    }
288                }
289            })
290            .map_err(internal)?;
291
292        Ok(Self {
293            pid,
294            chunks: Mutex::new(rx),
295            pending: Mutex::new(Vec::new()),
296            eof: AtomicBool::new(false),
297            quiet_since: Mutex::new(None),
298            writer,
299            master: Mutex::new(pair.master),
300            child: Mutex::new(child),
301            tree,
302            exit: Mutex::new(None),
303            _starter: starter,
304            drain_quiet: Duration::from_millis(config.drain_quiet_ms),
305            kill_wait: Duration::from_millis(config.kill_wait_ms),
306        })
307    }
308
309    fn poll_exit(&self) -> Result<Option<ExitInfo>, ProviderError> {
310        let mut exit = lock(&self.exit)?;
311        if exit.is_none()
312            && let Some(status) = lock(&self.child)?.try_wait().map_err(internal)?
313        {
314            *exit = Some(exit_info(&status));
315        }
316        Ok(*exit)
317    }
318}
319
320impl TerminalRun for PtyRun {
321    fn pid(&self) -> i64 {
322        self.pid
323    }
324
325    fn read(&self, dst: &mut [u8], timeout_ms: i64) -> Result<i64, ProviderError> {
326        let mut pending = lock(&self.pending)?;
327        if pending.is_empty() {
328            if self.eof.load(Ordering::Acquire) {
329                return Ok(0);
330            }
331            let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
332            let chunks = lock(&self.chunks)?;
333            loop {
334                let now = Instant::now();
335                let drained_at = match self.poll_exit()? {
336                    Some(_) => {
337                        Some(*lock(&self.quiet_since)?.get_or_insert(now) + self.drain_quiet)
338                    }
339                    None => None,
340                };
341                let until = drained_at.unwrap_or(now + EXIT_CHECK).min(deadline);
342                match chunks.recv_timeout(until.saturating_duration_since(now)) {
343                    Ok(chunk) => {
344                        *lock(&self.quiet_since)? = None;
345                        *pending = chunk;
346                        break;
347                    }
348                    Err(RecvTimeoutError::Disconnected) => {
349                        // The terminal can close before the child is reaped; the end of output
350                        // promises its exit status, so wait for it as kill does.
351                        let settle = Instant::now() + self.kill_wait;
352                        while self.poll_exit()?.is_none() && Instant::now() < settle {
353                            std::thread::sleep(EXIT_POLL);
354                        }
355                        self.eof.store(true, Ordering::Release);
356                        return Ok(0);
357                    }
358                    Err(RecvTimeoutError::Timeout) => {
359                        let now = Instant::now();
360                        if drained_at.is_some_and(|at| now >= at) {
361                            self.eof.store(true, Ordering::Release);
362                            return Ok(0);
363                        }
364                        if now >= deadline {
365                            return Ok(READ_TIMED_OUT);
366                        }
367                    }
368                }
369            }
370        }
371        let n = pending.len().min(dst.len());
372        dst[..n].copy_from_slice(&pending[..n]);
373        pending.drain(..n);
374        Ok(n as i64)
375    }
376
377    fn write(&self, data: &[u8]) -> Result<(), ProviderError> {
378        let mut writer = lock(&self.writer)?;
379        let input = os::translate_input(data);
380        writer
381            .write_all(&input)
382            .and_then(|()| writer.flush())
383            .map_err(internal)
384    }
385
386    fn resize(&self, rows: i64, cols: i64) -> Result<(), ProviderError> {
387        let (rows, cols) = (dimension(rows)?, dimension(cols)?);
388        lock(&self.master)?
389            .resize(size(rows, cols))
390            .map_err(internal)
391    }
392
393    fn kill(&self) -> Result<(), ProviderError> {
394        let leader_alive = lock(&self.exit)?.is_none();
395        self.tree.kill(leader_alive).map_err(internal)?;
396        // An error here means it already exited, which is what was asked.
397        let _ = lock(&self.child)?.kill();
398        // Killing is asynchronous; a caller may remove the working directory next.
399        let deadline = Instant::now() + self.kill_wait;
400        while (self.poll_exit()?.is_none() || self.tree.running()) && Instant::now() < deadline {
401            std::thread::sleep(EXIT_POLL);
402        }
403        Ok(())
404    }
405
406    fn exit_status(&self, timeout_ms: i64) -> Result<Value, ProviderError> {
407        let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64);
408        loop {
409            if let Some(exit) = self.poll_exit()? {
410                return exit.to_value().map_err(internal);
411            }
412            if Instant::now() >= deadline {
413                return ExitInfo {
414                    running: true,
415                    ..ExitInfo::default()
416                }
417                .to_value()
418                .map_err(internal);
419            }
420            std::thread::sleep(EXIT_POLL);
421        }
422    }
423}
424
425impl Drop for PtyRun {
426    fn drop(&mut self) {
427        let _ = TerminalRun::kill(self);
428        if let Ok(mut child) = self.child.lock() {
429            let _ = child.wait();
430        }
431    }
432}
433
434/// Writes [`CURSOR_REPORT`] as the terminal's answer. A failed write means the program is gone.
435#[cfg(windows)]
436fn answer(writer: &Mutex<Box<dyn Write + Send>>) {
437    if let Ok(mut writer) = writer.lock() {
438        let _ = writer
439            .write_all(CURSOR_REPORT)
440            .and_then(|()| writer.flush());
441    }
442}
443
444/// Removes [`CURSOR_QUERY`] from a stream read in chunks, holding back the end of a chunk that
445/// may be the start of one.
446#[cfg(any(windows, test))]
447#[derive(Default)]
448struct CursorQueries {
449    held: Vec<u8>,
450}
451
452#[cfg(any(windows, test))]
453impl CursorQueries {
454    /// The chunk with every whole query removed, and how many there were.
455    fn filter(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
456        let mut bytes = std::mem::take(&mut self.held);
457        bytes.extend_from_slice(chunk);
458        let mut output = Vec::with_capacity(bytes.len());
459        let mut asked = 0;
460        let mut index = 0;
461        while index < bytes.len() {
462            let rest = &bytes[index..];
463            if rest.starts_with(CURSOR_QUERY) {
464                asked += 1;
465                index += CURSOR_QUERY.len();
466            } else if CURSOR_QUERY.starts_with(rest) {
467                self.held = rest.to_vec();
468                break;
469            } else {
470                output.push(bytes[index]);
471                index += 1;
472            }
473        }
474        (output, asked)
475    }
476
477    /// What was held back, once the stream has ended.
478    fn finish(&mut self) -> Vec<u8> {
479        std::mem::take(&mut self.held)
480    }
481}
482
483fn exit_info(status: &portable_pty::ExitStatus) -> ExitInfo {
484    match status.signal() {
485        Some(name) => ExitInfo {
486            running: false,
487            code: None,
488            signal: Some(signal_number(name)),
489        },
490        None => ExitInfo {
491            running: false,
492            // `portable-pty` keeps Windows' unsigned exit code; it is reported as the signed
493            // 32-bit value the standard library and every transport give (`0xFFFFFFFF` is -1).
494            code: Some(i64::from(status.exit_code().cast_signed())),
495            signal: None,
496        },
497    }
498}
499
500/// `portable-pty` reports a signal by name; the contract carries its number.
501fn signal_number(name: &str) -> i64 {
502    match name.trim_start_matches("SIG").to_ascii_uppercase().as_str() {
503        "HUP" | "HANGUP" => 1,
504        "INT" | "INTERRUPT" => 2,
505        "QUIT" => 3,
506        "ABRT" | "ABORTED" => 6,
507        "KILL" | "KILLED" => 9,
508        "SEGV" | "SEGMENTATION FAULT" => 11,
509        "PIPE" | "BROKEN PIPE" => 13,
510        "TERM" | "TERMINATED" => 15,
511        _ => -1,
512    }
513}
514
515fn size(rows: u16, cols: u16) -> PtySize {
516    PtySize {
517        rows: rows.min(MAX_DIMENSION),
518        cols: cols.min(MAX_DIMENSION),
519        pixel_width: 0,
520        pixel_height: 0,
521    }
522}
523
524fn dimension(n: i64) -> Result<u16, ProviderError> {
525    u16::try_from(n)
526        .ok()
527        .filter(|&n| (1..=MAX_DIMENSION).contains(&n))
528        .ok_or_else(|| {
529            refuse(
530                Status::GUATIAO_ERR_BAD_VALUE,
531                "rows and cols must be 1 to 32767",
532            )
533        })
534}
535
536fn lock<T>(m: &Mutex<T>) -> Result<std::sync::MutexGuard<'_, T>, ProviderError> {
537    m.lock()
538        .map_err(|_| refuse(Status::GUATIAO_ERR_INTERNAL, "a run lock was poisoned"))
539}
540
541fn refuse(status: Status, message: impl std::fmt::Display) -> ProviderError {
542    ProviderError::new(status, &message.to_string())
543}
544
545fn internal(e: impl std::fmt::Display) -> ProviderError {
546    refuse(Status::GUATIAO_ERR_INTERNAL, e)
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    fn filtered(chunks: &[&[u8]]) -> (Vec<u8>, usize) {
554        let mut queries = CursorQueries::default();
555        let mut output = Vec::new();
556        let mut asked = 0;
557        for chunk in chunks {
558            let (out, n) = queries.filter(chunk);
559            output.extend(out);
560            asked += n;
561        }
562        output.extend(queries.finish());
563        (output, asked)
564    }
565
566    #[test]
567    fn an_exit_code_with_the_high_bit_set_is_negative() {
568        for (raw, code) in [
569            (0, 0),
570            (3, 3),
571            (0xFFFF_FFFF, -1),
572            (0xC000_013A, -1_073_741_510),
573        ] {
574            let exit = exit_info(&portable_pty::ExitStatus::with_exit_code(raw));
575            assert_eq!(exit.code, Some(code), "{raw:#010X}");
576        }
577    }
578
579    #[test]
580    fn a_cursor_query_is_counted_and_removed_even_across_chunks() {
581        assert_eq!(
582            filtered(&[b"\x1b[6n\x1b[?9001hready\r\n"]),
583            (b"\x1b[?9001hready\r\n".to_vec(), 1)
584        );
585        assert_eq!(
586            filtered(&[b"a\x1b", b"[", b"6", b"nb\x1b[6n"]),
587            (b"ab".to_vec(), 2)
588        );
589    }
590
591    #[test]
592    fn other_sequences_and_a_held_tail_pass_through() {
593        assert_eq!(
594            filtered(&[b"\x1b[6m\x1b[66n", b"\x1b[6"]),
595            (b"\x1b[6m\x1b[66n\x1b[6".to_vec(), 0)
596        );
597    }
598}