petitcarnets 0.0.9

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
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
//! The few libc calls a terminal needs, declared by hand so the crate has
//! no dependencies. This is the only module allowed `unsafe` code.
//!
//! The `termios` structure differs between Linux and macOS (field widths
//! and the size of `c_cc`). It is never read here: it is kept as an
//! opaque, over-sized, 8-byte-aligned buffer that `tcgetattr` fills,
//! `cfmakeraw` edits and `tcsetattr` reads back, so its layout never
//! matters.
//!
//! Signals are installed with `signal(2)`, not `sigaction`, because
//! `struct sigaction` differs between glibc, musl, macOS and FreeBSD
//! while `signal` takes only a number and a function. On all four it
//! keeps the handler installed and restarts interrupted calls. Variadic C
//! functions (`ioctl`, `fcntl`) are declared variadic: Apple Silicon
//! passes variadic arguments differently from fixed ones.
#![allow(unsafe_code)] // The FFI boundary: each call's safety is argued where it is made.

#[cfg(not(target_os = "macos"))]
use std::ffi::c_short;
use std::ffi::{c_int, c_ulong, c_ushort, c_void};
use std::io;
use std::sync::OnceLock;
use std::time::{Duration, Instant};

/// Room for any platform's `termios` (60 bytes on Linux, 72 on macOS).
const TERMIOS_WORDS: usize = 32;

/// `TCSANOW`: apply the change at once, keeping unread input (0 on
/// Linux, macOS and FreeBSD alike).
const TCSANOW: c_int = 0;

/// Values that differ between the supported systems.
#[cfg(target_os = "linux")]
mod os {
    use std::ffi::{c_int, c_ulong};
    /// `TIOCGWINSZ`: read the window size.
    pub(super) const TIOCGWINSZ: c_ulong = 0x5413;
    /// `O_NONBLOCK` (the generic Linux value, as on x86 and Arm).
    pub(super) const O_NONBLOCK: c_int = 0o4000;
    /// `nfds_t`.
    pub(super) type NFds = c_ulong;
    /// `TCIFLUSH`: discard unread input.
    pub(super) const TCIFLUSH: c_int = 0;
    /// `O_CLOEXEC` (the generic Linux value, as on x86 and Arm).
    pub(super) const O_CLOEXEC: c_int = 0o2_000_000;
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
mod os {
    #[cfg(target_os = "freebsd")]
    use std::ffi::c_uint;
    use std::ffi::{c_int, c_ulong};
    /// `TIOCGWINSZ`: read the window size.
    pub(super) const TIOCGWINSZ: c_ulong = 0x4008_7468;
    /// `O_NONBLOCK`.
    pub(super) const O_NONBLOCK: c_int = 0x0004;
    /// `nfds_t`.
    #[cfg(target_os = "freebsd")]
    pub(super) type NFds = c_uint;
    /// `TCIFLUSH`: discard unread input.
    pub(super) const TCIFLUSH: c_int = 1;
    /// `O_CLOEXEC` (FreeBSD's; macOS has no `pipe2` to pass it to).
    #[cfg(target_os = "freebsd")]
    pub(super) const O_CLOEXEC: c_int = 0x0010_0000;
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "freebsd")))]
compile_error!("petitcarnets supports Linux, macOS and FreeBSD for now");
// The constants above are checked on x86-64 and 64-bit Arm only; other
// Linux architectures (MIPS, PowerPC, SPARC) use other values.
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
compile_error!("petitcarnets supports x86-64 and 64-bit Arm for now");

/// `fcntl` commands, the same on every supported system.
const F_GETFL: c_int = 3;
const F_SETFL: c_int = 4;
#[cfg(target_os = "macos")]
const F_SETFD: c_int = 2;
#[cfg(target_os = "macos")]
const FD_CLOEXEC: c_int = 1;

/// `poll` event bits, the same on every supported system.
#[cfg(not(target_os = "macos"))]
const POLLIN: c_short = 0x01;
#[cfg(not(target_os = "macos"))]
const POLLERR: c_short = 0x08;
#[cfg(not(target_os = "macos"))]
const POLLHUP: c_short = 0x10;
#[cfg(not(target_os = "macos"))]
const POLLNVAL: c_short = 0x20;

/// `EINTR`: a call interrupted by a signal (4 everywhere).
const EINTR: i32 = 4;

/// A saved terminal mode, as an opaque buffer.
#[derive(Clone, Copy)]
pub(crate) struct Termios([u64; TERMIOS_WORDS]);

#[cfg(not(test))]
impl std::fmt::Debug for Termios {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Termios(..)")
    }
}

