interprocess_docfix/os/unix/udsocket/
stream.rs

1#![allow(dead_code)]
2
3#[cfg(uds_supported)]
4use super::c_wrappers;
5use super::{
6    imports::*,
7    util::{check_ancillary_unsound, mk_msghdr_r, mk_msghdr_w},
8    AncillaryData, AncillaryDataBuf, EncodedAncillaryData, ToUdSocketPath, UdSocketPath,
9};
10use std::{
11    fmt::{self, Debug, Formatter},
12    io::{self, IoSlice, IoSliceMut, Read, Write},
13    iter,
14    net::Shutdown,
15};
16use to_method::To;
17
18/// A Unix domain socket byte stream, obtained either from [`UdStreamListener`](super::UdStreamListener) or by connecting to an existing server.
19///
20/// # Examples
21/// Basic example:
22/// ```no_run
23/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
24/// # #[cfg(unix)] {
25/// use interprocess::os::unix::udsocket::UdStream;
26/// use std::io::prelude::*;
27///
28/// let mut conn = UdStream::connect("/tmp/example1.sock")?;
29/// conn.write_all(b"Hello from client!")?;
30/// let mut string_buffer = String::new();
31/// conn.read_to_string(&mut string_buffer)?;
32/// println!("Server answered: {}", string_buffer);
33/// # }
34/// # Ok(()) }
35/// ```
36pub struct UdStream {
37    fd: FdOps,
38}
39impl UdStream {
40    /// Connects to a Unix domain socket server at the specified path.
41    ///
42    /// See [`ToUdSocketPath`] for an example of using various string types to specify socket paths.
43    ///
44    /// # System calls
45    /// - `socket`
46    /// - `connect`
47    pub fn connect<'a>(path: impl ToUdSocketPath<'a>) -> io::Result<Self> {
48        Self::_connect(path.to_socket_path()?, false)
49    }
50    pub(crate) fn connect_nonblocking<'a>(path: impl ToUdSocketPath<'a>) -> io::Result<Self> {
51        Self::_connect(path.to_socket_path()?, true)
52    }
53    fn _connect(path: UdSocketPath<'_>, nonblocking: bool) -> io::Result<Self> {
54        let addr = path.try_to::<sockaddr_un>()?;
55
56        let fd = c_wrappers::create_uds(SOCK_STREAM, nonblocking)?;
57        unsafe {
58            // SAFETY: addr is well-constructed
59            c_wrappers::connect(&fd, &addr)?;
60        }
61        c_wrappers::set_passcred(&fd, true)?;
62
63        Ok(Self { fd })
64    }
65
66    /// Receives bytes from the socket stream.
67    ///
68    /// # System calls
69    /// - `read`
70    pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
71        self.fd.read(buf)
72    }
73    /// Receives bytes from the socket stream, making use of [scatter input] for the main data.
74    ///
75    /// # System calls
76    /// - `readv`
77    ///
78    /// [scatter input]: https://en.wikipedia.org/wiki/Vectored_I/O " "
79    pub fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
80        self.fd.read_vectored(bufs)
81    }
82    /// Receives both bytes and ancillary data from the socket stream.
83    ///
84    /// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, mutable slices of bytes (`u8` values) can be passed directly.
85    ///
86    /// # System calls
87    /// - `recvmsg`
88    pub fn recv_ancillary<'a: 'b, 'b>(
89        &self,
90        buf: &mut [u8],
91        abuf: &'b mut AncillaryDataBuf<'a>,
92    ) -> io::Result<(usize, usize)> {
93        check_ancillary_unsound()?;
94        self.recv_ancillary_vectored(&mut [IoSliceMut::new(buf)], abuf)
95    }
96    /// Receives bytes and ancillary data from the socket stream, making use of [scatter input] for the main data.
97    ///
98    /// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, mutable slices of bytes (`u8` values) can be passed directly.
99    ///
100    /// # System calls
101    /// - `recvmsg`
102    ///
103    /// [scatter input]: https://en.wikipedia.org/wiki/Vectored_I/O " "
104    #[allow(clippy::useless_conversion)]
105    pub fn recv_ancillary_vectored<'a: 'b, 'b>(
106        &self,
107        bufs: &mut [IoSliceMut<'_>],
108        abuf: &'b mut AncillaryDataBuf<'a>,
109    ) -> io::Result<(usize, usize)> {
110        check_ancillary_unsound()?;
111        let mut hdr = mk_msghdr_r(bufs, abuf.as_mut())?;
112        let (success, bytes_read) = unsafe {
113            let result = libc::recvmsg(self.as_raw_fd(), &mut hdr as *mut _, 0);
114            (result != -1, result as usize)
115        };
116        if success {
117            Ok((bytes_read, hdr.msg_controllen as _))
118        } else {
119            Err(io::Error::last_os_error())
120        }
121    }
122
123    /// Sends bytes into the socket stream.
124    ///
125    /// # System calls
126    /// - `write`
127    pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
128        self.fd.write(buf)
129    }
130    /// Sends bytes into the socket stream, making use of [gather output] for the main data.
131    ///
132    /// # System calls
133    /// - `senv`
134    ///
135    /// [gather output]: https://en.wikipedia.org/wiki/Vectored_I/O " "
136    pub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
137        self.fd.write_vectored(bufs)
138    }
139    /// Sends bytes and ancillary data into the socket stream.
140    ///
141    /// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, slices and `Vec`s of `AncillaryData` can be passed directly.
142    ///
143    /// # System calls
144    /// - `sendmsg`
145    pub fn send_ancillary<'a>(
146        &self,
147        buf: &[u8],
148        ancillary_data: impl IntoIterator<Item = AncillaryData<'a>>,
149    ) -> io::Result<(usize, usize)> {
150        check_ancillary_unsound()?;
151        self.send_ancillary_vectored(&[IoSlice::new(buf)], ancillary_data)
152    }
153
154    /// Sends bytes and ancillary data into the socket stream, making use of [gather output] for the main data.
155    ///
156    /// The ancillary data buffer is automatically converted from the supplied value, if possible. For that reason, slices and `Vec`s of `AncillaryData` can be passed directly.
157    ///
158    /// # System calls
159    /// - `sendmsg`
160    ///
161    /// [gather output]: https://en.wikipedia.org/wiki/Vectored_I/O " "
162    #[allow(clippy::useless_conversion)]
163    pub fn send_ancillary_vectored<'a>(
164        &self,
165        bufs: &[IoSlice<'_>],
166        ancillary_data: impl IntoIterator<Item = AncillaryData<'a>>,
167    ) -> io::Result<(usize, usize)> {
168        check_ancillary_unsound()?;
169        let abuf = ancillary_data
170            .into_iter()
171            .collect::<EncodedAncillaryData<'_>>();
172        let hdr = mk_msghdr_w(bufs, abuf.as_ref())?;
173        let (success, bytes_written) = unsafe {
174            let result = libc::sendmsg(self.as_raw_fd(), &hdr as *const _, 0);
175            (result != -1, result as usize)
176        };
177        if success {
178            Ok((bytes_written, hdr.msg_controllen as _))
179        } else {
180            Err(io::Error::last_os_error())
181        }
182    }
183
184    /// Shuts down the read, write, or both halves of the stream. See [`Shutdown`].
185    ///
186    /// Attempting to call this method with the same `how` argument multiple times may return `Ok(())` every time or it may return an error the second time it is called, depending on the platform. You must either avoid using the same value twice or ignore the error entirely.
187    pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
188        c_wrappers::shutdown(&self.fd, how)
189    }
190
191    /// Enables or disables the nonblocking mode for the stream. By default, it is disabled.
192    ///
193    /// In nonblocking mode, calls to the `recv…` methods and the `Read` trait methods will never wait for at least one byte of data to become available; calls to `send…` methods and the `Write` trait methods will never wait for the other side to remove enough bytes from the buffer for the write operation to be performed. Those operations will instead return a [`WouldBlock`] error immediately, allowing the thread to perform other useful operations in the meantime.
194    ///
195    /// [`accept`]: #method.accept " "
196    /// [`incoming`]: #method.incoming " "
197    /// [`WouldBlock`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html#variant.WouldBlock " "
198    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
199        c_wrappers::set_nonblocking(&self.fd, nonblocking)
200    }
201    /// Checks whether the stream is currently in nonblocking mode or not.
202    pub fn is_nonblocking(&self) -> io::Result<bool> {
203        c_wrappers::get_nonblocking(&self.fd)
204    }
205
206    /// Fetches the credentials of the other end of the connection without using ancillary data. The returned structure contains the process identifier, user identifier and group identifier of the peer.
207    #[cfg(any(doc, uds_peercred))]
208    #[cfg_attr( // uds_peercred template
209        feature = "doc_cfg",
210        doc(cfg(any(
211            all(
212                target_os = "linux",
213                any(
214                    target_env = "gnu",
215                    target_env = "musl",
216                    target_env = "musleabi",
217                    target_env = "musleabihf"
218                )
219            ),
220            target_os = "emscripten",
221            target_os = "redox",
222            target_os = "haiku"
223        )))
224    )]
225    pub fn get_peer_credentials(&self) -> io::Result<ucred> {
226        c_wrappers::get_peer_ucred(&self.fd)
227    }
228}
229
230impl Read for UdStream {
231    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
232        self.fd.read(buf)
233    }
234    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
235        let mut abuf = AncillaryDataBuf::Owned(Vec::new());
236        self.recv_ancillary_vectored(bufs, &mut abuf).map(|x| x.0)
237    }
238}
239impl Write for UdStream {
240    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
241        self.fd.write(buf)
242    }
243    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
244        self.send_ancillary_vectored(bufs, iter::empty())
245            .map(|x| x.0)
246    }
247    fn flush(&mut self) -> io::Result<()> {
248        // You cannot flush a socket
249        Ok(())
250    }
251}
252
253impl Debug for UdStream {
254    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
255        f.debug_struct("UdStream")
256            .field("fd", &self.as_raw_fd())
257            .finish()
258    }
259}
260
261impl AsRawFd for UdStream {
262    #[cfg(unix)]
263    fn as_raw_fd(&self) -> c_int {
264        self.fd.as_raw_fd()
265    }
266}
267impl IntoRawFd for UdStream {
268    #[cfg(unix)]
269    fn into_raw_fd(self) -> c_int {
270        self.fd.into_raw_fd()
271    }
272}
273impl FromRawFd for UdStream {
274    #[cfg(unix)]
275    unsafe fn from_raw_fd(fd: c_int) -> Self {
276        Self { fd: FdOps::new(fd) }
277    }
278}