tocat 0.2.0

A socat-inspired relay with a config file and a plugin pipeline
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
//! tty.rs: `tty:`.
//!
//! Opens a terminal that already exists, rather than allocating one the way
//! [`pty`](super::pty) does. A `/dev/pts/N` somebody else made, or a serial
//! device.
//!
//! # Why not `file:`
//!
//! Two reasons, and both are about shape rather than about the path being a
//! device.
//!
//! A terminal is duplex on one descriptor. `file:` is half-duplex by role and
//! has no spelling that opens both ways, so `file:/dev/pts/5` writes to the
//! terminal and nothing ever comes back. It also opens without `O_NOCTTY`, so
//! a relay that is a session leader without a controlling terminal acquires
//! one, and signals generated by that terminal start arriving here.
//!
//! And a terminal outlives the relay. Its settings belong to the system, so
//! raw mode has to be put back on the way out, which is what
//! [`Restore`] does and what nothing in `file:` has a place for.
//!
//! # This is where a device's line settings live
//!
//! A `/dev/ttyUSB0` at the wrong speed reads as noise rather than as an error,
//! so the settings are options here rather than something to arrange with
//! `stty` beforehand and hope survives.
//!
//! `clocal` is the one that looks like a hang instead of a mistake: without it
//! the *open* waits for carrier detect, which a three-wire cable never
//! asserts. It is on by default for that reason, and turning it off is how you
//! ask for modem control.

use std::{os::fd::OwnedFd, path::PathBuf, str::FromStr};

use anyhow::Context;
use rustix::{
    fs::{Mode, OFlags, open},
    termios::{
        ControlModes, InputModes, OptionalActions, Termios, ioctl_tiocexcl, isatty, tcgetattr,
        tcsetattr,
    },
};
use serde::{Deserialize, Serialize};
use tocat_api::normalize;
use tokio::io::unix::AsyncFd;
use tracing::{debug, warn};

use crate::endpoint::{
    Connection, EndpointStream,
    parse::{Opt, ParseEndpointError},
    pty::{Terminal, WinSize},
};

mod stream;

/// Software flow control, the `ixon`/`ixoff` pair as one option.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Flow {
    #[default]
    None,
    /// `CRTSCTS`: the two hardware lines.
    Rts,
    /// `IXON | IXOFF`: XON and XOFF bytes in the data.
    Xon,
}

impl FromStr for Flow {
    type Err = ParseEndpointError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalize(s).as_str() {
            "none" | "off" => Ok(Self::None),
            "rts" | "rtscts" | "hardware" | "hw" => Ok(Self::Rts),
            "xon" | "xonxoff" | "software" | "sw" => Ok(Self::Xon),
            _ => Err(ParseEndpointError::InvalidFlag(s.to_string())),
        }
    }
}

/// The parity bit, if there is one.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Parity {
    #[default]
    None,
    Even,
    Odd,
}

impl FromStr for Parity {
    type Err = ParseEndpointError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match normalize(s).as_str() {
            "none" | "n" => Ok(Self::None),
            "even" | "e" => Ok(Self::Even),
            "odd" | "o" => Ok(Self::Odd),
            _ => Err(ParseEndpointError::InvalidFlag(s.to_string())),
        }
    }
}

/// The line settings a serial device needs and a pts ignores.
///
/// Every field is optional in the sense that leaving it alone is a coherent
/// choice for a pts, and none of them are optional for a serial cable: a
/// device at the wrong speed produces bytes rather than an error.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Line {
    pub speed: Option<u32>,
    pub bits: u8,
    pub parity: Parity,
    /// Two stop bits rather than one.
    pub stop2: bool,
    pub flow: Flow,
    /// Ignore modem control lines. See the module docs for why this is on.
    pub clocal: bool,
}

impl Default for Line {
    fn default() -> Self {
        Self {
            speed: None,
            bits: 8,
            parity: Parity::None,
            stop2: false,
            flow: Flow::None,
            clocal: true,
        }
    }
}

impl Line {
    fn char_size(self) -> Result<ControlModes, ParseEndpointError> {
        Ok(match self.bits {
            5 => ControlModes::CS5,
            6 => ControlModes::CS6,
            7 => ControlModes::CS7,
            8 => ControlModes::CS8,
            other => return Err(ParseEndpointError::InvalidNumber(format!("bits={other}"))),
        })
    }

