rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! One shell under a pseudo-terminal (portable-pty: a pty on Unix, ConPTY
//! on Windows), relayed to its host stream.
//!
//! Reads, writes and waiting for the shell block, so a thread of its own
//! does each: the reader hands what the shell prints to [`Terminal::run`]
//! one read at a time and waits until it is taken, so while the client
//! has not read the stream's 64 KiB the reader stops, the pty fills, and
//! the program printing waits: a flood slows the shell, not the daemon.
//! The writer writes what is typed, and resizes, in the order they came.
//!
//! Closing the stream hangs up as closing a terminal does: on Unix the
//! shell and the job in the foreground hear `SIGHUP`, which a shell passes
//! to its jobs, and what is left of their groups after a grace is killed;
//! on Windows the shell is killed and its console closed, which ends what
//! is attached to it. A job that left the shell's session (`setsid`) is
//! beyond either, as it is beyond ssh's.

use std::{
    io::{Read, Write},
    path::PathBuf,
    sync::{
        atomic::{AtomicBool, Ordering},
        mpsc, Arc, Mutex, MutexGuard,
    },
    time::Duration,
};

use anyhow::{Context as _, Result};
use portable_pty::{native_pty_system, Child, ChildKiller, CommandBuilder, MasterPty, PtySize};
use rho_protocol::{methods::HOST_SHELL_INPUT_MAX_BYTES, ClientEnvironment, HostStreamWriter};
use tokio::{
    sync::{mpsc as tokio_mpsc, oneshot, OwnedSemaphorePermit, Semaphore},
    time::Instant,
};

/// The most bytes one read of the pseudo-terminal takes. Up to three reads
/// wait on top of the stream's 64 KiB (the reader's, the one handed over,
/// and the one being written to the stream), so a person interrupting a
/// flood sees up to 24 KiB more.
//
// As `crate::pty` reads; a Linux pty answered 4 KiB a read for `ls -la
// /usr/bin` (206 KB in 52 reads), so a larger buffer would rarely fill.
const READ_BYTES: usize = 8 * 1024;

/// The most bytes the writer writes at once, between which it looks
/// whether the shell's stream ended.
//
// Once the stream ended, the daemon empties the terminal's input queue,
// so a write waiting for room there completes, as long as it fits an empty
// queue: Linux's holds 4 KiB (N_TTY_BUF_SIZE), macOS's a 1 KiB line
// (MAX_CANON).
const WRITE_BYTES: usize = 512;

/// How long, all told, the drain of an exited shell waits for the terminal
/// to print more, before its stream ends without the rest. Waiting for the
/// client to read does not count.
//
// Once a bash or zsh login shell exited, its pty read EIO within 1.1 ms
// (20 runs, Linux); what still prints past this is a job the shell left,
// which ssh, too, stops relaying when the shell exits.
const EXIT_DRAIN: Duration = Duration::from_millis(100);

/// The most an exited shell's drain relays, so a job the shell left
/// flooding its terminal cannot hold the stream open.
//
// What the shell printed before it exited and the client has not read
// waits in the pty, which holds 20480 bytes (Linux, 3 runs), and in two
// reads of READ_BYTES: 36 KiB. This is a tripwire well above that.
const EXIT_DRAIN_BYTES: usize = 64 * 1024;

/// How long a hung-up shell and its foreground job have to exit on their
/// `SIGHUP`, before what is left of their groups is killed.
//
// bash and zsh login shells, with a job in the foreground and one in the
// background, exited 0.3 to 3.8 ms after it (20 runs, Linux); a job's own
// cleanup, such as vim preserving its swap file, gets the rest.
#[cfg(unix)]
const HANGUP_GRACE: Duration = Duration::from_millis(500);

/// How often the hang-up looks whether the groups it signalled still have
/// members. A shell is gone within one look (see [`HANGUP_GRACE`]).
#[cfg(unix)]
const HANGUP_POLL: Duration = Duration::from_millis(10);

/// What starts a shell.
pub(super) struct Spawn {
    pub(super) program: PathBuf,
    pub(super) args: &'static [&'static str],
    pub(super) folder: PathBuf,
    /// Its whole environment.
    pub(super) environment: ClientEnvironment,
    pub(super) columns: u16,
    pub(super) rows: u16,
}