/// In tests, the words that are set, so a failed comparison shows where.
#[cfg(test)]
impl std::fmt::Debug for Termios {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let set = self
            .settled()
            .into_iter()
            .enumerate()
            .filter(|(_, w)| *w != 0);
        f.debug_map()
            .entries(set.map(|(i, w)| (i, format!("{w:#x}"))))
            .finish()
    }
}

#[cfg(test)]
impl Termios {
    /// The words, without what the system sets on its own: macOS's
    /// kernel sets `PENDIN` (in `c_lflag`, the fourth word there) when
    /// canonical mode comes back on, to reprocess pending input.
    fn settled(&self) -> [u64; TERMIOS_WORDS] {
        let words = self.0;
        #[cfg(target_os = "macos")]
        let words = {
            const PENDIN: u64 = 0x2000_0000;
            let mut words = words;
            words[3] &= !PENDIN;
            words
        };
        words
    }
}

#[cfg(test)]
impl PartialEq for Termios {
    fn eq(&self, other: &Self) -> bool {
        self.settled() == other.settled()
    }
}

/// `struct winsize`: the same four `unsigned short`s everywhere.
#[repr(C)]
#[derive(Default)]
struct Winsize {
    rows: c_ushort,
    cols: c_ushort,
    x_pixels: c_ushort,
    y_pixels: c_ushort,
}

/// `struct pollfd`: the same layout everywhere.
#[cfg(not(target_os = "macos"))]
#[repr(C)]
struct PollFd {
    fd: c_int,
    events: c_short,
    revents: c_short,
}

unsafe extern "C" {
    fn tcgetattr(fd: c_int, termios: *mut u64) -> c_int;
    fn tcsetattr(fd: c_int, action: c_int, termios: *const u64) -> c_int;
    fn cfmakeraw(termios: *mut u64);
    fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
    fn isatty(fd: c_int) -> c_int;
    fn tcflush(fd: c_int, queue: c_int) -> c_int;
    #[cfg(target_os = "macos")]
    fn pipe(fds: *mut c_int) -> c_int;
    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    fn pipe2(fds: *mut c_int, flags: c_int) -> c_int;
    fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize;
    fn write(fd: c_int, buf: *const c_void, count: usize) -> isize;
    fn close(fd: c_int) -> c_int;
    fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
    #[cfg(not(target_os = "macos"))]
    fn poll(fds: *mut PollFd, nfds: os::NFds, timeout: c_int) -> c_int;
}

/// Standard input's file descriptor.
pub(crate) const STDIN: c_int = 0;

/// Standard output's file descriptor.
pub(crate) const STDOUT: c_int = 1;

/// `Ok(value)` when a call succeeded, else the OS error.
fn check(rc: c_int) -> io::Result<c_int> {
    if rc == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(rc)
    }
}

/// The terminal's current mode.
pub(crate) fn get_mode(fd: c_int) -> io::Result<Termios> {
    let mut t = Termios([0; TERMIOS_WORDS]);
    // SAFETY: `t.0` is a writable buffer larger than any platform's
    // `termios` and suitably aligned; `tcgetattr` writes at most one.
    check(unsafe { tcgetattr(fd, t.0.as_mut_ptr()) }).map(drop)?;
    Ok(t)
}

/// Sets the terminal's mode at once and discards unread input: for the
/// start and the end of a run. Not `TCSAFLUSH`, which first waits for
/// output to drain: with no time limit on macOS (and 300 seconds on
/// FreeBSD), a terminal that stops reading (a frozen ssh session) would
/// hold the process, raw, forever. Go's x/term sets the mode at once
/// too.
pub(crate) fn set_mode(fd: c_int, termios: &Termios) -> io::Result<()> {
    set_mode_when(fd, TCSANOW, termios)?;
    // SAFETY: `tcflush` only discards the descriptor's queued input.
    check(unsafe { tcflush(fd, os::TCIFLUSH) }).map(drop)
}

/// Sets the terminal's mode at once, keeping unread input: for handing
/// the terminal to another program and taking it back, where every byte
/// typed must reach one of them.
pub(crate) fn set_mode_now(fd: c_int, termios: &Termios) -> io::Result<()> {
    set_mode_when(fd, TCSANOW, termios)
}

/// `tcsetattr` with `action`.
fn set_mode_when(fd: c_int, action: c_int, termios: &Termios) -> io::Result<()> {
    // SAFETY: the buffer was filled by `tcgetattr` (and perhaps edited by
    // `cfmakeraw`), so it holds a valid `termios`; it outlives the call.
    check(unsafe { tcsetattr(fd, action, termios.0.as_ptr()) }).map(drop)
}

