Skip to main content

serialplugin_testing/
peer.rs

1//! Devices behind a real file descriptor: a TCP serial bridge and (unix) a PTY pair.
2
3use crate::{Modem, WAIT};
4use std::io::{self, ErrorKind, Read, Write};
5use std::net::{TcpListener, TcpStream};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::Arc;
8use std::thread::JoinHandle;
9use std::time::{Duration, Instant};
10
11/// How long a device-side call waits before it looks at its deadline (or stop) again.
12const POLL: Duration = Duration::from_millis(20);
13
14/// The device side of a port: a PTY master or the TCP peer.
15pub trait Io: Read + Write + Send {
16    /// Bound every read by `timeout`: it ends with `TimedOut` or `WouldBlock`.
17    fn bound_reads(&mut self, timeout: Duration) -> io::Result<()>;
18
19    /// The same for writes.
20    fn bound_writes(&mut self, timeout: Duration) -> io::Result<()>;
21
22    /// The host may open the port again after it closed it. Otherwise its end is final.
23    fn reopens(&self) -> bool {
24        false
25    }
26}
27
28impl Io for TcpStream {
29    fn bound_reads(&mut self, timeout: Duration) -> io::Result<()> {
30        self.set_read_timeout(Some(timeout))
31    }
32
33    fn bound_writes(&mut self, timeout: Duration) -> io::Result<()> {
34        self.set_write_timeout(Some(timeout))
35    }
36}
37
38#[cfg(unix)]
39impl Io for serialport::TTYPort {
40    fn bound_reads(&mut self, timeout: Duration) -> io::Result<()> {
41        Ok(serialport::SerialPort::set_timeout(self, timeout)?)
42    }
43
44    fn bound_writes(&mut self, timeout: Duration) -> io::Result<()> {
45        self.bound_reads(timeout)
46    }
47
48    fn reopens(&self) -> bool {
49        true
50    }
51}
52
53/// A TCP serial bridge: the listener and the `tcp://` path to open.
54pub fn tcp_listener() -> (TcpListener, String) {
55    let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
56    let path = format!("tcp://{}", listener.local_addr().unwrap());
57    (listener, path)
58}
59
60/// The connection the host opened to `listener` (a blocking one, as
61/// [`tcp_listener`] gives; it is blocking again afterwards).
62pub fn accept(listener: &TcpListener) -> TcpStream {
63    listener.set_nonblocking(true).unwrap();
64    let deadline = Instant::now() + WAIT;
65    let accepted = loop {
66        match listener.accept() {
67            Err(e) if e.kind() == ErrorKind::WouldBlock && Instant::now() < deadline => {
68                std::thread::park_timeout(Duration::from_millis(1));
69            }
70            other => break other,
71        }
72    };
73    listener.set_nonblocking(false).unwrap();
74    let (mut stream, _) = accepted.unwrap_or_else(|e| panic!("the host did not connect: {e}"));
75    stream.set_nonblocking(false).unwrap();
76    stream.bound_reads(POLL).unwrap();
77    stream
78}
79
80/// Read from the device side until `done` holds for everything read; panics after
81/// [`WAIT`], and at once when the host closed the connection for good.
82pub fn recv_until(io: &mut dyn Io, done: impl Fn(&[u8]) -> bool) -> Vec<u8> {
83    let deadline = Instant::now() + WAIT;
84    let mut got = Vec::new();
85    io.bound_reads(POLL).expect("the device side is open");
86    while !done(&got) {
87        let closed = match read_some(io) {
88            Got::Data(bytes) => {
89                got.extend(bytes);
90                false
91            }
92            Got::Nothing => false,
93            Got::Closed => true,
94        };
95        let text = || String::from_utf8_lossy(&got).into_owned();
96        assert!(
97            !closed || io.reopens(),
98            "the host closed the connection, got {:?}",
99            text()
100        );
101        assert!(
102            Instant::now() < deadline,
103            "the host never sent it{}, got {:?}",
104            if closed { " (the port is closed)" } else { "" },
105            text()
106        );
107        if closed {
108            std::thread::park_timeout(POLL);
109        }
110    }
111    got
112}
113
114enum Got {
115    Data(Vec<u8>),
116    /// Nothing yet.
117    Nothing,
118    /// No host on the other side.
119    Closed,
120}
121
122fn read_some(io: &mut dyn Io) -> Got {
123    let mut buf = [0; 256];
124    match io.read(&mut buf) {
125        Ok(0) => Got::Closed,
126        Ok(n) => Got::Data(buf[..n].to_vec()),
127        Err(e) if is_transient(&e) => Got::Nothing,
128        // Linux: EIO on a PTY master while no slave is open. TCP: the connection is gone.
129        Err(_) => Got::Closed,
130    }
131}
132
133fn is_transient(e: &io::Error) -> bool {
134    matches!(
135        e.kind(),
136        ErrorKind::TimedOut | ErrorKind::WouldBlock | ErrorKind::Interrupted
137    )
138}
139
140/// Run `modem` on the device side until the [`Server`] is dropped, or the host closed a
141/// connection that does not come back (a TCP bridge; a PTY is served again when it is
142/// reopened). It sets the timeouts of `io`.
143pub fn serve(mut io: Box<dyn Io>, mut modem: Modem) -> Server {
144    let stop = Arc::new(AtomicBool::new(false));
145    let stopped = stop.clone();
146    let thread = std::thread::spawn(move || {
147        if io.bound_reads(POLL).and(io.bound_writes(POLL)).is_err() {
148            return;
149        }
150        let mut reply = Vec::new();
151        while !stopped.load(Ordering::SeqCst) {
152            let closed = if reply.is_empty() {
153                match read_some(io.as_mut()) {
154                    Got::Data(bytes) => {
155                        reply = modem.feed(&bytes);
156                        false
157                    }
158                    Got::Nothing => false,
159                    Got::Closed => true,
160                }
161            } else {
162                // A host that does not read holds the modem up, it does not end it.
163                match io.write(&reply) {
164                    Ok(0) => true,
165                    Ok(n) => {
166                        reply.drain(..n);
167                        false
168                    }
169                    Err(e) => !is_transient(&e),
170                }
171            };
172            if closed && !io.reopens() {
173                return;
174            }
175            if closed {
176                // What a closed port was sent is lost.
177                reply.clear();
178                std::thread::park_timeout(POLL);
179            }
180        }
181    });
182    Server {
183        stop,
184        thread: Some(thread),
185    }
186}
187
188/// A running device thread; dropping it ends the thread.
189#[must_use = "the device is served until the Server is dropped"]
190#[derive(Debug)]
191pub struct Server {
192    stop: Arc<AtomicBool>,
193    thread: Option<JoinHandle<()>>,
194}
195
196impl Drop for Server {
197    fn drop(&mut self) {
198        self.stop.store(true, Ordering::SeqCst);
199        if let Some(thread) = self.thread.take() {
200            thread.thread().unpark();
201            let _ = thread.join();
202        }
203    }
204}
205
206/// Both ends of a pseudo terminal.
207#[cfg(unix)]
208#[derive(Debug)]
209#[non_exhaustive]
210pub struct Pty {
211    /// The device side (the master).
212    pub device: serialport::TTYPort,
213    /// The host side (the slave), open; drop it when the code under test opens `path` itself.
214    pub host: serialport::TTYPort,
215    /// The path of the host side.
216    pub path: String,
217}
218
219/// A new PTY pair.
220#[cfg(unix)]
221pub fn pty() -> Pty {
222    use serialport::SerialPort;
223    // `ptsname` is not thread-safe on macOS.
224    static PAIR: std::sync::Mutex<()> = std::sync::Mutex::new(());
225    let guard = PAIR.lock().unwrap_or_else(|e| e.into_inner());
226    let (mut device, host) = serialport::TTYPort::pair().expect("pty pair");
227    drop(guard);
228    let path = host.name().expect("slave name");
229    device.set_timeout(POLL).unwrap();
230    Pty { device, host, path }
231}