Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
Vendored
+739
@@ -0,0 +1,739 @@
|
||||
// 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", target_os = "horizon")))]
|
||||
use std::io::IoSlice;
|
||||
#[cfg(not(any(target_os = "redox", target_os = "wasi", target_os = "horizon")))]
|
||||
use std::marker::PhantomData;
|
||||
#[cfg(not(any(target_os = "redox", target_os = "wasi", target_os = "horizon")))]
|
||||
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), "§ion=", 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", target_os = "horizon"))
|
||||
))]
|
||||
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",
|
||||
target_os = "horizon"
|
||||
))
|
||||
))]
|
||||
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", target_os = "horizon")))]
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
pub struct RecvFlags(c_int);
|
||||
|
||||
#[cfg(not(any(target_os = "redox", target_os = "wasi", target_os = "horizon")))]
|
||||
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",
|
||||
target_os = "horizon"
|
||||
)))]
|
||||
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",
|
||||
target_os = "horizon"
|
||||
)))]
|
||||
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",
|
||||
target_os = "horizon"
|
||||
)))]
|
||||
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",
|
||||
target_os = "horizon"
|
||||
)))]
|
||||
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 = "emscripten",
|
||||
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",
|
||||
target_os = "nuttx",
|
||||
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 = "emscripten",
|
||||
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",
|
||||
target_os = "nuttx",
|
||||
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", target_os = "horizon")))]
|
||||
#[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", target_os = "horizon")))]
|
||||
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", target_os = "horizon")))]
|
||||
impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
"MsgHdr".fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "redox", target_os = "wasi", target_os = "horizon")))]
|
||||
unsafe impl Send for MsgHdr<'_, '_, '_> {}
|
||||
|
||||
/// 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", target_os = "horizon")))]
|
||||
#[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", target_os = "horizon")))]
|
||||
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", target_os = "horizon")))]
|
||||
impl<'name, 'bufs, 'control> fmt::Debug for MsgHdrMut<'name, 'bufs, 'control> {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
"MsgHdrMut".fmt(fmt)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "redox", target_os = "wasi", target_os = "horizon")))]
|
||||
unsafe impl Send for MsgHdrMut<'_, '_, '_> {}
|
||||
Vendored
+653
@@ -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()
|
||||
}
|
||||
}
|
||||
Vendored
+2479
File diff suppressed because it is too large
Load Diff
Vendored
+121
@@ -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()
|
||||
}
|
||||
}
|
||||
Vendored
+3099
File diff suppressed because it is too large
Load Diff
Vendored
+1179
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user