Skip to main content

tilo_socket/
datagram.rs

1//! Two connected ends that carry whole datagrams: a Unix datagram socket pair, or on Windows a
2//! pipe only this process joined ([`crate::link::pair`]) with each datagram written behind its
3//! length, so a datagram is read whole however the pipe splits its bytes. A caller hands one end to
4//! a process or thread it starts and keeps the other; [`crate::tokio::Datagram`] drives an end on
5//! a runtime.
6//!
7//! One thread reads an end at a time: on Windows a datagram is a header and its bytes, and two
8//! readers of one end would split them.
9
10use std::io;
11#[cfg(unix)]
12use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
13#[cfg(unix)]
14use std::os::unix::net::UnixDatagram;
15use std::time::Duration;
16
17/// The largest datagram an end carries: the largest UDP payload.
18pub const MAX_DATAGRAM: usize = 65_535;
19
20/// One end of a connected datagram pair.
21#[derive(Debug)]
22pub struct Datagram {
23    #[cfg(unix)]
24    socket: UnixDatagram,
25    #[cfg(windows)]
26    stream: crate::Stream,
27    #[cfg(not(any(unix, windows)))]
28    never: std::convert::Infallible,
29}
30
31impl Datagram {
32    /// Two connected ends, both in this process.
33    ///
34    /// # Errors
35    /// The system's error making the pair.
36    pub fn pair() -> io::Result<(Self, Self)> {
37        #[cfg(unix)]
38        {
39            let (ours, theirs) = UnixDatagram::pair()?;
40            Ok((Self { socket: ours }, Self { socket: theirs }))
41        }
42        #[cfg(windows)]
43        {
44            let (ours, theirs) = crate::link::pair()?;
45            Ok((Self { stream: ours }, Self { stream: theirs }))
46        }
47        #[cfg(not(any(unix, windows)))]
48        {
49            Err(io::Error::new(
50                io::ErrorKind::Unsupported,
51                "a page has no local socket",
52            ))
53        }
54    }
55
56    /// Send `payload` as one datagram.
57    ///
58    /// # Errors
59    /// The other end is gone, or `payload` is longer than [`MAX_DATAGRAM`].
60    pub fn send(&self, payload: &[u8]) -> io::Result<usize> {
61        if payload.len() > MAX_DATAGRAM {
62            return Err(too_long(payload.len()));
63        }
64        #[cfg(unix)]
65        {
66            self.socket.send(payload)
67        }
68        #[cfg(windows)]
69        {
70            use std::io::Write as _;
71            (&self.stream).write_all(&framed(payload))?;
72            Ok(payload.len())
73        }
74        #[cfg(not(any(unix, windows)))]
75        {
76            match self.never {}
77        }
78    }
79
80    /// The next datagram, into `buffer`: its length, cut to the buffer's when it is longer, as a
81    /// datagram socket reads one. `0` when the other end is gone and says so (a Windows pipe
82    /// does; a Unix datagram socket may wait out its timeout instead).
83    ///
84    /// # Errors
85    /// The read timeout passed before a datagram began ([`io::ErrorKind::WouldBlock`] or
86    /// [`io::ErrorKind::TimedOut`]), or the system's error reading.
87    pub fn recv(&self, buffer: &mut [u8]) -> io::Result<usize> {
88        #[cfg(unix)]
89        {
90            self.socket.recv(buffer)
91        }
92        #[cfg(windows)]
93        {
94            let mut header = [0_u8; HEADER];
95            if !self.fill(&mut header, false)? {
96                return Ok(0);
97            }
98            let length = usize::try_from(u32::from_le_bytes(header)).unwrap_or(usize::MAX);
99            if length > MAX_DATAGRAM {
100                return Err(too_long(length));
101            }
102            let kept = length.min(buffer.len());
103            let mut rest = vec![0_u8; length.saturating_sub(kept)];
104            let whole = self.fill(buffer.get_mut(..kept).unwrap_or_default(), true)?
105                && self.fill(&mut rest, true)?;
106            Ok(if whole { kept } else { 0 })
107        }
108        #[cfg(not(any(unix, windows)))]
109        {
110            let _ = buffer;
111            match self.never {}
112        }
113    }
114
115    /// Fill `into` from the pipe: `false` when the other end closed first. A timeout ends the
116    /// wait only before a datagram's first byte; once it `begun`, the rest of it is read whatever
117    /// the timeout, so the next read starts at a header.
118    #[cfg(windows)]
119    fn fill(&self, into: &mut [u8], begun: bool) -> io::Result<bool> {
120        use std::io::Read as _;
121        let mut at = 0;
122        while let Some(left) = into.get_mut(at..).filter(|left| !left.is_empty()) {
123            match (&self.stream).read(left) {
124                Ok(0) => return Ok(false),
125                Ok(read) => at = at.saturating_add(read),
126                Err(error)
127                    if (begun || at > 0)
128                        && matches!(
129                            error.kind(),
130                            io::ErrorKind::WouldBlock
131                                | io::ErrorKind::TimedOut
132                                | io::ErrorKind::Interrupted
133                        ) => {}
134                Err(error) => return Err(error),
135            }
136        }
137        Ok(true)
138    }
139
140    /// How long [`Self::recv`] waits for a datagram to begin; `None` waits for ever.
141    ///
142    /// # Errors
143    /// The system's error setting it.
144    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
145        #[cfg(unix)]
146        {
147            self.socket.set_read_timeout(timeout)
148        }
149        #[cfg(windows)]
150        {
151            self.stream.set_read_timeout(timeout)
152        }
153        #[cfg(not(any(unix, windows)))]
154        {
155            let _ = timeout;
156            match self.never {}
157        }
158    }
159
160    /// A second handle on this end, for a thread that sends while another reads.
161    ///
162    /// # Errors
163    /// The system's error duplicating it.
164    pub fn try_clone(&self) -> io::Result<Self> {
165        #[cfg(unix)]
166        {
167            Ok(Self {
168                socket: self.socket.try_clone()?,
169            })
170        }
171        #[cfg(windows)]
172        {
173            Ok(Self {
174                stream: self.stream.try_clone()?,
175            })
176        }
177        #[cfg(not(any(unix, windows)))]
178        {
179            match self.never {}
180        }
181    }
182
183    #[cfg(all(unix, feature = "tokio"))]
184    pub(crate) fn into_socket(self) -> UnixDatagram {
185        self.socket
186    }
187
188    #[cfg(all(windows, feature = "tokio"))]
189    pub(crate) fn into_stream(self) -> crate::Stream {
190        self.stream
191    }
192}
193
194/// A datagram's header on Windows: its length, little-endian.
195#[cfg(windows)]
196pub(crate) const HEADER: usize = 4;
197
198/// `payload` behind its length, written in one call so the pipe takes it as one message.
199#[cfg(windows)]
200pub(crate) fn framed(payload: &[u8]) -> Vec<u8> {
201    let length = u32::try_from(payload.len()).unwrap_or(u32::MAX);
202    let mut framed = Vec::with_capacity(HEADER.saturating_add(payload.len()));
203    framed.extend_from_slice(&length.to_le_bytes());
204    framed.extend_from_slice(payload);
205    framed
206}
207
208pub(crate) fn too_long(length: usize) -> io::Error {
209    io::Error::new(
210        io::ErrorKind::InvalidInput,
211        format!("a datagram of {length} bytes is longer than the {MAX_DATAGRAM} one carries"),
212    )
213}
214
215/// The end a process inherited by its descriptor.
216#[cfg(unix)]
217impl From<OwnedFd> for Datagram {
218    fn from(fd: OwnedFd) -> Self {
219        Self {
220            socket: UnixDatagram::from(fd),
221        }
222    }
223}
224
225#[cfg(unix)]
226impl AsFd for Datagram {
227    fn as_fd(&self) -> BorrowedFd<'_> {
228        self.socket.as_fd()
229    }
230}
231
232#[cfg(unix)]
233impl AsRawFd for Datagram {
234    fn as_raw_fd(&self) -> RawFd {
235        self.socket.as_raw_fd()
236    }
237}
238
239#[cfg(test)]
240#[cfg(any(unix, windows))]
241mod tests {
242    use super::Datagram;
243    use std::time::Duration;
244
245    #[test]
246    fn a_datagram_arrives_whole_and_cut_to_the_buffer() {
247        let (ours, theirs) = Datagram::pair().unwrap();
248        ours.send(b"first").unwrap();
249        ours.send(&[7; 3000]).unwrap();
250        ours.send(b"third").unwrap();
251        let mut buffer = [0_u8; 16];
252        assert_eq!(theirs.recv(&mut buffer).unwrap(), 5);
253        assert_eq!(&buffer[..5], b"first");
254        // A datagram longer than the buffer is cut, and the next starts where it should.
255        assert_eq!(theirs.recv(&mut buffer).unwrap(), 16);
256        assert_eq!(buffer, [7; 16]);
257        assert_eq!(theirs.recv(&mut buffer).unwrap(), 5);
258        assert_eq!(&buffer[..5], b"third");
259    }
260
261    #[test]
262    fn a_read_waits_no_longer_than_its_timeout() {
263        let (_ours, theirs) = Datagram::pair().unwrap();
264        theirs
265            .set_read_timeout(Some(Duration::from_millis(50)))
266            .unwrap();
267        let waited = theirs.recv(&mut [0_u8; 8]).unwrap_err();
268        assert!(
269            matches!(
270                waited.kind(),
271                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
272            ),
273            "{waited}"
274        );
275    }
276}