    /// Fold into a `Termios` already carrying the [`Terminal`] settings.
    fn apply(self, termios: &mut Termios) -> anyhow::Result<()> {
        if let Some(speed) = self.speed {
            termios
                .set_speed(speed)
                .with_context(|| format!("setting the line speed to {speed}"))?;
        }

        // `CREAD` is what makes the device readable at all, and a device found
        // with it clear is a device somebody left half configured.
        termios.control_modes.insert(ControlModes::CREAD);

        termios.control_modes.remove(ControlModes::CSIZE);
        termios
            .control_modes
            .insert(self.char_size().expect("validated at parse"));

        termios
            .control_modes
            .set(ControlModes::PARENB, !matches!(self.parity, Parity::None));
        termios
            .control_modes
            .set(ControlModes::PARODD, matches!(self.parity, Parity::Odd));
        termios.control_modes.set(ControlModes::CSTOPB, self.stop2);
        termios.control_modes.set(ControlModes::CLOCAL, self.clocal);

        termios
            .control_modes
            .set(ControlModes::CRTSCTS, self.flow == Flow::Rts);
        termios
            .input_modes
            .set(InputModes::IXON | InputModes::IXOFF, self.flow == Flow::Xon);

        Ok(())
    }
}

/// Puts a borrowed device back the way it was found.
///
/// A fresh pty is discarded when the relay ends and nothing has to be undone.
/// A device named on the command line is not: leaving `/dev/ttyUSB0` in raw
/// mode changes what the next program to open it sees, and doing it to the
/// terminal tocat was launched from leaves the shell unusable. Rides on
/// [`Connection::keepalive`], so it outlives the transfer and not the setup.
struct Restore {
    fd: OwnedFd,
    original: Termios,
}