/// How a shell's stream ended.
#[derive(Debug)]
pub(super) enum Ending {
    Exited(u32),
    /// By the signal, as the machine describes it.
    Signaled(String),
    /// The daemon lost the pseudo-terminal or the shell.
    Failed(String),
    /// The client closed its stream, or left, and the shell was hung up on.
    Closed,
}

/// The calls' handle on one running shell: where what is typed into it,
/// and its resizes, go, and what runs in its foreground.
#[derive(Clone)]
pub(super) struct Handle {
    requests: mpsc::Sender<Request>,
    /// The terminal, shared with the shell's task and its writer: where
    /// [`Self::foreground`] finds the foreground job.
    #[cfg(unix)]
    master: Shared,
    /// A permit per typed byte the writer has not written, of
    /// [`HOST_SHELL_INPUT_MAX_BYTES`]; each write's permits go back as it
    /// is written, or dropped with a writer that stopped.
    room: Arc<Semaphore>,
}

/// Input refused: `asked` bytes more than the shell's input holds unread,
/// with `queued` there.
pub(super) struct InputFull {
    pub(super) queued: u64,
    pub(super) asked: u64,
}

/// What the writer does next.
enum Request {
    Write(Vec<u8>, OwnedSemaphorePermit),
    Resize { columns: u16, rows: u16 },
}

impl Handle {
    /// Queues `bytes` for the shell, unless that would hold more than
    /// [`HOST_SHELL_INPUT_MAX_BYTES`] of its input unwritten. Never blocks.
    pub(super) fn write(&self, bytes: Vec<u8>) -> Result<(), InputFull> {
        let full = || InputFull {
            queued: u64::from(HOST_SHELL_INPUT_MAX_BYTES) - self.room.available_permits() as u64,
            asked: bytes.len() as u64,
        };
        let asked = u32::try_from(bytes.len()).map_err(|_| full())?;
        let permit = Arc::clone(&self.room)
            .try_acquire_many_owned(asked)
            .map_err(|_| full())?;
        self.send(Request::Write(bytes, permit));
        Ok(())
    }

    pub(super) fn resize(&self, columns: u16, rows: u16) {
        self.send(Request::Resize { columns, rows });
    }

    /// The name of the program in the foreground of the shell's terminal,
    /// where the machine says: its process group's leader's.
    pub(super) fn foreground(&self) -> Option<String> {
        #[cfg(unix)]
        {
            let leader = lock(&self.master).as_ref()?.process_group_leader()?;
            program_name(leader)
        }
        // A console has no foreground job.
        #[cfg(not(unix))]
        None
    }

    /// Hands `request` to the writer, which drops it once the shell is
    /// gone: the shell took it and did nothing, as the protocol says of an
    /// ended shell.
    fn send(&self, request: Request) {
        let _ = self.requests.send(request);
    }
}

/// A running shell and its threads' ends.
pub(super) struct Terminal {
    /// One read at a time from the reader thread; closed at the end of
    /// what the shell prints.
    printed: tokio_mpsc::Receiver<Vec<u8>>,
    exit: oneshot::Receiver<std::io::Result<portable_pty::ExitStatus>>,
    #[cfg(windows)]
    killer: Box<dyn ChildKiller + Send + Sync>,
    /// The shell's process id, which leads its session and group.
    #[cfg(unix)]
    pid: Option<u32>,
    /// Stops the reader and writer as the terminal drops: before
    /// `master`, which keeps the terminal's name this one's while it wakes
    /// them.
    _stop: Stop,
    /// Shared with the writer, which resizes it. Taken to close the
    /// console on Windows.
    master: Shared,
}

type Shared = Arc<Mutex<Option<Box<dyn MasterPty + Send>>>>;

fn lock(master: &Shared) -> MutexGuard<'_, Option<Box<dyn MasterPty + Send>>> {
    master
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

