mio/net/uds/stream.rs
1use std::fmt;
2use std::io::{self, IoSlice, IoSliceMut, Read, Write};
3use std::net::Shutdown;
4use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
5use std::os::unix::net::{self, SocketAddr};
6use std::path::Path;
7
8use crate::io_source::IoSource;
9use crate::{event, sys, Interest, Registry, Token};
10
11/// A non-blocking Unix stream socket.
12pub struct UnixStream {
13 inner: IoSource<net::UnixStream>,
14}
15
16impl UnixStream {
17 /// Connects to the socket named by `path`.
18 ///
19 /// This may return a `WouldBlock` in which case the socket connection
20 /// cannot be completed immediately. Usually it means the backlog is full.
21 pub fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
22 let addr = SocketAddr::from_pathname(path)?;
23 UnixStream::connect_addr(&addr)
24 }
25
26 /// Connects to the socket named by `address`.
27 ///
28 /// This may return a `WouldBlock` in which case the socket connection
29 /// cannot be completed immediately. Usually it means the backlog is full.
30 pub fn connect_addr(address: &SocketAddr) -> io::Result<UnixStream> {
31 sys::uds::stream::connect_addr(address).map(UnixStream::from_std)
32 }
33
34 /// Creates a new `UnixStream` from a standard `net::UnixStream`.
35 ///
36 /// This function is intended to be used to wrap a Unix stream from the
37 /// standard library in the Mio equivalent. The conversion assumes nothing
38 /// about the underlying stream; it is left up to the user to set it in
39 /// non-blocking mode.
40 ///
41 /// # Note
42 ///
43 /// The Unix stream here will not have `connect` called on it, so it
44 /// should already be connected via some other means (be it manually, or
45 /// the standard library).
46 pub fn from_std(stream: net::UnixStream) -> UnixStream {
47 UnixStream {
48 inner: IoSource::new(stream),
49 }
50 }
51
52 /// Creates an unnamed pair of connected sockets.
53 ///
54 /// Returns two `UnixStream`s which are connected to each other.
55 pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
56 sys::uds::stream::pair().map(|(stream1, stream2)| {
57 (UnixStream::from_std(stream1), UnixStream::from_std(stream2))
58 })
59 }
60
61 /// Returns the socket address of the local half of this connection.
62 pub fn local_addr(&self) -> io::Result<SocketAddr> {
63 self.inner.local_addr()
64 }
65
66 /// Returns the socket address of the remote half of this connection.
67 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
68 self.inner.peer_addr()
69 }
70
71 /// Returns the value of the `SO_ERROR` option.
72 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
73 self.inner.take_error()
74 }
75
76 /// Shuts down the read, write, or both halves of this connection.
77 ///
78 /// This function will cause all pending and future I/O calls on the
79 /// specified portions to immediately return with an appropriate value
80 /// (see the documentation of `Shutdown`).
81 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
82 self.inner.shutdown(how)
83 }
84
85 /// Execute an I/O operation ensuring that the socket receives more events
86 /// if it hits a [`WouldBlock`] error.
87 ///
88 /// # Notes
89 ///
90 /// This method is required to be called for **all** I/O operations to
91 /// ensure the user will receive events once the socket is ready again after
92 /// returning a [`WouldBlock`] error.
93 ///
94 /// [`WouldBlock`]: io::ErrorKind::WouldBlock
95 ///
96 /// # Examples
97 ///
98 #[cfg_attr(not(miri), doc = "```")]
99 #[cfg_attr(miri, doc = "```ignore")] // Miri doesn't support Unix domain sockets.
100 /// # use std::error::Error;
101 /// #
102 /// # fn main() -> Result<(), Box<dyn Error>> {
103 /// use std::io;
104 /// use std::os::fd::AsRawFd;
105 /// use mio::net::UnixStream;
106 ///
107 /// let (stream1, stream2) = UnixStream::pair()?;
108 ///
109 /// // Wait until the stream is writable...
110 ///
111 /// // Write to the stream using a direct libc call, of course the
112 /// // `io::Write` implementation would be easier to use.
113 /// let buf = b"hello";
114 /// let n = stream1.try_io(|| {
115 /// let buf_ptr = &buf as *const _ as *const _;
116 /// let res = unsafe { libc::send(stream1.as_raw_fd(), buf_ptr, buf.len(), 0) };
117 /// if res != -1 {
118 /// Ok(res as usize)
119 /// } else {
120 /// // If EAGAIN or EWOULDBLOCK is set by libc::send, the closure
121 /// // should return `WouldBlock` error.
122 /// Err(io::Error::last_os_error())
123 /// }
124 /// })?;
125 /// eprintln!("write {} bytes", n);
126 ///
127 /// // Wait until the stream is readable...
128 ///
129 /// // Read from the stream using a direct libc call, of course the
130 /// // `io::Read` implementation would be easier to use.
131 /// let mut buf = [0; 512];
132 /// let n = stream2.try_io(|| {
133 /// let buf_ptr = &mut buf as *mut _ as *mut _;
134 /// let res = unsafe { libc::recv(stream2.as_raw_fd(), buf_ptr, buf.len(), 0) };
135 /// if res != -1 {
136 /// Ok(res as usize)
137 /// } else {
138 /// // If EAGAIN or EWOULDBLOCK is set by libc::recv, the closure
139 /// // should return `WouldBlock` error.
140 /// Err(io::Error::last_os_error())
141 /// }
142 /// })?;
143 /// eprintln!("read {} bytes", n);
144 /// # Ok(())
145 /// # }
146 /// ```
147 pub fn try_io<F, T>(&self, f: F) -> io::Result<T>
148 where
149 F: FnOnce() -> io::Result<T>,
150 {
151 self.inner.do_io(|_| f())
152 }
153}
154
155impl Read for UnixStream {
156 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
157 self.inner.do_io(|mut inner| inner.read(buf))
158 }
159
160 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
161 self.inner.do_io(|mut inner| inner.read_vectored(bufs))
162 }
163}
164
165impl Read for &'_ UnixStream {
166 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
167 self.inner.do_io(|mut inner| inner.read(buf))
168 }
169
170 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
171 self.inner.do_io(|mut inner| inner.read_vectored(bufs))
172 }
173}
174
175impl Write for UnixStream {
176 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
177 self.inner.do_io(|mut inner| inner.write(buf))
178 }
179
180 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
181 self.inner.do_io(|mut inner| inner.write_vectored(bufs))
182 }
183
184 fn flush(&mut self) -> io::Result<()> {
185 self.inner.do_io(|mut inner| inner.flush())
186 }
187}
188
189impl Write for &'_ UnixStream {
190 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
191 self.inner.do_io(|mut inner| inner.write(buf))
192 }
193
194 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
195 self.inner.do_io(|mut inner| inner.write_vectored(bufs))
196 }
197
198 fn flush(&mut self) -> io::Result<()> {
199 self.inner.do_io(|mut inner| inner.flush())
200 }
201}
202
203impl event::Source for UnixStream {
204 fn register(
205 &mut self,
206 registry: &Registry,
207 token: Token,
208 interests: Interest,
209 ) -> io::Result<()> {
210 self.inner.register(registry, token, interests)
211 }
212
213 fn reregister(
214 &mut self,
215 registry: &Registry,
216 token: Token,
217 interests: Interest,
218 ) -> io::Result<()> {
219 self.inner.reregister(registry, token, interests)
220 }
221
222 fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
223 self.inner.deregister(registry)
224 }
225}
226
227impl fmt::Debug for UnixStream {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 self.inner.fmt(f)
230 }
231}
232
233impl IntoRawFd for UnixStream {
234 fn into_raw_fd(self) -> RawFd {
235 self.inner.into_inner().into_raw_fd()
236 }
237}
238
239impl AsRawFd for UnixStream {
240 fn as_raw_fd(&self) -> RawFd {
241 self.inner.as_raw_fd()
242 }
243}
244
245impl FromRawFd for UnixStream {
246 /// Converts a `RawFd` to a `UnixStream`.
247 ///
248 /// # Notes
249 ///
250 /// The caller is responsible for ensuring that the socket is in
251 /// non-blocking mode.
252 unsafe fn from_raw_fd(fd: RawFd) -> UnixStream {
253 UnixStream::from_std(FromRawFd::from_raw_fd(fd))
254 }
255}
256
257impl From<UnixStream> for net::UnixStream {
258 fn from(stream: UnixStream) -> Self {
259 // Safety: This is safe since we are extracting the raw fd from a well-constructed
260 // mio::net::uds::UnixStream which ensures that we actually pass in a valid file
261 // descriptor/socket
262 unsafe { net::UnixStream::from_raw_fd(stream.into_raw_fd()) }
263 }
264}
265
266impl From<UnixStream> for OwnedFd {
267 fn from(unix_stream: UnixStream) -> Self {
268 unix_stream.inner.into_inner().into()
269 }
270}
271
272impl AsFd for UnixStream {
273 fn as_fd(&self) -> BorrowedFd<'_> {
274 self.inner.as_fd()
275 }
276}
277
278impl From<OwnedFd> for UnixStream {
279 fn from(fd: OwnedFd) -> Self {
280 UnixStream::from_std(From::from(fd))
281 }
282}