cap-net-ext-3.4.1/.cargo_vcs_info.json0000644000000001510000000000100131630ustar { "git": { "sha1": "c461c0799f831df5d8ca2e121b7f541d9e8143af" }, "path_in_vcs": "cap-net-ext" }cap-net-ext-3.4.1/COPYRIGHT000064400000000000000000000015511046102023000132530ustar 00000000000000Short version for non-lawyers: `cap-net-ext` is triple-licensed under Apache 2.0 with the LLVM Exception, Apache 2.0, and MIT terms. Longer version: Copyrights in the `cap-net-ext` project are retained by their contributors. No copyright assignment is required to contribute to the `cap-net-ext` project. Some files include code derived from Rust's `libstd`; see the comments in the code for details. Except as otherwise noted (below and/or in individual files), `cap-net-ext` is licensed under: - the Apache License, Version 2.0, with the LLVM Exception or - the Apache License, Version 2.0 or , - or the MIT license or , at your option. cap-net-ext-3.4.1/Cargo.toml0000644000000023160000000000100111660ustar # 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 = "2021" name = "cap-net-ext" version = "3.4.1" authors = [ "Dan Gohman ", "Jakub Konka ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Extension traits for `TcpListener`, `Pool`, etc." readme = "README.md" keywords = ["filesystem"] categories = ["filesystem"] license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" repository = "https://github.com/bytecodealliance/cap-std" [lib] name = "cap_net_ext" path = "src/lib.rs" [dependencies.cap-primitives] version = "^3.4.1" [dependencies.cap-std] version = "^3.4.1" [dependencies.rustix] version = "0.38.0" features = ["net"] [dependencies.smallvec] version = "1.10" cap-net-ext-3.4.1/Cargo.toml.orig000064400000000000000000000011501046102023000146420ustar 00000000000000[package] name = "cap-net-ext" version = "3.4.1" description = "Extension traits for `TcpListener`, `Pool`, etc." authors = [ "Dan Gohman ", "Jakub Konka ", ] license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" keywords = ["filesystem"] categories = ["filesystem"] repository = "https://github.com/bytecodealliance/cap-std" edition = "2021" [dependencies] cap-std = { path = "../cap-std", version = "^3.4.1" } cap-primitives = { path = "../cap-primitives", version = "^3.4.1" } rustix = { version = "0.38.0", features = ["net"] } smallvec = "1.10" cap-net-ext-3.4.1/LICENSE-APACHE000064400000000000000000000251371046102023000137120ustar 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. cap-net-ext-3.4.1/LICENSE-Apache-2.0_WITH_LLVM-exception000064400000000000000000000277231046102023000201330ustar 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. --- LLVM Exceptions to the Apache 2.0 License ---- As an exception, if, as a result of your compiling your source code, portions of this Software are embedded into an Object form of such source code, you may redistribute such embedded portions in such Object form without complying with the conditions of Sections 4(a), 4(b) and 4(d) of the License. In addition, if you combine or link compiled forms of this Software with software that is licensed under the GPLv2 ("Combined Software") and if a court of competent jurisdiction determines that the patent provision (Section 3), the indemnity provision (Section 9) or other Section of the License conflicts with the conditions of the GPLv2, you may retroactively and prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software. cap-net-ext-3.4.1/LICENSE-MIT000064400000000000000000000017771046102023000134260ustar 00000000000000Permission 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. cap-net-ext-3.4.1/README.md000064400000000000000000000022171046102023000132370ustar 00000000000000

cap-net-ext

Extension traits for `TcpListener`, `UdpSocket`, `Pool`, etc.

Github Actions CI Status crates.io page docs.rs docs