impl Terminal {
    /// Starts `spawn`'s program under a pseudo-terminal, and the threads
    /// that read, write and wait for it. Blocks: call it off the runtime's
    /// threads.
    pub(super) fn start(spawn: Spawn) -> Result<(Self, Handle)> {
        let Spawn {
            program,
            args,
            folder,
            environment,
            columns,
            rows,
        } = spawn;
        let pair = native_pty_system()
            .openpty(size(columns, rows))
            .context("no pseudo-terminal")?;
        let reader = pair
            .master
            .try_clone_reader()
            .context("no reader of the pseudo-terminal")?;
        let writer = pair
            .master
            .take_writer()
            .context("no writer of the pseudo-terminal")?;
        let mut command = CommandBuilder::new(&program);
        command.args(args);
        command.cwd(&folder);
        command.env_clear();
        for (name, value) in environment.iter() {
            command.env(name, value);
        }
        let child = pair
            .slave
            .spawn_command(command)
            .with_context(|| format!("{} did not start", program.display()))?;
        drop(pair.slave);
        // Should a thread not start, the shell is hung up on as this drops.
        let mut started = Started(Some(child.clone_killer()));
        #[cfg(unix)]
        let pid = child.process_id();
        #[cfg(windows)]
        let killer = child.clone_killer();
        let stop = Stop {
            stopped: Arc::new(AtomicBool::new(false)),
            #[cfg(unix)]
            terminal: pair.master.tty_name(),
        };
        let master: Shared = Arc::new(Mutex::new(Some(pair.master)));
        let room = Arc::new(Semaphore::new(HOST_SHELL_INPUT_MAX_BYTES as usize));
        let printed = read_from(reader, Arc::clone(&stop.stopped))?;
        let requests = write_to(writer, Arc::clone(&master), Arc::clone(&stop.stopped))?;
        let exit = wait_for(child)?;
        started.0 = None;
        let terminal = Self {
            printed,
            exit,
            #[cfg(windows)]
            killer,
            #[cfg(unix)]
            pid,
            _stop: stop,
            master,
        };
        let handle = Handle {
            requests,
            #[cfg(unix)]
            master: Arc::clone(&terminal.master),
            room,
        };
        Ok((terminal, handle))
    }

    /// Relays what the shell prints to `output`, a read at a time as the
    /// stream has room, until the shell ends, or the client closes the
    /// stream or leaves, which hangs up on the shell. Ends the stream as
    /// the shell ended, and answers how.
    pub(super) async fn run(mut self, mut output: HostStreamWriter) -> Ending {
        let ending = match self.relay(&mut output).await {
            Some(status) => {
                self.drain(&mut output).await;
                ending_of(status)
            }
            None => {
                self.hang_up().await;
                Ending::Closed
            }
        };
        match &ending {
            Ending::Exited(code) => output.exited(*code),
            Ending::Signaled(signal) => output.signaled(signal.clone()),
            Ending::Failed(why) => output.fail(why.clone()),
            // The client closed the stream: nobody reads how it ended.
            Ending::Closed => drop(output),
        }
        ending
    }

    /// Relays what the shell prints until it exits, answering how, or the
    /// client closes the stream: `None`.
    async fn relay(
        &mut self,
        output: &mut HostStreamWriter,
    ) -> Option<Result<std::io::Result<portable_pty::ExitStatus>, oneshot::error::RecvError>> {
        loop {
            tokio::select! {
                // An exit first, so a shell the client closed as it exited
                // is not signalled once reaped, its id free for another.
                biased;
                status = &mut self.exit => return Some(status),
                () = output.closed() => return None,
                Some(bytes) = self.printed.recv() => {
                    if output.write(bytes).await.is_err() {
                        return None;
                    }
                }
            }
        }
    }

    /// Relays what the exited shell printed last: until its terminal
    /// closes, it went [`EXIT_DRAIN`] waiting for more, or it relayed
    /// [`EXIT_DRAIN_BYTES`].
    async fn drain(&mut self, output: &mut HostStreamWriter) {
        // ConPTY ends the output only once the console closes, which
        // writes out what it holds.
        #[cfg(windows)]
        close_console(&self.master);
        let mut waiting = EXIT_DRAIN;
        let mut relaying = EXIT_DRAIN_BYTES;
        while !waiting.is_zero() && relaying > 0 {
            let asked = Instant::now();
            let Ok(Some(bytes)) = tokio::time::timeout(waiting, self.printed.recv()).await else {
                return;
            };
            waiting = waiting.saturating_sub(asked.elapsed());
            relaying = relaying.saturating_sub(bytes.len());
            if output.write(bytes).await.is_err() {
                return;
            }
        }
    }

