chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

1
vendor/socket2/.cargo-checksum.json vendored Normal file
View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"d9496ebc9e9da381892f28c23f9f4f7dc0be5e60cbba739c1740b651f9722495","Cargo.lock":"1586faadf8962804b1a78918b3e1ef35210946a7cd9535b0ac54b8d033c8d0db","Cargo.toml":"8b7a9083b19569241428e9d486fbf4f461b03ff004e4ec8cea9563a687877329","Cargo.toml.orig":"a27397c2dd5de8688bea65db80a730419067dc9e5c34f285ac7f791c5f94fdee","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"444031b783070ac056bd95abc4b2f4a72fd98ab11270268d8ba4c4ca53dade68","src/lib.rs":"90e5edbced9a2eba7d7c46c66fd1b7a462a2a6dbe0c38ad04ace081a9093f11a","src/sockaddr.rs":"1eb260befdb62a53a1dc940a4c0863b1774ce7fa0daf3045154e42f6f477ecbd","src/socket.rs":"1d60e8c2729bf1d19a0852b1ec39c8c6224355abeab9e361a0c694419367fe62","src/sockref.rs":"0dbb3de3b6fb457330c09b88ca2c3777a3d1b57a7a91946afac8f5f313e30aa4","src/sys/unix.rs":"dc648e4ebbaabe77f7cbcfa85a22d79fe599b47c4a06e9b2fcc87ad164bb9be7","src/sys/windows.rs":"6d9d05a39b79ec53642bc7096f5ebfe32ae7c1562c3621d2400d08cfa8e91c3d"},"package":"3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"}

6
vendor/socket2/.cargo_vcs_info.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "642df44ae1eded922247300a83f8d60e159d9c9d"
},
"path_in_vcs": ""
}

97
vendor/socket2/Cargo.lock generated vendored Normal file
View File

@@ -0,0 +1,97 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "libc"
version = "0.2.172"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
[[package]]
name = "socket2"
version = "0.6.3"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.53.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
[[package]]
name = "windows_i686_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
[[package]]
name = "windows_i686_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"