The `cap-net-ext` crate provides extension traits adding extra features to types such as [`TcpListener`], [`UdpSocket`], and [`Pool`]. It provides split-out operations corresponding to `socket`, `bind`, `listen`, `accept`, and `connect`, and it exposes more options for enabling non-blocking mode. [`TcpListener`]: https://docs.rs/cap-std/latest/cap_std/net/struct.TcpListener.html [`UdpSocket`]: https://docs.rs/cap-std/latest/cap_std/net/struct.UdpSocket.html [`Pool`]: https://docs.rs/cap-std/latest/cap_std/net/struct.Pool.html cap-net-ext-3.4.1/src/lib.rs000064400000000000000000000663151046102023000136740ustar 00000000000000//! Extension traits for `TcpListener`, `UdpSocket`, and `Pool`. //! //! cap-std's [`TcpListener`], following the Rust standard library //! `TcpListener`, combines the `socket`, `bind`, `listen`, and `connect` //! operations of the POSIX socket API into a single `bind` or `connect` //! operation. In some use cases, it's desirable to perform the steps //! separately. //! //! This API adds extension traits to cap-std's `TcpListener`, `UdpSocket`, //! and `Pool` which support the following sequence for accepting incoming //! connections: //! //! - [`TcpListenerExt::new`] performs a `socket` and returns a new //! `TcpListener` that is not yet bound. //! - [`Pool::bind_existing_tcp_listener`] performs a `bind`, checking that //! the address is in the `Pool`. //! - [`TcpListenerExt::listen`] performs a `listen`. //! - Then, the regular [`TcpListener::accept`] may be used to accept new //! connections. Alternatively, [`TcpListener::accept_with`] may be used. //! //! and the following sequence for initiating outgoing connections: //! //! - [`TcpListenerExt::new`] performs a `socket` and returns a new //! `TcpListener` that is not yet connected. //! - [`Pool::connect_into_tcp_stream`] performs a `connect`, checking that //! the address is in the `Pool`. //! //! [`TcpListenerExt::new`] and [`TcpListener::accept_with`] additionally //! have [`Blocking`] arguments for requesting non-blocking operation. //! //! Similar API adaptations are available for UDP sockets as well. #![deny(missing_docs)] #![forbid(unsafe_code)] #![doc( html_logo_url = "https://raw.githubusercontent.com/bytecodealliance/cap-std/main/media/cap-std.svg" )] #![doc( html_favicon_url = "https://raw.githubusercontent.com/bytecodealliance/cap-std/main/media/cap-std.ico" )] use cap_primitives::net::no_socket_addrs; use cap_std::net::{IpAddr, Pool, SocketAddr, TcpListener, TcpStream, ToSocketAddrs, UdpSocket}; use rustix::fd::OwnedFd; use std::io; /// Address families supported by [`TcpListenerExt::new`] and /// [`UdpSocketExt::new`]. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum AddressFamily { /// IPv4 Ipv4, /// IPv6 Ipv6, } impl AddressFamily { /// Return the `AddressFamily` of an IP address. pub fn of_ip_addr(ip_addr: IpAddr) -> Self { match ip_addr { IpAddr::V4(_) => AddressFamily::Ipv4, IpAddr::V6(_) => AddressFamily::Ipv6, } } /// Return the `AddressFamily` of a socket address. pub fn of_socket_addr(socket_addr: SocketAddr) -> Self { match socket_addr { SocketAddr::V4(_) => AddressFamily::Ipv4, SocketAddr::V6(_) => AddressFamily::Ipv6, } } } impl From for rustix::net::AddressFamily { fn from(address_family: AddressFamily) -> Self { match address_family { AddressFamily::Ipv4 => rustix::net::AddressFamily::INET, AddressFamily::Ipv6 => rustix::net::AddressFamily::INET6, } } } /// Select blocking or non-blocking mode. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Blocking { /// Non-blocking No, /// Blocking Yes, } /// A trait for extending `TcpListener` types. pub trait TcpListenerExt: private::Sealed + Sized { /// Creates a new TCP socket with the given address family. /// /// The created socket is not bound or connected to any address and may be /// used for either listening or connecting. Use /// [`PoolExt::bind_existing_tcp_listener`] to bind it in preparation for /// listening, or [`PoolExt::connect_into_tcp_stream`] to initiate a /// connection. /// /// This is similar to [`Pool::bind_tcp_listener`] in that it creates a TCP /// socket, however it does not perform the `bind` or `listen` steps. And, /// it has a `blocking` argument to select blocking or non-blocking mode /// for the created socket. /// /// And it's similar to [`Pool::connect_tcp_stream`] in that it creates a /// TCP socket, however it does not perform the `connect` step. And, it has /// a `blocking` argument to select blocking or non-blocking mode for the /// created socket. fn new(address_family: AddressFamily, blocking: Blocking) -> io::Result; /// Enble listening in a `TcpListener`. /// /// A newly-created [`TcpListener`] created with [`TcpListenerExt::new`] /// and bound with [`PoolExt::bind_existing_tcp_listener`] is not yet /// listening; this function enables listening. After this, the listener /// may accept new connections with [`accept`] or [`accept_with`]. /// /// This is similar to [`Pool::bind_tcp_listener`] in that it performs the /// `listen` step, however it does not create the socket itself, or bind /// it. /// /// The `backlog` argument specifies an optional hint to the implementation /// about how many connections can be waiting before new connections are /// refused or ignored. /// /// [`accept`]: TcpListener::accept /// [`accept_with`]: TcpListenerExt::accept_with fn listen(&self, backlog: Option) -> io::Result<()>; /// Similar to [`accept`], but the resulting TCP connection are optionally /// set to non-blocking mode. /// /// The `accept` call itself may still block, if the socket is in blocking /// mode. /// /// [`accept`]: TcpListener::accept fn accept_with(&self, blocking: Blocking) -> io::Result<(TcpStream, SocketAddr)>; } impl TcpListenerExt for TcpListener { fn new(address_family: AddressFamily, blocking: Blocking) -> io::Result { socket(address_family, blocking, rustix::net::SocketType::STREAM).map(Self::from) } fn listen(&self, backlog: Option) -> io::Result<()> { let backlog = backlog.unwrap_or_else(default_backlog); Ok(rustix::net::listen(self, backlog)?) } fn accept_with(&self, blocking: Blocking) -> io::Result<(TcpStream, SocketAddr)> { let (stream, addr) = rustix::net::acceptfrom_with(self, socket_flags(blocking))?; set_socket_flags(&stream, blocking)?; // We know have a TCP socket, so we know we'll get an IP address. let addr = match addr { Some(rustix::net::SocketAddrAny::V4(v4)) => SocketAddr::V4(v4), Some(rustix::net::SocketAddrAny::V6(v6)) => SocketAddr::V6(v6), _ => unreachable!(), }; Ok((TcpStream::from(stream), addr)) } } /// A trait for extending `UdpSocket` types. pub trait UdpSocketExt: private::Sealed + Sized { /// Creates a new `UdpSocket` with the given address family. /// /// The created socket is initially not bound or connected to any address. /// Use [`PoolExt::bind_existing_udp_socket`] to bind it, or /// [`PoolExt::connect_existing_udp_socket`] to initiate a connection. /// /// This is similar to [`Pool::bind_udp_socket`] in that it creates a UDP /// socket, however it does not perform the `bind`. And, it has a /// `blocking` argument to select blocking or non-blocking mode for the /// created socket. /// /// And it's similar to [`Pool::connect_udp_socket`] in that it creates a /// UDP socket, however it does not perform the `connect` step. And, it has /// a `blocking` argument to select blocking or non-blocking mode for the /// created socket. fn new(address_family: AddressFamily, blocking: Blocking) -> io::Result; } impl UdpSocketExt for UdpSocket { fn new(address_family: AddressFamily, blocking: Blocking) -> io::Result { socket(address_family, blocking, rustix::net::SocketType::DGRAM).map(Self::from) } } /// A trait for extending `Pool` types. /// /// These functions have a `ToSocketAddrs` argument, which can return either /// IPv4 or IPv6 addresses, however they also require the socket to be created /// with a specific address family up front. Consequently, it's recommended to /// do address resolution outside of this API and just pass resolved /// `SocketAddr`s in. pub trait PoolExt: private::Sealed { /// Bind a [`TcpListener`] to the specified address. /// /// A newly-created `TcpListener` created with [`TcpListenerExt::new`] /// has not been bound yet; this function binds it. Before it can accept /// connections, it must be marked for listening with /// [`TcpListenerExt::listen`]. /// /// This is similar to [`Pool::bind_tcp_listener`] in that it binds a TCP /// socket, however it does not create the socket itself, or perform the /// `listen` step. /// /// This function ensures that the address to be bound is permitted by the /// pool, and performs the bind. To perform these steps separately, create /// a [`TcpBinder`] with [`Self::tcp_binder`] and use /// [`TcpBinder::bind_existing_tcp_listener`]. fn bind_existing_tcp_listener( &self, listener: &TcpListener, addrs: A, ) -> io::Result<()>; /// Bind a [`UdpSocket`] to the specified address. /// /// A newly-created `UdpSocket` created with [`UdpSocketExt::new`] has not /// been bound yet; this function binds it. /// /// This is similar to [`Pool::bind_udp_socket`] in that it binds a UDP /// socket, however it does not create the socket itself. /// /// This function ensures that the address to be bound is permitted by the /// pool, and performs the bind. To perform these steps separately, create /// a [`UdpBinder`] with [`Self::udp_binder`] and use /// [`UdpBinder::bind_existing_udp_socket`]. fn bind_existing_udp_socket( &self, socket: &UdpSocket, addrs: A, ) -> io::Result<()>; /// Initiate a TCP connection, converting a [`TcpListener`] to a /// [`TcpStream`]. /// /// This is simlar to [`Pool::connect_tcp_stream`] in that it performs a /// TCP connection, but instead of creating a new socket itself it takes a /// [`TcpListener`], such as one created with [`TcpListenerExt::new`]. /// /// Despite the name, this function uses the `TcpListener` type as a /// generic socket container. /// /// This function ensures that the address to connect to is permitted by /// the pool, and performs the connect. To perform these steps separately, /// create a [`TcpConnecter`] with [`Self::tcp_connecter`] and use /// [`TcpConnecter::connect_into_tcp_stream`]. fn connect_into_tcp_stream( &self, socket: TcpListener, addrs: A, ) -> io::Result; /// Initiate a TCP connection on a socket. /// /// This is simlar to [`Self::connect_into_tcp_stream`], however instead of /// converting a `TcpListener` to a `TcpStream`, it leaves fd in the /// existing `TcpListener`. /// /// This function ensures that the address to connect to is permitted by /// the pool, and performs the connect. To perform these steps separately, /// create a [`TcpConnecter`] with [`Self::tcp_connecter`] and use /// [`TcpConnecter::connect_existing_tcp_listener`]. fn connect_existing_tcp_listener( &self, socket: &TcpListener, addrs: A, ) -> io::Result<()>; /// Initiate a UDP connection. /// /// This is simlar to [`Pool::connect_udp_socket`] in that it performs a /// UDP connection, but instead of creating a new socket itself it takes a /// [`UdpSocket`], such as one created with [`UdpSocketExt::new`]. /// /// This function ensures that the address to connect to is permitted by /// the pool, and performs the connect. To perform these steps separately, /// create a [`UdpConnecter`] with [`Self::udp_connecter`] and use /// [`UdpConnecter::connect_existing_udp_socket`]. fn connect_existing_udp_socket( &self, socket: &UdpSocket, addrs: A, ) -> io::Result<()>; /// Create a TCP binder. /// /// This is an alternative to [`Self::bind_existing_tcp_listener`]. It /// checks that all the addresses in `addrs` are permitted for TCP binding /// up front, and then records them in a [`TcpBinder`] which can then be /// used to make repeated [`TcpBinder::bind_existing_tcp_listener`] calls. fn tcp_binder(&self, addrs: A) -> io::Result; /// Create a UDP binder. /// /// This is an alternative to [`Self::bind_existing_udp_socket`]. It checks /// that all the addresses in `addrs` are permitted for UDP binding up /// front, and then records them in a [`UdpBinder`] which can then be used /// to make repeated [`UdpBinder::bind_existing_udp_socket`] calls. fn udp_binder(&self, addrs: A) -> io::Result; /// Create a TCP connecter. /// /// This is an alternative to [`Self::connect_into_tcp_stream`] and /// [`Self::connect_existing_tcp_listener`]. It checks that all the /// addresses in `addrs` are permitted for TCP connecting up front, and /// then records them in a [`TcpConnecter`] which can then be used to make /// repeated [`TcpConnecter::connect_into_tcp_stream`] and /// [`TcpConnecter::connect_existing_tcp_listener`] calls. fn tcp_connecter(&self, addrs: A) -> io::Result; /// Create a UDP connecter. /// /// This is an alternative to [`Self::connect_existing_udp_socket`]. It /// checks that all the addresses in `addrs` are permitted for UDP /// connecting up front, and then records them in a [`UdpConnecter`] which /// can then be used to make repeated /// [`UdpConnecter::connect_existing_udp_socket`] calls. fn udp_connecter(&self, addrs: A) -> io::Result; } impl PoolExt for Pool { fn bind_existing_tcp_listener( &self, listener: &TcpListener, addrs: A, ) -> io::Result<()> { let addrs = addrs.to_socket_addrs()?; let mut last_err = None; for addr in addrs { self._pool().check_addr(&addr)?; set_reuseaddr(listener)?; match rustix::net::bind(listener, &addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err.into()), } } match last_err { Some(err) => Err(err), None => Err(no_socket_addrs()), } } fn bind_existing_udp_socket( &self, socket: &UdpSocket, addrs: A, ) -> io::Result<()> { let addrs = addrs.to_socket_addrs()?; let mut last_err = None; for addr in addrs { self._pool().check_addr(&addr)?; match rustix::net::bind(socket, &addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err), } } match last_err { Some(err) => Err(err.into()), None => Err(no_socket_addrs()), } } fn connect_into_tcp_stream( &self, socket: TcpListener, addrs: A, ) -> io::Result { self.connect_existing_tcp_listener(&socket, addrs)?; Ok(TcpStream::from(OwnedFd::from(socket))) } fn connect_existing_tcp_listener( &self, socket: &TcpListener, addrs: A, ) -> io::Result<()> { let addrs = addrs.to_socket_addrs()?; let mut last_err = None; for addr in addrs { self._pool().check_addr(&addr)?; match rustix::net::connect(socket, &addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err), } } match last_err { Some(err) => Err(err.into()), None => Err(no_socket_addrs()), } } fn connect_existing_udp_socket( &self, socket: &UdpSocket, addrs: A, ) -> io::Result<()> { let addrs = addrs.to_socket_addrs()?; let mut last_err = None; for addr in addrs { self._pool().check_addr(&addr)?; match rustix::net::connect(socket, &addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err), } } match last_err { Some(err) => Err(err.into()), None => Err(no_socket_addrs()), } } fn tcp_binder(&self, addrs: A) -> io::Result { Ok(TcpBinder(check_addrs(self._pool(), addrs)?)) } fn udp_binder(&self, addrs: A) -> io::Result { Ok(UdpBinder(check_addrs(self._pool(), addrs)?)) } fn tcp_connecter(&self, addrs: A) -> io::Result { Ok(TcpConnecter(check_addrs(self._pool(), addrs)?)) } fn udp_connecter(&self, addrs: A) -> io::Result { Ok(UdpConnecter(check_addrs(self._pool(), addrs)?)) } } /// Check all the addresses in `addrs` and return a new list of them. fn check_addrs( pool: &cap_primitives::net::Pool, addrs: A, ) -> io::Result> { let mut checked = smallvec::SmallVec::new(); for addr in addrs.to_socket_addrs()? { pool.check_addr(&addr)?; checked.push(addr); } Ok(checked) } /// A utility for binding TCP listeners. /// /// See [`PoolExt::tcp_binder`] for details. pub struct TcpBinder(smallvec::SmallVec<[SocketAddr; 1]>); impl TcpBinder { /// Bind a [`TcpListener`]. /// /// A newly-created `TcpListener` created with [`TcpListenerExt::new`] /// has not been bound yet; this function binds it. Before it can accept /// connections, it must be marked for listening with /// [`TcpListenerExt::listen`]. /// /// This is similar to [`Pool::bind_tcp_listener`] in that it binds a TCP /// socket, however it does not create the socket itself, or perform the /// `listen` step. /// /// This is similar to [`PoolExt::bind_existing_tcp_listener`] except that /// it uses a `TcpBinder` which contains addresses that have already been /// checked against a `Pool`. pub fn bind_existing_tcp_listener(&self, listener: &TcpListener) -> io::Result<()> { let mut last_err = None; for addr in &self.0 { set_reuseaddr(listener)?; match rustix::net::bind(listener, addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err.into()), } } match last_err { Some(err) => Err(err), None => Err(no_socket_addrs()), } } } /// A utility for binding UDP sockets. /// /// See [`PoolExt::udp_binder`] for details. pub struct UdpBinder(smallvec::SmallVec<[SocketAddr; 1]>); impl UdpBinder { /// Bind a [`UdpSocket`] to the specified address. /// /// A newly-created `UdpSocket` created with [`UdpSocketExt::new`] has not /// been bound yet; this function binds it. /// /// This is similar to [`Pool::bind_udp_socket`] in that it binds a UDP /// socket, however it does not create the socket itself. /// /// This is similar to [`PoolExt::bind_existing_udp_socket`] except that /// it uses a `UdpBinder` which contains addresses that have already been /// checked against a `Pool`. pub fn bind_existing_udp_socket(&self, socket: &UdpSocket) -> io::Result<()> { let mut last_err = None; for addr in &self.0 { match rustix::net::bind(socket, addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err.into()), } } match last_err { Some(err) => Err(err), None => Err(no_socket_addrs()), } } } /// A utility for making TCP connections. /// /// See [`PoolExt::tcp_connecter`] for details. pub struct TcpConnecter(smallvec::SmallVec<[SocketAddr; 1]>); impl TcpConnecter { /// Initiate a TCP connection, converting a [`TcpListener`] to a /// [`TcpStream`]. /// /// This is simlar to [`Pool::connect_tcp_stream`] in that it performs a /// TCP connection, but instead of creating a new socket itself it takes a /// [`TcpListener`], such as one created with [`TcpListenerExt::new`]. /// /// Despite the name, this function uses the `TcpListener` type as a /// generic socket container. /// /// This is similar to [`PoolExt::connect_into_tcp_stream`] except that /// it uses a `TcpConnecter` which contains addresses that have already /// been checked against a `Pool`. pub fn connect_into_tcp_stream(&self, socket: TcpListener) -> io::Result { self.connect_existing_tcp_listener(&socket)?; Ok(TcpStream::from(OwnedFd::from(socket))) } /// Initiate a TCP connection on a socket. /// /// This is simlar to [`Pool::connect_into_tcp_stream`], however instead of /// converting a `TcpListener` to a `TcpStream`, it leaves fd in the /// existing `TcpListener`. /// /// This is similar to [`PoolExt::connect_existing_tcp_listener`] except /// that it uses a `TcpConnecter` which contains addresses that have /// already been checked against a `Pool`. pub fn connect_existing_tcp_listener(&self, socket: &TcpListener) -> io::Result<()> { let mut last_err = None; for addr in &self.0 { match rustix::net::connect(socket, addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err), } } match last_err { Some(err) => Err(err.into()), None => Err(no_socket_addrs()), } } } /// A utility for making UDP connections. /// /// See [`PoolExt::udp_connecter`] for details. pub struct UdpConnecter(smallvec::SmallVec<[SocketAddr; 1]>); impl UdpConnecter { /// Initiate a UDP connection. /// /// This is simlar to [`Pool::connect_udp_socket`] in that it performs a /// UDP connection, but instead of creating a new socket itself it takes a /// [`UdpSocket`], such as one created with [`UdpSocketExt::new`]. /// /// This is similar to [`PoolExt::connect_existing_udp_socket`] except that /// it uses a `UdpConnecter` which contains addresses that have already /// been checked against a `Pool`. pub fn connect_existing_udp_socket(&self, socket: &UdpSocket) -> io::Result<()> { let mut last_err = None; for addr in &self.0 { match rustix::net::connect(socket, addr) { Ok(()) => return Ok(()), Err(err) => last_err = Some(err), } } match last_err { Some(err) => Err(err.into()), None => Err(no_socket_addrs()), } } } fn socket( address_family: AddressFamily, blocking: Blocking, socket_type: rustix::net::SocketType, ) -> io::Result { // The Rust standard library has code to call `WSAStartup`, which is needed // on Windows before we do any other Winsock2 calls, so just make a useless // API call once. #[cfg(windows)] { use std::sync::Once; static START: Once = Once::new(); START.call_once(|| { std::net::TcpStream::connect(std::net::SocketAddrV4::new( std::net::Ipv4Addr::UNSPECIFIED, 0, )) .unwrap_err(); }); } // Create the socket, using the desired flags if we can. let socket = rustix::net::socket_with( address_family.into(), socket_type, socket_flags(blocking), None, )?; // Set the desired flags if we couldn't set them at creation. set_socket_flags(&socket, blocking)?; Ok(socket) } /// Compute flags to pass to socket calls. fn socket_flags(blocking: Blocking) -> rustix::net::SocketFlags { let _ = blocking; #[allow(unused_mut)] let mut socket_flags = rustix::net::SocketFlags::empty(); // On platforms which do support `SOCK_CLOEXEC`, use it. #[cfg(not(any( windows, target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "haiku" )))] { socket_flags |= rustix::net::SocketFlags::CLOEXEC; } // On platforms which do support `SOCK_NONBLOCK`, use it. #[cfg(not(any( windows, target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "haiku" )))] match blocking { Blocking::Yes => (), Blocking::No => socket_flags |= rustix::net::SocketFlags::NONBLOCK, } socket_flags } /// On platforms which don't support `SOCK_CLOEXEC` or `SOCK_NONBLOCK, set them /// after creating the socket. fn set_socket_flags(fd: &OwnedFd, blocking: Blocking) -> io::Result<()> { let _ = fd; let _ = blocking; #[cfg(any( target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos" ))] { rustix::io::ioctl_fioclex(fd)?; } #[cfg(any( windows, target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos" ))] match blocking { Blocking::Yes => (), Blocking::No => rustix::io::ioctl_fionbio(fd, true)?, } #[cfg(target_os = "haiku")] { let mut flags = rustix::fs::fcntl_getfd(fd)?; flags |= rustix::fs::OFlags::CLOEXEC; match blocking { Blocking::Yes => (), Blocking::No => flags |= rustix::fs::OFlags::NONBLOCK, } rustix::fs::fcntl_setfd(fd, flags)?; } Ok(()) } /// On platforms where it's desirable, set the `SO_REUSEADDR` option. fn set_reuseaddr(listener: &TcpListener) -> io::Result<()> { let _ = listener; // The following logic is from // // at revision defa2456246a8272ceace9c1cdccdf2e4c36175e. // On platforms with Berkeley-derived sockets, this allows to quickly // rebind a socket, without needing to wait for the OS to clean up the // previous one. // // On Windows, this allows rebinding sockets which are actively in use, // which allows “socket hijacking”, so we explicitly don't set it here. // https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse #[cfg(not(windows))] rustix::net::sockopt::set_socket_reuseaddr(listener, true)?; Ok(()) } /// Determine the platform-specific default backlog value. fn default_backlog() -> i32 { // The following logic is from // // at revision defa2456246a8272ceace9c1cdccdf2e4c36175e. // The 3DS doesn't support a big connection backlog. Sometimes // it allows up to about 37, but other times it doesn't even // accept 32. There may be a global limitation causing this. #[cfg(target_os = "horizon")] let backlog = 20; // The default for all other platforms #[cfg(not(target_os = "horizon"))] let backlog = 128; backlog } /// Seal the public traits for [future-proofing]. /// /// [future-proofing]: https://rust-lang.github.io/api-guidelines/future-proofing.html mod private { pub trait Sealed {} impl Sealed for super::TcpListener {} impl Sealed for super::UdpSocket {} impl Sealed for super::Pool {} }