    /// Hangs up on the shell, as closing its terminal does, and kills what
    /// is left of it.
    #[cfg(unix)]
    async fn hang_up(mut self) {
        let foreground = lock(&self.master)
            .as_ref()
            .and_then(|master| master.process_group_leader())
            .and_then(|group| u32::try_from(group).ok());
        let mut groups = vec![self.pid, foreground];
        groups.dedup();
        for group in &groups {
            signal_group(*group, libc::SIGHUP);
        }
        let grace = Instant::now() + HANGUP_GRACE;
        let mut poll = tokio::time::interval(HANGUP_POLL);
        while Instant::now() < grace && groups.iter().any(|group| signal_group(*group, 0)) {
            // Reading on, so a job that prints as it hangs up is not held
            // by a full terminal.
            tokio::select! {
                Some(_) = self.printed.recv() => {}
                _ = poll.tick() => {}
            }
        }
        // Only groups that still have members: an empty one's id is free
        // for another process.
        for group in groups {
            if signal_group(group, 0) {
                signal_group(group, libc::SIGKILL);
            }
        }
    }

    /// Hangs up on the shell, as closing its console does.
    #[cfg(windows)]
    async fn hang_up(mut self) {
        let _ = self.killer.kill();
        close_console(&self.master);
    }
}

/// The name of process `pid`, as `ps` shows it: on Linux its `comm`, cut
/// to 15 bytes; on macOS its name, cut to 32. `None` for a process gone,
/// or elsewhere.
#[cfg(unix)]
fn program_name(pid: libc::pid_t) -> Option<String> {
    #[cfg(target_os = "linux")]
    {
        // Read as bytes: the cut at 15 may split a character.
        let comm = std::fs::read(format!("/proc/{pid}/comm")).ok()?;
        let comm = String::from_utf8_lossy(&comm);
        Some(comm.trim_end_matches('\n').to_owned()).filter(|name| !name.is_empty())
    }
    #[cfg(target_os = "macos")]
    {
        let mut name = [0_u8; 64];
        // SAFETY: proc_name copies the process's 32-byte name into the
        // buffer, which is longer and zeroed, so the name it measures with
        // strlen ends inside it; it answers that length, or 0 for a
        // process gone.
        let written = unsafe { libc::proc_name(pid, name.as_mut_ptr().cast(), name.len() as u32) };
        let written = usize::try_from(written)
            .ok()
            .filter(|written| *written > 0)?;
        Some(String::from_utf8_lossy(name.get(..written)?).into_owned())
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = pid;
        None
    }
}

/// Hangs up on a shell whose threads did not all start, as it drops,
/// unless they did and it was disarmed (`None`).
struct Started(Option<Box<dyn ChildKiller + Send + Sync>>);

impl Drop for Started {
    fn drop(&mut self) {
        if let Some(killer) = &mut self.0 {
            let _ = killer.kill();
        }
    }
}

/// Stops the reader and writer threads as it drops, once the shell's
/// stream ended, so they let go of their copies of the terminal: a job the
/// shell left that holds the terminal (`nohup server &`) then finds it hung
/// up, as when ssh closes it, and holds no thread of the daemon's.
struct Stop {
    /// Looked at by the threads after each read and write.
    stopped: Arc<AtomicBool>,
    /// The terminal's slave side, to wake the threads where they wait on it.
    #[cfg(unix)]
    terminal: Option<PathBuf>,
}

impl Drop for Stop {
    fn drop(&mut self) {
        self.stopped.store(true, Ordering::SeqCst);
        // On Windows the console closed, which ends both its pipes.
        #[cfg(unix)]
        if let Some(terminal) = &self.terminal {
            wake(terminal);
        }
    }
}

/// Wakes the reader, waiting for the shell to print, with a byte from the
/// terminal's slave side, and the writer, waiting for room in its input,
/// by emptying that input: both then find they are stopped.
#[cfg(unix)]
fn wake(terminal: &std::path::Path) {
    use std::os::unix::{fs::OpenOptionsExt as _, io::AsRawFd as _};

    // Without O_NOCTTY a daemon leading a session with no terminal would
    // take this one as its own; non-blocking, as nothing here may wait.
    let Ok(mut slave) = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .custom_flags(libc::O_NOCTTY | libc::O_NONBLOCK)
        .open(terminal)
    else {
        // No terminal left to wait on: the threads got its end.
        return;
    };
    // SAFETY: tcflush takes no pointers; the descriptor is open.
    unsafe { libc::tcflush(slave.as_raw_fd(), libc::TCIFLUSH) };
    // A full output queue already wakes the reader.
    let _ = slave.write(b"\0");
}

