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    match e.kind() {
76        // Unix reports a read timeout as WouldBlock; serial callers expect TimedOut.
77        io::ErrorKind::WouldBlock => io::Error::new(io::ErrorKind::TimedOut, e),
78        // Unix: SO_RCVTIMEO gives EAGAIN, so ETIMEDOUT here is failed keepalive probes.
79        // (Windows uses WSAETIMEDOUT for both; it reports a keepalive drop as
80        // WSAENETRESET below.)
81        #[cfg(unix)]
82        io::ErrorKind::TimedOut => io::Error::new(io::ErrorKind::ConnectionAborted, e),
83        #[cfg(windows)]
84        _ if e.raw_os_error() == Some(10052) => io::Error::new(io::ErrorKind::ConnectionReset, e),
85        _ => e,
86    }
87}
88
89/// Socket timeouts must be non-zero.
90fn socket_timeout(t: Duration) -> Option<Duration> {
91    Some(t.max(Duration::from_millis(1)))
92}
93
94impl TcpSerialPort {
95    pub fn connect(
96        path: &str,
97        baud_rate: u32,
98        data_bits: DataBits,
99        flow_control: FlowControl,
100        parity: Parity,
101        stop_bits: StopBits,
102        timeout: Duration,
103    ) -> io::Result<Self> {
104        let addr = tcp_address(path)
105            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a tcp:// path"))?;
106        let mut last_err = io::Error::new(io::ErrorKind::NotFound, format!("{addr}: no address"));
107        // Connecting is not bounded by the (short) read timeout: allow a few seconds.
108        let connect_timeout = timeout.max(Duration::from_secs(3));
109        for sock in addr.to_socket_addrs()? {
110            match TcpStream::connect_timeout(&sock, connect_timeout) {
111                Ok(stream) => {
112                    stream.set_nodelay(true)?;
113                    // Best effort: a stack that rejects an option still connects.
114                    if let Err(e) = enable_keepalive(&stream) {
115                        crate::log_warn!("{path}: TCP keepalive not set: {e}");
116                    }
117                    stream.set_read_timeout(socket_timeout(timeout))?;
118                    stream.set_write_timeout(socket_timeout(timeout))?;
119                    return Ok(Self {
120                        stream,
121                        path: path.to_string(),
122                        baud_rate,
123                        data_bits,
124                        flow_control,
125                        parity,
126                        stop_bits,
127                        timeout,
128                    });
129                }
130                Err(e) => last_err = e,
131            }
132        }
133        Err(last_err)
134    }
135}
136
137impl Read for TcpSerialPort {
138    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
139        match self.stream.read(buf) {
140            // A closed socket is an unplugged device, not an empty read.
141            Ok(0) if !buf.is_empty() => Err(io::Error::new(
142                io::ErrorKind::UnexpectedEof,
143                "TCP serial bridge closed the connection",
144            )),
145            Err(e) => Err(map_read_error(e)),
146            ok => ok,
147        }
148    }
149}
150
151impl Write for TcpSerialPort {
152    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
153        self.stream.write(buf)
154    }
155
156    fn flush(&mut self) -> io::Result<()> {
157        self.stream.flush()
158    }
159}
160
161impl SerialPort for TcpSerialPort {
162    fn name(&self) -> Option<String> {
163        Some(self.path.clone())
164    }
165
166    fn baud_rate(&self) -> serialport::Result<u32> {
167        Ok(self.baud_rate)
168    }
169
170    fn data_bits(&self) -> serialport::Result<DataBits> {
171        Ok(self.data_bits)
172    }
173
174    fn flow_control(&self) -> serialport::Result<FlowControl> {
175        Ok(self.flow_control)
176    }
177
178    fn parity(&self) -> serialport::Result<Parity> {
179        Ok(self.parity)
180    }
181
182    fn stop_bits(&self) -> serialport::Result<StopBits> {
183        Ok(self.stop_bits)
184    }
185
186    fn timeout(&self) -> Duration {
187        self.timeout
188    }
189
190    fn set_baud_rate(&mut self, baud_rate: u32) -> serialport::Result<()> {
191        self.baud_rate = baud_rate;
192        Ok(())
193    }
194
195    fn set_data_bits(&mut self, data_bits: DataBits) -> serialport::Result<()> {
196        self.data_bits = data_bits;
197        Ok(())
198    }
199
200    fn set_flow_control(&mut self, flow_control: FlowControl) -> serialport::Result<()> {
201        self.flow_control = flow_control;
202        Ok(())
203    }
204
205    fn set_parity(&mut self, parity: Parity) -> serialport::Result<()> {
206        self.parity = parity;
207        Ok(())
208    }
209
210    fn set_stop_bits(&mut self, stop_bits: StopBits) -> serialport::Result<()> {
211        self.stop_bits = stop_bits;
212        Ok(())
213    }
214
215    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
216        self.stream.set_read_timeout(socket_timeout(timeout))?;
217        self.stream.set_write_timeout(socket_timeout(timeout))?;
218        self.timeout = timeout;
219        Ok(())
220    }
221
222    fn write_request_to_send(&mut self, _level: bool) -> serialport::Result<()> {
223        Ok(())
224    }
225
226    fn write_data_terminal_ready(&mut self, _level: bool) -> serialport::Result<()> {
227        Ok(())
228    }
229
230    // A connected raw bridge behaves like a cable with the lines asserted.
231    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
232        Ok(true)
233    }
234
235    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
236        Ok(true)
237    }
238
239    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
240        Ok(false)
241    }
242
243    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
244        Ok(true)
245    }
246
247    fn bytes_to_read(&self) -> serialport::Result<u32> {
248        self.stream.set_nonblocking(true)?;
249        let mut buf = [0u8; 4096];
250        let pending = match self.stream.peek(&mut buf) {
251            Ok(n) => n as u32,
252            Err(e) if e.kind() == io::ErrorKind::WouldBlock => 0,
253            Err(e) => {
254                let _ = self.stream.set_nonblocking(false);
255                return Err(e.into());
256            }
257        };
258        self.stream.set_nonblocking(false)?;
259        Ok(pending)
260    }
261
262    fn bytes_to_write(&self) -> serialport::Result<u32> {
263        Ok(0)
264    }
265
266    fn clear(&self, buffer_to_clear: ClearBuffer) -> serialport::Result<()> {
267        if matches!(buffer_to_clear, ClearBuffer::Output) {
268            return Ok(());
269        }
270        // Drop whatever already arrived, without waiting for more.
271        self.stream.set_nonblocking(true)?;
272        let mut buf = [0u8; 4096];
273        let result = loop {
274            match (&self.stream).read(&mut buf) {
275                Ok(0) => break Ok(()),
276                Ok(_) => continue,
277                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break Ok(()),
278                Err(e) => break Err(e.into()),
279            }
280        };
281        self.stream.set_nonblocking(false)?;
282        result
283    }
284
285    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
286        Ok(Box::new(Self {
287            stream: self.stream.try_clone()?,
288            path: self.path.clone(),
289            baud_rate: self.baud_rate,
290            data_bits: self.data_bits,
291            flow_control: self.flow_control,
292            parity: self.parity,
293            stop_bits: self.stop_bits,
294            timeout: self.timeout,
295        }))
296    }
297
298    fn set_break(&self) -> serialport::Result<()> {
299        Ok(())
300    }
301
302    fn clear_break(&self) -> serialport::Result<()> {
303        Ok(())
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use std::net::TcpListener;
311
312    fn connect(listener: &TcpListener) -> TcpSerialPort {
313        let path = format!("tcp://{}", listener.local_addr().unwrap());
314        TcpSerialPort::connect(
315            &path,
316            115_200,
317            DataBits::Eight,
318            FlowControl::None,
319            Parity::None,
320            StopBits::One,
321            Duration::from_millis(50),
322        )
323        .unwrap()
324    }
325
326    #[test]
327    fn keepalive_is_on_with_a_short_idle() {
328        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
329        let port = connect(&listener);
330        let sock = socket2::SockRef::from(&port.stream);
331        assert!(sock.keepalive().unwrap());
332        #[cfg(unix)]
333        {
334            assert_eq!(sock.tcp_keepalive_time().unwrap(), KEEPALIVE_IDLE);
335            #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))]
336            assert_eq!(sock.tcp_keepalive_interval().unwrap(), KEEPALIVE_INTERVAL);
337        }
338        // A clone shares the socket, so it keeps the options.
339        let clone = port.try_clone().unwrap();
340        drop(clone);
341    }
342
343    /// Unix reports a read timeout as WouldBlock; a dead keepalive is ETIMEDOUT.
344    #[test]
345    fn keepalive_timeout_reads_as_a_disconnect() {
346        let timeout = map_read_error(io::Error::from(io::ErrorKind::WouldBlock));
347        assert_eq!(timeout.kind(), io::ErrorKind::TimedOut);
348        #[cfg(unix)]
349        {
350            let dead = map_read_error(io::Error::from(io::ErrorKind::TimedOut));
351            assert_eq!(dead.kind(), io::ErrorKind::ConnectionAborted);
352        }
353        let reset = map_read_error(io::Error::from(io::ErrorKind::ConnectionReset));
354        assert_eq!(reset.kind(), io::ErrorKind::ConnectionReset);
355    }
356
357    /// The bridge going away ends the hub with `Disconnect`, not endless timeouts.
358    #[cfg(not(target_os = "android"))]
359    #[test]
360    fn bridge_gone_ends_in_disconnect_event() {
361        use crate::events::{EventSink, SerialEvent};
362        use std::sync::{mpsc, Arc, Mutex};
363
364        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
365        let port = connect(&listener);
366        let (peer, _) = listener.accept().unwrap();
367        let (tx, rx) = mpsc::channel();
368        let tx = Mutex::new(tx);
369        let sink: EventSink = Arc::new(move |event: SerialEvent| {
370            if matches!(event, SerialEvent::Disconnect { .. }) {
371                let _ = tx.lock().unwrap().send(());
372            }
373            true
374        });
375        let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(port)));
376        let hub = crate::hub::PortRxHub::start(port, "tcp://bridge".into());
377        hub.attach_watch_with(sink, 10, 64, false, None);
378        drop(peer);
379        rx.recv_timeout(Duration::from_secs(3))
380            .expect("no Disconnect after the bridge closed");
381        hub.stop();
382    }
383}