tokio/net/unix/pipe.rs
1//! Unix pipe types.
2
3use crate::io::interest::Interest;
4use crate::io::{AsyncRead, AsyncWrite, PollEvented, ReadBuf, Ready};
5
6use mio::unix::pipe as mio_pipe;
7use std::fs::File;
8use std::io::{self, Read, Write};
9use std::os::unix::fs::OpenOptionsExt;
10use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
11use std::path::Path;
12use std::pin::Pin;
13use std::task::{Context, Poll};
14
15cfg_io_util! {
16 use bytes::BufMut;
17}
18
19/// Creates a new anonymous Unix pipe.
20///
21/// This function will open a new pipe and associate both pipe ends with the default
22/// event loop.
23///
24/// If you need to create a pipe for communication with a spawned process, you can
25/// use [`Stdio::piped()`] instead.
26///
27/// [`Stdio::piped()`]: std::process::Stdio::piped
28///
29/// # Errors
30///
31/// If creating a pipe fails, this function will return with the related OS error.
32///
33/// # Examples
34///
35/// Create a pipe and pass the writing end to a spawned process.
36///
37/// ```no_run
38/// use tokio::net::unix::pipe;
39/// use tokio::process::Command;
40/// # use tokio::io::AsyncReadExt;
41/// # use std::error::Error;
42///
43/// # async fn dox() -> Result<(), Box<dyn Error>> {
44/// let (tx, mut rx) = pipe::pipe()?;
45/// let mut buffer = String::new();
46///
47/// let status = Command::new("echo")
48/// .arg("Hello, world!")
49/// .stdout(tx.into_blocking_fd()?)
50/// .status();
51/// rx.read_to_string(&mut buffer).await?;
52///
53/// assert!(status.await?.success());
54/// assert_eq!(buffer, "Hello, world!\n");
55/// # Ok(())
56/// # }
57/// ```
58///
59/// # Panics
60///
61/// This function panics if it is not called from within a runtime with
62/// IO enabled.
63///
64/// The runtime is usually set implicitly when this function is called
65/// from a future driven by a tokio runtime, otherwise runtime can be set
66/// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
67pub fn pipe() -> io::Result<(Sender, Receiver)> {
68 let (tx, rx) = mio_pipe::new()?;
69 Ok((Sender::from_mio(tx)?, Receiver::from_mio(rx)?))
70}
71
72/// Options and flags which can be used to configure how a FIFO file is opened.
73///
74/// This builder allows configuring how to create a pipe end from a FIFO file.
75/// Generally speaking, when using `OpenOptions`, you'll first call [`new`],
76/// then chain calls to methods to set each option, then call either
77/// [`open_receiver`] or [`open_sender`], passing the path of the FIFO file you
78/// are trying to open. This will give you a [`io::Result`] with a pipe end
79/// inside that you can further operate on.
80///
81/// [`new`]: OpenOptions::new
82/// [`open_receiver`]: OpenOptions::open_receiver
83/// [`open_sender`]: OpenOptions::open_sender
84///
85/// # Examples
86///
87/// Opening a pair of pipe ends from a FIFO file:
88///
89/// ```no_run
90/// use tokio::net::unix::pipe;
91/// # use std::error::Error;
92///
93/// const FIFO_NAME: &str = "path/to/a/fifo";
94///
95/// # async fn dox() -> Result<(), Box<dyn Error>> {
96/// let rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
97/// let tx = pipe::OpenOptions::new().open_sender(FIFO_NAME)?;
98/// # Ok(())
99/// # }
100/// ```
101///
102/// Opening a [`Sender`] on Linux when you are sure the file is a FIFO:
103///
104/// ```ignore
105/// use tokio::net::unix::pipe;
106/// use nix::{unistd::mkfifo, sys::stat::Mode};
107/// # use std::error::Error;
108///
109/// // Our program has exclusive access to this path.
110/// const FIFO_NAME: &str = "path/to/a/new/fifo";
111///
112/// # async fn dox() -> Result<(), Box<dyn Error>> {
113/// mkfifo(FIFO_NAME, Mode::S_IRWXU)?;
114/// let tx = pipe::OpenOptions::new()
115/// .read_write(true)
116/// .unchecked(true)
117/// .open_sender(FIFO_NAME)?;
118/// # Ok(())
119/// # }
120/// ```
121#[derive(Clone, Debug)]
122pub struct OpenOptions {
123 #[cfg(any(target_os = "linux", target_os = "android"))]
124 read_write: bool,
125 unchecked: bool,
126}
127
128impl OpenOptions {
129 /// Creates a blank new set of options ready for configuration.
130 ///
131 /// All options are initially set to `false`.
132 pub fn new() -> OpenOptions {
133 OpenOptions {
134 #[cfg(any(target_os = "linux", target_os = "android"))]
135 read_write: false,
136 unchecked: false,
137 }
138 }
139
140 /// Sets the option for read-write access.
141 ///
142 /// This option, when true, will indicate that a FIFO file will be opened
143 /// in read-write access mode. This operation is not defined by the POSIX
144 /// standard and is only guaranteed to work on Linux.
145 ///
146 /// # Examples
147 ///
148 /// Opening a [`Sender`] even if there are no open reading ends:
149 ///
150 /// ```ignore
151 /// use tokio::net::unix::pipe;
152 ///
153 /// let tx = pipe::OpenOptions::new()
154 /// .read_write(true)
155 /// .open_sender("path/to/a/fifo");
156 /// ```
157 ///
158 /// Opening a resilient [`Receiver`] i.e. a reading pipe end which will not
159 /// fail with [`UnexpectedEof`] during reading if all writing ends of the
160 /// pipe close the FIFO file.
161 ///
162 /// [`UnexpectedEof`]: std::io::ErrorKind::UnexpectedEof
163 ///
164 /// ```ignore
165 /// use tokio::net::unix::pipe;
166 ///
167 /// let tx = pipe::OpenOptions::new()
168 /// .read_write(true)
169 /// .open_receiver("path/to/a/fifo");
170 /// ```
171 #[cfg(any(target_os = "linux", target_os = "android"))]
172 #[cfg_attr(docsrs, doc(cfg(any(target_os = "linux", target_os = "android"))))]
173 pub fn read_write(&mut self, value: bool) -> &mut Self {
174 self.read_write = value;
175 self
176 }
177
178 /// Sets the option to skip the check for FIFO file type.
179 ///
180 /// By default, [`open_receiver`] and [`open_sender`] functions will check
181 /// if the opened file is a FIFO file. Set this option to `true` if you are
182 /// sure the file is a FIFO file.
183 ///
184 /// [`open_receiver`]: OpenOptions::open_receiver
185 /// [`open_sender`]: OpenOptions::open_sender
186 ///
187 /// # Examples
188 ///
189 /// ```no_run
190 /// use tokio::net::unix::pipe;
191 /// use nix::{unistd::mkfifo, sys::stat::Mode};
192 /// # use std::error::Error;
193 ///
194 /// // Our program has exclusive access to this path.
195 /// const FIFO_NAME: &str = "path/to/a/new/fifo";
196 ///
197 /// # async fn dox() -> Result<(), Box<dyn Error>> {
198 /// mkfifo(FIFO_NAME, Mode::S_IRWXU)?;
199 /// let rx = pipe::OpenOptions::new()
200 /// .unchecked(true)
201 /// .open_receiver(FIFO_NAME)?;
202 /// # Ok(())
203 /// # }
204 /// ```
205 pub fn unchecked(&mut self, value: bool) -> &mut Self {
206 self.unchecked = value;
207 self
208 }
209
210 /// Creates a [`Receiver`] from a FIFO file with the options specified by `self`.
211 ///
212 /// This function will open the FIFO file at the specified path, possibly
213 /// check if it is a pipe, and associate the pipe with the default event
214 /// loop for reading.
215 ///
216 /// # Errors
217 ///
218 /// If the file type check fails, this function will fail with `io::ErrorKind::InvalidInput`.
219 /// This function may also fail with other standard OS errors.
220 ///
221 /// # Panics
222 ///
223 /// This function panics if it is not called from within a runtime with
224 /// IO enabled.
225 ///
226 /// The runtime is usually set implicitly when this function is called
227 /// from a future driven by a tokio runtime, otherwise runtime can be set
228 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
229 pub fn open_receiver<P: AsRef<Path>>(&self, path: P) -> io::Result<Receiver> {
230 let file = self.open(path.as_ref(), PipeEnd::Receiver)?;
231 Receiver::from_file_unchecked(file)
232 }
233
234 /// Creates a [`Sender`] from a FIFO file with the options specified by `self`.
235 ///
236 /// This function will open the FIFO file at the specified path, possibly
237 /// check if it is a pipe, and associate the pipe with the default event
238 /// loop for writing.
239 ///
240 /// # Errors
241 ///
242 /// If the file type check fails, this function will fail with `io::ErrorKind::InvalidInput`.
243 /// If the file is not opened in read-write access mode and the file is not
244 /// currently open for reading, this function will fail with `ENXIO`.
245 /// This function may also fail with other standard OS errors.
246 ///
247 /// # Panics
248 ///
249 /// This function panics if it is not called from within a runtime with
250 /// IO enabled.
251 ///
252 /// The runtime is usually set implicitly when this function is called
253 /// from a future driven by a tokio runtime, otherwise runtime can be set
254 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
255 pub fn open_sender<P: AsRef<Path>>(&self, path: P) -> io::Result<Sender> {
256 let file = self.open(path.as_ref(), PipeEnd::Sender)?;
257 Sender::from_file_unchecked(file)
258 }
259
260 fn open(&self, path: &Path, pipe_end: PipeEnd) -> io::Result<File> {
261 let mut options = std::fs::OpenOptions::new();
262 options
263 .read(pipe_end == PipeEnd::Receiver)
264 .write(pipe_end == PipeEnd::Sender)
265 .custom_flags(libc::O_NONBLOCK);
266
267 #[cfg(any(target_os = "linux", target_os = "android"))]
268 if self.read_write {
269 options.read(true).write(true);
270 }
271
272 let file = options.open(path)?;
273
274 if !self.unchecked && !is_pipe(file.as_fd())? {
275 return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a pipe"));
276 }
277
278 Ok(file)
279 }
280}
281
282impl Default for OpenOptions {
283 fn default() -> OpenOptions {
284 OpenOptions::new()
285 }
286}
287
288#[derive(Clone, Copy, PartialEq, Eq, Debug)]
289enum PipeEnd {
290 Sender,
291 Receiver,
292}
293
294/// Writing end of a Unix pipe.
295///
296/// It can be constructed from a FIFO file with [`OpenOptions::open_sender`].
297///
298/// Opening a named pipe for writing involves a few steps.
299/// Call to [`OpenOptions::open_sender`] might fail with an error indicating
300/// different things:
301///
302/// * [`io::ErrorKind::NotFound`] - There is no file at the specified path.
303/// * [`io::ErrorKind::InvalidInput`] - The file exists, but it is not a FIFO.
304/// * [`ENXIO`] - The file is a FIFO, but no process has it open for reading.
305/// Sleep for a while and try again.
306/// * Other OS errors not specific to opening FIFO files.
307///
308/// Opening a `Sender` from a FIFO file should look like this:
309///
310/// ```no_run
311/// use tokio::net::unix::pipe;
312/// use tokio::time::{self, Duration};
313///
314/// const FIFO_NAME: &str = "path/to/a/fifo";
315///
316/// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
317/// // Wait for a reader to open the file.
318/// let tx = loop {
319/// match pipe::OpenOptions::new().open_sender(FIFO_NAME) {
320/// Ok(tx) => break tx,
321/// Err(e) if e.raw_os_error() == Some(libc::ENXIO) => {},
322/// Err(e) => return Err(e.into()),
323/// }
324///
325/// time::sleep(Duration::from_millis(50)).await;
326/// };
327/// # Ok(())
328/// # }
329/// ```
330///
331/// On Linux, it is possible to create a `Sender` without waiting in a sleeping
332/// loop. This is done by opening a named pipe in read-write access mode with
333/// `OpenOptions::read_write`. This way, a `Sender` can at the same time hold
334/// both a writing end and a reading end, and the latter allows to open a FIFO
335/// without [`ENXIO`] error since the pipe is open for reading as well.
336///
337/// `Sender` cannot be used to read from a pipe, so in practice the read access
338/// is only used when a FIFO is opened. However, using a `Sender` in read-write
339/// mode **may lead to lost data**, because written data will be dropped by the
340/// system as soon as all pipe ends are closed. To avoid lost data you have to
341/// make sure that a reading end has been opened before dropping a `Sender`.
342///
343/// Note that using read-write access mode with FIFO files is not defined by
344/// the POSIX standard and it is only guaranteed to work on Linux.
345///
346/// ```ignore
347/// use tokio::io::AsyncWriteExt;
348/// use tokio::net::unix::pipe;
349///
350/// const FIFO_NAME: &str = "path/to/a/fifo";
351///
352/// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
353/// let mut tx = pipe::OpenOptions::new()
354/// .read_write(true)
355/// .open_sender(FIFO_NAME)?;
356///
357/// // Asynchronously write to the pipe before a reader.
358/// tx.write_all(b"hello world").await?;
359/// # Ok(())
360/// # }
361/// ```
362///
363/// [`ENXIO`]: https://docs.rs/libc/latest/libc/constant.ENXIO.html
364#[derive(Debug)]
365pub struct Sender {
366 io: PollEvented<mio_pipe::Sender>,
367}
368
369impl Sender {
370 fn from_mio(mio_tx: mio_pipe::Sender) -> io::Result<Sender> {
371 let io = PollEvented::new_with_interest(mio_tx, Interest::WRITABLE)?;
372 Ok(Sender { io })
373 }
374
375 /// Creates a new `Sender` from a [`File`].
376 ///
377 /// This function is intended to construct a pipe from a [`File`] representing
378 /// a special FIFO file. It will check if the file is a pipe and has write access,
379 /// set it in non-blocking mode and perform the conversion.
380 ///
381 /// # Errors
382 ///
383 /// Fails with `io::ErrorKind::InvalidInput` if the file is not a pipe or it
384 /// does not have write access. Also fails with any standard OS error if it occurs.
385 ///
386 /// # Panics
387 ///
388 /// This function panics if it is not called from within a runtime with
389 /// IO enabled.
390 ///
391 /// The runtime is usually set implicitly when this function is called
392 /// from a future driven by a tokio runtime, otherwise runtime can be set
393 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
394 pub fn from_file(file: File) -> io::Result<Sender> {
395 Sender::from_owned_fd(file.into())
396 }
397
398 /// Creates a new `Sender` from an [`OwnedFd`].
399 ///
400 /// This function is intended to construct a pipe from an [`OwnedFd`] representing
401 /// an anonymous pipe or a special FIFO file. It will check if the file descriptor
402 /// is a pipe and has write access, set it in non-blocking mode and perform the
403 /// conversion.
404 ///
405 /// # Errors
406 ///
407 /// Fails with `io::ErrorKind::InvalidInput` if the file descriptor is not a pipe
408 /// or it does not have write access. Also fails with any standard OS error if it
409 /// occurs.
410 ///
411 /// # Panics
412 ///
413 /// This function panics if it is not called from within a runtime with
414 /// IO enabled.
415 ///
416 /// The runtime is usually set implicitly when this function is called
417 /// from a future driven by a tokio runtime, otherwise runtime can be set
418 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
419 pub fn from_owned_fd(owned_fd: OwnedFd) -> io::Result<Sender> {
420 if !is_pipe(owned_fd.as_fd())? {
421 return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a pipe"));
422 }
423
424 let flags = get_file_flags(owned_fd.as_fd())?;
425 if has_write_access(flags) {
426 set_nonblocking(owned_fd.as_fd(), flags)?;
427 Sender::from_owned_fd_unchecked(owned_fd)
428 } else {
429 Err(io::Error::new(
430 io::ErrorKind::InvalidInput,
431 "not in O_WRONLY or O_RDWR access mode",
432 ))
433 }
434 }
435
436 /// Creates a new `Sender` from a [`File`] without checking pipe properties.
437 ///
438 /// This function is intended to construct a pipe from a File representing
439 /// a special FIFO file. The conversion assumes nothing about the underlying
440 /// file; it is left up to the user to make sure it is opened with write access,
441 /// represents a pipe and is set in non-blocking mode.
442 ///
443 /// # Examples
444 ///
445 /// ```no_run
446 /// use tokio::net::unix::pipe;
447 /// use std::fs::OpenOptions;
448 /// use std::os::unix::fs::{FileTypeExt, OpenOptionsExt};
449 /// # use std::error::Error;
450 ///
451 /// const FIFO_NAME: &str = "path/to/a/fifo";
452 ///
453 /// # async fn dox() -> Result<(), Box<dyn Error>> {
454 /// let file = OpenOptions::new()
455 /// .write(true)
456 /// .custom_flags(libc::O_NONBLOCK)
457 /// .open(FIFO_NAME)?;
458 /// if file.metadata()?.file_type().is_fifo() {
459 /// let tx = pipe::Sender::from_file_unchecked(file)?;
460 /// /* use the Sender */
461 /// }
462 /// # Ok(())
463 /// # }
464 /// ```
465 ///
466 /// # Panics
467 ///
468 /// This function panics if it is not called from within a runtime with
469 /// IO enabled.
470 ///
471 /// The runtime is usually set implicitly when this function is called
472 /// from a future driven by a tokio runtime, otherwise runtime can be set
473 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
474 pub fn from_file_unchecked(file: File) -> io::Result<Sender> {
475 Sender::from_owned_fd_unchecked(file.into())
476 }
477
478 /// Creates a new `Sender` from an [`OwnedFd`] without checking pipe properties.
479 ///
480 /// This function is intended to construct a pipe from an [`OwnedFd`] representing
481 /// an anonymous pipe or a special FIFO file. The conversion assumes nothing about
482 /// the underlying pipe; it is left up to the user to make sure that the file
483 /// descriptor represents the writing end of a pipe and the pipe is set in
484 /// non-blocking mode.
485 ///
486 /// # Panics
487 ///
488 /// This function panics if it is not called from within a runtime with
489 /// IO enabled.
490 ///
491 /// The runtime is usually set implicitly when this function is called
492 /// from a future driven by a tokio runtime, otherwise runtime can be set
493 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
494 pub fn from_owned_fd_unchecked(owned_fd: OwnedFd) -> io::Result<Sender> {
495 // Safety: OwnedFd represents a valid, open file descriptor.
496 let mio_tx = unsafe { mio_pipe::Sender::from_raw_fd(owned_fd.into_raw_fd()) };
497 Sender::from_mio(mio_tx)
498 }
499
500 /// Waits for any of the requested ready states.
501 ///
502 /// This function can be used instead of [`writable()`] to check the returned
503 /// ready set for [`Ready::WRITABLE`] and [`Ready::WRITE_CLOSED`] events.
504 ///
505 /// The function may complete without the pipe being ready. This is a
506 /// false-positive and attempting an operation will return with
507 /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
508 /// [`Ready`] set, so you should always check the returned value and possibly
509 /// wait again if the requested states are not set.
510 ///
511 /// [`writable()`]: Self::writable
512 ///
513 /// # Cancel safety
514 ///
515 /// This method is cancel safe. Once a readiness event occurs, the method
516 /// will continue to return immediately until the readiness event is
517 /// consumed by an attempt to write that fails with `WouldBlock` or
518 /// `Poll::Pending`.
519 pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
520 let event = self.io.registration().readiness(interest).await?;
521 Ok(event.ready)
522 }
523
524 /// Waits for the pipe to become writable.
525 ///
526 /// This function is equivalent to `ready(Interest::WRITABLE)` and is usually
527 /// paired with [`try_write()`].
528 ///
529 /// [`try_write()`]: Self::try_write
530 ///
531 /// # Examples
532 ///
533 /// ```no_run
534 /// use tokio::net::unix::pipe;
535 /// use std::io;
536 ///
537 /// #[tokio::main]
538 /// async fn main() -> io::Result<()> {
539 /// // Open a writing end of a fifo
540 /// let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;
541 ///
542 /// loop {
543 /// // Wait for the pipe to be writable
544 /// tx.writable().await?;
545 ///
546 /// // Try to write data, this may still fail with `WouldBlock`
547 /// // if the readiness event is a false positive.
548 /// match tx.try_write(b"hello world") {
549 /// Ok(n) => {
550 /// break;
551 /// }
552 /// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
553 /// continue;
554 /// }
555 /// Err(e) => {
556 /// return Err(e.into());
557 /// }
558 /// }
559 /// }
560 ///
561 /// Ok(())
562 /// }
563 /// ```
564 pub async fn writable(&self) -> io::Result<()> {
565 self.ready(Interest::WRITABLE).await?;
566 Ok(())
567 }
568
569 /// Polls for write readiness.
570 ///
571 /// If the pipe is not currently ready for writing, this method will
572 /// store a clone of the `Waker` from the provided `Context`. When the pipe
573 /// becomes ready for writing, `Waker::wake` will be called on the waker.
574 ///
575 /// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
576 /// the `Waker` from the `Context` passed to the most recent call is
577 /// scheduled to receive a wakeup.
578 ///
579 /// This function is intended for cases where creating and pinning a future
580 /// via [`writable`] is not feasible. Where possible, using [`writable`] is
581 /// preferred, as this supports polling from multiple tasks at once.
582 ///
583 /// [`writable`]: Self::writable
584 ///
585 /// # Return value
586 ///
587 /// The function returns:
588 ///
589 /// * `Poll::Pending` if the pipe is not ready for writing.
590 /// * `Poll::Ready(Ok(()))` if the pipe is ready for writing.
591 /// * `Poll::Ready(Err(e))` if an error is encountered.
592 ///
593 /// # Errors
594 ///
595 /// This function may encounter any standard I/O error except `WouldBlock`.
596 pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
597 self.io.registration().poll_write_ready(cx).map_ok(|_| ())
598 }
599
600 /// Tries to write a buffer to the pipe, returning how many bytes were
601 /// written.
602 ///
603 /// The function will attempt to write the entire contents of `buf`, but
604 /// only part of the buffer may be written. If the length of `buf` is not
605 /// greater than `PIPE_BUF` (an OS constant, 4096 under Linux), then the
606 /// write is guaranteed to be atomic, i.e. either the entire content of
607 /// `buf` will be written or this method will fail with `WouldBlock`. There
608 /// is no such guarantee if `buf` is larger than `PIPE_BUF`.
609 ///
610 /// This function is usually paired with [`writable`].
611 ///
612 /// [`writable`]: Self::writable
613 ///
614 /// # Return
615 ///
616 /// If data is successfully written, `Ok(n)` is returned, where `n` is the
617 /// number of bytes written. If the pipe is not ready to write data,
618 /// `Err(io::ErrorKind::WouldBlock)` is returned.
619 ///
620 /// # Examples
621 ///
622 /// ```no_run
623 /// use tokio::net::unix::pipe;
624 /// use std::io;
625 ///
626 /// #[tokio::main]
627 /// async fn main() -> io::Result<()> {
628 /// // Open a writing end of a fifo
629 /// let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;
630 ///
631 /// loop {
632 /// // Wait for the pipe to be writable
633 /// tx.writable().await?;
634 ///
635 /// // Try to write data, this may still fail with `WouldBlock`
636 /// // if the readiness event is a false positive.
637 /// match tx.try_write(b"hello world") {
638 /// Ok(n) => {
639 /// break;
640 /// }
641 /// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
642 /// continue;
643 /// }
644 /// Err(e) => {
645 /// return Err(e.into());
646 /// }
647 /// }
648 /// }
649 ///
650 /// Ok(())
651 /// }
652 /// ```
653 pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
654 self.io
655 .registration()
656 .try_io(Interest::WRITABLE, || (&*self.io).write(buf))
657 }
658
659 /// Tries to write several buffers to the pipe, returning how many bytes
660 /// were written.
661 ///
662 /// Data is written from each buffer in order, with the final buffer read
663 /// from possible being only partially consumed. This method behaves
664 /// equivalently to a single call to [`try_write()`] with concatenated
665 /// buffers.
666 ///
667 /// If the total length of buffers is not greater than `PIPE_BUF` (an OS
668 /// constant, 4096 under Linux), then the write is guaranteed to be atomic,
669 /// i.e. either the entire contents of buffers will be written or this
670 /// method will fail with `WouldBlock`. There is no such guarantee if the
671 /// total length of buffers is greater than `PIPE_BUF`.
672 ///
673 /// This function is usually paired with [`writable`].
674 ///
675 /// [`try_write()`]: Self::try_write()
676 /// [`writable`]: Self::writable
677 ///
678 /// # Return
679 ///
680 /// If data is successfully written, `Ok(n)` is returned, where `n` is the
681 /// number of bytes written. If the pipe is not ready to write data,
682 /// `Err(io::ErrorKind::WouldBlock)` is returned.
683 ///
684 /// # Examples
685 ///
686 /// ```no_run
687 /// use tokio::net::unix::pipe;
688 /// use std::io;
689 ///
690 /// #[tokio::main]
691 /// async fn main() -> io::Result<()> {
692 /// // Open a writing end of a fifo
693 /// let tx = pipe::OpenOptions::new().open_sender("path/to/a/fifo")?;
694 ///
695 /// let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];
696 ///
697 /// loop {
698 /// // Wait for the pipe to be writable
699 /// tx.writable().await?;
700 ///
701 /// // Try to write data, this may still fail with `WouldBlock`
702 /// // if the readiness event is a false positive.
703 /// match tx.try_write_vectored(&bufs) {
704 /// Ok(n) => {
705 /// break;
706 /// }
707 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
708 /// continue;
709 /// }
710 /// Err(e) => {
711 /// return Err(e.into());
712 /// }
713 /// }
714 /// }
715 ///
716 /// Ok(())
717 /// }
718 /// ```
719 pub fn try_write_vectored(&self, buf: &[io::IoSlice<'_>]) -> io::Result<usize> {
720 self.io
721 .registration()
722 .try_io(Interest::WRITABLE, || (&*self.io).write_vectored(buf))
723 }
724
725 /// Tries to write from the socket using a user-provided IO operation.
726 ///
727 /// If the socket is ready, the provided closure is called. The closure
728 /// should attempt to perform IO operation on the socket by manually
729 /// calling the appropriate syscall. If the operation fails because the
730 /// socket is not actually ready, then the closure should return a
731 /// `WouldBlock` error and the readiness flag is cleared. The return value
732 /// of the closure is then returned by `try_io`.
733 ///
734 /// If the socket is not ready, then the closure is not called
735 /// and a `WouldBlock` error is returned.
736 ///
737 /// The closure should only return a `WouldBlock` error if it has performed
738 /// an IO operation on the socket that failed due to the socket not being
739 /// ready. Returning a `WouldBlock` error in any other situation will
740 /// incorrectly clear the readiness flag, which can cause the socket to
741 /// behave incorrectly.
742 ///
743 /// The closure should not perform the IO operation using any of the methods
744 /// defined on the Tokio `pipe::Sender` type, as this will mess with the
745 /// readiness flag and can cause the socket to behave incorrectly.
746 ///
747 /// Usually, [`writable()`] or [`ready()`] is used with this function.
748 ///
749 /// [`writable()`]: Self::writable()
750 /// [`ready()`]: Self::ready()
751 pub fn try_io<R>(&self, f: impl FnOnce() -> io::Result<R>) -> io::Result<R> {
752 self.io
753 .registration()
754 .try_io(Interest::WRITABLE, || self.io.try_io(f))
755 }
756
757 /// Converts the pipe into an [`OwnedFd`] in blocking mode.
758 ///
759 /// This function will deregister this pipe end from the event loop, set
760 /// it in blocking mode and perform the conversion.
761 pub fn into_blocking_fd(self) -> io::Result<OwnedFd> {
762 let fd = self.into_nonblocking_fd()?;
763 set_blocking(&fd)?;
764 Ok(fd)
765 }
766
767 /// Converts the pipe into an [`OwnedFd`] in nonblocking mode.
768 ///
769 /// This function will deregister this pipe end from the event loop and
770 /// perform the conversion. The returned file descriptor will be in nonblocking
771 /// mode.
772 pub fn into_nonblocking_fd(self) -> io::Result<OwnedFd> {
773 let mio_pipe = self.io.into_inner()?;
774
775 // Safety: the pipe is now deregistered from the event loop
776 // and we are the only owner of this pipe end.
777 let owned_fd = unsafe { OwnedFd::from_raw_fd(mio_pipe.into_raw_fd()) };
778
779 Ok(owned_fd)
780 }
781}
782
783impl AsyncWrite for Sender {
784 fn poll_write(
785 self: Pin<&mut Self>,
786 cx: &mut Context<'_>,
787 buf: &[u8],
788 ) -> Poll<io::Result<usize>> {
789 self.io.poll_write(cx, buf)
790 }
791
792 fn poll_write_vectored(
793 self: Pin<&mut Self>,
794 cx: &mut Context<'_>,
795 bufs: &[io::IoSlice<'_>],
796 ) -> Poll<io::Result<usize>> {
797 self.io.poll_write_vectored(cx, bufs)
798 }
799
800 fn is_write_vectored(&self) -> bool {
801 true
802 }
803
804 fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
805 Poll::Ready(Ok(()))
806 }
807
808 fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
809 Poll::Ready(Ok(()))
810 }
811}
812
813impl AsRawFd for Sender {
814 fn as_raw_fd(&self) -> RawFd {
815 self.io.as_raw_fd()
816 }
817}
818
819impl AsFd for Sender {
820 fn as_fd(&self) -> BorrowedFd<'_> {
821 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
822 }
823}
824
825/// Reading end of a Unix pipe.
826///
827/// It can be constructed from a FIFO file with [`OpenOptions::open_receiver`].
828///
829/// # Examples
830///
831/// Receiving messages from a named pipe in a loop:
832///
833/// ```no_run
834/// use tokio::net::unix::pipe;
835/// use tokio::io::{self, AsyncReadExt};
836///
837/// const FIFO_NAME: &str = "path/to/a/fifo";
838///
839/// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
840/// let mut rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
841/// loop {
842/// let mut msg = vec![0; 256];
843/// match rx.read_exact(&mut msg).await {
844/// Ok(_) => {
845/// /* handle the message */
846/// }
847/// Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
848/// // Writing end has been closed, we should reopen the pipe.
849/// rx = pipe::OpenOptions::new().open_receiver(FIFO_NAME)?;
850/// }
851/// Err(e) => return Err(e.into()),
852/// }
853/// }
854/// # }
855/// ```
856///
857/// On Linux, you can use a `Receiver` in read-write access mode to implement
858/// resilient reading from a named pipe. Unlike `Receiver` opened in read-only
859/// mode, read from a pipe in read-write mode will not fail with `UnexpectedEof`
860/// when the writing end is closed. This way, a `Receiver` can asynchronously
861/// wait for the next writer to open the pipe.
862///
863/// You should not use functions waiting for EOF such as [`read_to_end`] with
864/// a `Receiver` in read-write access mode, since it **may wait forever**.
865/// `Receiver` in this mode also holds an open writing end, which prevents
866/// receiving EOF.
867///
868/// To set the read-write access mode you can use `OpenOptions::read_write`.
869/// Note that using read-write access mode with FIFO files is not defined by
870/// the POSIX standard and it is only guaranteed to work on Linux.
871///
872/// ```ignore
873/// use tokio::net::unix::pipe;
874/// use tokio::io::AsyncReadExt;
875/// # use std::error::Error;
876///
877/// const FIFO_NAME: &str = "path/to/a/fifo";
878///
879/// # async fn dox() -> Result<(), Box<dyn Error>> {
880/// let mut rx = pipe::OpenOptions::new()
881/// .read_write(true)
882/// .open_receiver(FIFO_NAME)?;
883/// loop {
884/// let mut msg = vec![0; 256];
885/// rx.read_exact(&mut msg).await?;
886/// /* handle the message */
887/// }
888/// # }
889/// ```
890///
891/// [`read_to_end`]: crate::io::AsyncReadExt::read_to_end
892#[derive(Debug)]
893pub struct Receiver {
894 io: PollEvented<mio_pipe::Receiver>,
895}
896
897impl Receiver {
898 fn from_mio(mio_rx: mio_pipe::Receiver) -> io::Result<Receiver> {
899 let io = PollEvented::new_with_interest(mio_rx, Interest::READABLE)?;
900 Ok(Receiver { io })
901 }
902
903 /// Creates a new `Receiver` from a [`File`].
904 ///
905 /// This function is intended to construct a pipe from a [`File`] representing
906 /// a special FIFO file. It will check if the file is a pipe and has read access,
907 /// set it in non-blocking mode and perform the conversion.
908 ///
909 /// # Errors
910 ///
911 /// Fails with `io::ErrorKind::InvalidInput` if the file is not a pipe or it
912 /// does not have read access. Also fails with any standard OS error if it occurs.
913 ///
914 /// # Panics
915 ///
916 /// This function panics if it is not called from within a runtime with
917 /// IO enabled.
918 ///
919 /// The runtime is usually set implicitly when this function is called
920 /// from a future driven by a tokio runtime, otherwise runtime can be set
921 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
922 pub fn from_file(file: File) -> io::Result<Receiver> {
923 Receiver::from_owned_fd(file.into())
924 }
925
926 /// Creates a new `Receiver` from an [`OwnedFd`].
927 ///
928 /// This function is intended to construct a pipe from an [`OwnedFd`] representing
929 /// an anonymous pipe or a special FIFO file. It will check if the file descriptor
930 /// is a pipe and has read access, set it in non-blocking mode and perform the
931 /// conversion.
932 ///
933 /// # Errors
934 ///
935 /// Fails with `io::ErrorKind::InvalidInput` if the file descriptor is not a pipe
936 /// or it does not have read access. Also fails with any standard OS error if it
937 /// occurs.
938 ///
939 /// # Panics
940 ///
941 /// This function panics if it is not called from within a runtime with
942 /// IO enabled.
943 ///
944 /// The runtime is usually set implicitly when this function is called
945 /// from a future driven by a tokio runtime, otherwise runtime can be set
946 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
947 pub fn from_owned_fd(owned_fd: OwnedFd) -> io::Result<Receiver> {
948 if !is_pipe(owned_fd.as_fd())? {
949 return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a pipe"));
950 }
951
952 let flags = get_file_flags(owned_fd.as_fd())?;
953 if has_read_access(flags) {
954 set_nonblocking(owned_fd.as_fd(), flags)?;
955 Receiver::from_owned_fd_unchecked(owned_fd)
956 } else {
957 Err(io::Error::new(
958 io::ErrorKind::InvalidInput,
959 "not in O_RDONLY or O_RDWR access mode",
960 ))
961 }
962 }
963
964 /// Creates a new `Receiver` from a [`File`] without checking pipe properties.
965 ///
966 /// This function is intended to construct a pipe from a File representing
967 /// a special FIFO file. The conversion assumes nothing about the underlying
968 /// file; it is left up to the user to make sure it is opened with read access,
969 /// represents a pipe and is set in non-blocking mode.
970 ///
971 /// # Examples
972 ///
973 /// ```no_run
974 /// use tokio::net::unix::pipe;
975 /// use std::fs::OpenOptions;
976 /// use std::os::unix::fs::{FileTypeExt, OpenOptionsExt};
977 /// # use std::error::Error;
978 ///
979 /// const FIFO_NAME: &str = "path/to/a/fifo";
980 ///
981 /// # async fn dox() -> Result<(), Box<dyn Error>> {
982 /// let file = OpenOptions::new()
983 /// .read(true)
984 /// .custom_flags(libc::O_NONBLOCK)
985 /// .open(FIFO_NAME)?;
986 /// if file.metadata()?.file_type().is_fifo() {
987 /// let rx = pipe::Receiver::from_file_unchecked(file)?;
988 /// /* use the Receiver */
989 /// }
990 /// # Ok(())
991 /// # }
992 /// ```
993 ///
994 /// # Panics
995 ///
996 /// This function panics if it is not called from within a runtime with
997 /// IO enabled.
998 ///
999 /// The runtime is usually set implicitly when this function is called
1000 /// from a future driven by a tokio runtime, otherwise runtime can be set
1001 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
1002 pub fn from_file_unchecked(file: File) -> io::Result<Receiver> {
1003 Receiver::from_owned_fd_unchecked(file.into())
1004 }
1005
1006 /// Creates a new `Receiver` from an [`OwnedFd`] without checking pipe properties.
1007 ///
1008 /// This function is intended to construct a pipe from an [`OwnedFd`] representing
1009 /// an anonymous pipe or a special FIFO file. The conversion assumes nothing about
1010 /// the underlying pipe; it is left up to the user to make sure that the file
1011 /// descriptor represents the reading end of a pipe and the pipe is set in
1012 /// non-blocking mode.
1013 ///
1014 /// # Panics
1015 ///
1016 /// This function panics if it is not called from within a runtime with
1017 /// IO enabled.
1018 ///
1019 /// The runtime is usually set implicitly when this function is called
1020 /// from a future driven by a tokio runtime, otherwise runtime can be set
1021 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
1022 pub fn from_owned_fd_unchecked(owned_fd: OwnedFd) -> io::Result<Receiver> {
1023 // Safety: OwnedFd represents a valid, open file descriptor.
1024 let mio_rx = unsafe { mio_pipe::Receiver::from_raw_fd(owned_fd.into_raw_fd()) };
1025 Receiver::from_mio(mio_rx)
1026 }
1027
1028 /// Waits for any of the requested ready states.
1029 ///
1030 /// This function can be used instead of [`readable()`] to check the returned
1031 /// ready set for [`Ready::READABLE`] and [`Ready::READ_CLOSED`] events.
1032 ///
1033 /// The function may complete without the pipe being ready. This is a
1034 /// false-positive and attempting an operation will return with
1035 /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
1036 /// [`Ready`] set, so you should always check the returned value and possibly
1037 /// wait again if the requested states are not set.
1038 ///
1039 /// [`readable()`]: Self::readable
1040 ///
1041 /// # Cancel safety
1042 ///
1043 /// This method is cancel safe. Once a readiness event occurs, the method
1044 /// will continue to return immediately until the readiness event is
1045 /// consumed by an attempt to read that fails with `WouldBlock` or
1046 /// `Poll::Pending`.
1047 pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
1048 let event = self.io.registration().readiness(interest).await?;
1049 Ok(event.ready)
1050 }
1051
1052 /// Waits for the pipe to become readable.
1053 ///
1054 /// This function is equivalent to `ready(Interest::READABLE)` and is usually
1055 /// paired with [`try_read()`].
1056 ///
1057 /// [`try_read()`]: Self::try_read()
1058 ///
1059 /// # Examples
1060 ///
1061 /// ```no_run
1062 /// use tokio::net::unix::pipe;
1063 /// use std::io;
1064 ///
1065 /// #[tokio::main]
1066 /// async fn main() -> io::Result<()> {
1067 /// // Open a reading end of a fifo
1068 /// let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;
1069 ///
1070 /// let mut msg = vec![0; 1024];
1071 ///
1072 /// loop {
1073 /// // Wait for the pipe to be readable
1074 /// rx.readable().await?;
1075 ///
1076 /// // Try to read data, this may still fail with `WouldBlock`
1077 /// // if the readiness event is a false positive.
1078 /// match rx.try_read(&mut msg) {
1079 /// Ok(n) => {
1080 /// msg.truncate(n);
1081 /// break;
1082 /// }
1083 /// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
1084 /// continue;
1085 /// }
1086 /// Err(e) => {
1087 /// return Err(e.into());
1088 /// }
1089 /// }
1090 /// }
1091 ///
1092 /// println!("GOT = {:?}", msg);
1093 /// Ok(())
1094 /// }
1095 /// ```
1096 pub async fn readable(&self) -> io::Result<()> {
1097 self.ready(Interest::READABLE).await?;
1098 Ok(())
1099 }
1100
1101 /// Polls for read readiness.
1102 ///
1103 /// If the pipe is not currently ready for reading, this method will
1104 /// store a clone of the `Waker` from the provided `Context`. When the pipe
1105 /// becomes ready for reading, `Waker::wake` will be called on the waker.
1106 ///
1107 /// Note that on multiple calls to `poll_read_ready` or `poll_read`, only
1108 /// the `Waker` from the `Context` passed to the most recent call is
1109 /// scheduled to receive a wakeup.
1110 ///
1111 /// This function is intended for cases where creating and pinning a future
1112 /// via [`readable`] is not feasible. Where possible, using [`readable`] is
1113 /// preferred, as this supports polling from multiple tasks at once.
1114 ///
1115 /// [`readable`]: Self::readable
1116 ///
1117 /// # Return value
1118 ///
1119 /// The function returns:
1120 ///
1121 /// * `Poll::Pending` if the pipe is not ready for reading.
1122 /// * `Poll::Ready(Ok(()))` if the pipe is ready for reading.
1123 /// * `Poll::Ready(Err(e))` if an error is encountered.
1124 ///
1125 /// # Errors
1126 ///
1127 /// This function may encounter any standard I/O error except `WouldBlock`.
1128 pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1129 self.io.registration().poll_read_ready(cx).map_ok(|_| ())
1130 }
1131
1132 /// Tries to read data from the pipe into the provided buffer, returning how
1133 /// many bytes were read.
1134 ///
1135 /// Reads any pending data from the pipe but does not wait for new data
1136 /// to arrive. On success, returns the number of bytes read. Because
1137 /// `try_read()` is non-blocking, the buffer does not have to be stored by
1138 /// the async task and can exist entirely on the stack.
1139 ///
1140 /// Usually [`readable()`] is used with this function.
1141 ///
1142 /// [`readable()`]: Self::readable()
1143 ///
1144 /// # Return
1145 ///
1146 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
1147 /// number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:
1148 ///
1149 /// 1. The pipe's writing end is closed and will no longer write data.
1150 /// 2. The specified buffer was 0 bytes in length.
1151 ///
1152 /// If the pipe is not ready to read data,
1153 /// `Err(io::ErrorKind::WouldBlock)` is returned.
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```no_run
1158 /// use tokio::net::unix::pipe;
1159 /// use std::io;
1160 ///
1161 /// #[tokio::main]
1162 /// async fn main() -> io::Result<()> {
1163 /// // Open a reading end of a fifo
1164 /// let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;
1165 ///
1166 /// let mut msg = vec![0; 1024];
1167 ///
1168 /// loop {
1169 /// // Wait for the pipe to be readable
1170 /// rx.readable().await?;
1171 ///
1172 /// // Try to read data, this may still fail with `WouldBlock`
1173 /// // if the readiness event is a false positive.
1174 /// match rx.try_read(&mut msg) {
1175 /// Ok(n) => {
1176 /// msg.truncate(n);
1177 /// break;
1178 /// }
1179 /// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
1180 /// continue;
1181 /// }
1182 /// Err(e) => {
1183 /// return Err(e.into());
1184 /// }
1185 /// }
1186 /// }
1187 ///
1188 /// println!("GOT = {:?}", msg);
1189 /// Ok(())
1190 /// }
1191 /// ```
1192 pub fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
1193 self.io
1194 .registration()
1195 .try_io(Interest::READABLE, || (&*self.io).read(buf))
1196 }
1197
1198 /// Tries to read data from the pipe into the provided buffers, returning
1199 /// how many bytes were read.
1200 ///
1201 /// Data is copied to fill each buffer in order, with the final buffer
1202 /// written to possibly being only partially filled. This method behaves
1203 /// equivalently to a single call to [`try_read()`] with concatenated
1204 /// buffers.
1205 ///
1206 /// Reads any pending data from the pipe but does not wait for new data
1207 /// to arrive. On success, returns the number of bytes read. Because
1208 /// `try_read_vectored()` is non-blocking, the buffer does not have to be
1209 /// stored by the async task and can exist entirely on the stack.
1210 ///
1211 /// Usually, [`readable()`] is used with this function.
1212 ///
1213 /// [`try_read()`]: Self::try_read()
1214 /// [`readable()`]: Self::readable()
1215 ///
1216 /// # Return
1217 ///
1218 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
1219 /// number of bytes read. `Ok(0)` indicates the pipe's writing end is
1220 /// closed and will no longer write data. If the pipe is not ready to read
1221 /// data `Err(io::ErrorKind::WouldBlock)` is returned.
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```no_run
1226 /// use tokio::net::unix::pipe;
1227 /// use std::io;
1228 ///
1229 /// #[tokio::main]
1230 /// async fn main() -> io::Result<()> {
1231 /// // Open a reading end of a fifo
1232 /// let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;
1233 ///
1234 /// loop {
1235 /// // Wait for the pipe to be readable
1236 /// rx.readable().await?;
1237 ///
1238 /// // Creating the buffer **after** the `await` prevents it from
1239 /// // being stored in the async task.
1240 /// let mut buf_a = [0; 512];
1241 /// let mut buf_b = [0; 1024];
1242 /// let mut bufs = [
1243 /// io::IoSliceMut::new(&mut buf_a),
1244 /// io::IoSliceMut::new(&mut buf_b),
1245 /// ];
1246 ///
1247 /// // Try to read data, this may still fail with `WouldBlock`
1248 /// // if the readiness event is a false positive.
1249 /// match rx.try_read_vectored(&mut bufs) {
1250 /// Ok(0) => break,
1251 /// Ok(n) => {
1252 /// println!("read {} bytes", n);
1253 /// }
1254 /// Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
1255 /// continue;
1256 /// }
1257 /// Err(e) => {
1258 /// return Err(e.into());
1259 /// }
1260 /// }
1261 /// }
1262 ///
1263 /// Ok(())
1264 /// }
1265 /// ```
1266 pub fn try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
1267 self.io
1268 .registration()
1269 .try_io(Interest::READABLE, || (&*self.io).read_vectored(bufs))
1270 }
1271
1272 /// Tries to read to the socket using a user-provided IO operation.
1273 ///
1274 /// If the socket is ready, the provided closure is called. The closure
1275 /// should attempt to perform IO operation on the socket by manually
1276 /// calling the appropriate syscall. If the operation fails because the
1277 /// socket is not actually ready, then the closure should return a
1278 /// `WouldBlock` error and the readiness flag is cleared. The return value
1279 /// of the closure is then returned by `try_io`.
1280 ///
1281 /// If the socket is not ready, then the closure is not called
1282 /// and a `WouldBlock` error is returned.
1283 ///
1284 /// The closure should only return a `WouldBlock` error if it has performed
1285 /// an IO operation on the socket that failed due to the socket not being
1286 /// ready. Returning a `WouldBlock` error in any other situation will
1287 /// incorrectly clear the readiness flag, which can cause the socket to
1288 /// behave incorrectly.
1289 ///
1290 /// The closure should not perform the IO operation using any of the methods
1291 /// defined on the Tokio `pipe::Receiver` type, as this will mess with the
1292 /// readiness flag and can cause the socket to behave incorrectly.
1293 ///
1294 /// Usually, [`readable()`] or [`ready()`] is used with this function.
1295 ///
1296 /// [`readable()`]: Self::readable()
1297 /// [`ready()`]: Self::ready()
1298 pub fn try_io<R>(&self, f: impl FnOnce() -> io::Result<R>) -> io::Result<R> {
1299 self.io
1300 .registration()
1301 .try_io(Interest::READABLE, || self.io.try_io(f))
1302 }
1303
1304 cfg_io_util! {
1305 /// Tries to read data from the pipe into the provided buffer, advancing the
1306 /// buffer's internal cursor, returning how many bytes were read.
1307 ///
1308 /// Reads any pending data from the pipe but does not wait for new data
1309 /// to arrive. On success, returns the number of bytes read. Because
1310 /// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
1311 /// the async task and can exist entirely on the stack.
1312 ///
1313 /// Usually, [`readable()`] or [`ready()`] is used with this function.
1314 ///
1315 /// [`readable()`]: Self::readable
1316 /// [`ready()`]: Self::ready
1317 ///
1318 /// # Return
1319 ///
1320 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
1321 /// number of bytes read. `Ok(0)` indicates the pipe's writing end is
1322 /// closed and will no longer write data. If the pipe is not ready to read
1323 /// data `Err(io::ErrorKind::WouldBlock)` is returned.
1324 ///
1325 /// # Examples
1326 ///
1327 /// ```no_run
1328 /// use tokio::net::unix::pipe;
1329 /// use std::io;
1330 ///
1331 /// #[tokio::main]
1332 /// async fn main() -> io::Result<()> {
1333 /// // Open a reading end of a fifo
1334 /// let rx = pipe::OpenOptions::new().open_receiver("path/to/a/fifo")?;
1335 ///
1336 /// loop {
1337 /// // Wait for the pipe to be readable
1338 /// rx.readable().await?;
1339 ///
1340 /// let mut buf = Vec::with_capacity(4096);
1341 ///
1342 /// // Try to read data, this may still fail with `WouldBlock`
1343 /// // if the readiness event is a false positive.
1344 /// match rx.try_read_buf(&mut buf) {
1345 /// Ok(0) => break,
1346 /// Ok(n) => {
1347 /// println!("read {} bytes", n);
1348 /// }
1349 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
1350 /// continue;
1351 /// }
1352 /// Err(e) => {
1353 /// return Err(e.into());
1354 /// }
1355 /// }
1356 /// }
1357 ///
1358 /// Ok(())
1359 /// }
1360 /// ```
1361 pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
1362 self.io.registration().try_io(Interest::READABLE, || {
1363 use std::io::Read;
1364
1365 let dst = buf.chunk_mut();
1366 let dst =
1367 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
1368
1369 // Safety: `mio_pipe::Receiver` uses a `std::fs::File` underneath,
1370 // which correctly handles reads into uninitialized memory.
1371 let n = (&*self.io).read(dst)?;
1372
1373 unsafe {
1374 buf.advance_mut(n);
1375 }
1376
1377 Ok(n)
1378 })
1379 }
1380 }
1381
1382 /// Converts the pipe into an [`OwnedFd`] in blocking mode.
1383 ///
1384 /// This function will deregister this pipe end from the event loop, set
1385 /// it in blocking mode and perform the conversion.
1386 pub fn into_blocking_fd(self) -> io::Result<OwnedFd> {
1387 let fd = self.into_nonblocking_fd()?;
1388 set_blocking(&fd)?;
1389 Ok(fd)
1390 }
1391
1392 /// Converts the pipe into an [`OwnedFd`] in nonblocking mode.
1393 ///
1394 /// This function will deregister this pipe end from the event loop and
1395 /// perform the conversion. Returned file descriptor will be in nonblocking
1396 /// mode.
1397 pub fn into_nonblocking_fd(self) -> io::Result<OwnedFd> {
1398 let mio_pipe = self.io.into_inner()?;
1399
1400 // Safety: the pipe is now deregistered from the event loop
1401 // and we are the only owner of this pipe end.
1402 let owned_fd = unsafe { OwnedFd::from_raw_fd(mio_pipe.into_raw_fd()) };
1403
1404 Ok(owned_fd)
1405 }
1406}
1407
1408impl AsyncRead for Receiver {
1409 fn poll_read(
1410 self: Pin<&mut Self>,
1411 cx: &mut Context<'_>,
1412 buf: &mut ReadBuf<'_>,
1413 ) -> Poll<io::Result<()>> {
1414 // Safety: `mio_pipe::Receiver` uses a `std::fs::File` underneath,
1415 // which correctly handles reads into uninitialized memory.
1416 unsafe { self.io.poll_read(cx, buf) }
1417 }
1418}
1419
1420impl AsRawFd for Receiver {
1421 fn as_raw_fd(&self) -> RawFd {
1422 self.io.as_raw_fd()
1423 }
1424}
1425
1426impl AsFd for Receiver {
1427 fn as_fd(&self) -> BorrowedFd<'_> {
1428 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
1429 }
1430}
1431
1432/// Checks if the file descriptor is a pipe or a FIFO.
1433fn is_pipe(fd: BorrowedFd<'_>) -> io::Result<bool> {
1434 // Safety: `libc::stat` is C-like struct used for syscalls and all-zero
1435 // byte pattern forms a valid value.
1436 let mut stat: libc::stat = unsafe { std::mem::zeroed() };
1437
1438 // Safety: it's safe to call `fstat` with a valid, open file descriptor
1439 // and a valid pointer to a `stat` struct.
1440 let r = unsafe { libc::fstat(fd.as_raw_fd(), &mut stat) };
1441
1442 if r == -1 {
1443 Err(io::Error::last_os_error())
1444 } else {
1445 Ok((stat.st_mode as libc::mode_t & libc::S_IFMT) == libc::S_IFIFO)
1446 }
1447}
1448
1449/// Gets file descriptor's flags by fcntl.
1450fn get_file_flags(fd: BorrowedFd<'_>) -> io::Result<libc::c_int> {
1451 // Safety: it's safe to use `fcntl` to read flags of a valid, open file descriptor.
1452 let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
1453 if flags < 0 {
1454 Err(io::Error::last_os_error())
1455 } else {
1456 Ok(flags)
1457 }
1458}
1459
1460/// Checks for `O_RDONLY` or `O_RDWR` access mode.
1461fn has_read_access(flags: libc::c_int) -> bool {
1462 let mode = flags & libc::O_ACCMODE;
1463 mode == libc::O_RDONLY || mode == libc::O_RDWR
1464}
1465
1466/// Checks for `O_WRONLY` or `O_RDWR` access mode.
1467fn has_write_access(flags: libc::c_int) -> bool {
1468 let mode = flags & libc::O_ACCMODE;
1469 mode == libc::O_WRONLY || mode == libc::O_RDWR
1470}
1471
1472/// Sets file descriptor's flags with `O_NONBLOCK` by fcntl.
1473fn set_nonblocking(fd: BorrowedFd<'_>, current_flags: libc::c_int) -> io::Result<()> {
1474 let flags = current_flags | libc::O_NONBLOCK;
1475
1476 if flags != current_flags {
1477 // Safety: it's safe to use `fcntl` to set the `O_NONBLOCK` flag of a valid,
1478 // open file descriptor.
1479 let ret = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags) };
1480 if ret < 0 {
1481 return Err(io::Error::last_os_error());
1482 }
1483 }
1484
1485 Ok(())
1486}
1487
1488/// Removes `O_NONBLOCK` from fd's flags.
1489fn set_blocking<T: AsRawFd>(fd: &T) -> io::Result<()> {
1490 // Safety: it's safe to use `fcntl` to read flags of a valid, open file descriptor.
1491 let previous = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
1492 if previous == -1 {
1493 return Err(io::Error::last_os_error());
1494 }
1495
1496 let new = previous & !libc::O_NONBLOCK;
1497
1498 // Safety: it's safe to use `fcntl` to unset the `O_NONBLOCK` flag of a valid,
1499 // open file descriptor.
1500 let r = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, new) };
1501 if r == -1 {
1502 Err(io::Error::last_os_error())
1503 } else {
1504 Ok(())
1505 }
1506}