/// `mode` changed to raw: no echo, no line buffering, no signal keys,
/// no output processing; reads return after one byte.
pub(crate) fn make_raw(mode: &Termios) -> Termios {
    let mut raw = *mode;
    // SAFETY: the buffer holds a valid `termios` from `tcgetattr`;
    // `cfmakeraw` only edits its fields in place.
    unsafe { cfmakeraw(raw.0.as_mut_ptr()) };
    raw
}

/// The window's size as `(columns, rows)`.
pub(crate) fn window_size(fd: c_int) -> io::Result<(u16, u16)> {
    let mut size = Winsize::default();
    // SAFETY: `TIOCGWINSZ` writes one `struct winsize`, which `Winsize`
    // matches field for field (`repr(C)`), into a live local.
    let rc = unsafe { ioctl(fd, os::TIOCGWINSZ, &raw mut size) };
    if rc == 0 && size.cols > 0 && size.rows > 0 {
        Ok((size.cols, size.rows))
    } else {
        Err(io::Error::other("the window size is not available"))
    }
}

/// Whether `fd` is a terminal.
pub(crate) fn is_tty(fd: c_int) -> bool {
    // SAFETY: `isatty` only inspects the descriptor; any value is safe.
    unsafe { isatty(fd) == 1 }
}

/// Reads into `buf`, retrying when a signal interrupts the call; 0 means
/// end of input.
pub(crate) fn read_fd(fd: c_int, buf: &mut [u8]) -> io::Result<usize> {
    loop {
        // SAFETY: `buf` is a live, writable buffer of `buf.len()` bytes.
        let n = unsafe { read(fd, buf.as_mut_ptr().cast(), buf.len()) };
        match usize::try_from(n) {
            Ok(n) => return Ok(n),
            Err(_) => interrupted_or(io::Error::last_os_error())?,
        }
    }
}

/// Writes all of `bytes`, retrying when a signal interrupts the call.
pub(crate) fn write_all_fd(fd: c_int, mut bytes: &[u8]) -> io::Result<()> {
    while !bytes.is_empty() {
        // SAFETY: `bytes` is a live buffer of `bytes.len()` bytes.
        let n = unsafe { write(fd, bytes.as_ptr().cast(), bytes.len()) };
        match usize::try_from(n) {
            Ok(0) => return Err(io::ErrorKind::WriteZero.into()),
            Ok(n) => bytes = &bytes[n..],
            Err(_) => interrupted_or(io::Error::last_os_error())?,
        }
    }
    Ok(())
}

/// `Ok` for an interrupted call (to retry), else the error.
fn interrupted_or(err: io::Error) -> io::Result<()> {
    if err.raw_os_error() == Some(EINTR) {
        Ok(())
    } else {
        Err(err)
    }
}

/// Which of `fds` can be read without blocking (or have hung up), waiting
/// until at least one can or `timeout` passes (none are, then); `None`
/// waits as long as it takes. Interrupted waits are retried with the
/// time left.
///
/// On macOS this is `select`: macOS's `poll` does not support terminal
/// devices such as `/dev/tty` (its manual says so under BUGS).
pub(crate) fn wait_readable<const N: usize>(
    fds: [c_int; N],
    timeout: Option<Duration>,
) -> io::Result<[bool; N]> {
    #[cfg(target_os = "macos")]
    return select::wait_readable(fds, timeout.map(|t| Instant::now() + t));
    #[cfg(not(target_os = "macos"))]
    poll_readable(fds, timeout.map(|t| Instant::now() + t))
}

/// [`wait_readable`] with `poll`. A descriptor `poll` cannot watch
/// (`POLLNVAL`) is an error, not "readable": reading it would block.
#[cfg(not(target_os = "macos"))]
fn poll_readable<const N: usize>(
    fds: [c_int; N],
    deadline: Option<Instant>,
) -> io::Result<[bool; N]> {
    let mut polled = fds.map(|fd| PollFd {
        fd,
        events: POLLIN,
        revents: 0,
    });
    let count = os::NFds::try_from(N).map_err(io::Error::other)?;
    loop {
        let wait = poll_timeout(deadline);
        // SAFETY: `polled` is a live array of `N` `pollfd`s; `poll` only
        // writes their `revents`.
        let rc = unsafe { poll(polled.as_mut_ptr(), count, wait) };
        if rc >= 0 {
            break;
        }
        interrupted_or(io::Error::last_os_error())?;
    }
    if polled.iter().any(|p| p.revents & POLLNVAL != 0) {
        return Err(io::Error::other("poll cannot watch this descriptor"));
    }
    let ready = POLLIN | POLLERR | POLLHUP;
    Ok(polled.map(|p| p.revents & ready != 0))
}