104
vendor/socket2/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,104 @@
# 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"
rust-version = "1.70"
name = "socket2"
version = "0.6.3"
authors = [
"Alex Crichton <alex@alexcrichton.com>",
"Thomas de Zeeuw <thomasdezeeuw@gmail.com>",
]
build = false
include = [
"Cargo.toml",
"LICENSE-APACHE",
"LICENSE-MIT",
"README.md",
"src/**/*.rs",
]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
Utilities for handling networking sockets with a maximal amount of configuration
possible intended.
"""
homepage = "https://github.com/rust-lang/socket2"
documentation = "https://docs.rs/socket2"
readme = "README.md"
keywords = [
"io",
"socket",
"network",
]
categories = [
"api-bindings",
"network-programming",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-lang/socket2"
[package.metadata.docs.rs]
all-features = true
default-target = "x86_64-unknown-linux-gnu"
targets = [
"aarch64-apple-ios",
"aarch64-linux-android",
"armv7-linux-androideabi",
"i686-linux-android",
"x86_64-apple-darwin",
"x86_64-pc-solaris",
"x86_64-pc-windows-msvc",
"x86_64-unknown-freebsd",
"x86_64-unknown-fuchsia",
"x86_64-unknown-illumos",
"x86_64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"x86_64-unknown-netbsd",
"x86_64-unknown-redox",
]
[package.metadata.playground]
features = ["all"]
[package.metadata.cargo_check_external_types]
allowed_external_types = [
"libc::socklen_t",
"libc::*::socklen_t",
"libc::sa_family_t",
"libc::*::sa_family_t",
"windows_sys::Win32::Networking::WinSock::socklen_t",
"windows_sys::Win32::Networking::WinSock::ADDRESS_FAMILY",
]
[features]
all = []
[lib]
name = "socket2"
path = "src/lib.rs"
[target.'cfg(any(unix, target_os = "wasi"))'.dependencies.libc]
version = "0.2.172"
[target."cfg(windows)".dependencies.windows-sys]
version = ">=0.60, <0.62"
features = [
"Win32_Foundation",
"Win32_Networking_WinSock",
"Win32_System_IO",
"Win32_System_Threading",
"Win32_System_WindowsProgramming",
]

201
vendor/socket2/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,201 @@
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.

25
vendor/socket2/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,25 @@
Copyright (c) 2014 Alex Crichton
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

85
vendor/socket2/README.md vendored Normal file
View File

@@ -0,0 +1,85 @@
# Socket2
Socket2 is a crate that provides utilities for creating and using sockets.
The goal of this crate is to create and use a socket using advanced
configuration options (those that are not available in the types in the standard
library) without using any unsafe code.
This crate provides as direct as possible access to the system's functionality
for sockets, this means little effort to provide cross-platform utilities. It is
up to the user to know how to use sockets when using this crate. *If you don't
know how to create a socket using libc/system calls then this crate is not for
you*. Most, if not all, functions directly relate to the equivalent system call
with no error handling applied, so no handling errors such as `EINTR`. As a
result using this crate can be a little wordy, but it should give you maximal
flexibility over configuration of sockets.
See the [API documentation] for more.
[API documentation]: https://docs.rs/socket2
# Branches
Currently Socket2 supports the following versions:
* v0.6 developed in the master branch
* v0.5 developed in the [v0.5.x branch]
* v0.4 developed in the [v0.4.x branch]
[v0.5.x branch]: https://github.com/rust-lang/socket2/tree/v0.5.x
[v0.4.x branch]: https://github.com/rust-lang/socket2/tree/v0.4.x
# OS support
Socket2 attempts to support the same OS/architectures as Rust does, see
https://doc.rust-lang.org/nightly/rustc/platform-support.html. However this is
not always possible, below is current list of support OSs.
*If your favorite OS is not on the list consider contributing it!*
### Tier 1
These OSs are tested with each commit in the CI and must always pass the tests.
All functions/types/etc., excluding ones behind the `all` feature, must work on
these OSs.
* Linux
* macOS
* Windows
### Tier 2
These OSs are currently build in the CI, but not tested. Not all
functions/types/etc. may work on these OSs, even ones **not** behind the `all`
feature flag.
* Android
* FreeBSD
* Fuchsia
* iOS
* illumos
* NetBSD
* Redox
* Solaris
* OpenHarmony
# Minimum Supported Rust Version (MSRV)
Socket2 uses 1.70.0 as MSRV.
# License
This project is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
https://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
https://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this project by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.

717
vendor/socket2/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,717 @@
// Copyright 2015 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(clippy::needless_lifetimes)]
//! Utilities for creating and using sockets.
//!
//! The goal of this crate is to create and use a socket using advanced
//! configuration options (those that are not available in the types in the
//! standard library) without using any unsafe code.
//!
//! This crate provides as direct as possible access to the system's
//! functionality for sockets, this means little effort to provide
//! cross-platform utilities. It is up to the user to know how to use sockets
//! when using this crate. *If you don't know how to create a socket using
//! libc/system calls then this crate is not for you*. Most, if not all,
//! functions directly relate to the equivalent system call with no error
//! handling applied, so no handling errors such as [`EINTR`]. As a result using
//! this crate can be a little wordy, but it should give you maximal flexibility
//! over configuration of sockets.
//!
//! [`EINTR`]: std::io::ErrorKind::Interrupted
//!
//! # Examples
//!
//! ```no_run
//! # fn main() -> std::io::Result<()> {
//! use std::net::{SocketAddr, TcpListener};
//! use socket2::{Socket, Domain, Type};
//!
//! // Create a TCP listener bound to two addresses.
//! let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
//!
//! socket.set_only_v6(false)?;
//! let address: SocketAddr = "[::1]:12345".parse().unwrap();
//! socket.bind(&address.into())?;
//! socket.listen(128)?;
//!
//! let listener: TcpListener = socket.into();
//! // ...
//! # drop(listener);
//! # Ok(()) }
//! ```
//!
//! ## Features
//!
//! This crate has a single feature `all`, which enables all functions even ones
//! that are not available on all OSs.
#![deny(missing_docs, missing_debug_implementations, rust_2018_idioms)]
// Automatically generate required OS/features for docs.rs.
#![cfg_attr(docsrs, feature(doc_cfg))]
// Disallow warnings when running tests.
#![cfg_attr(test, deny(warnings))]
// Disallow warnings in examples.
#![doc(test(attr(deny(warnings))))]
use std::fmt;
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
use std::io::IoSlice;
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
use std::marker::PhantomData;
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
use std::mem;
use std::mem::MaybeUninit;
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::time::Duration;
/// Macro to implement `fmt::Debug` for a type, printing the constant names
/// rather than a number.
///
/// Note this is used in the `sys` module and thus must be defined before
/// defining the modules.
macro_rules! impl_debug {
(
// Type name for which to implement `fmt::Debug`.
$type: path,
$(
$(#[$target: meta])*
// The flag(s) to check.
// Need to specific the libc crate because Windows doesn't use
// `libc` but `windows_sys`.
$libc: ident :: $flag: ident
),+ $(,)*
) => {
impl std::fmt::Debug for $type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let string = match self.0 {
$(
$(#[$target])*
$libc :: $flag => stringify!($flag),
)+
n => return write!(f, "{n}"),
};
f.write_str(string)
}
}
};
}
/// Macro to convert from one network type to another.
macro_rules! from {
($from: ty, $for: ty) => {
impl From<$from> for $for {
fn from(socket: $from) -> $for {
#[cfg(any(unix, all(target_os = "wasi", not(target_env = "p1"))))]
unsafe {
<$for>::from_raw_fd(socket.into_raw_fd())
}
#[cfg(windows)]
unsafe {
<$for>::from_raw_socket(socket.into_raw_socket())
}
}
}
};
}
/// Link to online documentation for (almost) all supported OSs.
#[rustfmt::skip]
macro_rules! man_links {
// Links to all OSs.
($syscall: tt ( $section: tt ) ) => {
concat!(
man_links!(__ intro),
man_links!(__ unix $syscall($section)),
man_links!(__ windows $syscall($section)),
)
};
// Links to Unix-like OSs.
(unix: $syscall: tt ( $section: tt ) ) => {
concat!(
man_links!(__ intro),
man_links!(__ unix $syscall($section)),
)
};
// Links to Windows only.
(windows: $syscall: tt ( $section: tt ) ) => {
concat!(
man_links!(__ intro),
man_links!(__ windows $syscall($section)),
)
};
// Internals.
(__ intro) => {
"\n\nAdditional documentation can be found in manual of the OS:\n\n"
};
// List for Unix-like OSs.
(__ unix $syscall: tt ( $section: tt ) ) => {
concat!(
" * DragonFly BSD: <https://man.dragonflybsd.org/?command=", stringify!($syscall), "&section=", stringify!($section), ">\n",
" * FreeBSD: <https://www.freebsd.org/cgi/man.cgi?query=", stringify!($syscall), "&sektion=", stringify!($section), ">\n",
" * Linux: <https://man7.org/linux/man-pages/man", stringify!($section), "/", stringify!($syscall), ".", stringify!($section), ".html>\n",
" * macOS: <https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/", stringify!($syscall), ".", stringify!($section), ".html> (archived, actually for iOS)\n",
" * NetBSD: <https://man.netbsd.org/", stringify!($syscall), ".", stringify!($section), ">\n",
" * OpenBSD: <https://man.openbsd.org/", stringify!($syscall), ".", stringify!($section), ">\n",
" * iOS: <https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/", stringify!($syscall), ".", stringify!($section), ".html> (archived)\n",
" * illumos: <https://illumos.org/man/3SOCKET/", stringify!($syscall), ">\n",
)
};
// List for Window (so just Windows).
(__ windows $syscall: tt ( $section: tt ) ) => {
concat!(
" * Windows: <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-", stringify!($syscall), ">\n",
)
};
}
mod sockaddr;
mod socket;
mod sockref;
#[cfg_attr(
any(unix, all(target_os = "wasi", not(target_env = "p1"))),
path = "sys/unix.rs"
)]
#[cfg_attr(windows, path = "sys/windows.rs")]
mod sys;
#[cfg(not(any(windows, unix, all(target_os = "wasi", not(target_env = "p1")))))]
compile_error!("Socket2 doesn't support the compile target");
use sys::c_int;
pub use sockaddr::{sa_family_t, socklen_t, SockAddr, SockAddrStorage};
#[cfg(not(any(
target_os = "haiku",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
target_os = "wasi",
)))]
pub use socket::InterfaceIndexOrAddress;
pub use socket::Socket;
pub use sockref::SockRef;
#[cfg(all(feature = "all", target_os = "linux"))]
pub use sys::CcidEndpoints;
#[cfg(all(feature = "all", any(target_os = "linux", target_os = "android")))]
pub use sys::SockFilter;
/// Specification of the communication domain for a socket.
///
/// This is a newtype wrapper around an integer which provides a nicer API in
/// addition to an injection point for documentation. Convenience constants such
/// as [`Domain::IPV4`], [`Domain::IPV6`], etc, are provided to avoid reaching
/// into libc for various constants.
///
/// This type is freely interconvertible with C's `int` type, however, if a raw
/// value needs to be provided.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Domain(c_int);
impl Domain {
/// Domain for IPv4 communication, corresponding to `AF_INET`.
pub const IPV4: Domain = Domain(sys::AF_INET);
/// Domain for IPv6 communication, corresponding to `AF_INET6`.
pub const IPV6: Domain = Domain(sys::AF_INET6);
/// Domain for Unix socket communication, corresponding to `AF_UNIX`.
#[cfg(not(target_os = "wasi"))]
pub const UNIX: Domain = Domain(sys::AF_UNIX);
/// Returns the correct domain for `address`.
pub const fn for_address(address: SocketAddr) -> Domain {
match address {
SocketAddr::V4(_) => Domain::IPV4,
SocketAddr::V6(_) => Domain::IPV6,
}
}
}
impl From<c_int> for Domain {
fn from(d: c_int) -> Domain {
Domain(d)
}
}
impl From<Domain> for c_int {
fn from(d: Domain) -> c_int {
d.0
}
}
/// Specification of communication semantics on a socket.
///
/// This is a newtype wrapper around an integer which provides a nicer API in
/// addition to an injection point for documentation. Convenience constants such
/// as [`Type::STREAM`], [`Type::DGRAM`], etc, are provided to avoid reaching
/// into libc for various constants.
///
/// This type is freely interconvertible with C's `int` type, however, if a raw
/// value needs to be provided.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Type(c_int);
impl Type {
/// Type corresponding to `SOCK_STREAM`.
///
/// Used for protocols such as TCP.
pub const STREAM: Type = Type(sys::SOCK_STREAM);
/// Type corresponding to `SOCK_DGRAM`.
///
/// Used for protocols such as UDP.
pub const DGRAM: Type = Type(sys::SOCK_DGRAM);
/// Type corresponding to `SOCK_DCCP`.
///
/// Used for the DCCP protocol.
#[cfg(all(feature = "all", target_os = "linux"))]
pub const DCCP: Type = Type(sys::SOCK_DCCP);
/// Type corresponding to `SOCK_SEQPACKET`.
#[cfg(all(feature = "all", not(any(target_os = "espidf", target_os = "wasi"))))]
pub const SEQPACKET: Type = Type(sys::SOCK_SEQPACKET);
/// Type corresponding to `SOCK_RAW`.
#[cfg(all(
feature = "all",
not(any(target_os = "redox", target_os = "espidf", target_os = "wasi"))
))]
pub const RAW: Type = Type(sys::SOCK_RAW);
}
impl From<c_int> for Type {
fn from(t: c_int) -> Type {
Type(t)
}
}
impl From<Type> for c_int {
fn from(t: Type) -> c_int {
t.0
}
}
/// Protocol specification used for creating sockets via `Socket::new`.
///
/// This is a newtype wrapper around an integer which provides a nicer API in
/// addition to an injection point for documentation.
///
/// This type is freely interconvertible with C's `int` type, however, if a raw
/// value needs to be provided.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Protocol(c_int);
impl Protocol {
/// Protocol corresponding to `ICMPv4`.
#[cfg(not(target_os = "wasi"))]
pub const ICMPV4: Protocol = Protocol(sys::IPPROTO_ICMP);
/// Protocol corresponding to `ICMPv6`.
#[cfg(not(target_os = "wasi"))]
pub const ICMPV6: Protocol = Protocol(sys::IPPROTO_ICMPV6);
/// Protocol corresponding to `TCP`.
pub const TCP: Protocol = Protocol(sys::IPPROTO_TCP);
/// Protocol corresponding to `UDP`.
pub const UDP: Protocol = Protocol(sys::IPPROTO_UDP);
#[cfg(target_os = "linux")]
/// Protocol corresponding to `MPTCP`.
pub const MPTCP: Protocol = Protocol(sys::IPPROTO_MPTCP);
/// Protocol corresponding to `DCCP`.
#[cfg(all(feature = "all", target_os = "linux"))]
pub const DCCP: Protocol = Protocol(sys::IPPROTO_DCCP);
/// Protocol corresponding to `SCTP`.
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))]
pub const SCTP: Protocol = Protocol(sys::IPPROTO_SCTP);
/// Protocol corresponding to `UDPLITE`.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
)
))]
pub const UDPLITE: Protocol = Protocol(sys::IPPROTO_UDPLITE);
/// Protocol corresponding to `DIVERT`.
#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))]
pub const DIVERT: Protocol = Protocol(sys::IPPROTO_DIVERT);
}
impl From<c_int> for Protocol {
fn from(p: c_int) -> Protocol {
Protocol(p)
}
}
impl From<Protocol> for c_int {
fn from(p: Protocol) -> c_int {
p.0
}
}
/// Flags for incoming messages.
///
/// Flags provide additional information about incoming messages.
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct RecvFlags(c_int);
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
impl RecvFlags {
/// Check if the message contains a truncated datagram.
///
/// This flag is only used for datagram-based sockets,
/// not for stream sockets.
///
/// On Unix this corresponds to the `MSG_TRUNC` flag.
/// On Windows this corresponds to the `WSAEMSGSIZE` error code.
#[cfg(not(target_os = "espidf"))]
pub const fn is_truncated(self) -> bool {
self.0 & sys::MSG_TRUNC != 0
}
}
/// A version of [`IoSliceMut`] that allows the buffer to be uninitialised.
///
/// [`IoSliceMut`]: std::io::IoSliceMut
#[repr(transparent)]
pub struct MaybeUninitSlice<'a>(sys::MaybeUninitSlice<'a>);
impl<'a> fmt::Debug for MaybeUninitSlice<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.0.as_slice(), fmt)
}
}
impl<'a> MaybeUninitSlice<'a> {
/// Creates a new `MaybeUninitSlice` wrapping a byte slice.
///
/// # Panics
///
/// Panics on Windows if the slice is larger than 4GB.
pub fn new(buf: &'a mut [MaybeUninit<u8>]) -> MaybeUninitSlice<'a> {
MaybeUninitSlice(sys::MaybeUninitSlice::new(buf))
}
}
impl<'a> Deref for MaybeUninitSlice<'a> {
type Target = [MaybeUninit<u8>];
fn deref(&self) -> &[MaybeUninit<u8>] {
self.0.as_slice()
}
}
impl<'a> DerefMut for MaybeUninitSlice<'a> {
fn deref_mut(&mut self) -> &mut [MaybeUninit<u8>] {
self.0.as_mut_slice()
}
}
/// Configures a socket's TCP keepalive parameters.
///
/// See [`Socket::set_tcp_keepalive`].
#[derive(Debug, Clone)]
pub struct TcpKeepalive {
#[cfg_attr(
any(target_os = "openbsd", target_os = "haiku", target_os = "vita"),
allow(dead_code)
)]
time: Option<Duration>,
#[cfg(not(any(
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
target_os = "haiku",
)))]
interval: Option<Duration>,
#[cfg(not(any(
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
target_os = "haiku",
)))]
retries: Option<u32>,
}
impl TcpKeepalive {
/// Returns a new, empty set of TCP keepalive parameters.
#[allow(clippy::new_without_default)]
pub const fn new() -> TcpKeepalive {
TcpKeepalive {
time: None,
#[cfg(not(any(
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
target_os = "haiku",
)))]
interval: None,
#[cfg(not(any(
target_os = "openbsd",
target_os = "redox",
target_os = "solaris",
target_os = "nto",
target_os = "espidf",
target_os = "vita",
target_os = "haiku",
)))]
retries: None,
}
}
/// Set the amount of time after which TCP keepalive probes will be sent on
/// idle connections.
///
/// This will set `TCP_KEEPALIVE` on macOS and iOS, and
/// `TCP_KEEPIDLE` on all other Unix operating systems, except
/// OpenBSD and Haiku which don't support any way to set this
/// option. On Windows, this sets the value of the `tcp_keepalive`
/// struct's `keepalivetime` field.
///
/// Some platforms specify this value in seconds, so sub-second
/// specifications may be omitted.
pub const fn with_time(self, time: Duration) -> Self {
Self {
time: Some(time),
..self
}
}
/// Set the value of the `TCP_KEEPINTVL` option. On Windows, this sets the
/// value of the `tcp_keepalive` struct's `keepaliveinterval` field.
///
/// Sets the time interval between TCP keepalive probes.
///
/// Some platforms specify this value in seconds, so sub-second
/// specifications may be omitted.
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "ios",
target_os = "visionos",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "tvos",
target_os = "watchos",
target_os = "windows",
target_os = "cygwin",
all(target_os = "wasi", not(target_env = "p1")),
))]
pub const fn with_interval(self, interval: Duration) -> Self {
Self {
interval: Some(interval),
..self
}
}
/// Set the value of the `TCP_KEEPCNT` option.
///
/// Set the maximum number of TCP keepalive probes that will be sent before
/// dropping a connection, if TCP keepalive is enabled on this socket.
#[cfg(all(
feature = "all",
any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "ios",
target_os = "visionos",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "tvos",
target_os = "watchos",
target_os = "cygwin",
target_os = "windows",
all(target_os = "wasi", not(target_env = "p1")),
)
))]
pub const fn with_retries(self, retries: u32) -> Self {
Self {
retries: Some(retries),
..self
}
}
}
/// Configuration of a `sendmsg(2)` system call.
///
/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdrMut`]
/// for the variant used by `recvmsg(2)`.
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[repr(transparent)]
pub struct MsgHdr<'addr, 'bufs, 'control> {
inner: sys::msghdr,
#[allow(clippy::type_complexity)]
_lifetimes: PhantomData<(&'addr SockAddr, &'bufs IoSlice<'bufs>, &'control [u8])>,
}
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> {
/// Create a new `MsgHdr` with all empty/zero fields.
#[allow(clippy::new_without_default)]
pub fn new() -> MsgHdr<'addr, 'bufs, 'control> {
// SAFETY: all zero is valid for `msghdr` and `WSAMSG`.
MsgHdr {
inner: unsafe { mem::zeroed() },
_lifetimes: PhantomData,
}
}
/// Set the address (name) of the message.
///
/// Corresponds to setting `msg_name` and `msg_namelen` on Unix and `name`
/// and `namelen` on Windows.
pub fn with_addr(mut self, addr: &'addr SockAddr) -> Self {
sys::set_msghdr_name(&mut self.inner, addr);
self
}
/// Set the buffer(s) of the message.
///
/// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers`
/// and `dwBufferCount` on Windows.
pub fn with_buffers(mut self, bufs: &'bufs [IoSlice<'_>]) -> Self {
let ptr = bufs.as_ptr() as *mut _;
sys::set_msghdr_iov(&mut self.inner, ptr, bufs.len());
self
}
/// Set the control buffer of the message.
///
/// Corresponds to setting `msg_control` and `msg_controllen` on Unix and
/// `Control` on Windows.
pub fn with_control(mut self, buf: &'control [u8]) -> Self {
let ptr = buf.as_ptr() as *mut _;
sys::set_msghdr_control(&mut self.inner, ptr, buf.len());
self
}
/// Set the flags of the message.
///
/// Corresponds to setting `msg_flags` on Unix and `dwFlags` on Windows.
pub fn with_flags(mut self, flags: sys::c_int) -> Self {
sys::set_msghdr_flags(&mut self.inner, flags);
self
}
}
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
"MsgHdr".fmt(fmt)
}
}
/// Configuration of a `recvmsg(2)` system call.
///
/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdr`] for
/// the variant used by `sendmsg(2)`.
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[repr(transparent)]
pub struct MsgHdrMut<'addr, 'bufs, 'control> {
inner: sys::msghdr,
#[allow(clippy::type_complexity)]
_lifetimes: PhantomData<(
&'addr mut SockAddr,
&'bufs mut MaybeUninitSlice<'bufs>,
&'control mut [u8],
)>,
}
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
impl<'addr, 'bufs, 'control> MsgHdrMut<'addr, 'bufs, 'control> {
/// Create a new `MsgHdrMut` with all empty/zero fields.
#[allow(clippy::new_without_default)]
pub fn new() -> MsgHdrMut<'addr, 'bufs, 'control> {
// SAFETY: all zero is valid for `msghdr` and `WSAMSG`.
MsgHdrMut {
inner: unsafe { mem::zeroed() },
_lifetimes: PhantomData,
}
}
/// Set the mutable address (name) of the message.
///
/// Corresponds to setting `msg_name` and `msg_namelen` on Unix and `name`
/// and `namelen` on Windows.
#[allow(clippy::needless_pass_by_ref_mut)]
pub fn with_addr(mut self, addr: &'addr mut SockAddr) -> Self {
sys::set_msghdr_name(&mut self.inner, addr);
self
}
/// Set the mutable buffer(s) of the message.
///
/// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers`
/// and `dwBufferCount` on Windows.
pub fn with_buffers(mut self, bufs: &'bufs mut [MaybeUninitSlice<'_>]) -> Self {
sys::set_msghdr_iov(&mut self.inner, bufs.as_mut_ptr().cast(), bufs.len());
self
}
/// Set the mutable control buffer of the message.
///
/// Corresponds to setting `msg_control` and `msg_controllen` on Unix and
/// `Control` on Windows.
pub fn with_control(mut self, buf: &'control mut [MaybeUninit<u8>]) -> Self {
sys::set_msghdr_control(&mut self.inner, buf.as_mut_ptr().cast(), buf.len());
self
}
/// Returns the flags of the message.
pub fn flags(&self) -> RecvFlags {
sys::msghdr_flags(&self.inner)
}
/// Gets the length of the control buffer.
///
/// Can be used to determine how much, if any, of the control buffer was filled by `recvmsg`.
///
/// Corresponds to `msg_controllen` on Unix and `Control.len` on Windows.
pub fn control_len(&self) -> usize {
sys::msghdr_control_len(&self.inner)
}
}
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
impl<'name, 'bufs, 'control> fmt::Debug for MsgHdrMut<'name, 'bufs, 'control> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
"MsgHdrMut".fmt(fmt)
}
}

653
vendor/socket2/src/sockaddr.rs vendored Normal file
View File

@@ -0,0 +1,653 @@
use std::hash::Hash;
use std::mem::{self, size_of};
use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
#[cfg(not(target_os = "wasi"))]
use std::path::Path;
use std::{fmt, io, ptr};
#[cfg(windows)]
use windows_sys::Win32::Networking::WinSock::SOCKADDR_IN6_0;
#[cfg(not(target_os = "wasi"))]
use crate::sys::AF_UNIX;
use crate::sys::{c_int, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_INET, AF_INET6};
use crate::Domain;
/// The integer type used with `getsockname` on this platform.
#[allow(non_camel_case_types)]
pub type socklen_t = crate::sys::socklen_t;
/// The integer type for the `ss_family` field on this platform.
#[allow(non_camel_case_types)]
pub type sa_family_t = crate::sys::sa_family_t;
/// Rust version of the [`sockaddr_storage`] type.
///
/// This type is intended to be used with with direct calls to the `getsockname` syscall. See the
/// documentation of [`SockAddr::new`] for examples.
///
/// This crate defines its own `sockaddr_storage` type to avoid semver concerns with upgrading
/// `windows-sys`.
#[repr(transparent)]
pub struct SockAddrStorage {
storage: sockaddr_storage,
}
impl SockAddrStorage {
/// Construct a new storage containing all zeros.
#[inline]
pub fn zeroed() -> Self {
// SAFETY: All zeros is valid for this type.
unsafe { mem::zeroed() }
}
/// Returns the size of this storage.
#[inline]
pub fn size_of(&self) -> socklen_t {
size_of::<Self>() as socklen_t
}
/// View this type as another type.
///
/// # Safety
///
/// The type `T` must be one of the `sockaddr_*` types defined by this platform.
///
/// # Examples
/// ```
/// # #[allow(dead_code)]
/// # #[cfg(unix)] mod unix_example {
/// # use core::mem::size_of;
/// use libc::sockaddr_storage;
/// use socket2::{SockAddr, SockAddrStorage, socklen_t};
///
/// fn from_sockaddr_storage(recv_address: &sockaddr_storage) -> SockAddr {
/// let mut storage = SockAddrStorage::zeroed();
/// let libc_address = unsafe { storage.view_as::<sockaddr_storage>() };
/// *libc_address = *recv_address;
/// unsafe { SockAddr::new(storage, size_of::<sockaddr_storage>() as socklen_t) }
/// }
/// # }
/// ```
#[inline]
pub unsafe fn view_as<T>(&mut self) -> &mut T {
assert!(size_of::<T>() <= size_of::<Self>());
// SAFETY: This type is repr(transparent) over `sockaddr_storage` and `T` is one of the
// `sockaddr_*` types defined by this platform.
&mut *(self as *mut Self as *mut T)
}
}
impl std::fmt::Debug for SockAddrStorage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("sockaddr_storage")
.field("ss_family", &self.storage.ss_family)
.finish_non_exhaustive()
}
}
/// The address of a socket.
///
/// `SockAddr`s may be constructed directly to and from the standard library
/// [`SocketAddr`], [`SocketAddrV4`], and [`SocketAddrV6`] types.
#[derive(Clone)]
pub struct SockAddr {
storage: sockaddr_storage,
len: socklen_t,
}
#[allow(clippy::len_without_is_empty)]
impl SockAddr {
/// Create a `SockAddr` from the underlying storage and its length.
///
/// # Safety
///
/// Caller must ensure that the address family and length match the type of
/// storage address. For example if `storage.ss_family` is set to `AF_INET`
/// the `storage` must be initialised as `sockaddr_in`, setting the content
/// and length appropriately.
///
/// # Examples
///
/// ```
/// # fn main() -> std::io::Result<()> {
/// # #[cfg(unix)] {
/// use std::io;
/// use std::os::fd::AsRawFd;
///
/// use socket2::{SockAddr, SockAddrStorage, Socket, Domain, Type};
///
/// let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
///
/// // Initialise a `SocketAddr` by calling `getsockname(2)`.
/// let mut addr_storage = SockAddrStorage::zeroed();
/// let mut len = addr_storage.size_of();
///
/// // The `getsockname(2)` system call will initialize `storage` for
/// // us, setting `len` to the correct length.
/// let res = unsafe {
/// libc::getsockname(
/// socket.as_raw_fd(),
/// addr_storage.view_as(),
/// &mut len,
/// )
/// };
/// if res == -1 {
/// return Err(io::Error::last_os_error());
/// }
///
/// let address = unsafe { SockAddr::new(addr_storage, len) };
/// # drop(address);
/// # }
/// # Ok(())
/// # }
/// ```
pub const unsafe fn new(storage: SockAddrStorage, len: socklen_t) -> SockAddr {
SockAddr {
storage: storage.storage,
len: len as socklen_t,
}
}
/// Initialise a `SockAddr` by calling the function `init`.
///
/// The type of the address storage and length passed to the function `init`
/// is OS/architecture specific.
///
/// The address is zeroed before `init` is called and is thus valid to
/// dereference and read from. The length initialised to the maximum length
/// of the storage.
///
/// # Safety
///
/// Caller must ensure that the address family and length match the type of
/// storage address. For example if `storage.ss_family` is set to `AF_INET`
/// the `storage` must be initialised as `sockaddr_in`, setting the content
/// and length appropriately.
///
/// # Examples
///
/// ```
/// # fn main() -> std::io::Result<()> {
/// # #[cfg(unix)] {
/// use std::io;
/// use std::os::fd::AsRawFd;
///
/// use socket2::{SockAddr, Socket, Domain, Type};
///
/// let socket = Socket::new(Domain::IPV4, Type::STREAM, None)?;
///
/// // Initialise a `SocketAddr` by calling `getsockname(2)`.
/// let (_, address) = unsafe {
/// SockAddr::try_init(|addr_storage, len| {
/// // The `getsockname(2)` system call will initialize `storage` for
/// // us, setting `len` to the correct length.
/// if libc::getsockname(socket.as_raw_fd(), addr_storage.cast(), len) == -1 {
/// Err(io::Error::last_os_error())
/// } else {
/// Ok(())
/// }
/// })
/// }?;
/// # drop(address);
/// # }
/// # Ok(())
/// # }
/// ```
pub unsafe fn try_init<F, T>(init: F) -> io::Result<(T, SockAddr)>
where
F: FnOnce(*mut SockAddrStorage, *mut socklen_t) -> io::Result<T>,
{
const STORAGE_SIZE: socklen_t = size_of::<sockaddr_storage>() as socklen_t;
// NOTE: `SockAddr::unix` depends on the storage being zeroed before
// calling `init`.
// NOTE: calling `recvfrom` with an empty buffer also depends on the
// storage being zeroed before calling `init` as the OS might not
// initialise it.
let mut storage = SockAddrStorage::zeroed();
let mut len = STORAGE_SIZE;
init(&mut storage, &mut len).map(|res| {
debug_assert!(len <= STORAGE_SIZE, "overflown address storage");
(res, SockAddr::new(storage, len))
})
}
/// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path.
///
/// Returns an error if the path is longer than `SUN_LEN`.
#[cfg(not(target_os = "wasi"))]
pub fn unix<P>(path: P) -> io::Result<SockAddr>
where
P: AsRef<Path>,
{
crate::sys::unix_sockaddr(path.as_ref())
}
/// Set the length of the address.
///
/// # Safety
///
/// Caller must ensure that the address up to `length` bytes are properly
/// initialised.
pub unsafe fn set_length(&mut self, length: socklen_t) {
self.len = length;
}
/// Returns this address's family.
pub const fn family(&self) -> sa_family_t {
self.storage.ss_family
}
/// Returns this address's `Domain`.
pub const fn domain(&self) -> Domain {
Domain(self.storage.ss_family as c_int)
}
/// Returns the size of this address in bytes.
pub const fn len(&self) -> socklen_t {
self.len
}
/// Returns a raw pointer to the address.
pub const fn as_ptr(&self) -> *const SockAddrStorage {
&self.storage as *const sockaddr_storage as *const SockAddrStorage
}
/// Returns the address as the storage.
pub const fn as_storage(self) -> SockAddrStorage {
SockAddrStorage {
storage: self.storage,
}
}
/// Returns true if this address is in the `AF_INET` (IPv4) family, false otherwise.
pub const fn is_ipv4(&self) -> bool {
self.storage.ss_family == AF_INET as sa_family_t
}
/// Returns true if this address is in the `AF_INET6` (IPv6) family, false
/// otherwise.
pub const fn is_ipv6(&self) -> bool {
self.storage.ss_family == AF_INET6 as sa_family_t
}
/// Returns true if this address is of a unix socket (for local interprocess communication),
/// i.e. it is from the `AF_UNIX` family, false otherwise.
#[cfg(not(target_os = "wasi"))]
pub fn is_unix(&self) -> bool {
self.storage.ss_family == AF_UNIX as sa_family_t
}
/// Returns this address as a `SocketAddr` if it is in the `AF_INET` (IPv4)
/// or `AF_INET6` (IPv6) family, otherwise returns `None`.
pub fn as_socket(&self) -> Option<SocketAddr> {
if self.storage.ss_family == AF_INET as sa_family_t {
// SAFETY: if the `ss_family` field is `AF_INET` then storage must
// be a `sockaddr_in`.
let addr = unsafe { &*(ptr::addr_of!(self.storage).cast::<sockaddr_in>()) };
let ip = crate::sys::from_in_addr(addr.sin_addr);
let port = u16::from_be(addr.sin_port);
Some(SocketAddr::V4(SocketAddrV4::new(ip, port)))
} else if self.storage.ss_family == AF_INET6 as sa_family_t {
// SAFETY: if the `ss_family` field is `AF_INET6` then storage must
// be a `sockaddr_in6`.
let addr = unsafe { &*(ptr::addr_of!(self.storage).cast::<sockaddr_in6>()) };
let ip = crate::sys::from_in6_addr(addr.sin6_addr);
let port = u16::from_be(addr.sin6_port);
Some(SocketAddr::V6(SocketAddrV6::new(
ip,
port,
addr.sin6_flowinfo,
#[cfg(any(unix, all(target_os = "wasi", not(target_env = "p1"))))]
addr.sin6_scope_id,
#[cfg(windows)]
unsafe {
addr.Anonymous.sin6_scope_id
},
)))
} else {
None
}
}
/// Returns this address as a [`SocketAddrV4`] if it is in the `AF_INET`
/// family.
pub fn as_socket_ipv4(&self) -> Option<SocketAddrV4> {
match self.as_socket() {
Some(SocketAddr::V4(addr)) => Some(addr),
_ => None,
}
}
/// Returns this address as a [`SocketAddrV6`] if it is in the `AF_INET6`
/// family.
pub fn as_socket_ipv6(&self) -> Option<SocketAddrV6> {
match self.as_socket() {
Some(SocketAddr::V6(addr)) => Some(addr),
_ => None,
}
}
/// Returns the initialised storage bytes.
fn as_bytes(&self) -> &[u8] {
// SAFETY: `self.storage` is a C struct which can always be treated a
// slice of bytes. Furthermore, we ensure we don't read any uninitialised
// bytes by using `self.len`.
unsafe { std::slice::from_raw_parts(self.as_ptr().cast(), self.len as usize) }
}
}
impl From<SocketAddr> for SockAddr {
fn from(addr: SocketAddr) -> SockAddr {
match addr {
SocketAddr::V4(addr) => addr.into(),
SocketAddr::V6(addr) => addr.into(),
}
}
}
impl From<SocketAddrV4> for SockAddr {
fn from(addr: SocketAddrV4) -> SockAddr {
// SAFETY: a `sockaddr_storage` of all zeros is valid.
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
let len = {
let storage = unsafe { &mut *ptr::addr_of_mut!(storage).cast::<sockaddr_in>() };
storage.sin_family = AF_INET as sa_family_t;
storage.sin_port = addr.port().to_be();
storage.sin_addr = crate::sys::to_in_addr(addr.ip());
#[cfg(not(target_os = "wasi"))]
{
storage.sin_zero = Default::default();
}
mem::size_of::<sockaddr_in>() as socklen_t
};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "haiku",
target_os = "hermit",
target_os = "ios",
target_os = "visionos",
target_os = "macos",
target_os = "netbsd",
target_os = "nto",
target_os = "openbsd",
target_os = "tvos",
target_os = "vxworks",
target_os = "watchos",
))]
{
storage.ss_len = len as u8;
}
SockAddr { storage, len }
}
}
impl From<SocketAddrV6> for SockAddr {
fn from(addr: SocketAddrV6) -> SockAddr {
// SAFETY: a `sockaddr_storage` of all zeros is valid.
let mut storage = unsafe { mem::zeroed::<sockaddr_storage>() };
let len = {
let storage = unsafe { &mut *ptr::addr_of_mut!(storage).cast::<sockaddr_in6>() };
storage.sin6_family = AF_INET6 as sa_family_t;
storage.sin6_port = addr.port().to_be();
storage.sin6_addr = crate::sys::to_in6_addr(addr.ip());
storage.sin6_flowinfo = addr.flowinfo();
#[cfg(any(unix, all(target_os = "wasi", not(target_env = "p1"))))]
{
storage.sin6_scope_id = addr.scope_id();
}
#[cfg(windows)]
{
storage.Anonymous = SOCKADDR_IN6_0 {
sin6_scope_id: addr.scope_id(),
};
}
mem::size_of::<sockaddr_in6>() as socklen_t
};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "haiku",
target_os = "hermit",
target_os = "ios",
target_os = "visionos",
target_os = "macos",
target_os = "netbsd",
target_os = "nto",
target_os = "openbsd",
target_os = "tvos",
target_os = "vxworks",
target_os = "watchos",
))]
{
storage.ss_len = len as u8;
}
SockAddr { storage, len }
}
}
impl fmt::Debug for SockAddr {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = fmt.debug_struct("SockAddr");
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "haiku",
target_os = "hermit",
target_os = "ios",
target_os = "visionos",
target_os = "macos",
target_os = "netbsd",
target_os = "nto",
target_os = "openbsd",
target_os = "tvos",
target_os = "vxworks",
target_os = "watchos",
))]
f.field("ss_len", &self.storage.ss_len);
f.field("ss_family", &self.storage.ss_family)
.field("len", &self.len)
.finish()
}
}
impl PartialEq for SockAddr {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Eq for SockAddr {}
impl Hash for SockAddr {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ipv4() {
use std::net::Ipv4Addr;
let std = SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 9876);
let addr = SockAddr::from(std);
assert!(addr.is_ipv4());
assert!(!addr.is_ipv6());
#[cfg(not(target_os = "wasi"))]
assert!(!addr.is_unix());
assert_eq!(addr.family(), AF_INET as sa_family_t);
assert_eq!(addr.domain(), Domain::IPV4);
assert_eq!(addr.len(), size_of::<sockaddr_in>() as socklen_t);
assert_eq!(addr.as_socket(), Some(SocketAddr::V4(std)));
assert_eq!(addr.as_socket_ipv4(), Some(std));
assert!(addr.as_socket_ipv6().is_none());
let addr = SockAddr::from(SocketAddr::from(std));
assert_eq!(addr.family(), AF_INET as sa_family_t);
assert_eq!(addr.len(), size_of::<sockaddr_in>() as socklen_t);
assert_eq!(addr.as_socket(), Some(SocketAddr::V4(std)));
assert_eq!(addr.as_socket_ipv4(), Some(std));
assert!(addr.as_socket_ipv6().is_none());
#[cfg(all(unix, not(target_os = "wasi")))]
{
assert!(addr.as_pathname().is_none());
assert!(addr.as_abstract_namespace().is_none());
}
}
#[test]
fn ipv6() {
use std::net::Ipv6Addr;
let std = SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9876, 11, 12);
let addr = SockAddr::from(std);
assert!(addr.is_ipv6());
assert!(!addr.is_ipv4());
#[cfg(not(target_os = "wasi"))]
assert!(!addr.is_unix());
assert_eq!(addr.family(), AF_INET6 as sa_family_t);
assert_eq!(addr.domain(), Domain::IPV6);
assert_eq!(addr.len(), size_of::<sockaddr_in6>() as socklen_t);
assert_eq!(addr.as_socket(), Some(SocketAddr::V6(std)));
assert!(addr.as_socket_ipv4().is_none());
assert_eq!(addr.as_socket_ipv6(), Some(std));
let addr = SockAddr::from(SocketAddr::from(std));
assert_eq!(addr.family(), AF_INET6 as sa_family_t);
assert_eq!(addr.len(), size_of::<sockaddr_in6>() as socklen_t);
assert_eq!(addr.as_socket(), Some(SocketAddr::V6(std)));
assert!(addr.as_socket_ipv4().is_none());
assert_eq!(addr.as_socket_ipv6(), Some(std));
#[cfg(all(unix, not(target_os = "wasi")))]
{
assert!(addr.as_pathname().is_none());
assert!(addr.as_abstract_namespace().is_none());
}
}
#[test]
fn ipv4_eq() {
use std::net::Ipv4Addr;
let std1 = SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 9876);
let std2 = SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 8765);
test_eq(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
}
#[test]
fn ipv4_hash() {
use std::net::Ipv4Addr;
let std1 = SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 9876);
let std2 = SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 8765);
test_hash(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
}
#[test]
fn ipv6_eq() {
use std::net::Ipv6Addr;
let std1 = SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9876, 11, 12);
let std2 = SocketAddrV6::new(Ipv6Addr::new(3, 4, 5, 6, 7, 8, 9, 0), 7654, 13, 14);
test_eq(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
}
#[test]
fn ipv6_hash() {
use std::net::Ipv6Addr;
let std1 = SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9876, 11, 12);
let std2 = SocketAddrV6::new(Ipv6Addr::new(3, 4, 5, 6, 7, 8, 9, 0), 7654, 13, 14);
test_hash(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
}
#[test]
fn ipv4_ipv6_eq() {
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
let std1 = SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 9876);
let std2 = SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9876, 11, 12);
test_eq(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
test_eq(
SockAddr::from(std2),
SockAddr::from(std2),
SockAddr::from(std1),
);
}
#[test]
fn ipv4_ipv6_hash() {
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
let std1 = SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 9876);
let std2 = SocketAddrV6::new(Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8), 9876, 11, 12);
test_hash(
SockAddr::from(std1),
SockAddr::from(std1),
SockAddr::from(std2),
);
test_hash(
SockAddr::from(std2),
SockAddr::from(std2),
SockAddr::from(std1),
);
}
#[allow(clippy::eq_op)] // allow a0 == a0 check
fn test_eq(a0: SockAddr, a1: SockAddr, b: SockAddr) {
assert!(a0 == a0);
assert!(a0 == a1);
assert!(a1 == a0);
assert!(a0 != b);
assert!(b != a0);
}
fn test_hash(a0: SockAddr, a1: SockAddr, b: SockAddr) {
assert!(calculate_hash(&a0) == calculate_hash(&a0));
assert!(calculate_hash(&a0) == calculate_hash(&a1));
// technically unequal values can have the same hash, in this case x != z and both have different hashes
assert!(calculate_hash(&a0) != calculate_hash(&b));
}
fn calculate_hash(x: &SockAddr) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
x.hash(&mut hasher);
hasher.finish()
}
}

2447
vendor/socket2/src/socket.rs vendored Normal file

File diff suppressed because it is too large Load Diff

121
vendor/socket2/src/sockref.rs vendored Normal file
View File

@@ -0,0 +1,121 @@
use std::fmt;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ops::Deref;
#[cfg(any(unix, all(target_os = "wasi", not(target_env = "p1"))))]
use std::os::fd::{AsFd, AsRawFd, FromRawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawSocket, AsSocket, FromRawSocket};
use crate::Socket;
/// A reference to a [`Socket`] that can be used to configure socket types other
/// than the `Socket` type itself.
///
/// This allows for example a [`TcpStream`], found in the standard library, to
/// be configured using all the additional methods found in the [`Socket`] API.
///
/// `SockRef` can be created from any socket type that implements [`AsFd`]
/// (Unix) or [`AsSocket`] (Windows) using the [`From`] implementation.
///
/// [`TcpStream`]: std::net::TcpStream
// Don't use intra-doc links because they won't build on every platform.
/// [`AsFd`]: https://doc.rust-lang.org/stable/std/os/fd/trait.AsFd.html
/// [`AsSocket`]: https://doc.rust-lang.org/stable/std/os/windows/io/trait.AsSocket.html
///
/// # Examples
///
/// Below is an example of converting a [`TcpStream`] into a [`SockRef`].
///
/// ```
/// use std::net::{TcpStream, SocketAddr};
///
/// use socket2::SockRef;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Create `TcpStream` from the standard library.
/// let address: SocketAddr = "127.0.0.1:1234".parse()?;
/// # let b1 = std::sync::Arc::new(std::sync::Barrier::new(2));
/// # let b2 = b1.clone();
/// # let handle = std::thread::spawn(move || {
/// # let listener = std::net::TcpListener::bind(address).unwrap();
/// # b2.wait();
/// # let (stream, _) = listener.accept().unwrap();
/// # std::thread::sleep(std::time::Duration::from_millis(10));
/// # drop(stream);
/// # });
/// # b1.wait();
/// let stream = TcpStream::connect(address)?;
///
/// // Create a `SockRef`erence to the stream.
/// let socket_ref = SockRef::from(&stream);
/// // Use `Socket::set_tcp_nodelay` on the stream.
/// socket_ref.set_tcp_nodelay(true)?;
/// drop(socket_ref);
///
/// assert_eq!(stream.nodelay()?, true);
/// # handle.join().unwrap();
/// # Ok(())
/// # }
/// ```
pub struct SockRef<'s> {
/// Because this is a reference we don't own the `Socket`, however `Socket`
/// closes itself when dropped, so we use `ManuallyDrop` to prevent it from
/// closing itself.
socket: ManuallyDrop<Socket>,
/// Because we don't own the socket we need to ensure the socket remains
/// open while we have a "reference" to it, the lifetime `'s` ensures this.
_lifetime: PhantomData<&'s Socket>,
}
impl<'s> Deref for SockRef<'s> {
type Target = Socket;
fn deref(&self) -> &Self::Target {
&self.socket
}
}
/// On Windows, a corresponding `From<&impl AsSocket>` implementation exists.
#[cfg(any(unix, all(target_os = "wasi", not(target_env = "p1"))))]
impl<'s, S> From<&'s S> for SockRef<'s>
where
S: AsFd,
{
/// The caller must ensure `S` is actually a socket.
fn from(socket: &'s S) -> Self {
let fd = socket.as_fd().as_raw_fd();
assert!(fd >= 0);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_fd(fd) }),
_lifetime: PhantomData,
}
}
}
/// On Unix, a corresponding `From<&impl AsFd>` implementation exists.
#[cfg(windows)]
impl<'s, S> From<&'s S> for SockRef<'s>
where
S: AsSocket,
{
/// See the `From<&impl AsFd>` implementation.
fn from(socket: &'s S) -> Self {
let socket = socket.as_socket().as_raw_socket();
assert!(socket != windows_sys::Win32::Networking::WinSock::INVALID_SOCKET as _);
SockRef {
socket: ManuallyDrop::new(unsafe { Socket::from_raw_socket(socket) }),
_lifetime: PhantomData,
}
}
}
impl fmt::Debug for SockRef<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SockRef")
.field("raw", &self.socket.as_raw())
.field("local_addr", &self.socket.local_addr().ok())
.field("peer_addr", &self.socket.peer_addr().ok())
.finish()
}
}

3052
vendor/socket2/src/sys/unix.rs vendored Normal file

File diff suppressed because it is too large Load Diff

1136
vendor/socket2/src/sys/windows.rs vendored Normal file

File diff suppressed because it is too large Load Diff