diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/socket2/src/sys | |
parent | Initial commit. (diff) | |
download | firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/socket2/src/sys')
-rw-r--r-- | third_party/rust/socket2/src/sys/redox/mod.rs | 828 | ||||
-rw-r--r-- | third_party/rust/socket2/src/sys/unix.rs | 1103 | ||||
-rw-r--r-- | third_party/rust/socket2/src/sys/windows.rs | 977 |
3 files changed, 2908 insertions, 0 deletions
diff --git a/third_party/rust/socket2/src/sys/redox/mod.rs b/third_party/rust/socket2/src/sys/redox/mod.rs new file mode 100644 index 0000000000..bd1ebfcb02 --- /dev/null +++ b/third_party/rust/socket2/src/sys/redox/mod.rs @@ -0,0 +1,828 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::fmt; +use std::fs::File; +use std::io; +use std::io::{ErrorKind, Read, Write}; +use std::mem; +use std::net::Shutdown; +use std::net::{self, Ipv4Addr, Ipv6Addr}; +use std::ops::Neg; +use std::os::unix::prelude::*; +use std::time::Duration; +use syscall; + +use libc::{self, c_int, c_uint, c_void, socklen_t, ssize_t}; + +use libc::IPV6_ADD_MEMBERSHIP; +use libc::IPV6_DROP_MEMBERSHIP; + +const MSG_NOSIGNAL: c_int = 0x0; + +use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; + +use crate::utils::One; +use crate::SockAddr; + +pub const IPPROTO_TCP: i32 = libc::IPPROTO_TCP; + +pub const IPPROTO_ICMP: i32 = -1; +pub const IPPROTO_ICMPV6: i32 = -1; +pub const IPPROTO_UDP: i32 = -1; +pub const SOCK_RAW: i32 = -1; +pub const SOCK_SEQPACKET: i32 = -1; + +pub struct Socket { + fd: c_int, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { + if ty == -1 { + return Err(io::Error::new(ErrorKind::Other, "Type not implemented yet")); + } + if protocol == -1 { + return Err(io::Error::new( + ErrorKind::Other, + "Protocol not implemented yet", + )); + } + unsafe { + let fd = cvt(libc::socket(family, ty, protocol))?; + let fd = Socket::from_raw_fd(fd as RawFd); + set_cloexec(fd.as_raw_fd() as c_int)?; + Ok(fd) + } + } + + pub fn pair(_family: c_int, _ty: c_int, _protocol: c_int) -> io::Result<(Socket, Socket)> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::bind(self.fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { cvt(libc::listen(self.fd, backlog)).map(|_| ()) } + } + + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::connect(self.fd, addr.as_ptr(), addr.len())).map(|_| ()) } + } + + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { + return Err(io::Error::new( + ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + if timeout.as_secs() > ::std::i64::MAX as u64 { + return Err(io::Error::new( + ErrorKind::InvalidInput, + "too large duration", + )); + } + + self.connect(addr)?; + + let mut event = File::open("event:")?; + let mut time = File::open("time:")?; + + event.write(&syscall::Event { + id: self.fd as usize, + flags: syscall::EVENT_WRITE, + data: 0, + })?; + + event.write(&syscall::Event { + id: time.as_raw_fd(), + flags: syscall::EVENT_WRITE, + data: 1, + })?; + + let mut current = syscall::TimeSpec::default(); + time.read(&mut current)?; + current.tv_sec += timeout.as_secs() as i64; + current.tv_nsec += timeout.subsec_nanos() as i32; + time.write(¤t)?; + + let mut out = syscall::Event::default(); + event.read(&mut out)?; + + if out.data == 1 { + // the timeout we registered + return Err(io::Error::new(ErrorKind::TimedOut, "connection timed out")); + } + + Ok(()) + } + + pub fn local_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getsockname( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn peer_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getpeername( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len as c_uint, + )) + } + } + + pub fn try_clone(&self) -> io::Result<Socket> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + #[allow(unused_mut)] + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_ERROR)?; + if raw == 0 { + Ok(None) + } else { + Ok(Some(io::Error::from_raw_os_error(raw as i32))) + } + } + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?; + let new = if nonblocking { + previous | libc::O_NONBLOCK + } else { + previous & !libc::O_NONBLOCK + }; + if new != previous { + cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?; + } + Ok(()) + } + } + + pub fn shutdown(&self, _how: Shutdown) -> io::Result<()> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::recv( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + 0, + ) + })?; + Ok(n as usize) + } + } + + pub fn peek(&self, _buf: &mut [u8]) -> io::Result<usize> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, 0) + } + + pub fn peek_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + fn recvfrom(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut addrlen = mem::size_of_val(&storage) as socklen_t; + + let n = cvt({ + libc::recvfrom( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) + })?; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); + Ok((n as usize, addr)) + } + } + + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::send( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + ) + })?; + Ok(n as usize) + } + } + + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::sendto( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + addr.as_ptr(), + addr.len(), + ) + })?; + Ok(n as usize) + } + } + + // ================================================ + + pub fn ttl(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) } + } + + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn set_unicast_hops_v6(&self, _hops: u32) -> io::Result<()> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn only_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)?; + Ok(raw != 0) + } + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, only_v6 as c_int) } + } + + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO)?, + )) + } + } + + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO, dur2timeval(dur)?) } + } + + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO)?, + )) + } + } + + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO, dur2timeval(dur)?) } + } + + pub fn nodelay(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY)?; + Ok(raw != 0) + } + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) } + } + + pub fn broadcast(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST)?; + Ok(raw != 0) + } + } + + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST, broadcast as c_int) } + } + + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_LOOP, + multicast_loop_v4 as c_int, + ) + } + } + + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_TTL, + multicast_ttl_v4 as c_int, + ) + } + } + + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn set_multicast_hops_v6(&self, _hops: u32) -> io::Result<()> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn set_multicast_if_v4(&self, _interface: &Ipv4Addr) -> io::Result<()> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn multicast_if_v6(&self) -> io::Result<u32> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn set_multicast_if_v6(&self, _interface: u32) -> io::Result<()> { + return Err(io::Error::new(ErrorKind::Other, "Not implemented yet")); + } + + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int, + ) + } + } + + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq) } + } + + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) } + } + + pub fn linger(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(linger2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_LINGER)?, + )) + } + } + + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_LINGER, dur2linger(dur)) } + } + + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR, reuse as c_int) } + } + + pub fn reuse_address(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR)?; + Ok(raw != 0) + } + } + + pub fn recv_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF)?; + Ok(raw as usize) + } + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF, size as c_int) + } + } + + pub fn send_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF)?; + Ok(raw as usize) + } + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF, size as c_int) + } + } + + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_KEEPALIVE)?; + if raw == 0 { + return Ok(None); + } + let secs: c_int = self.getsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION)?; + Ok(Some(Duration::new(secs as u64, 0))) + } + } + + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::SOL_SOCKET, + libc::SO_KEEPALIVE, + keepalive.is_some() as c_int, + )?; + if let Some(dur) = keepalive { + // TODO: checked cast here + self.setsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION, dur.as_secs() as c_int)?; + } + Ok(()) + } + } + + unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()> + where + T: Copy, + { + let payload = &payload as *const T as *const c_void; + cvt(libc::setsockopt( + self.fd, + opt, + val, + payload, + mem::size_of::<T>() as libc::socklen_t, + ))?; + Ok(()) + } + + unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::<T>() as libc::socklen_t; + cvt(libc::getsockopt( + self.fd, + opt, + val, + &mut slot as *mut _ as *mut _, + &mut len, + ))?; + assert_eq!(len as usize, mem::size_of::<T>()); + Ok(slot) + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + <&Socket>::read(&mut &*self, buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::read( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + ) + })?; + Ok(n as usize) + } + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + <&Socket>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> io::Result<()> { + <&Socket>::flush(&mut &*self) + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.send(buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Socket"); + f.field("fd", &self.fd); + if let Ok(addr) = self.local_addr() { + f.field("local_addr", &addr); + } + if let Ok(addr) = self.peer_addr() { + f.field("peer_addr", &addr); + } + f.finish() + } +} + +impl AsRawFd for Socket { + fn as_raw_fd(&self) -> RawFd { + self.fd as RawFd + } +} + +impl IntoRawFd for Socket { + fn into_raw_fd(self) -> RawFd { + let fd = self.fd as RawFd; + mem::forget(self); + return fd; + } +} + +impl FromRawFd for Socket { + unsafe fn from_raw_fd(fd: RawFd) -> Socket { + Socket { fd: fd as c_int } + } +} + +impl AsRawFd for crate::Socket { + fn as_raw_fd(&self) -> RawFd { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for crate::Socket { + fn into_raw_fd(self) -> RawFd { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for crate::Socket { + unsafe fn from_raw_fd(fd: RawFd) -> crate::Socket { + crate::Socket { + inner: Socket::from_raw_fd(fd), + } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + unsafe { net::TcpStream::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + unsafe { net::TcpListener::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + unsafe { net::UdpSocket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +fn max_len() -> usize { + // The maximum read limit on most posix-like systems is `SSIZE_MAX`, + // with the man page quoting that if the count of bytes to read is + // greater than `SSIZE_MAX` the result is "unspecified". + <ssize_t>::max_value() as usize +} + +fn cvt<T: One + PartialEq + Neg<Output = T>>(t: T) -> io::Result<T> { + let one: T = T::one(); + if t == -one { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +fn set_cloexec(fd: c_int) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; + let new = previous | syscall::O_CLOEXEC as i32; + if new != previous { + cvt(libc::fcntl(fd, libc::F_SETFD, new))?; + } + Ok(()) + } +} + +fn dur2timeval(dur: Option<Duration>) -> io::Result<libc::timeval> { + match dur { + Some(dur) => { + if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { + return Err(io::Error::new( + ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { + libc::time_t::max_value() + } else { + dur.as_secs() as libc::time_t + }; + let mut timeout = libc::timeval { + tv_sec: secs, + tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t, + }; + if timeout.tv_sec == 0 && timeout.tv_usec == 0 { + timeout.tv_usec = 1; + } + Ok(timeout) + } + None => Ok(libc::timeval { + tv_sec: 0, + tv_usec: 0, + }), + } +} + +fn timeval2dur(raw: libc::timeval) -> Option<Duration> { + if raw.tv_sec == 0 && raw.tv_usec == 0 { + None + } else { + let sec = raw.tv_sec as u64; + let nsec = (raw.tv_usec as u32) * 1000; + Some(Duration::new(sec, nsec)) + } +} + +fn to_s_addr(addr: &Ipv4Addr) -> libc::in_addr_t { + let octets = addr.octets(); + crate::hton( + ((octets[0] as libc::in_addr_t) << 24) + | ((octets[1] as libc::in_addr_t) << 16) + | ((octets[2] as libc::in_addr_t) << 8) + | ((octets[3] as libc::in_addr_t) << 0), + ) +} + +fn to_in6_addr(addr: &Ipv6Addr) -> libc::in6_addr { + let mut ret: libc::in6_addr = unsafe { mem::zeroed() }; + ret.s6_addr = addr.octets(); + return ret; +} + +fn to_ipv6mr_interface(value: u32) -> libc::c_uint { + value as libc::c_uint +} + +fn linger2dur(linger_opt: libc::linger) -> Option<Duration> { + if linger_opt.l_onoff == 0 { + None + } else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +fn dur2linger(dur: Option<Duration>) -> libc::linger { + match dur { + Some(d) => libc::linger { + l_onoff: 1, + l_linger: d.as_secs() as c_int, + }, + None => libc::linger { + l_onoff: 0, + l_linger: 0, + }, + } +} + +#[test] +fn test_ip() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + assert_eq!(ip, from_s_addr(to_s_addr(&ip))); +} diff --git a/third_party/rust/socket2/src/sys/unix.rs b/third_party/rust/socket2/src/sys/unix.rs new file mode 100644 index 0000000000..cacbcb5fb3 --- /dev/null +++ b/third_party/rust/socket2/src/sys/unix.rs @@ -0,0 +1,1103 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::fmt; +use std::io; +use std::io::{ErrorKind, Read, Write}; +use std::mem; +use std::net::Shutdown; +use std::net::{self, Ipv4Addr, Ipv6Addr}; +use std::ops::Neg; +#[cfg(feature = "unix")] +use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; +use std::os::unix::prelude::*; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use libc::{self, c_int, c_void, socklen_t, ssize_t}; + +cfg_if::cfg_if! { + if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", + target_os = "ios", target_os = "macos", + target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", target_os = "haiku"))] { + use libc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; + use libc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; + } else { + use libc::IPV6_ADD_MEMBERSHIP; + use libc::IPV6_DROP_MEMBERSHIP; + } +} + +cfg_if::cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "android", + target_os = "dragonfly", target_os = "freebsd", + target_os = "openbsd", target_os = "netbsd", + target_os = "haiku", target_os = "bitrig"))] { + use libc::MSG_NOSIGNAL; + } else { + const MSG_NOSIGNAL: c_int = 0x0; + } +} + +cfg_if::cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + use libc::TCP_KEEPALIVE as KEEPALIVE_OPTION; + } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "haiku"))] { + use libc::SO_KEEPALIVE as KEEPALIVE_OPTION; + } else { + use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; + } +} + +use crate::utils::One; +use crate::SockAddr; + +pub const IPPROTO_ICMP: i32 = libc::IPPROTO_ICMP; +pub const IPPROTO_ICMPV6: i32 = libc::IPPROTO_ICMPV6; +pub const IPPROTO_TCP: i32 = libc::IPPROTO_TCP; +pub const IPPROTO_UDP: i32 = libc::IPPROTO_UDP; +pub const SOCK_SEQPACKET: i32 = libc::SOCK_SEQPACKET; +pub const SOCK_RAW: i32 = libc::SOCK_RAW; + +pub struct Socket { + fd: c_int, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { + unsafe { + // On linux we first attempt to pass the SOCK_CLOEXEC flag to + // atomically create the socket and set it as CLOEXEC. Support for + // this option, however, was added in 2.6.27, and we still support + // 2.6.18 as a kernel, so if the returned error is EINVAL we + // fallthrough to the fallback. + #[cfg(target_os = "linux")] + { + match cvt(libc::socket(family, ty | libc::SOCK_CLOEXEC, protocol)) { + Ok(fd) => return Ok(Socket::from_raw_fd(fd)), + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} + Err(e) => return Err(e), + } + } + + let fd = cvt(libc::socket(family, ty, protocol))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + #[cfg(target_os = "macos")] + { + fd.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + } + Ok(fd) + } + } + + pub fn pair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<(Socket, Socket)> { + unsafe { + let mut fds = [0, 0]; + cvt(libc::socketpair(family, ty, protocol, fds.as_mut_ptr()))?; + let fds = (Socket::from_raw_fd(fds[0]), Socket::from_raw_fd(fds[1])); + set_cloexec(fds.0.as_raw_fd())?; + set_cloexec(fds.1.as_raw_fd())?; + #[cfg(target_os = "macos")] + { + fds.0 + .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + fds.1 + .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + } + Ok(fds) + } + } + + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::bind(self.fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { cvt(libc::listen(self.fd, backlog)).map(|_| ()) } + } + + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::connect(self.fd, addr.as_ptr(), addr.len())).map(|_| ()) } + } + + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + self.set_nonblocking(true)?; + let r = self.connect(addr); + self.set_nonblocking(false)?; + + match r { + Ok(()) => return Ok(()), + // there's no io::ErrorKind conversion registered for EINPROGRESS :( + Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} + Err(e) => return Err(e), + } + + let mut pollfd = libc::pollfd { + fd: self.fd, + events: libc::POLLOUT, + revents: 0, + }; + + if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let start = Instant::now(); + + loop { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )); + } + + let timeout = timeout - elapsed; + let mut timeout = timeout + .as_secs() + .saturating_mul(1_000) + .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); + if timeout == 0 { + timeout = 1; + } + + let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int; + + match unsafe { libc::poll(&mut pollfd, 1, timeout) } { + -1 => { + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } + 0 => { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )) + } + _ => { + // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look + // for POLLHUP rather than read readiness + if pollfd.revents & libc::POLLHUP != 0 { + let e = self.take_error()?.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") + }); + return Err(e); + } + return Ok(()); + } + } + } + } + + pub fn local_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getsockname( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn peer_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getpeername( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn try_clone(&self) -> io::Result<Socket> { + // implementation lifted from libstd + #[cfg(any(target_os = "android", target_os = "haiku"))] + use libc::F_DUPFD as F_DUPFD_CLOEXEC; + #[cfg(not(any(target_os = "android", target_os = "haiku")))] + use libc::F_DUPFD_CLOEXEC; + + static CLOEXEC_FAILED: AtomicBool = AtomicBool::new(false); + unsafe { + if !CLOEXEC_FAILED.load(Ordering::Relaxed) { + match cvt(libc::fcntl(self.fd, F_DUPFD_CLOEXEC, 0)) { + Ok(fd) => { + let fd = Socket::from_raw_fd(fd); + if cfg!(target_os = "linux") { + set_cloexec(fd.as_raw_fd())?; + } + return Ok(fd); + } + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { + CLOEXEC_FAILED.store(true, Ordering::Relaxed); + } + Err(e) => return Err(e), + } + } + let fd = cvt(libc::fcntl(self.fd, libc::F_DUPFD, 0))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + Ok(fd) + } + } + + #[allow(unused_mut)] + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; + let mut len = mem::size_of_val(&storage) as socklen_t; + + let mut socket = None; + #[cfg(target_os = "linux")] + { + let res = cvt_r(|| unsafe { + libc::syscall( + libc::SYS_accept4, + self.fd as libc::c_long, + &mut storage as *mut _ as libc::c_long, + len as libc::c_long, + libc::SOCK_CLOEXEC as libc::c_long, + ) as libc::c_int + }); + match res { + Ok(fd) => socket = Some(Socket { fd: fd }), + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} + Err(e) => return Err(e), + } + } + + let socket = match socket { + Some(socket) => socket, + None => unsafe { + let fd = + cvt_r(|| libc::accept(self.fd, &mut storage as *mut _ as *mut _, &mut len))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + fd + }, + }; + let addr = unsafe { SockAddr::from_raw_parts(&storage as *const _ as *const _, len) }; + Ok((socket, addr)) + } + + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_ERROR)?; + if raw == 0 { + Ok(None) + } else { + Ok(Some(io::Error::from_raw_os_error(raw as i32))) + } + } + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?; + let new = if nonblocking { + previous | libc::O_NONBLOCK + } else { + previous & !libc::O_NONBLOCK + }; + if new != previous { + cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?; + } + Ok(()) + } + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => libc::SHUT_WR, + Shutdown::Read => libc::SHUT_RD, + Shutdown::Both => libc::SHUT_RDWR, + }; + cvt(unsafe { libc::shutdown(self.fd, how) })?; + Ok(()) + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::recv( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + 0, + ) + })?; + Ok(n as usize) + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::recv( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + libc::MSG_PEEK, + ) + })?; + Ok(n as usize) + } + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, 0) + } + + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, libc::MSG_PEEK) + } + + fn recvfrom(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut addrlen = mem::size_of_val(&storage) as socklen_t; + + let n = cvt({ + libc::recvfrom( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) + })?; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); + Ok((n as usize, addr)) + } + } + + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::send( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + ) + })?; + Ok(n as usize) + } + } + + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::sendto( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + addr.as_ptr(), + addr.len(), + ) + })?; + Ok(n as usize) + } + } + + // ================================================ + + pub fn ttl(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) } + } + + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_UNICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_unicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6 as c_int, + libc::IPV6_UNICAST_HOPS, + hops as c_int, + ) + } + } + + pub fn only_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)?; + Ok(raw != 0) + } + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, only_v6 as c_int) } + } + + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO)?, + )) + } + } + + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO, dur2timeval(dur)?) } + } + + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO)?, + )) + } + } + + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO, dur2timeval(dur)?) } + } + + pub fn nodelay(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY)?; + Ok(raw != 0) + } + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) } + } + + pub fn broadcast(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST)?; + Ok(raw != 0) + } + } + + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST, broadcast as c_int) } + } + + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_LOOP, + multicast_loop_v4 as c_int, + ) + } + } + + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_TTL, + multicast_ttl_v4 as c_int, + ) + } + } + + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS, hops as c_int) } + } + + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + unsafe { + let imr_interface: libc::in_addr = + self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF)?; + Ok(from_s_addr(imr_interface.s_addr)) + } + } + + pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> { + let interface = to_s_addr(interface); + let imr_interface = libc::in_addr { s_addr: interface }; + + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF, imr_interface) } + } + + pub fn multicast_if_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_IF)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_IF, + interface as c_int, + ) + } + } + + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int, + ) + } + } + + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq) } + } + + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) } + } + + pub fn linger(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(linger2dur( + self.getsockopt(libc::SOL_SOCKET, libc::SO_LINGER)?, + )) + } + } + + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_LINGER, dur2linger(dur)) } + } + + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR, reuse as c_int) } + } + + pub fn reuse_address(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR)?; + Ok(raw != 0) + } + } + + pub fn recv_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF)?; + Ok(raw as usize) + } + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF, size as c_int) + } + } + + pub fn send_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF)?; + Ok(raw as usize) + } + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF, size as c_int) + } + } + + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_KEEPALIVE)?; + if raw == 0 { + return Ok(None); + } + let secs: c_int = self.getsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION)?; + Ok(Some(Duration::new(secs as u64, 0))) + } + } + + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::SOL_SOCKET, + libc::SO_KEEPALIVE, + keepalive.is_some() as c_int, + )?; + if let Some(dur) = keepalive { + // TODO: checked cast here + self.setsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION, dur.as_secs() as c_int)?; + } + Ok(()) + } + } + + #[cfg(all(unix, feature = "reuseport"))] + pub fn reuse_port(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT)?; + Ok(raw != 0) + } + } + + #[cfg(all(unix, feature = "reuseport"))] + pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT, reuse as c_int) } + } + + unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()> + where + T: Copy, + { + let payload = &payload as *const T as *const c_void; + cvt(libc::setsockopt( + self.fd, + opt, + val, + payload, + mem::size_of::<T>() as libc::socklen_t, + ))?; + Ok(()) + } + + unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::<T>() as libc::socklen_t; + cvt(libc::getsockopt( + self.fd, + opt, + val, + &mut slot as *mut _ as *mut _, + &mut len, + ))?; + assert_eq!(len as usize, mem::size_of::<T>()); + Ok(slot) + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + <&Socket>::read(&mut &*self, buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::read( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + ) + })?; + Ok(n as usize) + } + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + <&Socket>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> io::Result<()> { + <&Socket>::flush(&mut &*self) + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.send(buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Socket"); + f.field("fd", &self.fd); + if let Ok(addr) = self.local_addr() { + f.field("local_addr", &addr); + } + if let Ok(addr) = self.peer_addr() { + f.field("peer_addr", &addr); + } + f.finish() + } +} + +impl AsRawFd for Socket { + fn as_raw_fd(&self) -> c_int { + self.fd + } +} + +impl IntoRawFd for Socket { + fn into_raw_fd(self) -> c_int { + let fd = self.fd; + mem::forget(self); + return fd; + } +} + +impl FromRawFd for Socket { + unsafe fn from_raw_fd(fd: c_int) -> Socket { + Socket { fd: fd } + } +} + +impl AsRawFd for crate::Socket { + fn as_raw_fd(&self) -> c_int { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for crate::Socket { + fn into_raw_fd(self) -> c_int { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for crate::Socket { + unsafe fn from_raw_fd(fd: c_int) -> crate::Socket { + crate::Socket { + inner: Socket::from_raw_fd(fd), + } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + unsafe { net::TcpStream::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + unsafe { net::TcpListener::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + unsafe { net::UdpSocket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixStream { + fn from(socket: Socket) -> UnixStream { + unsafe { UnixStream::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixListener { + fn from(socket: Socket) -> UnixListener { + unsafe { UnixListener::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixDatagram { + fn from(socket: Socket) -> UnixDatagram { + unsafe { UnixDatagram::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixStream> for Socket { + fn from(socket: UnixStream) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixListener> for Socket { + fn from(socket: UnixListener) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixDatagram> for Socket { + fn from(socket: UnixDatagram) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +fn max_len() -> usize { + // The maximum read limit on most posix-like systems is `SSIZE_MAX`, + // with the man page quoting that if the count of bytes to read is + // greater than `SSIZE_MAX` the result is "unspecified". + // + // On macOS, however, apparently the 64-bit libc is either buggy or + // intentionally showing odd behavior by rejecting any read with a size + // larger than or equal to INT_MAX. To handle both of these the read + // size is capped on both platforms. + if cfg!(target_os = "macos") { + <c_int>::max_value() as usize - 1 + } else { + <ssize_t>::max_value() as usize + } +} + +fn cvt<T: One + PartialEq + Neg<Output = T>>(t: T) -> io::Result<T> { + let one: T = T::one(); + if t == -one { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +fn cvt_r<F, T>(mut f: F) -> io::Result<T> +where + F: FnMut() -> T, + T: One + PartialEq + Neg<Output = T>, +{ + loop { + match cvt(f()) { + Err(ref e) if e.kind() == ErrorKind::Interrupted => {} + other => return other, + } + } +} + +fn set_cloexec(fd: c_int) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; + let new = previous | libc::FD_CLOEXEC; + if new != previous { + cvt(libc::fcntl(fd, libc::F_SETFD, new))?; + } + Ok(()) + } +} + +fn dur2timeval(dur: Option<Duration>) -> io::Result<libc::timeval> { + match dur { + Some(dur) => { + if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { + libc::time_t::max_value() + } else { + dur.as_secs() as libc::time_t + }; + let mut timeout = libc::timeval { + tv_sec: secs, + tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t, + }; + if timeout.tv_sec == 0 && timeout.tv_usec == 0 { + timeout.tv_usec = 1; + } + Ok(timeout) + } + None => Ok(libc::timeval { + tv_sec: 0, + tv_usec: 0, + }), + } +} + +fn timeval2dur(raw: libc::timeval) -> Option<Duration> { + if raw.tv_sec == 0 && raw.tv_usec == 0 { + None + } else { + let sec = raw.tv_sec as u64; + let nsec = (raw.tv_usec as u32) * 1000; + Some(Duration::new(sec, nsec)) + } +} + +fn to_s_addr(addr: &Ipv4Addr) -> libc::in_addr_t { + let octets = addr.octets(); + crate::hton( + ((octets[0] as libc::in_addr_t) << 24) + | ((octets[1] as libc::in_addr_t) << 16) + | ((octets[2] as libc::in_addr_t) << 8) + | ((octets[3] as libc::in_addr_t) << 0), + ) +} + +fn from_s_addr(in_addr: libc::in_addr_t) -> Ipv4Addr { + let h_addr = crate::ntoh(in_addr); + + let a: u8 = (h_addr >> 24) as u8; + let b: u8 = (h_addr >> 16) as u8; + let c: u8 = (h_addr >> 8) as u8; + let d: u8 = (h_addr >> 0) as u8; + + Ipv4Addr::new(a, b, c, d) +} + +fn to_in6_addr(addr: &Ipv6Addr) -> libc::in6_addr { + let mut ret: libc::in6_addr = unsafe { mem::zeroed() }; + ret.s6_addr = addr.octets(); + return ret; +} + +#[cfg(target_os = "android")] +fn to_ipv6mr_interface(value: u32) -> c_int { + value as c_int +} + +#[cfg(not(target_os = "android"))] +fn to_ipv6mr_interface(value: u32) -> libc::c_uint { + value as libc::c_uint +} + +fn linger2dur(linger_opt: libc::linger) -> Option<Duration> { + if linger_opt.l_onoff == 0 { + None + } else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +fn dur2linger(dur: Option<Duration>) -> libc::linger { + match dur { + Some(d) => libc::linger { + l_onoff: 1, + l_linger: d.as_secs() as c_int, + }, + None => libc::linger { + l_onoff: 0, + l_linger: 0, + }, + } +} + +#[test] +fn test_ip() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + assert_eq!(ip, from_s_addr(to_s_addr(&ip))); +} diff --git a/third_party/rust/socket2/src/sys/windows.rs b/third_party/rust/socket2/src/sys/windows.rs new file mode 100644 index 0000000000..d2c5a882e7 --- /dev/null +++ b/third_party/rust/socket2/src/sys/windows.rs @@ -0,0 +1,977 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::fmt; +use std::io; +use std::io::{Read, Write}; +use std::mem; +use std::net::Shutdown; +use std::net::{self, Ipv4Addr, Ipv6Addr}; +use std::os::windows::prelude::*; +use std::ptr; +use std::sync::{Once, ONCE_INIT}; +use std::time::Duration; + +use winapi::ctypes::{c_char, c_int, c_long, c_ulong}; +use winapi::shared::in6addr::*; +use winapi::shared::inaddr::*; +use winapi::shared::minwindef::DWORD; +use winapi::shared::ntdef::{HANDLE, ULONG}; +use winapi::shared::ws2def; +use winapi::shared::ws2def::*; +use winapi::shared::ws2ipdef::*; +use winapi::um::handleapi::SetHandleInformation; +use winapi::um::processthreadsapi::GetCurrentProcessId; +use winapi::um::winbase::INFINITE; +use winapi::um::winsock2 as sock; + +use crate::SockAddr; + +const HANDLE_FLAG_INHERIT: DWORD = 0x00000001; +const MSG_PEEK: c_int = 0x2; +const SD_BOTH: c_int = 2; +const SD_RECEIVE: c_int = 0; +const SD_SEND: c_int = 1; +const SIO_KEEPALIVE_VALS: DWORD = 0x98000004; +const WSA_FLAG_OVERLAPPED: DWORD = 0x01; + +pub const IPPROTO_ICMP: i32 = ws2def::IPPROTO_ICMP as i32; +pub const IPPROTO_ICMPV6: i32 = ws2def::IPPROTO_ICMPV6 as i32; +pub const IPPROTO_TCP: i32 = ws2def::IPPROTO_TCP as i32; +pub const IPPROTO_UDP: i32 = ws2def::IPPROTO_UDP as i32; +pub const SOCK_SEQPACKET: i32 = ws2def::SOCK_SEQPACKET as i32; +pub const SOCK_RAW: i32 = ws2def::SOCK_RAW as i32; + +#[repr(C)] +struct tcp_keepalive { + onoff: c_ulong, + keepalivetime: c_ulong, + keepaliveinterval: c_ulong, +} + +fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| { + // Initialize winsock through the standard library by just creating a + // dummy socket. Whether this is successful or not we drop the result as + // libstd will be sure to have initialized winsock. + let _ = net::UdpSocket::bind("127.0.0.1:34254"); + }); +} + +fn last_error() -> io::Error { + io::Error::from_raw_os_error(unsafe { sock::WSAGetLastError() }) +} + +pub struct Socket { + socket: sock::SOCKET, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { + init(); + unsafe { + let socket = match sock::WSASocketW( + family, + ty, + protocol, + ptr::null_mut(), + 0, + WSA_FLAG_OVERLAPPED, + ) { + sock::INVALID_SOCKET => return Err(last_error()), + socket => socket, + }; + let socket = Socket::from_raw_socket(socket as RawSocket); + socket.set_no_inherit()?; + Ok(socket) + } + } + + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { + if sock::bind(self.socket, addr.as_ptr(), addr.len()) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { + if sock::listen(self.socket, backlog) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { + if sock::connect(self.socket, addr.as_ptr(), addr.len()) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + self.set_nonblocking(true)?; + let r = self.connect(addr); + self.set_nonblocking(false)?; + + match r { + Ok(()) => return Ok(()), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e), + } + + if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let mut timeout = sock::timeval { + tv_sec: timeout.as_secs() as c_long, + tv_usec: (timeout.subsec_nanos() / 1000) as c_long, + }; + if timeout.tv_sec == 0 && timeout.tv_usec == 0 { + timeout.tv_usec = 1; + } + + let fds = unsafe { + let mut fds = mem::zeroed::<sock::fd_set>(); + fds.fd_count = 1; + fds.fd_array[0] = self.socket; + fds + }; + + let mut writefds = fds; + let mut errorfds = fds; + + match unsafe { sock::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout) } { + sock::SOCKET_ERROR => return Err(io::Error::last_os_error()), + 0 => { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )) + } + _ => { + if writefds.fd_count != 1 { + if let Some(e) = self.take_error()? { + return Err(e); + } + } + Ok(()) + } + } + } + + pub fn local_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + if sock::getsockname(self.socket, &mut storage as *mut _ as *mut _, &mut len) != 0 { + return Err(last_error()); + } + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn peer_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + if sock::getpeername(self.socket, &mut storage as *mut _ as *mut _, &mut len) != 0 { + return Err(last_error()); + } + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn try_clone(&self) -> io::Result<Socket> { + unsafe { + let mut info: sock::WSAPROTOCOL_INFOW = mem::zeroed(); + let r = sock::WSADuplicateSocketW(self.socket, GetCurrentProcessId(), &mut info); + if r != 0 { + return Err(io::Error::last_os_error()); + } + let socket = sock::WSASocketW( + info.iAddressFamily, + info.iSocketType, + info.iProtocol, + &mut info, + 0, + WSA_FLAG_OVERLAPPED, + ); + let socket = match socket { + sock::INVALID_SOCKET => return Err(last_error()), + n => Socket::from_raw_socket(n as RawSocket), + }; + socket.set_no_inherit()?; + Ok(socket) + } + } + + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + let socket = { sock::accept(self.socket, &mut storage as *mut _ as *mut _, &mut len) }; + let socket = match socket { + sock::INVALID_SOCKET => return Err(last_error()), + socket => Socket::from_raw_socket(socket as RawSocket), + }; + socket.set_no_inherit()?; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, len); + Ok((socket, addr)) + } + } + + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_ERROR)?; + if raw == 0 { + Ok(None) + } else { + Ok(Some(io::Error::from_raw_os_error(raw as i32))) + } + } + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + unsafe { + let mut nonblocking = nonblocking as c_ulong; + let r = sock::ioctlsocket(self.socket, sock::FIONBIO as c_int, &mut nonblocking); + if r == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => SD_SEND, + Shutdown::Read => SD_RECEIVE, + Shutdown::Both => SD_BOTH, + }; + if unsafe { sock::shutdown(self.socket, how) == 0 } { + Ok(()) + } else { + Err(last_error()) + } + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::recv( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + 0, + ) + }; + match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), + sock::SOCKET_ERROR => Err(last_error()), + n => Ok(n as usize), + } + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::recv( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + MSG_PEEK, + ) + }; + match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), + sock::SOCKET_ERROR => Err(last_error()), + n => Ok(n as usize), + } + } + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, 0) + } + + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, MSG_PEEK) + } + + fn recvfrom(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut addrlen = mem::size_of_val(&storage) as c_int; + + let n = { + sock::recvfrom( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) + }; + let n = match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => 0, + sock::SOCKET_ERROR => return Err(last_error()), + n => n as usize, + }; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); + Ok((n, addr)) + } + } + + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::send( + self.socket, + buf.as_ptr() as *const c_char, + clamp(buf.len()), + 0, + ) + }; + if n == sock::SOCKET_ERROR { + Err(last_error()) + } else { + Ok(n as usize) + } + } + } + + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + unsafe { + let n = { + sock::sendto( + self.socket, + buf.as_ptr() as *const c_char, + clamp(buf.len()), + 0, + addr.as_ptr(), + addr.len(), + ) + }; + if n == sock::SOCKET_ERROR { + Err(last_error()) + } else { + Ok(n as usize) + } + } + } + + // ================================================ + + pub fn ttl(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_TTL, ttl as c_int) } + } + + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_UNICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_unicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_UNICAST_HOPS, hops as c_int) } + } + + pub fn only_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_V6ONLY)?; + Ok(raw != 0) + } + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_V6ONLY, only_v6 as c_int) } + } + + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_RCVTIMEO)?)) } + } + + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_RCVTIMEO, dur2ms(dur)?) } + } + + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_SNDTIMEO)?)) } + } + + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_SNDTIMEO, dur2ms(dur)?) } + } + + pub fn nodelay(&self) -> io::Result<bool> { + unsafe { + let raw: c_char = self.getsockopt(IPPROTO_TCP, TCP_NODELAY)?; + Ok(raw != 0) + } + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_TCP, TCP_NODELAY, nodelay as c_char) } + } + + pub fn broadcast(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_BROADCAST)?; + Ok(raw != 0) + } + } + + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_BROADCAST, broadcast as c_int) } + } + + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP, multicast_loop_v4 as c_int) } + } + + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, multicast_ttl_v4 as c_int) } + } + + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_HOPS, hops as c_int) } + } + + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + unsafe { + let imr_interface: IN_ADDR = self.getsockopt(IPPROTO_IP, IP_MULTICAST_IF)?; + Ok(from_s_addr(imr_interface.S_un)) + } + } + + pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> { + let interface = to_s_addr(interface); + let imr_interface = IN_ADDR { S_un: interface }; + + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_IF, imr_interface) } + } + + pub fn multicast_if_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_IF)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_IF, interface as c_int) } + } + + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + IPPROTO_IPV6 as c_int, + IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int, + ) + } + } + + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = IP_MREQ { + imr_multiaddr: IN_ADDR { S_un: multiaddr }, + imr_interface: IN_ADDR { S_un: interface }, + }; + unsafe { self.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) } + } + + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = IPV6_MREQ { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: interface, + }; + unsafe { self.setsockopt(IPPROTO_IP, IPV6_ADD_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = IP_MREQ { + imr_multiaddr: IN_ADDR { S_un: multiaddr }, + imr_interface: IN_ADDR { S_un: interface }, + }; + unsafe { self.setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = IPV6_MREQ { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: interface, + }; + unsafe { self.setsockopt(IPPROTO_IP, IPV6_DROP_MEMBERSHIP, mreq) } + } + + pub fn linger(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(linger2dur(self.getsockopt(SOL_SOCKET, SO_LINGER)?)) } + } + + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_LINGER, dur2linger(dur)) } + } + + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_REUSEADDR, reuse as c_int) } + } + + pub fn reuse_address(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_REUSEADDR)?; + Ok(raw != 0) + } + } + + pub fn recv_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_RCVBUF)?; + Ok(raw as usize) + } + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(SOL_SOCKET, SO_RCVBUF, size as c_int) + } + } + + pub fn send_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_SNDBUF)?; + Ok(raw as usize) + } + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(SOL_SOCKET, SO_SNDBUF, size as c_int) + } + } + + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + let mut ka = tcp_keepalive { + onoff: 0, + keepalivetime: 0, + keepaliveinterval: 0, + }; + let n = unsafe { + sock::WSAIoctl( + self.socket, + SIO_KEEPALIVE_VALS, + 0 as *mut _, + 0, + &mut ka as *mut _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0 as *mut _, + None, + ) + }; + if n == 0 { + Ok(if ka.onoff == 0 { + None + } else if ka.keepaliveinterval == 0 { + None + } else { + let seconds = ka.keepaliveinterval / 1000; + let nanos = (ka.keepaliveinterval % 1000) * 1_000_000; + Some(Duration::new(seconds as u64, nanos as u32)) + }) + } else { + Err(last_error()) + } + } + + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + let ms = dur2ms(keepalive)?; + // TODO: checked casts here + let ka = tcp_keepalive { + onoff: keepalive.is_some() as c_ulong, + keepalivetime: ms as c_ulong, + keepaliveinterval: ms as c_ulong, + }; + let mut out = 0; + let n = unsafe { + sock::WSAIoctl( + self.socket, + SIO_KEEPALIVE_VALS, + &ka as *const _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0, + &mut out, + 0 as *mut _, + None, + ) + }; + if n == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + + unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()> + where + T: Copy, + { + let payload = &payload as *const T as *const c_char; + if sock::setsockopt(self.socket, opt, val, payload, mem::size_of::<T>() as c_int) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + + unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::<T>() as c_int; + if sock::getsockopt( + self.socket, + opt, + val, + &mut slot as *mut _ as *mut _, + &mut len, + ) == 0 + { + assert_eq!(len as usize, mem::size_of::<T>()); + Ok(slot) + } else { + Err(last_error()) + } + } + + fn set_no_inherit(&self) -> io::Result<()> { + unsafe { + let r = SetHandleInformation(self.socket as HANDLE, HANDLE_FLAG_INHERIT, 0); + if r == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + <&Socket>::read(&mut &*self, buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.recv(buf) + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + <&Socket>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> io::Result<()> { + <&Socket>::flush(&mut &*self) + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.send(buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Socket"); + f.field("socket", &self.socket); + if let Ok(addr) = self.local_addr() { + f.field("local_addr", &addr); + } + if let Ok(addr) = self.peer_addr() { + f.field("peer_addr", &addr); + } + f.finish() + } +} + +impl AsRawSocket for Socket { + fn as_raw_socket(&self) -> RawSocket { + self.socket as RawSocket + } +} + +impl IntoRawSocket for Socket { + fn into_raw_socket(self) -> RawSocket { + let socket = self.socket; + mem::forget(self); + socket as RawSocket + } +} + +impl FromRawSocket for Socket { + unsafe fn from_raw_socket(socket: RawSocket) -> Socket { + Socket { + socket: socket as sock::SOCKET, + } + } +} + +impl AsRawSocket for crate::Socket { + fn as_raw_socket(&self) -> RawSocket { + self.inner.as_raw_socket() + } +} + +impl IntoRawSocket for crate::Socket { + fn into_raw_socket(self) -> RawSocket { + self.inner.into_raw_socket() + } +} + +impl FromRawSocket for crate::Socket { + unsafe fn from_raw_socket(socket: RawSocket) -> crate::Socket { + crate::Socket { + inner: Socket::from_raw_socket(socket), + } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = sock::closesocket(self.socket); + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + unsafe { net::TcpStream::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + unsafe { net::TcpListener::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + unsafe { net::UdpSocket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +fn clamp(input: usize) -> c_int { + cmp::min(input, <c_int>::max_value() as usize) as c_int +} + +fn dur2ms(dur: Option<Duration>) -> io::Result<DWORD> { + match dur { + Some(dur) => { + // Note that a duration is a (u64, u32) (seconds, nanoseconds) + // pair, and the timeouts in windows APIs are typically u32 + // milliseconds. To translate, we have two pieces to take care of: + // + // * Nanosecond precision is rounded up + // * Greater than u32::MAX milliseconds (50 days) is rounded up to + // INFINITE (never time out). + let ms = dur + .as_secs() + .checked_mul(1000) + .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) + .and_then(|ms| { + ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { + 1 + } else { + 0 + }) + }) + .map(|ms| { + if ms > <DWORD>::max_value() as u64 { + INFINITE + } else { + ms as DWORD + } + }) + .unwrap_or(INFINITE); + if ms == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + Ok(ms) + } + None => Ok(0), + } +} + +fn ms2dur(raw: DWORD) -> Option<Duration> { + if raw == 0 { + None + } else { + let secs = raw / 1000; + let nsec = (raw % 1000) * 1000000; + Some(Duration::new(secs as u64, nsec as u32)) + } +} + +fn to_s_addr(addr: &Ipv4Addr) -> in_addr_S_un { + let octets = addr.octets(); + let res = crate::hton( + ((octets[0] as ULONG) << 24) + | ((octets[1] as ULONG) << 16) + | ((octets[2] as ULONG) << 8) + | ((octets[3] as ULONG) << 0), + ); + let mut new_addr: in_addr_S_un = unsafe { mem::zeroed() }; + unsafe { *(new_addr.S_addr_mut()) = res }; + new_addr +} + +fn from_s_addr(in_addr: in_addr_S_un) -> Ipv4Addr { + let h_addr = crate::ntoh(unsafe { *in_addr.S_addr() }); + + let a: u8 = (h_addr >> 24) as u8; + let b: u8 = (h_addr >> 16) as u8; + let c: u8 = (h_addr >> 8) as u8; + let d: u8 = (h_addr >> 0) as u8; + + Ipv4Addr::new(a, b, c, d) +} + +fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr { + let mut ret_addr: in6_addr_u = unsafe { mem::zeroed() }; + unsafe { *(ret_addr.Byte_mut()) = addr.octets() }; + let mut ret: in6_addr = unsafe { mem::zeroed() }; + ret.u = ret_addr; + ret +} + +fn linger2dur(linger_opt: sock::linger) -> Option<Duration> { + if linger_opt.l_onoff == 0 { + None + } else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +fn dur2linger(dur: Option<Duration>) -> sock::linger { + match dur { + Some(d) => sock::linger { + l_onoff: 1, + l_linger: d.as_secs() as u16, + }, + None => sock::linger { + l_onoff: 0, + l_linger: 0, + }, + } +} + +#[test] +fn test_ip() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + assert_eq!(ip, from_s_addr(to_s_addr(&ip))); +} |