├── .github ├── dependabot.yml └── workflows │ └── sendfd.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-BSD ├── README.mkd └── src ├── changelog.rs └── lib.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "13:00" 8 | open-pull-requests-limit: 10 9 | allow: 10 | - dependency-type: direct 11 | - dependency-type: indirect 12 | -------------------------------------------------------------------------------- /.github/workflows/sendfd.yml: -------------------------------------------------------------------------------- 1 | name: Test sendfd 2 | 3 | on: 4 | push: 5 | paths-ignore: 6 | - '*.mkd' 7 | - 'LICENSE' 8 | pull_request: 9 | 10 | jobs: 11 | native-test: 12 | runs-on: ${{ matrix.os }} 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | rust_toolchain: [nightly, stable, 1.70.0] 17 | os: [ubuntu-latest, macOS-latest] 18 | flags: ["--all-features", "--all-features --release", ""] 19 | timeout-minutes: 20 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Install Rust ${{ matrix.rust_toolchain }} 23 | uses: actions-rs/toolchain@v1 24 | with: 25 | toolchain: ${{ matrix.rust_toolchain }} 26 | profile: minimal 27 | default: true 28 | - name: Test 29 | uses: actions-rs/cargo@v1 30 | with: 31 | command: test 32 | args: ${{ matrix.flags }} --manifest-path=Cargo.toml -- --nocapture 33 | 34 | bare-cross-build: 35 | runs-on: ubuntu-latest 36 | strategy: 37 | fail-fast: false 38 | matrix: 39 | rust_target: 40 | # BSDs: could be tested with full system emulation 41 | # - x86_64-unknown-dragonfly 42 | # - x86_64-unknown-freebsd 43 | # - x86_64-unknown-haiku 44 | # - x86_64-unknown-netbsd 45 | - x86_64-unknown-openbsd 46 | # - x86_64-unknown-redox 47 | # - x86_64-fuchsia 48 | timeout-minutes: 20 49 | steps: 50 | - uses: actions/checkout@v2 51 | - name: Install Rust nightly 52 | uses: actions-rs/toolchain@v1 53 | with: 54 | toolchain: nightly 55 | profile: minimal 56 | default: true 57 | - name: Fix-up toolchain 58 | run: | 59 | rustup component add rust-src --toolchain nightly --target ${{ matrix.rust_target }} 60 | - name: Update 61 | uses: actions-rs/cargo@v1 62 | with: 63 | command: update 64 | args: --manifest-path=Cargo.toml 65 | - name: Build ${{ matrix.rust_target }} 66 | uses: actions-rs/cargo@v1 67 | with: 68 | command: build 69 | args: --target ${{ matrix.rust_target }} --manifest-path=Cargo.toml -Zbuild-std 70 | 71 | cross-ios-build: 72 | runs-on: macos-latest 73 | strategy: 74 | fail-fast: false 75 | matrix: 76 | rust_toolchain: [nightly, stable] 77 | rust_target: 78 | - aarch64-apple-ios 79 | - x86_64-apple-ios 80 | timeout-minutes: 20 81 | steps: 82 | - uses: actions/checkout@v2 83 | - name: Install Rust ${{ matrix.rust_toolchain }} 84 | uses: actions-rs/toolchain@v1 85 | with: 86 | toolchain: ${{ matrix.rust_toolchain }} 87 | target: ${{ matrix.rust_target }} 88 | profile: minimal 89 | default: true 90 | - name: Update 91 | uses: actions-rs/cargo@v1 92 | with: 93 | command: update 94 | args: --manifest-path=Cargo.toml 95 | - name: Build ${{ matrix.rust_target }} 96 | uses: actions-rs/cargo@v1 97 | with: 98 | command: build 99 | args: --target=${{ matrix.rust_target }} --manifest-path=Cargo.toml 100 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sendfd" 3 | version = "0.4.4" 4 | authors = [ 5 | "Simonas Kazlauskas ", 6 | "Bernardo Meurer ", 7 | "Léo Gaspard " 8 | ] 9 | edition = "2015" 10 | description = "Send file descriptors along with data over UNIX domain sockets" 11 | keywords = ["ipc"] 12 | license = "Apache-2.0 OR BSD-3-Clause" 13 | repository = "https://github.com/standard-ai/sendfd" 14 | documentation = "https://docs.rs/sendfd" 15 | readme = "README.mkd" 16 | 17 | [dependencies] 18 | libc = "0.2" 19 | tokio = { version = "1.0.0", features = [ "net" ], optional = true } 20 | 21 | [package.metadata.docs.rs] 22 | all-features = true 23 | rustdoc-args = ["--cfg", "sendfd_docs"] 24 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Standard Cognition 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LICENSE-BSD: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2019, Standard Cognition 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | -------------------------------------------------------------------------------- /README.mkd: -------------------------------------------------------------------------------- 1 | # sendfd 2 | 3 | sendfd is a little bare-bones crate that provides APIs to send file descriptors over UNIX sockets in 4 | Rust. 5 | 6 | This is done by providing an extension trait that is implemented by the UNIX domain socket types 7 | available in the standard library and (optionally) Tokio. For more information, see [the 8 | documentation]. 9 | 10 | There is no intention to make this crate a cross-platform abstraction (use the `ipc-channel` crate 11 | for that). 12 | 13 | Thanks to [roblabla] for giving us the crate name, as well as for the inspiration 14 | from their original implementation. 15 | 16 | sendfd is distributed under Apache 2.0 or BSD 3-clause license at your choice. 17 | 18 | [the documentation]: https://docs.rs/sendfd 19 | [roblabla]: https://github.com/roblabla 20 | -------------------------------------------------------------------------------- /src/changelog.rs: -------------------------------------------------------------------------------- 1 | //! Project changelog 2 | 3 | /// Release 0.4.1 4 | /// 5 | /// * Asynchronous socket support has been fixed to register interest with the runtime. In absence 6 | /// of this fix it was possible for an application to busy loop waiting for changes. 7 | pub mod r0_4_1 {} 8 | 9 | /// Release 0.4.2 10 | /// 11 | /// * Implemented [SendWithFd](crate::SendWithFd) for [tokio::net::unix::WriteHalf] 12 | /// * Implemented [RecvWithFd](crate::RecvWithFd) for [tokio::net::unix::ReadHalf] 13 | pub mod r0_4_2 {} 14 | 15 | /// Release 0.4.0 16 | /// 17 | /// * tokio 0.2 and tokio 0.3 support has been replaced by support for tokio 1.0. 18 | /// * 1.53.0 is now the minimum supported version of the `rustc` toolchain. 19 | pub mod r0_4_0 {} 20 | 21 | /// Release 0.3.3 22 | /// 23 | /// * Compatibility with tokio::net::UnixStream and tokio::net::UnixDatagram for tokio 0.2 and 0.3. 24 | pub mod r0_3_3 {} 25 | 26 | /// Release 0.3.2 27 | /// 28 | /// * Compatibility with musl. 29 | pub mod r0_3_2 {} 30 | 31 | /// Release 0.3.1 32 | /// 33 | /// * Compatibility with macOS and BSDs. 34 | pub mod r0_3_1 {} 35 | 36 | /// Release 0.3.0 37 | /// 38 | /// * Removed the `Receivable` trait, because it is difficult to write meaningful code with `` for `T ≠ RawFd`. 40 | /// * Removed the `Sendable` trait. While the generalisation here is sound and is beneficial, the 41 | /// inconsistency between ability to send any sendable and then only being able to receive a 42 | /// `RawFd` was deemed to be not worth it. 43 | pub mod r0_3_0 {} 44 | 45 | /// Release 0.2.1 46 | /// 47 | /// Removed an accidentally publicly exported internal function. 48 | /// 49 | /// 0.2.0 has been yanked. 50 | pub mod r0_2_1 {} 51 | 52 | /// Release 0.2.0 53 | /// 54 | /// Pure-Rust reimplementation of the crate. 55 | pub mod r0_2_0 {} 56 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(sendfd_docs, feature(doc_cfg))] 2 | 3 | extern crate libc; 4 | #[cfg(feature = "tokio")] 5 | extern crate tokio; 6 | 7 | use std::os::unix::io::{AsRawFd, RawFd}; 8 | use std::os::unix::net; 9 | use std::{alloc, io, mem, ptr}; 10 | #[cfg(feature = "tokio")] 11 | use tokio::io::Interest; 12 | 13 | pub mod changelog; 14 | 15 | /// An extension trait that enables sending associated file descriptors along with the data. 16 | pub trait SendWithFd { 17 | /// Send the bytes and the file descriptors. 18 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result; 19 | } 20 | 21 | /// An extension trait that enables receiving associated file descriptors along with the data. 22 | pub trait RecvWithFd { 23 | /// Receive the bytes and the file descriptors. 24 | /// 25 | /// The bytes and the file descriptors are received into the corresponding buffers. 26 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)>; 27 | } 28 | 29 | // Replace with `<*const u8>::offset_from` once it is stable. 30 | unsafe fn ptr_offset_from(this: *const u8, origin: *const u8) -> isize { 31 | isize::wrapping_sub(this as _, origin as _) 32 | } 33 | 34 | /// Construct the `libc::msghdr` which is used as an argument to `libc::sendmsg` and 35 | /// `libc::recvmsg`. 36 | /// 37 | /// The constructed `msghdr` contains the references to the given `iov` and has sufficient 38 | /// (dynamically allocated) space to store `fd_count` file descriptors delivered as ancillary data. 39 | /// 40 | /// # Unsafety 41 | /// 42 | /// This function provides a "mostly" safe interface, however it is kept unsafe as its only uses 43 | /// are intended to be in other unsafe code and its implementation itself is also unsafe. 44 | unsafe fn construct_msghdr_for( 45 | iov: &mut libc::iovec, 46 | fd_count: usize, 47 | ) -> (libc::msghdr, alloc::Layout, usize) { 48 | let fd_len = mem::size_of::() * fd_count; 49 | let cmsg_buffer_len = libc::CMSG_SPACE(fd_len as u32) as usize; 50 | let layout = alloc::Layout::from_size_align(cmsg_buffer_len, mem::align_of::()); 51 | let (cmsg_buffer, cmsg_layout) = if let Ok(layout) = layout { 52 | const NULL_MUT_U8: *mut u8 = ptr::null_mut(); 53 | match alloc::alloc(layout) { 54 | NULL_MUT_U8 => alloc::handle_alloc_error(layout), 55 | x => (x as *mut _, layout), 56 | } 57 | } else { 58 | // NB: it is fine to construct such a `Layout` as it is not used for actual allocation, 59 | // just for the error reporting. Either way this branch is not reachable at all provided a 60 | // well behaved implementation of `CMSG_SPACE` in the host libc. 61 | alloc::handle_alloc_error(alloc::Layout::from_size_align_unchecked( 62 | cmsg_buffer_len, 63 | mem::align_of::(), 64 | )) 65 | }; 66 | 67 | let mut msghdr = mem::zeroed::(); 68 | msghdr.msg_name = ptr::null_mut(); 69 | msghdr.msg_namelen = 0; 70 | msghdr.msg_iov = iov as *mut _; 71 | msghdr.msg_iovlen = 1; 72 | msghdr.msg_control = cmsg_buffer; 73 | msghdr.msg_controllen = cmsg_buffer_len as _; 74 | 75 | (msghdr, cmsg_layout, fd_len) 76 | } 77 | 78 | /// A common implementation of `sendmsg` that sends provided bytes with ancillary file descriptors 79 | /// over either a datagram or stream unix socket. 80 | fn send_with_fd(socket: RawFd, bs: &[u8], fds: &[RawFd]) -> io::Result { 81 | unsafe { 82 | let mut iov = libc::iovec { 83 | // NB: this casts *const to *mut, and in doing so we trust the OS to be a good citizen 84 | // and not mutate our buffer. This is the API we have to live with. 85 | iov_base: bs.as_ptr() as *const _ as *mut _, 86 | iov_len: bs.len(), 87 | }; 88 | let (mut msghdr, cmsg_layout, fd_len) = construct_msghdr_for(&mut iov, fds.len()); 89 | let cmsg_buffer = msghdr.msg_control; 90 | 91 | // Fill cmsg with the file descriptors we are sending. 92 | let cmsg_header = libc::CMSG_FIRSTHDR(&mut msghdr as *mut _); 93 | let mut cmsghdr = mem::zeroed::(); 94 | cmsghdr.cmsg_level = libc::SOL_SOCKET; 95 | cmsghdr.cmsg_type = libc::SCM_RIGHTS; 96 | cmsghdr.cmsg_len = libc::CMSG_LEN(fd_len as u32) as _; 97 | 98 | ptr::write(cmsg_header, cmsghdr); 99 | 100 | let cmsg_data = libc::CMSG_DATA(cmsg_header) as *mut RawFd; 101 | for (i, fd) in fds.iter().enumerate() { 102 | ptr::write_unaligned(cmsg_data.add(i), *fd); 103 | } 104 | let count = libc::sendmsg(socket, &msghdr as *const _, 0); 105 | if count < 0 { 106 | let error = io::Error::last_os_error(); 107 | alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); 108 | Err(error) 109 | } else { 110 | alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); 111 | Ok(count as usize) 112 | } 113 | } 114 | } 115 | 116 | /// A common implementation of `recvmsg` that receives provided bytes and the ancillary file 117 | /// descriptors over either a datagram or stream unix socket. 118 | fn recv_with_fd(socket: RawFd, bs: &mut [u8], mut fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 119 | unsafe { 120 | let mut iov = libc::iovec { 121 | iov_base: bs.as_mut_ptr() as *mut _, 122 | iov_len: bs.len(), 123 | }; 124 | let (mut msghdr, cmsg_layout, _) = construct_msghdr_for(&mut iov, fds.len()); 125 | let cmsg_buffer = msghdr.msg_control; 126 | let count = libc::recvmsg(socket, &mut msghdr as *mut _, 0); 127 | if count < 0 { 128 | let error = io::Error::last_os_error(); 129 | alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); 130 | return Err(error); 131 | } 132 | 133 | // Walk the ancillary data buffer and copy the raw descriptors from it into the output 134 | // buffer. 135 | let mut descriptor_count = 0; 136 | let mut cmsg_header = libc::CMSG_FIRSTHDR(&mut msghdr as *mut _); 137 | while !cmsg_header.is_null() { 138 | if (*cmsg_header).cmsg_level == libc::SOL_SOCKET 139 | && (*cmsg_header).cmsg_type == libc::SCM_RIGHTS 140 | { 141 | let data_ptr = libc::CMSG_DATA(cmsg_header); 142 | let data_offset = ptr_offset_from(data_ptr, cmsg_header as *const _); 143 | debug_assert!(data_offset >= 0); 144 | let data_byte_count = (*cmsg_header).cmsg_len as usize - data_offset as usize; 145 | debug_assert!((*cmsg_header).cmsg_len as isize >= data_offset); 146 | debug_assert!(data_byte_count % mem::size_of::() == 0); 147 | let rawfd_count = (data_byte_count / mem::size_of::()) as isize; 148 | let fd_ptr = data_ptr as *const RawFd; 149 | for i in 0..rawfd_count { 150 | if let Some((dst, rest)) = { fds }.split_first_mut() { 151 | *dst = ptr::read_unaligned(fd_ptr.offset(i)); 152 | descriptor_count += 1; 153 | fds = rest; 154 | } else { 155 | // This branch is unreachable. We allocate the ancillary data buffer just 156 | // large enough to fit exactly the number of `RawFd`s that are in the `fds` 157 | // buffer. It is not possible for the OS to return more of them. 158 | // 159 | // If this branch ended up being reachable for some reason, it would be 160 | // necessary for this branch to close the file descriptors to avoid leaking 161 | // resources. 162 | // 163 | // TODO: consider using unreachable_unchecked 164 | unreachable!(); 165 | } 166 | } 167 | } 168 | cmsg_header = libc::CMSG_NXTHDR(&mut msghdr as *mut _, cmsg_header); 169 | } 170 | 171 | alloc::dealloc(cmsg_buffer as *mut _, cmsg_layout); 172 | Ok((count as usize, descriptor_count)) 173 | } 174 | } 175 | 176 | impl SendWithFd for net::UnixStream { 177 | /// Send the bytes and the file descriptors as a stream. 178 | /// 179 | /// Neither is guaranteed to be received by the other end in a single chunk and 180 | /// may arrive entirely independently. 181 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { 182 | send_with_fd(self.as_raw_fd(), bytes, fds) 183 | } 184 | } 185 | 186 | #[cfg(feature = "tokio")] 187 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 188 | impl SendWithFd for tokio::net::UnixStream { 189 | /// Send the bytes and the file descriptors as a stream. 190 | /// 191 | /// Neither is guaranteed to be received by the other end in a single chunk and 192 | /// may arrive entirely independently. 193 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { 194 | self.try_io(Interest::WRITABLE, || { 195 | send_with_fd(self.as_raw_fd(), bytes, fds) 196 | }) 197 | } 198 | } 199 | 200 | #[cfg(feature = "tokio")] 201 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 202 | impl SendWithFd for tokio::net::unix::WriteHalf<'_> { 203 | /// Send the bytes and the file descriptors as a stream. 204 | /// 205 | /// Neither is guaranteed to be received by the other end in a single chunk and 206 | /// may arrive entirely independently. 207 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { 208 | let unix_stream: &tokio::net::UnixStream = self.as_ref(); 209 | unix_stream.send_with_fd(bytes, fds) 210 | } 211 | } 212 | 213 | impl SendWithFd for net::UnixDatagram { 214 | /// Send the bytes and the file descriptors as a single packet. 215 | /// 216 | /// It is guaranteed that the bytes and the associated file descriptors will arrive at the same 217 | /// time, however the receiver end may not receive the full message if its buffers are too 218 | /// small. 219 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { 220 | send_with_fd(self.as_raw_fd(), bytes, fds) 221 | } 222 | } 223 | 224 | #[cfg(feature = "tokio")] 225 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 226 | impl SendWithFd for tokio::net::UnixDatagram { 227 | /// Send the bytes and the file descriptors as a single packet. 228 | /// 229 | /// It is guaranteed that the bytes and the associated file descriptors will arrive at the same 230 | /// time, however the receiver end may not receive the full message if its buffers are too 231 | /// small. 232 | fn send_with_fd(&self, bytes: &[u8], fds: &[RawFd]) -> io::Result { 233 | self.try_io(Interest::WRITABLE, || { 234 | send_with_fd(self.as_raw_fd(), bytes, fds) 235 | }) 236 | } 237 | } 238 | 239 | impl RecvWithFd for net::UnixStream { 240 | /// Receive the bytes and the file descriptors from the stream. 241 | /// 242 | /// It is not guaranteed that the received information will form a single coherent packet of 243 | /// data. In other words, it is not required that this receives the bytes and file descriptors 244 | /// that were sent with a single `send_with_fd` call by somebody else. 245 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 246 | recv_with_fd(self.as_raw_fd(), bytes, fds) 247 | } 248 | } 249 | 250 | #[cfg(feature = "tokio")] 251 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 252 | impl RecvWithFd for tokio::net::UnixStream { 253 | /// Receive the bytes and the file descriptors from the stream. 254 | /// 255 | /// It is not guaranteed that the received information will form a single coherent packet of 256 | /// data. In other words, it is not required that this receives the bytes and file descriptors 257 | /// that were sent with a single `send_with_fd` call by somebody else. 258 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 259 | self.try_io(Interest::READABLE, || { 260 | recv_with_fd(self.as_raw_fd(), bytes, fds) 261 | }) 262 | } 263 | } 264 | 265 | #[cfg(feature = "tokio")] 266 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 267 | impl RecvWithFd for tokio::net::unix::ReadHalf<'_> { 268 | /// Receive the bytes and the file descriptors from the stream. 269 | /// 270 | /// It is not guaranteed that the received information will form a single coherent packet of 271 | /// data. In other words, it is not required that this receives the bytes and file descriptors 272 | /// that were sent with a single `send_with_fd` call by somebody else. 273 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 274 | let unix_stream: &tokio::net::UnixStream = self.as_ref(); 275 | unix_stream.recv_with_fd(bytes, fds) 276 | } 277 | } 278 | 279 | impl RecvWithFd for net::UnixDatagram { 280 | /// Receive the bytes and the file descriptors as a single packet. 281 | /// 282 | /// It is guaranteed that the received information will form a single coherent packet, and data 283 | /// received will match a corresponding `send_with_fd` call. Note, however, that in case the 284 | /// receiving buffer(s) are to small, the message may get silently truncated and the 285 | /// undelivered data will be discarded. 286 | /// 287 | /// For receiving the file descriptors, the internal buffer is sized according to the size of 288 | /// the `fds` buffer. If the sender sends `fds.len()` descriptors, but prefaces the descriptors 289 | /// with some other ancilliary data, then some file descriptors may be truncated as well. 290 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 291 | recv_with_fd(self.as_raw_fd(), bytes, fds) 292 | } 293 | } 294 | 295 | #[cfg(feature = "tokio")] 296 | #[cfg_attr(sendfd_docs, doc(cfg(feature = "tokio")))] 297 | impl RecvWithFd for tokio::net::UnixDatagram { 298 | /// Receive the bytes and the file descriptors as a single packet. 299 | /// 300 | /// It is guaranteed that the received information will form a single coherent packet, and data 301 | /// received will match a corresponding `send_with_fd` call. Note, however, that in case the 302 | /// receiving buffer(s) are to small, the message may get silently truncated and the 303 | /// undelivered data will be discarded. 304 | /// 305 | /// For receiving the file descriptors, the internal buffer is sized according to the size of 306 | /// the `fds` buffer. If the sender sends `fds.len()` descriptors, but prefaces the descriptors 307 | /// with some other ancilliary data, then some file descriptors may be truncated as well. 308 | fn recv_with_fd(&self, bytes: &mut [u8], fds: &mut [RawFd]) -> io::Result<(usize, usize)> { 309 | self.try_io(Interest::READABLE, || { 310 | recv_with_fd(self.as_raw_fd(), bytes, fds) 311 | }) 312 | } 313 | } 314 | 315 | #[cfg(test)] 316 | mod tests { 317 | use super::{RecvWithFd, SendWithFd}; 318 | use std::os::unix::io::{AsRawFd, FromRawFd}; 319 | use std::os::unix::net; 320 | 321 | #[test] 322 | fn stream_works() { 323 | let (l, r) = net::UnixStream::pair().expect("create UnixStream pair"); 324 | let sent_bytes = b"hello world!"; 325 | let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; 326 | assert_eq!( 327 | l.send_with_fd(&sent_bytes[..], &sent_fds[..]) 328 | .expect("send should be successful"), 329 | sent_bytes.len() 330 | ); 331 | let mut recv_bytes = [0; 128]; 332 | let mut recv_fds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 333 | assert_eq!( 334 | r.recv_with_fd(&mut recv_bytes, &mut recv_fds) 335 | .expect("recv should be successful"), 336 | (sent_bytes.len(), sent_fds.len()) 337 | ); 338 | assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); 339 | for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { 340 | // Modify the sent resource and check if the received resource has been modified the 341 | // same way. 342 | let expected_value = Some(std::time::Duration::from_secs(42)); 343 | unsafe { 344 | let s = net::UnixStream::from_raw_fd(sent); 345 | s.set_read_timeout(expected_value) 346 | .expect("set read timeout"); 347 | std::mem::forget(s); 348 | assert_eq!( 349 | net::UnixStream::from_raw_fd(recvd) 350 | .read_timeout() 351 | .expect("get read timeout"), 352 | expected_value 353 | ); 354 | } 355 | } 356 | } 357 | 358 | #[test] 359 | fn datagram_works() { 360 | let (l, r) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); 361 | let sent_bytes = b"hello world!"; 362 | let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; 363 | assert_eq!( 364 | l.send_with_fd(&sent_bytes[..], &sent_fds[..]) 365 | .expect("send should be successful"), 366 | sent_bytes.len() 367 | ); 368 | let mut recv_bytes = [0; 128]; 369 | let mut recv_fds = [0, 0, 0, 0, 0, 0, 0]; 370 | assert_eq!( 371 | r.recv_with_fd(&mut recv_bytes, &mut recv_fds) 372 | .expect("recv should be successful"), 373 | (sent_bytes.len(), sent_fds.len()) 374 | ); 375 | assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); 376 | for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { 377 | // Modify the sent resource and check if the received resource has been modified the 378 | // same way. 379 | let expected_value = Some(std::time::Duration::from_secs(42)); 380 | unsafe { 381 | let s = net::UnixDatagram::from_raw_fd(sent); 382 | s.set_read_timeout(expected_value) 383 | .expect("set read timeout"); 384 | std::mem::forget(s); 385 | assert_eq!( 386 | net::UnixDatagram::from_raw_fd(recvd) 387 | .read_timeout() 388 | .expect("get read timeout"), 389 | expected_value 390 | ); 391 | } 392 | } 393 | } 394 | 395 | #[test] 396 | fn datagram_works_across_processes() { 397 | let (l, r) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); 398 | let sent_bytes = b"hello world!"; 399 | let sent_fds = [l.as_raw_fd(), r.as_raw_fd()]; 400 | 401 | unsafe { 402 | match libc::fork() { 403 | -1 => panic!("fork failed!"), 404 | 0 => { 405 | // This is the child in which we attempt to send a file descriptor back to 406 | // parent, emulating the cross-process FD sharing. 407 | l.send_with_fd(&sent_bytes[..], &sent_fds[..]) 408 | .expect("send should be successful"); 409 | ::std::process::exit(0); 410 | } 411 | _ => { 412 | // Parent process, receives the file descriptors sent by forked child. 413 | } 414 | } 415 | let mut recv_bytes = [0; 128]; 416 | let mut recv_fds = [0, 0, 0, 0, 0, 0, 0]; 417 | assert_eq!( 418 | r.recv_with_fd(&mut recv_bytes, &mut recv_fds) 419 | .expect("recv should be successful"), 420 | (sent_bytes.len(), sent_fds.len()) 421 | ); 422 | assert_eq!(recv_bytes[..sent_bytes.len()], sent_bytes[..]); 423 | for (&sent, &recvd) in sent_fds.iter().zip(&recv_fds[..]) { 424 | // Modify the sent resource and check if the received resource has been 425 | // modified the same way. 426 | let expected_value = Some(std::time::Duration::from_secs(42)); 427 | let s = net::UnixDatagram::from_raw_fd(sent); 428 | s.set_read_timeout(expected_value) 429 | .expect("set read timeout"); 430 | std::mem::forget(s); 431 | assert_eq!( 432 | net::UnixDatagram::from_raw_fd(recvd) 433 | .read_timeout() 434 | .expect("get read timeout"), 435 | expected_value 436 | ); 437 | } 438 | } 439 | } 440 | 441 | #[test] 442 | fn sending_junk_fails() { 443 | let (l, _) = net::UnixDatagram::pair().expect("create UnixDatagram pair"); 444 | let sent_bytes = b"hello world!"; 445 | if let Ok(_) = l.send_with_fd(&sent_bytes[..], &[i32::max_value()][..]) { 446 | panic!("expected an error when sending a junk file descriptor"); 447 | } 448 | if let Ok(_) = l.send_with_fd(&sent_bytes[..], &[0xffi32][..]) { 449 | panic!("expected an error when sending a junk file descriptor"); 450 | } 451 | } 452 | 453 | #[test] 454 | fn sending_empty_fds_works() { 455 | let (l, r) = net::UnixStream::pair().expect("create UnixStream pair"); 456 | let sent_bytes = b"hello world!"; 457 | let sent_fds = []; 458 | 459 | assert_eq!( 460 | l.send_with_fd(&sent_bytes[..], &sent_fds[..]) 461 | .expect("send should be successful"), 462 | sent_bytes.len() 463 | ); 464 | 465 | let mut recv_bytes = [0; 128]; 466 | let mut recv_fds = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 467 | 468 | assert_eq!( 469 | r.recv_with_fd(&mut recv_bytes, &mut recv_fds) 470 | .expect("recv should be successful"), 471 | (sent_bytes.len(), sent_fds.len()) 472 | ); 473 | } 474 | } 475 | --------------------------------------------------------------------------------