impl Drop for Restore {
    fn drop(&mut self) {
        // Best effort by necessity: this runs during teardown, where there is
        // nobody left to report to and the device may already be gone.
        match tcsetattr(&self.fd, OptionalActions::Now, &self.original) {
            Ok(()) => debug!("terminal settings restored"),
            Err(e) => warn!(error = %e, "could not restore the terminal settings"),
        }
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Tty {
    pub path: PathBuf,
    #[serde(default)]
    pub name: Option<String>,

    /// `TIOCEXCL`, so a second unprivileged open fails with `EBUSY` rather
    /// than interleaving its reads with the relay's.
    #[serde(default)]
    pub exclusive: bool,

    // The `pty:` terminal settings, spelled out for the same reason they are
    // spelled out there: `flatten` and an internally tagged enum do not mix.
    #[serde(default = "crate::endpoint::sys::default_true")]
    pub raw: bool,
    #[serde(default)]
    pub echo: bool,
    #[serde(default)]
    pub size: Option<WinSize>,

    #[serde(default)]
    pub speed: Option<u32>,
    #[serde(default = "default_bits")]
    pub bits: u8,
    #[serde(default)]
    pub parity: Parity,
    #[serde(default)]
    pub stop2: bool,
    #[serde(default)]
    pub flow: Flow,
    #[serde(default = "crate::endpoint::sys::default_true")]
    pub clocal: bool,
}

fn default_bits() -> u8 {
    8
}

impl Tty {
    const SCHEME: &'static str = "tty";

    pub(super) fn parse<'a>(
        body: &str,
        opts: impl Iterator<Item = Opt<'a>>,
    ) -> Result<Self, ParseEndpointError> {
        if body.is_empty() {
            return Err(ParseEndpointError::Empty);
        }

        let mut name = None;
        let mut exclusive = false;
        let mut terminal = Terminal::default();
        let mut line = Line::default();

        for opt in opts {
            let key = normalize(opt.key);

            if terminal.parse_opt(&opt, key.as_str())? {
                continue;
            }

            match key.as_str() {
                "name" => name = Some(opt.string()?),
                "exclusive" | "excl" => exclusive = opt.flag()?,
                "clocal" => line.clocal = opt.flag()?,
                "flow" => line.flow = opt.text()?.parse()?,
                "parity" => line.parity = opt.text()?.parse()?,
                "stop2" => line.stop2 = opt.flag()?,
                "bits" => {
                    line.bits = opt
                        .text()?
                        .parse()
                        .map_err(|_| ParseEndpointError::InvalidNumber(opt.key.to_string()))?;
                }
                // `b115200` reads the way every other serial tool spells it,
                // and `speed=115200` reads the way every other tocat option
                // does. Both, since neither costs anything.
                "speed" | "baud" => {
                    line.speed = Some(
                        opt.text()?
                            .parse()
                            .map_err(|_| ParseEndpointError::InvalidNumber(opt.key.to_string()))?,
                    );
                }
                other
                    if other.starts_with('b')
                        && other.len() > 1
                        && other[1..].chars().all(|c| c.is_ascii_digit()) =>
                {
                    line.speed = Some(
                        other[1..]
                            .parse()
                            .map_err(|_| ParseEndpointError::InvalidNumber(opt.key.to_string()))?,
                    );
                }
                _ => return Err(opt.unsupported(Self::SCHEME)),
            }
        }

        // Rejected here rather than at open, so a typo is a parse error next
        // to the thing that caused it.
        line.char_size()?;

        Ok(Self {
            path: PathBuf::from(body),
            name,
            exclusive,
            raw: terminal.raw,
            echo: terminal.echo,
            size: terminal.size,
            speed: line.speed,
            bits: line.bits,
            parity: line.parity,
            stop2: line.stop2,
            flow: line.flow,
            clocal: line.clocal,
        })
    }

    fn terminal(&self) -> Terminal {
        Terminal {
            raw: self.raw,
            echo: self.echo,
            size: self.size,
        }
    }

    fn line(&self) -> Line {
        Line {
            speed: self.speed,
            bits: self.bits,
            parity: self.parity,
            stop2: self.stop2,
            flow: self.flow,
            clocal: self.clocal,
        }
    }

    /// A device is identified by its path, as a file is.
    pub(super) fn label(&self) -> String {
        format!("tty://{}", self.path.display())
    }

    pub(super) async fn connect(&self) -> anyhow::Result<Connection> {
        // `NOCTTY` so the relay does not acquire this terminal as its
        // controlling one; `NONBLOCK` because `AsyncFd` needs it, and because
        // without `CLOCAL` the open itself would wait on carrier.
        let fd = open(
            &self.path,
            OFlags::RDWR | OFlags::NOCTTY | OFlags::NONBLOCK,
            Mode::empty(),
        )
        .with_context(|| format!("opening {}", self.path.display()))?;

        // Refusing here is the difference between a clear error and a relay
        // that half works: `file:` would open a regular file of this name, or
        // create one.
        if !isatty(&fd) {
            anyhow::bail!("{} is not a terminal", self.path.display());
        }

        if self.exclusive {
            ioctl_tiocexcl(&fd)
                .with_context(|| format!("claiming {} exclusively", self.path.display()))?;
        }

        let original = tcgetattr(&fd).context("reading the terminal settings")?;
        let mut termios = original.clone();

        self.terminal().fill(&mut termios);
        self.line().apply(&mut termios)?;

        tcsetattr(&fd, OptionalActions::Now, &termios).context("applying the terminal settings")?;

        // Taken before the fd is consumed, and dropped after the relay ends.
        let restore = Restore {
            fd: fd.try_clone().context("duplicating the terminal")?,
            original,
        };

        self.terminal().resize(&fd)?;

        let stream = AsyncFd::new(fd).context("registering the terminal with the reactor")?;

        Ok(EndpointStream::Duplex(Box::new(stream::Stream(stream)))
            .into_connection()
            .with_keepalive(restore))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::endpoint::EndpointSpec;

    fn tty(s: &str) -> Tty {
        match s.parse::<EndpointSpec>().expect("parses") {
            EndpointSpec::Tty(e) => e,
            other => panic!("wrong variant: {other:?}"),
        }
    }

    /// Raw on, echo off, and modem control ignored: the settings that make a
    /// three-wire cable work rather than hang.
    #[test]
    fn the_defaults_suit_a_relay() {
        let e = tty("tty:/dev/ttyUSB0");

        assert!(e.raw);
        assert!(!e.echo);
        assert!(e.clocal);
        assert_eq!(e.bits, 8);
        assert_eq!(e.parity, Parity::None);
        assert_eq!(e.flow, Flow::None);
        assert_eq!(e.speed, None);
    }

    /// `b115200` is how every other serial tool spells it.
    #[test]
    fn speed_is_spelled_two_ways() {
        assert_eq!(tty("tty:/dev/ttyUSB0,b115200").speed, Some(115_200));
        assert_eq!(tty("tty:/dev/ttyUSB0,speed=115200").speed, Some(115_200));
        assert_eq!(tty("tty:/dev/ttyUSB0,baud=9600").speed, Some(9600));
    }

    #[test]
    fn the_line_settings_have_aliases_worth_having() {
        assert_eq!(tty("tty:/dev/ttyUSB0,flow=hw").flow, Flow::Rts);
        assert_eq!(tty("tty:/dev/ttyUSB0,flow=xon-xoff").flow, Flow::Xon);
        assert_eq!(tty("tty:/dev/ttyUSB0,parity=e").parity, Parity::Even);
        assert_eq!(tty("tty:/dev/ttyUSB0,parity=odd").parity, Parity::Odd);
    }

    /// A width the hardware cannot express is a parse error, not a surprise at
    /// open.
    #[test]
    fn an_impossible_character_size_is_rejected() {
        assert!("tty:/dev/ttyUSB0,bits=9".parse::<EndpointSpec>().is_err());
        assert!("tty:/dev/ttyUSB0,bits=7".parse::<EndpointSpec>().is_ok());
    }

    #[test]
    fn a_path_is_required() {
        assert!(matches!(
            "tty:".parse::<EndpointSpec>(),
            Err(ParseEndpointError::Empty)
        ));
    }

    #[test]
    fn an_option_the_scheme_does_not_take_is_an_error() {
        assert!("tty:/dev/ttyUSB0,fork".parse::<EndpointSpec>().is_err());
        assert!(
            "tty:/dev/ttyUSB0,link=/tmp/x"
                .parse::<EndpointSpec>()
                .is_err()
        );
    }
}