tokio-pipe-0.2.12/.cargo_vcs_info.json0000644000000001360000000000100131760ustar { "git": { "sha1": "503e8aeea4374738951c98b8afd8751af15de2d7" }, "path_in_vcs": "" }tokio-pipe-0.2.12/.github/workflows/tests.yml000064400000000000000000000035660072674642500173120ustar 00000000000000name: tests on: push: branches: - master pull_request: schedule: - cron: '20 9 * * 1' jobs: check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable override: true profile: minimal components: rustfmt, clippy - name: Check format uses: actions-rs/cargo@v1 with: command: fmt args: -- --check - name: Annotate commit with clippy warnings uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: --all-features - name: Security audit uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} test: runs-on: ${{ matrix.os }} strategy: matrix: os: - ubuntu-latest - macos-latest rust-version: - stable - "1.49" steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust-version }} override: true profile: minimal - name: Tests uses: actions-rs/cargo@v1 with: command: test args: --no-fail-fast cov: runs-on: ubuntu-latest env: CARGO_TERM_COLOR: always steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable override: true profile: minimal components: llvm-tools-preview - name: Install cargo-llvm-cov uses: taiki-e/install-action@cargo-llvm-cov - name: Tests uses: actions-rs/cargo@v1 with: command: llvm-cov args: --all-features --workspace --lcov --output-path lcov.info - name: Upload coverage uses: codecov/codecov-action@v3 with: files: lcov.info # vim: set sw=2 ts=2 sts=2: tokio-pipe-0.2.12/.gitignore000064400000000000000000000000230072674642500140010ustar 00000000000000/target Cargo.lock tokio-pipe-0.2.12/Cargo.toml0000644000000021350000000000100111750ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.49" name = "tokio-pipe" version = "0.2.12" authors = ["yskszk63 "] description = "Asynchronous pipe(2) library using tokio." readme = "README.md" keywords = [ "tokio", "pipe", "async", ] categories = ["asynchronous"] license = "MIT/Apache-2.0" repository = "https://github.com/yskszk63/tokio-pipe" [dependencies.libc] version = "0.2" [dependencies.tokio] version = "1.17" features = ["net"] [dev-dependencies.anyhow] version = "1.0" [dev-dependencies.tokio] version = "1.17" features = [ "macros", "rt-multi-thread", "io-util", "process", "time", ] tokio-pipe-0.2.12/Cargo.toml.orig000064400000000000000000000010660072674642500147100ustar 00000000000000[package] name = "tokio-pipe" version = "0.2.12" authors = ["yskszk63 "] edition = "2018" description = "Asynchronous pipe(2) library using tokio." license = "MIT/Apache-2.0" repository = "https://github.com/yskszk63/tokio-pipe" readme = "README.md" keywords = ["tokio", "pipe", "async"] categories = ["asynchronous"] rust-version = "1.49" [dependencies] tokio = { version="1.17", features=["net"] } libc = "0.2" [dev-dependencies] tokio = { version="1.17", features=["macros", "rt-multi-thread", "io-util", "process", "time"] } anyhow = "1.0" tokio-pipe-0.2.12/LICENSE-APACHE000064400000000000000000000261350072674642500137510ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. tokio-pipe-0.2.12/LICENSE-MIT000064400000000000000000000020560072674642500134550ustar 00000000000000MIT License Copyright (c) 2021 yusuke suzuki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tokio-pipe-0.2.12/README.md000064400000000000000000000021200072674642500132700ustar 00000000000000# tokio-pipe [![tokio-pipe](https://docs.rs/tokio-pipe/badge.svg)](https://docs.rs/tokio-pipe) [![dependency status](https://deps.rs/repo/github/yskszk63/tokio-pipe/status.svg)](https://deps.rs/repo/github/yskszk63/tokio-pipe) Asynchronous pipe(2) library using tokio. ## Example ```rust use tokio::prelude::*; #[tokio::main] async fn main() -> anyhow::Result<()> { let (mut r, mut w) = tokio_pipe::pipe()?; w.write_all(b"HELLO, WORLD!").await?; let mut buf = [0; 16]; let len = r.read(&mut buf[..]).await?; assert_eq!(&buf[..len], &b"HELLO, WORLD!"[..]); Ok(()) } ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. tokio-pipe-0.2.12/src/lib.rs000064400000000000000000000760660072674642500137400ustar 00000000000000#![doc(html_root_url = "https://docs.rs/tokio-pipe/0.2.12")] //! Asynchronous pipe(2) library using tokio. //! //! # Example //! //! ``` //! use tokio::io::{AsyncReadExt, AsyncWriteExt}; //! //! #[tokio::main] //! async fn main() -> anyhow::Result<()> { //! let (mut r, mut w) = tokio_pipe::pipe()?; //! //! w.write_all(b"HELLO, WORLD!").await?; //! //! let mut buf = [0; 16]; //! let len = r.read(&mut buf[..]).await?; //! //! assert_eq!(&buf[..len], &b"HELLO, WORLD!"[..]); //! Ok(()) //! } //! ``` use std::cmp; use std::convert::TryFrom; use std::ffi::c_void; use std::fmt; use std::io; use std::mem; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::pin::Pin; #[cfg(target_os = "linux")] use std::ptr; use std::task::{Context, Poll}; use tokio::io::unix::AsyncFd; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; #[cfg(target_os = "linux")] pub use libc::off64_t; pub use libc::PIPE_BUF; #[cfg(target_os = "macos")] const MAX_LEN: usize = ::MAX as usize - 1; #[cfg(not(target_os = "macos"))] const MAX_LEN: usize = ::MAX as usize; macro_rules! try_libc { ($e: expr) => {{ let ret = $e; if ret == -1 { return Err(io::Error::last_os_error()); } ret }}; } macro_rules! cvt { ($e:expr) => {{ let ret = $e; if ret == -1 { Err(io::Error::last_os_error()) } else { Ok(ret) } }}; } macro_rules! ready { ($e:expr) => { match $e { Poll::Pending => return Poll::Pending, Poll::Ready(e) => e, } }; } fn is_wouldblock(err: &io::Error) -> bool { err.kind() == io::ErrorKind::WouldBlock } unsafe fn set_nonblocking(fd: RawFd) { let status_flags = libc::fcntl(fd, libc::F_GETFL); if (status_flags & libc::O_NONBLOCK) == 0 { libc::fcntl(fd, libc::F_SETFL, status_flags | libc::O_NONBLOCK); } } unsafe fn set_nonblocking_checked(fd: RawFd, status_flags: libc::c_int) -> Result<(), io::Error> { if (status_flags & libc::O_NONBLOCK) == 0 { let res = libc::fcntl(fd, libc::F_SETFL, status_flags | libc::O_NONBLOCK); try_libc!(res); } Ok(()) } /// Return whether (reader is ready, writer is ready). /// /// Readiness for reader/writer does not just mean readable/writable, /// they are also considered as ready if they aqre disconnected or an /// exceptional condition has occured (`libc::POLLERR`). #[cfg(target_os = "linux")] unsafe fn test_read_write_readiness(reader: RawFd, writer: RawFd) -> io::Result<(bool, bool)> { use libc::{poll, pollfd, POLLERR, POLLHUP, POLLIN, POLLNVAL, POLLOUT}; let mut fds = [ pollfd { fd: reader, events: POLLIN, revents: 0, }, pollfd { fd: writer, events: POLLOUT, revents: 0, }, ]; // Specify timeout to 0 so that it returns immediately. try_libc!(poll(&mut fds[0], 2, 0)); let is_read_ready = match fds[0].revents { POLLERR | POLLHUP | POLLIN => true, POLLNVAL => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "fd of reader is invalid", )) } _ => false, }; let is_writer_ready = match fds[1].revents { POLLERR | POLLHUP | POLLOUT => true, POLLNVAL => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "fd of writer is invalid", )) } _ => false, }; Ok((is_read_ready, is_writer_ready)) } fn check_pipe(fd: RawFd) -> Result<(), io::Error> { let mut stat = mem::MaybeUninit::::uninit(); try_libc!(unsafe { libc::fstat(fd, stat.as_mut_ptr()) }); let stat = unsafe { stat.assume_init() }; if (stat.st_mode & libc::S_IFMT) == libc::S_IFIFO { Ok(()) } else { Err(io::Error::new(io::ErrorKind::Other, "Fd is not a pipe")) } } fn get_status_flags(fd: RawFd) -> Result { Ok(try_libc!(unsafe { libc::fcntl(fd, libc::F_GETFL) })) } // needs impl AsRawFd for RawFd (^v1.48) #[derive(Debug)] // Optimize size of `Option` by manually specifing the range. // Shamelessly taken from [`io-lifetimes::OwnedFd`](https://github.com/sunfishcode/io-lifetimes/blob/8669b5a9fc1d0604d1105f6e39c77fa633ac9c71/src/types.rs#L99). #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_start(0))] // libstd/os/raw/mod.rs me that every libstd-supported platform has a // 32-bit c_int. // // Below is -2, in two's complement, but that only works out // because c_int is 32 bits. #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))] struct PipeFd(RawFd); impl PipeFd { /// * `fd` - PipeFd would take the ownership of this fd. /// * `readable` - true for the read end, false for the write end fn from_raw_fd_checked(fd: RawFd, readable: bool) -> Result { let (access_mode, errmsg) = if readable { (libc::O_RDONLY, "Fd is not the read end") } else { (libc::O_WRONLY, "Fd is not the write end") }; check_pipe(fd)?; let status_flags = get_status_flags(fd)?; if (status_flags & libc::O_ACCMODE) == access_mode { unsafe { set_nonblocking_checked(fd, status_flags) }?; Ok(Self(fd)) } else { Err(io::Error::new(io::ErrorKind::Other, errmsg)) } } } impl AsRawFd for PipeFd { fn as_raw_fd(&self) -> RawFd { self.0 } } impl Drop for PipeFd { fn drop(&mut self) { let _ = unsafe { libc::close(self.0) }; } } /// A buffer that can be written atomically #[derive(Copy, Clone, Debug)] pub struct AtomicWriteBuffer<'a>(&'a [u8]); impl<'a> AtomicWriteBuffer<'a> { /// If buffer is more than PIPE_BUF, then return None. pub fn new(buffer: &'a [u8]) -> Option { if buffer.len() <= PIPE_BUF { Some(Self(buffer)) } else { None } } pub fn into_inner(self) -> &'a [u8] { self.0 } } /// `IoSlice`s that can be written atomically #[derive(Copy, Clone, Debug)] pub struct AtomicWriteIoSlices<'a, 'b>(&'a [io::IoSlice<'b>], usize); impl<'a, 'b> AtomicWriteIoSlices<'a, 'b> { /// If total length is more than PIPE_BUF, then return None. pub fn new(buffers: &'a [io::IoSlice<'b>]) -> Option { let mut total_len = 0; for buffer in buffers { total_len += buffer.len(); if total_len > PIPE_BUF { return None; } } Some(Self(buffers, total_len)) } pub fn get_total_len(self) -> usize { self.1 } pub fn into_inner(self) -> &'a [io::IoSlice<'b>] { self.0 } } #[cfg(target_os = "linux")] async fn tee_impl(pipe_in: &PipeRead, pipe_out: &PipeWrite, len: usize) -> io::Result { // There is only one reader and one writer, so it only needs to polled once. let mut read_ready = pipe_in.0.readable().await?; let mut write_ready = pipe_out.0.writable().await?; loop { let ret = unsafe { libc::tee( pipe_in.as_raw_fd(), pipe_out.as_raw_fd(), len, libc::SPLICE_F_NONBLOCK, ) }; match cvt!(ret) { Err(e) if is_wouldblock(&e) => { // Since tokio might use epoll's edge-triggered mode, we cannot blindly // clear the readiness, otherwise it would block forever. // // So what we do instead is to use test_read_write_readiness, which // uses poll to test for readiness. // // Poll always uses level-triggered mode and it does not require // any registration at all. let (read_readiness, write_readiness) = unsafe { test_read_write_readiness(pipe_in.as_raw_fd(), pipe_out.as_raw_fd())? }; if !read_readiness { read_ready.clear_ready(); read_ready = pipe_in.0.readable().await?; } if !write_readiness { write_ready.clear_ready(); write_ready = pipe_out.0.writable().await?; } } Err(e) => break Err(e), Ok(ret) => break Ok(ret as usize), } } } /// Duplicates up to len bytes of data from pipe_in to pipe_out. /// /// It does not consume the data that is duplicated from pipe_in; therefore, that data /// can be copied by a subsequent splice. #[cfg(target_os = "linux")] pub async fn tee( pipe_in: &mut PipeRead, pipe_out: &mut PipeWrite, len: usize, ) -> io::Result { tee_impl(pipe_in, pipe_out, len).await } #[cfg(target_os = "linux")] fn as_ptr(option: Option<&mut T>) -> *mut T { match option { Some(some) => some, None => ptr::null_mut(), } } #[cfg(target_os = "linux")] async fn splice_impl( fd_in: &mut AsyncFd, mut off_in: Option<&mut off64_t>, fd_out: &AsyncFd, mut off_out: Option<&mut off64_t>, len: usize, has_more_data: bool, ) -> io::Result { // There is only one reader and one writer, so it only needs to polled once. let mut read_ready = fd_in.readable().await?; let mut write_ready = fd_out.writable().await?; // Prepare args for the syscall let flags = libc::SPLICE_F_NONBLOCK | if has_more_data { libc::SPLICE_F_MORE } else { 0 }; loop { let ret = unsafe { libc::splice( fd_in.as_raw_fd(), as_ptr(off_in.as_deref_mut()), fd_out.as_raw_fd(), as_ptr(off_out.as_deref_mut()), len, flags, ) }; match cvt!(ret) { Err(e) if is_wouldblock(&e) => { // Since tokio might use epoll's edge-triggered mode, we cannot blindly // clear the readiness, otherwise it would block forever. // // So what we do instead is to use test_read_write_readiness, which // uses poll to test for readiness. // // Poll always uses level-triggered mode and it does not require // any registration at all. let (read_readiness, write_readiness) = unsafe { test_read_write_readiness(fd_in.as_raw_fd(), fd_out.as_raw_fd())? }; if !read_readiness { read_ready.clear_ready(); read_ready = fd_in.readable().await?; } if !write_readiness { write_ready.clear_ready(); write_ready = fd_out.writable().await?; } } Err(e) => break Err(e), Ok(ret) => break Ok(ret as usize), } } } /// Moves data between pipes without copying between kernel address space and /// user address space. /// /// It transfers up to len bytes of data from pipe_in to pipe_out. #[cfg(target_os = "linux")] pub async fn splice( pipe_in: &mut PipeRead, pipe_out: &mut PipeWrite, len: usize, ) -> io::Result { splice_impl(&mut pipe_in.0, None, &pipe_out.0, None, len, false).await } /// Pipe read pub struct PipeRead(AsyncFd); impl TryFrom for PipeRead { type Error = io::Error; fn try_from(fd: RawFd) -> Result { Self::from_raw_fd_checked(fd) } } impl PipeRead { fn new(fd: RawFd) -> Result { Self::from_pipefd(PipeFd(fd)) } fn from_pipefd(pipe_fd: PipeFd) -> Result { Ok(Self(AsyncFd::new(pipe_fd)?)) } /// * `fd` - PipeRead would take the ownership of this fd. pub fn from_raw_fd_checked(fd: RawFd) -> Result { Self::from_pipefd(PipeFd::from_raw_fd_checked(fd, true)?) } /// Moves data between pipe and fd without copying between kernel address space and /// user address space. /// /// It transfers up to len bytes of data from self to asyncfd_out. /// /// * `asyncfd_out` - must be have O_NONBLOCK set, /// otherwise this function might block. /// * `off_out` - If it is not None, then it would be updated on success. /// * `has_more_data` - If there is more data to be sent to off_out. /// This is a helpful hint for socket (see also the description of MSG_MORE /// in send(2), and the description of TCP_CORK in tcp(7)). #[cfg(target_os = "linux")] pub async fn splice_to( &mut self, asyncfd_out: &AsyncFd, off_out: Option<&mut off64_t>, len: usize, has_more_data: bool, ) -> io::Result { splice_impl(&mut self.0, None, asyncfd_out, off_out, len, has_more_data).await } } impl AsyncRead for PipeRead { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { let fd = self.0.as_raw_fd(); loop { let pinned = Pin::new(&mut self.0); let mut ready = ready!(pinned.poll_read_ready(cx))?; let ret = unsafe { libc::read( fd, buf.unfilled_mut() as *mut _ as *mut c_void, cmp::min(buf.remaining(), MAX_LEN), ) }; match cvt!(ret) { Err(e) if is_wouldblock(&e) => { ready.clear_ready(); } Err(e) => return Poll::Ready(Err(e)), Ok(ret) => { let ret = ret as usize; unsafe { buf.assume_init(ret); }; buf.advance(ret); return Poll::Ready(Ok(())); } } } } } impl AsRawFd for PipeRead { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl IntoRawFd for PipeRead { fn into_raw_fd(self) -> RawFd { let inner = self.0.into_inner(); let fd = inner.0; mem::forget(inner); fd } } impl FromRawFd for PipeRead { unsafe fn from_raw_fd(fd: RawFd) -> Self { set_nonblocking(fd); Self::new(fd).unwrap() } } impl fmt::Debug for PipeRead { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PipeRead({})", self.as_raw_fd()) } } /// Pipe write pub struct PipeWrite(AsyncFd); impl TryFrom for PipeWrite { type Error = io::Error; fn try_from(fd: RawFd) -> Result { Self::from_raw_fd_checked(fd) } } impl PipeWrite { fn new(fd: RawFd) -> Result { Self::from_pipefd(PipeFd(fd)) } fn from_pipefd(pipe_fd: PipeFd) -> Result { Ok(Self(AsyncFd::new(pipe_fd)?)) } /// * `fd` - PipeWrite would take the ownership of this fd. pub fn from_raw_fd_checked(fd: RawFd) -> Result { Self::from_pipefd(PipeFd::from_raw_fd_checked(fd, false)?) } } impl AsRawFd for PipeWrite { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl IntoRawFd for PipeWrite { fn into_raw_fd(self) -> RawFd { let inner = self.0.into_inner(); let fd = inner.0; mem::forget(inner); fd } } impl FromRawFd for PipeWrite { unsafe fn from_raw_fd(fd: RawFd) -> Self { set_nonblocking(fd); Self::new(fd).unwrap() } } impl PipeWrite { fn poll_write_impl( self: Pin<&Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { let fd = self.0.as_raw_fd(); loop { let pinned = Pin::new(&self.0); let mut ready = ready!(pinned.poll_write_ready(cx))?; let ret = unsafe { libc::write( fd, buf.as_ptr() as *mut c_void, cmp::min(buf.len(), MAX_LEN), ) }; match cvt!(ret) { Err(e) if is_wouldblock(&e) => { ready.clear_ready(); } Err(e) => return Poll::Ready(Err(e)), Ok(ret) => return Poll::Ready(Ok(ret as usize)), } } } /// Write buf atomically to the pipe, using guarantees provided in POSIX.1 pub fn poll_write_atomic( self: Pin<&Self>, cx: &mut Context<'_>, buf: AtomicWriteBuffer, ) -> Poll> { self.poll_write_impl(cx, buf.0) } fn poll_write_vectored_impl( self: Pin<&Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll> { let fd = self.0.as_raw_fd(); loop { let pinned = Pin::new(&self.0); let mut ready = ready!(pinned.poll_write_ready(cx))?; let ret = unsafe { libc::writev(fd, bufs.as_ptr() as *const libc::iovec, bufs.len() as i32) }; match cvt!(ret) { Err(e) if is_wouldblock(&e) => { ready.clear_ready(); } Err(e) => return Poll::Ready(Err(e)), Ok(ret) => return Poll::Ready(Ok(ret as usize)), } } } pub fn poll_write_vectored_atomic( self: Pin<&Self>, cx: &mut Context<'_>, bufs: AtomicWriteIoSlices<'_, '_>, ) -> Poll> { self.poll_write_vectored_impl(cx, bufs.0) } /// Moves data between fd and pipe without copying between kernel address space and /// user address space. /// /// It transfers up to len bytes of data from asyncfd_in to self. /// /// * `asyncfd_in` - must be have O_NONBLOCK set, /// otherwise this function might block. /// There must not be other reader for that fd (or its duplicates). /// * `off_in` - If it is not None, then it would be updated on success. #[cfg(target_os = "linux")] pub async fn splice_from( &mut self, asyncfd_in: &mut AsyncFd, off_in: Option<&mut off64_t>, len: usize, ) -> io::Result { splice_impl(asyncfd_in, off_in, &self.0, None, len, false).await } } impl AsyncWrite for PipeWrite { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { self.as_ref().poll_write_impl(cx, buf) } fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { Poll::Ready(Ok(())) } fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll> { self.as_ref().poll_write_vectored_impl(cx, bufs) } fn is_write_vectored(&self) -> bool { true } } impl fmt::Debug for PipeWrite { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PipeRead({})", self.as_raw_fd()) } } #[cfg(any(target_os = "linux", target_os = "solaris"))] fn sys_pipe() -> io::Result<(RawFd, RawFd)> { let mut pipefd = [0; 2]; let ret = unsafe { libc::pipe2(pipefd.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) }; if ret == -1 { return Err(io::Error::last_os_error()); } Ok((pipefd[0], pipefd[1])) } #[cfg(not(any(target_os = "linux", target_os = "solaris")))] fn sys_pipe() -> io::Result<(RawFd, RawFd)> { let mut pipefd = [0; 2]; try_libc!(unsafe { libc::pipe(pipefd.as_mut_ptr()) }); for fd in &pipefd { let ret = try_libc!(unsafe { libc::fcntl(*fd, libc::F_GETFD) }); try_libc!(unsafe { libc::fcntl(*fd, libc::F_SETFD, ret | libc::FD_CLOEXEC) }); let ret = try_libc!(unsafe { libc::fcntl(*fd, libc::F_GETFL) }); try_libc!(unsafe { libc::fcntl(*fd, libc::F_SETFL, ret | libc::O_NONBLOCK) }); } Ok((pipefd[0], pipefd[1])) } /// Open pipe pub fn pipe() -> io::Result<(PipeRead, PipeWrite)> { let (r, w) = sys_pipe()?; Ok((PipeRead::new(r)?, PipeWrite::new(w)?)) } #[cfg(test)] mod tests { use super::*; use std::fs::File; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[cfg(target_os = "linux")] use tokio::time::{sleep, Duration}; #[tokio::test] async fn test() { let (mut r, mut w) = pipe().unwrap(); let w_task = tokio::spawn(async move { for n in 0..=65535 { w.write_u32(n).await.unwrap(); } //w.shutdown().await.unwrap(); }); let r_task = tokio::spawn(async move { let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 65535 { r.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } }); tokio::try_join!(w_task, r_task).unwrap(); } #[tokio::test] async fn test_write_after_shutdown() { let (r, mut w) = pipe().unwrap(); w.shutdown().await.unwrap(); let result = w.write(b"ok").await; assert!(result.is_ok()); drop(r) } #[tokio::test] async fn test_read_to_end() -> io::Result<()> { let (mut r, mut w) = pipe()?; let t = tokio::spawn(async move { w.write_all(&b"Hello, World!"[..]).await?; io::Result::Ok(()) }); let mut buf = vec![]; r.read_to_end(&mut buf).await?; assert_eq!(&b"Hello, World!"[..], &buf[..]); t.await? } #[tokio::test] async fn test_from_child_stdio() -> io::Result<()> { use std::process::Stdio; use tokio::process::Command; let (mut r, w) = pipe()?; let script = r#"#!/usr/bin/env python3 import os with os.fdopen(1, 'wb') as w: w.write(b"Hello, World!") "#; let mut command = Command::new("python"); command .args(&["-c", script]) .stdout(unsafe { Stdio::from_raw_fd(w.as_raw_fd()) }); unsafe { // suppress posix_spawn command.pre_exec(|| Ok(())); } let mut child = command.spawn()?; drop(w); let mut buf = vec![]; r.read_to_end(&mut buf).await?; assert_eq!(&b"Hello, World!"[..], &buf[..]); child.wait().await?; Ok(()) } #[tokio::test] async fn test_from_child_no_stdio() -> io::Result<()> { use tokio::process::Command; let (mut r, w) = pipe()?; let script = r#"#!/usr/bin/env python3 import os with os.fdopen(3, 'wb') as w: w.write(b"Hello, World!") "#; let mut command = Command::new("python"); command.args(&["-c", script]); unsafe { let w = w.as_raw_fd(); command.pre_exec(move || { if w == 3 { // drop CLOEXEC let flags = libc::fcntl(w, libc::F_SETFD); if flags == -1 { return Err(io::Error::last_os_error()); } if flags & libc::FD_CLOEXEC != 0 && libc::fcntl(w, libc::F_SETFD, flags ^ libc::FD_CLOEXEC) == -1 { return Err(io::Error::last_os_error()); } } else { let r = libc::dup2(w, 3); if r == -1 { return Err(io::Error::last_os_error()); } } Ok(()) }); } let mut child = command.spawn()?; drop(w); let mut buf = vec![]; r.read_to_end(&mut buf).await?; assert_eq!(&b"Hello, World!"[..], &buf[..]); child.wait().await?; Ok(()) } #[cfg(target_os = "linux")] #[tokio::test] async fn test_tee() { let (mut r1, mut w1) = pipe().unwrap(); let (mut r2, mut w2) = pipe().unwrap(); for n in 0..1024 { w1.write_u32(n).await.unwrap(); } tee(&mut r1, &mut w2, 4096).await.unwrap(); let r2_task = tokio::spawn(async move { let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r2.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } }); let r1_task = tokio::spawn(async move { let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r1.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } }); tokio::try_join!(r1_task, r2_task).unwrap(); } #[cfg(target_os = "linux")] #[tokio::test] async fn test_tee_no_inf_loop() { let (mut r1, mut w1) = pipe().unwrap(); let (mut r2, mut w2) = pipe().unwrap(); let w1_task = tokio::spawn(async move { sleep(Duration::from_millis(100)).await; for n in 0..1024 { w1.write_u32(n).await.unwrap(); } }); for n in 0..1024 { w2.write_u32(n).await.unwrap(); } let r2_task = tokio::spawn(async move { sleep(Duration::from_millis(200)).await; let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r2.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } }); tee(&mut r1, &mut w2, 4096).await.unwrap(); tokio::try_join!(w1_task, r2_task).unwrap(); } #[cfg(target_os = "linux")] #[tokio::test] async fn test_splice() { let (mut r1, mut w1) = pipe().unwrap(); let (mut r2, mut w2) = pipe().unwrap(); for n in 0..1024 { w1.write_u32(n).await.unwrap(); } splice(&mut r1, &mut w2, 4096).await.unwrap(); let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r2.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } } #[cfg(target_os = "linux")] #[tokio::test] async fn test_splice_no_inf_loop() { let (mut r1, mut w1) = pipe().unwrap(); let (mut r2, mut w2) = pipe().unwrap(); let w1_task = tokio::spawn(async move { sleep(Duration::from_millis(100)).await; for n in 0..1024 { w1.write_u32(n).await.unwrap(); } }); for n in 0..1024 { w2.write_u32(n).await.unwrap(); } let r2_task = tokio::spawn(async move { sleep(Duration::from_millis(200)).await; let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r2.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_be_bytes()); n += 1; } } }); splice(&mut r1, &mut w2, 4096).await.unwrap(); tokio::try_join!(w1_task, r2_task).unwrap(); } fn as_ioslice(v: &[T]) -> io::IoSlice<'_> { io::IoSlice::new(unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * std::mem::size_of::()) }) } #[tokio::test] async fn test_writev() { let (mut r, mut w) = pipe().unwrap(); let w_task = tokio::spawn(async move { let buffer1: Vec = (0..512).collect(); let buffer2: Vec = (512..1024).collect(); w.write_vectored(&[as_ioslice(&buffer1), as_ioslice(&buffer2)]) .await .unwrap(); }); let r_task = tokio::spawn(async move { let mut n = 0u32; let mut buf = [0; 4 * 128]; while n < 1024 { r.read_exact(&mut buf).await.unwrap(); for x in buf.chunks(4) { assert_eq!(x, n.to_ne_bytes()); n += 1; } } }); tokio::try_join!(w_task, r_task).unwrap(); } #[tokio::test] async fn test_piperead_from_raw_fd_checked_success() { let (r, _w) = pipe().unwrap(); let _r = PipeRead::from_raw_fd_checked(r.into_raw_fd()).unwrap(); } #[tokio::test] async fn test_piperead_from_raw_fd_checked_failure_not_read_end() { let (_r, w) = pipe().unwrap(); let error = PipeRead::from_raw_fd_checked(w.into_raw_fd()) .unwrap_err() .into_inner() .unwrap(); assert_eq!(format!("{}", error), "Fd is not the read end"); } #[tokio::test] async fn test_piperead_from_raw_fd_checked_failure_not_pipe() { let fd = File::open("/dev/null").unwrap().into_raw_fd(); let error = PipeRead::from_raw_fd_checked(fd) .unwrap_err() .into_inner() .unwrap(); assert_eq!(format!("{}", error), "Fd is not a pipe"); } #[tokio::test] async fn test_pipewrite_from_raw_fd_checked_success() { let (_r, w) = pipe().unwrap(); let _w = PipeWrite::from_raw_fd_checked(w.into_raw_fd()).unwrap(); } #[tokio::test] async fn test_pipewrite_from_raw_fd_checked_failure_not_write_end() { let (r, _w) = pipe().unwrap(); let error = PipeWrite::from_raw_fd_checked(r.into_raw_fd()) .unwrap_err() .into_inner() .unwrap(); assert_eq!(format!("{}", error), "Fd is not the write end"); } #[tokio::test] async fn test_pipewrite_from_raw_fd_checked_failure_not_pipe() { let fd = File::open("/dev/null").unwrap().into_raw_fd(); let error = PipeWrite::from_raw_fd_checked(fd) .unwrap_err() .into_inner() .unwrap(); assert_eq!(format!("{}", error), "Fd is not a pipe"); } #[test] fn test_atomic_write_io_slices() { let bytes: Vec = (0..PIPE_BUF + 20) .map(|i| (i % (u8::MAX as usize)) as u8) .collect(); let mut io_slices = Vec::>::new(); for i in 0..bytes.len() { io_slices.push(io::IoSlice::new(&bytes[i..i + 1])); } for i in 0..PIPE_BUF { let slices = AtomicWriteIoSlices::new(&io_slices[..i]).unwrap(); assert_eq!(slices.get_total_len(), i); } for i in PIPE_BUF + 1..bytes.len() { assert!(AtomicWriteIoSlices::new(&io_slices[..i]).is_none()); } } }