Skip to main content

serialplugin_core/port/
tcp.rs

1//! Serial-over-TCP transport: `tcp://host:port`.
2//!
3//! Talks raw bytes to a TCP serial bridge (ser2net in raw mode, ESP-Link, Moxa/USR
4//! device servers, `socat TCP-LISTEN:… /dev/ttyUSB0`). Works on every platform,
5//! including iOS, which has no local serial API. Line settings (baud, parity, …) and
6//! modem lines are stored but not sent: a raw bridge has its own port settings.
7//!
8//! TCP keepalive is on with a short idle time, so a bridge that vanished without a FIN
9//! (power cut, Wi-Fi drop) fails the next read within about
10//! `KEEPALIVE_IDLE + KEEPALIVE_RETRIES * KEEPALIVE_INTERVAL` and the hub reports
11//! `Disconnect`, instead of the port timing out quietly forever.
12// ponytail: raw TCP only; add RFC 2217 (telnet COM-PORT-OPTION) if remote line
13// control is needed.
14#[cfg(target_os = "ios")]
15use crate::serialport;
16
17use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
18use std::io::{self, Read, Write};
19use std::net::{TcpStream, ToSocketAddrs};
20use std::time::Duration;
21
22pub const TCP_SCHEME: &str = "tcp://";
23
24/// `tcp://host:port` → `host:port`, or `None` for an ordinary device path.
25pub fn tcp_address(path: &str) -> Option<&str> {
26    path.strip_prefix(TCP_SCHEME)
27}
28
29pub struct TcpSerialPort {
30    stream: TcpStream,
31    path: String,
32    baud_rate: u32,
33    data_bits: DataBits,
34    flow_control: FlowControl,
35    parity: Parity,
36    stop_bits: StopBits,
37    timeout: Duration,
38}
39
40/// Idle time before the first keepalive probe.
41const KEEPALIVE_IDLE: Duration = Duration::from_secs(10);
42/// Time between unanswered probes (whole seconds: most stacks round down).
43#[allow(dead_code)] // not settable on every stack
44const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(5);
45/// Unanswered probes before the stack drops the connection (not set on Windows,
46/// where it stays at the system's 10).
47#[allow(dead_code)] // not settable on every stack
48const KEEPALIVE_RETRIES: u32 = 3;
49
50// ponytail: keepalive only covers an idle link; a half-open link with unsent data
51// waits for the TCP retransmit timeout (TCP_USER_TIMEOUT on Linux) if that matters.
52fn enable_keepalive(stream: &TcpStream) -> io::Result<()> {
53    let ka = socket2::TcpKeepalive::new().with_time(KEEPALIVE_IDLE);
54    #[cfg(any(
55        target_os = "android",
56        target_os = "linux",
57        target_os = "macos",
58        target_os = "ios",
59        target_os = "windows"
60    ))]
61    let ka = ka.with_interval(KEEPALIVE_INTERVAL);
62    #[cfg(any(
63        target_os = "android",
64        target_os = "linux",
65        target_os = "macos",
66        target_os = "ios"
67    ))]
68    let ka = ka.with_retries(KEEPALIVE_RETRIES);
69    socket2::SockRef::from(stream).set_tcp_keepalive(&ka)
70}
71
72/// Read errors as the hub expects them: a read timeout is `TimedOut` (benign), a
73/// dead connection is a disconnect kind.
74fn map_read_error(e: io::Error) -> io::Error {
75    let kind = read_error_kind(e.kind(), e.raw_os_error(), cfg!(windows));
76    if kind == e.kind() {
77        e
78    } else {
79        io::Error::new(kind, e)
80    }
81}
82
83/// WSAENETRESET: Windows reports failed keepalive probes with it.
84const WSAENETRESET: i32 = 10052;
85
86/// The kind [`map_read_error`] gives a socket read error (`windows`: the platform's
87/// codes; a parameter so both mappings are tested on every host).
88fn read_error_kind(kind: io::ErrorKind, os_code: Option<i32>, windows: bool) -> io::ErrorKind {
89    match kind {
90        // Unix reports a read timeout as WouldBlock; serial callers expect TimedOut.
91        io::ErrorKind::WouldBlock => io::ErrorKind::TimedOut,
92        // Unix: SO_RCVTIMEO gives EAGAIN, so ETIMEDOUT here is failed keepalive probes.
93        // (Windows uses WSAETIMEDOUT for both; it reports a keepalive drop as
94        // WSAENETRESET below.)
95        io::ErrorKind::TimedOut if !windows => io::ErrorKind::ConnectionAborted,
96        _ if windows && os_code == Some(WSAENETRESET) => io::ErrorKind::ConnectionReset,
97        other => other,
98    }
99}
100
101/// Socket timeouts must be non-zero.
102fn socket_timeout(t: Duration) -> Option<Duration> {
103    Some(t.max(Duration::from_millis(1)))
104}
105
106impl TcpSerialPort {
107    pub fn connect(
108        path: &str,
109        baud_rate: u32,
110        data_bits: DataBits,
111        flow_control: FlowControl,
112        parity: Parity,
113        stop_bits: StopBits,
114        timeout: Duration,
115    ) -> io::Result<Self> {
116        let addr = tcp_address(path)
117            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a tcp:// path"))?;
118        let mut last_err = io::Error::new(io::ErrorKind::NotFound, format!("{addr}: no address"));
119        // Connecting is not bounded by the (short) read timeout: allow a few seconds.
120        let connect_timeout = timeout.max(Duration::from_secs(3));
121        for sock in addr.to_socket_addrs()? {
122            match TcpStream::connect_timeout(&sock, connect_timeout) {
123                Ok(stream) => {
124                    stream.set_nodelay(true)?;
125                    // Best effort: a stack that rejects an option still connects.
126                    if let Err(e) = enable_keepalive(&stream) {
127                        crate::log_warn!("{path}: TCP keepalive not set: {e}");
128                    }
129                    stream.set_read_timeout(socket_timeout(timeout))?;
130                    stream.set_write_timeout(socket_timeout(timeout))?;
131                    return Ok(Self {
132                        stream,
133                        path: path.to_string(),
134                        baud_rate,
135                        data_bits,
136                        flow_control,
137                        parity,
138                        stop_bits,
139                        timeout,
140                    });
141                }
142                Err(e) => last_err = e,
143            }
144        }
145        Err(last_err)
146    }
147}
148
149impl Read for TcpSerialPort {
150    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
151        // Windows' recv into an empty buffer waits for data (or the timeout); unix returns 0.
152        if buf.is_empty() {
153            return Ok(0);
154        }
155        // A recv that times out on Windows may take bytes with it (about one in 100 000
156        // timeouts with plain std, and the hub's reads time out all the time). A peek takes
157        // none, and after it the read has its bytes.
158        #[cfg(windows)]
159        self.stream.peek(&mut [0]).map_err(map_read_error)?;
160        match self.stream.read(buf) {
161            // A closed socket is an unplugged device, not an empty read.
162            Ok(0) => Err(io::Error::new(
163                io::ErrorKind::UnexpectedEof,
164                "TCP serial bridge closed the connection",
165            )),
166            Err(e) => Err(map_read_error(e)),
167            ok => ok,
168        }
169    }
170}
171
172impl Write for TcpSerialPort {
173    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
174        self.stream.write(buf)
175    }
176
177    // A TcpStream has no user-space write buffer (its `flush` does nothing).
178    fn flush(&mut self) -> io::Result<()> {
179        Ok(())
180    }
181}
182
183impl SerialPort for TcpSerialPort {
184    fn name(&self) -> Option<String> {
185        Some(self.path.clone())
186    }
187
188    fn baud_rate(&self) -> serialport::Result<u32> {
189        Ok(self.baud_rate)
190    }
191
192    fn data_bits(&self) -> serialport::Result<DataBits> {
193        Ok(self.data_bits)
194    }
195
196    fn flow_control(&self) -> serialport::Result<FlowControl> {
197        Ok(self.flow_control)
198    }
199
200    fn parity(&self) -> serialport::Result<Parity> {
201        Ok(self.parity)
202    }
203
204    fn stop_bits(&self) -> serialport::Result<StopBits> {
205        Ok(self.stop_bits)
206    }
207
208    fn timeout(&self) -> Duration {
209        self.timeout
210    }
211
212    fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
213        self.baud_rate = baud_rate;
214        Ok(())
215    }
216
217    fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
218        self.data_bits = data_bits;
219        Ok(())
220    }
221
222    fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
223        self.flow_control = flow_control;
224        Ok(())
225    }
226
227    fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
228        self.parity = parity;
229        Ok(())
230    }
231
232    fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
233        self.stop_bits = stop_bits;
234        Ok(())
235    }
236
237    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
238        self.stream.set_read_timeout(socket_timeout(timeout))?;
239        self.stream.set_write_timeout(socket_timeout(timeout))?;
240        self.timeout = timeout;
241        Ok(())
242    }
243
244    fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
245        Ok(())
246    }
247
248    fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
249        Ok(())
250    }
251
252    // A connected raw bridge behaves like a cable with the lines asserted.
253    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
254        Ok(true)
255    }
256
257    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
258        Ok(true)
259    }
260
261    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
262        Ok(false)
263    }
264
265    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
266        Ok(true)
267    }
268
269    fn bytes_to_read(&self) -> serialport::Result<u32> {
270        self.stream.set_nonblocking(true)?;
271        let mut buf = [0u8; 4096];
272        let pending = match self.stream.peek(&mut buf) {
273            Ok(n) => n as u32,
274            Err(e) => match e.kind() {
275                io::ErrorKind::WouldBlock => 0,
276                _ => {
277                    let _ = self.stream.set_nonblocking(false);
278                    return Err(e.into());
279                }
280            },
281        };
282        self.stream.set_nonblocking(false)?;
283        Ok(pending)
284    }
285
286    fn bytes_to_write(&self) -> serialport::Result<u32> {
287        Ok(0)
288    }
289
290    fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
291        if matches!(buffer_to_clear, ClearBuffer::Output) {
292            return Ok(());
293        }
294        // Drop whatever already arrived, without waiting for more.
295        self.stream.set_nonblocking(true)?;
296        let mut buf = [0u8; 4096];
297        let result = loop {
298            match (&self.stream).read(&mut buf) {
299                Ok(0) => break Ok(()),
300                Ok(_) => continue,
301                Err(e) => match e.kind() {
302                    io::ErrorKind::WouldBlock => break Ok(()),
303                    _ => break Err(e.into()),
304                },
305            }
306        };
307        self.stream.set_nonblocking(false)?;
308        result
309    }
310
311    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
312        Ok(Box::new(Self {
313            stream: self.stream.try_clone()?,
314            path: self.path.clone(),
315            baud_rate: self.baud_rate,
316            data_bits: self.data_bits,
317            flow_control: self.flow_control,
318            parity: self.parity,
319            stop_bits: self.stop_bits,
320            timeout: self.timeout,
321        }))
322    }
323
324    fn set_break(&self) -> serialport::Result<()> {
325        Ok(())
326    }
327
328    fn clear_break(&self) -> serialport::Result<()> {
329        Ok(())
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    //! In `src/`: the socket is private, and a dead link takes the keepalive minutes.
336    use super::*;
337    use std::net::TcpListener;
338
339    fn connect(listener: &TcpListener) -> TcpSerialPort {
340        let path = format!("tcp://{}", listener.local_addr().unwrap());
341        TcpSerialPort::connect(
342            &path,
343            115_200,
344            DataBits::Eight,
345            FlowControl::None,
346            Parity::None,
347            StopBits::One,
348            Duration::from_millis(50),
349        )
350        .unwrap()
351    }
352
353    #[test]
354    fn keepalive_is_on_with_a_short_idle() {
355        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
356        let port = connect(&listener);
357        assert_eq!(
358            port.name(),
359            Some(format!("tcp://{}", listener.local_addr().unwrap()))
360        );
361        let sock = socket2::SockRef::from(&port.stream);
362        assert!(sock.keepalive().unwrap());
363        #[cfg(unix)]
364        {
365            assert_eq!(sock.tcp_keepalive_time().unwrap(), KEEPALIVE_IDLE);
366            #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
367            assert_eq!(sock.tcp_keepalive_interval().unwrap(), KEEPALIVE_INTERVAL);
368        }
369        // A clone shares the socket, so it keeps the options.
370        let clone = port.try_clone().unwrap();
371        drop(clone);
372    }
373
374    /// Unix reports a read timeout as WouldBlock; a dead keepalive is ETIMEDOUT there
375    /// and WSAENETRESET on Windows.
376    #[test]
377    fn keepalive_timeout_reads_as_a_disconnect() {
378        use io::ErrorKind::*;
379        let timeout = map_read_error(io::Error::from(WouldBlock));
380        assert_eq!(timeout.kind(), TimedOut);
381        assert_eq!(
382            timeout.into_inner().unwrap().to_string(),
383            io::Error::from(WouldBlock).to_string()
384        );
385        #[cfg(unix)]
386        {
387            let dead = map_read_error(io::Error::from(TimedOut));
388            assert_eq!(dead.kind(), ConnectionAborted);
389        }
390        let reset = map_read_error(io::Error::from(ConnectionReset));
391        assert_eq!(reset.kind(), ConnectionReset);
392        assert!(
393            reset.get_ref().is_none(),
394            "an unmapped error is passed through as is"
395        );
396        for windows in [false, true] {
397            assert_eq!(read_error_kind(WouldBlock, None, windows), TimedOut);
398            assert_eq!(read_error_kind(Other, Some(WSAENETRESET), false), Other);
399        }
400        assert_eq!(read_error_kind(TimedOut, None, false), ConnectionAborted);
401        assert_eq!(read_error_kind(TimedOut, None, true), TimedOut);
402        assert_eq!(
403            read_error_kind(Other, Some(WSAENETRESET), true),
404            ConnectionReset
405        );
406        assert_eq!(read_error_kind(Other, Some(10053), true), Other);
407        assert_eq!(read_error_kind(Other, None, true), Other);
408    }
409}