Oregami
Repositories/oxedyne/daimond

oxedyne/daimond/hand/src/pty.rs

82.6 KiB, 1 run

created by r2519314175:923, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A real terminal for a command: `argv` only, fenced, and bidirectional.
2//!
3//! [`crate::exec`] runs a command down a pipe, and that covers nearly everything
4//! an agent does. It does not cover `sudo`, `ssh`, `vim`, `git commit`, `psql` or
5//! any REPL, because none of those work down a pipe: each one asks the kernel
6//! whether it is talking to a terminal and behaves differently when it is not.
7//! `sudo` refuses to read a password, `ssh` refuses a passphrase, `git` opens an
8//! editor that has nothing to draw on, and a shell turns off its prompt, its job
9//! control and its line editing. So this module allocates a real terminal and
10//! gives the command the far end of it.
11//!
12//! # A terminal is not a flag on a pipe
13//!
14//! Three things have to be true before a program believes it has a terminal, and
15//! only the first is about file descriptors:
16//!
17//! * `isatty(0)` must answer yes -- which a pty slave on the descriptor gives.
18//! * The process must have that terminal as its **controlling terminal**, or
19//! `Ctrl-C` reaches nobody, `/dev/tty` cannot be opened, and a shell cannot set
20//! a foreground process group. This is the part that is easy to get subtly
21//! wrong, and it is why [`adopt_terminal`] exists.
22//! * The kernel must know how big it is, and must be told again every time the
23//! window changes; see [`PtySessions::resize`].
24//!
25//! # Where the controlling terminal is established, and why there
26//!
27//! A controlling terminal is claimed by a **session leader**, which means
28//! `setsid` followed by `TIOCSCTTY` on the terminal, in the process that is about
29//! to become the command. The usual way to do that in Rust is
30//! `CommandExt::pre_exec`, which is `unsafe` and which this project does not
31//! write.
32//!
33//! It does not need to. [`crate::exec`] already re-executes the hand as a
34//! launcher, for the same reason in a different guise: the fence has to be
35//! applied by the process that becomes the command, so the hand spawns *itself*,
36//! applies the fence to itself, and `exec`s. A launcher is an ordinary process
37//! running ordinary code -- not a hook between `fork` and `exec` -- so it can
38//! call `setsid` and `TIOCSCTTY` safely, and the terminal, like the fence, is
39//! inherited across the `exec`. [`adopt_terminal`] is that code, called by the
40//! launcher when the plan says the command is to have a terminal.
41//!
42//! Two consequences worth naming. The launcher is **not** given its own process
43//! group by [`std::process::Command::process_group`], as the pipe path does:
44//! `setsid` fails with `EPERM` for a process that already leads a group, and it
45//! would undo the very thing it is there to do. It produces the same group in
46//! the end -- a session leader leads a new group whose id is its own process id --
47//! so the group kill works exactly as it does for a piped run. And when a
48//! session leader claims a terminal, the kernel makes that leader's group the
49//! terminal's **foreground process group**, which is what makes `Ctrl-C` work:
50//! the line discipline sends `SIGINT` to whichever group is in the foreground,
51//! and a shell that starts a job moves the foreground group to the job.
52//!
53//! # Bytes, not text
54//!
55//! Everything in both directions is base64, as [`crate::wire`] says. A terminal
56//! carries arbitrary bytes -- a `cat` of a binary, half a UTF-8 character at the
57//! edge of a read, a control sequence, `0x03` -- and a lossy text conversion
58//! corrupts exactly the case a terminal exists for. `REVIEW.md` records the pipe
59//! path's own version of this: it holds a partial character back between reads.
60//! Here there is nothing to hold back, because nothing is decoded.
61//!
62//! # Bounded
63//!
64//! `REVIEW.md` §3.7 and §3.8 are both about one channel carrying everything. The
65//! answers here are shaped by them:
66//!
67//! * Nothing in the public API awaits the response channel except
68//! [`PtySessions::open`], which the dispatcher already calls from a task of its
69//! own. [`PtySessions::input`], [`PtySessions::resize`] and
70//! [`PtySessions::close`] never block, so a `Bye` arriving behind a flood is
71//! still answered.
72//! * Output is never buffered beyond one read of [`READ_MAX`], because the reader
73//! waits for room on the channel rather than accumulating. That waiting is not
74//! a stall but the correct behaviour of a terminal: a program writing faster
75//! than the terminal can draw is made to wait by the pty itself, exactly as it
76//! would be by a slow serial line. The reader is a task of its own, so a
77//! session whose output nobody is taking cannot delay a kill, a resize or
78//! another session.
79//! * A session that has forwarded [`SESSION_OUTPUT_MAX`] is ended rather than
80//! truncated. Discarding a run of bytes is right for a pipe and wrong for a
81//! terminal, where every dropped byte desynchronises the screen from that point
82//! on; a quarter of a gigabyte through one terminal is a runaway, and saying so
83//! is more honest than drawing the rest of the session wrong.
84//! * Input is bounded twice: [`INPUT_MAX`] per message and [`WORD_QUEUE`]
85//! messages outstanding, so a page that types faster than a program reads is
86//! told rather than allowed to grow the hand.
87//!
88//! # The dependency
89//!
90//! `rustix` provides safe wrappers for the five system calls a terminal needs
91//! that `std` has none of: `posix_openpt`, `grantpt`/`unlockpt`/`ptsname`,
92//! `setsid`, `TIOCSCTTY` and `TIOCSWINSZ`. `nix` was the obvious candidate and
93//! covers only the first three: it has no safe `TIOCSWINSZ` and no safe
94//! `TIOCSCTTY`, so both would have to be reached through its `ioctl_*!` macros,
95//! which generate `unsafe fn`. There is no `unsafe` in this file, and the choice
96//! of crate is the reason there does not have to be.
97
98use crate::{
99 exec::{
100 add_defaults,
101 detected_terminal_fence,
102 encode_payload,
103 screen_env,
104 screen_scratch,
105 signal_group,
106 vet_cwd,
107 vet_program,
108 Act,
109 Launcher,
110 Payload,
111 Scratch,
112 Signalling,
113 Vetted,
114 Vetted0,
115 DRAIN_GRACE_MS,
116 TMP_VARS,
117 },
118 fence::Unfenced,
119 wire::{
120 PtySize,
121 Req,
122 Resp,
123 Sig,
124 },
125};
126
127use oxedyne_fe2o3_core::prelude::*;
128use oxedyne_fe2o3_text::base64;
129
130use std::{
131 collections::HashMap,
132 fs::File,
133 io::{
134 Read,
135 Write,
136 },
137 os::fd::{
138 AsFd,
139 OwnedFd,
140 },
141 process::Stdio,
142 sync::{
143 Arc,
144 Mutex,
145 },
146 time::Duration,
147};
148
149use tokio::{
150 io::{
151 unix::AsyncFd,
152 AsyncWriteExt,
153 },
154 process::{
155 Child,
156 Command,
157 },
158 sync::mpsc::{
159 error::TrySendError,
160 Receiver,
161 Sender,
162 },
163 task::JoinHandle,
164 time::timeout,
165};
166
167// ┌───────────────────────────────────────────────────────────────┐
168// │ Limits │
169// └───────────────────────────────────────────────────────────────┘
170
171/// What the hand tells a command its terminal is.
172///
173/// The hand's to set and not the caller's, as [`crate::wire::Req::Open`] says: a
174/// caller that could name `TERM` could promise capabilities the page cannot draw,
175/// and a program that believes in them draws a screen nobody can read. This
176/// value is what the page's terminal emulator implements.
177pub const TERM: &str = "xterm-256color";
178
179/// Bytes taken from the terminal in one read.
180///
181/// Base64 costs four characters for every three bytes, so a read of this size
182/// becomes a little over 87 KiB of payload -- inside [`crate::wire::CHUNK_MAX`]
183/// with room for the envelope, and far inside [`crate::wire::FRAME_MAX`].
184pub const READ_MAX: usize = 64 * 1024;
185
186/// The most typed input carried in one [`crate::wire::Req::Input`].
187///
188/// A keystroke is one byte and the longest ordinary burst is a paste. Sixty-four
189/// kilobytes of paste is already unusual; more than that is a caller trying to
190/// use the terminal as a pipe, which is what [`crate::wire::Req::Exec`] is for.
191pub const INPUT_MAX: usize = 64 * 1024;
192
193/// How many messages may be outstanding to one session before the page is told.
194///
195/// Bounded rather than unbounded, and small: with [`INPUT_MAX`] this caps what
196/// one unread session can hold at four megabytes, and a page typing faster than
197/// the program reads is told so rather than allowed to grow the hand.
198pub const WORD_QUEUE: usize = 64;
199
200/// How many terminals may be open at once.
201///
202/// Every session is a pty, two tasks and a process group; a page that could open
203/// them without limit could exhaust the machine's pty devices, which are shared
204/// with everything else the user is running.
205pub const SESSIONS_MAX: usize = 8;
206
207/// The most output one session will forward before it is ended.
208///
209/// See the module documentation for why this ends the session rather than
210/// truncating it.
211pub const SESSION_OUTPUT_MAX: u64 = 256 * 1024 * 1024;
212
213/// The largest terminal the hand will set.
214///
215/// A window size is two `u16` fields, and a caller sending 65,535 columns is
216/// making every program that allocates a line buffer allocate a large one.
217pub const CELLS_MAX: u16 = 4_000;
218
219/// How long a write to the terminal is given before it is given up on.
220///
221/// A program that has stopped reading its terminal fills the pty's input buffer,
222/// after which a write waits for ever. That must not wedge the session: the
223/// keystrokes are dropped, the page is told, and the session goes on answering.
224const TYPE_GRACE_MS: u64 = 5_000;
225
226/// How long a group signal is given before it is given up on.
227const KILL_GRACE_MS: u64 = 2_000;
228
229// ┌───────────────────────────────────────────────────────────────┐
230// │ Outcomes the caller distinguishes │
231// └───────────────────────────────────────────────────────────────┘
232
233/// What became of a request to open a terminal.
234///
235/// An enum rather than an error, for the reason [`crate::exec::Launch`] gives: a
236/// refusal is not a failure, and a model can recover from a sentence.
237#[derive(Clone, Copy, Debug, Eq, PartialEq)]
238pub enum Opening {
239 /// The terminal is open and the command is attached to it, under this
240 /// process id, which is also its process group.
241 Opened(u32),
242 /// The hand declined; the sentence has already gone out as
243 /// [`crate::wire::Resp::Refused`].
244 Refused,
245}
246
247/// What became of a message aimed at a live session.
248///
249/// Three arms rather than two, because "the page typed faster than the program
250/// read" and "the session has ended" are different facts and the page acts on
251/// them differently.
252#[derive(Clone, Copy, Debug, Eq, PartialEq)]
253pub enum Reached {
254 /// The session has it.
255 Delivered,
256 /// The session's queue is full; the message was not delivered.
257 Busy,
258 /// No such session is live. Not an error.
259 Finished,
260}
261
262/// What a session's supervisor is told to do.
263enum Word {
264 /// Bytes typed at the terminal.
265 Type(Vec<u8>),
266 /// The window changed size.
267 Size(PtySize),
268 /// End the session now.
269 Stop,
270 /// The reader gave up, and this is what to tell the page first.
271 Spent(String),
272}
273
274// ┌───────────────────────────────────────────────────────────────┐
275// │ One session │
276// └───────────────────────────────────────────────────────────────┘
277
278/// One live terminal, as the registry holds it.
279///
280/// A handle and not the terminal itself: the pty, the child and the two tasks are
281/// owned by the supervisor, and everything reaches them down one line. That is
282/// what keeps [`PtySessions::input`] and [`PtySessions::close`] free of locks
283/// held across an `await` and free of any wait at all.
284#[derive(Clone, Debug)]
285pub struct PtySession {
286 /// The caller's identifier.
287 id: String,
288 /// The child's process id, which is also its process group.
289 pid: u32,
290 /// The line to the supervisor, which owns the terminal.
291 words: Sender<Word>,
292}
293
294impl PtySession {
295
296 /// The caller's identifier for this session.
297 pub fn id(&self) -> &str {
298 &self.id
299 }
300
301 /// The process id of the command attached to this terminal.
302 pub fn pid(&self) -> u32 {
303 self.pid
304 }
305
306 /// Types bytes at the terminal, exactly as they were given.
307 ///
308 /// # Arguments
309 /// * `bytes` - The raw keystrokes.
310 pub fn write(&self, bytes: Vec<u8>) -> Reached {
311 self.tell(Word::Type(bytes))
312 }
313
314 /// Tells the kernel the window changed size, which tells the program.
315 ///
316 /// # Arguments
317 /// * `size` - The new size, in character cells.
318 pub fn resize(&self, size: PtySize) -> Reached {
319 self.tell(Word::Size(size))
320 }
321
322 /// Ends the session and everything it started.
323 pub fn close(&self) -> Reached {
324 self.tell(Word::Stop)
325 }
326
327 /// Hands one word to the supervisor without ever waiting.
328 ///
329 /// # Arguments
330 /// * `w` - What the supervisor is to do.
331 fn tell(&self, w: Word) -> Reached {
332 match self.words.try_send(w) {
333 Ok(()) => Reached::Delivered,
334 Err(TrySendError::Full(_)) => Reached::Busy,
335 Err(TrySendError::Closed(_)) => Reached::Finished,
336 }
337 }
338}
339
340// A `Word` holds bytes and nothing that can be printed usefully, but the handle
341// derives `Debug` so that a registry of them can be.
342impl std::fmt::Debug for Word {
343 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344 match self {
345 Self::Type(b) => write!(f, "Type({} bytes)", b.len()),
346 Self::Size(s) => write!(f, "Size({}x{})", s.cols, s.rows),
347 Self::Stop => write!(f, "Stop"),
348 Self::Spent(_) => write!(f, "Spent"),
349 }
350 }
351}
352
353// ┌───────────────────────────────────────────────────────────────┐
354// │ The registry │
355// └───────────────────────────────────────────────────────────────┘
356
357/// Opens terminals, keeps them reachable, and closes them.
358///
359/// Cheap to clone: every clone shares one registry of live sessions. The sibling
360/// of [`crate::exec::Runner`] and deliberately the same shape, down to the
361/// launcher it re-executes and the identifier it keys on.
362#[derive(Clone)]
363pub struct PtySessions {
364 /// Live sessions, keyed by the caller's identifier.
365 live: Arc<Mutex<HashMap<String, PtySession>>>,
366 /// What is re-executed to apply the fence. See [`crate::exec::Launcher`].
367 launcher: Arc<Launcher>,
368}
369
370impl Default for PtySessions {
371 fn default() -> Self {
372 Self::new()
373 }
374}
375
376impl PtySessions {
377
378 /// Creates an empty registry that fences through this binary.
379 pub fn new() -> Self {
380 Self::with_launcher(Launcher::SelfExe)
381 }
382
383 /// Creates an empty registry with a stated launcher.
384 ///
385 /// # Arguments
386 /// * `launcher` - What to re-execute in order to apply the fence.
387 pub fn with_launcher(launcher: Launcher) -> Self {
388 Self {
389 live: Arc::new(Mutex::new(HashMap::new())),
390 launcher: Arc::new(launcher),
391 }
392 }
393
394 /// Opens a terminal and starts a command attached to it.
395 ///
396 /// [`crate::wire::Resp::Opened`] is sent before this returns; every
397 /// [`crate::wire::Resp::Output`] and the closing
398 /// [`crate::wire::Resp::Closed`] follow on `tx` from a task, in that order.
399 ///
400 /// The order of what happens here is the same as [`crate::exec::Runner::spawn`]'s
401 /// and for the same reasons: the caller's own fence is checked *before* the
402 /// hand widens it, the widenings are made before the plan because a launcher
403 /// cannot add to a plan it is handed, and a fence that cannot be honoured is a
404 /// refusal on this side of the `exec` rather than a death on the other.
405 ///
406 /// # Arguments
407 /// * `req` - A [`crate::wire::Req::Open`]; any other variant is a caller bug.
408 /// * `tx` - Where every response about this session is sent.
409 ///
410 /// # Returns
411 /// [`Opening::Opened`] with the child's process id, or [`Opening::Refused`].
412 pub async fn open(&self, req: Req, tx: Sender<Resp>) -> Outcome<Opening> {
413 let (id, argv, cwd, mut env, size, mut fence) = match req {
414 // `toolkits` is spent before the request gets here; see `Runner::spawn`.
415 Req::Open { id, argv, cwd, env, size, fence, toolkits: _ } =>
416 (id, argv, cwd, env, size, fence),
417 other => return Err(err!(
418 "PtySessions::open was given {:?}, which is not an Open request.", other;
419 Bug, Invalid, Input)),
420 };
421
422 if argv.is_empty() {
423 return self.refuse(&id, &tx, fmt!(
424 "Refused: a terminal was asked for with no program to run in it. The first element \
425 of argv is the program and the rest are its arguments -- a shell is a perfectly \
426 ordinary thing to put there, and usually what you want.")).await;
427 }
428
429 // The answers are taken out of the lock before they are used, so that no
430 // guard is held across the `await` that sends a refusal.
431 let (already, open_now) = {
432 let g = lock_mutex!(self.live);
433 (g.contains_key(&id), g.len())
434 };
435 if already {
436 return self.refuse(&id, &tx, fmt!(
437 "Refused: '{}' is already the identifier of a terminal that is still open. \
438 Identifiers are how keystrokes reach a session and how its output is recognised, \
439 so two cannot share one. Give this one a different id, or close the one already \
440 open.", id)).await;
441 }
442 if open_now >= SESSIONS_MAX {
443 return self.refuse(&id, &tx, fmt!(
444 "Refused: {} terminals are already open, which is as many as this hand will hold. \
445 Every one is a pseudo-terminal device shared with the rest of the machine. Close \
446 one before opening another.", SESSIONS_MAX)).await;
447 }
448
449 if let Some(s) = screen_env(&env) {
450 return self.refuse(&id, &tx, s).await;
451 }
452 if let Some(s) = screen_scratch(&env) {
453 return self.refuse(&id, &tx, s).await;
454 }
455 if let Some(s) = screen_term(&env) {
456 return self.refuse(&id, &tx, s).await;
457 }
458
459 // Against the fence the caller sent, before the hand widens it: the
460 // scratch and the terminal are roots the caller did not ask for, and a
461 // spec that grants nothing must still read as granting nothing.
462 let dir = match vet_cwd(&cwd, &fence) {
463 Vetted::Ok(p) => p,
464 Vetted::Refused(s) => return self.refuse(&id, &tx, s).await,
465 };
466
467 let scratch = match Scratch::make(&id) {
468 Ok(s) => s,
469 Err(e) => return self.refuse(&id, &tx, fmt!(
470 "Refused: this session could not be given a private directory to write temporary \
471 files in, and the hand will not run one without. {} ", e.msgs().join(" "))).await,
472 };
473 fence.rw.push(fmt!("{}", scratch.dir().display()));
474 // Appended after the caller's pairs, so that the hand's answer is the
475 // last word even if one of these names ever reached this far.
476 for k in TMP_VARS {
477 env.push((fmt!("{}", k), fmt!("{}", scratch.dir().display())));
478 }
479 env.push((fmt!("TERM"), fmt!("{}", TERM)));
480 // The same two a piped command is given where the request named neither,
481 // and for the same reasons -- a terminal is a command with a screen. A
482 // shell with no `HOME` cannot expand `~`, read a profile or find a
483 // configuration, and one with no `PATH` cannot find a program at all,
484 // which for an interactive session is the whole of it.
485 add_defaults(&mut env);
486
487 let term = match Pty::make(size) {
488 Ok(p) => p,
489 Err(e) => return self.refuse(&id, &tx, fmt!(
490 "Refused: this machine would not give the hand a pseudo-terminal, so there is no \
491 terminal to attach the command to. {}", e.msgs().join(" "))).await,
492 };
493
494 // The terminal the hand made is added to the fence, like the scratch and
495 // for the same reason: a program on a terminal is entitled to its own
496 // terminal, and `sudo` asking for a password opens `/dev/tty` to do it.
497 // Neither grant widens anything the caller could have reached otherwise
498 // -- `/dev/tty` resolves to the process's own controlling terminal, which
499 // is this pty and nothing else.
500 fence.rw.push(fmt!("{}", term.path.display()));
501 fence.rw.push(fmt!("/dev/tty"));
502
503 // `detected_terminal_fence` and not `detected_fence`: a terminal's carved directories may
504 // be LISTED, because a terminal opens in the granted root and the granted root always
505 // holds `.daimond`. Sealed, `ls` there fails with nothing on screen to explain it. See
506 // `exec::detected_terminal_fence` for what the difference costs and why a terminal is
507 // where it can be afforded.
508 let plan = match detected_terminal_fence().plan(&fence, &Unfenced::Refuse) {
509 Ok(p) => p,
510 Err(e) => return self.refuse(&id, &tx, fmt!(
511 "Refused: {}", e.msgs().join(" "))).await,
512 };
513
514 let prog = match vet_program(&argv[0], &dir, &env, &plan) {
515 Vetted0::Ok(p) => p,
516 Vetted0::Refused(s) => return self.refuse(&id, &tx, s).await,
517 };
518
519 let payload = res!(encode_payload(&Payload {
520 prog: prog.clone(),
521 argv: argv.clone(),
522 env: env.clone(),
523 plan: plan.clone(),
524 tty: true,
525 act: Act::Exec,
526 }));
527
528 let mut cmd = Command::new(res!(self.launcher.prog()));
529 cmd.args(self.launcher.args());
530 cmd.current_dir(&dir);
531 cmd.env_clear();
532 for (k, v) in self.launcher.env() {
533 cmd.env(k, v);
534 }
535
536 // Standard input is the launcher's channel, exactly as it is for a piped
537 // run: the plan arrives there, and the launcher replaces the descriptor
538 // with the terminal before it becomes the command. Standard output and
539 // standard error are the terminal from the first instant, which means the
540 // pty has a reader before the hand starts watching it -- without that,
541 // reading a master no slave has opened yet answers EIO, and the session
542 // would close before it began. It also means a launcher that dies saying
543 // why says it on the terminal, where the page can see it.
544 cmd.stdin(Stdio::piped());
545 cmd.stdout(Stdio::from(res!(term.slave_dup())));
546 cmd.stderr(Stdio::from(res!(term.slave_dup())));
547 cmd.kill_on_drop(true);
548
549 // Deliberately no `process_group(0)`: the launcher calls `setsid`, which
550 // fails with EPERM for a process that already leads a group. It arrives
551 // at the same place -- a session leader leads a new group whose id is its
552 // own process id -- so the group kill below reaches the whole tree just
553 // as it does for a piped run.
554
555 let mut child = res!(cmd.spawn()
556 .map_err(|e| err!(e,
557 "The hand could not start the launcher that fences '{}' on a terminal in '{}'.",
558 prog.display(), dir.display();
559 IO, Init)));
560
561 let pid = match child.id() {
562 Some(p) => p,
563 None => return Err(err!(
564 "The child exited before the hand could learn its process id."; IO, Unexpected)),
565 };
566
567 if let Some(mut w) = child.stdin.take() {
568 tokio::spawn(async move {
569 let _ = w.write_all(&payload).await;
570 let _ = w.shutdown().await; // Nothing follows the plan: input is typed.
571 });
572 }
573
574 // The hand's own copy of the slave goes now, so that when the command
575 // exits and the last descriptor on it closes, the master reports it and
576 // the session ends. Held on to, it would keep the terminal open for ever
577 // and the page would wait for a `Closed` that could not come.
578 let Pty { master, path: _, slave } = term;
579 drop(slave);
580
581 let (wordtx, wordrx) = tokio::sync::mpsc::channel::<Word>(WORD_QUEUE);
582 let session = PtySession { id: id.clone(), pid, words: wordtx.clone() };
583 {
584 let mut g = lock_mutex!(self.live);
585 g.insert(id.clone(), session);
586 }
587
588 if tx.send(Resp::Opened { id: id.clone(), pid }).await.is_err() {
589 // The entry was made before the announcement and must not outlive it:
590 // left behind it is permanent, because there would be no supervisor
591 // to receive anything sent to it. The child dies with `cmd`, which
592 // was built with `kill_on_drop`.
593 {
594 let mut g = lock_mutex!(self.live);
595 g.remove(&id);
596 }
597 return Err(err!(
598 "The page stopped listening before '{}' could be announced.", id;
599 Channel, IO));
600 }
601
602 let sess = Watch {
603 id: id.clone(),
604 pgid: pid,
605 live: Arc::clone(&self.live),
606 tx: tx.clone(),
607 scratch: Some(scratch),
608 };
609 tokio::spawn(async move {
610 let wid = sess.id.clone();
611 let wtx = sess.tx.clone();
612 if let Err(e) = watch(sess, child, master, wordrx, wordtx).await {
613 let _ = wtx.send(Resp::Error {
614 id: Some(wid),
615 message: fmt!("{}", e),
616 }).await;
617 }
618 });
619
620 Ok(Opening::Opened(pid))
621 }
622
623 /// Types at a live session, decoding the base64 the wire carries.
624 ///
625 /// Never waits, so the dispatcher can answer this while a session floods.
626 ///
627 /// # Arguments
628 /// * `id` - The identifier given at [`crate::wire::Req::Open`].
629 /// * `data` - Base64 of the bytes typed.
630 pub fn input(&self, id: &str, data: &str) -> Outcome<Reached> {
631 let bytes = res!(base64::decode(data).map_err(|e| err!(e,
632 "The keystrokes for '{}' are not the base64 the wire carries, so the hand does not \
633 know what was typed and will not guess.", id;
634 Invalid, Input, Decode)));
635 if bytes.len() > INPUT_MAX {
636 return Err(err!(
637 "'{}' was sent {} bytes of input at once and {} is the most a terminal will take. \
638 A terminal is for typing; a payload that size wants Exec and a stdin field.",
639 id, bytes.len(), INPUT_MAX;
640 Excessive, Input, Size));
641 }
642 Ok(self.with(id, |s| s.write(bytes)))
643 }
644
645 /// Tells a live session's terminal that the window changed size.
646 ///
647 /// # Arguments
648 /// * `id` - The identifier given at [`crate::wire::Req::Open`].
649 /// * `size` - The new size, in character cells.
650 pub fn resize(&self, id: &str, size: PtySize) -> Outcome<Reached> {
651 Ok(self.with(id, |s| s.resize(size)))
652 }
653
654 /// Ends one session.
655 ///
656 /// # Arguments
657 /// * `id` - The identifier given at [`crate::wire::Req::Open`].
658 pub fn close(&self, id: &str) -> Outcome<Reached> {
659 Ok(self.with(id, |s| s.close()))
660 }
661
662 /// Ends every session, on the way out of a conversation.
663 ///
664 /// Called from the shutdown block in `main`, beside `Runner::stop_all`, which is the one place
665 /// every ending passes through -- a goodbye, a page that vanished, a loop that failed. Putting
666 /// it in the [`crate::wire::Req::Bye`] arm as well would be a second call site for one rule,
667 /// and it is the second call site that eventually gets forgotten: this had NO call site for
668 /// long enough that its own doc comment described a caller that did not exist.
669 ///
670 /// Each session's stop sweeps every process group in it and not merely the leader's -- see
671 /// [`sweep`], and the `sleep 60 &` that is the reason.
672 ///
673 /// # Returns
674 /// How many sessions were told to stop.
675 pub fn close_all(&self) -> Outcome<usize> {
676 let all = {
677 let g = lock_mutex!(self.live);
678 g.values().cloned().collect::<Vec<_>>()
679 };
680 let mut n = 0;
681 for s in all {
682 if s.close() != Reached::Finished {
683 n += 1;
684 }
685 }
686 Ok(n)
687 }
688
689 /// The process id of a live session, or `None` if it has closed.
690 ///
691 /// # Arguments
692 /// * `id` - The identifier given at [`crate::wire::Req::Open`].
693 pub fn pid_of(&self, id: &str) -> Outcome<Option<u32>> {
694 let g = lock_mutex!(self.live);
695 Ok(g.get(id).map(|s| s.pid))
696 }
697
698 /// How many sessions are open.
699 pub fn live_count(&self) -> Outcome<usize> {
700 let g = lock_mutex!(self.live);
701 Ok(g.len())
702 }
703
704 /// Does something to a named session, if it is still there.
705 ///
706 /// The handle is cloned out of the lock before it is used, so the registry is
707 /// never locked while a message is being handed over.
708 ///
709 /// # Arguments
710 /// * `id` - The session.
711 /// * `f` - What to do with it.
712 fn with<F>(&self, id: &str, f: F) -> Reached
713 where
714 F: FnOnce(&PtySession) -> Reached,
715 {
716 let found = {
717 let g = match self.live.lock() {
718 Ok(g) => g,
719 Err(p) => p.into_inner(), // A poisoned registry is still a registry.
720 };
721 g.get(id).cloned()
722 };
723 match found {
724 Some(s) => f(&s),
725 None => Reached::Finished,
726 }
727 }
728
729 /// Sends a refusal and reports it, so the caller does not repeat itself.
730 ///
731 /// # Arguments
732 /// * `id` - The session the refusal concerns.
733 /// * `tx` - Where the refusal is sent.
734 /// * `reason` - The whole sentence.
735 async fn refuse(&self, id: &str, tx: &Sender<Resp>, reason: String) -> Outcome<Opening> {
736 if tx.send(Resp::Refused { id: fmt!("{}", id), reason }).await.is_err() {
737 return Err(err!(
738 "The page stopped listening before the refusal for '{}' could be sent.", id;
739 Channel, IO));
740 }
741 Ok(Opening::Refused)
742 }
743}
744
745/// Refuses an environment that tries to say what the terminal is.
746///
747/// Refused rather than dropped, for the reason [`crate::exec`]'s screens give: a
748/// caller whose setting silently did not take effect has no way to find that out.
749///
750/// # Arguments
751/// * `env` - The pairs the caller asked for.
752///
753/// # Returns
754/// The refusal sentence, or `None` if the caller left the question alone.
755fn screen_term(env: &[(String, String)]) -> Option<String> {
756 for (k, _) in env {
757 if k == "TERM" {
758 return Some(fmt!(
759 "Refused: this session asked to run with TERM set. TERM is what a program asks in \
760 order to know what the terminal can draw, and the hand sets it to {} because that \
761 is what the page implements. A caller able to name it could promise a program \
762 capabilities nothing on the other end can draw.", TERM));
763 }
764 }
765 None
766}
767
768// ┌───────────────────────────────────────────────────────────────┐
769// │ The terminal itself │
770// └───────────────────────────────────────────────────────────────┘
771
772/// A pseudo-terminal pair, before the command is attached to it.
773struct Pty {
774 /// The end the hand holds: what the program writes appears here, and what is
775 /// written here is what the program reads.
776 master: OwnedFd,
777 /// The end the command holds, by name. The launcher opens this after
778 /// `setsid` so that it becomes the command's controlling terminal.
779 path: std::path::PathBuf,
780 /// The end the command holds, as a descriptor, kept only long enough to give
781 /// the launcher one.
782 slave: OwnedFd,
783}
784
785impl Pty {
786
787 /// Allocates a terminal of the size the page asked for.
788 ///
789 /// The four calls are the POSIX ritual and all four are safe here:
790 /// `posix_openpt` takes the master, `grantpt` and `unlockpt` make the slave
791 /// openable, and `ptsname` says what to open. `O_NOCTTY` is on both opens
792 /// because neither the hand nor anything it does should acquire a controlling
793 /// terminal by accident -- only the launcher does that, deliberately, after
794 /// `setsid`.
795 ///
796 /// # Arguments
797 /// * `size` - How big the terminal is when it opens.
798 fn make(size: PtySize) -> Outcome<Self> {
799 use rustix::{
800 fs::{
801 Mode,
802 OFlags,
803 },
804 pty::{
805 grantpt,
806 openpt,
807 ptsname,
808 unlockpt,
809 },
810 };
811
812 let master = res!(openpt(
813 rustix::pty::OpenptFlags::RDWR
814 | rustix::pty::OpenptFlags::NOCTTY
815 | rustix::pty::OpenptFlags::CLOEXEC)
816 .map_err(|e| err!(e,
817 "This machine would not open a pseudo-terminal."; IO, System)));
818 res!(grantpt(&master).map_err(|e| err!(e,
819 "The pseudo-terminal's far end could not be made usable."; IO, System)));
820 res!(unlockpt(&master).map_err(|e| err!(e,
821 "The pseudo-terminal's far end could not be unlocked."; IO, System)));
822
823 let name = res!(ptsname(&master, Vec::new()).map_err(|e| err!(e,
824 "The pseudo-terminal has no name, so there is nothing for the command to open.";
825 IO, System)));
826 let path = std::path::PathBuf::from(match name.into_string() {
827 Ok(s) => s,
828 Err(e) => return Err(err!(
829 "The pseudo-terminal's name is not text ({:?}).", e; IO, System, Invalid)),
830 });
831
832 // Opened by the hand as well as by the launcher: this is the descriptor
833 // the launcher is started with, and holding the terminal open across the
834 // whole of the launcher's life is what stops the master reporting the end
835 // of the session before the session has begun.
836 let slave = res!(rustix::fs::open(&path, OFlags::RDWR | OFlags::NOCTTY, Mode::empty())
837 .map_err(|e| err!(e,
838 "The pseudo-terminal '{}' could not be opened.", path.display(); IO, System)));
839
840 // Non-blocking, because the master is about to be watched by the runtime,
841 // and a blocking read on it would stop every other task on the thread.
842 res!(rustix::io::ioctl_fionbio(&master, true).map_err(|e| err!(e,
843 "The pseudo-terminal could not be made non-blocking."; IO, System)));
844
845 let this = Self { master, path, slave };
846 res!(this.set_size(size));
847 Ok(this)
848 }
849
850 /// Another descriptor on the command's end of the terminal.
851 ///
852 /// One each for the launcher's standard output and standard error, because
853 /// `Stdio` takes ownership of what it is given.
854 fn slave_dup(&self) -> Outcome<OwnedFd> {
855 Ok(res!(self.slave.try_clone().map_err(|e| err!(e,
856 "The pseudo-terminal's far end could not be duplicated."; IO, System))))
857 }
858
859 /// Tells the kernel how big the terminal is.
860 ///
861 /// # Arguments
862 /// * `size` - The size, in character cells.
863 fn set_size(&self, size: PtySize) -> Outcome<()> {
864 res!(set_winsize(&self.master, size));
865 Ok(())
866 }
867}
868
869/// Sets a terminal's window size, which is what makes the kernel signal the
870/// program.
871///
872/// The size is clamped rather than refused: a window of no columns is not a
873/// window, and a page that reports one has a layout problem, not a request the
874/// hand should end a session over.
875///
876/// # Arguments
877/// * `fd` - Either end of the terminal.
878/// * `size` - The size, in character cells.
879fn set_winsize<F: AsFd>(fd: F, size: PtySize) -> Outcome<()> {
880 let ws = rustix::termios::Winsize {
881 ws_row: size.rows.clamp(1, CELLS_MAX),
882 ws_col: size.cols.clamp(1, CELLS_MAX),
883 ws_xpixel: 0,
884 ws_ypixel: 0,
885 };
886 res!(rustix::termios::tcsetwinsize(fd, ws).map_err(|e| err!(e,
887 "The terminal would not take a size of {} columns by {} rows.", size.cols, size.rows;
888 IO, System)));
889 Ok(())
890}
891
892// ┌───────────────────────────────────────────────────────────────┐
893// │ The launcher's half │
894// └───────────────────────────────────────────────────────────────┘
895
896/// Makes the terminal on descriptor 1 this process's controlling terminal, and
897/// hands back the same terminal for descriptor 0.
898///
899/// Called by [`crate::exec::launch_main`] when the plan says the command is to
900/// have a terminal, and called there rather than here because it must happen in
901/// the process that is about to *become* the command: a controlling terminal, like
902/// the fence, is inherited across `exec` and cannot be given to somebody else's
903/// child.
904///
905/// Three steps and each is necessary:
906///
907/// * `setsid` puts this process in a session of its own with no controlling
908/// terminal. Without it `TIOCSCTTY` fails, because only a session leader may
909/// claim a terminal. It also makes this process a group leader, which is why
910/// the hand does not ask for a process group when it spawns the launcher --
911/// `setsid` would then fail with `EPERM`.
912/// * `TIOCSCTTY` claims the terminal. The kernel makes this process's group the
913/// terminal's foreground group as it does so, which is what makes `Ctrl-C`
914/// reach the command: the line discipline signals the foreground group, and a
915/// shell that starts a job moves that group to the job.
916/// * Descriptor 0 is still the pipe the plan arrived on, so the terminal is
917/// duplicated for it. Descriptors 1 and 2 are already the terminal.
918///
919/// It runs **before** the fence is applied. Nothing here needs a grant that way,
920/// so a session's fence does not have to include the machinery that built it.
921///
922/// # Returns
923/// What the command's standard input should be.
924pub fn adopt_terminal() -> Outcome<Stdio> {
925 let out = std::io::stdout();
926 if !rustix::termios::isatty(&out) {
927 return Err(err!(
928 "The plan says this command is to have a terminal, and the descriptor the hand \
929 provided is not one. Nothing was run.";
930 Invalid, Input, Bug));
931 }
932 res!(rustix::process::setsid().map_err(|e| err!(e,
933 "This process could not start a session of its own, so it cannot own a terminal.";
934 IO, System)));
935 res!(rustix::process::ioctl_tiocsctty(&out).map_err(|e| err!(e,
936 "The terminal would not become this process's controlling terminal, so Ctrl-C would \
937 reach nothing and /dev/tty could not be opened.";
938 IO, System)));
939 let dup = res!(out.as_fd().try_clone_to_owned().map_err(|e| err!(e,
940 "The terminal could not be duplicated onto standard input."; IO, System)));
941 Ok(Stdio::from(dup))
942}
943
944// ┌───────────────────────────────────────────────────────────────┐
945// │ Supervision │
946// └───────────────────────────────────────────────────────────────┘
947
948/// Everything the supervisor needs that is not the terminal or the child.
949struct Watch {
950 /// The caller's identifier.
951 id: String,
952 /// The child's process group, which is its process id.
953 pgid: u32,
954 /// The shared registry, so the session can forget itself when it ends.
955 live: Arc<Mutex<HashMap<String, PtySession>>>,
956 /// Where responses go.
957 tx: Sender<Resp>,
958 /// The session's private temporary directory, removed by the one piece of
959 /// code that sees every way a session can end.
960 scratch: Option<Scratch>,
961}
962
963/// Watches one session to its end and sends the closing [`crate::wire::Resp::Closed`].
964///
965/// # Arguments
966/// * `watch` - The session's identity and outputs.
967/// * `child` - The spawned launcher, which has become the command.
968/// * `master` - The hand's end of the terminal.
969/// * `words` - Keystrokes, resizes and the order to stop.
970/// * `wordtx` - A live sender, kept so the receiver never reports closure and so
971/// the reader can ask for the session to end.
972async fn watch(
973 mut watch: Watch,
974 mut child: Child,
975 master: OwnedFd,
976 mut words: Receiver<Word>,
977 wordtx: Sender<Word>,
978)
979 -> Outcome<()>
980{
981 // Two descriptors on one terminal: the reader owns one and this task owns the
982 // other. That is what lets a session whose output nobody is taking still be
983 // resized and still be killed -- a single task doing both would be waiting on
984 // the channel with the keystrokes unread behind it.
985 let for_read = res!(master.try_clone().map_err(|e| err!(e,
986 "The terminal could not be duplicated for reading."; IO, System)));
987 let read_fd = res!(AsyncFd::new(File::from(for_read)).map_err(|e| err!(e,
988 "The terminal could not be watched for output."; IO, System)));
989 let write_fd = res!(AsyncFd::new(File::from(master)).map_err(|e| err!(e,
990 "The terminal could not be watched for input."; IO, System)));
991
992 let mut reader: JoinHandle<()> = tokio::spawn(read_out(
993 read_fd, watch.id.clone(), watch.tx.clone(), wordtx.clone()));
994
995 let mut stopped = false;
996 let mut degraded: Option<String> = None;
997
998 let status = loop {
999 tokio::select! {
1000 r = child.wait() => break r,
1001 w = words.recv() => {
1002 match w {
1003 Some(Word::Type(bytes)) => {
1004 match timeout(
1005 Duration::from_millis(TYPE_GRACE_MS),
1006 type_in(&write_fd, &bytes)).await
1007 {
1008 Ok(Ok(())) => (),
1009 Ok(Err(e)) => {
1010 let _ = watch.tx.send(Resp::Error {
1011 id: Some(watch.id.clone()),
1012 message: fmt!(
1013 "What was typed did not reach the terminal. {}",
1014 e.msgs().join(" ")),
1015 }).await;
1016 },
1017 Err(_) => {
1018 let _ = watch.tx.send(Resp::Error {
1019 id: Some(watch.id.clone()),
1020 message: fmt!(
1021 "The program has not read its terminal for {} ms and the \
1022 terminal's own buffer is full, so {} bytes of what was \
1023 typed were dropped. The session is still open.",
1024 TYPE_GRACE_MS, bytes.len()),
1025 }).await;
1026 },
1027 }
1028 },
1029 Some(Word::Size(size)) => {
1030 if let Err(e) = set_winsize(write_fd.get_ref(), size) {
1031 let _ = watch.tx.send(Resp::Error {
1032 id: Some(watch.id.clone()),
1033 message: fmt!(
1034 "The terminal could not be resized, so the program still \
1035 believes it has the size it had. {}", e.msgs().join(" ")),
1036 }).await;
1037 }
1038 },
1039 Some(Word::Spent(why)) => {
1040 let _ = watch.tx.send(Resp::Error {
1041 id: Some(watch.id.clone()),
1042 message: why,
1043 }).await;
1044 stopped = true;
1045 sweep(watch.pgid, &mut degraded).await;
1046 let _ = child.start_kill();
1047 },
1048 Some(Word::Stop) | None => {
1049 stopped = true;
1050 // The group and not the child: a shell's own children are
1051 // what a terminal session is made of, and killing only the
1052 // shell leaves them holding the terminal open.
1053 sweep(watch.pgid, &mut degraded).await;
1054 let _ = child.start_kill();
1055 },
1056 }
1057 },
1058 }
1059 };
1060
1061 // The command has gone. Anything it started is still running, and this is
1062 // where that ends: a session must not leave processes behind it. Swept again
1063 // even when it was swept on the way in, because the first sweep raced with
1064 // whatever the shell was starting at the time. The reader is then given a
1065 // moment to take what is still in the terminal's buffer before it is
1066 // abandoned.
1067 sweep(watch.pgid, &mut degraded).await;
1068 if timeout(Duration::from_millis(DRAIN_GRACE_MS), &mut reader).await.is_err() {
1069 reader.abort();
1070 }
1071
1072 if let Some(why) = &degraded {
1073 let _ = watch.tx.send(Resp::Error {
1074 id: Some(watch.id.clone()),
1075 message: fmt!(
1076 "The signal reached the command itself but not the process group it leads, so \
1077 anything it had started may still be running. {}", why),
1078 }).await;
1079 }
1080
1081 // Forgotten before it is announced, so that a keystroke arriving after the
1082 // announcement is answered `Finished` rather than sent nowhere.
1083 {
1084 let mut g = lock_mutex!(watch.live);
1085 g.remove(&watch.id);
1086 }
1087
1088 if let Some(mut s) = watch.scratch.take() {
1089 if let Err(e) = s.remove() {
1090 let _ = watch.tx.send(Resp::Error {
1091 id: Some(watch.id.clone()),
1092 message: fmt!(
1093 "The session's private temporary directory could not be removed, so what it \
1094 wrote there is still on this machine. {}", e.msgs().join(" ")),
1095 }).await;
1096 }
1097 }
1098
1099 let (exit, killed) = match &status {
1100 Ok(st) => match st.code() {
1101 Some(c) => (c, stopped),
1102 // No exit code means a signal ended it, which is the ordinary way a
1103 // terminal's Ctrl-C ends a program and is exactly what the page needs
1104 // to be able to tell apart from the program's own decision to stop.
1105 None => (-1, true),
1106 },
1107 Err(_) => (-1, stopped),
1108 };
1109
1110 if watch.tx.send(Resp::Closed { id: watch.id.clone(), exit, killed }).await.is_err() {
1111 return Err(err!(
1112 "The page stopped listening before '{}' could be closed off.", watch.id;
1113 Channel, IO));
1114 }
1115
1116 if let Err(e) = status {
1117 return Err(err!(e, "Waiting on '{}' failed.", watch.id; IO));
1118 }
1119 Ok(())
1120}
1121
1122/// Kills everything in a session, and not merely the group its leader leads.
1123///
1124/// The distinction is the whole of this function, and it was found by a test
1125/// rather than reasoned about in advance. A terminal is what makes job control
1126/// work, and job control means the shell puts **each job in a process group of
1127/// its own**: `sleep 60 &` typed at a session leaves a process the leader's group
1128/// does not contain. Signalling that one group -- which is what
1129/// [`crate::exec`] does, correctly, for a piped run where no job control exists
1130/// -- left the `sleep` running after the page had been told the session had
1131/// closed. Closing the terminal does not help either: the kernel hangs up the
1132/// *foreground* group, and a background job is by definition not it.
1133///
1134/// So every group in the session is signalled. The session is read from `/proc`,
1135/// which the hand may do because the hand is not the fenced thing; where there is
1136/// no `/proc` the leader's own group is still signalled, and that is the same
1137/// guarantee the pipe path gives.
1138///
1139/// # Arguments
1140/// * `sid` - The session, whose id is the process id the launcher was given.
1141/// * `degraded` - Where the first failure to signal is kept.
1142async fn sweep(sid: u32, degraded: &mut Option<String>) {
1143 // The leader's own group first: it is the common case, and it stops the
1144 // shell starting anything else while the rest is being worked out.
1145 note(degraded, timeout(
1146 Duration::from_millis(KILL_GRACE_MS),
1147 signal_group(sid, Sig::Kill)).await);
1148
1149 for pgid in session_groups(sid) {
1150 if pgid == sid || pgid == 0 {
1151 continue;
1152 }
1153 note(degraded, timeout(
1154 Duration::from_millis(KILL_GRACE_MS),
1155 signal_group(pgid, Sig::Kill)).await);
1156 }
1157}
1158
1159/// Every distinct process group in a session, according to `/proc`.
1160///
1161/// The fourth and sixth fields of `stat` are the group and the session, and both
1162/// are read from after the last `)` because the second field is the executable's
1163/// name and may contain brackets, spaces and anything else a file name may.
1164///
1165/// A process that ends while the directory is being read is skipped rather than
1166/// reported: this is a best effort by construction, which is why the caller
1167/// signals the leader's group whatever this returns.
1168///
1169/// # Arguments
1170/// * `sid` - The session to look for.
1171fn session_groups(sid: u32) -> Vec<u32> {
1172 let dir = match std::fs::read_dir("/proc") {
1173 Ok(d) => d,
1174 Err(_) => return Vec::new(), // No /proc: the leader's group is all there is.
1175 };
1176 let mut found = Vec::new();
1177 for entry in dir.flatten() {
1178 let name = entry.file_name();
1179 if !name.to_string_lossy().chars().all(|c| c.is_ascii_digit()) {
1180 continue;
1181 }
1182 let stat = match std::fs::read_to_string(entry.path().join("stat")) {
1183 Ok(s) => s,
1184 Err(_) => continue, // It ended while we were looking at it.
1185 };
1186 let tail = match stat.rsplit_once(')') {
1187 Some((_, t)) => t,
1188 None => continue,
1189 };
1190 // What follows the name is: state, parent, group, session.
1191 let mut fields = tail.split_whitespace().skip(2);
1192 let pgrp = match fields.next().and_then(|f| f.parse::<u32>().ok()) {
1193 Some(v) => v,
1194 None => continue,
1195 };
1196 let sess = match fields.next().and_then(|f| f.parse::<u32>().ok()) {
1197 Some(v) => v,
1198 None => continue,
1199 };
1200 if sess == sid && !found.contains(&pgrp) {
1201 found.push(pgrp);
1202 }
1203 }
1204 found
1205}
1206
1207/// Keeps the first thing that went wrong with a group signal, if anything did.
1208///
1209/// # Arguments
1210/// * `slot` - Where the explanation is kept.
1211/// * `got` - What the attempt returned, or `Err` if it ran out of time.
1212fn note(
1213 slot: &mut Option<String>,
1214 got: Result<Signalling, tokio::time::error::Elapsed>,
1215) {
1216 if slot.is_some() {
1217 return;
1218 }
1219 *slot = match got {
1220 Ok(Signalling::Sent) => None,
1221 // A group that is already gone is the ORDINARY case, not a degradation: a session
1222 // usually ends because the shell exited, and by the time the sweep runs there is
1223 // nothing left to signal. Reported as a fault, it told the page a clean `exit` had
1224 // failed to stop something -- which is both untrue and the opposite of reassuring.
1225 Ok(Signalling::Degraded(why)) if gone(&why) => None,
1226 Ok(Signalling::Unavailable(why)) if gone(&why) => None,
1227 Ok(Signalling::Degraded(why)) => Some(why),
1228 Ok(Signalling::Unavailable(why)) => Some(why),
1229 Err(_) => Some(fmt!(
1230 "The kill helper did not finish within {} ms and was given up on.", KILL_GRACE_MS)),
1231 };
1232}
1233
1234/// Whether a failure to signal means the target had already finished.
1235///
1236/// `kill` says so in words rather than by exit code, and the words differ between util-linux
1237/// and BusyBox, so both spellings of the one condition are matched. Anything else is a real
1238/// failure and is kept.
1239///
1240/// # Arguments
1241/// * `why` - What the signal attempt reported.
1242fn gone(why: &str) -> bool {
1243 let w = why.to_ascii_lowercase();
1244 w.contains("no such process") || w.contains("esrch")
1245}
1246
1247/// Reads the terminal to its end, emitting bounded, sequenced, base64 output.
1248///
1249/// Nothing is decoded and nothing is held back: every byte the terminal produced
1250/// is forwarded as it was produced. The wait for room on the channel is the
1251/// terminal's own back pressure and is left in place deliberately -- a program
1252/// writing faster than the far end can draw is made to wait by the pty, which is
1253/// what every terminal since the teletype has done, and is better than a screen
1254/// drawn from bytes with a hole in them.
1255///
1256/// # Arguments
1257/// * `fd` - The hand's end of the terminal.
1258/// * `id` - The caller's identifier.
1259/// * `tx` - Where output is sent.
1260/// * `words` - The line to the supervisor, used only to end a runaway session.
1261async fn read_out(
1262 fd: AsyncFd<File>,
1263 id: String,
1264 tx: Sender<Resp>,
1265 words: Sender<Word>,
1266) {
1267 let mut buf = vec![0u8; READ_MAX];
1268 let mut seq = 0u64;
1269 let mut spent = 0u64;
1270
1271 loop {
1272 let mut guard = match fd.readable().await {
1273 Ok(g) => g,
1274 Err(_) => return,
1275 };
1276 let got = match guard.try_io(|f| (&*f.get_ref()).read(&mut buf)) {
1277 Ok(Ok(0)) => return, // The terminal is closed.
1278 Ok(Ok(n)) => n,
1279 // EIO on a master is not a fault: it is what the kernel says when the
1280 // last descriptor on the other end has gone, which is how the end of
1281 // a session announces itself.
1282 Ok(Err(_)) => return,
1283 Err(_) => {
1284 guard.clear_ready();
1285 continue;
1286 },
1287 };
1288
1289 spent += got as u64;
1290 if spent > SESSION_OUTPUT_MAX {
1291 let _ = words.try_send(Word::Spent(fmt!(
1292 "This terminal has produced {} bytes, which is more than the {} one session may \
1293 send, and it is being closed. Output was not truncated: a terminal drawn from \
1294 bytes with a hole in them is wrong from that point on, so the session ends \
1295 instead. Whatever is producing this much output wants Exec, not a terminal.",
1296 spent, SESSION_OUTPUT_MAX)));
1297 return;
1298 }
1299
1300 let msg = Resp::Output {
1301 id: fmt!("{}", id),
1302 seq,
1303 data: base64::encode(&buf[..got]),
1304 };
1305 if tx.send(msg).await.is_err() {
1306 return; // The page stopped listening; the supervisor will notice.
1307 }
1308 seq += 1;
1309 }
1310}
1311
1312/// Writes every byte of `bytes` to the terminal, however many turns it takes.
1313///
1314/// # Arguments
1315/// * `fd` - The hand's end of the terminal.
1316/// * `bytes` - What was typed.
1317async fn type_in(fd: &AsyncFd<File>, bytes: &[u8]) -> Outcome<()> {
1318 let mut at = 0usize;
1319 while at < bytes.len() {
1320 let mut guard = res!(fd.writable().await.map_err(|e| err!(e,
1321 "The terminal could not be waited on for room."; IO)));
1322 match guard.try_io(|f| (&*f.get_ref()).write(&bytes[at..])) {
1323 Ok(Ok(0)) => return Err(err!(
1324 "The terminal took none of the {} bytes still to be typed.", bytes.len() - at;
1325 IO, Write)),
1326 Ok(Ok(n)) => at += n,
1327 Ok(Err(e)) => return Err(err!(e,
1328 "The terminal would not take what was typed."; IO, Write)),
1329 Err(_) => guard.clear_ready(),
1330 }
1331 }
1332 Ok(())
1333}
1334
1335// ┌───────────────────────────────────────────────────────────────┐
1336// │ Tests │
1337// └───────────────────────────────────────────────────────────────┘
1338
1339#[cfg(test)]
1340mod tests {
1341 use super::*;
1342
1343 use crate::exec::launch_main;
1344
1345 use std::path::{
1346 Path,
1347 PathBuf,
1348 };
1349
1350 use tokio::sync::mpsc::Receiver as RespRx;
1351
1352 // ── Becoming the launcher ───────────────────────────────────────
1353 //
1354 // As in `exec`: every session here is really fenced, by the real
1355 // `launch_main`, in a real second process, because the test binary can be
1356 // made to re-enter itself. `/proc/self/exe` here is libtest, whose `main`
1357 // will not dispatch `LAUNCH_ARG`, so the launcher is invoked as "run exactly
1358 // the test named below" and that test calls `launch_main`.
1359 //
1360 // One artefact, and it is louder here than there: libtest announces itself on
1361 // standard output before reaching the test, and standard output is the
1362 // terminal, so every session opens with that announcement -- with its
1363 // newlines turned into carriage-return line-feed pairs by the terminal's own
1364 // output processing, which is itself a small proof that a terminal is what
1365 // this is. The tests therefore look for what they expect inside the output
1366 // rather than at the whole of it.
1367
1368 /// The environment name that turns a copy of the test binary into a launcher.
1369 const LAUNCH_CHILD: &str = "DAIMOND_HAND_TEST_PTY_LAUNCHER";
1370
1371 /// The launcher entry point, reached only in a re-executed test binary.
1372 #[test]
1373 fn launcher_child_entry() {
1374 if std::env::var(LAUNCH_CHILD).is_err() {
1375 return;
1376 }
1377 launch_main()
1378 }
1379
1380 /// A launcher that re-enters this test binary at [`launcher_child_entry`].
1381 fn test_launcher() -> Outcome<Launcher> {
1382 let exe = res!(std::env::current_exe().map_err(|e| err!(e,
1383 "The launcher tests need to know their own binary."; Test, IO)));
1384 Ok(Launcher::Explicit {
1385 prog: exe,
1386 args: vec![
1387 fmt!("pty::tests::launcher_child_entry"),
1388 fmt!("--exact"),
1389 fmt!("--nocapture"),
1390 fmt!("--test-threads=1"),
1391 ],
1392 env: vec![(fmt!("{}", LAUNCH_CHILD), fmt!("1"))],
1393 })
1394 }
1395
1396 /// A registry whose launcher is this test binary.
1397 fn sessions() -> Outcome<PtySessions> {
1398 Ok(PtySessions::with_launcher(res!(test_launcher())))
1399 }
1400
1401 /// A directory that certainly exists and that the tests never write to.
1402 fn root() -> String {
1403 fmt!("{}", env!("CARGO_MANIFEST_DIR"))
1404 }
1405
1406 /// A fence that permits the crate's own directory and nothing else.
1407 fn fence_here() -> crate::wire::FenceSpec {
1408 crate::wire::FenceSpec {
1409 rw: vec![root()],
1410 ro: Vec::new(),
1411 deny: Vec::new(),
1412 net: false,
1413 }
1414 }
1415
1416 /// A workspace with something in it, and something outside it.
1417 ///
1418 /// Under the home cache and never `/tmp`: that is a tmpfs here, and filling it
1419 /// has taken this machine down before.
1420 ///
1421 /// # Arguments
1422 /// * `name` - A name unique to the calling test.
1423 fn fixture(name: &str) -> Outcome<PathBuf> {
1424 let home = match std::env::var("HOME") {
1425 Ok(h) => h,
1426 Err(e) => return Err(err!(e,
1427 "The pty tests need HOME to know where to put fixtures."; Test, Configuration)),
1428 };
1429 let base = PathBuf::from(home).join(".cache/daimond-hand-pty-tests").join(name);
1430 let _ = std::fs::remove_dir_all(&base);
1431 res!(std::fs::create_dir_all(base.join("ws")));
1432 res!(std::fs::create_dir_all(base.join("outside")));
1433 res!(std::fs::write(base.join("ws/inside.txt"), "INSIDE-THE-FENCE"));
1434 res!(std::fs::write(base.join("outside/other.txt"), "OUTSIDE-THE-FENCE"));
1435 Ok(res!(base.canonicalize()))
1436 }
1437
1438 /// An `Open` request with the fields the tests vary and sensible rest.
1439 ///
1440 /// # Arguments
1441 /// * `id` - The session's identifier.
1442 /// * `argv` - The program and its arguments.
1443 fn open(id: &str, argv: &[&str]) -> Req {
1444 Req::Open {
1445 id: fmt!("{}", id),
1446 argv: argv.iter().map(|a| fmt!("{}", a)).collect(),
1447 cwd: root(),
1448 env: Vec::new(),
1449 size: PtySize { cols: 80, rows: 24 },
1450 fence: fence_here(),
1451 toolkits: Vec::new(),
1452 }
1453 }
1454
1455 /// The same, in a workspace of its own.
1456 ///
1457 /// # Arguments
1458 /// * `id` - The session's identifier.
1459 /// * `argv` - The program and its arguments.
1460 /// * `ws` - The workspace, which is the whole of the fence.
1461 fn open_in(id: &str, argv: &[&str], ws: &Path) -> Req {
1462 Req::Open {
1463 id: fmt!("{}", id),
1464 argv: argv.iter().map(|a| fmt!("{}", a)).collect(),
1465 cwd: fmt!("{}", ws.display()),
1466 env: Vec::new(),
1467 size: PtySize { cols: 80, rows: 24 },
1468 fence: crate::wire::FenceSpec {
1469 rw: vec![fmt!("{}", ws.display())],
1470 ro: Vec::new(),
1471 deny: Vec::new(),
1472 net: false,
1473 },
1474 toolkits: Vec::new(),
1475 }
1476 }
1477
1478 /// Everything a session said, until it closed or the patience ran out.
1479 ///
1480 /// # Arguments
1481 /// * `rx` - Where the session's responses arrive.
1482 /// * `ms` - How long to wait in total.
1483 async fn collect(rx: &mut RespRx<Resp>, ms: u64) -> Vec<Resp> {
1484 let mut v = Vec::new();
1485 let deadline = tokio::time::Instant::now() + Duration::from_millis(ms);
1486 loop {
1487 let left = deadline.saturating_duration_since(tokio::time::Instant::now());
1488 if left.is_zero() {
1489 return v;
1490 }
1491 match timeout(left, rx.recv()).await {
1492 Ok(Some(r)) => {
1493 let done = matches!(r, Resp::Closed { .. } | Resp::Refused { .. });
1494 v.push(r);
1495 if done {
1496 return v;
1497 }
1498 },
1499 Ok(None) => return v,
1500 Err(_) => return v,
1501 }
1502 }
1503 }
1504
1505 /// Every byte the terminal produced, in order, base64 decoded.
1506 ///
1507 /// # Arguments
1508 /// * `rs` - Everything the session said.
1509 fn bytes_of(rs: &[Resp]) -> Outcome<Vec<u8>> {
1510 let mut out = Vec::new();
1511 let mut want = 0u64;
1512 for r in rs {
1513 if let Resp::Output { seq, data, .. } = r {
1514 assert_eq!(*seq, want, "the output sequence skipped a number");
1515 want += 1;
1516 out.extend_from_slice(&res!(base64::decode(data)));
1517 }
1518 }
1519 Ok(out)
1520 }
1521
1522 /// The same, as lossy text, for the tests that look for a word.
1523 ///
1524 /// # Arguments
1525 /// * `rs` - Everything the session said.
1526 fn text_of(rs: &[Resp]) -> Outcome<String> {
1527 Ok(String::from_utf8_lossy(&res!(bytes_of(rs))).to_string())
1528 }
1529
1530 /// The closing message.
1531 ///
1532 /// # Arguments
1533 /// * `rs` - Everything the session said.
1534 fn closed(rs: &[Resp]) -> Option<(i32, bool)> {
1535 for r in rs {
1536 if let Resp::Closed { exit, killed, .. } = r {
1537 return Some((*exit, *killed));
1538 }
1539 }
1540 None
1541 }
1542
1543 /// Types text at a session, as the page would.
1544 ///
1545 /// # Arguments
1546 /// * `s` - The registry.
1547 /// * `id` - The session.
1548 /// * `text` - What to type.
1549 fn typed(s: &PtySessions, id: &str, text: &str) -> Outcome<Reached> {
1550 s.input(id, &base64::encode(text.as_bytes()))
1551 }
1552
1553 /// A shell session, opened and ready to be typed at.
1554 ///
1555 /// # Arguments
1556 /// * `s` - The registry.
1557 /// * `id` - The session's identifier.
1558 async fn shell(s: &PtySessions, id: &str) -> Outcome<RespRx<Resp>> {
1559 let (tx, rx) = tokio::sync::mpsc::channel::<Resp>(256);
1560 match res!(s.open(open(id, &["/bin/sh"]), tx).await) {
1561 Opening::Opened(_) => Ok(rx),
1562 Opening::Refused => Err(err!(
1563 "The shell session was refused."; Test, Unexpected)),
1564 }
1565 }
1566
1567 // ── 1. A program that asks the kernel gets the right answer ─────
1568
1569 /// The whole reason this module exists.
1570 ///
1571 /// `test -t 0` asks the kernel, not the hand, and the shell only answers yes
1572 /// when standard input really is a terminal.
1573 ///
1574 /// **The marker is composed by the shell and never typed.** A terminal
1575 /// echoes what is typed at it, so a test looking for a word it had just sent
1576 /// finds its own keystrokes and passes with the program removed entirely.
1577 /// The first draft of this test did exactly that, and the broken-case run is
1578 /// what found it: with the controlling terminal taken away, it still passed.
1579 /// Expanding `$t` is the fix -- `REAL-TTY` exists only in what the program
1580 /// wrote.
1581 #[tokio::test]
1582 async fn test_the_program_really_has_a_terminal() -> Outcome<()> {
1583 let s = res!(sessions());
1584 let mut rx = res!(shell(&s, "t1").await);
1585 res!(typed(&s, "t1", "t=REAL; test -t 0 && echo \"$t-TTY\"\nexit\n"));
1586 let rs = collect(&mut rx, 10_000).await;
1587 let said = res!(text_of(&rs));
1588 assert!(said.contains("REAL-TTY"),
1589 "the program did not see a terminal on its standard input: {:?}", said);
1590 Ok(())
1591 }
1592
1593 // ── 2. And it is the CONTROLLING terminal ───────────────────────
1594
1595 /// The discriminating test, and the one that fails when `setsid` or
1596 /// `TIOCSCTTY` is missed.
1597 ///
1598 /// `/dev/tty` is the kernel's name for *this process's controlling terminal*.
1599 /// A process that has none gets `ENXIO` -- "No such device or address" -- and
1600 /// with the two calls in place the write comes back around the pty, because
1601 /// `/dev/tty` and the terminal the hand is holding are the same device.
1602 ///
1603 /// Proved against the broken case: with the `TIOCSCTTY` call taken out of
1604 /// [`adopt_terminal`], the same session answers `/bin/sh: 1: cannot create
1605 /// /dev/tty: No such device or address` and says `can't access tty; job
1606 /// control turned off` on the way in. The marker is composed by the shell
1607 /// for the reason given on the test above.
1608 #[tokio::test]
1609 async fn test_the_terminal_is_the_controlling_terminal() -> Outcome<()> {
1610 let s = res!(sessions());
1611 let mut rx = res!(shell(&s, "t2").await);
1612 // Two names for the same terminal, and the session is granted both: the
1613 // magic one every program means by "my terminal", and the real one it has
1614 // in `/dev/pts`, which is what a program that reopens its own tty by name
1615 // asks for.
1616 res!(typed(&s, "t2",
1617 "t=CTTY; echo \"$t-OK\" > /dev/tty; echo \"$t-BY-NAME\" > $(tty)\nexit\n"));
1618 let rs = collect(&mut rx, 10_000).await;
1619 let said = res!(text_of(&rs));
1620 assert!(said.contains("CTTY-OK"),
1621 "the command has no controlling terminal: {:?}", said);
1622 assert!(said.contains("CTTY-BY-NAME"),
1623 "the session could not reopen its own terminal by name: {:?}", said);
1624 // The other half of the same fact, in the shell's own words: a shell
1625 // with no controlling terminal cannot do job control and says so.
1626 assert!(!said.contains("job control turned off"),
1627 "the shell could not take job control of the terminal: {:?}", said);
1628 Ok(())
1629 }
1630
1631 // ── 3. Ctrl-C ───────────────────────────────────────────────────
1632
1633 /// One byte, `0x03`, and the program stops.
1634 ///
1635 /// Nothing in the hand sends a signal here. The byte goes into the terminal,
1636 /// the line discipline recognises it as the interrupt character, and the
1637 /// kernel signals the terminal's foreground process group -- which exists only
1638 /// because the launcher claimed the terminal. A session without a controlling
1639 /// terminal swallows the byte and `sleep 30` runs to completion.
1640 #[tokio::test]
1641 async fn test_control_c_reaches_the_program() -> Outcome<()> {
1642 let s = res!(sessions());
1643 let (tx, mut rx) = tokio::sync::mpsc::channel::<Resp>(256);
1644 let opened = res!(s.open(open("t3", &["/bin/sleep", "30"]), tx).await);
1645 assert!(matches!(opened, Opening::Opened(_)), "the session did not open");
1646
1647 // Long enough that `sleep` is certainly the program on the terminal.
1648 tokio::time::sleep(Duration::from_millis(500)).await;
1649 assert_eq!(res!(s.input("t3", &base64::encode(&[0x03u8]))), Reached::Delivered);
1650
1651 let rs = collect(&mut rx, 8_000).await;
1652 let (exit, killed) = match closed(&rs) {
1653 Some(c) => c,
1654 None => return Err(err!(
1655 "Ctrl-C did not reach the program: it was still running after 8 seconds.";
1656 Test, Unexpected)),
1657 };
1658 assert_eq!(exit, -1, "a program ended by a signal has no exit code");
1659 assert!(killed, "the closing message did not say a signal ended it");
1660 Ok(())
1661 }
1662
1663 // ── 4. Resize ───────────────────────────────────────────────────
1664
1665 /// `stty size` asks the kernel how big the terminal is.
1666 ///
1667 /// Proved against the broken case: with [`set_winsize`] made a no-op the same
1668 /// session answers `24 80`, the size it opened with.
1669 #[tokio::test]
1670 async fn test_resize_is_seen_by_the_program() -> Outcome<()> {
1671 let s = res!(sessions());
1672 let mut rx = res!(shell(&s, "t4").await);
1673 assert_eq!(
1674 res!(s.resize("t4", PtySize { cols: 100, rows: 37 })),
1675 Reached::Delivered);
1676 res!(typed(&s, "t4", "stty size\nexit\n"));
1677 let rs = collect(&mut rx, 10_000).await;
1678 let said = res!(text_of(&rs));
1679 assert!(said.contains("37 100"),
1680 "the program was not told the terminal had been resized: {:?}", said);
1681 Ok(())
1682 }
1683
1684 // ── 5. Bytes, not text ──────────────────────────────────────────
1685
1686 /// Three bytes that are not UTF-8 arrive as themselves.
1687 ///
1688 /// Proved against the broken case: forwarding
1689 /// `String::from_utf8_lossy(&buf[..got])` instead of the bytes turns each of
1690 /// them into the three bytes of U+FFFD, and the assertion below fails.
1691 #[tokio::test]
1692 async fn test_output_is_byte_exact_through_base64() -> Outcome<()> {
1693 let s = res!(sessions());
1694 let (tx, mut rx) = tokio::sync::mpsc::channel::<Resp>(256);
1695 // Octal escapes, so the bytes are the program's and not the test's: 0xFF
1696 // and 0xFE are never valid UTF-8 anywhere, and 0x81 is a continuation
1697 // byte with nothing to continue.
1698 let opened = res!(s.open(
1699 open("t5", &["/usr/bin/printf", "A\\377\\376\\201Z"]), tx).await);
1700 assert!(matches!(opened, Opening::Opened(_)), "the session did not open");
1701 let rs = collect(&mut rx, 10_000).await;
1702 let raw = res!(bytes_of(&rs));
1703 let want = [b'A', 0xFF, 0xFE, 0x81, b'Z'];
1704 assert!(raw.windows(want.len()).any(|w| w == want),
1705 "the bytes did not survive the wire: {:?}", raw);
1706 Ok(())
1707 }
1708
1709 // ── 6. Lifecycle ────────────────────────────────────────────────
1710
1711 /// A session ends by itself, is reaped, and leaves the registry empty.
1712 #[tokio::test]
1713 async fn test_a_session_ends_cleanly_and_is_reaped() -> Outcome<()> {
1714 let s = res!(sessions());
1715 let (tx, mut rx) = tokio::sync::mpsc::channel::<Resp>(256);
1716 let opened = res!(s.open(open("t6", &["/bin/echo", "hello"]), tx).await);
1717 let pid = match opened {
1718 Opening::Opened(p) => p,
1719 Opening::Refused => return Err(err!(
1720 "The session was refused."; Test, Unexpected)),
1721 };
1722 assert_eq!(res!(s.pid_of("t6")), Some(pid));
1723
1724 let rs = collect(&mut rx, 10_000).await;
1725 let said = res!(text_of(&rs));
1726 // A terminal turns the program's newline into a carriage return and a
1727 // line feed. Asserted rather than tolerated: it is what tells the page it
1728 // is talking to a terminal and not a pipe.
1729 assert!(said.contains("hello\r\n"), "the terminal said {:?}", said);
1730
1731 let (exit, killed) = match closed(&rs) {
1732 Some(c) => c,
1733 None => return Err(err!("No Closed was sent."; Test, Missing)),
1734 };
1735 assert_eq!(exit, 0);
1736 assert!(!killed, "nothing signalled this session");
1737 assert_eq!(res!(s.live_count()), 0, "the session was not forgotten");
1738 assert_eq!(res!(s.pid_of("t6")), None);
1739 assert_eq!(res!(s.input("t6", &base64::encode(b"x"))), Reached::Finished);
1740 Ok(())
1741 }
1742
1743 /// `Bye` closes a session that would otherwise sit there for ever.
1744 #[tokio::test]
1745 async fn test_close_all_ends_a_waiting_session() -> Outcome<()> {
1746 let s = res!(sessions());
1747 let mut rx = res!(shell(&s, "t7").await);
1748 assert_eq!(res!(s.live_count()), 1);
1749 assert_eq!(res!(s.close_all()), 1);
1750 let rs = collect(&mut rx, 8_000).await;
1751 let (_, killed) = match closed(&rs) {
1752 Some(c) => c,
1753 None => return Err(err!(
1754 "The session was still open after close_all."; Test, Unexpected)),
1755 };
1756 assert!(killed);
1757 assert_eq!(res!(s.live_count()), 0);
1758 Ok(())
1759 }
1760
1761 /// Everything the session started goes with it.
1762 ///
1763 /// A terminal session is mostly other processes: the shell starts them, and a
1764 /// kill that reached only the shell would leave them holding the terminal
1765 /// open and running behind the page's back. The group is read out of
1766 /// `/proc` rather than inferred, and it is asserted to be more than one
1767 /// process *before* the close, so that a test which killed nothing could not
1768 /// pass by finding nothing.
1769 #[tokio::test]
1770 async fn test_a_closed_session_leaves_no_orphans() -> Outcome<()> {
1771 let s = res!(sessions());
1772 let mut rx = res!(shell(&s, "t13").await);
1773 let sid = match res!(s.pid_of("t13")) {
1774 Some(p) => p,
1775 None => return Err(err!("The session was not registered."; Test, Missing)),
1776 };
1777
1778 res!(typed(&s, "t13", "sleep 60 &\n"));
1779 // Long enough for the shell to have started it.
1780 tokio::time::sleep(Duration::from_millis(800)).await;
1781 let before = session_members(sid);
1782 assert!(before >= 2,
1783 "the session had nothing to orphan: {} processes in session {}", before, sid);
1784
1785 res!(s.close_all());
1786 let _ = collect(&mut rx, 8_000).await;
1787
1788 // The kill is delivered to the group and the reaping is init's, so a
1789 // moment is allowed for the last of it.
1790 let mut left = session_members(sid);
1791 for _ in 0..50 {
1792 if left == 0 {
1793 break;
1794 }
1795 tokio::time::sleep(Duration::from_millis(100)).await;
1796 left = session_members(sid);
1797 }
1798 assert_eq!(left, 0,
1799 "{} processes were left running in session {}", left, sid);
1800 Ok(())
1801 }
1802
1803 /// How many processes are in a session, according to `/proc`.
1804 ///
1805 /// By session and not by process group, because that is where the defect
1806 /// was: with job control on -- which is what having a terminal *means* -- a
1807 /// shell puts each job in a group of its own, so the leader's group is not
1808 /// the session and counting it would have missed the orphan.
1809 ///
1810 /// # Arguments
1811 /// * `sid` - The session to count.
1812 fn session_members(sid: u32) -> usize {
1813 let dir = match std::fs::read_dir("/proc") {
1814 Ok(d) => d,
1815 Err(_) => return 0,
1816 };
1817 let mut n = 0;
1818 for entry in dir.flatten() {
1819 let name = entry.file_name();
1820 let name = name.to_string_lossy();
1821 if !name.chars().all(|c| c.is_ascii_digit()) {
1822 continue;
1823 }
1824 let stat = match std::fs::read_to_string(entry.path().join("stat")) {
1825 Ok(s) => s,
1826 Err(_) => continue, // It ended while we were looking at it.
1827 };
1828 let tail = match stat.rsplit_once(')') {
1829 Some((_, t)) => t,
1830 None => continue,
1831 };
1832 // After the name come the state and then the parent, so the group is
1833 // the third field of what is left.
1834 if let Some(field) = tail.split_whitespace().nth(3) {
1835 if field.parse::<u32>() == Ok(sid) {
1836 n += 1;
1837 }
1838 }
1839 }
1840 n
1841 }
1842
1843 // ── 7. The fence, inside a terminal ─────────────────────────────
1844
1845 /// The one that matters most: a terminal is not a way around the compartment.
1846 ///
1847 /// Both halves are asserted in one test on purpose. A command that failed for
1848 /// any reason would satisfy the first half alone, so the same shell in the
1849 /// same session reads a file inside the fence and a file outside it, and the
1850 /// difference between the two answers is the fence and nothing else.
1851 #[tokio::test]
1852 async fn test_the_fence_holds_inside_a_terminal_session() -> Outcome<()> {
1853 let base = res!(fixture("fence"));
1854 let s = res!(sessions());
1855 let (tx, mut rx) = tokio::sync::mpsc::channel::<Resp>(256);
1856 let opened = res!(s.open(
1857 open_in("t8", &["/bin/sh"], &base.join("ws")), tx).await);
1858 assert!(matches!(opened, Opening::Opened(_)), "the session did not open");
1859
1860 res!(typed(&s, "t8", &fmt!(
1861 "cat {}\ncat {}\nexit\n",
1862 base.join("ws/inside.txt").display(),
1863 base.join("outside/other.txt").display())));
1864
1865 let rs = collect(&mut rx, 10_000).await;
1866 let said = res!(text_of(&rs));
1867 assert!(said.contains("INSIDE-THE-FENCE"),
1868 "the fence refused a file it granted: {:?}", said);
1869 assert!(!said.contains("OUTSIDE-THE-FENCE"),
1870 "a terminal session read a file outside its fence: {:?}", said);
1871 Ok(())
1872 }
1873
1874 // ── 8. Refusals ─────────────────────────────────────────────────
1875
1876 /// Two sessions cannot share an identifier.
1877 #[tokio::test]
1878 async fn test_a_second_session_cannot_take_a_live_identifier() -> Outcome<()> {
1879 let s = res!(sessions());
1880 let mut rx = res!(shell(&s, "t9").await);
1881 let (tx2, mut rx2) = tokio::sync::mpsc::channel::<Resp>(16);
1882 let again = res!(s.open(open("t9", &["/bin/sh"]), tx2).await);
1883 assert_eq!(again, Opening::Refused);
1884 match rx2.recv().await {
1885 Some(Resp::Refused { reason, .. }) => assert!(reason.starts_with("Refused: ")),
1886 other => return Err(err!(
1887 "Expected a refusal, got {:?}.", other; Test, Mismatch)),
1888 }
1889 res!(s.close_all());
1890 let _ = collect(&mut rx, 8_000).await;
1891 Ok(())
1892 }
1893
1894 /// The caller does not get to say what the terminal is, and the hand does.
1895 #[tokio::test]
1896 async fn test_term_is_the_hands_to_set() -> Outcome<()> {
1897 let s = res!(sessions());
1898 let (tx, mut rx) = tokio::sync::mpsc::channel::<Resp>(16);
1899 let req = match open("t10", &["/bin/sh"]) {
1900 Req::Open { id, argv, cwd, size, fence, .. } => Req::Open {
1901 id, argv, cwd, size, fence,
1902 env: vec![(fmt!("TERM"), fmt!("nonsense-9000"))],
1903 toolkits: Vec::new(),
1904 },
1905 other => other,
1906 };
1907 assert_eq!(res!(s.open(req, tx).await), Opening::Refused);
1908 match rx.recv().await {
1909 Some(Resp::Refused { reason, .. }) => assert!(reason.contains("TERM")),
1910 other => return Err(err!(
1911 "Expected a refusal, got {:?}.", other; Test, Mismatch)),
1912 }
1913
1914 // And the value the hand sets is the one the program sees.
1915 let (tx2, mut rx2) = tokio::sync::mpsc::channel::<Resp>(256);
1916 let opened = res!(s.open(open("t11", &["/bin/sh"]), tx2).await);
1917 assert!(matches!(opened, Opening::Opened(_)), "the session did not open");
1918 res!(typed(&s, "t11", "echo TERM-IS-$TERM\nexit\n"));
1919 let rs = collect(&mut rx2, 10_000).await;
1920 let said = res!(text_of(&rs));
1921 assert!(said.contains(&fmt!("TERM-IS-{}", TERM)),
1922 "the program was told a different terminal: {:?}", said);
1923 Ok(())
1924 }
1925
1926 /// Typing more at once than a terminal takes is an error with a sentence.
1927 #[tokio::test]
1928 async fn test_an_oversized_paste_is_refused() -> Outcome<()> {
1929 let s = res!(sessions());
1930 let mut rx = res!(shell(&s, "t12").await);
1931 let big = base64::encode(&vec![b'x'; INPUT_MAX + 1]);
1932 assert!(s.input("t12", &big).is_err(), "an oversized paste was accepted");
1933 // And a non-base64 payload is refused rather than guessed at.
1934 assert!(s.input("t12", "not base64 at all").is_err());
1935 res!(s.close_all());
1936 let _ = collect(&mut rx, 8_000).await;
1937 Ok(())
1938 }
1939
1940 /// Everything that reaches a session that has ended answers `Finished`.
1941 #[tokio::test]
1942 async fn test_a_closed_session_answers_finished() -> Outcome<()> {
1943 let s = res!(sessions());
1944 assert_eq!(res!(s.input("nobody", &base64::encode(b"x"))), Reached::Finished);
1945 assert_eq!(res!(s.resize("nobody", PtySize { cols: 80, rows: 24 })), Reached::Finished);
1946 assert_eq!(res!(s.close("nobody")), Reached::Finished);
1947 assert_eq!(res!(s.close_all()), 0);
1948 Ok(())
1949 }
1950}