1#![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);
48const EXIT_CHECK: Duration = Duration::from_millis(50);
50const MAX_DIMENSION: u16 = i16::MAX as u16;
52#[cfg(any(windows, test))]
54const CURSOR_QUERY: &[u8] = b"\x1b[6n";
55#[cfg(windows)]
57const CURSOR_REPORT: &[u8] = b"\x1b[1;1R";
58
59#[derive(ToValue, FromValue, Schema, Debug, Clone, PartialEq, Eq)]
61#[map(crate = ::ai6::guatiao)]
62pub struct PtyConfig {
63 #[map(default = 65536)]
65 pub read_chunk_bytes: u64,
66 #[map(default = 200)]
70 pub drain_quiet_ms: u64,
71 #[map(default = 2_000)]
74 pub kill_wait_ms: u64,
75 #[map(default = DEFAULT_TREE_SCANS)]
78 pub tree_scans: u64,
79 #[map(default = false)]
84 pub allow_root: bool,
85}
86
87const 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#[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 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
151static STARTING: Mutex<()> = Mutex::new(());
153
154struct PtyRun {
155 pid: i64,
156 chunks: Mutex<Receiver<Vec<u8>>>,
157 pending: Mutex<Vec<u8>>,
159 eof: AtomicBool,
160 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 _starter: std::sync::mpsc::Sender<()>,
169 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 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 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 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 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 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 let _ = lock(&self.child)?.kill();
398 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#[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#[cfg(any(windows, test))]
447#[derive(Default)]
448struct CursorQueries {
449 held: Vec<u8>,
450}
451
452#[cfg(any(windows, test))]
453impl CursorQueries {
454 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 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 code: Some(i64::from(status.exit_code().cast_signed())),
495 signal: None,
496 },
497 }
498}
499
500fn 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}