From 55e23db137bd659a4299abc29104eb643a5a0b1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Sun, 1 Nov 2020 00:27:55 +0100 Subject: [PATCH 1/8] Represent SocketAddrV4 and SocketAddrV6 as Rust native encoding --- library/std/src/net/addr.rs | 177 ++++++++++++++--------------- library/std/src/sys/unix/net.rs | 4 +- library/std/src/sys/windows/net.rs | 4 +- library/std/src/sys_common/net.rs | 20 ++-- 4 files changed, 100 insertions(+), 105 deletions(-) diff --git a/library/std/src/net/addr.rs b/library/std/src/net/addr.rs index 81dd042425c1d..d724f7e7843b0 100644 --- a/library/std/src/net/addr.rs +++ b/library/std/src/net/addr.rs @@ -73,12 +73,11 @@ pub enum SocketAddr { /// assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1)); /// assert_eq!(socket.port(), 8080); /// ``` -#[derive(Copy)] +#[derive(Copy, Clone, Eq, PartialEq)] #[stable(feature = "rust1", since = "1.0.0")] pub struct SocketAddrV4 { - // Do not assume that this struct is implemented as the underlying system representation. - // The memory layout is not part of the stable interface that std exposes. - inner: c::sockaddr_in, + ip: Ipv4Addr, + port: u16, } /// An IPv6 socket address. @@ -107,12 +106,13 @@ pub struct SocketAddrV4 { /// assert_eq!(socket.ip(), &Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)); /// assert_eq!(socket.port(), 8080); /// ``` -#[derive(Copy)] +#[derive(Copy, Clone, Eq, PartialEq)] #[stable(feature = "rust1", since = "1.0.0")] pub struct SocketAddrV6 { - // Do not assume that this struct is implemented as the underlying system representation. - // The memory layout is not part of the stable interface that std exposes. - inner: c::sockaddr_in6, + ip: Ipv6Addr, + port: u16, + flowinfo: u32, + scope_id: u32, } impl SocketAddr { @@ -131,7 +131,8 @@ impl SocketAddr { /// ``` #[stable(feature = "ip_addr", since = "1.7.0")] #[must_use] - pub fn new(ip: IpAddr, port: u16) -> SocketAddr { + #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + pub const fn new(ip: IpAddr, port: u16) -> SocketAddr { match ip { IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)), IpAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0)), @@ -277,15 +278,9 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - pub fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 { - SocketAddrV4 { - inner: c::sockaddr_in { - sin_family: c::AF_INET as c::sa_family_t, - sin_port: htons(port), - sin_addr: ip.into_inner(), - ..unsafe { mem::zeroed() } - }, - } + #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 { + SocketAddrV4 { ip, port } } /// Returns the IP address associated with this socket address. @@ -302,9 +297,7 @@ impl SocketAddrV4 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn ip(&self) -> &Ipv4Addr { - // SAFETY: `Ipv4Addr` is `#[repr(C)] struct { _: in_addr; }`. - // It is safe to cast from `&in_addr` to `&Ipv4Addr`. - unsafe { &*(&self.inner.sin_addr as *const c::in_addr as *const Ipv4Addr) } + &self.ip } /// Changes the IP address associated with this socket address. @@ -320,7 +313,7 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_ip(&mut self, new_ip: Ipv4Addr) { - self.inner.sin_addr = new_ip.into_inner() + self.ip = new_ip; } /// Returns the port number associated with this socket address. @@ -337,7 +330,7 @@ impl SocketAddrV4 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn port(&self) -> u16 { - ntohs(self.inner.sin_port) + self.port } /// Changes the port number associated with this socket address. @@ -353,7 +346,7 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_port(&mut self, new_port: u16) { - self.inner.sin_port = htons(new_port); + self.port = new_port; } } @@ -376,17 +369,9 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - pub fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 { - SocketAddrV6 { - inner: c::sockaddr_in6 { - sin6_family: c::AF_INET6 as c::sa_family_t, - sin6_port: htons(port), - sin6_addr: *ip.as_inner(), - sin6_flowinfo: flowinfo, - sin6_scope_id: scope_id, - ..unsafe { mem::zeroed() } - }, - } + #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 { + SocketAddrV6 { ip, port, flowinfo, scope_id } } /// Returns the IP address associated with this socket address. @@ -403,7 +388,7 @@ impl SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn ip(&self) -> &Ipv6Addr { - unsafe { &*(&self.inner.sin6_addr as *const c::in6_addr as *const Ipv6Addr) } + &self.ip } /// Changes the IP address associated with this socket address. @@ -419,7 +404,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_ip(&mut self, new_ip: Ipv6Addr) { - self.inner.sin6_addr = *new_ip.as_inner() + self.ip = new_ip; } /// Returns the port number associated with this socket address. @@ -436,7 +421,7 @@ impl SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn port(&self) -> u16 { - ntohs(self.inner.sin6_port) + self.port } /// Changes the port number associated with this socket address. @@ -452,7 +437,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_port(&mut self, new_port: u16) { - self.inner.sin6_port = htons(new_port); + self.port = new_port; } /// Returns the flow information associated with this address. @@ -479,7 +464,7 @@ impl SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn flowinfo(&self) -> u32 { - self.inner.sin6_flowinfo + self.flowinfo } /// Changes the flow information associated with this socket address. @@ -497,7 +482,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_flowinfo(&mut self, new_flowinfo: u32) { - self.inner.sin6_flowinfo = new_flowinfo; + self.flowinfo = new_flowinfo; } /// Returns the scope ID associated with this address. @@ -519,7 +504,7 @@ impl SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn scope_id(&self) -> u32 { - self.inner.sin6_scope_id + self.scope_id } /// Changes the scope ID associated with this socket address. @@ -537,19 +522,51 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "sockaddr_setters", since = "1.9.0")] pub fn set_scope_id(&mut self, new_scope_id: u32) { - self.inner.sin6_scope_id = new_scope_id; + self.scope_id = new_scope_id; } } impl FromInner for SocketAddrV4 { fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { - SocketAddrV4 { inner: addr } + SocketAddrV4 { + ip: unsafe { *(&addr.sin_addr as *const c::in_addr as *const Ipv4Addr) }, + port: ntohs(addr.sin_port), + } } } impl FromInner for SocketAddrV6 { fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 { - SocketAddrV6 { inner: addr } + SocketAddrV6 { + ip: unsafe { *(&addr.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }, + port: ntohs(addr.sin6_port), + flowinfo: addr.sin6_flowinfo, + scope_id: addr.sin6_scope_id, + } + } +} + +impl IntoInner for SocketAddrV4 { + fn into_inner(self) -> c::sockaddr_in { + c::sockaddr_in { + sin_family: c::AF_INET as c::sa_family_t, + sin_port: htons(self.port), + sin_addr: self.ip.into_inner(), + ..unsafe { mem::zeroed() } + } + } +} + +impl IntoInner for SocketAddrV6 { + fn into_inner(self) -> c::sockaddr_in6 { + c::sockaddr_in6 { + sin6_family: c::AF_INET6 as c::sa_family_t, + sin6_port: htons(self.port), + sin6_addr: *self.ip.as_inner(), + sin6_flowinfo: self.flowinfo, + sin6_scope_id: self.scope_id, + ..unsafe { mem::zeroed() } + } } } @@ -582,14 +599,32 @@ impl> From<(I, u16)> for SocketAddr { } } -impl<'a> IntoInner<(*const c::sockaddr, c::socklen_t)> for &'a SocketAddr { - fn into_inner(self) -> (*const c::sockaddr, c::socklen_t) { +/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level +/// SocketAddr* types into their system representation. The benefit of this specific +/// type over using `c::sockaddr_storage` is that this type is exactly as large as it +/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust. +#[repr(C)] +pub(crate) union SocketAddrCRepr { + v4: c::sockaddr_in, + v6: c::sockaddr_in6, +} + +impl SocketAddrCRepr { + pub fn as_ptr(&self) -> *const c::sockaddr { + self as *const _ as *const c::sockaddr + } +} + +impl<'a> IntoInner<(SocketAddrCRepr, c::socklen_t)> for &'a SocketAddr { + fn into_inner(self) -> (SocketAddrCRepr, c::socklen_t) { match *self { SocketAddr::V4(ref a) => { - (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t) + let sockaddr = SocketAddrCRepr { v4: a.into_inner() }; + (sockaddr, mem::size_of::() as c::socklen_t) } SocketAddr::V6(ref a) => { - (a as *const _ as *const _, mem::size_of_val(a) as c::socklen_t) + let sockaddr = SocketAddrCRepr { v6: a.into_inner() }; + (sockaddr, mem::size_of::() as c::socklen_t) } } } @@ -688,40 +723,6 @@ impl fmt::Debug for SocketAddrV6 { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl Clone for SocketAddrV4 { - fn clone(&self) -> SocketAddrV4 { - *self - } -} -#[stable(feature = "rust1", since = "1.0.0")] -impl Clone for SocketAddrV6 { - fn clone(&self) -> SocketAddrV6 { - *self - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for SocketAddrV4 { - fn eq(&self, other: &SocketAddrV4) -> bool { - self.inner.sin_port == other.inner.sin_port - && self.inner.sin_addr.s_addr == other.inner.sin_addr.s_addr - } -} -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for SocketAddrV6 { - fn eq(&self, other: &SocketAddrV6) -> bool { - self.inner.sin6_port == other.inner.sin6_port - && self.inner.sin6_addr.s6_addr == other.inner.sin6_addr.s6_addr - && self.inner.sin6_flowinfo == other.inner.sin6_flowinfo - && self.inner.sin6_scope_id == other.inner.sin6_scope_id - } -} -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for SocketAddrV4 {} -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for SocketAddrV6 {} - #[stable(feature = "socketaddr_ordering", since = "1.45.0")] impl PartialOrd for SocketAddrV4 { fn partial_cmp(&self, other: &SocketAddrV4) -> Option { @@ -753,19 +754,13 @@ impl Ord for SocketAddrV6 { #[stable(feature = "rust1", since = "1.0.0")] impl hash::Hash for SocketAddrV4 { fn hash(&self, s: &mut H) { - (self.inner.sin_port, self.inner.sin_addr.s_addr).hash(s) + (self.port, self.ip).hash(s) } } #[stable(feature = "rust1", since = "1.0.0")] impl hash::Hash for SocketAddrV6 { fn hash(&self, s: &mut H) { - ( - self.inner.sin6_port, - &self.inner.sin6_addr.s6_addr, - self.inner.sin6_flowinfo, - self.inner.sin6_scope_id, - ) - .hash(s) + (self.port, &self.ip, self.flowinfo, self.scope_id).hash(s) } } diff --git a/library/std/src/sys/unix/net.rs b/library/std/src/sys/unix/net.rs index a1bbc2d87b640..462a45b01ab49 100644 --- a/library/std/src/sys/unix/net.rs +++ b/library/std/src/sys/unix/net.rs @@ -139,8 +139,8 @@ impl Socket { pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> { self.set_nonblocking(true)?; let r = unsafe { - let (addrp, len) = addr.into_inner(); - cvt(libc::connect(self.as_raw_fd(), addrp, len)) + let (addr, len) = addr.into_inner(); + cvt(libc::connect(self.as_raw_fd(), addr.as_ptr(), len)) }; self.set_nonblocking(false)?; diff --git a/library/std/src/sys/windows/net.rs b/library/std/src/sys/windows/net.rs index d1e72cd54437c..e0701a498fad7 100644 --- a/library/std/src/sys/windows/net.rs +++ b/library/std/src/sys/windows/net.rs @@ -143,8 +143,8 @@ impl Socket { pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> { self.set_nonblocking(true)?; let result = { - let (addrp, len) = addr.into_inner(); - let result = unsafe { c::connect(self.as_raw_socket(), addrp, len) }; + let (addr, len) = addr.into_inner(); + let result = unsafe { c::connect(self.as_raw_socket(), addr.as_ptr(), len) }; cvt(result).map(drop) }; self.set_nonblocking(false)?; diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index f5730a2cea52b..8c4349bf7ed9e 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -224,8 +224,8 @@ impl TcpStream { let sock = Socket::new(addr, c::SOCK_STREAM)?; - let (addrp, len) = addr.into_inner(); - cvt_r(|| unsafe { c::connect(sock.as_raw(), addrp, len) })?; + let (addr, len) = addr.into_inner(); + cvt_r(|| unsafe { c::connect(sock.as_raw(), addr.as_ptr(), len) })?; Ok(TcpStream { inner: sock }) } @@ -395,8 +395,8 @@ impl TcpListener { setsockopt(&sock, c::SOL_SOCKET, c::SO_REUSEADDR, 1 as c_int)?; // Bind our new socket - let (addrp, len) = addr.into_inner(); - cvt(unsafe { c::bind(sock.as_raw(), addrp, len as _) })?; + let (addr, len) = addr.into_inner(); + cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?; cfg_if::cfg_if! { if #[cfg(target_os = "horizon")] { @@ -500,8 +500,8 @@ impl UdpSocket { init(); let sock = Socket::new(addr, c::SOCK_DGRAM)?; - let (addrp, len) = addr.into_inner(); - cvt(unsafe { c::bind(sock.as_raw(), addrp, len as _) })?; + let (addr, len) = addr.into_inner(); + cvt(unsafe { c::bind(sock.as_raw(), addr.as_ptr(), len as _) })?; Ok(UdpSocket { inner: sock }) } @@ -531,14 +531,14 @@ impl UdpSocket { pub fn send_to(&self, buf: &[u8], dst: &SocketAddr) -> io::Result { let len = cmp::min(buf.len(), ::MAX as usize) as wrlen_t; - let (dstp, dstlen) = dst.into_inner(); + let (dst, dstlen) = dst.into_inner(); let ret = cvt(unsafe { c::sendto( self.inner.as_raw(), buf.as_ptr() as *const c_void, len, MSG_NOSIGNAL, - dstp, + dst.as_ptr(), dstlen, ) })?; @@ -677,8 +677,8 @@ impl UdpSocket { } pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> { - let (addrp, len) = addr?.into_inner(); - cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addrp, len) }).map(drop) + let (addr, len) = addr?.into_inner(); + cvt_r(|| unsafe { c::connect(self.inner.as_raw(), addr.as_ptr(), len) }).map(drop) } } From 2e6256b2431c3b3713fa33ab46f293dbd07dec93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 3 Nov 2020 00:40:27 +0100 Subject: [PATCH 2/8] Implement IpV{4,6}Addr structs with native Rust encoding --- library/std/src/net/addr.rs | 11 +-- library/std/src/net/ip.rs | 138 ++++++++---------------------- library/std/src/sys_common/net.rs | 6 +- 3 files changed, 41 insertions(+), 114 deletions(-) diff --git a/library/std/src/net/addr.rs b/library/std/src/net/addr.rs index d724f7e7843b0..bfda46a802b38 100644 --- a/library/std/src/net/addr.rs +++ b/library/std/src/net/addr.rs @@ -12,7 +12,7 @@ use crate::option; use crate::slice; use crate::sys::net::netc as c; use crate::sys_common::net::LookupHost; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{FromInner, IntoInner}; use crate::vec; /// An internet socket address, either IPv4 or IPv6. @@ -528,17 +528,14 @@ impl SocketAddrV6 { impl FromInner for SocketAddrV4 { fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { - SocketAddrV4 { - ip: unsafe { *(&addr.sin_addr as *const c::in_addr as *const Ipv4Addr) }, - port: ntohs(addr.sin_port), - } + SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: ntohs(addr.sin_port) } } } impl FromInner for SocketAddrV6 { fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 { SocketAddrV6 { - ip: unsafe { *(&addr.sin6_addr as *const c::in6_addr as *const Ipv6Addr) }, + ip: Ipv6Addr::from_inner(addr.sin6_addr), port: ntohs(addr.sin6_port), flowinfo: addr.sin6_flowinfo, scope_id: addr.sin6_scope_id, @@ -562,7 +559,7 @@ impl IntoInner for SocketAddrV6 { c::sockaddr_in6 { sin6_family: c::AF_INET6 as c::sa_family_t, sin6_port: htons(self.port), - sin6_addr: *self.ip.as_inner(), + sin6_addr: self.ip.into_inner(), sin6_flowinfo: self.flowinfo, sin6_scope_id: self.scope_id, ..unsafe { mem::zeroed() } diff --git a/library/std/src/net/ip.rs b/library/std/src/net/ip.rs index 438bae01b60d2..1d49024f13e15 100644 --- a/library/std/src/net/ip.rs +++ b/library/std/src/net/ip.rs @@ -4,11 +4,10 @@ mod tests; use crate::cmp::Ordering; use crate::fmt::{self, Write as FmtWrite}; -use crate::hash; use crate::io::Write as IoWrite; use crate::mem::transmute; use crate::sys::net::netc as c; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{FromInner, IntoInner}; /// An IP address, either IPv4 or IPv6. /// @@ -77,10 +76,10 @@ pub enum IpAddr { /// assert!("0000000.0.0.0".parse::().is_err()); // first octet is a zero in octal /// assert!("0xcb.0x0.0x71.0x00".parse::().is_err()); // all octets are in hex /// ``` -#[derive(Copy)] +#[derive(Copy, Clone, PartialEq, Eq, Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Ipv4Addr { - inner: c::in_addr, + octets: [u8; 4], } /// An IPv6 address. @@ -162,10 +161,10 @@ pub struct Ipv4Addr { /// assert_eq!("::1".parse(), Ok(localhost)); /// assert_eq!(localhost.is_loopback(), true); /// ``` -#[derive(Copy)] +#[derive(Copy, Clone, PartialEq, Eq, Hash)] #[stable(feature = "rust1", since = "1.0.0")] pub struct Ipv6Addr { - inner: c::in6_addr, + octets: [u8; 16], } /// Scope of an [IPv6 multicast address] as defined in [IETF RFC 7346 section 2]. @@ -461,9 +460,7 @@ impl Ipv4Addr { #[must_use] #[inline] pub const fn new(a: u8, b: u8, c: u8, d: u8) -> Ipv4Addr { - // `s_addr` is stored as BE on all machine and the array is in BE order. - // So the native endian conversion method is used so that it's never swapped. - Ipv4Addr { inner: c::in_addr { s_addr: u32::from_ne_bytes([a, b, c, d]) } } + Ipv4Addr { octets: [a, b, c, d] } } /// An IPv4 address with the address pointing to localhost: `127.0.0.1` @@ -523,8 +520,7 @@ impl Ipv4Addr { #[must_use] #[inline] pub const fn octets(&self) -> [u8; 4] { - // This returns the order we want because s_addr is stored in big-endian. - self.inner.s_addr.to_ne_bytes() + self.octets } /// Returns [`true`] for the special 'unspecified' address (`0.0.0.0`). @@ -547,7 +543,7 @@ impl Ipv4Addr { #[must_use] #[inline] pub const fn is_unspecified(&self) -> bool { - self.inner.s_addr == 0 + u32::from_be_bytes(self.octets) == 0 } /// Returns [`true`] if this is a loopback address (`127.0.0.0/8`). @@ -910,9 +906,7 @@ impl Ipv4Addr { #[inline] pub const fn to_ipv6_compatible(&self) -> Ipv6Addr { let [a, b, c, d] = self.octets(); - Ipv6Addr { - inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] }, - } + Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a, b, c, d] } } /// Converts this address to an [IPv4-mapped] [`IPv6` address]. @@ -937,9 +931,7 @@ impl Ipv4Addr { #[inline] pub const fn to_ipv6_mapped(&self) -> Ipv6Addr { let [a, b, c, d] = self.octets(); - Ipv6Addr { - inner: c::in6_addr { s6_addr: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] }, - } + Ipv6Addr { octets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, a, b, c, d] } } } @@ -1034,22 +1026,6 @@ impl fmt::Debug for Ipv4Addr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Ipv4Addr { - #[inline] - fn clone(&self) -> Ipv4Addr { - *self - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for Ipv4Addr { - #[inline] - fn eq(&self, other: &Ipv4Addr) -> bool { - self.inner.s_addr == other.inner.s_addr - } -} - #[stable(feature = "ip_cmp", since = "1.16.0")] impl PartialEq for IpAddr { #[inline] @@ -1072,21 +1048,6 @@ impl PartialEq for Ipv4Addr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for Ipv4Addr {} - -#[stable(feature = "rust1", since = "1.0.0")] -impl hash::Hash for Ipv4Addr { - #[inline] - fn hash(&self, s: &mut H) { - // NOTE: - // * hash in big endian order - // * in netbsd, `in_addr` has `repr(packed)`, we need to - // copy `s_addr` to avoid unsafe borrowing - { self.inner.s_addr }.hash(s) - } -} - #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for Ipv4Addr { #[inline] @@ -1121,15 +1082,21 @@ impl PartialOrd for Ipv4Addr { impl Ord for Ipv4Addr { #[inline] fn cmp(&self, other: &Ipv4Addr) -> Ordering { - // Compare as native endian - u32::from_be(self.inner.s_addr).cmp(&u32::from_be(other.inner.s_addr)) + self.octets.cmp(&other.octets) } } impl IntoInner for Ipv4Addr { #[inline] fn into_inner(self) -> c::in_addr { - self.inner + // `s_addr` is stored as BE on all machines and the array is in BE order. + // So the native endian conversion method is used so that it's never swapped. + c::in_addr { s_addr: u32::from_ne_bytes(self.octets) } + } +} +impl FromInner for Ipv4Addr { + fn from_inner(addr: c::in_addr) -> Ipv4Addr { + Ipv4Addr { octets: addr.s_addr.to_ne_bytes() } } } @@ -1147,8 +1114,7 @@ impl From for u32 { /// ``` #[inline] fn from(ip: Ipv4Addr) -> u32 { - let ip = ip.octets(); - u32::from_be_bytes(ip) + u32::from_be_bytes(ip.octets) } } @@ -1166,7 +1132,7 @@ impl From for Ipv4Addr { /// ``` #[inline] fn from(ip: u32) -> Ipv4Addr { - Ipv4Addr::from(ip.to_be_bytes()) + Ipv4Addr { octets: ip.to_be_bytes() } } } @@ -1184,7 +1150,7 @@ impl From<[u8; 4]> for Ipv4Addr { /// ``` #[inline] fn from(octets: [u8; 4]) -> Ipv4Addr { - Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]) + Ipv4Addr { octets } } } @@ -1234,13 +1200,9 @@ impl Ipv6Addr { h.to_be(), ]; Ipv6Addr { - inner: c::in6_addr { - // All elements in `addr16` are big endian. - // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`. - // rustc_allow_const_fn_unstable: the transmute could be written as stable const - // code, but that leads to worse code generation (#75085) - s6_addr: unsafe { transmute::<_, [u8; 16]>(addr16) }, - }, + // All elements in `addr16` are big endian. + // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`. + octets: unsafe { transmute::<_, [u8; 16]>(addr16) }, } } @@ -1285,11 +1247,9 @@ impl Ipv6Addr { #[must_use] #[inline] pub const fn segments(&self) -> [u16; 8] { - // All elements in `s6_addr` must be big endian. + // All elements in `self.octets` must be big endian. // SAFETY: `[u8; 16]` is always safe to transmute to `[u16; 8]`. - // rustc_allow_const_fn_unstable: the transmute could be written as stable const code, but - // that leads to worse code generation (#75085) - let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.inner.s6_addr) }; + let [a, b, c, d, e, f, g, h] = unsafe { transmute::<_, [u16; 8]>(self.octets) }; // We want native endian u16 [ u16::from_be(a), @@ -1748,7 +1708,7 @@ impl Ipv6Addr { #[must_use] #[inline] pub const fn octets(&self) -> [u8; 16] { - self.inner.s6_addr + self.octets } } @@ -1856,22 +1816,6 @@ impl fmt::Debug for Ipv6Addr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Ipv6Addr { - #[inline] - fn clone(&self) -> Ipv6Addr { - *self - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for Ipv6Addr { - #[inline] - fn eq(&self, other: &Ipv6Addr) -> bool { - self.inner.s6_addr == other.inner.s6_addr - } -} - #[stable(feature = "ip_cmp", since = "1.16.0")] impl PartialEq for Ipv6Addr { #[inline] @@ -1894,17 +1838,6 @@ impl PartialEq for IpAddr { } } -#[stable(feature = "rust1", since = "1.0.0")] -impl Eq for Ipv6Addr {} - -#[stable(feature = "rust1", since = "1.0.0")] -impl hash::Hash for Ipv6Addr { - #[inline] - fn hash(&self, s: &mut H) { - self.inner.s6_addr.hash(s) - } -} - #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for Ipv6Addr { #[inline] @@ -1943,16 +1876,15 @@ impl Ord for Ipv6Addr { } } -impl AsInner for Ipv6Addr { - #[inline] - fn as_inner(&self) -> &c::in6_addr { - &self.inner +impl IntoInner for Ipv6Addr { + fn into_inner(self) -> c::in6_addr { + c::in6_addr { s6_addr: self.octets } } } impl FromInner for Ipv6Addr { #[inline] fn from_inner(addr: c::in6_addr) -> Ipv6Addr { - Ipv6Addr { inner: addr } + Ipv6Addr { octets: addr.s6_addr } } } @@ -1973,8 +1905,7 @@ impl From for u128 { /// ``` #[inline] fn from(ip: Ipv6Addr) -> u128 { - let ip = ip.octets(); - u128::from_be_bytes(ip) + u128::from_be_bytes(ip.octets) } } #[stable(feature = "i128", since = "1.26.0")] @@ -2025,8 +1956,7 @@ impl From<[u8; 16]> for Ipv6Addr { /// ``` #[inline] fn from(octets: [u8; 16]) -> Ipv6Addr { - let inner = c::in6_addr { s6_addr: octets }; - Ipv6Addr::from_inner(inner) + Ipv6Addr { octets } } } diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index 8c4349bf7ed9e..e49337999d2c5 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -10,7 +10,7 @@ use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::ptr; use crate::sys::net::netc as c; use crate::sys::net::{cvt, cvt_gai, cvt_r, init, wrlen_t, Socket}; -use crate::sys_common::{AsInner, FromInner, IntoInner}; +use crate::sys_common::{FromInner, IntoInner}; use crate::time::Duration; use libc::{c_int, c_void}; @@ -621,7 +621,7 @@ impl UdpSocket { pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { - ipv6mr_multiaddr: *multiaddr.as_inner(), + ipv6mr_multiaddr: multiaddr.into_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), }; setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) @@ -637,7 +637,7 @@ impl UdpSocket { pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { let mreq = c::ipv6_mreq { - ipv6mr_multiaddr: *multiaddr.as_inner(), + ipv6mr_multiaddr: multiaddr.into_inner(), ipv6mr_interface: to_ipv6mr_interface(interface), }; setsockopt(&self.inner, c::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) From 8cd73519621513fe75b915e8c37c87f128b453dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Tue, 3 Nov 2020 01:08:31 +0100 Subject: [PATCH 3/8] Remove ntohs/htons in favor of to_be/from_be --- library/std/src/net/addr.rs | 10 +++++----- library/std/src/net/mod.rs | 9 --------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/library/std/src/net/addr.rs b/library/std/src/net/addr.rs index bfda46a802b38..4b5c5d03465be 100644 --- a/library/std/src/net/addr.rs +++ b/library/std/src/net/addr.rs @@ -7,7 +7,7 @@ use crate::hash; use crate::io::{self, Write}; use crate::iter; use crate::mem; -use crate::net::{htons, ntohs, IpAddr, Ipv4Addr, Ipv6Addr}; +use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use crate::option; use crate::slice; use crate::sys::net::netc as c; @@ -528,7 +528,7 @@ impl SocketAddrV6 { impl FromInner for SocketAddrV4 { fn from_inner(addr: c::sockaddr_in) -> SocketAddrV4 { - SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: ntohs(addr.sin_port) } + SocketAddrV4 { ip: Ipv4Addr::from_inner(addr.sin_addr), port: u16::from_be(addr.sin_port) } } } @@ -536,7 +536,7 @@ impl FromInner for SocketAddrV6 { fn from_inner(addr: c::sockaddr_in6) -> SocketAddrV6 { SocketAddrV6 { ip: Ipv6Addr::from_inner(addr.sin6_addr), - port: ntohs(addr.sin6_port), + port: u16::from_be(addr.sin6_port), flowinfo: addr.sin6_flowinfo, scope_id: addr.sin6_scope_id, } @@ -547,7 +547,7 @@ impl IntoInner for SocketAddrV4 { fn into_inner(self) -> c::sockaddr_in { c::sockaddr_in { sin_family: c::AF_INET as c::sa_family_t, - sin_port: htons(self.port), + sin_port: self.port.to_be(), sin_addr: self.ip.into_inner(), ..unsafe { mem::zeroed() } } @@ -558,7 +558,7 @@ impl IntoInner for SocketAddrV6 { fn into_inner(self) -> c::sockaddr_in6 { c::sockaddr_in6 { sin6_family: c::AF_INET6 as c::sa_family_t, - sin6_port: htons(self.port), + sin6_port: self.port.to_be(), sin6_addr: self.ip.into_inner(), sin6_flowinfo: self.flowinfo, sin6_scope_id: self.scope_id, diff --git a/library/std/src/net/mod.rs b/library/std/src/net/mod.rs index 9ed4a98f943cd..e7a40bdaf8e99 100644 --- a/library/std/src/net/mod.rs +++ b/library/std/src/net/mod.rs @@ -69,15 +69,6 @@ pub enum Shutdown { Both, } -#[inline] -const fn htons(i: u16) -> u16 { - i.to_be() -} -#[inline] -const fn ntohs(i: u16) -> u16 { - u16::from_be(i) -} - fn each_addr(addr: A, mut f: F) -> io::Result where F: FnMut(io::Result<&SocketAddr>) -> io::Result, From 230441e8ab2fed8a03efbf1ccaabe06e922fc61a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Sun, 29 Nov 2020 21:57:14 +0100 Subject: [PATCH 4/8] Add IP structural_match tests --- library/std/src/net/ip/tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/library/std/src/net/ip/tests.rs b/library/std/src/net/ip/tests.rs index 7956c6a25e495..c29509331d7a9 100644 --- a/library/std/src/net/ip/tests.rs +++ b/library/std/src/net/ip/tests.rs @@ -944,3 +944,26 @@ fn ip_const() { const IS_IP_V6: bool = IP_ADDRESS.is_ipv6(); assert!(!IS_IP_V6); } + +#[test] +fn structural_match() { + // test that all IP types can be structurally matched upon + + const IPV4: Ipv4Addr = Ipv4Addr::LOCALHOST; + match IPV4 { + Ipv4Addr::LOCALHOST => {} + _ => unreachable!(), + } + + const IPV6: Ipv6Addr = Ipv6Addr::LOCALHOST; + match IPV6 { + Ipv6Addr::LOCALHOST => {} + _ => unreachable!(), + } + + const IP: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST); + match IP { + IpAddr::V4(Ipv4Addr::LOCALHOST) => {} + _ => unreachable!(), + } +} From a344d10810187430811b43a71ad9b742d25f9b37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Thu, 23 Jun 2022 19:03:32 +0200 Subject: [PATCH 5/8] Assign issue number to the new const_socketaddr --- library/std/src/net/addr.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/std/src/net/addr.rs b/library/std/src/net/addr.rs index 4b5c5d03465be..13d85f2303502 100644 --- a/library/std/src/net/addr.rs +++ b/library/std/src/net/addr.rs @@ -131,7 +131,7 @@ impl SocketAddr { /// ``` #[stable(feature = "ip_addr", since = "1.7.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn new(ip: IpAddr, port: u16) -> SocketAddr { match ip { IpAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a, port)), @@ -278,7 +278,7 @@ impl SocketAddrV4 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn new(ip: Ipv4Addr, port: u16) -> SocketAddrV4 { SocketAddrV4 { ip, port } } @@ -369,7 +369,7 @@ impl SocketAddrV6 { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[must_use] - #[rustc_const_unstable(feature = "const_socketaddr", issue = "none")] + #[rustc_const_unstable(feature = "const_socketaddr", issue = "82485")] pub const fn new(ip: Ipv6Addr, port: u16, flowinfo: u32, scope_id: u32) -> SocketAddrV6 { SocketAddrV6 { ip, port, flowinfo, scope_id } } From 7aabd85faa9e78e40161839b14946c5aa6750086 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Thu, 23 Jun 2022 22:45:40 +0200 Subject: [PATCH 6/8] Remove invalid doc comment on the size of an IP struct --- library/std/src/net/ip.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/library/std/src/net/ip.rs b/library/std/src/net/ip.rs index 1d49024f13e15..41ca9ba842588 100644 --- a/library/std/src/net/ip.rs +++ b/library/std/src/net/ip.rs @@ -14,9 +14,6 @@ use crate::sys_common::{FromInner, IntoInner}; /// This enum can contain either an [`Ipv4Addr`] or an [`Ipv6Addr`], see their /// respective documentation for more details. /// -/// The size of an `IpAddr` instance may vary depending on the target operating -/// system. -/// /// # Examples /// /// ``` @@ -49,9 +46,6 @@ pub enum IpAddr { /// /// See [`IpAddr`] for a type encompassing both IPv4 and IPv6 addresses. /// -/// The size of an `Ipv4Addr` struct may vary depending on the target operating -/// system. -/// /// [IETF RFC 791]: https://tools.ietf.org/html/rfc791 /// /// # Textual representation @@ -87,9 +81,6 @@ pub struct Ipv4Addr { /// IPv6 addresses are defined as 128-bit integers in [IETF RFC 4291]. /// They are usually represented as eight 16-bit segments. /// -/// The size of an `Ipv6Addr` struct may vary depending on the target operating -/// system. -/// /// [IETF RFC 4291]: https://tools.ietf.org/html/rfc4291 /// /// # Embedding IPv4 Addresses From b20b69a79b4e8bfc3574c767ec798d356d33045d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Sun, 17 Jul 2022 09:48:56 +0200 Subject: [PATCH 7/8] Move SocketAddrCRepr to sys_common --- library/std/src/net/addr.rs | 31 --------------------------- library/std/src/sys_common/net.rs | 35 +++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 31 deletions(-) diff --git a/library/std/src/net/addr.rs b/library/std/src/net/addr.rs index 13d85f2303502..53fee952a7a7a 100644 --- a/library/std/src/net/addr.rs +++ b/library/std/src/net/addr.rs @@ -596,37 +596,6 @@ impl> From<(I, u16)> for SocketAddr { } } -/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level -/// SocketAddr* types into their system representation. The benefit of this specific -/// type over using `c::sockaddr_storage` is that this type is exactly as large as it -/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust. -#[repr(C)] -pub(crate) union SocketAddrCRepr { - v4: c::sockaddr_in, - v6: c::sockaddr_in6, -} - -impl SocketAddrCRepr { - pub fn as_ptr(&self) -> *const c::sockaddr { - self as *const _ as *const c::sockaddr - } -} - -impl<'a> IntoInner<(SocketAddrCRepr, c::socklen_t)> for &'a SocketAddr { - fn into_inner(self) -> (SocketAddrCRepr, c::socklen_t) { - match *self { - SocketAddr::V4(ref a) => { - let sockaddr = SocketAddrCRepr { v4: a.into_inner() }; - (sockaddr, mem::size_of::() as c::socklen_t) - } - SocketAddr::V6(ref a) => { - let sockaddr = SocketAddrCRepr { v6: a.into_inner() }; - (sockaddr, mem::size_of::() as c::socklen_t) - } - } - } -} - #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index e49337999d2c5..47c6a82f6469b 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -700,3 +700,38 @@ impl fmt::Debug for UdpSocket { res.field(name, &self.inner.as_raw()).finish() } } + +//////////////////////////////////////////////////////////////////////////////// +// Converting SocketAddr to libc representation +//////////////////////////////////////////////////////////////////////////////// + +/// A type with the same memory layout as `c::sockaddr`. Used in converting Rust level +/// SocketAddr* types into their system representation. The benefit of this specific +/// type over using `c::sockaddr_storage` is that this type is exactly as large as it +/// needs to be and not a lot larger. And it can be initialized more cleanly from Rust. +#[repr(C)] +pub(crate) union SocketAddrCRepr { + v4: c::sockaddr_in, + v6: c::sockaddr_in6, +} + +impl SocketAddrCRepr { + pub fn as_ptr(&self) -> *const c::sockaddr { + self as *const _ as *const c::sockaddr + } +} + +impl<'a> IntoInner<(SocketAddrCRepr, c::socklen_t)> for &'a SocketAddr { + fn into_inner(self) -> (SocketAddrCRepr, c::socklen_t) { + match *self { + SocketAddr::V4(ref a) => { + let sockaddr = SocketAddrCRepr { v4: a.into_inner() }; + (sockaddr, mem::size_of::() as c::socklen_t) + } + SocketAddr::V6(ref a) => { + let sockaddr = SocketAddrCRepr { v6: a.into_inner() }; + (sockaddr, mem::size_of::() as c::socklen_t) + } + } + } +} From 73bb371ad3dd401a8f6dca518ad2bbf0bad590e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20F=C3=A4rnstrand?= Date: Sun, 24 Jul 2022 18:27:19 +0200 Subject: [PATCH 8/8] Remove socklen_t from platforms where it's no longer used --- library/std/src/sys/sgx/net.rs | 2 -- library/std/src/sys/unsupported/net.rs | 2 -- library/std/src/sys/wasi/net.rs | 2 -- 3 files changed, 6 deletions(-) diff --git a/library/std/src/sys/sgx/net.rs b/library/std/src/sys/sgx/net.rs index 1d899525081b9..4c4cd7d1d1d86 100644 --- a/library/std/src/sys/sgx/net.rs +++ b/library/std/src/sys/sgx/net.rs @@ -538,6 +538,4 @@ pub mod netc { #[derive(Copy, Clone)] pub struct sockaddr {} - - pub type socklen_t = usize; } diff --git a/library/std/src/sys/unsupported/net.rs b/library/std/src/sys/unsupported/net.rs index 360115d503374..a5204a0845378 100644 --- a/library/std/src/sys/unsupported/net.rs +++ b/library/std/src/sys/unsupported/net.rs @@ -363,6 +363,4 @@ pub mod netc { #[derive(Copy, Clone)] pub struct sockaddr {} - - pub type socklen_t = usize; } diff --git a/library/std/src/sys/wasi/net.rs b/library/std/src/sys/wasi/net.rs index 937b1b850e7ba..590d268c38087 100644 --- a/library/std/src/sys/wasi/net.rs +++ b/library/std/src/sys/wasi/net.rs @@ -524,6 +524,4 @@ pub mod netc { #[derive(Copy, Clone)] pub struct sockaddr {} - - pub type socklen_t = usize; }