Skip to main content

tokio/net/unix/
stream.rs

1use crate::io::{AsyncRead, AsyncWrite, Interest, PollEvented, ReadBuf, Ready};
2use crate::net::unix::split::{split, ReadHalf, WriteHalf};
3use crate::net::unix::split_owned::{split_owned, OwnedReadHalf, OwnedWriteHalf};
4use crate::net::unix::ucred::{self, UCred};
5use crate::net::unix::SocketAddr;
6use crate::util::check_socket_for_blocking;
7
8use std::fmt;
9use std::future::poll_fn;
10use std::io::{self, Read, Write};
11use std::net::Shutdown;
12#[cfg(target_os = "android")]
13use std::os::android::net::SocketAddrExt;
14#[cfg(target_os = "linux")]
15use std::os::linux::net::SocketAddrExt;
16#[cfg(any(target_os = "linux", target_os = "android"))]
17use std::os::unix::ffi::OsStrExt;
18use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
19use std::os::unix::net::{self, SocketAddr as StdSocketAddr};
20use std::path::Path;
21use std::pin::Pin;
22use std::task::{Context, Poll};
23
24cfg_io_util! {
25    use bytes::BufMut;
26}
27
28cfg_net_unix! {
29    /// A structure representing a connected Unix socket.
30    ///
31    /// This socket can be connected directly with [`UnixStream::connect`] or accepted
32    /// from a listener with [`UnixListener::accept`]. Additionally, a pair of
33    /// anonymous Unix sockets can be created with `UnixStream::pair`.
34    ///
35    /// To shut down the stream in the write direction, you can call the
36    /// [`shutdown()`] method. This will cause the other peer to receive a read of
37    /// length 0, indicating that no more data will be sent. This only closes
38    /// the stream in one direction.
39    ///
40    /// [`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown
41    /// [`UnixListener::accept`]: crate::net::UnixListener::accept
42    #[cfg_attr(docsrs, doc(alias = "uds"))]
43    pub struct UnixStream {
44        io: PollEvented<mio::net::UnixStream>,
45    }
46}
47
48impl UnixStream {
49    pub(crate) async fn connect_mio(sys: mio::net::UnixStream) -> io::Result<UnixStream> {
50        let stream = UnixStream::new(sys)?;
51
52        // Once we've connected, wait for the stream to be writable as
53        // that's when the actual connection has been initiated. Once we're
54        // writable we check for `take_socket_error` to see if the connect
55        // actually hit an error or not.
56        //
57        // If all that succeeded then we ship everything on up.
58        poll_fn(|cx| stream.io.registration().poll_write_ready(cx)).await?;
59
60        if let Some(e) = stream.io.take_error()? {
61            return Err(e);
62        }
63
64        Ok(stream)
65    }
66
67    /// Connects to the socket named by `path`.
68    ///
69    /// This function will create a new Unix socket and connect to the path
70    /// specified, associating the returned stream with the default event loop's
71    /// handle.
72    ///
73    /// # Panics
74    ///
75    /// This function panics if it is not called from within a runtime with
76    /// IO enabled.
77    ///
78    /// The runtime is usually set implicitly when this function is called
79    /// from a future driven by a tokio runtime, otherwise runtime can be set
80    /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
81    pub async fn connect<P>(path: P) -> io::Result<UnixStream>
82    where
83        P: AsRef<Path>,
84    {
85        // On linux, abstract socket paths need to be considered.
86        #[cfg(any(target_os = "linux", target_os = "android"))]
87        let addr = {
88            let os_str_bytes = path.as_ref().as_os_str().as_bytes();
89            if os_str_bytes.starts_with(b"\0") {
90                StdSocketAddr::from_abstract_name(&os_str_bytes[1..])?
91            } else {
92                StdSocketAddr::from_pathname(path)?
93            }
94        };
95        #[cfg(not(any(target_os = "linux", target_os = "android")))]
96        let addr = StdSocketAddr::from_pathname(path)?;
97
98        let addr = SocketAddr::from(addr);
99        UnixStream::connect_addr(&addr).await
100    }
101
102    /// Connects to the socket named by `socket_addr`.
103    ///
104    /// This function will create a new Unix socket and connect to the address
105    /// specified, associating the returned stream with the default event
106    /// loop's handle.
107    ///
108    /// # Panics
109    ///
110    /// This function panics if it is not called from within a runtime with
111    /// IO enabled.
112    ///
113    /// The runtime is usually set implicitly when this function is called
114    /// from a future driven by a tokio runtime, otherwise runtime can be set
115    /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
116    pub async fn connect_addr(socket_addr: &SocketAddr) -> io::Result<UnixStream> {
117        let stream = mio::net::UnixStream::connect_addr(&socket_addr.0)?;
118        let stream = UnixStream::new(stream)?;
119
120        poll_fn(|cx| stream.io.registration().poll_write_ready(cx)).await?;
121
122        if let Some(e) = stream.io.take_error()? {
123            return Err(e);
124        }
125
126        Ok(stream)
127    }
128
129    /// Waits for any of the requested ready states.
130    ///
131    /// This function is usually paired with `try_read()` or `try_write()`. It
132    /// can be used to concurrently read / write to the same socket on a single
133    /// task without splitting the socket.
134    ///
135    /// The function may complete without the socket being ready. This is a
136    /// false-positive and attempting an operation will return with
137    /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
138    /// [`Ready`] set, so you should always check the returned value and possibly
139    /// wait again if the requested states are not set.
140    ///
141    /// # Cancel safety
142    ///
143    /// This method is cancel safe. Once a readiness event occurs, the method
144    /// will continue to return immediately until the readiness event is
145    /// consumed by an attempt to read or write that fails with `WouldBlock` or
146    /// `Poll::Pending`.
147    ///
148    /// # Examples
149    ///
150    /// Concurrently read and write to the stream on the same task without
151    /// splitting.
152    ///
153    /// ```no_run
154    /// use tokio::io::Interest;
155    /// use tokio::net::UnixStream;
156    /// use std::error::Error;
157    /// use std::io;
158    ///
159    /// #[tokio::main]
160    /// async fn main() -> Result<(), Box<dyn Error>> {
161    ///     let dir = tempfile::tempdir().unwrap();
162    ///     let bind_path = dir.path().join("bind_path");
163    ///     let stream = UnixStream::connect(bind_path).await?;
164    ///
165    ///     loop {
166    ///         let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;
167    ///
168    ///         if ready.is_readable() {
169    ///             let mut data = vec![0; 1024];
170    ///             // Try to read data, this may still fail with `WouldBlock`
171    ///             // if the readiness event is a false positive.
172    ///             match stream.try_read(&mut data) {
173    ///                 Ok(n) => {
174    ///                     println!("read {} bytes", n);
175    ///                 }
176    ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
177    ///                     continue;
178    ///                 }
179    ///                 Err(e) => {
180    ///                     return Err(e.into());
181    ///                 }
182    ///             }
183    ///
184    ///         }
185    ///
186    ///         if ready.is_writable() {
187    ///             // Try to write data, this may still fail with `WouldBlock`
188    ///             // if the readiness event is a false positive.
189    ///             match stream.try_write(b"hello world") {
190    ///                 Ok(n) => {
191    ///                     println!("write {} bytes", n);
192    ///                 }
193    ///                 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
194    ///                     continue;
195    ///                 }
196    ///                 Err(e) => {
197    ///                     return Err(e.into());
198    ///                 }
199    ///             }
200    ///         }
201    ///     }
202    /// }
203    /// ```
204    pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
205        let event = self.io.registration().readiness(interest).await?;
206        Ok(event.ready)
207    }
208
209    /// Waits for the socket to become readable.
210    ///
211    /// This function is equivalent to `ready(Interest::READABLE)` and is usually
212    /// paired with `try_read()`.
213    ///
214    /// # Cancel safety
215    ///
216    /// This method is cancel safe. Once a readiness event occurs, the method
217    /// will continue to return immediately until the readiness event is
218    /// consumed by an attempt to read that fails with `WouldBlock` or
219    /// `Poll::Pending`.
220    ///
221    /// # Examples
222    ///
223    /// ```no_run
224    /// use tokio::net::UnixStream;
225    /// use std::error::Error;
226    /// use std::io;
227    ///
228    /// #[tokio::main]
229    /// async fn main() -> Result<(), Box<dyn Error>> {
230    ///     // Connect to a peer
231    ///     let dir = tempfile::tempdir().unwrap();
232    ///     let bind_path = dir.path().join("bind_path");
233    ///     let stream = UnixStream::connect(bind_path).await?;
234    ///
235    ///     let mut msg = vec![0; 1024];
236    ///
237    ///     loop {
238    ///         // Wait for the socket to be readable
239    ///         stream.readable().await?;
240    ///
241    ///         // Try to read data, this may still fail with `WouldBlock`
242    ///         // if the readiness event is a false positive.
243    ///         match stream.try_read(&mut msg) {
244    ///             Ok(n) => {
245    ///                 msg.truncate(n);
246    ///                 break;
247    ///             }
248    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
249    ///                 continue;
250    ///             }
251    ///             Err(e) => {
252    ///                 return Err(e.into());
253    ///             }
254    ///         }
255    ///     }
256    ///
257    ///     println!("GOT = {:?}", msg);
258    ///     Ok(())
259    /// }
260    /// ```
261    pub async fn readable(&self) -> io::Result<()> {
262        self.ready(Interest::READABLE).await?;
263        Ok(())
264    }
265
266    /// Polls for read readiness.
267    ///
268    /// If the unix stream is not currently ready for reading, this method will
269    /// store a clone of the `Waker` from the provided `Context`. When the unix
270    /// stream becomes ready for reading, `Waker::wake` will be called on the
271    /// waker.
272    ///
273    /// Note that on multiple calls to `poll_read_ready` or `poll_read`, only
274    /// the `Waker` from the `Context` passed to the most recent call is
275    /// scheduled to receive a wakeup. (However, `poll_write_ready` retains a
276    /// second, independent waker.)
277    ///
278    /// This function is intended for cases where creating and pinning a future
279    /// via [`readable`] is not feasible. Where possible, using [`readable`] is
280    /// preferred, as this supports polling from multiple tasks at once.
281    ///
282    /// # Return value
283    ///
284    /// The function returns:
285    ///
286    /// * `Poll::Pending` if the unix stream is not ready for reading.
287    /// * `Poll::Ready(Ok(()))` if the unix stream is ready for reading.
288    /// * `Poll::Ready(Err(e))` if an error is encountered.
289    ///
290    /// # Errors
291    ///
292    /// This function may encounter any standard I/O error except `WouldBlock`.
293    ///
294    /// [`readable`]: method@Self::readable
295    pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
296        self.io.registration().poll_read_ready(cx).map_ok(|_| ())
297    }
298
299    /// Try to read data from the stream into the provided buffer, returning how
300    /// many bytes were read.
301    ///
302    /// Receives any pending data from the socket but does not wait for new data
303    /// to arrive. On success, returns the number of bytes read. Because
304    /// `try_read()` is non-blocking, the buffer does not have to be stored by
305    /// the async task and can exist entirely on the stack.
306    ///
307    /// Usually, [`readable()`] or [`ready()`] is used with this function.
308    ///
309    /// [`readable()`]: UnixStream::readable()
310    /// [`ready()`]: UnixStream::ready()
311    ///
312    /// # Return
313    ///
314    /// If data is successfully read, `Ok(n)` is returned, where `n` is the
315    /// number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:
316    ///
317    /// 1. The stream's read half is closed and will no longer yield data.
318    /// 2. The specified buffer was 0 bytes in length.
319    ///
320    /// If the stream is not ready to read data,
321    /// `Err(io::ErrorKind::WouldBlock)` is returned.
322    ///
323    /// # Examples
324    ///
325    /// ```no_run
326    /// use tokio::net::UnixStream;
327    /// use std::error::Error;
328    /// use std::io;
329    ///
330    /// #[tokio::main]
331    /// async fn main() -> Result<(), Box<dyn Error>> {
332    ///     // Connect to a peer
333    ///     let dir = tempfile::tempdir().unwrap();
334    ///     let bind_path = dir.path().join("bind_path");
335    ///     let stream = UnixStream::connect(bind_path).await?;
336    ///
337    ///     loop {
338    ///         // Wait for the socket to be readable
339    ///         stream.readable().await?;
340    ///
341    ///         // Creating the buffer **after** the `await` prevents it from
342    ///         // being stored in the async task.
343    ///         let mut buf = [0; 4096];
344    ///
345    ///         // Try to read data, this may still fail with `WouldBlock`
346    ///         // if the readiness event is a false positive.
347    ///         match stream.try_read(&mut buf) {
348    ///             Ok(0) => break,
349    ///             Ok(n) => {
350    ///                 println!("read {} bytes", n);
351    ///             }
352    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
353    ///                 continue;
354    ///             }
355    ///             Err(e) => {
356    ///                 return Err(e.into());
357    ///             }
358    ///         }
359    ///     }
360    ///
361    ///     Ok(())
362    /// }
363    /// ```
364    pub fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
365        self.io
366            .registration()
367            .try_io(Interest::READABLE, || (&*self.io).read(buf))
368    }
369
370    /// Tries to read data from the stream into the provided buffers, returning
371    /// how many bytes were read.
372    ///
373    /// Data is copied to fill each buffer in order, with the final buffer
374    /// written to possibly being only partially filled. This method behaves
375    /// equivalently to a single call to [`try_read()`] with concatenated
376    /// buffers.
377    ///
378    /// Receives any pending data from the socket but does not wait for new data
379    /// to arrive. On success, returns the number of bytes read. Because
380    /// `try_read_vectored()` is non-blocking, the buffer does not have to be
381    /// stored by the async task and can exist entirely on the stack.
382    ///
383    /// Usually, [`readable()`] or [`ready()`] is used with this function.
384    ///
385    /// [`try_read()`]: UnixStream::try_read()
386    /// [`readable()`]: UnixStream::readable()
387    /// [`ready()`]: UnixStream::ready()
388    ///
389    /// # Return
390    ///
391    /// If data is successfully read, `Ok(n)` is returned, where `n` is the
392    /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
393    /// and will no longer yield data. If the stream is not ready to read data
394    /// `Err(io::ErrorKind::WouldBlock)` is returned.
395    ///
396    /// # Examples
397    ///
398    /// ```no_run
399    /// use tokio::net::UnixStream;
400    /// use std::error::Error;
401    /// use std::io::{self, IoSliceMut};
402    ///
403    /// #[tokio::main]
404    /// async fn main() -> Result<(), Box<dyn Error>> {
405    ///     // Connect to a peer
406    ///     let dir = tempfile::tempdir().unwrap();
407    ///     let bind_path = dir.path().join("bind_path");
408    ///     let stream = UnixStream::connect(bind_path).await?;
409    ///
410    ///     loop {
411    ///         // Wait for the socket to be readable
412    ///         stream.readable().await?;
413    ///
414    ///         // Creating the buffer **after** the `await` prevents it from
415    ///         // being stored in the async task.
416    ///         let mut buf_a = [0; 512];
417    ///         let mut buf_b = [0; 1024];
418    ///         let mut bufs = [
419    ///             IoSliceMut::new(&mut buf_a),
420    ///             IoSliceMut::new(&mut buf_b),
421    ///         ];
422    ///
423    ///         // Try to read data, this may still fail with `WouldBlock`
424    ///         // if the readiness event is a false positive.
425    ///         match stream.try_read_vectored(&mut bufs) {
426    ///             Ok(0) => break,
427    ///             Ok(n) => {
428    ///                 println!("read {} bytes", n);
429    ///             }
430    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
431    ///                 continue;
432    ///             }
433    ///             Err(e) => {
434    ///                 return Err(e.into());
435    ///             }
436    ///         }
437    ///     }
438    ///
439    ///     Ok(())
440    /// }
441    /// ```
442    pub fn try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
443        self.io
444            .registration()
445            .try_io(Interest::READABLE, || (&*self.io).read_vectored(bufs))
446    }
447
448    cfg_io_util! {
449        /// Tries to read data from the stream into the provided buffer, advancing the
450        /// buffer's internal cursor, returning how many bytes were read.
451        ///
452        /// Receives any pending data from the socket but does not wait for new data
453        /// to arrive. On success, returns the number of bytes read. Because
454        /// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
455        /// the async task and can exist entirely on the stack.
456        ///
457        /// Usually, [`readable()`] or [`ready()`] is used with this function.
458        ///
459        /// [`readable()`]: UnixStream::readable()
460        /// [`ready()`]: UnixStream::ready()
461        ///
462        /// # Return
463        ///
464        /// If data is successfully read, `Ok(n)` is returned, where `n` is the
465        /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
466        /// and will no longer yield data. If the stream is not ready to read data
467        /// `Err(io::ErrorKind::WouldBlock)` is returned.
468        ///
469        /// # Examples
470        ///
471        /// ```no_run
472        /// use tokio::net::UnixStream;
473        /// use std::error::Error;
474        /// use std::io;
475        ///
476        /// #[tokio::main]
477        /// async fn main() -> Result<(), Box<dyn Error>> {
478        ///     // Connect to a peer
479        ///     let dir = tempfile::tempdir().unwrap();
480        ///     let bind_path = dir.path().join("bind_path");
481        ///     let stream = UnixStream::connect(bind_path).await?;
482        ///
483        ///     loop {
484        ///         // Wait for the socket to be readable
485        ///         stream.readable().await?;
486        ///
487        ///         let mut buf = Vec::with_capacity(4096);
488        ///
489        ///         // Try to read data, this may still fail with `WouldBlock`
490        ///         // if the readiness event is a false positive.
491        ///         match stream.try_read_buf(&mut buf) {
492        ///             Ok(0) => break,
493        ///             Ok(n) => {
494        ///                 println!("read {} bytes", n);
495        ///             }
496        ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
497        ///                 continue;
498        ///             }
499        ///             Err(e) => {
500        ///                 return Err(e.into());
501        ///             }
502        ///         }
503        ///     }
504        ///
505        ///     Ok(())
506        /// }
507        /// ```
508        pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
509            self.io.registration().try_io(Interest::READABLE, || {
510                use std::io::Read;
511
512                let dst = buf.chunk_mut();
513                let dst =
514                    unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
515
516                // Safety: We trust `UnixStream::read` to have filled up `n` bytes in the
517                // buffer.
518                let n = (&*self.io).read(dst)?;
519
520                unsafe {
521                    buf.advance_mut(n);
522                }
523
524                Ok(n)
525            })
526        }
527    }
528
529    /// Waits for the socket to become writable.
530    ///
531    /// This function is equivalent to `ready(Interest::WRITABLE)` and is usually
532    /// paired with `try_write()`.
533    ///
534    /// # Cancel safety
535    ///
536    /// This method is cancel safe. Once a readiness event occurs, the method
537    /// will continue to return immediately until the readiness event is
538    /// consumed by an attempt to write that fails with `WouldBlock` or
539    /// `Poll::Pending`.
540    ///
541    /// # Examples
542    ///
543    /// ```no_run
544    /// use tokio::net::UnixStream;
545    /// use std::error::Error;
546    /// use std::io;
547    ///
548    /// #[tokio::main]
549    /// async fn main() -> Result<(), Box<dyn Error>> {
550    ///     // Connect to a peer
551    ///     let dir = tempfile::tempdir().unwrap();
552    ///     let bind_path = dir.path().join("bind_path");
553    ///     let stream = UnixStream::connect(bind_path).await?;
554    ///
555    ///     loop {
556    ///         // Wait for the socket to be writable
557    ///         stream.writable().await?;
558    ///
559    ///         // Try to write data, this may still fail with `WouldBlock`
560    ///         // if the readiness event is a false positive.
561    ///         match stream.try_write(b"hello world") {
562    ///             Ok(n) => {
563    ///                 break;
564    ///             }
565    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
566    ///                 continue;
567    ///             }
568    ///             Err(e) => {
569    ///                 return Err(e.into());
570    ///             }
571    ///         }
572    ///     }
573    ///
574    ///     Ok(())
575    /// }
576    /// ```
577    pub async fn writable(&self) -> io::Result<()> {
578        self.ready(Interest::WRITABLE).await?;
579        Ok(())
580    }
581
582    /// Polls for write readiness.
583    ///
584    /// If the unix stream is not currently ready for writing, this method will
585    /// store a clone of the `Waker` from the provided `Context`. When the unix
586    /// stream becomes ready for writing, `Waker::wake` will be called on the
587    /// waker.
588    ///
589    /// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
590    /// the `Waker` from the `Context` passed to the most recent call is
591    /// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
592    /// second, independent waker.)
593    ///
594    /// This function is intended for cases where creating and pinning a future
595    /// via [`writable`] is not feasible. Where possible, using [`writable`] is
596    /// preferred, as this supports polling from multiple tasks at once.
597    ///
598    /// # Return value
599    ///
600    /// The function returns:
601    ///
602    /// * `Poll::Pending` if the unix stream is not ready for writing.
603    /// * `Poll::Ready(Ok(()))` if the unix stream is ready for writing.
604    /// * `Poll::Ready(Err(e))` if an error is encountered.
605    ///
606    /// # Errors
607    ///
608    /// This function may encounter any standard I/O error except `WouldBlock`.
609    ///
610    /// [`writable`]: method@Self::writable
611    pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
612        self.io.registration().poll_write_ready(cx).map_ok(|_| ())
613    }
614
615    /// Tries to write a buffer to the stream, returning how many bytes were
616    /// written.
617    ///
618    /// The function will attempt to write the entire contents of `buf`, but
619    /// only part of the buffer may be written.
620    ///
621    /// This function is usually paired with `writable()`.
622    ///
623    /// # Return
624    ///
625    /// If data is successfully written, `Ok(n)` is returned, where `n` is the
626    /// number of bytes written. If the stream is not ready to write data,
627    /// `Err(io::ErrorKind::WouldBlock)` is returned.
628    ///
629    /// # Examples
630    ///
631    /// ```no_run
632    /// use tokio::net::UnixStream;
633    /// use std::error::Error;
634    /// use std::io;
635    ///
636    /// #[tokio::main]
637    /// async fn main() -> Result<(), Box<dyn Error>> {
638    ///     // Connect to a peer
639    ///     let dir = tempfile::tempdir().unwrap();
640    ///     let bind_path = dir.path().join("bind_path");
641    ///     let stream = UnixStream::connect(bind_path).await?;
642    ///
643    ///     loop {
644    ///         // Wait for the socket to be writable
645    ///         stream.writable().await?;
646    ///
647    ///         // Try to write data, this may still fail with `WouldBlock`
648    ///         // if the readiness event is a false positive.
649    ///         match stream.try_write(b"hello world") {
650    ///             Ok(n) => {
651    ///                 break;
652    ///             }
653    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
654    ///                 continue;
655    ///             }
656    ///             Err(e) => {
657    ///                 return Err(e.into());
658    ///             }
659    ///         }
660    ///     }
661    ///
662    ///     Ok(())
663    /// }
664    /// ```
665    pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
666        self.io
667            .registration()
668            .try_io(Interest::WRITABLE, || (&*self.io).write(buf))
669    }
670
671    /// Tries to write several buffers to the stream, returning how many bytes
672    /// were written.
673    ///
674    /// Data is written from each buffer in order, with the final buffer read
675    /// from possible being only partially consumed. This method behaves
676    /// equivalently to a single call to [`try_write()`] with concatenated
677    /// buffers.
678    ///
679    /// This function is usually paired with `writable()`.
680    ///
681    /// [`try_write()`]: UnixStream::try_write()
682    ///
683    /// # Return
684    ///
685    /// If data is successfully written, `Ok(n)` is returned, where `n` is the
686    /// number of bytes written. If the stream is not ready to write data,
687    /// `Err(io::ErrorKind::WouldBlock)` is returned.
688    ///
689    /// # Examples
690    ///
691    /// ```no_run
692    /// use tokio::net::UnixStream;
693    /// use std::error::Error;
694    /// use std::io;
695    ///
696    /// #[tokio::main]
697    /// async fn main() -> Result<(), Box<dyn Error>> {
698    ///     // Connect to a peer
699    ///     let dir = tempfile::tempdir().unwrap();
700    ///     let bind_path = dir.path().join("bind_path");
701    ///     let stream = UnixStream::connect(bind_path).await?;
702    ///
703    ///     let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];
704    ///
705    ///     loop {
706    ///         // Wait for the socket to be writable
707    ///         stream.writable().await?;
708    ///
709    ///         // Try to write data, this may still fail with `WouldBlock`
710    ///         // if the readiness event is a false positive.
711    ///         match stream.try_write_vectored(&bufs) {
712    ///             Ok(n) => {
713    ///                 break;
714    ///             }
715    ///             Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
716    ///                 continue;
717    ///             }
718    ///             Err(e) => {
719    ///                 return Err(e.into());
720    ///             }
721    ///         }
722    ///     }
723    ///
724    ///     Ok(())
725    /// }
726    /// ```
727    pub fn try_write_vectored(&self, buf: &[io::IoSlice<'_>]) -> io::Result<usize> {
728        self.io
729            .registration()
730            .try_io(Interest::WRITABLE, || (&*self.io).write_vectored(buf))
731    }
732
733    /// Tries to read or write from the socket using a user-provided IO operation.
734    ///
735    /// If the socket is ready, the provided closure is called. The closure
736    /// should attempt to perform IO operation on the socket by manually
737    /// calling the appropriate syscall. If the operation fails because the
738    /// socket is not actually ready, then the closure should return a
739    /// `WouldBlock` error and the readiness flag is cleared. The return value
740    /// of the closure is then returned by `try_io`.
741    ///
742    /// If the socket is not ready, then the closure is not called
743    /// and a `WouldBlock` error is returned.
744    ///
745    /// The closure should only return a `WouldBlock` error if it has performed
746    /// an IO operation on the socket that failed due to the socket not being
747    /// ready. Returning a `WouldBlock` error in any other situation will
748    /// incorrectly clear the readiness flag, which can cause the socket to
749    /// behave incorrectly.
750    ///
751    /// The closure should not perform the IO operation using any of the methods
752    /// defined on the Tokio `UnixStream` type, as this will mess with the
753    /// readiness flag and can cause the socket to behave incorrectly.
754    ///
755    /// This method is not intended to be used with combined interests.
756    /// The closure should perform only one type of IO operation, so it should not
757    /// require more than one ready state. This method may panic or sleep forever
758    /// if it is called with a combined interest.
759    ///
760    /// Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.
761    ///
762    /// [`readable()`]: UnixStream::readable()
763    /// [`writable()`]: UnixStream::writable()
764    /// [`ready()`]: UnixStream::ready()
765    pub fn try_io<R>(
766        &self,
767        interest: Interest,
768        f: impl FnOnce() -> io::Result<R>,
769    ) -> io::Result<R> {
770        self.io
771            .registration()
772            .try_io(interest, || self.io.try_io(f))
773    }
774
775    /// Reads or writes from the socket using a user-provided IO operation.
776    ///
777    /// The readiness of the socket is awaited and when the socket is ready,
778    /// the provided closure is called. The closure should attempt to perform
779    /// IO operation on the socket by manually calling the appropriate syscall.
780    /// If the operation fails because the socket is not actually ready,
781    /// then the closure should return a `WouldBlock` error. In such case the
782    /// readiness flag is cleared and the socket readiness is awaited again.
783    /// This loop is repeated until the closure returns an `Ok` or an error
784    /// other than `WouldBlock`.
785    ///
786    /// The closure should only return a `WouldBlock` error if it has performed
787    /// an IO operation on the socket that failed due to the socket not being
788    /// ready. Returning a `WouldBlock` error in any other situation will
789    /// incorrectly clear the readiness flag, which can cause the socket to
790    /// behave incorrectly.
791    ///
792    /// The closure should not perform the IO operation using any of the methods
793    /// defined on the Tokio `UnixStream` type, as this will mess with the
794    /// readiness flag and can cause the socket to behave incorrectly.
795    ///
796    /// This method is not intended to be used with combined interests.
797    /// The closure should perform only one type of IO operation, so it should not
798    /// require more than one ready state. This method may panic or sleep forever
799    /// if it is called with a combined interest.
800    pub async fn async_io<R>(
801        &self,
802        interest: Interest,
803        mut f: impl FnMut() -> io::Result<R>,
804    ) -> io::Result<R> {
805        self.io
806            .registration()
807            .async_io(interest, || self.io.try_io(&mut f))
808            .await
809    }
810
811    /// Creates new [`UnixStream`] from a [`std::os::unix::net::UnixStream`].
812    ///
813    /// This function is intended to be used to wrap a `UnixStream` from the
814    /// standard library in the Tokio equivalent.
815    ///
816    /// # Notes
817    ///
818    /// The caller is responsible for ensuring that the stream is in
819    /// non-blocking mode. Otherwise all I/O operations on the stream
820    /// will block the thread, which will cause unexpected behavior.
821    /// Non-blocking mode can be set using [`set_nonblocking`].
822    ///
823    /// Passing a listener in blocking mode is always erroneous,
824    /// and the behavior in that case may change in the future.
825    /// For example, it could panic.
826    ///
827    /// [`set_nonblocking`]: std::os::unix::net::UnixStream::set_nonblocking
828    ///
829    /// # Examples
830    ///
831    /// ```no_run
832    /// use tokio::net::UnixStream;
833    /// use std::os::unix::net::UnixStream as StdUnixStream;
834    /// # use std::error::Error;
835    ///
836    /// # async fn dox() -> Result<(), Box<dyn Error>> {
837    /// let std_stream = StdUnixStream::connect("/path/to/the/socket")?;
838    /// std_stream.set_nonblocking(true)?;
839    /// let stream = UnixStream::from_std(std_stream)?;
840    /// # Ok(())
841    /// # }
842    /// ```
843    ///
844    /// # Panics
845    ///
846    /// This function panics if it is not called from within a runtime with
847    /// IO enabled.
848    ///
849    /// The runtime is usually set implicitly when this function is called
850    /// from a future driven by a tokio runtime, otherwise runtime can be set
851    /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
852    #[track_caller]
853    pub fn from_std(stream: net::UnixStream) -> io::Result<UnixStream> {
854        check_socket_for_blocking(&stream)?;
855
856        let stream = mio::net::UnixStream::from_std(stream);
857        let io = PollEvented::new(stream)?;
858
859        Ok(UnixStream { io })
860    }
861
862    /// Turns a [`tokio::net::UnixStream`] into a [`std::os::unix::net::UnixStream`].
863    ///
864    /// The returned [`std::os::unix::net::UnixStream`] will have nonblocking
865    /// mode set as `true`.  Use [`set_nonblocking`] to change the blocking
866    /// mode if needed.
867    ///
868    /// # Examples
869    ///
870    /// ```
871    /// use std::error::Error;
872    /// use std::io::Read;
873    /// use tokio::net::UnixListener;
874    /// # use tokio::net::UnixStream;
875    /// # use tokio::io::AsyncWriteExt;
876    ///
877    /// #[tokio::main]
878    /// async fn main() -> Result<(), Box<dyn Error>> {
879    /// #   if cfg!(miri) { return Ok(()); } // No Unix domain sockets in miri.
880    ///     let dir = tempfile::tempdir().unwrap();
881    ///     let bind_path = dir.path().join("bind_path");
882    ///
883    ///     let mut data = [0u8; 12];
884    ///     let listener = UnixListener::bind(&bind_path)?;
885    /// #   let handle = tokio::spawn(async {
886    /// #       let mut stream = UnixStream::connect(bind_path).await.unwrap();
887    /// #       stream.write(b"Hello world!").await.unwrap();
888    /// #   });
889    ///     let (tokio_unix_stream, _) = listener.accept().await?;
890    ///     let mut std_unix_stream = tokio_unix_stream.into_std()?;
891    /// #   handle.await.expect("The task being joined has panicked");
892    ///     std_unix_stream.set_nonblocking(false)?;
893    ///     std_unix_stream.read_exact(&mut data)?;
894    /// #   assert_eq!(b"Hello world!", &data);
895    ///     Ok(())
896    /// }
897    /// ```
898    /// [`tokio::net::UnixStream`]: UnixStream
899    /// [`std::os::unix::net::UnixStream`]: std::os::unix::net::UnixStream
900    /// [`set_nonblocking`]: fn@std::os::unix::net::UnixStream::set_nonblocking
901    pub fn into_std(self) -> io::Result<std::os::unix::net::UnixStream> {
902        self.io
903            .into_inner()
904            .map(IntoRawFd::into_raw_fd)
905            .map(|raw_fd| unsafe { std::os::unix::net::UnixStream::from_raw_fd(raw_fd) })
906    }
907
908    /// Creates an unnamed pair of connected sockets.
909    ///
910    /// This function will create a pair of interconnected Unix sockets for
911    /// communicating back and forth between one another. Each socket will
912    /// be associated with the default event loop's handle.
913    pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
914        let (a, b) = mio::net::UnixStream::pair()?;
915        let a = UnixStream::new(a)?;
916        let b = UnixStream::new(b)?;
917
918        Ok((a, b))
919    }
920
921    pub(crate) fn new(stream: mio::net::UnixStream) -> io::Result<UnixStream> {
922        let io = PollEvented::new(stream)?;
923        Ok(UnixStream { io })
924    }
925
926    /// Returns the socket address of the local half of this connection.
927    ///
928    /// # Examples
929    ///
930    /// ```no_run
931    /// use tokio::net::UnixStream;
932    ///
933    /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
934    /// let dir = tempfile::tempdir().unwrap();
935    /// let bind_path = dir.path().join("bind_path");
936    /// let stream = UnixStream::connect(bind_path).await?;
937    ///
938    /// println!("{:?}", stream.local_addr()?);
939    /// # Ok(())
940    /// # }
941    /// ```
942    pub fn local_addr(&self) -> io::Result<SocketAddr> {
943        self.io.local_addr().map(SocketAddr)
944    }
945
946    /// Returns the socket address of the remote half of this connection.
947    ///
948    /// # Examples
949    ///
950    /// ```no_run
951    /// use tokio::net::UnixStream;
952    ///
953    /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
954    /// let dir = tempfile::tempdir().unwrap();
955    /// let bind_path = dir.path().join("bind_path");
956    /// let stream = UnixStream::connect(bind_path).await?;
957    ///
958    /// println!("{:?}", stream.peer_addr()?);
959    /// # Ok(())
960    /// # }
961    /// ```
962    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
963        self.io.peer_addr().map(SocketAddr)
964    }
965
966    /// Returns effective credentials of the process which called `connect` or `pair`.
967    pub fn peer_cred(&self) -> io::Result<UCred> {
968        ucred::get_peer_cred(self)
969    }
970
971    /// Returns the value of the `SO_ERROR` option.
972    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
973        self.io.take_error()
974    }
975
976    /// Shuts down the read, write, or both halves of this connection.
977    ///
978    /// This function will cause all pending and future I/O calls on the
979    /// specified portions to immediately return with an appropriate value
980    /// (see the documentation of `Shutdown`).
981    pub(super) fn shutdown_std(&self, how: Shutdown) -> io::Result<()> {
982        self.io.shutdown(how)
983    }
984
985    // These lifetime markers also appear in the generated documentation, and make
986    // it more clear that this is a *borrowed* split.
987    #[allow(clippy::needless_lifetimes)]
988    /// Splits a `UnixStream` into a read half and a write half, which can be used
989    /// to read and write the stream concurrently.
990    ///
991    /// This method is more efficient than [`into_split`], but the halves cannot be
992    /// moved into independently spawned tasks.
993    ///
994    /// [`into_split`]: Self::into_split()
995    pub fn split<'a>(&'a mut self) -> (ReadHalf<'a>, WriteHalf<'a>) {
996        split(self)
997    }
998
999    /// Splits a `UnixStream` into a read half and a write half, which can be used
1000    /// to read and write the stream concurrently.
1001    ///
1002    /// Unlike [`split`], the owned halves can be moved to separate tasks, however
1003    /// this comes at the cost of a heap allocation.
1004    ///
1005    /// **Note:** Dropping the write half will only shut down the write half of the
1006    /// stream. This is equivalent to calling [`shutdown()`] on the `UnixStream`.
1007    ///
1008    /// [`split`]: Self::split()
1009    /// [`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown
1010    pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf) {
1011        split_owned(self)
1012    }
1013}
1014
1015impl TryFrom<net::UnixStream> for UnixStream {
1016    type Error = io::Error;
1017
1018    /// Consumes stream, returning the tokio I/O object.
1019    ///
1020    /// This is equivalent to
1021    /// [`UnixStream::from_std(stream)`](UnixStream::from_std).
1022    fn try_from(stream: net::UnixStream) -> io::Result<Self> {
1023        Self::from_std(stream)
1024    }
1025}
1026
1027impl AsyncRead for UnixStream {
1028    fn poll_read(
1029        self: Pin<&mut Self>,
1030        cx: &mut Context<'_>,
1031        buf: &mut ReadBuf<'_>,
1032    ) -> Poll<io::Result<()>> {
1033        self.poll_read_priv(cx, buf)
1034    }
1035}
1036
1037impl AsyncWrite for UnixStream {
1038    fn poll_write(
1039        self: Pin<&mut Self>,
1040        cx: &mut Context<'_>,
1041        buf: &[u8],
1042    ) -> Poll<io::Result<usize>> {
1043        self.poll_write_priv(cx, buf)
1044    }
1045
1046    fn poll_write_vectored(
1047        self: Pin<&mut Self>,
1048        cx: &mut Context<'_>,
1049        bufs: &[io::IoSlice<'_>],
1050    ) -> Poll<io::Result<usize>> {
1051        self.poll_write_vectored_priv(cx, bufs)
1052    }
1053
1054    fn is_write_vectored(&self) -> bool {
1055        true
1056    }
1057
1058    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
1059        Poll::Ready(Ok(()))
1060    }
1061
1062    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
1063        self.shutdown_std(std::net::Shutdown::Write)?;
1064        Poll::Ready(Ok(()))
1065    }
1066}
1067
1068impl UnixStream {
1069    // == Poll IO functions that takes `&self` ==
1070    //
1071    // To read or write without mutable access to the `UnixStream`, combine the
1072    // `poll_read_ready` or `poll_write_ready` methods with the `try_read` or
1073    // `try_write` methods.
1074
1075    pub(crate) fn poll_read_priv(
1076        &self,
1077        cx: &mut Context<'_>,
1078        buf: &mut ReadBuf<'_>,
1079    ) -> Poll<io::Result<()>> {
1080        // Safety: `UnixStream::read` correctly handles reads into uninitialized memory
1081        unsafe { self.io.poll_read(cx, buf) }
1082    }
1083
1084    pub(crate) fn poll_write_priv(
1085        &self,
1086        cx: &mut Context<'_>,
1087        buf: &[u8],
1088    ) -> Poll<io::Result<usize>> {
1089        self.io.poll_write(cx, buf)
1090    }
1091
1092    pub(super) fn poll_write_vectored_priv(
1093        &self,
1094        cx: &mut Context<'_>,
1095        bufs: &[io::IoSlice<'_>],
1096    ) -> Poll<io::Result<usize>> {
1097        self.io.poll_write_vectored(cx, bufs)
1098    }
1099}
1100
1101impl fmt::Debug for UnixStream {
1102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103        (*self.io).fmt(f)
1104    }
1105}
1106
1107impl AsRef<Self> for UnixStream {
1108    fn as_ref(&self) -> &Self {
1109        self
1110    }
1111}
1112
1113impl AsRawFd for UnixStream {
1114    fn as_raw_fd(&self) -> RawFd {
1115        self.io.as_raw_fd()
1116    }
1117}
1118
1119impl AsFd for UnixStream {
1120    fn as_fd(&self) -> BorrowedFd<'_> {
1121        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
1122    }
1123}