/// `poll`'s timeout in milliseconds until `deadline`, rounded up so the
/// wait never ends early; -1 for none.
#[cfg(not(target_os = "macos"))]
fn poll_timeout(deadline: Option<Instant>) -> c_int {
    deadline.map_or(-1, |at| {
        let left = at.saturating_duration_since(Instant::now());
        let ms = left.as_micros().div_ceil(1000);
        c_int::try_from(ms).unwrap_or(c_int::MAX)
    })
}

/// A pipe whose write end never blocks: a signal handler or another
/// thread wakes a `poll` by writing one byte to it. Both ends close on
/// drop and are not inherited by child processes.
#[derive(Debug)]
pub(crate) struct Pipe {
    /// The end to read and poll.
    pub(crate) read: c_int,
    /// The end to write a byte to.
    pub(crate) write: c_int,
}

impl Pipe {
    /// A new pipe.
    pub(crate) fn new() -> io::Result<Self> {
        let pipe = Self::cloexec()?;
        // SAFETY: as above; `F_GETFL` takes no argument.
        let flags = check(unsafe { fcntl(pipe.write, F_GETFL) })?;
        // SAFETY: as above; `F_SETFL` takes the new flags.
        check(unsafe { fcntl(pipe.write, F_SETFL, flags | os::O_NONBLOCK) }).map(drop)?;
        Ok(pipe)
    }

    /// A pipe not inherited by child processes: atomically with `pipe2`
    /// where there is one, so a thread that forks meanwhile cannot hand
    /// it on.
    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
    fn cloexec() -> io::Result<Self> {
        let mut fds = [-1; 2];
        // SAFETY: `fds` has room for the two descriptors `pipe2` writes.
        check(unsafe { pipe2(fds.as_mut_ptr(), os::O_CLOEXEC) }).map(drop)?;
        Ok(Self {
            read: fds[0],
            write: fds[1],
        })
    }

    /// A pipe not inherited by child processes. macOS has no `pipe2`,
    /// so a thread that forks between the two calls could hand it on.
    #[cfg(target_os = "macos")]
    fn cloexec() -> io::Result<Self> {
        let mut fds = [-1; 2];
        // SAFETY: `fds` has room for the two descriptors `pipe` writes.
        check(unsafe { pipe(fds.as_mut_ptr()) }).map(drop)?;
        let pipe = Self {
            read: fds[0],
            write: fds[1],
        };
        for fd in fds {
            // SAFETY: `fd` is a descriptor this pipe owns.
            check(unsafe { fcntl(fd, F_SETFD, FD_CLOEXEC) }).map(drop)?;
        }
        Ok(pipe)
    }

    /// Closes the write end, so the read end sees end of input.
    #[cfg(test)]
    pub(crate) fn close_write(&mut self) {
        close_fd(&mut self.write);
    }
}

/// Closes `fd` once and marks it closed with -1.
fn close_fd(fd: &mut c_int) {
    if *fd >= 0 {
        // SAFETY: the caller owns `fd`; it is marked closed right after,
        // so it is never closed twice.
        let _ = unsafe { close(*fd) };
        *fd = -1;
    }
}

impl Drop for Pipe {
    fn drop(&mut self) {
        close_fd(&mut self.read);
        close_fd(&mut self.write);
    }
}

/// The wake pipe: one per process, made on first use and never closed,
/// so the signal handler can never write to a closed descriptor (or to
/// one reused for something else). A run starts by reading whatever an
/// earlier run left in it.
pub(crate) fn wake_pipe() -> io::Result<&'static Pipe> {
    static WAKE: OnceLock<Pipe> = OnceLock::new();
    if let Some(pipe) = WAKE.get() {
        return Ok(pipe);
    }
    let pipe = Pipe::new()?;
    Ok(WAKE.get_or_init(|| pipe))
}

/// Signals: watching them, and stopping the process group.
mod signal;
pub(crate) use signal::{default_stop, signo, stop_process_group, unwatch_signals, watch_signals};

/// `wait_readable` with `select`, for macOS.
#[cfg(target_os = "macos")]
mod select;

/// A test pseudo-terminal, opened with the POSIX calls.
#[cfg(test)]
mod pty;
#[cfg(test)]
pub(crate) use pty::open_pty;

#[cfg(test)]
mod tests;