fn size(columns: u16, rows: u16) -> PtySize {
    PtySize {
        rows,
        cols: columns,
        pixel_width: 0,
        pixel_height: 0,
    }
}

/// How the shell ended, from what waiting for it answered.
fn ending_of(
    status: Result<std::io::Result<portable_pty::ExitStatus>, oneshot::error::RecvError>,
) -> Ending {
    match status {
        Ok(Ok(status)) => match status.signal() {
            Some(signal) => Ending::Signaled(signal.to_owned()),
            None => Ending::Exited(status.exit_code()),
        },
        Ok(Err(error)) => Ending::Failed(format!("waiting for the shell failed: {error}")),
        Err(_) => Ending::Failed("the thread waiting for the shell stopped".to_owned()),
    }
}

#[cfg(unix)]
use super::super::machine::signal_group;

/// Closes the console, off the runtime's threads, since ConPTY may wait
/// for its output to be read as it closes.
#[cfg(windows)]
fn close_console(master: &Shared) {
    if let Some(master) = lock(master).take() {
        tokio::task::spawn_blocking(move || drop(master));
    }
}

/// Reads what the shell prints on a thread of its own, as a read blocks,
/// handing each read over once the last was taken. On Unix the thread
/// ends at the end of the output, once the receiver is gone, or once
/// [`Stop`] stopped it. On Windows it reads on to the end, since closing a
/// console waits for its output to be read.
fn read_from(
    mut reader: Box<dyn Read + Send>,
    stopped: Arc<AtomicBool>,
) -> Result<tokio_mpsc::Receiver<Vec<u8>>> {
    let (printed, receiver) = tokio_mpsc::channel(1);
    std::thread::Builder::new()
        .name("rho-shell-read".into())
        .spawn(move || {
            let mut buffer = vec![0; READ_BYTES];
            while let Ok(read @ 1..) = reader.read(&mut buffer) {
                let gone = stopped.load(Ordering::SeqCst)
                    || printed.blocking_send(buffer[..read].to_vec()).is_err();
                if gone && !cfg!(windows) {
                    return;
                }
            }
        })
        .context("no thread to read the shell")?;
    Ok(receiver)
}

/// Writes what is typed, and resizes, in the order sent, on a thread of
/// its own, as a write blocks while the program does not read. The thread
/// ends once every sender is gone, the terminal is, or [`Stop`] stopped
/// it; what it had queued drops with it, its permits going back.
fn write_to(
    mut writer: Box<dyn Write + Send>,
    master: Shared,
    stopped: Arc<AtomicBool>,
) -> Result<mpsc::Sender<Request>> {
    let (requests, received) = mpsc::channel::<Request>();
    std::thread::Builder::new()
        .name("rho-shell-write".into())
        .spawn(move || {
            for request in received {
                match request {
                    Request::Write(bytes, _written) => {
                        for chunk in bytes.chunks(WRITE_BYTES) {
                            let written = !stopped.load(Ordering::SeqCst)
                                && writer
                                    .write_all(chunk)
                                    .and_then(|()| writer.flush())
                                    .is_ok();
                            if !written {
                                return;
                            }
                        }
                    }
                    Request::Resize { columns, rows } => {
                        if let Some(master) = lock(&master).as_ref() {
                            // A resize the terminal refuses changes nothing.
                            let _ = master.resize(size(columns, rows));
                        }
                    }
                }
            }
        })
        .context("no thread to write to the shell")?;
    Ok(requests)
}

/// Waits for the shell to exit on a thread of its own, reaping it.
fn wait_for(
    mut child: Box<dyn Child + Send + Sync>,
) -> Result<oneshot::Receiver<std::io::Result<portable_pty::ExitStatus>>> {
    let (exited, exit) = oneshot::channel();
    std::thread::Builder::new()
        .name("rho-shell-wait".into())
        .spawn(move || {
            let _ = exited.send(child.wait());
        })
        .context("no thread to wait for the shell")?;
    Ok(exit)
}

#[cfg(test)]
#[path = "terminal_tests.rs"]
mod tests;