sendfd-0.4.3/.cargo_vcs_info.json0000644000000001360000000000100123030ustar { "git": { "sha1": "69994c1b6d0ceb72e39afd4854694b38d6132861" }, "path_in_vcs": "" }sendfd-0.4.3/.github/dependabot.yml000064400000000000000000000003240072674642500153120ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 allow: - dependency-type: direct - dependency-type: indirect sendfd-0.4.3/.github/workflows/sendfd.yml000064400000000000000000000054440072674642500165150ustar 00000000000000name: Test sendfd on: push: paths-ignore: - '*.mkd' - 'LICENSE' pull_request: jobs: native-test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: rust_toolchain: [nightly, stable, 1.53.0] os: [ubuntu-latest, macOS-latest] flags: ["--all-features", "--all-features --release", ""] timeout-minutes: 20 steps: - uses: actions/checkout@v2 - name: Install Rust ${{ matrix.rust_toolchain }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust_toolchain }} profile: minimal default: true - name: Test uses: actions-rs/cargo@v1 with: command: test args: ${{ matrix.flags }} --manifest-path=Cargo.toml -- --nocapture bare-cross-build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust_target: # BSDs: could be tested with full system emulation # - x86_64-unknown-dragonfly # - x86_64-unknown-freebsd # - x86_64-unknown-haiku # - x86_64-unknown-netbsd - x86_64-unknown-openbsd # - x86_64-unknown-redox # - x86_64-fuchsia timeout-minutes: 20 steps: - uses: actions/checkout@v2 - name: Install Rust nightly uses: actions-rs/toolchain@v1 with: toolchain: nightly profile: minimal default: true - name: Fix-up toolchain run: | rustup component add rust-src --toolchain nightly --target ${{ matrix.rust_target }} - name: Update uses: actions-rs/cargo@v1 with: command: update args: --manifest-path=Cargo.toml - name: Build ${{ matrix.rust_target }} uses: actions-rs/cargo@v1 with: command: build args: --target ${{ matrix.rust_target }} --manifest-path=Cargo.toml -Zbuild-std cross-ios-build: runs-on: macos-latest strategy: fail-fast: false matrix: rust_toolchain: [nightly, stable] rust_target: - aarch64-apple-ios - x86_64-apple-ios timeout-minutes: 20 steps: - uses: actions/checkout@v2 - name: Install Rust ${{ matrix.rust_toolchain }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust_toolchain }} target: ${{ matrix.rust_target }} profile: minimal default: true - name: Update uses: actions-rs/cargo@v1 with: command: update args: --manifest-path=Cargo.toml - name: Build ${{ matrix.rust_target }} uses: actions-rs/cargo@v1 with: command: build args: --target=${{ matrix.rust_target }} --manifest-path=Cargo.toml sendfd-0.4.3/.gitignore000064400000000000000000000000360072674642500131120ustar 00000000000000/target **/*.rs.bk Cargo.lock sendfd-0.4.3/Cargo.toml0000644000000021620000000000100103020ustar # 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 = "2015" name = "sendfd" version = "0.4.3" authors = [ "Simonas Kazlauskas ", "Bernardo Meurer ", "Léo Gaspard ", ] description = "Send file descriptors along with data over UNIX domain sockets" documentation = "https://docs.rs/sendfd" readme = "README.mkd" keywords = ["ipc"] license = "Apache-2.0 OR BSD-3-Clause" repository = "https://github.com/standard-ai/sendfd" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "sendfd_docs", ] [dependencies.libc] version = "0.2" [dependencies.tokio] version = "1.0.0" features = ["net"] optional = true sendfd-0.4.3/Cargo.toml.orig000064400000000000000000000012050072674642500140100ustar 00000000000000[package] name = "sendfd" version = "0.4.3" authors = [ "Simonas Kazlauskas ", "Bernardo Meurer ", "Léo Gaspard " ] edition = "2015" description = "Send file descriptors along with data over UNIX domain sockets" keywords = ["ipc"] license = "Apache-2.0 OR BSD-3-Clause" repository = "https://github.com/standard-ai/sendfd" documentation = "https://docs.rs/sendfd" readme = "README.mkd" [dependencies] libc = "0.2" tokio = { version = "1.0.0", features = [ "net" ], optional = true } [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "sendfd_docs"] sendfd-0.4.3/LICENSE-APACHE000064400000000000000000000261250072674642500130550ustar 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 2019 Standard Cognition 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. sendfd-0.4.3/LICENSE-BSD000064400000000000000000000027670072674642500125520ustar 00000000000000BSD 3-Clause License Copyright (c) 2019, Standard Cognition All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sendfd-0.4.3/README.mkd000064400000000000000000000013130072674642500125530ustar 00000000000000# sendfd sendfd is a little bare-bones crate that provides APIs to send file descriptors over UNIX sockets in Rust. This is done by providing an extension trait that is implemented by the UNIX domain socket types available in the standard library and (optionally) Tokio. For more information, see [the documentation]. There is no intention to make this crate a cross-platform abstraction (use the `ipc-channel` crate for that). Thanks to [roblabla] for giving us the crate name, as well as for the inspiration from their original implementation. sendfd is distributed under Apache 2.0 or BSD 3-clause license at your choice. [the documentation]: https://docs.rs/sendfd [roblabla]: https://github.com/roblabla sendfd-0.4.3/src/changelog.rs000064400000000000000000000030560072674642500142130ustar 00000000000000//! Project changelog /// Release 0.4.1 /// /// * Asynchronous socket support has been fixed to register interest with the runtime. In absence /// of this fix it was possible for an application to busy loop waiting for changes. pub mod r0_4_1 {} /// Release 0.4.2 /// /// * Implemented [SendWithFd](crate::SendWithFd) for [tokio::net::unix::WriteHalf] /// * Implemented [RecvWithFd](crate::RecvWithFd) for [tokio::net::unix::ReadHalf] pub mod r0_4_2 {} /// Release 0.4.0 /// /// * tokio 0.2 and tokio 0.3 support has been replaced by support for tokio 1.0. /// * 1.53.0 is now the minimum supported version of the `rustc` toolchain. pub mod r0_4_0 {} /// Release 0.3.3 /// /// * Compatibility with tokio::net::UnixStream and tokio::net::UnixDatagram for tokio 0.2 and 0.3. pub mod r0_3_3 {} /// Release 0.3.2 /// /// * Compatibility with musl. pub mod r0_3_2 {} /// Release 0.3.1 /// /// * Compatibility with macOS and BSDs. pub mod r0_3_1 {} /// Release 0.3.0 /// /// * Removed the `Receivable` trait, because it is difficult to write meaningful code with `` for `T ≠ RawFd`. /// * Removed the `Sendable` trait. While the generalisation here is sound and is beneficial, the /// inconsistency between ability to send any sendable and then only being able to receive a /// `RawFd` was deemed to be not worth it. pub mod r0_3_0 {} /// Release 0.2.1 /// /// Removed an accidentally publicly exported internal function. /// /// 0.2.0 has been yanked. pub mod r0_2_1 {} /// Release 0.2.0 /// /// Pure-Rust reimplementation of the crate. pub mod r0_2_0 {} sendfd-0.4.3/src/lib.rs000064400000000000000000000460530072674642500130360ustar 00000000000000#![cfg_attr(sendfd_docs, feature(doc_cfg))] extern crate libc; #[cfg(feature = "tokio")] extern crate tokio; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net; use std::{alloc, io, mem, ptr}; #[cfg(feature = "tokio")] use tokio::io::Interest; pub mod changelog; /// An extension trait that enables sending associated file descriptors along with the data. pub trait SendWithFd { /// Send the bytes and the file descriptors. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result; } /// An extension trait that enables receiving associated file descriptors along with the data. pub trait RecvWithFd { /// Receive the bytes and the file descriptors. /// /// The bytes and the file descriptors are received into the corresponding buffers. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)>; } // Replace with `<*const u8>::offset_from` once it is stable. unsafe fn ptr_offset_from(this: *const u8, origin: *const u8) -> isize { isize::wrapping_sub(this as _, origin as _) } /// Construct the `libc::msghdr` which is used as an argument to `libc::sendmsg` and /// `libc::recvmsg`. /// /// The constructed `msghdr` contains the references to the given `iov` and has sufficient /// (dynamically allocated) space to store `fd_count` file descriptors delivered as ancillary data. /// /// # Unsafety /// /// This function provides a "mostly" safe interface, however it is kept unsafe as its only uses /// are intended to be in other unsafe code and its implementation itself is also unsafe. unsafe fn construct_msghdr_for( iov: &mut libc::iovec, fd_count: usize, ) -> (libc::msghdr, alloc::Layout, usize) { let fd_len = mem::size_of::() * fd_count; let cmsg_buffer_len = libc::CMSG_SPACE(fd_len as u32) as usize; let layout = alloc::Layout::from_size_align(cmsg_buffer_len, mem::align_of::()); let (cmsg_buffer, cmsg_layout) = if let Ok(layout) = layout { const NULL_MUT_U8: *mut u8 = ptr::null_mut(); match alloc::alloc(layout) { NULL_MUT_U8 => alloc::handle_alloc_error(layout), x => (x as *mut _, layout), } } else { // NB: it is fine to construct such a `Layout` as it is not used for actual allocation, // just for the error reporting. Either way this branch is not reachable at all provided a // well behaved implementation of `CMSG_SPACE` in the host libc. alloc::handle_alloc_error(alloc::Layout::from_size_align_unchecked( cmsg_buffer_len, mem::align_of::(), )) }; let mut msghdr = mem::zeroed::(); msghdr.msg_name = ptr::null_mut(); msghdr.msg_namelen = 0; msghdr.msg_iov = iov as *mut _; msghdr.msg_iovlen = 1; msghdr.msg_control = cmsg_buffer; msghdr.msg_controllen = cmsg_buffer_len as _; (msghdr, cmsg_layout, fd_len) } /// A common implementation of `sendmsg` that sends provided bytes with ancillary file descriptors /// over either a datagram or stream unix socket. fn send_with_fd(socket: RawFd, bs: &[u8], fds: &[RawFd]) -> io::Result { unsafe { let mut iov = libc::iovec { // NB: this casts *const to *mut, and in doing so we trust the OS to be a good citizen // and not mutate our buffer. This is the API we have to live with. iov_base: bs.as_ptr() as *const _ as *mut _, iov_len: bs.len(), }; let (mut msghdr, cmsg_layout, fd_len) = construct_msghdr_for(&mut iov, fds.len()); let cmsg_buffer = msghdr.msg_control; // Fill cmsg with the file descriptors we are sending. let cmsg_header = libc::CMSG_FIRSTHDR(&mut msghdr as *mut _); let mut cmsghdr = mem::zeroed::(); cmsghdr.cmsg_level = libc::SOL_SOCKET; cmsghdr.cmsg_type = libc::SCM_RIGHTS; cmsghdr.cmsg_len = libc::CMSG_LEN(fd_len as u32) as _; ptr::write(cmsg_header, cmsghdr); let cmsg_data = libc::CMSG_DATA(cmsg_header) as *mut RawFd; for (i, fd) in fds.iter().enumerate() { ptr::write_unaligned(cmsg_data.add(i), *fd); } let count = libc::sendmsg(socket, &msghdr as *const _, 0); if count < 0 { let error = io::Error::last_os_error(); alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); Err(error) } else { alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); Ok(count as usize) } } } /// A common implementation of `recvmsg` that receives provided bytes and the ancillary file /// descriptors over either a datagram or stream unix socket. fn recv_with_fd(socket: RawFd, bs: &mut [u8], mut fds: &mut [RawFd]) -> io::Result<(usize, usize)> { unsafe { let mut iov = libc::iovec { iov_base: bs.as_mut_ptr() as *mut _, iov_len: bs.len(), }; let (mut msghdr, cmsg_layout, _) = construct_msghdr_for(&mut iov, fds.len()); let cmsg_buffer = msghdr.msg_control; let count = libc::recvmsg(socket, &mut msghdr as *mut _, 0); if count < 0 { let error = io::Error::last_os_error(); alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); return Err(error); } // Walk the ancillary data buffer and copy the raw descriptors from it into the output // buffer. let mut descriptor_count = 0; let mut cmsg_header = libc::CMSG_FIRSTHDR(&mut msghdr as *mut _); while !cmsg_header.is_null() { if (*cmsg_header).cmsg_level == libc::SOL_SOCKET && (*cmsg_header).cmsg_type == libc::SCM_RIGHTS { let data_ptr = libc::CMSG_DATA(cmsg_header); let data_offset = ptr_offset_from(data_ptr, cmsg_header as *const _); debug_assert!(data_offset >= 0); let data_byte_count = (*cmsg_header).cmsg_len as usize - data_offset as usize; debug_assert!((*cmsg_header).cmsg_len as isize > data_offset); debug_assert!(data_byte_count % mem::size_of::() == 0); let rawfd_count = (data_byte_count / mem::size_of::()) as isize; let fd_ptr = data_ptr as *const RawFd; for i in 0..rawfd_count { if let Some((dst, rest)) = { fds }.split_first_mut() { *dst = ptr::read_unaligned(fd_ptr.offset(i)); descriptor_count += 1; fds = rest; } else { // This branch is unreachable. We allocate the ancillary data buffer just // large enough to fit exactly the number of `RawFd`s that are in the `fds` // buffer. It is not possible for the OS to return more of them. // // If this branch ended up being reachable for some reason, it would be // necessary for this branch to close the file descriptors to avoid leaking // resources. // // TODO: consider using unreachable_unchecked unreachable!(); } } } cmsg_header = libc::CMSG_NXTHDR(&mut msghdr as *mut _, cmsg_header); } alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); Ok((count as usize, descriptor_count)) } } impl SendWithFd for net::UnixStream { /// Send the bytes and the file descriptors as a stream. /// /// Neither is guaranteed to be received by the other end in a single chunk and /// may arrive entirely independently. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { send_with_fd(self.as_raw_fd(), bytes, fds) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl SendWithFd for tokio::net::UnixStream { /// Send the bytes and the file descriptors as a stream. /// /// Neither is guaranteed to be received by the other end in a single chunk and /// may arrive entirely independently. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { self.try_io(Interest::WRITABLE, || send_with_fd(self.as_raw_fd(), bytes, fds)) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl SendWithFd for tokio::net::unix::WriteHalf<'_> { /// Send the bytes and the file descriptors as a stream. /// /// Neither is guaranteed to be received by the other end in a single chunk and /// may arrive entirely independently. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { let unix_stream: &tokio::net::UnixStream = self.as_ref(); unix_stream.send_with_fd(bytes, fds) } } impl SendWithFd for net::UnixDatagram { /// Send the bytes and the file descriptors as a single packet. /// /// It is guaranteed that the bytes and the associated file descriptors will arrive at the same /// time, however the receiver end may not receive the full message if its buffers are too /// small. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { send_with_fd(self.as_raw_fd(), bytes, fds) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl SendWithFd for tokio::net::UnixDatagram { /// Send the bytes and the file descriptors as a single packet. /// /// It is guaranteed that the bytes and the associated file descriptors will arrive at the same /// time, however the receiver end may not receive the full message if its buffers are too /// small. fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { self.try_io(Interest::WRITABLE, || send_with_fd(self.as_raw_fd(), bytes, fds)) } } impl RecvWithFd for net::UnixStream { /// Receive the bytes and the file descriptors from the stream. /// /// It is not guaranteed that the received information will form a single coherent packet of /// data. In other words, it is not required that this receives the bytes and file descriptors /// that were sent with a single `send_with_fd` call by somebody else. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { recv_with_fd(self.as_raw_fd(), bytes, fds) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl RecvWithFd for tokio::net::UnixStream { /// Receive the bytes and the file descriptors from the stream. /// /// It is not guaranteed that the received information will form a single coherent packet of /// data. In other words, it is not required that this receives the bytes and file descriptors /// that were sent with a single `send_with_fd` call by somebody else. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { self.try_io(Interest::READABLE, || recv_with_fd(self.as_raw_fd(), bytes, fds)) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl RecvWithFd for tokio::net::unix::ReadHalf<'_> { /// Receive the bytes and the file descriptors from the stream. /// /// It is not guaranteed that the received information will form a single coherent packet of /// data. In other words, it is not required that this receives the bytes and file descriptors /// that were sent with a single `send_with_fd` call by somebody else. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { let unix_stream: &tokio::net::UnixStream = self.as_ref(); unix_stream.recv_with_fd(bytes, fds) } } impl RecvWithFd for net::UnixDatagram { /// Receive the bytes and the file descriptors as a single packet. /// /// It is guaranteed that the received information will form a single coherent packet, and data /// received will match a corresponding `send_with_fd` call. Note, however, that in case the /// receiving buffer(s) are to small, the message may get silently truncated and the /// undelivered data will be discarded. /// /// For receiving the file descriptors, the internal buffer is sized according to the size of /// the `fds` buffer. If the sender sends `fds.len()` descriptors, but prefaces the descriptors /// with some other ancilliary data, then some file descriptors may be truncated as well. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { recv_with_fd(self.as_raw_fd(), bytes, fds) } } #[cfg(feature = "tokio")] #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] impl RecvWithFd for tokio::net::UnixDatagram { /// Receive the bytes and the file descriptors as a single packet. /// /// It is guaranteed that the received information will form a single coherent packet, and data /// received will match a corresponding `send_with_fd` call. Note, however, that in case the /// receiving buffer(s) are to small, the message may get silently truncated and the /// undelivered data will be discarded. /// /// For receiving the file descriptors, the internal buffer is sized according to the size of /// the `fds` buffer. If the sender sends `fds.len()` descriptors, but prefaces the descriptors /// with some other ancilliary data, then some file descriptors may be truncated as well. fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { self.try_io(Interest::READABLE, || recv_with_fd(self.as_raw_fd(), bytes, fds)) } } #[cfg(test)] mod tests { use super::{RecvWithFd, SendWithFd}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net; #[test] fn stream_works() { let (l, r) = net::UnixStream::pair().expect("create UnixStream pair"); let sent_bytes = b"hello world!"; let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; assert_eq!( l.send_with_fd(&sent_bytes[..], &sent_fds[..]) .expect("send should be successful"), sent_bytes.len() ); let mut recv_bytes = [0; 128]; let mut recv_fds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; assert_eq!( r.recv_with_fd(&mut recv_bytes, &mut recv_fds) .expect("recv should be successful"), (sent_bytes.len(), sent_fds.len()) ); assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { // Modify the sent resource and check if the received resource has been modified the // same way. let expected_value = Some(std::time::Duration::from_secs(42)); unsafe { let s = net::UnixStream::from_raw_fd(sent); s.set_read_timeout(expected_value) .expect("set read timeout"); std::mem::forget(s); assert_eq!( net::UnixStream::from_raw_fd(recvd) .read_timeout() .expect("get read timeout"), expected_value ); } } } #[test] fn datagram_works() { let (l, r) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); let sent_bytes = b"hello world!"; let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; assert_eq!( l.send_with_fd(&sent_bytes[..], &sent_fds[..]) .expect("send should be successful"), sent_bytes.len() ); let mut recv_bytes = [0; 128]; let mut recv_fds = [0, 0, 0, 0, 0, 0, 0]; assert_eq!( r.recv_with_fd(&mut recv_bytes, &mut recv_fds) .expect("recv should be successful"), (sent_bytes.len(), sent_fds.len()) ); assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { // Modify the sent resource and check if the received resource has been modified the // same way. let expected_value = Some(std::time::Duration::from_secs(42)); unsafe { let s = net::UnixDatagram::from_raw_fd(sent); s.set_read_timeout(expected_value) .expect("set read timeout"); std::mem::forget(s); assert_eq!( net::UnixDatagram::from_raw_fd(recvd) .read_timeout() .expect("get read timeout"), expected_value ); } } } #[test] fn datagram_works_across_processes() { let (l, r) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); let sent_bytes = b"hello world!"; let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; unsafe { match libc::fork() { -1 => panic!("fork failed!"), 0 => { // This is the child in which we attempt to send a file descriptor back to // parent, emulating the cross-process FD sharing. l.send_with_fd(&sent_bytes[..], &sent_fds[..]) .expect("send should be successful"); ::std::process::exit(0); } _ => { // Parent process, receives the file descriptors sent by forked child. } } let mut recv_bytes = [0; 128]; let mut recv_fds = [0, 0, 0, 0, 0, 0, 0]; assert_eq!( r.recv_with_fd(&mut recv_bytes, &mut recv_fds) .expect("recv should be successful"), (sent_bytes.len(), sent_fds.len()) ); assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { // Modify the sent resource and check if the received resource has been // modified the same way. let expected_value = Some(std::time::Duration::from_secs(42)); let s = net::UnixDatagram::from_raw_fd(sent); s.set_read_timeout(expected_value) .expect("set read timeout"); std::mem::forget(s); assert_eq!( net::UnixDatagram::from_raw_fd(recvd) .read_timeout() .expect("get read timeout"), expected_value ); } } } #[test] fn sending_junk_fails() { let (l, _) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); let sent_bytes = b"hello world!"; if let Ok(_) = l.send_with_fd(&sent_bytes[..], &[i32::max_value()][..]) { panic!("expected an error when sending a junk file descriptor"); } if let Ok(_) = l.send_with_fd(&sent_bytes[..], &[0xffi32][..]) { panic!("expected an error when sending a junk file descriptor"); } } }