From fea2cb42fc2c31c8a21490567c520a902906dabe Mon Sep 17 00:00:00 2001 From: Jonathan Davies Date: Sun, 21 May 2023 16:30:08 +0100 Subject: [PATCH 01/28] Add support for SO_REUSEPORT_LB --- src/sys/unix.rs | 29 +++++++++++++++++++++++++++++ tests/socket.rs | 2 ++ 2 files changed, 31 insertions(+) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index f4447213..935c6387 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -1983,6 +1983,35 @@ impl crate::Socket { } } + /// Get the value of the `SO_REUSEPORT_LB` option on this socket. + /// + /// For more information about this option, see [`set_reuse_port_lb`]. + /// + /// [`set_reuse_port_lb`]: crate::Socket::set_reuse_port_lb + #[cfg(all(feature = "all", target_os = "freebsd"))] + pub fn reuse_port_lb(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT_LB) + .map(|reuse| reuse != 0) + } + } + + /// Set value for the `SO_REUSEPORT_LB` option on this socket. + /// + /// This allows multiple programs or threads to bind to the same port and + /// incoming connections will be load balanced using a hash function. + #[cfg(all(feature = "all", target_os = "freebsd"))] + pub fn set_reuse_port_lb(&self, reuse: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_REUSEPORT_LB, + reuse as c_int, + ) + } + } + /// Get the value of the `IP_FREEBIND` option on this socket. /// /// For more information about this option, see [`set_freebind`]. diff --git a/tests/socket.rs b/tests/socket.rs index e12fab2d..af601442 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -1228,6 +1228,8 @@ test!(reuse_address, set_reuse_address(true)); not(any(windows, target_os = "solaris", target_os = "illumos")) ))] test!(reuse_port, set_reuse_port(true)); +#[cfg(all(feature = "all", target_os = "freebsd"))] +test!(reuse_port_lb, set_reuse_port_lb(true)); #[cfg(all(feature = "all", unix, not(target_os = "redox")))] test!( #[cfg_attr(target_os = "linux", ignore = "Different value returned")] From 5ca396079f2ac85891ff94b6ce0f95eae94cb069 Mon Sep 17 00:00:00 2001 From: Emils Date: Wed, 22 Mar 2023 09:57:49 +0000 Subject: [PATCH 02/28] Add IPv6 versions of bind_device_by_index --- src/sys/unix.rs | 127 +++++++++++++++++++++++++++++++++++++++++++++++- tests/socket.rs | 55 +++++++++++++++++++-- 2 files changed, 175 insertions(+), 7 deletions(-) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 935c6387..61e3e393 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -1833,6 +1833,33 @@ impl crate::Socket { .map(|_| ()) } + /// This method is deprecated, use [`crate::Socket::bind_device_by_index_v4`]. + #[cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))] + #[cfg_attr( + docsrs, + doc(cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))) + )] + #[deprecated = "Use `Socket::device_index_v4` instead"] + pub fn bind_device_by_index(&self, interface: Option) -> io::Result<()> { + self.bind_device_by_index_v4(interface) + } + /// Sets the value for `IP_BOUND_IF` option on this socket. /// /// If a socket is bound to an interface, only packets received from that @@ -1864,11 +1891,47 @@ impl crate::Socket { ) ))) )] - pub fn bind_device_by_index(&self, interface: Option) -> io::Result<()> { + pub fn bind_device_by_index_v4(&self, interface: Option) -> io::Result<()> { let index = interface.map_or(0, NonZeroU32::get); unsafe { setsockopt(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF, index) } } + /// Sets the value for `IPV6_BOUND_IF` option on this socket. + /// + /// If a socket is bound to an interface, only packets received from that + /// particular interface are processed by the socket. + /// + /// If `interface` is `None`, the binding is removed. If the `interface` + /// index is not valid, an error is returned. + /// + /// One can use [`libc::if_nametoindex`] to convert an interface alias to an + /// index. + #[cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))] + #[cfg_attr( + docsrs, + doc(cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))) + )] + pub fn bind_device_by_index_v6(&self, interface: Option) -> io::Result<()> { + let index = interface.map_or(0, NonZeroU32::get); + unsafe { setsockopt(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF, index) } + } + /// Gets the value for `IP_BOUND_IF` option on this socket, i.e. the index /// for the interface to which the socket is bound. /// @@ -1895,12 +1958,72 @@ impl crate::Socket { ) ))) )] - pub fn device_index(&self) -> io::Result> { + pub fn device_index_v4(&self) -> io::Result> { let index = unsafe { getsockopt::(self.as_raw(), IPPROTO_IP, libc::IP_BOUND_IF)? }; Ok(NonZeroU32::new(index)) } + /// This method is deprecated, use [`crate::Socket::device_index_v4`]. + #[cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))] + #[cfg_attr( + docsrs, + doc(cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))) + )] + #[deprecated = "Use `Socket::device_index_v4` instead"] + pub fn device_index(&self) -> io::Result> { + self.device_index_v4() + } + + /// Gets the value for `IPV6_BOUND_IF` option on this socket, i.e. the index + /// for the interface to which the socket is bound. + /// + /// Returns `None` if the socket is not bound to any interface, otherwise + /// returns an interface index. + #[cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))] + #[cfg_attr( + docsrs, + doc(cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) + ))) + )] + pub fn device_index_v6(&self) -> io::Result> { + let index = unsafe { + getsockopt::(self.as_raw(), IPPROTO_IPV6, libc::IPV6_BOUND_IF)? + }; + Ok(NonZeroU32::new(index)) + } + /// Get the value of the `SO_INCOMING_CPU` option on this socket. /// /// For more information about this option, see [`set_cpu_affinity`]. diff --git a/tests/socket.rs b/tests/socket.rs index af601442..2a3f8063 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -926,7 +926,7 @@ fn device() { const INTERFACES: &[&str] = &["lo\0", "lo0\0", "en0\0"]; let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); - assert_eq!(socket.device_index().unwrap(), None); + assert_eq!(socket.device_index_v4().unwrap(), None); for interface in INTERFACES.iter() { let iface_index = std::num::NonZeroU32::new(unsafe { @@ -936,7 +936,7 @@ fn device() { if iface_index.is_none() { continue; } - if let Err(err) = socket.bind_device_by_index(iface_index) { + if let Err(err) = socket.bind_device_by_index_v4(iface_index) { // Network interface is not available try another. if matches!(err.raw_os_error(), Some(libc::ENODEV)) { eprintln!("error binding to device (`{interface}`): {err}"); @@ -945,10 +945,55 @@ fn device() { panic!("unexpected error binding device: {}", err); } } - assert_eq!(socket.device_index().unwrap(), iface_index); + assert_eq!(socket.device_index_v4().unwrap(), iface_index); - socket.bind_device_by_index(None).unwrap(); - assert_eq!(socket.device_index().unwrap(), None); + socket.bind_device_by_index_v4(None).unwrap(); + assert_eq!(socket.device_index_v4().unwrap(), None); + // Just need to do it with one interface. + return; + } + + panic!("failed to bind to any device."); +} + +#[cfg(all( + feature = "all", + any( + target_os = "ios", + target_os = "macos", + target_os = "tvos", + target_os = "watchos", + ) +))] +#[test] +fn device_v6() { + // Some common network interface on macOS. + const INTERFACES: &[&str] = &["lo\0", "lo0\0", "en0\0"]; + + let socket = Socket::new(Domain::IPV6, Type::STREAM, None).unwrap(); + assert_eq!(socket.device_index_v6().unwrap(), None); + + for interface in INTERFACES.iter() { + let iface_index = std::num::NonZeroU32::new(unsafe { + libc::if_nametoindex(interface.as_ptr() as *const _) + }); + // If no index is returned, try another interface alias + if iface_index.is_none() { + continue; + } + if let Err(err) = socket.bind_device_by_index_v6(iface_index) { + // Network interface is not available try another. + if matches!(err.raw_os_error(), Some(libc::ENODEV)) { + eprintln!("error binding to device (`{interface}`): {err}"); + continue; + } else { + panic!("unexpected error binding device: {}", err); + } + } + assert_eq!(socket.device_index_v6().unwrap(), iface_index); + + socket.bind_device_by_index_v6(None).unwrap(); + assert_eq!(socket.device_index_v6().unwrap(), None); // Just need to do it with one interface. return; } From 51377a08811760f8c4a715ba47fa3b09214fa450 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 2 Jun 2023 22:22:41 +0200 Subject: [PATCH 03/28] Add MsgHdr type This wraps msghdr on Unix and WSAMSG on Windows to be used in send/recvmsg calls. --- src/lib.rs | 100 +++++++++++++++++++++++++++++++++++++++++++++ src/sys/unix.rs | 27 ++++++++++++ src/sys/windows.rs | 22 ++++++++++ 3 files changed, 149 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 6169d9b7..029065ae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,6 +59,12 @@ #![doc(test(attr(deny(warnings))))] use std::fmt; +#[cfg(not(target_os = "redox"))] +use std::io::IoSlice; +#[cfg(not(target_os = "redox"))] +use std::marker::PhantomData; +#[cfg(not(target_os = "redox"))] +use std::mem; use std::mem::MaybeUninit; use std::net::SocketAddr; use std::ops::{Deref, DerefMut}; @@ -562,3 +568,97 @@ impl TcpKeepalive { } } } + +/// Configuration of a `{send,recv}msg` system call. +/// +/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. +#[cfg(not(target_os = "redox"))] +pub struct MsgHdr<'addr, 'bufs, 'control> { + inner: sys::msghdr, + #[allow(clippy::type_complexity)] + _lifetimes: PhantomData<(&'addr SockAddr, &'bufs [&'bufs [u8]], &'control [u8])>, +} + +#[cfg(not(target_os = "redox"))] +impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { + /// Create a new `MsgHdr` with all empty/zero fields. + #[allow(clippy::new_without_default)] + pub fn new() -> MsgHdr<'addr, 'bufs, 'control> { + // SAFETY: all zero is valid for `msghdr` and `WSAMSG`. + MsgHdr { + inner: unsafe { mem::zeroed() }, + _lifetimes: PhantomData, + } + } + + /// Set the address (name) of the message. + /// + /// Corresponds to setting `msg_name` and `msg_namelen` on Unix and `name` + /// and `namelen` on Windows. + pub fn with_addr(mut self, addr: &'addr SockAddr) -> Self { + sys::set_msghdr_name(&mut self.inner, addr); + self + } + + /// Set the mutable address (name) of the message. Same as [`with_addr`], + /// but with a mutable address. + /// + /// [`with_addr`]: MsgHdr::with_addr + pub fn with_addr_mut(mut self, addr: &'addr mut SockAddr) -> Self { + sys::set_msghdr_name(&mut self.inner, addr); + self + } + + /// Set the buffer(s) of the message. + /// + /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` + /// and `dwBufferCount` on Windows. + pub fn with_buffers(mut self, bufs: &'bufs [IoSlice<'bufs>]) -> Self { + let ptr = bufs.as_ptr().cast_mut().cast(); + sys::set_msghdr_iov(&mut self.inner, ptr, bufs.len()); + self + } + + /// Set the mutable buffer(s) of the message. Same as [`with_buffers`], but + /// with mutable buffers. + /// + /// [`with_buffers`]: MsgHdr::with_buffers + pub fn with_buffers_mut(mut self, bufs: &'bufs mut [MaybeUninitSlice<'bufs>]) -> Self { + sys::set_msghdr_iov(&mut self.inner, bufs.as_mut_ptr().cast(), bufs.len()); + self + } + + /// Set the control buffer of the message. + /// + /// Corresponds to setting `msg_control` and `msg_controllen` on Unix and + /// `Control` on Windows. + pub fn with_control(mut self, buf: &'control [u8]) -> Self { + let ptr = buf.as_ptr().cast_mut().cast(); + sys::set_msghdr_control(&mut self.inner, ptr, buf.len()); + self + } + + /// Set the mutable control buffer of the message. Same as [`with_control`], + /// but with a mutable buffers. + /// + /// [`with_control`]: MsgHdr::with_control + pub fn with_control_mut(mut self, buf: &'control mut [u8]) -> Self { + sys::set_msghdr_control(&mut self.inner, buf.as_mut_ptr().cast(), buf.len()); + self + } + + /// Set the flags of the message. + /// + /// Corresponds to setting `msg_flags` on Unix and `dwFlags` on Windows. + pub fn with_flags(mut self, flags: sys::c_int) -> Self { + sys::set_msghdr_flags(&mut self.inner, flags); + self + } +} + +#[cfg(not(target_os = "redox"))] +impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + "MsgHdr".fmt(fmt) + } +} diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 61e3e393..d766b00e 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -642,6 +642,33 @@ pub(crate) fn unix_sockaddr(path: &Path) -> io::Result { Ok(unsafe { SockAddr::new(storage, len as socklen_t) }) } +// Used in `MsgHdr`. +#[cfg(not(target_os = "redox"))] +pub(crate) use libc::msghdr; + +#[cfg(not(target_os = "redox"))] +pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { + msg.msg_name = name.as_ptr().cast_mut().cast(); + msg.msg_namelen = name.len(); +} + +#[cfg(not(target_os = "redox"))] +pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut libc::iovec, len: usize) { + msg.msg_iov = ptr; + msg.msg_iovlen = len as _; +} + +#[cfg(not(target_os = "redox"))] +pub(crate) fn set_msghdr_control(msg: &mut msghdr, ptr: *mut libc::c_void, len: usize) { + msg.msg_control = ptr; + msg.msg_controllen = len as _; +} + +#[cfg(not(target_os = "redox"))] +pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: libc::c_int) { + msg.msg_flags = flags; +} + /// Unix only API. impl SockAddr { /// Constructs a `SockAddr` with the family `AF_VSOCK` and the provided CID/port. diff --git a/src/sys/windows.rs b/src/sys/windows.rs index a4d07e2c..bfeb5dd3 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -187,6 +187,28 @@ impl<'a> MaybeUninitSlice<'a> { } } +// Used in `MsgHdr`. +pub(crate) use windows_sys::Win32::Networking::WinSock::WSAMSG as msghdr; + +pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { + msg.name = name.as_ptr().cast_mut().cast(); + msg.namelen = name.len(); +} + +pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut WSABUF, len: usize) { + msg.lpBuffers = ptr; + msg.dwBufferCount = len as _; +} + +pub(crate) fn set_msghdr_control(msg: &mut msghdr, ptr: *mut u8, len: usize) { + msg.Control.buf = ptr; + msg.Control.len = len as u32; +} + +pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: c_int) { + msg.dwFlags = flags as u32; +} + fn init() { static INIT: Once = Once::new(); From 56806e8cd6b6134e245295e43b8dc4117889fc0b Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 2 Jun 2023 22:35:53 +0200 Subject: [PATCH 04/28] Use MsgHdr in send(_to)_vectored --- src/sockaddr.rs | 6 ------ src/sys/unix.rs | 32 ++++++++------------------------ 2 files changed, 8 insertions(+), 30 deletions(-) diff --git a/src/sockaddr.rs b/src/sockaddr.rs index 53342270..5922ec06 100644 --- a/src/sockaddr.rs +++ b/src/sockaddr.rs @@ -205,12 +205,6 @@ impl SockAddr { self.storage.ss_family == AF_UNIX as sa_family_t } - /// Returns a raw pointer to the address storage. - #[cfg(all(unix, not(target_os = "redox")))] - pub(crate) const fn as_storage_ptr(&self) -> *const sockaddr_storage { - &self.storage - } - /// Returns this address as a `SocketAddr` if it is in the `AF_INET` (IPv4) /// or `AF_INET6` (IPv6) family, otherwise returns `None`. pub fn as_socket(&self) -> Option { diff --git a/src/sys/unix.rs b/src/sys/unix.rs index d766b00e..f5a37799 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -70,9 +70,9 @@ use std::{io, slice}; use libc::ssize_t; use libc::{in6_addr, in_addr}; -#[cfg(not(target_os = "redox"))] -use crate::RecvFlags; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; +#[cfg(not(target_os = "redox"))] +use crate::{MsgHdr, RecvFlags}; pub(crate) use libc::c_int; @@ -1036,7 +1036,8 @@ pub(crate) fn send(fd: Socket, buf: &[u8], flags: c_int) -> io::Result { #[cfg(not(target_os = "redox"))] pub(crate) fn send_vectored(fd: Socket, bufs: &[IoSlice<'_>], flags: c_int) -> io::Result { - sendmsg(fd, ptr::null(), 0, bufs, flags) + let msg = MsgHdr::new().with_buffers(bufs); + sendmsg(fd, &msg, flags) } pub(crate) fn send_to(fd: Socket, buf: &[u8], addr: &SockAddr, flags: c_int) -> io::Result { @@ -1058,30 +1059,13 @@ pub(crate) fn send_to_vectored( addr: &SockAddr, flags: c_int, ) -> io::Result { - sendmsg(fd, addr.as_storage_ptr(), addr.len(), bufs, flags) + let msg = MsgHdr::new().with_addr(addr).with_buffers(bufs); + sendmsg(fd, &msg, flags) } -/// Returns the (bytes received, sending address len, `RecvFlags`). #[cfg(not(target_os = "redox"))] -#[allow(clippy::unnecessary_cast)] // For `IovLen::MAX as usize` (Already `usize` on Linux). -fn sendmsg( - fd: Socket, - msg_name: *const sockaddr_storage, - msg_namelen: socklen_t, - bufs: &[IoSlice<'_>], - flags: c_int, -) -> io::Result { - // libc::msghdr contains unexported padding fields on Fuchsia. - let mut msg: libc::msghdr = unsafe { mem::zeroed() }; - // Safety: we're creating a `*mut` pointer from a reference, which is UB - // once actually used. However the OS should not write to it in the - // `sendmsg` system call. - msg.msg_name = (msg_name as *mut sockaddr_storage).cast(); - msg.msg_namelen = msg_namelen; - // Safety: Same as above about `*const` -> `*mut`. - msg.msg_iov = bufs.as_ptr() as *mut _; - msg.msg_iovlen = min(bufs.len(), IovLen::MAX as usize) as IovLen; - syscall!(sendmsg(fd, &msg, flags)).map(|n| n as usize) +fn sendmsg(fd: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result { + syscall!(sendmsg(fd, &msg.inner, flags)).map(|n| n as usize) } /// Wrapper around `getsockopt` to deal with platform specific timeouts. From 0cd03ccb348135b10880d24c4e54034db8eb3931 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 2 Jun 2023 22:50:26 +0200 Subject: [PATCH 05/28] Add Socket::sendmsg Wrapper around sendmsg(2). --- src/socket.rs | 10 +++++++++- src/sys/unix.rs | 2 +- src/sys/windows.rs | 19 ++++++++++++++++++- tests/socket.rs | 18 ++++++++++++++++++ 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/src/socket.rs b/src/socket.rs index e51b2df9..cfd523eb 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -23,7 +23,7 @@ use std::time::Duration; use crate::sys::{self, c_int, getsockopt, setsockopt, Bool}; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; #[cfg(not(target_os = "redox"))] -use crate::{MaybeUninitSlice, RecvFlags}; +use crate::{MaybeUninitSlice, MsgHdr, RecvFlags}; /// Owned wrapper around a system socket. /// @@ -725,6 +725,14 @@ impl Socket { ) -> io::Result { sys::send_to_vectored(self.as_raw(), bufs, addr, flags) } + + /// Send a message on a socket using a message structure. + #[doc = man_links!(sendmsg(2))] + #[cfg(not(target_os = "redox"))] + #[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))] + pub fn sendmsg(&self, msg: &MsgHdr<'_, '_, '_>, flags: sys::c_int) -> io::Result { + sys::sendmsg(self.as_raw(), msg, flags) + } } /// Set `SOCK_CLOEXEC` and `NO_HANDLE_INHERIT` on the `ty`pe on platforms that diff --git a/src/sys/unix.rs b/src/sys/unix.rs index f5a37799..773267a3 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -1064,7 +1064,7 @@ pub(crate) fn send_to_vectored( } #[cfg(not(target_os = "redox"))] -fn sendmsg(fd: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result { +pub(crate) fn sendmsg(fd: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result { syscall!(sendmsg(fd, &msg.inner, flags)).map(|n| n as usize) } diff --git a/src/sys/windows.rs b/src/sys/windows.rs index bfeb5dd3..d9c35412 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -28,7 +28,7 @@ use windows_sys::Win32::Networking::WinSock::{ }; use windows_sys::Win32::System::Threading::INFINITE; -use crate::{RecvFlags, SockAddr, TcpKeepalive, Type}; +use crate::{MsgHdr, RecvFlags, SockAddr, TcpKeepalive, Type}; #[allow(non_camel_case_types)] pub(crate) type c_int = std::os::raw::c_int; @@ -659,6 +659,23 @@ pub(crate) fn send_to_vectored( .map(|_| nsent as usize) } +pub(crate) fn sendmsg(socket: Socket, msg: &MsgHdr<'_, '_, '_>, flags: c_int) -> io::Result { + let mut nsent = 0; + syscall!( + WSASendMsg( + socket, + &msg.inner, + flags as u32, + &mut nsent, + ptr::null_mut(), + None, + ), + PartialEq::eq, + SOCKET_ERROR + ) + .map(|_| nsent as usize) +} + /// Wrapper around `getsockopt` to deal with platform specific timeouts. pub(crate) fn timeout_opt(fd: Socket, lvl: c_int, name: i32) -> io::Result> { unsafe { getsockopt(fd, lvl, name).map(from_ms) } diff --git a/tests/socket.rs b/tests/socket.rs index 2a3f8063..79451da4 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -703,6 +703,24 @@ fn send_from_recv_to_vectored() { assert_eq!(unsafe { assume_init(&swear) }, b"swear"); } +#[test] +#[cfg(not(target_os = "redox"))] +fn sendmsg() { + let (socket_a, socket_b) = udp_pair_unconnected(); + + const DATA: &[u8] = b"Hello, World!"; + + let bufs = &[IoSlice::new(DATA)]; + let addr_b = socket_b.local_addr().unwrap(); + let msg = socket2::MsgHdr::new().with_addr(&addr_b).with_buffers(bufs); + let sent = socket_a.sendmsg(&msg, 0).unwrap(); + assert_eq!(sent, DATA.len()); + + let mut buf = Vec::with_capacity(DATA.len() + 1); + let received = socket_b.recv(buf.spare_capacity_mut()).unwrap(); + assert_eq!(received, DATA.len()); +} + #[test] #[cfg(not(target_os = "redox"))] fn recv_vectored_truncated() { From 457d3267b4d533f7c364744931835795ac09f080 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 2 Jun 2023 22:54:41 +0200 Subject: [PATCH 06/28] Simplify two cfg attributes --- src/sys/unix.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 773267a3..a733f30a 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -1831,8 +1831,8 @@ impl crate::Socket { /// Sets the value for the `SO_SETFIB` option on this socket. /// /// Bind socket to the specified forwarding table (VRF) on a FreeBSD. - #[cfg(all(feature = "all", any(target_os = "freebsd")))] - #[cfg_attr(docsrs, doc(cfg(all(feature = "all", any(target_os = "freebsd")))))] + #[cfg(all(feature = "all", target_os = "freebsd"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "freebsd"))))] pub fn set_fib(&self, fib: u32) -> io::Result<()> { syscall!(setsockopt( self.as_raw(), @@ -2587,8 +2587,8 @@ impl crate::Socket { /// Therefore, there is no corresponding `set` helper. /// /// For more information about this option, see [Linux patch](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=5daab9db7b65df87da26fd8cfa695fb9546a1ddb) - #[cfg(all(feature = "all", any(target_os = "linux")))] - #[cfg_attr(docsrs, doc(cfg(all(feature = "all", any(target_os = "linux")))))] + #[cfg(all(feature = "all", target_os = "linux"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "all", target_os = "linux"))))] pub fn cookie(&self) -> io::Result { unsafe { getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_COOKIE) } } From 49b844fa0320127daa943e0ea7107698618ce594 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Sat, 3 Jun 2023 16:00:24 +0200 Subject: [PATCH 07/28] Don't use MsgHdr for recvmsg Instead we'll create a separate MsgHdrMut for recvmsg, similar to IoSlice and IoSliceMut. --- src/lib.rs | 34 ++++------------------------------ 1 file changed, 4 insertions(+), 30 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 029065ae..269fbfe4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -569,14 +569,15 @@ impl TcpKeepalive { } } -/// Configuration of a `{send,recv}msg` system call. +/// Configuration of a `sendmsg(2)` system call. /// -/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. +/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdrMut`] +/// for the variant used by `recvmsg(2)`. #[cfg(not(target_os = "redox"))] pub struct MsgHdr<'addr, 'bufs, 'control> { inner: sys::msghdr, #[allow(clippy::type_complexity)] - _lifetimes: PhantomData<(&'addr SockAddr, &'bufs [&'bufs [u8]], &'control [u8])>, + _lifetimes: PhantomData<(&'addr SockAddr, &'bufs IoSlice<'bufs>, &'control [u8])>, } #[cfg(not(target_os = "redox"))] @@ -600,15 +601,6 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { self } - /// Set the mutable address (name) of the message. Same as [`with_addr`], - /// but with a mutable address. - /// - /// [`with_addr`]: MsgHdr::with_addr - pub fn with_addr_mut(mut self, addr: &'addr mut SockAddr) -> Self { - sys::set_msghdr_name(&mut self.inner, addr); - self - } - /// Set the buffer(s) of the message. /// /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` @@ -619,15 +611,6 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { self } - /// Set the mutable buffer(s) of the message. Same as [`with_buffers`], but - /// with mutable buffers. - /// - /// [`with_buffers`]: MsgHdr::with_buffers - pub fn with_buffers_mut(mut self, bufs: &'bufs mut [MaybeUninitSlice<'bufs>]) -> Self { - sys::set_msghdr_iov(&mut self.inner, bufs.as_mut_ptr().cast(), bufs.len()); - self - } - /// Set the control buffer of the message. /// /// Corresponds to setting `msg_control` and `msg_controllen` on Unix and @@ -638,15 +621,6 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { self } - /// Set the mutable control buffer of the message. Same as [`with_control`], - /// but with a mutable buffers. - /// - /// [`with_control`]: MsgHdr::with_control - pub fn with_control_mut(mut self, buf: &'control mut [u8]) -> Self { - sys::set_msghdr_control(&mut self.inner, buf.as_mut_ptr().cast(), buf.len()); - self - } - /// Set the flags of the message. /// /// Corresponds to setting `msg_flags` on Unix and `dwFlags` on Windows. From 0e2f962985ea3ddc66630915eae6f866da6cdc80 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Sat, 3 Jun 2023 16:12:10 +0200 Subject: [PATCH 08/28] Add MsgHdrMut type To be used in recvmsg(2) calls. --- src/lib.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++ src/sys/unix.rs | 5 ++++ src/sys/windows.rs | 6 ++++- 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 269fbfe4..c5ce6bb1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -636,3 +636,70 @@ impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> { "MsgHdr".fmt(fmt) } } + +/// Configuration of a `recvmsg(2)` system call. +/// +/// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdr`] for +/// the variant used by `sendmsg(2)`. +#[cfg(not(target_os = "redox"))] +pub struct MsgHdrMut<'addr, 'bufs, 'control> { + inner: sys::msghdr, + #[allow(clippy::type_complexity)] + _lifetimes: PhantomData<( + &'addr mut SockAddr, + &'bufs mut MaybeUninitSlice<'bufs>, + &'control mut [u8], + )>, +} + +#[cfg(not(target_os = "redox"))] +impl<'addr, 'bufs, 'control> MsgHdrMut<'addr, 'bufs, 'control> { + /// Create a new `MsgHdrMut` with all empty/zero fields. + #[allow(clippy::new_without_default)] + pub fn new() -> MsgHdrMut<'addr, 'bufs, 'control> { + // SAFETY: all zero is valid for `msghdr` and `WSAMSG`. + MsgHdrMut { + inner: unsafe { mem::zeroed() }, + _lifetimes: PhantomData, + } + } + + /// Set the mutable address (name) of the message. + /// + /// Corresponds to setting `msg_name` and `msg_namelen` on Unix and `name` + /// and `namelen` on Windows. + pub fn with_addr(mut self, addr: &'addr mut SockAddr) -> Self { + sys::set_msghdr_name(&mut self.inner, addr); + self + } + + /// Set the mutable buffer(s) of the message. + /// + /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` + /// and `dwBufferCount` on Windows. + pub fn with_buffers(mut self, bufs: &'bufs mut [MaybeUninitSlice<'bufs>]) -> Self { + sys::set_msghdr_iov(&mut self.inner, bufs.as_mut_ptr().cast(), bufs.len()); + self + } + + /// Set the mutable control buffer of the message. + /// + /// Corresponds to setting `msg_control` and `msg_controllen` on Unix and + /// `Control` on Windows. + pub fn with_control(mut self, buf: &'control mut [MaybeUninit]) -> Self { + sys::set_msghdr_control(&mut self.inner, buf.as_mut_ptr().cast(), buf.len()); + self + } + + /// Returns the flags of the message. + pub fn flags(&self) -> RecvFlags { + sys::msghdr_flags(&self.inner) + } +} + +#[cfg(not(target_os = "redox"))] +impl<'name, 'bufs, 'control> fmt::Debug for MsgHdrMut<'name, 'bufs, 'control> { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + "MsgHdrMut".fmt(fmt) + } +} diff --git a/src/sys/unix.rs b/src/sys/unix.rs index a733f30a..42bac391 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -669,6 +669,11 @@ pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: libc::c_int) { msg.msg_flags = flags; } +#[cfg(not(target_os = "redox"))] +pub(crate) fn msghdr_flags(msg: &msghdr) -> RecvFlags { + RecvFlags(msg.msg_flags) +} + /// Unix only API. impl SockAddr { /// Constructs a `SockAddr` with the family `AF_VSOCK` and the provided CID/port. diff --git a/src/sys/windows.rs b/src/sys/windows.rs index d9c35412..5b2dc186 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -28,7 +28,7 @@ use windows_sys::Win32::Networking::WinSock::{ }; use windows_sys::Win32::System::Threading::INFINITE; -use crate::{MsgHdr, RecvFlags, SockAddr, TcpKeepalive, Type}; +use crate::{MsgHdr, MsgHdrMut, RecvFlags, SockAddr, TcpKeepalive, Type}; #[allow(non_camel_case_types)] pub(crate) type c_int = std::os::raw::c_int; @@ -209,6 +209,10 @@ pub(crate) fn set_msghdr_flags(msg: &mut msghdr, flags: c_int) { msg.dwFlags = flags as u32; } +pub(crate) fn msghdr_flags(msg: &msghdr) -> RecvFlags { + RecvFlags(msg.dwFlags as c_int) +} + fn init() { static INIT: Once = Once::new(); From 2ff147e2dedbe93bbfb6067358a92d3783b67922 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Sat, 3 Jun 2023 17:34:20 +0200 Subject: [PATCH 09/28] Use proper truncation in set_msghdr_iov --- src/sys/unix.rs | 2 +- src/sys/windows.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 42bac391..f1e83266 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -655,7 +655,7 @@ pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { #[cfg(not(target_os = "redox"))] pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut libc::iovec, len: usize) { msg.msg_iov = ptr; - msg.msg_iovlen = len as _; + msg.msg_iovlen = min(len, IovLen::MAX as usize) as IovLen; } #[cfg(not(target_os = "redox"))] diff --git a/src/sys/windows.rs b/src/sys/windows.rs index 5b2dc186..cf929c14 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -197,7 +197,7 @@ pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut WSABUF, len: usize) { msg.lpBuffers = ptr; - msg.dwBufferCount = len as _; + msg.dwBufferCount = min(len, u32::MAX as usize) as u32; } pub(crate) fn set_msghdr_control(msg: &mut msghdr, ptr: *mut u8, len: usize) { From 008603dd80d6318bd565ba4786e47e3cba3f0761 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Sat, 3 Jun 2023 17:37:45 +0200 Subject: [PATCH 10/28] Use MsgHdrMut in recvmsg --- src/lib.rs | 4 ++-- src/sys/unix.rs | 51 +++++++++++++++++-------------------------------- 2 files changed, 20 insertions(+), 35 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c5ce6bb1..f657505b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -605,7 +605,7 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { /// /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` /// and `dwBufferCount` on Windows. - pub fn with_buffers(mut self, bufs: &'bufs [IoSlice<'bufs>]) -> Self { + pub fn with_buffers(mut self, bufs: &'bufs [IoSlice<'_>]) -> Self { let ptr = bufs.as_ptr().cast_mut().cast(); sys::set_msghdr_iov(&mut self.inner, ptr, bufs.len()); self @@ -677,7 +677,7 @@ impl<'addr, 'bufs, 'control> MsgHdrMut<'addr, 'bufs, 'control> { /// /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` /// and `dwBufferCount` on Windows. - pub fn with_buffers(mut self, bufs: &'bufs mut [MaybeUninitSlice<'bufs>]) -> Self { + pub fn with_buffers(mut self, bufs: &'bufs mut [MaybeUninitSlice<'_>]) -> Self { sys::set_msghdr_iov(&mut self.inner, bufs.as_mut_ptr().cast(), bufs.len()); self } diff --git a/src/sys/unix.rs b/src/sys/unix.rs index f1e83266..2d4ec8bb 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -72,7 +72,7 @@ use libc::{in6_addr, in_addr}; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; #[cfg(not(target_os = "redox"))] -use crate::{MsgHdr, RecvFlags}; +use crate::{MsgHdr, MsgHdrMut, RecvFlags}; pub(crate) use libc::c_int; @@ -982,7 +982,9 @@ pub(crate) fn recv_vectored( bufs: &mut [crate::MaybeUninitSlice<'_>], flags: c_int, ) -> io::Result<(usize, RecvFlags)> { - recvmsg(fd, ptr::null_mut(), bufs, flags).map(|(n, _, recv_flags)| (n, recv_flags)) + let mut msg = MsgHdrMut::new().with_buffers(bufs); + let n = recvmsg(fd, &mut msg, flags)?; + Ok((n, msg.flags())) } #[cfg(not(target_os = "redox"))] @@ -991,42 +993,25 @@ pub(crate) fn recv_from_vectored( bufs: &mut [crate::MaybeUninitSlice<'_>], flags: c_int, ) -> io::Result<(usize, RecvFlags, SockAddr)> { - // Safety: `recvmsg` initialises the address storage and we set the length + let mut msg = MsgHdrMut::new().with_buffers(bufs); + // SAFETY: `recvmsg` initialises the address storage and we set the length // manually. - unsafe { + let (n, addr) = unsafe { SockAddr::try_init(|storage, len| { - recvmsg(fd, storage, bufs, flags).map(|(n, addrlen, recv_flags)| { - // Set the correct address length. - *len = addrlen; - (n, recv_flags) - }) - }) - } - .map(|((n, recv_flags), addr)| (n, recv_flags, addr)) + msg.inner.msg_name = storage.cast(); + msg.inner.msg_namelen = *len; + let n = recvmsg(fd, &mut msg, flags)?; + // Set the correct address length. + *len = msg.inner.msg_namelen; + Ok(n) + })? + }; + Ok((n, msg.flags(), addr)) } -/// Returns the (bytes received, sending address len, `RecvFlags`). #[cfg(not(target_os = "redox"))] -#[allow(clippy::unnecessary_cast)] // For `IovLen::MAX as usize` (Already `usize` on Linux). -fn recvmsg( - fd: Socket, - msg_name: *mut sockaddr_storage, - bufs: &mut [crate::MaybeUninitSlice<'_>], - flags: c_int, -) -> io::Result<(usize, libc::socklen_t, RecvFlags)> { - let msg_namelen = if msg_name.is_null() { - 0 - } else { - size_of::() as libc::socklen_t - }; - // libc::msghdr contains unexported padding fields on Fuchsia. - let mut msg: libc::msghdr = unsafe { mem::zeroed() }; - msg.msg_name = msg_name.cast(); - msg.msg_namelen = msg_namelen; - msg.msg_iov = bufs.as_mut_ptr().cast(); - msg.msg_iovlen = min(bufs.len(), IovLen::MAX as usize) as IovLen; - syscall!(recvmsg(fd, &mut msg, flags)) - .map(|n| (n as usize, msg.msg_namelen, RecvFlags(msg.msg_flags))) +fn recvmsg(fd: Socket, msg: &mut MsgHdrMut<'_, '_, '_>, flags: c_int) -> io::Result { + syscall!(recvmsg(fd, &mut msg.inner, flags)).map(|n| n as usize) } pub(crate) fn send(fd: Socket, buf: &[u8], flags: c_int) -> io::Result { From fc41670adc1eaf4dffa068e62efa76ec7e776c77 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Wed, 7 Jun 2023 13:10:59 +0200 Subject: [PATCH 11/28] Add Socket::recvmsg --- src/socket.rs | 15 +++++++++++++++ src/sys/unix.rs | 6 +++++- src/sys/windows.rs | 2 +- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/socket.rs b/src/socket.rs index cfd523eb..fe34bea0 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -21,6 +21,8 @@ use std::os::windows::io::{FromRawSocket, IntoRawSocket}; use std::time::Duration; use crate::sys::{self, c_int, getsockopt, setsockopt, Bool}; +#[cfg(all(unix, not(target_os = "redox")))] +use crate::MsgHdrMut; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; #[cfg(not(target_os = "redox"))] use crate::{MaybeUninitSlice, MsgHdr, RecvFlags}; @@ -627,6 +629,19 @@ impl Socket { sys::peek_sender(self.as_raw()) } + /// Receive a message from a socket using a message structure. + /// + /// This is not supported on Windows as calling `WSARecvMsg` (the `recvmsg` + /// equivalent) is not straight forward on Windows. See + /// + /// for an example (in C++). + #[doc = man_links!(recvmsg(2))] + #[cfg(all(unix, not(target_os = "redox")))] + #[cfg_attr(docsrs, doc(cfg(all(unix, not(target_os = "redox")))))] + pub fn recvmsg(&self, msg: &mut MsgHdrMut<'_, '_, '_>, flags: sys::c_int) -> io::Result { + sys::recvmsg(self.as_raw(), msg, flags) + } + /// Sends data on the socket to a connected peer. /// /// This is typically used on TCP sockets or datagram sockets which have diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 2d4ec8bb..3b8f385f 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -1010,7 +1010,11 @@ pub(crate) fn recv_from_vectored( } #[cfg(not(target_os = "redox"))] -fn recvmsg(fd: Socket, msg: &mut MsgHdrMut<'_, '_, '_>, flags: c_int) -> io::Result { +pub(crate) fn recvmsg( + fd: Socket, + msg: &mut MsgHdrMut<'_, '_, '_>, + flags: c_int, +) -> io::Result { syscall!(recvmsg(fd, &mut msg.inner, flags)).map(|n| n as usize) } diff --git a/src/sys/windows.rs b/src/sys/windows.rs index cf929c14..296b3dd2 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -28,7 +28,7 @@ use windows_sys::Win32::Networking::WinSock::{ }; use windows_sys::Win32::System::Threading::INFINITE; -use crate::{MsgHdr, MsgHdrMut, RecvFlags, SockAddr, TcpKeepalive, Type}; +use crate::{MsgHdr, RecvFlags, SockAddr, TcpKeepalive, Type}; #[allow(non_camel_case_types)] pub(crate) type c_int = std::os::raw::c_int; From 54e721551fc391c0bbccfcf57717daef67e04c33 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Wed, 7 Jun 2023 13:16:40 +0200 Subject: [PATCH 12/28] Support MSRV 1.63 pointer::cast_mut was stablised in 1.65, so it's too new. --- src/lib.rs | 4 ++-- src/sys/unix.rs | 3 ++- src/sys/windows.rs | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f657505b..7d417d81 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -606,7 +606,7 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { /// Corresponds to setting `msg_iov` and `msg_iovlen` on Unix and `lpBuffers` /// and `dwBufferCount` on Windows. pub fn with_buffers(mut self, bufs: &'bufs [IoSlice<'_>]) -> Self { - let ptr = bufs.as_ptr().cast_mut().cast(); + let ptr = bufs.as_ptr() as *mut _; sys::set_msghdr_iov(&mut self.inner, ptr, bufs.len()); self } @@ -616,7 +616,7 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { /// Corresponds to setting `msg_control` and `msg_controllen` on Unix and /// `Control` on Windows. pub fn with_control(mut self, buf: &'control [u8]) -> Self { - let ptr = buf.as_ptr().cast_mut().cast(); + let ptr = buf.as_ptr() as *mut _; sys::set_msghdr_control(&mut self.inner, ptr, buf.len()); self } diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 3b8f385f..a388bdc6 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -648,11 +648,12 @@ pub(crate) use libc::msghdr; #[cfg(not(target_os = "redox"))] pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { - msg.msg_name = name.as_ptr().cast_mut().cast(); + msg.msg_name = name.as_ptr() as *mut _; msg.msg_namelen = name.len(); } #[cfg(not(target_os = "redox"))] +#[allow(clippy::unnecessary_cast)] // IovLen type can be `usize`. pub(crate) fn set_msghdr_iov(msg: &mut msghdr, ptr: *mut libc::iovec, len: usize) { msg.msg_iov = ptr; msg.msg_iovlen = min(len, IovLen::MAX as usize) as IovLen; diff --git a/src/sys/windows.rs b/src/sys/windows.rs index 296b3dd2..0d22a649 100644 --- a/src/sys/windows.rs +++ b/src/sys/windows.rs @@ -191,7 +191,7 @@ impl<'a> MaybeUninitSlice<'a> { pub(crate) use windows_sys::Win32::Networking::WinSock::WSAMSG as msghdr; pub(crate) fn set_msghdr_name(msg: &mut msghdr, name: &SockAddr) { - msg.name = name.as_ptr().cast_mut().cast(); + msg.name = name.as_ptr() as *mut _; msg.namelen = name.len(); } From 9ce984da8c84df59b22446ef3d28a6c6de7039b9 Mon Sep 17 00:00:00 2001 From: Jonsen Yang Date: Tue, 13 Jun 2023 23:04:15 +0800 Subject: [PATCH 13/28] Add support for IPPROTO_DIVERT --- src/lib.rs | 4 ++++ src/sys/unix.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 7d417d81..ae64ecf2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -339,6 +339,10 @@ impl Protocol { ) ))] pub const UDPLITE: Protocol = Protocol(sys::IPPROTO_UDPLITE); + + /// Protocol corresponding to `DIVERT`. + #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))] + pub const DIVERT: Protocol = Protocol(sys::IPPROTO_DIVERT); } impl From for Protocol { diff --git a/src/sys/unix.rs b/src/sys/unix.rs index a388bdc6..808c6ef1 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -105,6 +105,8 @@ pub(crate) use libc::IPPROTO_SCTP; pub(crate) use libc::IPPROTO_UDPLITE; pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP}; // Used in `SockAddr`. +#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))] +pub(crate) use libc::IPPROTO_DIVERT; pub(crate) use libc::{ sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, socklen_t, }; @@ -520,6 +522,8 @@ impl_debug!( ) ))] libc::IPPROTO_UDPLITE, + #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "openbsd")))] + libc::IPPROTO_DIVERT, ); /// Unix-only API. From 48e38944c1ffc7466f5f47bb5579a66ea5455a58 Mon Sep 17 00:00:00 2001 From: Johnathan Sharratt Date: Fri, 27 May 2022 00:21:13 +0200 Subject: [PATCH 14/28] Implemented full networking for WebAssembly (WASIX) --- Cargo.toml | 4 +- README.md | 8 + src/lib.rs | 30 +- src/sockaddr.rs | 11 +- src/socket.rs | 27 +- src/sockref.rs | 6 +- src/sys/unix.rs | 10 +- src/sys/wasi.rs | 1253 +++++++++++++++++++++++++++++++++++++++++++++++ tests/socket.rs | 26 +- 9 files changed, 1340 insertions(+), 35 deletions(-) create mode 100644 src/sys/wasi.rs diff --git a/Cargo.toml b/Cargo.toml index fff31e45..2b4ad029 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,8 +34,8 @@ targets = ["aarch64-apple-ios", "aarch64-linux-android", "x86_64-apple-darwin", [package.metadata.playground] features = ["all"] -[target."cfg(unix)".dependencies] -libc = "0.2.141" +[target.'cfg(any(unix, target_os = "wasi"))'.dependencies] +libc = { git = "https://github.com/wasix-org/libc.git" } [target.'cfg(windows)'.dependencies.windows-sys] version = "0.48" diff --git a/README.md b/README.md index 8bb09495..ed3f24e6 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,18 @@ See the [API documentation] for more. # Branches +<<<<<<< HEAD Currently Socket2 supports two versions: v0.5 and v0.4. Version 0.5 is being developed in the master branch. Version 0.4 is developed in the [v0.4.x branch] branch. +======= +Currently Socket2 supports two versions: v0.4 and v0.3. Version 0.4 is developed +in the [v0.4.x branch] branch, version 0.3 in the [v0.3.x branch]. Version 0.5 +is currently being developed in the master branch. + +[v0.3.x branch]: https://github.com/rust-lang/socket2/tree/v0.3.x +>>>>>>> 50f3a0c (Implemented full networking for WebAssembly (WASIX)) [v0.4.x branch]: https://github.com/rust-lang/socket2/tree/v0.4.x # OS support diff --git a/src/lib.rs b/src/lib.rs index ae64ecf2..23447c69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,11 +59,11 @@ #![doc(test(attr(deny(warnings))))] use std::fmt; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use std::io::IoSlice; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use std::marker::PhantomData; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use std::mem; use std::mem::MaybeUninit; use std::net::SocketAddr; @@ -107,7 +107,7 @@ macro_rules! from { ($from: ty, $for: ty) => { impl From<$from> for $for { fn from(socket: $from) -> $for { - #[cfg(unix)] + #[cfg(any(unix, target_os="wasi"))] unsafe { <$for>::from_raw_fd(socket.into_raw_fd()) } @@ -176,9 +176,10 @@ mod sockref; #[cfg_attr(unix, path = "sys/unix.rs")] #[cfg_attr(windows, path = "sys/windows.rs")] +#[cfg_attr(target_os = "wasi", path = "sys/wasi.rs")] mod sys; -#[cfg(not(any(windows, unix)))] +#[cfg(not(any(windows, unix, target_os = "wasi")))] compile_error!("Socket2 doesn't support the compile target"); use sys::c_int; @@ -255,12 +256,12 @@ impl Type { /// Type corresponding to `SOCK_STREAM`. /// /// Used for protocols such as TCP. - pub const STREAM: Type = Type(sys::SOCK_STREAM); + pub const STREAM: Type = Type(sys::SOCK_STREAM as i32); /// Type corresponding to `SOCK_DGRAM`. /// /// Used for protocols such as UDP. - pub const DGRAM: Type = Type(sys::SOCK_DGRAM); + pub const DGRAM: Type = Type(sys::SOCK_DGRAM as i32); /// Type corresponding to `SOCK_DCCP`. /// @@ -517,6 +518,7 @@ impl TcpKeepalive { target_os = "tvos", target_os = "watchos", target_os = "windows", + target_os = "wasi", ))) )] pub const fn with_interval(self, interval: Duration) -> Self { @@ -541,6 +543,7 @@ impl TcpKeepalive { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -559,6 +562,7 @@ impl TcpKeepalive { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -577,14 +581,14 @@ impl TcpKeepalive { /// /// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdrMut`] /// for the variant used by `recvmsg(2)`. -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] pub struct MsgHdr<'addr, 'bufs, 'control> { inner: sys::msghdr, #[allow(clippy::type_complexity)] _lifetimes: PhantomData<(&'addr SockAddr, &'bufs IoSlice<'bufs>, &'control [u8])>, } -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { /// Create a new `MsgHdr` with all empty/zero fields. #[allow(clippy::new_without_default)] @@ -634,7 +638,7 @@ impl<'addr, 'bufs, 'control> MsgHdr<'addr, 'bufs, 'control> { } } -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { "MsgHdr".fmt(fmt) @@ -645,7 +649,7 @@ impl<'name, 'bufs, 'control> fmt::Debug for MsgHdr<'name, 'bufs, 'control> { /// /// This wraps `msghdr` on Unix and `WSAMSG` on Windows. Also see [`MsgHdr`] for /// the variant used by `sendmsg(2)`. -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] pub struct MsgHdrMut<'addr, 'bufs, 'control> { inner: sys::msghdr, #[allow(clippy::type_complexity)] @@ -656,7 +660,7 @@ pub struct MsgHdrMut<'addr, 'bufs, 'control> { )>, } -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] impl<'addr, 'bufs, 'control> MsgHdrMut<'addr, 'bufs, 'control> { /// Create a new `MsgHdrMut` with all empty/zero fields. #[allow(clippy::new_without_default)] @@ -701,7 +705,7 @@ impl<'addr, 'bufs, 'control> MsgHdrMut<'addr, 'bufs, 'control> { } } -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] impl<'name, 'bufs, 'control> fmt::Debug for MsgHdrMut<'name, 'bufs, 'control> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { "MsgHdrMut".fmt(fmt) diff --git a/src/sockaddr.rs b/src/sockaddr.rs index 5922ec06..b88523ab 100644 --- a/src/sockaddr.rs +++ b/src/sockaddr.rs @@ -1,6 +1,7 @@ use std::hash::Hash; use std::mem::{self, size_of, MaybeUninit}; use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; +#[cfg(not(target_os = "wasi"))] use std::path::Path; use std::{fmt, io, ptr}; @@ -146,6 +147,7 @@ impl SockAddr { /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path. /// /// Returns an error if the path is longer than `SUN_LEN`. + #[cfg(not(target_os = "wasi"))] pub fn unix

(path: P) -> io::Result where P: AsRef, @@ -204,6 +206,11 @@ impl SockAddr { pub fn is_unix(&self) -> bool { self.storage.ss_family == AF_UNIX as sa_family_t } + /// Returns a raw pointer to the address storage. + #[cfg(target_os = "wasi")] + pub(crate) const fn as_storage_ptr(&self) -> *const sockaddr_storage { + &self.storage + } /// Returns this address as a `SocketAddr` if it is in the `AF_INET` (IPv4) /// or `AF_INET6` (IPv6) family, otherwise returns `None`. @@ -225,7 +232,7 @@ impl SockAddr { ip, port, addr.sin6_flowinfo, - #[cfg(unix)] + #[cfg(any(unix, all(target_os = "wasi", target_vendor = "wasmer")))] addr.sin6_scope_id, #[cfg(windows)] unsafe { @@ -299,7 +306,7 @@ impl From for SockAddr { storage.sin6_port = addr.port().to_be(); storage.sin6_addr = crate::sys::to_in6_addr(addr.ip()); storage.sin6_flowinfo = addr.flowinfo(); - #[cfg(unix)] + #[cfg(any(unix, all(target_os = "wasi", target_vendor = "wasmer")))] { storage.sin6_scope_id = addr.scope_id(); } diff --git a/src/socket.rs b/src/socket.rs index fe34bea0..c1474ef5 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -18,6 +18,8 @@ use std::net::{self, Ipv4Addr, Shutdown}; use std::os::unix::io::{FromRawFd, IntoRawFd}; #[cfg(windows)] use std::os::windows::io::{FromRawSocket, IntoRawSocket}; +#[cfg(target_os = "wasi")] +use std::os::wasi::io::{FromRawFd, IntoRawFd}; use std::time::Duration; use crate::sys::{self, c_int, getsockopt, setsockopt, Bool}; @@ -25,7 +27,9 @@ use crate::sys::{self, c_int, getsockopt, setsockopt, Bool}; use crate::MsgHdrMut; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; #[cfg(not(target_os = "redox"))] -use crate::{MaybeUninitSlice, MsgHdr, RecvFlags}; +use crate::{MaybeUninitSlice, RecvFlags}; +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] +use crate::MsgHdr; /// Owned wrapper around a system socket. /// @@ -102,7 +106,7 @@ impl Socket { // Violating this assumption (fd never negative) causes UB, // something we don't want. So check for that we have this // `assert!`. - #[cfg(unix)] + #[cfg(any(unix, target_os = "wasi"))] assert!(raw >= 0, "tried to create a `Socket` with an invalid fd"); sys::socket_from_raw(raw) }, @@ -233,7 +237,7 @@ impl Socket { match res { Ok(()) => return Ok(()), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} - #[cfg(unix)] + #[cfg(any(unix, target_os = "wasi"))] Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} Err(e) => return Err(e), } @@ -271,6 +275,7 @@ impl Socket { target_os = "fuchsia", target_os = "illumos", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd", ))] @@ -284,6 +289,7 @@ impl Socket { target_os = "fuchsia", target_os = "illumos", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd", )))] @@ -625,6 +631,7 @@ impl Socket { /// but suppresses the `WSAEMSGSIZE` error on Windows. /// /// [`peek_from`]: Socket::peek_from + #[cfg(not(target_os = "wasi"))] pub fn peek_sender(&self) -> io::Result { sys::peek_sender(self.as_raw()) } @@ -743,7 +750,7 @@ impl Socket { /// Send a message on a socket using a message structure. #[doc = man_links!(sendmsg(2))] - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))] pub fn sendmsg(&self, msg: &MsgHdr<'_, '_, '_>, flags: sys::c_int) -> io::Result { sys::sendmsg(self.as_raw(), msg, flags) @@ -762,6 +769,7 @@ const fn set_common_type(ty: Type) -> Type { target_os = "fuchsia", target_os = "illumos", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd", ))] @@ -788,6 +796,7 @@ fn set_common_flags(socket: Socket) -> io::Result { target_os = "fuchsia", target_os = "illumos", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd", )) @@ -1112,7 +1121,7 @@ impl Socket { #[cfg_attr(docsrs, doc(cfg(all(feature = "all", not(target_os = "redox")))))] pub fn header_included(&self) -> io::Result { unsafe { - getsockopt::(self.as_raw(), sys::IPPROTO_IP, sys::IP_HDRINCL) + getsockopt::(self.as_raw(), sys::IPPROTO_IP, libc::IP_HDRINCL) .map(|included| included != 0) } } @@ -1139,7 +1148,7 @@ impl Socket { setsockopt( self.as_raw(), sys::IPPROTO_IP, - sys::IP_HDRINCL, + libc::IP_HDRINCL, included as c_int, ) } @@ -1755,6 +1764,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "haiku", + target_os = "wasi", )))] pub fn recv_tclass_v6(&self) -> io::Result { unsafe { @@ -1777,6 +1787,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "haiku", + target_os = "wasi", )))] pub fn set_recv_tclass_v6(&self, recv_tclass: bool) -> io::Result<()> { unsafe { @@ -1831,6 +1842,7 @@ impl Socket { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -1849,6 +1861,7 @@ impl Socket { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -1878,6 +1891,7 @@ impl Socket { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -1896,6 +1910,7 @@ impl Socket { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", diff --git a/src/sockref.rs b/src/sockref.rs index d23b7c0f..6a6e11c6 100644 --- a/src/sockref.rs +++ b/src/sockref.rs @@ -6,6 +6,8 @@ use std::ops::Deref; use std::os::unix::io::{AsFd, AsRawFd, FromRawFd}; #[cfg(windows)] use std::os::windows::io::{AsRawSocket, AsSocket, FromRawSocket}; +#[cfg(target_os = "wasi")] +use std::os::wasi::io::{AsFd, AsRawFd, FromRawFd}; use crate::Socket; @@ -77,8 +79,8 @@ impl<'s> Deref for SockRef<'s> { } /// On Windows, a corresponding `From<&impl AsSocket>` implementation exists. -#[cfg(unix)] -#[cfg_attr(docsrs, doc(cfg(unix)))] +#[cfg(any(unix, target_os = "wasi"))] +#[cfg_attr(docsrs, doc(cfg(any(unix, target_os = "wasi"))))] impl<'s, S> From<&'s S> for SockRef<'s> where S: AsFd, diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 808c6ef1..02b005b1 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -295,6 +295,10 @@ const MAX_BUF_LEN: usize = c_int::MAX as usize - 1; #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))] const TCP_CA_NAME_MAX: usize = 16; +// TCP_CA_NAME_MAX isn't defined in user space include files(not in libc) +#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))] +const TCP_CA_NAME_MAX: usize = 16; + #[cfg(any( all( target_os = "linux", @@ -647,7 +651,7 @@ pub(crate) fn unix_sockaddr(path: &Path) -> io::Result { } // Used in `MsgHdr`. -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] pub(crate) use libc::msghdr; #[cfg(not(target_os = "redox"))] @@ -1172,7 +1176,7 @@ fn fcntl_get(fd: Socket, cmd: c_int) -> io::Result { syscall!(fcntl(fd, cmd)) } -/// Add `flag` to the current set flags of `F_GETFD`. +//// Add `flag` to the current set flags of `F_GETFD`. fn fcntl_add(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> { let previous = fcntl_get(fd, get_cmd)?; let new = previous | flag; @@ -3060,4 +3064,4 @@ fn in6_addr_convertion() { let want = [32, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7]; assert_eq!(raw.s6_addr, want); assert_eq!(from_in6_addr(raw), ip); -} +} \ No newline at end of file diff --git a/src/sys/wasi.rs b/src/sys/wasi.rs new file mode 100644 index 00000000..a53a9e0a --- /dev/null +++ b/src/sys/wasi.rs @@ -0,0 +1,1253 @@ +#![allow(unused_imports)] +use std::cmp::min; +use std::io::IoSlice; +use std::marker::PhantomData; +use std::mem::{self, size_of, MaybeUninit}; +use std::net::Shutdown; +use std::net::{Ipv4Addr, Ipv6Addr}; +use std::num::NonZeroUsize; +use std::num::NonZeroU32; +use std::os::wasi::io::RawFd; +use std::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; +use std::path::Path; +use std::ptr; +use std::time::{Duration, Instant}; +use std::{io, slice}; + +use libc::ssize_t; +use libc::{c_void, in6_addr, in_addr}; + +use std::os::wasi::ffi::OsStrExt; + +use crate::RecvFlags; +use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; + +pub(crate) use libc::c_int; + +// Used in `Domain`. +pub(crate) use libc::{AF_INET, AF_INET6, AF_UNIX}; +// Used in `Type`. +pub(crate) use libc::SOCK_RAW; +#[cfg(feature = "all")] +pub(crate) use libc::SOCK_SEQPACKET; +pub(crate) use libc::{SOCK_DGRAM, SOCK_STREAM}; +// Used in `Protocol`. +pub(crate) use libc::{IPPROTO_ICMP, IPPROTO_ICMPV6, IPPROTO_TCP, IPPROTO_UDP}; +// Used in `SockAddr`. +pub(crate) use libc::{ + sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, socklen_t, +}; +// Used in `RecvFlags`. +pub(crate) use libc::{MSG_TRUNC, SO_OOBINLINE}; +// Used in `Socket`. +pub(crate) use libc::IP_RECVTOS; +pub(crate) use libc::IP_TOS; +pub(crate) use libc::SO_LINGER; +pub(crate) use libc::{ + ip_mreq as IpMreq, ipv6_mreq as Ipv6Mreq, linger, IPPROTO_IP, IPPROTO_IPV6, + IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY, + IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_IF, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, + IP_TTL, MSG_OOB, MSG_PEEK, SOL_SOCKET, SO_BROADCAST, SO_ERROR, SO_KEEPALIVE, SO_RCVBUF, + SO_RCVTIMEO, SO_REUSEADDR, SO_SNDBUF, SO_SNDTIMEO, SO_TYPE, TCP_NODELAY, +}; +pub(crate) use libc::{ + ip_mreq_source as IpMreqSource, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP, +}; +pub(crate) use libc::{IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP}; +pub(crate) use libc::{TCP_KEEPCNT, TCP_KEEPINTVL}; + +// See this type in the Windows file. +pub(crate) type Bool = c_int; + +use libc::TCP_KEEPIDLE as KEEPALIVE_TIME; + +/// Helper macro to execute a system call that returns an `io::Result`. +macro_rules! syscall { + ($fn: ident ( $($arg: expr),* $(,)* ) ) => {{ + #[allow(unused_unsafe)] + let res = unsafe { libc::$fn($($arg, )*) }; + if res == -1 { + Err(std::io::Error::last_os_error()) + } else { + Ok(res) + } + }}; +} + +/// Maximum size of a buffer passed to system call like `recv` and `send`. +const MAX_BUF_LEN: usize = ssize_t::MAX as usize; + +type IovLen = usize; + +impl_debug!( + Domain, + libc::AF_INET, + libc::AF_INET6, + libc::AF_UNSPEC, // = 0. +); + +/// Unix only API. +impl Type { + /// Set `SOCK_NONBLOCK` on the `Type`. + pub const fn nonblocking(self) -> Type { + Type(self.0 | libc::SOCK_NONBLOCK) + } + + /// Set `SOCK_CLOEXEC` on the `Type`. + pub const fn cloexec(self) -> Type { + self._cloexec() + } + pub(crate) const fn _cloexec(self) -> Type { + Type(self.0 | libc::SOCK_CLOEXEC) + } +} + +impl_debug!( + Type, + libc::SOCK_STREAM, + libc::SOCK_DGRAM, + libc::SOCK_RAW, +); + +impl_debug!( + Protocol, + libc::IPPROTO_ICMP, + libc::IPPROTO_ICMPV6, + libc::IPPROTO_TCP, + libc::IPPROTO_UDP, +); + +#[repr(transparent)] +pub struct MaybeUninitSlice<'a> { + vec: libc::iovec, + _lifetime: PhantomData<&'a mut [MaybeUninit]>, +} + +unsafe impl<'a> Send for MaybeUninitSlice<'a> {} + +unsafe impl<'a> Sync for MaybeUninitSlice<'a> {} + +impl std::fmt::Debug for RecvFlags { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RecvFlags") + .field("is_truncated", &self.is_truncated()) + .finish() + } +} + +impl<'a> MaybeUninitSlice<'a> { + pub(crate) fn new(buf: &'a mut [MaybeUninit]) -> MaybeUninitSlice<'a> { + MaybeUninitSlice { + vec: libc::iovec { + iov_base: buf.as_mut_ptr().cast(), + iov_len: buf.len(), + }, + _lifetime: PhantomData, + } + } + + pub(crate) fn as_slice(&self) -> &[MaybeUninit] { + unsafe { slice::from_raw_parts(self.vec.iov_base.cast(), self.vec.iov_len) } + } + + pub(crate) fn as_mut_slice(&mut self) -> &mut [MaybeUninit] { + unsafe { slice::from_raw_parts_mut(self.vec.iov_base.cast(), self.vec.iov_len) } + } +} + +/// Unix only API. +impl SockAddr { + /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path. + /// + /// # Failure + /// + /// Returns an error if the path is longer than `SUN_LEN`. + #[cfg(feature = "all")] + #[cfg_attr(docsrs, doc(cfg(feature = "all")))] + #[allow(unused_unsafe)] // TODO: replace with `unsafe_op_in_unsafe_fn` once stable. + pub fn unix

(path: P) -> io::Result + where + P: AsRef, + { + unsafe { + SockAddr::try_init(|storage, len| { + // Safety: `SockAddr::try_init` zeros the address, which is a valid + // representation. + let storage: &mut libc::sockaddr_un = unsafe { &mut *storage.cast() }; + let len: &mut socklen_t = unsafe { &mut *len }; + + let bytes = path.as_ref().as_os_str().as_bytes(); + let too_long = match bytes.first() { + None => false, + // linux abstract namespaces aren't null-terminated + Some(&0) => bytes.len() > storage.sun_path.len(), + Some(_) => bytes.len() >= storage.sun_path.len(), + }; + if too_long { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN", + )); + } + + storage.sun_family = libc::AF_UNIX as sa_family_t; + // Safety: `bytes` and `addr.sun_path` are not overlapping and + // both point to valid memory. + // `SockAddr::try_init` zeroes the memory, so the path is already + // null terminated. + unsafe { + ptr::copy_nonoverlapping( + bytes.as_ptr(), + storage.sun_path.as_mut_ptr() as *mut u8, + bytes.len(), + ) + }; + + let base = storage as *const _ as usize; + let path = &storage.sun_path as *const _ as usize; + let sun_path_offset = path - base; + let length = sun_path_offset + + bytes.len() + + match bytes.first() { + Some(&0) | None => 0, + Some(_) => 1, + }; + *len = length as socklen_t; + + Ok(()) + }) + } + .map(|(_, addr)| addr) + } +} + + +pub(crate) type Socket = c_int; + +pub(crate) unsafe fn socket_from_raw(socket: Socket) -> crate::socket::Inner { + crate::socket::Inner::from_raw_fd(socket) +} + +pub(crate) fn socket_as_raw(socket: &crate::socket::Inner) -> Socket { + socket.as_raw_fd() +} + +pub(crate) fn socket_into_raw(socket: crate::socket::Inner) -> Socket { + socket.into_raw_fd() +} + +pub(crate) fn socket(family: c_int, ty: c_int, protocol: c_int) -> io::Result { + syscall!(socket(family, ty, protocol)) +} + +#[cfg(feature = "all")] +pub(crate) fn socketpair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<[Socket; 2]> { + let mut fds = [0, 0]; + syscall!(socketpair(family, ty, protocol, fds.as_mut_ptr())).map(|_| fds) +} + +pub(crate) fn bind(fd: Socket, addr: &SockAddr) -> io::Result<()> { + syscall!(bind(fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) +} + +pub(crate) fn connect(fd: Socket, addr: &SockAddr) -> io::Result<()> { + syscall!(connect(fd, addr.as_ptr(), addr.len())).map(|_| ()) +} + +pub(crate) fn poll_connect(socket: &crate::Socket, timeout: Duration) -> io::Result<()> { + let start = Instant::now(); + + let mut pollfd = libc::pollfd { + fd: socket.as_raw(), + events: libc::POLLIN | libc::POLLOUT, + revents: 0, + }; + + loop { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(io::ErrorKind::TimedOut.into()); + } + + let timeout = (timeout - elapsed).as_millis(); + let timeout = clamp(timeout, 1, c_int::MAX as u128) as c_int; + + match syscall!(poll(&mut pollfd, 1, timeout)) { + Ok(0) => return Err(io::ErrorKind::TimedOut.into()), + Ok(_) => { + // Error or hang up indicates an error (or failure to connect). + if (pollfd.revents & libc::POLLHUP) != 0 || (pollfd.revents & libc::POLLERR) != 0 { + match socket.take_error() { + Ok(Some(err)) => return Err(err), + Ok(None) => { + return Err(io::Error::new( + io::ErrorKind::Other, + "no error set after POLLHUP", + )) + } + Err(err) => return Err(err), + } + } + return Ok(()); + } + // Got interrupted, try again. + Err(ref err) if err.kind() == io::ErrorKind::Interrupted => continue, + Err(err) => return Err(err), + } + } +} + +// TODO: use clamp from std lib, stable since 1.50. +fn clamp(value: T, min: T, max: T) -> T +where + T: Ord, +{ + if value <= min { + min + } else if value >= max { + max + } else { + value + } +} + +pub(crate) fn listen(fd: Socket, backlog: c_int) -> io::Result<()> { + syscall!(listen(fd, backlog)).map(|_| ()) +} + +pub(crate) fn accept(fd: Socket) -> io::Result<(Socket, SockAddr)> { + // Safety: `accept` initialises the `SockAddr` for us. + unsafe { SockAddr::try_init(|storage, len| syscall!(accept(fd, storage.cast(), len))) } +} + +pub(crate) fn getsockname(fd: Socket) -> io::Result { + // Safety: `accept` initialises the `SockAddr` for us. + unsafe { SockAddr::try_init(|storage, len| syscall!(getsockname(fd, storage.cast(), len))) } + .map(|(_, addr)| addr) +} + +pub(crate) fn getpeername(fd: Socket) -> io::Result { + // Safety: `accept` initialises the `SockAddr` for us. + unsafe { SockAddr::try_init(|storage, len| syscall!(getpeername(fd, storage.cast(), len))) } + .map(|(_, addr)| addr) +} + +pub(crate) fn try_clone(fd: Socket) -> io::Result { + syscall!(fcntl(fd, libc::F_DUPFD_CLOEXEC, 0)) +} + +pub(crate) fn set_nonblocking(fd: Socket, nonblocking: bool) -> io::Result<()> { + if nonblocking { + fcntl_add(fd, libc::F_GETFL, libc::F_SETFL, libc::O_NONBLOCK) + } else { + fcntl_remove(fd, libc::F_GETFL, libc::F_SETFL, libc::O_NONBLOCK) + } +} + +pub(crate) fn shutdown(fd: Socket, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => libc::SHUT_WR, + Shutdown::Read => libc::SHUT_RD, + Shutdown::Both => libc::SHUT_RDWR, + }; + syscall!(shutdown(fd, how)).map(|_| ()) +} + +pub(crate) fn recv(fd: Socket, buf: &mut [MaybeUninit], flags: c_int) -> io::Result { + syscall!(recv( + fd, + buf.as_mut_ptr().cast(), + min(buf.len(), MAX_BUF_LEN), + flags, + )) + .map(|n| n as usize) +} + +pub(crate) fn recv_from( + fd: Socket, + buf: &mut [MaybeUninit], + flags: c_int, +) -> io::Result<(usize, SockAddr)> { + // Safety: `recvfrom` initialises the `SockAddr` for us. + unsafe { + SockAddr::try_init(|addr, addrlen| { + syscall!(recvfrom( + fd, + buf.as_mut_ptr().cast(), + min(buf.len(), MAX_BUF_LEN), + flags, + addr.cast(), + addrlen + )) + .map(|n| n as usize) + }) + } +} + +pub(crate) fn recv_vectored( + fd: Socket, + bufs: &mut [crate::MaybeUninitSlice<'_>], + flags: c_int, +) -> io::Result<(usize, RecvFlags)> { + recvmsg(fd, ptr::null_mut(), bufs, flags).map(|(n, _, recv_flags)| (n, recv_flags)) +} + +pub(crate) fn recv_from_vectored( + fd: Socket, + bufs: &mut [crate::MaybeUninitSlice<'_>], + flags: c_int, +) -> io::Result<(usize, RecvFlags, SockAddr)> { + // Safety: `recvmsg` initialises the address storage and we set the length + // manually. + unsafe { + SockAddr::try_init(|storage, len| { + recvmsg(fd, storage, bufs, flags).map(|(n, addrlen, recv_flags)| { + // Set the correct address length. + *len = addrlen; + (n, recv_flags) + }) + }) + } + .map(|((n, recv_flags), addr)| (n, recv_flags, addr)) +} + +/// Returns the (bytes received, sending address len, `RecvFlags`). +fn recvmsg( + fd: Socket, + msg_name: *mut sockaddr_storage, + bufs: &mut [crate::MaybeUninitSlice<'_>], + flags: c_int, +) -> io::Result<(usize, libc::socklen_t, RecvFlags)> { + let msg_namelen = if msg_name.is_null() { + 0 + } else { + size_of::() as libc::socklen_t + }; + // libc::msghdr contains unexported padding fields on Fuchsia. + let mut msg: libc::msghdr = unsafe { mem::zeroed() }; + msg.msg_name = msg_name.cast(); + msg.msg_namelen = msg_namelen; + msg.msg_iov = bufs.as_mut_ptr().cast(); + msg.msg_iovlen = min(bufs.len(), IovLen::MAX as usize) as IovLen; + syscall!(recvmsg(fd, &mut msg, flags)) + .map(|n| (n as usize, msg.msg_namelen, RecvFlags(msg.msg_flags))) +} + +pub(crate) fn send(fd: Socket, buf: &[u8], flags: c_int) -> io::Result { + syscall!(send( + fd, + buf.as_ptr().cast(), + min(buf.len(), MAX_BUF_LEN), + flags, + )) + .map(|n| n as usize) +} + +pub(crate) fn send_vectored(fd: Socket, bufs: &[IoSlice<'_>], flags: c_int) -> io::Result { + sendmsg(fd, ptr::null(), 0, bufs, flags) +} + +pub(crate) fn send_to(fd: Socket, buf: &[u8], addr: &SockAddr, flags: c_int) -> io::Result { + syscall!(sendto( + fd, + buf.as_ptr().cast(), + min(buf.len(), MAX_BUF_LEN), + flags, + addr.as_ptr(), + addr.len(), + )) + .map(|n| n as usize) +} + +pub(crate) fn send_to_vectored( + fd: Socket, + bufs: &[IoSlice<'_>], + addr: &SockAddr, + flags: c_int, +) -> io::Result { + sendmsg(fd, addr.as_storage_ptr(), addr.len(), bufs, flags) +} + +/// Returns the (bytes received, sending address len, `RecvFlags`). +fn sendmsg( + fd: Socket, + msg_name: *const sockaddr_storage, + msg_namelen: socklen_t, + bufs: &[IoSlice<'_>], + flags: c_int, +) -> io::Result { + // libc::msghdr contains unexported padding fields on Fuchsia. + let mut msg: libc::msghdr = unsafe { mem::zeroed() }; + // Safety: we're creating a `*mut` pointer from a reference, which is UB + // once actually used. However the OS should not write to it in the + // `sendmsg` system call. + msg.msg_name = (msg_name as *mut sockaddr_storage).cast(); + msg.msg_namelen = msg_namelen; + // Safety: Same as above about `*const` -> `*mut`. + msg.msg_iov = bufs.as_ptr() as *mut _; + msg.msg_iovlen = min(bufs.len(), IovLen::MAX as usize) as IovLen; + syscall!(sendmsg(fd, &msg, flags)).map(|n| n as usize) +} + +/// Wrapper around `getsockopt` to deal with platform specific timeouts. +pub(crate) fn timeout_opt(fd: Socket, opt: c_int, val: c_int) -> io::Result> { + unsafe { getsockopt(fd, opt, val).map(from_timeval) } +} + +fn from_timeval(duration: libc::timeval) -> Option { + if duration.tv_sec == 0 && duration.tv_usec == 0 { + None + } else { + let sec = duration.tv_sec as u64; + let nsec = (duration.tv_usec as u32) * 1000; + Some(Duration::new(sec, nsec)) + } +} + +/// Wrapper around `setsockopt` to deal with platform specific timeouts. +pub(crate) fn set_timeout_opt( + fd: Socket, + opt: c_int, + val: c_int, + duration: Option, +) -> io::Result<()> { + let duration = into_timeval(duration); + unsafe { setsockopt(fd, opt, val, duration) } +} + +fn into_timeval(duration: Option) -> libc::timeval { + match duration { + // https://github.com/rust-lang/libc/issues/1848 + #[cfg_attr(target_env = "musl", allow(deprecated))] + Some(duration) => libc::timeval { + tv_sec: min(duration.as_secs(), libc::time_t::MAX as u64) as libc::time_t, + tv_usec: duration.subsec_micros() as libc::suseconds_t, + }, + None => libc::timeval { + tv_sec: 0, + tv_usec: 0, + }, + } +} + +#[cfg(feature = "all")] +#[cfg(not(any(target_os = "haiku", target_os = "openbsd")))] +pub(crate) fn keepalive_time(fd: Socket) -> io::Result { + unsafe { + getsockopt::(fd, IPPROTO_TCP, KEEPALIVE_TIME) + .map(|secs| Duration::from_secs(secs as u64)) + } +} + +#[allow(unused_variables)] +pub(crate) fn set_tcp_keepalive(fd: Socket, keepalive: &TcpKeepalive) -> io::Result<()> { + #[cfg(not(any(target_os = "haiku", target_os = "openbsd")))] + if let Some(time) = keepalive.time { + let secs = into_secs(time); + unsafe { setsockopt(fd, libc::IPPROTO_TCP, KEEPALIVE_TIME, secs)? } + } + + { + if let Some(interval) = keepalive.interval { + let secs = into_secs(interval); + unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL, secs)? } + } + + if let Some(retries) = keepalive.retries { + unsafe { setsockopt(fd, libc::IPPROTO_TCP, libc::TCP_KEEPCNT, retries as c_int)? } + } + } + + Ok(()) +} + +fn into_secs(duration: Duration) -> c_int { + min(duration.as_secs(), c_int::MAX as u64) as c_int +} + +/// Add `flag` to the current set flags of `F_GETFD`. +fn fcntl_add(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> { + let previous = syscall!(fcntl(fd, get_cmd))?; + let new = previous | flag; + if new != previous { + syscall!(fcntl(fd, set_cmd, new)).map(|_| ()) + } else { + // Flag was already set. + Ok(()) + } +} + +/// Remove `flag` to the current set flags of `F_GETFD`. +fn fcntl_remove(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> { + let previous = syscall!(fcntl(fd, get_cmd))?; + let new = previous & !flag; + if new != previous { + syscall!(fcntl(fd, set_cmd, new)).map(|_| ()) + } else { + // Flag was already set. + Ok(()) + } +} + +/// Caller must ensure `T` is the correct type for `opt` and `val`. +pub(crate) unsafe fn getsockopt(fd: Socket, opt: c_int, val: c_int) -> io::Result { + let mut payload: MaybeUninit = MaybeUninit::uninit(); + let mut len = size_of::() as libc::socklen_t; + syscall!(getsockopt( + fd, + opt, + val, + payload.as_mut_ptr().cast(), + &mut len, + )) + .map(|_| { + debug_assert_eq!(len as usize, size_of::()); + // Safety: `getsockopt` initialised `payload` for us. + payload.assume_init() + }) +} + +/// Caller must ensure `T` is the correct type for `opt` and `val`. +pub(crate) unsafe fn setsockopt( + fd: Socket, + opt: c_int, + val: c_int, + payload: T, +) -> io::Result<()> { + let payload = &payload as *const T as *const c_void; + syscall!(setsockopt( + fd, + opt, + val, + payload, + mem::size_of::() as libc::socklen_t, + )) + .map(|_| ()) +} + +pub(crate) fn to_in_addr(addr: &Ipv4Addr) -> in_addr { + // `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. + in_addr { + s_addr: u32::from_ne_bytes(addr.octets()), + } +} + +pub(crate) fn from_in_addr(in_addr: in_addr) -> Ipv4Addr { + Ipv4Addr::from(in_addr.s_addr.to_ne_bytes()) +} + +pub(crate) fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr { + in6_addr { + s6_addr: addr.octets(), + } +} + +pub(crate) fn from_in6_addr(addr: in6_addr) -> Ipv6Addr { + Ipv6Addr::from(addr.s6_addr) +} + +pub(crate) fn to_mreqn( + multiaddr: &Ipv4Addr, + interface: &crate::socket::InterfaceIndexOrAddress, +) -> libc::ip_mreqn { + match interface { + crate::socket::InterfaceIndexOrAddress::Index(interface) => libc::ip_mreqn { + imr_multiaddr: to_in_addr(multiaddr), + imr_address: to_in_addr(&Ipv4Addr::UNSPECIFIED), + imr_ifindex: *interface as _, + }, + crate::socket::InterfaceIndexOrAddress::Address(interface) => libc::ip_mreqn { + imr_multiaddr: to_in_addr(multiaddr), + imr_address: to_in_addr(interface), + imr_ifindex: 0, + }, + } +} + +/// Unix only API. +impl crate::Socket { + /// Accept a new incoming connection from this listener. + /// + /// This function directly corresponds to the `accept4(2)` function. + /// + /// This function will block the calling thread until a new connection is + /// established. When established, the corresponding `Socket` and the remote + /// peer's address will be returned. + pub fn accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> { + self._accept4(flags) + } + + pub(crate) fn _accept4(&self, flags: c_int) -> io::Result<(crate::Socket, SockAddr)> { + // Safety: `accept4` initialises the `SockAddr` for us. + unsafe { + SockAddr::try_init(|storage, len| { + syscall!(accept4(self.as_raw(), storage.cast(), len, flags)) + .map(crate::Socket::from_raw) + }) + } + } + + /// Sets `CLOEXEC` on the socket. + /// + /// # Notes + /// + /// On supported platforms you can use [`Type::cloexec`]. + pub fn set_cloexec(&self, close_on_exec: bool) -> io::Result<()> { + self._set_cloexec(close_on_exec) + } + + pub(crate) fn _set_cloexec(&self, close_on_exec: bool) -> io::Result<()> { + if close_on_exec { + fcntl_add( + self.as_raw(), + libc::F_GETFD, + libc::F_SETFD, + libc::FD_CLOEXEC, + ) + } else { + fcntl_remove( + self.as_raw(), + libc::F_GETFD, + libc::F_SETFD, + libc::FD_CLOEXEC, + ) + } + } + + /// Gets the value of the `TCP_MAXSEG` option on this socket. + /// + /// For more information about this option, see [`set_mss`]. + /// + /// [`set_mss`]: crate::Socket::set_mss + pub fn mss(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_MAXSEG) + .map(|mss| mss as u32) + } + } + + /// Sets the value of the `TCP_MAXSEG` option on this socket. + /// + /// The `TCP_MAXSEG` option denotes the TCP Maximum Segment Size and is only + /// available on TCP sockets. + pub fn set_mss(&self, mss: u32) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_MAXSEG, + mss as c_int, + ) + } + } + + /// Returns `true` if `listen(2)` was called on this socket by checking the + /// `SO_ACCEPTCONN` option on this socket. + pub fn is_listener(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_ACCEPTCONN) + .map(|v| v != 0) + } + } + + /// Returns the [`Protocol`] of this socket by checking the `SO_PROTOCOL` + /// option on this socket. + pub fn protocol(&self) -> io::Result> { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_PROTOCOL).map(|v| match v + { + 0 => None, + p => Some(Protocol(p)), + }) + } + } + + /// Gets the value for the `SO_MARK` option on this socket. + /// + /// This value gets the socket mark field for each packet sent through + /// this socket. + /// + /// On Linux this function requires the `CAP_NET_ADMIN` capability. + pub fn mark(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_MARK) + .map(|mark| mark as u32) + } + } + + /// Sets the value for the `SO_MARK` option on this socket. + /// + /// This value sets the socket mark field for each packet sent through + /// this socket. Changing the mark can be used for mark-based routing + /// without netfilter or for packet filtering. + /// + /// On Linux this function requires the `CAP_NET_ADMIN` capability. + pub fn set_mark(&self, mark: u32) -> io::Result<()> { + unsafe { + setsockopt::( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_MARK, + mark as c_int, + ) + } + } + + /// Get the value of the `TCP_CORK` option on this socket. + /// + /// For more information about this option, see [`set_cork`]. + /// + /// [`set_cork`]: Socket::set_cork + pub fn cork(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_CORK) + .map(|cork| cork != 0) + } + } + + /// Set the value of the `TCP_CORK` option on this socket. + /// + /// If set, don't send out partial frames. All queued partial frames are + /// sent when the option is cleared again. There is a 200 millisecond ceiling on + /// the time for which output is corked by `TCP_CORK`. If this ceiling is reached, + /// then queued data is automatically transmitted. + pub fn set_cork(&self, cork: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_CORK, + cork as c_int, + ) + } + } + + /// Get the value of the `TCP_QUICKACK` option on this socket. + /// + /// For more information about this option, see [`set_quickack`]. + /// + /// [`set_quickack`]: Socket::set_quickack + pub fn quickack(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_QUICKACK) + .map(|quickack| quickack != 0) + } + } + + /// Set the value of the `TCP_QUICKACK` option on this socket. + /// + /// If set, acks are sent immediately, rather than delayed if needed in accordance to normal + /// TCP operation. This flag is not permanent, it only enables a switch to or from quickack mode. + /// Subsequent operation of the TCP protocol will once again enter/leave quickack mode depending on + /// internal protocol processing and factors such as delayed ack timeouts occurring and data transfer. + pub fn set_quickack(&self, quickack: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_QUICKACK, + quickack as c_int, + ) + } + } + + /// Get the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket. + /// + /// For more information about this option, see [`set_thin_linear_timeouts`]. + /// + /// [`set_thin_linear_timeouts`]: Socket::set_thin_linear_timeouts + pub fn thin_linear_timeouts(&self) -> io::Result { + unsafe { + getsockopt::( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_THIN_LINEAR_TIMEOUTS, + ) + .map(|timeouts| timeouts != 0) + } + } + + /// Set the value of the `TCP_THIN_LINEAR_TIMEOUTS` option on this socket. + /// + /// If set, the kernel will dynamically detect a thin-stream connection if there are less than four packets in flight. + /// With less than four packets in flight the normal TCP fast retransmission will not be effective. + /// The kernel will modify the retransmission to avoid the very high latencies that thin stream suffer because of exponential backoff. + pub fn set_thin_linear_timeouts(&self, timeouts: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_THIN_LINEAR_TIMEOUTS, + timeouts as c_int, + ) + } + } + + /// Gets the value for the `SO_BINDTODEVICE` option on this socket. + /// + /// This value gets the socket binded device's interface name. + pub fn device(&self) -> io::Result>> { + // TODO: replace with `MaybeUninit::uninit_array` once stable. + let mut buf: [MaybeUninit; libc::IFNAMSIZ] = + unsafe { MaybeUninit::uninit().assume_init() }; + let mut len = buf.len() as libc::socklen_t; + syscall!(getsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_BINDTODEVICE, + buf.as_mut_ptr().cast(), + &mut len, + ))?; + if len == 0 { + Ok(None) + } else { + let buf = &buf[..len as usize - 1]; + // TODO: use `MaybeUninit::slice_assume_init_ref` once stable. + Ok(Some(unsafe { &*(buf as *const [_] as *const [u8]) }.into())) + } + } + + /// Sets the value for the `SO_BINDTODEVICE` option on this socket. + /// + /// If a socket is bound to an interface, only packets received from that + /// particular interface are processed by the socket. Note that this only + /// works for some socket types, particularly `AF_INET` sockets. + /// + /// If `interface` is `None` or an empty string it removes the binding. + pub fn bind_device(&self, interface: Option<&[u8]>) -> io::Result<()> { + let (value, len) = if let Some(interface) = interface { + (interface.as_ptr(), interface.len()) + } else { + (ptr::null(), 0) + }; + syscall!(setsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_BINDTODEVICE, + value.cast(), + len as libc::socklen_t, + )) + .map(|_| ()) + } + + /// Get the value of the `SO_INCOMING_CPU` option on this socket. + /// + /// For more information about this option, see [`set_cpu_affinity`]. + /// + /// [`set_cpu_affinity`]: crate::Socket::set_cpu_affinity + pub fn cpu_affinity(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_INCOMING_CPU) + .map(|cpu| cpu as usize) + } + } + + /// Set value for the `SO_INCOMING_CPU` option on this socket. + /// + /// Sets the CPU affinity of the socket. + pub fn set_cpu_affinity(&self, cpu: usize) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_INCOMING_CPU, + cpu as c_int, + ) + } + } + + /// Get the value of the `SO_REUSEPORT` option on this socket. + /// + /// For more information about this option, see [`set_reuse_port`]. + /// + /// [`set_reuse_port`]: crate::Socket::set_reuse_port + pub fn reuse_port(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_SOCKET, libc::SO_REUSEPORT) + .map(|reuse| reuse != 0) + } + } + + /// Set value for the `SO_REUSEPORT` option on this socket. + /// + /// This indicates that further calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_REUSEPORT, + reuse as c_int, + ) + } + } + + /// Get the value of the `IP_FREEBIND` option on this socket. + /// + /// For more information about this option, see [`set_freebind`]. + /// + /// [`set_freebind`]: crate::Socket::set_freebind + pub fn freebind(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_IP, libc::IP_FREEBIND) + .map(|freebind| freebind != 0) + } + } + + /// Set value for the `IP_FREEBIND` option on this socket. + /// + /// If enabled, this boolean option allows binding to an IP address that is + /// nonlocal or does not (yet) exist. This permits listening on a socket, + /// without requiring the underlying network interface or the specified + /// dynamic IP address to be up at the time that the application is trying + /// to bind to it. + pub fn set_freebind(&self, freebind: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_IP, + libc::IP_FREEBIND, + freebind as c_int, + ) + } + } + + /// Get the value of the `IPV6_FREEBIND` option on this socket. + /// + /// This is an IPv6 counterpart of `IP_FREEBIND` socket option on + /// Android/Linux. For more information about this option, see + /// [`set_freebind`]. + /// + /// [`set_freebind`]: crate::Socket::set_freebind + pub fn freebind_ipv6(&self) -> io::Result { + unsafe { + getsockopt::(self.as_raw(), libc::SOL_IPV6, libc::IPV6_FREEBIND) + .map(|freebind| freebind != 0) + } + } + + /// Set value for the `IPV6_FREEBIND` option on this socket. + /// + /// This is an IPv6 counterpart of `IP_FREEBIND` socket option on + /// Android/Linux. For more information about this option, see + /// [`set_freebind`]. + /// + /// [`set_freebind`]: crate::Socket::set_freebind + /// + /// # Examples + /// + /// On Linux: + /// + /// ``` + /// use socket2::{Domain, Socket, Type}; + /// use std::io::{self, Error, ErrorKind}; + /// + /// fn enable_freebind(socket: &Socket) -> io::Result<()> { + /// match socket.domain()? { + /// Domain::IPV4 => socket.set_freebind(true)?, + /// Domain::IPV6 => socket.set_freebind_ipv6(true)?, + /// _ => return Err(Error::new(ErrorKind::Other, "unsupported domain")), + /// }; + /// Ok(()) + /// } + /// + /// # fn main() -> io::Result<()> { + /// # let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?; + /// # enable_freebind(&socket) + /// # } + /// ``` + pub fn set_freebind_ipv6(&self, freebind: bool) -> io::Result<()> { + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_IPV6, + libc::IPV6_FREEBIND, + freebind as c_int, + ) + } + } + + /// Copies data between a `file` and this socket using the `sendfile(2)` + /// system call. Because this copying is done within the kernel, + /// `sendfile()` is more efficient than the combination of `read(2)` and + /// `write(2)`, which would require transferring data to and from user + /// space. + /// + /// Different OSs support different kinds of `file`s, see the OS + /// documentation for what kind of files are supported. Generally *regular* + /// files are supported by all OSs. + /// + /// The `offset` is the absolute offset into the `file` to use as starting + /// point. + /// + /// Depending on the OS this function *may* change the offset of `file`. For + /// the best results reset the offset of the file before using it again. + /// + /// The `length` determines how many bytes to send, where a length of `None` + /// means it will try to send all bytes. + pub fn sendfile( + &self, + file: &F, + offset: usize, + length: Option, + ) -> io::Result + where + F: AsRawFd, + { + self._sendfile(file.as_raw_fd(), offset as _, length) + } + + fn _sendfile( + &self, + file: RawFd, + offset: libc::off_t, + length: Option, + ) -> io::Result { + let count = match length { + Some(n) => n.get() as libc::size_t, + // The maximum the Linux kernel will write in a single call. + None => 0x7ffff000, // 2,147,479,552 bytes. + }; + let mut offset = offset; + syscall!(sendfile(self.as_raw(), file, &mut offset, count)).map(|n| n as usize) + } + + /// Set the value of the `TCP_USER_TIMEOUT` option on this socket. + /// + /// If set, this specifies the maximum amount of time that transmitted data may remain + /// unacknowledged or buffered data may remain untransmitted before TCP will forcibly close the + /// corresponding connection. + /// + /// Setting `timeout` to `None` or a zero duration causes the system default timeouts to + /// be used. If `timeout` in milliseconds is larger than `c_uint::MAX`, the timeout is clamped + /// to `c_uint::MAX`. For example, when `c_uint` is a 32-bit value, this limits the timeout to + /// approximately 49.71 days. + pub fn set_tcp_user_timeout(&self, timeout: Option) -> io::Result<()> { + let timeout = timeout + .map(|to| min(to.as_millis(), libc::c_uint::MAX as u128) as libc::c_uint) + .unwrap_or(0); + unsafe { + setsockopt( + self.as_raw(), + libc::IPPROTO_TCP, + libc::TCP_USER_TIMEOUT, + timeout, + ) + } + } + + /// Get the value of the `TCP_USER_TIMEOUT` option on this socket. + /// + /// For more information about this option, see [`set_tcp_user_timeout`]. + /// + /// [`set_tcp_user_timeout`]: Socket::set_tcp_user_timeout + pub fn tcp_user_timeout(&self) -> io::Result> { + unsafe { + getsockopt::(self.as_raw(), libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT) + .map(|millis| { + if millis == 0 { + None + } else { + Some(Duration::from_millis(millis as u64)) + } + }) + } + } + + /// Attach Berkeley Packet Filter(BPF) on this socket. + /// + /// BPF allows a user-space program to attach a filter onto any socket + /// and allow or disallow certain types of data to come through the socket. + /// + /// For more information about this option, see [filter](https://www.kernel.org/doc/html/v5.12/networking/filter.html) + pub fn attach_filter(&self, filters: &[libc::sock_filter]) -> io::Result<()> { + let prog = libc::sock_fprog { + len: filters.len() as u16, + filter: filters.as_ptr() as *mut _, + }; + + unsafe { + setsockopt( + self.as_raw(), + libc::SOL_SOCKET, + libc::SO_ATTACH_FILTER, + prog, + ) + } + } + + /// Detach Berkeley Packet Filter(BPF) from this socket. + /// + /// For more information about this option, see [`attach_filter`] + pub fn detach_filter(&self) -> io::Result<()> { + unsafe { setsockopt(self.as_raw(), libc::SOL_SOCKET, libc::SO_DETACH_FILTER, 0) } + } +} + +impl AsFd for crate::Socket { + fn as_fd(&self) -> BorrowedFd<'_> { + // SAFETY: lifetime is bound by self. + unsafe { BorrowedFd::borrow_raw(self.as_raw()) } + } +} + +impl AsRawFd for crate::Socket { + fn as_raw_fd(&self) -> c_int { + self.as_raw() + } +} + +impl From for OwnedFd { + fn from(sock: crate::Socket) -> OwnedFd { + // SAFETY: sock.into_raw() always returns a valid fd. + unsafe { OwnedFd::from_raw_fd(sock.into_raw()) } + } +} + +impl IntoRawFd for crate::Socket { + fn into_raw_fd(self) -> c_int { + self.into_raw() + } +} + +impl From for crate::Socket { + fn from(fd: OwnedFd) -> crate::Socket { + // SAFETY: `OwnedFd` ensures the fd is valid. + unsafe { crate::Socket::from_raw_fd(fd.into_raw_fd()) } + } +} + +impl FromRawFd for crate::Socket { + unsafe fn from_raw_fd(fd: c_int) -> crate::Socket { + crate::Socket::from_raw(fd) + } +} + +#[test] +fn in_addr_convertion() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + let raw = to_in_addr(&ip); + // NOTE: `in_addr` is packed on NetBSD and it's unsafe to borrow. + let a = raw.s_addr; + assert_eq!(a, u32::from_ne_bytes([127, 0, 0, 1])); + assert_eq!(from_in_addr(raw), ip); + + let ip = Ipv4Addr::new(127, 34, 4, 12); + let raw = to_in_addr(&ip); + let a = raw.s_addr; + assert_eq!(a, u32::from_ne_bytes([127, 34, 4, 12])); + assert_eq!(from_in_addr(raw), ip); +} + +#[test] +fn in6_addr_convertion() { + let ip = Ipv6Addr::new(0x2000, 1, 2, 3, 4, 5, 6, 7); + let raw = to_in6_addr(&ip); + let want = [32, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7]; + assert_eq!(raw.s6_addr, want); + assert_eq!(from_in6_addr(raw), ip); +} diff --git a/tests/socket.rs b/tests/socket.rs index 79451da4..205126f4 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -9,6 +9,7 @@ target_os = "macos", target_os = "tvos", target_os = "watchos", + target_os = "wasi", ) ))] use std::fs::File; @@ -31,6 +32,7 @@ use std::net::{Ipv6Addr, SocketAddrV6}; target_os = "macos", target_os = "tvos", target_os = "watchos", + target_os = "wasi", ) ))] use std::num::NonZeroUsize; @@ -38,7 +40,7 @@ use std::num::NonZeroUsize; use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] use std::path::Path; use std::str; use std::thread; @@ -69,9 +71,9 @@ fn domain_fmt_debug() { (Domain::IPV4, "AF_INET"), (Domain::IPV6, "AF_INET6"), (Domain::UNIX, "AF_UNIX"), - #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux")))] + #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux", target_os = "wasi")))] (Domain::PACKET, "AF_PACKET"), - #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] + #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] (Domain::VSOCK, "AF_VSOCK"), (0.into(), "AF_UNSPEC"), (500.into(), "500"), @@ -179,7 +181,7 @@ fn socket_address_unix_unnamed() { } #[test] -#[cfg(all(any(target_os = "linux", target_os = "android"), feature = "all"))] +#[cfg(all(any(target_os = "linux", target_os = "android", target_os = "wasi"), feature = "all"))] fn socket_address_unix_abstract_namespace() { let path = "\0h".repeat(108 / 2); let addr = SockAddr::unix(&path).unwrap(); @@ -195,7 +197,7 @@ fn socket_address_unix_abstract_namespace() { } #[test] -#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] +#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] fn socket_address_vsock() { let addr = SockAddr::vsock(1, 9999); assert!(addr.as_socket_ipv4().is_none()); @@ -267,6 +269,7 @@ fn no_common_flags() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd" ) @@ -318,6 +321,7 @@ fn set_cloexec() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", + target_os = "wasi", target_os = "netbsd", target_os = "openbsd" ) @@ -540,7 +544,7 @@ fn unix() { } #[test] -#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] +#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] #[ignore = "using VSOCK family requires optional kernel support (works when enabled)"] fn vsock() { let addr = SockAddr::vsock(libc::VMADDR_CID_LOCAL, libc::VMADDR_PORT_ANY); @@ -822,6 +826,7 @@ fn tcp_keepalive() { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -839,6 +844,7 @@ fn tcp_keepalive() { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -866,6 +872,7 @@ fn tcp_keepalive() { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -887,6 +894,7 @@ fn tcp_keepalive() { target_os = "ios", target_os = "linux", target_os = "macos", + target_os = "wasi", target_os = "netbsd", target_os = "tvos", target_os = "watchos", @@ -1029,6 +1037,7 @@ fn device_v6() { target_os = "macos", target_os = "tvos", target_os = "watchos", + target_os = "wasi", ) ))] #[test] @@ -1103,6 +1112,7 @@ fn sendfile() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", + target_os = "wasi", ) ))] #[test] @@ -1122,6 +1132,7 @@ fn is_listener() { // target_os = "freebsd", target_os = "fuchsia", target_os = "linux", + target_os = "wasi", ) ))] #[test] @@ -1143,6 +1154,7 @@ fn domain() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", + target_os = "wasi", ) ))] #[test] @@ -1190,7 +1202,7 @@ fn r#type() { } } -#[cfg(all(feature = "all", target_os = "linux"))] +#[cfg(all(feature = "all", target_os = "linux", target_os = "wasi"))] #[test] fn cpu_affinity() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); From 54d018894786630ff84458108f0c1974c9b5270d Mon Sep 17 00:00:00 2001 From: Johnathan Sharratt Date: Fri, 14 Jul 2023 07:54:26 +1000 Subject: [PATCH 15/28] Fixed a bug with the socket types --- src/socket.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/socket.rs b/src/socket.rs index c1474ef5..88f98ffd 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -769,7 +769,6 @@ const fn set_common_type(ty: Type) -> Type { target_os = "fuchsia", target_os = "illumos", target_os = "linux", - target_os = "wasi", target_os = "netbsd", target_os = "openbsd", ))] @@ -796,7 +795,6 @@ fn set_common_flags(socket: Socket) -> io::Result { target_os = "fuchsia", target_os = "illumos", target_os = "linux", - target_os = "wasi", target_os = "netbsd", target_os = "openbsd", )) From e5a4d26e8c4b01f7b005eebbcccb3d6b5f3eedb4 Mon Sep 17 00:00:00 2001 From: Josh Guilfoyle Date: Sat, 15 Jul 2023 05:47:37 -0700 Subject: [PATCH 16/28] Support for the ESP-IDF framework Smoke tested on esp32c3 dev board. I've also tested a similar patch backported to v0.4.9 with much greater functionality including tokio + mio with other patches I've been working on and it's fully working. Closes #379 --- src/lib.rs | 16 ++++++++++++---- src/socket.rs | 23 +++++++++++++++++++---- src/sys/unix.rs | 31 +++++++++++++++++++++---------- 3 files changed, 52 insertions(+), 18 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index ae64ecf2..7ed91054 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -270,13 +270,16 @@ impl Type { pub const DCCP: Type = Type(sys::SOCK_DCCP); /// Type corresponding to `SOCK_SEQPACKET`. - #[cfg(feature = "all")] - #[cfg_attr(docsrs, doc(cfg(feature = "all")))] + #[cfg(all(feature = "all", not(target_os = "espidf")))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "all", not(target_os = "espidf")))))] pub const SEQPACKET: Type = Type(sys::SOCK_SEQPACKET); /// Type corresponding to `SOCK_RAW`. - #[cfg(all(feature = "all", not(target_os = "redox")))] - #[cfg_attr(docsrs, doc(cfg(all(feature = "all", not(target_os = "redox")))))] + #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))] + #[cfg_attr( + docsrs, + doc(cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))) + )] pub const RAW: Type = Type(sys::SOCK_RAW); } @@ -374,6 +377,7 @@ impl RecvFlags { /// /// On Unix this corresponds to the `MSG_TRUNC` flag. /// On Windows this corresponds to the `WSAEMSGSIZE` error code. + #[cfg(not(target_os = "espidf"))] pub const fn is_truncated(self) -> bool { self.0 & sys::MSG_TRUNC != 0 } @@ -428,6 +432,7 @@ pub struct TcpKeepalive { target_os = "redox", target_os = "solaris", target_os = "nto", + target_os = "espidf", )))] interval: Option, #[cfg(not(any( @@ -436,6 +441,7 @@ pub struct TcpKeepalive { target_os = "solaris", target_os = "windows", target_os = "nto", + target_os = "espidf", )))] retries: Option, } @@ -450,6 +456,7 @@ impl TcpKeepalive { target_os = "redox", target_os = "solaris", target_os = "nto", + target_os = "espidf", )))] interval: None, #[cfg(not(any( @@ -458,6 +465,7 @@ impl TcpKeepalive { target_os = "solaris", target_os = "windows", target_os = "nto", + target_os = "espidf", )))] retries: None, } diff --git a/src/socket.rs b/src/socket.rs index fe34bea0..73b806ba 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -790,6 +790,7 @@ fn set_common_flags(socket: Socket) -> io::Result { target_os = "linux", target_os = "netbsd", target_os = "openbsd", + target_os = "espidf", )) ))] socket._set_cloexec(true)?; @@ -1108,8 +1109,11 @@ impl Socket { /// For more information about this option, see [`set_header_included`]. /// /// [`set_header_included`]: Socket::set_header_included - #[cfg(all(feature = "all", not(target_os = "redox")))] - #[cfg_attr(docsrs, doc(cfg(all(feature = "all", not(target_os = "redox")))))] + #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))] + #[cfg_attr( + docsrs, + doc(cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))) + )] pub fn header_included(&self) -> io::Result { unsafe { getsockopt::(self.as_raw(), sys::IPPROTO_IP, sys::IP_HDRINCL) @@ -1132,8 +1136,11 @@ impl Socket { any(target_os = "fuchsia", target_os = "illumos", target_os = "solaris"), allow(rustdoc::broken_intra_doc_links) )] - #[cfg(all(feature = "all", not(target_os = "redox")))] - #[cfg_attr(docsrs, doc(cfg(all(feature = "all", not(target_os = "redox")))))] + #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))] + #[cfg_attr( + docsrs, + doc(cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))) + )] pub fn set_header_included(&self, included: bool) -> io::Result<()> { unsafe { setsockopt( @@ -1237,6 +1244,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "nto", + target_os = "espidf", )))] pub fn join_multicast_v4_n( &self, @@ -1268,6 +1276,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "nto", + target_os = "espidf", )))] pub fn leave_multicast_v4_n( &self, @@ -1300,6 +1309,7 @@ impl Socket { target_os = "redox", target_os = "fuchsia", target_os = "nto", + target_os = "espidf", )))] pub fn join_ssm_v4( &self, @@ -1335,6 +1345,7 @@ impl Socket { target_os = "redox", target_os = "fuchsia", target_os = "nto", + target_os = "espidf", )))] pub fn leave_ssm_v4( &self, @@ -1512,6 +1523,7 @@ impl Socket { target_os = "solaris", target_os = "haiku", target_os = "nto", + target_os = "espidf", )))] pub fn set_recv_tos(&self, recv_tos: bool) -> io::Result<()> { unsafe { @@ -1540,6 +1552,7 @@ impl Socket { target_os = "solaris", target_os = "haiku", target_os = "nto", + target_os = "espidf", )))] pub fn recv_tos(&self) -> io::Result { unsafe { @@ -1755,6 +1768,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "haiku", + target_os = "espidf", )))] pub fn recv_tclass_v6(&self) -> io::Result { unsafe { @@ -1777,6 +1791,7 @@ impl Socket { target_os = "redox", target_os = "solaris", target_os = "haiku", + target_os = "espidf", )))] pub fn set_recv_tclass_v6(&self, recv_tclass: bool) -> io::Result<()> { unsafe { diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 808c6ef1..788d9fdb 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -81,9 +81,9 @@ pub(crate) use libc::{AF_INET, AF_INET6, AF_UNIX}; // Used in `Type`. #[cfg(all(feature = "all", target_os = "linux"))] pub(crate) use libc::SOCK_DCCP; -#[cfg(all(feature = "all", not(target_os = "redox")))] +#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))] pub(crate) use libc::SOCK_RAW; -#[cfg(feature = "all")] +#[cfg(all(feature = "all", not(target_os = "espidf")))] pub(crate) use libc::SOCK_SEQPACKET; pub(crate) use libc::{SOCK_DGRAM, SOCK_STREAM}; // Used in `Protocol`. @@ -111,8 +111,10 @@ pub(crate) use libc::{ sa_family_t, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_storage, socklen_t, }; // Used in `RecvFlags`. +#[cfg(not(any(target_os = "redox", target_os = "espidf")))] +pub(crate) use libc::MSG_TRUNC; #[cfg(not(target_os = "redox"))] -pub(crate) use libc::{MSG_TRUNC, SO_OOBINLINE}; +pub(crate) use libc::SO_OOBINLINE; // Used in `Socket`. #[cfg(not(target_os = "nto"))] pub(crate) use libc::ipv6_mreq as Ipv6Mreq; @@ -125,6 +127,7 @@ pub(crate) use libc::ipv6_mreq as Ipv6Mreq; target_os = "redox", target_os = "solaris", target_os = "haiku", + target_os = "espidf", )))] pub(crate) use libc::IPV6_RECVTCLASS; #[cfg(all(feature = "all", not(target_os = "redox")))] @@ -140,6 +143,7 @@ pub(crate) use libc::IP_HDRINCL; target_os = "solaris", target_os = "haiku", target_os = "nto", + target_os = "espidf", )))] pub(crate) use libc::IP_RECVTOS; #[cfg(not(any( @@ -178,6 +182,7 @@ pub(crate) use libc::{ target_os = "redox", target_os = "fuchsia", target_os = "nto", + target_os = "espidf", )))] pub(crate) use libc::{ ip_mreq_source as IpMreqSource, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP, @@ -329,6 +334,7 @@ type IovLen = usize; target_os = "solaris", target_os = "tvos", target_os = "watchos", + target_os = "espidf", ))] type IovLen = c_int; @@ -471,10 +477,11 @@ impl_debug!( libc::SOCK_DGRAM, #[cfg(all(feature = "all", target_os = "linux"))] libc::SOCK_DCCP, - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "redox", target_os = "espidf")))] libc::SOCK_RAW, - #[cfg(not(any(target_os = "redox", target_os = "haiku")))] + #[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "espidf")))] libc::SOCK_RDM, + #[cfg(not(target_os = "espidf"))] libc::SOCK_SEQPACKET, /* TODO: add these optional bit OR-ed flags: #[cfg(any( @@ -538,6 +545,7 @@ impl RecvFlags { /// On Unix this corresponds to the `MSG_EOR` flag. /// /// [`SEQPACKET`]: Type::SEQPACKET + #[cfg(not(target_os = "espidf"))] pub const fn is_end_of_record(self) -> bool { self.0 & libc::MSG_EOR != 0 } @@ -556,11 +564,13 @@ impl RecvFlags { #[cfg(not(target_os = "redox"))] impl std::fmt::Debug for RecvFlags { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("RecvFlags") - .field("is_end_of_record", &self.is_end_of_record()) - .field("is_out_of_band", &self.is_out_of_band()) - .field("is_truncated", &self.is_truncated()) - .finish() + let mut s = f.debug_struct("RecvFlags"); + #[cfg(not(target_os = "espidf"))] + s.field("is_end_of_record", &self.is_end_of_record()); + s.field("is_out_of_band", &self.is_out_of_band()); + #[cfg(not(target_os = "espidf"))] + s.field("is_truncated", &self.is_truncated()); + s.finish() } } @@ -1264,6 +1274,7 @@ pub(crate) fn from_in6_addr(addr: in6_addr) -> Ipv6Addr { target_os = "redox", target_os = "solaris", target_os = "nto", + target_os = "espidf", )))] pub(crate) const fn to_mreqn( multiaddr: &Ipv4Addr, From baa8f2b27de11cfd582f9f0f891a5c421d3b200e Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 14 Jul 2023 18:19:56 +0200 Subject: [PATCH 17/28] Fix Clippy warning --- tests/socket.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/socket.rs b/tests/socket.rs index 79451da4..e21a3bcb 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -1334,7 +1334,7 @@ test!( test!(keepalive, set_keepalive(true)); #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux")))] test!(freebind, set_freebind(true)); -#[cfg(all(feature = "all", any(target_os = "linux")))] +#[cfg(all(feature = "all", target_os = "linux"))] test!(IPv6 freebind_ipv6, set_freebind_ipv6(true)); test!(IPv4 ttl, set_ttl(40)); From 77e3bb9befd4a24b247343040ca766b69968951d Mon Sep 17 00:00:00 2001 From: Josh Guilfoyle Date: Mon, 31 Jul 2023 10:36:18 -0700 Subject: [PATCH 18/28] Small fix for ESP-IDF platform support This was missed in #452 because I wasn't testing with feature="all" enabled for my small socket2 test. For the full tokio integration I was using v0.4.x which didn't need this fix. Properly closes #379. --- src/sys/unix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 788d9fdb..639d26e7 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -130,7 +130,7 @@ pub(crate) use libc::ipv6_mreq as Ipv6Mreq; target_os = "espidf", )))] pub(crate) use libc::IPV6_RECVTCLASS; -#[cfg(all(feature = "all", not(target_os = "redox")))] +#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "espidf"))))] pub(crate) use libc::IP_HDRINCL; #[cfg(not(any( target_os = "aix", From 86711242d893888d5575fce510dfa6061701e314 Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Wed, 23 Aug 2023 15:09:09 +0400 Subject: [PATCH 19/28] Clean it up --- Cargo.toml | 2 ++ README.md | 8 -------- src/lib.rs | 7 ++++--- src/sockaddr.rs | 1 + src/socket.rs | 18 ++++++++---------- src/sockref.rs | 4 +--- src/sys/unix.rs | 6 +++--- src/sys/wasi.rs | 11 +++-------- tests/socket.rs | 34 ++++++++++++++++++++-------------- 9 files changed, 42 insertions(+), 49 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2b4ad029..b9fa3cc8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,8 @@ targets = ["aarch64-apple-ios", "aarch64-linux-android", "x86_64-apple-darwin", features = ["all"] [target.'cfg(any(unix, target_os = "wasi"))'.dependencies] +# Temporary, must be updated to point to the official libc package as soon +# as WASIX-related changes are merged in. libc = { git = "https://github.com/wasix-org/libc.git" } [target.'cfg(windows)'.dependencies.windows-sys] diff --git a/README.md b/README.md index ed3f24e6..8bb09495 100644 --- a/README.md +++ b/README.md @@ -21,18 +21,10 @@ See the [API documentation] for more. # Branches -<<<<<<< HEAD Currently Socket2 supports two versions: v0.5 and v0.4. Version 0.5 is being developed in the master branch. Version 0.4 is developed in the [v0.4.x branch] branch. -======= -Currently Socket2 supports two versions: v0.4 and v0.3. Version 0.4 is developed -in the [v0.4.x branch] branch, version 0.3 in the [v0.3.x branch]. Version 0.5 -is currently being developed in the master branch. - -[v0.3.x branch]: https://github.com/rust-lang/socket2/tree/v0.3.x ->>>>>>> 50f3a0c (Implemented full networking for WebAssembly (WASIX)) [v0.4.x branch]: https://github.com/rust-lang/socket2/tree/v0.4.x # OS support diff --git a/src/lib.rs b/src/lib.rs index 6f2448df..4f97af4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -107,7 +107,7 @@ macro_rules! from { ($from: ty, $for: ty) => { impl From<$from> for $for { fn from(socket: $from) -> $for { - #[cfg(any(unix, target_os="wasi"))] + #[cfg(any(unix, target_os = "wasi"))] unsafe { <$for>::from_raw_fd(socket.into_raw_fd()) } @@ -256,12 +256,12 @@ impl Type { /// Type corresponding to `SOCK_STREAM`. /// /// Used for protocols such as TCP. - pub const STREAM: Type = Type(sys::SOCK_STREAM as i32); + pub const STREAM: Type = Type(sys::SOCK_STREAM); /// Type corresponding to `SOCK_DGRAM`. /// /// Used for protocols such as UDP. - pub const DGRAM: Type = Type(sys::SOCK_DGRAM as i32); + pub const DGRAM: Type = Type(sys::SOCK_DGRAM); /// Type corresponding to `SOCK_DCCP`. /// @@ -509,6 +509,7 @@ impl TcpKeepalive { target_os = "netbsd", target_os = "tvos", target_os = "watchos", + target_os = "wasi", target_os = "windows", ))] #[cfg_attr( diff --git a/src/sockaddr.rs b/src/sockaddr.rs index b88523ab..b537ee4f 100644 --- a/src/sockaddr.rs +++ b/src/sockaddr.rs @@ -206,6 +206,7 @@ impl SockAddr { pub fn is_unix(&self) -> bool { self.storage.ss_family == AF_UNIX as sa_family_t } + /// Returns a raw pointer to the address storage. #[cfg(target_os = "wasi")] pub(crate) const fn as_storage_ptr(&self) -> *const sockaddr_storage { diff --git a/src/socket.rs b/src/socket.rs index 737de985..d48ab5af 100644 --- a/src/socket.rs +++ b/src/socket.rs @@ -14,22 +14,20 @@ use std::mem::MaybeUninit; #[cfg(not(target_os = "nto"))] use std::net::Ipv6Addr; use std::net::{self, Ipv4Addr, Shutdown}; -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] use std::os::unix::io::{FromRawFd, IntoRawFd}; #[cfg(windows)] use std::os::windows::io::{FromRawSocket, IntoRawSocket}; -#[cfg(target_os = "wasi")] -use std::os::wasi::io::{FromRawFd, IntoRawFd}; use std::time::Duration; use crate::sys::{self, c_int, getsockopt, setsockopt, Bool}; +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] +use crate::MsgHdr; #[cfg(all(unix, not(target_os = "redox")))] use crate::MsgHdrMut; use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type}; #[cfg(not(target_os = "redox"))] use crate::{MaybeUninitSlice, RecvFlags}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use crate::MsgHdr; /// Owned wrapper around a system socket. /// @@ -153,7 +151,7 @@ impl Socket { /// This function sets the same flags as in done for [`Socket::new`], /// [`Socket::pair_raw`] can be used if you don't want to set those flags. #[doc = man_links!(unix: socketpair(2))] - #[cfg(all(feature = "all", unix))] + #[cfg(all(feature = "all", any(unix, target_os = "wasi")))] #[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))] pub fn pair( domain: Domain, @@ -170,7 +168,7 @@ impl Socket { /// Creates a pair of sockets which are connected to each other. /// /// This function corresponds to `socketpair(2)`. - #[cfg(all(feature = "all", unix))] + #[cfg(all(feature = "all", any(unix, target_os = "wasi")))] #[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))] pub fn pair_raw( domain: Domain, @@ -631,7 +629,7 @@ impl Socket { /// but suppresses the `WSAEMSGSIZE` error on Windows. /// /// [`peek_from`]: Socket::peek_from - #[cfg(not(target_os = "wasi"))] + #[cfg(any(doc, not(target_os = "wasi")))] pub fn peek_sender(&self) -> io::Result { sys::peek_sender(self.as_raw()) } @@ -1123,7 +1121,7 @@ impl Socket { )] pub fn header_included(&self) -> io::Result { unsafe { - getsockopt::(self.as_raw(), sys::IPPROTO_IP, libc::IP_HDRINCL) + getsockopt::(self.as_raw(), sys::IPPROTO_IP, sys::IP_HDRINCL) .map(|included| included != 0) } } @@ -1153,7 +1151,7 @@ impl Socket { setsockopt( self.as_raw(), sys::IPPROTO_IP, - libc::IP_HDRINCL, + sys::IP_HDRINCL, included as c_int, ) } diff --git a/src/sockref.rs b/src/sockref.rs index 6a6e11c6..36809ff3 100644 --- a/src/sockref.rs +++ b/src/sockref.rs @@ -2,12 +2,10 @@ use std::fmt; use std::marker::PhantomData; use std::mem::ManuallyDrop; use std::ops::Deref; -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] use std::os::unix::io::{AsFd, AsRawFd, FromRawFd}; #[cfg(windows)] use std::os::windows::io::{AsRawSocket, AsSocket, FromRawSocket}; -#[cfg(target_os = "wasi")] -use std::os::wasi::io::{AsFd, AsRawFd, FromRawFd}; use crate::Socket; diff --git a/src/sys/unix.rs b/src/sys/unix.rs index b831f79b..5fa4acbc 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -661,7 +661,7 @@ pub(crate) fn unix_sockaddr(path: &Path) -> io::Result { } // Used in `MsgHdr`. -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] +#[cfg(not(target_os = "redox"))] pub(crate) use libc::msghdr; #[cfg(not(target_os = "redox"))] @@ -1186,7 +1186,7 @@ fn fcntl_get(fd: Socket, cmd: c_int) -> io::Result { syscall!(fcntl(fd, cmd)) } -//// Add `flag` to the current set flags of `F_GETFD`. +/// Add `flag` to the current set flags of `F_GETFD`. fn fcntl_add(fd: Socket, get_cmd: c_int, set_cmd: c_int, flag: c_int) -> io::Result<()> { let previous = fcntl_get(fd, get_cmd)?; let new = previous | flag; @@ -3075,4 +3075,4 @@ fn in6_addr_convertion() { let want = [32, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7]; assert_eq!(raw.s6_addr, want); assert_eq!(from_in6_addr(raw), ip); -} \ No newline at end of file +} diff --git a/src/sys/wasi.rs b/src/sys/wasi.rs index a53a9e0a..7234fc0f 100644 --- a/src/sys/wasi.rs +++ b/src/sys/wasi.rs @@ -5,8 +5,8 @@ use std::marker::PhantomData; use std::mem::{self, size_of, MaybeUninit}; use std::net::Shutdown; use std::net::{Ipv4Addr, Ipv6Addr}; -use std::num::NonZeroUsize; use std::num::NonZeroU32; +use std::num::NonZeroUsize; use std::os::wasi::io::RawFd; use std::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; use std::path::Path; @@ -40,6 +40,7 @@ pub(crate) use libc::{ // Used in `RecvFlags`. pub(crate) use libc::{MSG_TRUNC, SO_OOBINLINE}; // Used in `Socket`. +pub(crate) use libc::IP_HDRINCL; pub(crate) use libc::IP_RECVTOS; pub(crate) use libc::IP_TOS; pub(crate) use libc::SO_LINGER; @@ -102,12 +103,7 @@ impl Type { } } -impl_debug!( - Type, - libc::SOCK_STREAM, - libc::SOCK_DGRAM, - libc::SOCK_RAW, -); +impl_debug!(Type, libc::SOCK_STREAM, libc::SOCK_DGRAM, libc::SOCK_RAW,); impl_debug!( Protocol, @@ -221,7 +217,6 @@ impl SockAddr { } } - pub(crate) type Socket = c_int; pub(crate) unsafe fn socket_from_raw(socket: Socket) -> crate::socket::Inner { diff --git a/tests/socket.rs b/tests/socket.rs index f6a0453f..06222bee 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -16,6 +16,7 @@ use std::fs::File; use std::io; #[cfg(not(target_os = "redox"))] use std::io::IoSlice; +#[cfg(not(target_os = "wasi"))] use std::io::Read; use std::io::Write; use std::mem::{self, MaybeUninit}; @@ -36,15 +37,16 @@ use std::net::{Ipv6Addr, SocketAddrV6}; ) ))] use std::num::NonZeroUsize; -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] use std::os::unix::io::AsRawFd; #[cfg(windows)] use std::os::windows::io::AsRawSocket; -#[cfg(any(unix, target_os = "wasi"))] +#[cfg(unix)] use std::path::Path; use std::str; use std::thread; use std::time::Duration; +#[cfg(not(target_os = "wasi"))] use std::{env, fs}; #[cfg(windows)] @@ -71,9 +73,9 @@ fn domain_fmt_debug() { (Domain::IPV4, "AF_INET"), (Domain::IPV6, "AF_INET6"), (Domain::UNIX, "AF_UNIX"), - #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux", target_os = "wasi")))] + #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux")))] (Domain::PACKET, "AF_PACKET"), - #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] + #[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] (Domain::VSOCK, "AF_VSOCK"), (0.into(), "AF_UNSPEC"), (500.into(), "500"), @@ -143,6 +145,7 @@ fn from_invalid_raw_fd_should_panic() { } #[test] +#[cfg(not(target_os = "wasi"))] fn socket_address_unix() { let string = "/tmp/socket"; let addr = SockAddr::unix(string).unwrap(); @@ -163,6 +166,7 @@ fn socket_address_unix() { } #[test] +#[cfg(not(target_os = "wasi"))] fn socket_address_unix_unnamed() { let addr = SockAddr::unix("").unwrap(); assert!(addr.as_socket_ipv4().is_none()); @@ -181,7 +185,7 @@ fn socket_address_unix_unnamed() { } #[test] -#[cfg(all(any(target_os = "linux", target_os = "android", target_os = "wasi"), feature = "all"))] +#[cfg(all(any(target_os = "linux", target_os = "android"), feature = "all"))] fn socket_address_unix_abstract_namespace() { let path = "\0h".repeat(108 / 2); let addr = SockAddr::unix(&path).unwrap(); @@ -197,7 +201,7 @@ fn socket_address_unix_abstract_namespace() { } #[test] -#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] +#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] fn socket_address_vsock() { let addr = SockAddr::vsock(1, 9999); assert!(addr.as_socket_ipv4().is_none()); @@ -218,7 +222,7 @@ fn set_nonblocking() { } fn assert_common_flags(socket: &Socket, expected: bool) { - #[cfg(unix)] + #[cfg(any(unix, target_os = "wasi"))] assert_close_on_exec(socket, expected); #[cfg(any( target_os = "ios", @@ -282,7 +286,7 @@ fn type_nonblocking() { } /// Assert that `NONBLOCK` is set on `socket`. -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] #[track_caller] pub fn assert_nonblocking(socket: &Socket, want: bool) { #[cfg(all(feature = "all", unix))] @@ -334,7 +338,7 @@ fn type_cloexec() { } /// Assert that `CLOEXEC` is set on `socket`. -#[cfg(unix)] +#[cfg(any(unix, target_os = "wasi"))] #[track_caller] pub fn assert_close_on_exec(socket: &S, want: bool) where @@ -497,6 +501,7 @@ fn pair() { assert_eq!(&buf[..n], DATA); } +#[cfg(not(target_os = "wasi"))] fn unix_sockets_supported() -> bool { #[cfg(windows)] { @@ -516,6 +521,7 @@ fn unix_sockets_supported() -> bool { } #[test] +#[cfg(not(target_os = "wasi"))] fn unix() { if !unix_sockets_supported() { return; @@ -544,7 +550,7 @@ fn unix() { } #[test] -#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux", target_os = "wasi")))] +#[cfg(all(feature = "all", any(target_os = "android", target_os = "linux")))] #[ignore = "using VSOCK family requires optional kernel support (works when enabled)"] fn vsock() { let addr = SockAddr::vsock(libc::VMADDR_CID_LOCAL, libc::VMADDR_PORT_ANY); @@ -597,7 +603,7 @@ fn out_of_band() { } #[test] -#[cfg(not(target_os = "redox"))] // cfg of `udp_pair_unconnected()` +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] // cfg of `udp_pair_unconnected()` fn udp_peek_sender() { let (socket_a, socket_b) = udp_pair_unconnected(); @@ -708,7 +714,7 @@ fn send_from_recv_to_vectored() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn sendmsg() { let (socket_a, socket_b) = udp_pair_unconnected(); @@ -1132,7 +1138,6 @@ fn is_listener() { // target_os = "freebsd", target_os = "fuchsia", target_os = "linux", - target_os = "wasi", ) ))] #[test] @@ -1202,7 +1207,7 @@ fn r#type() { } } -#[cfg(all(feature = "all", target_os = "linux", target_os = "wasi"))] +#[cfg(all(feature = "all", any(target_os = "linux", target_os = "wasi")))] #[test] fn cpu_affinity() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); @@ -1409,6 +1414,7 @@ test!(IPv6 tclass_v6, set_tclass_v6(96)); target_os = "openbsd", target_os = "redox", target_os = "solaris", + target_os = "wasi", target_os = "windows", )))] test!(IPv6 recv_tclass_v6, set_recv_tclass_v6(true)); From bf480a5bee77a38668fdae5b64bc859b0b03642c Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Wed, 23 Aug 2023 15:11:57 +0400 Subject: [PATCH 20/28] Fix CI --- Cargo.toml | 2 +- src/sys/unix.rs | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b9fa3cc8..861bc005 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ features = ["all"] [target.'cfg(any(unix, target_os = "wasi"))'.dependencies] # Temporary, must be updated to point to the official libc package as soon # as WASIX-related changes are merged in. -libc = { git = "https://github.com/wasix-org/libc.git" } +libc = { git = "https://github.com/wasix-org/libc.git", branch = "main" } [target.'cfg(windows)'.dependencies.windows-sys] version = "0.48" diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 5fa4acbc..639d26e7 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -300,10 +300,6 @@ const MAX_BUF_LEN: usize = c_int::MAX as usize - 1; #[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))] const TCP_CA_NAME_MAX: usize = 16; -// TCP_CA_NAME_MAX isn't defined in user space include files(not in libc) -#[cfg(all(feature = "all", any(target_os = "freebsd", target_os = "linux")))] -const TCP_CA_NAME_MAX: usize = 16; - #[cfg(any( all( target_os = "linux", From bbdf7143bdc94560bb1934768c568f8287ff93c6 Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Wed, 23 Aug 2023 15:49:46 +0400 Subject: [PATCH 21/28] Add WASIX to CI --- .github/workflows/main.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 48099a48..6777785a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -42,6 +42,20 @@ jobs: - uses: taiki-e/install-action@cargo-hack - name: Run tests run: cargo hack test --feature-powerset && cargo hack test --feature-powerset --release + Test-Wasix: + name: Test (wasix) + runs-on: ubuntu-latest + env: + CARGO_TARGET_WASM32_WASMER_WASI_RUNNER: wasmer run --env RUST_BACKTRACE=1 --net + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@stable + - uses: taiki-e/install-action@cargo-hack + - uses: wasmerio/setup-wasmer@v2 + - run: cargo install cargo-wasix + - run: cargo wasix download-toolchain + - name: Run tests + run: cargo +wasix hack test --feature-powerset --target wasm32-wasmer-wasi -- -- --nocapture && cargo +wasix hack test --feature-powerset --release --target wasm32-wasmer-wasi -- -- --nocapture Rustfmt: name: Rustfmt runs-on: ubuntu-latest @@ -65,6 +79,17 @@ jobs: - uses: taiki-e/install-action@cargo-hack - name: Run check run: cargo hack check --feature-powerset --all-targets --examples --bins --tests --target ${{ matrix.target }} + Check-Wasix: + name: Check (wasix) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: dtolnay/rust-toolchain@stable + - uses: taiki-e/install-action@cargo-hack + - run: cargo install cargo-wasix + - run: cargo wasix download-toolchain + - name: Run check + run: cargo +wasix hack check --feature-powerset --all-targets --examples --bins --tests --target wasm32-wasmer-wasi Clippy: name: Clippy runs-on: ubuntu-latest From 27e89babf7971a762f5fc34fdea053aef8901a0c Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Fri, 25 Aug 2023 16:15:33 +0400 Subject: [PATCH 22/28] Filter out the tests that don't work on WASIX --- tests/socket.rs | 70 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 17 deletions(-) diff --git a/tests/socket.rs b/tests/socket.rs index 06222bee..0bc76d66 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -13,16 +13,21 @@ ) ))] use std::fs::File; +#[cfg(not(target_os = "wasi"))] use std::io; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use std::io::IoSlice; #[cfg(not(target_os = "wasi"))] use std::io::Read; use std::io::Write; -use std::mem::{self, MaybeUninit}; -use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream}; -#[cfg(not(target_os = "redox"))] +use std::mem; +#[cfg(not(target_os = "wasi"))] +use std::mem::MaybeUninit; +#[cfg(not(target_os = "wasi"))] +use std::net::{Ipv4Addr, SocketAddrV4}; +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use std::net::{Ipv6Addr, SocketAddrV6}; +use std::net::{SocketAddr, TcpStream}; #[cfg(all( feature = "all", any( @@ -44,7 +49,9 @@ use std::os::windows::io::AsRawSocket; #[cfg(unix)] use std::path::Path; use std::str; +#[cfg(not(target_os = "wasi"))] use std::thread; +#[cfg(not(target_os = "wasi"))] use std::time::Duration; #[cfg(not(target_os = "wasi"))] use std::{env, fs}; @@ -52,9 +59,11 @@ use std::{env, fs}; #[cfg(windows)] use windows_sys::Win32::Foundation::{GetHandleInformation, HANDLE_FLAG_INHERIT}; -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] use socket2::MaybeUninitSlice; -use socket2::{Domain, Protocol, SockAddr, Socket, TcpKeepalive, Type}; +use socket2::{Domain, Protocol, Socket, Type}; +#[cfg(not(target_os = "wasi"))] +use socket2::{SockAddr, TcpKeepalive}; #[test] fn domain_for_address() { @@ -68,6 +77,7 @@ fn domain_for_address() { } #[test] +#[cfg(not(target_os = "wasi"))] fn domain_fmt_debug() { let tests = &[ (Domain::IPV4, "AF_INET"), @@ -221,8 +231,9 @@ fn set_nonblocking() { assert_nonblocking(&socket, false); } +#[cfg(not(target_os = "wasi"))] fn assert_common_flags(socket: &Socket, expected: bool) { - #[cfg(any(unix, target_os = "wasi"))] + #[cfg(unix)] assert_close_on_exec(socket, expected); #[cfg(any( target_os = "ios", @@ -236,6 +247,7 @@ fn assert_common_flags(socket: &Socket, expected: bool) { } #[test] +#[cfg(not(target_os = "wasi"))] fn common_flags() { let listener = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); assert_common_flags(&listener, true); @@ -251,6 +263,7 @@ fn common_flags() { } #[test] +#[cfg(not(target_os = "wasi"))] fn no_common_flags() { let listener = Socket::new_raw(Domain::IPV4, Type::STREAM, None).unwrap(); assert_common_flags(&listener, false); @@ -440,9 +453,11 @@ where assert_eq!(flags, want as _, "non-blocking option"); } +#[cfg(not(target_os = "wasi"))] const DATA: &[u8] = b"hello world"; #[test] +#[cfg(not(target_os = "wasi"))] fn connect_timeout_unrouteable() { // This IP is unroutable, so connections should always time out. let addr = "10.255.255.1:80".parse::().unwrap().into(); @@ -456,6 +471,7 @@ fn connect_timeout_unrouteable() { } #[test] +#[cfg(not(target_os = "wasi"))] fn connect_timeout_unbound() { // Bind and drop a socket to track down a "probably unassigned" port. let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); @@ -475,6 +491,7 @@ fn connect_timeout_unbound() { } #[test] +#[cfg(not(target_os = "wasi"))] fn connect_timeout_valid() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); socket @@ -573,6 +590,7 @@ fn vsock() { } #[test] +#[cfg(not(target_os = "wasi"))] fn out_of_band() { let listener = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); listener.bind(&any_ipv4()).unwrap(); @@ -618,7 +636,7 @@ fn udp_peek_sender() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn send_recv_vectored() { let (socket_a, socket_b) = udp_pair_connected(); @@ -665,7 +683,7 @@ fn send_recv_vectored() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn send_from_recv_to_vectored() { let (socket_a, socket_b) = udp_pair_unconnected(); let addr_a = socket_a.local_addr().unwrap(); @@ -732,7 +750,7 @@ fn sendmsg() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn recv_vectored_truncated() { let (socket_a, socket_b) = udp_pair_connected(); @@ -752,7 +770,7 @@ fn recv_vectored_truncated() { } #[test] -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn recv_from_vectored_truncated() { let (socket_a, socket_b) = udp_pair_unconnected(); let addr_a = socket_a.local_addr().unwrap(); @@ -778,7 +796,7 @@ fn recv_from_vectored_truncated() { } /// Create a pair of non-connected UDP sockets suitable for unit tests. -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn udp_pair_unconnected() -> (Socket, Socket) { // Use ephemeral ports assigned by the OS. let unspecified_addr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0); @@ -806,7 +824,7 @@ fn udp_pair_unconnected() -> (Socket, Socket) { } /// Create a pair of connected UDP sockets suitable for unit tests. -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] fn udp_pair_connected() -> (Socket, Socket) { let (socket_a, socket_b) = udp_pair_unconnected(); @@ -819,6 +837,7 @@ fn udp_pair_connected() -> (Socket, Socket) { } #[test] +#[cfg(not(target_os = "wasi"))] fn tcp_keepalive() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); let params = TcpKeepalive::new().with_time(Duration::from_secs(200)); @@ -1183,6 +1202,7 @@ fn protocol() { } #[test] +#[cfg(not(target_os = "wasi"))] fn r#type() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); assert_eq!(socket.r#type().unwrap(), Type::STREAM); @@ -1227,12 +1247,14 @@ fn niche() { } } +#[cfg(not(target_os = "wasi"))] fn any_ipv4() -> SockAddr { SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into() } /// Assume the `buf`fer to be initialised. // TODO: replace with `MaybeUninit::slice_assume_init_ref` once stable. +#[cfg(not(target_os = "wasi"))] unsafe fn assume_init(buf: &[MaybeUninit]) -> &[u8] { &*(buf as *const [MaybeUninit] as *const [u8]) } @@ -1281,26 +1303,30 @@ macro_rules! test { }; } +#[cfg(not(target_os = "wasi"))] const SET_BUF_SIZE: usize = 4096; // Linux doubles the buffer size for kernel usage, and exposes that when // retrieving the buffer size. -#[cfg(not(target_os = "linux"))] +#[cfg(not(any(target_os = "linux", target_os = "wasi")))] const GET_BUF_SIZE: usize = SET_BUF_SIZE; #[cfg(target_os = "linux")] const GET_BUF_SIZE: usize = 2 * SET_BUF_SIZE; +#[cfg(not(target_os = "wasi"))] test!(nodelay, set_nodelay(true)); +#[cfg(not(target_os = "wasi"))] test!( recv_buffer_size, set_recv_buffer_size(SET_BUF_SIZE), GET_BUF_SIZE ); +#[cfg(not(target_os = "wasi"))] test!( send_buffer_size, set_send_buffer_size(SET_BUF_SIZE), GET_BUF_SIZE ); -#[cfg(not(target_os = "redox"))] +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] test!(out_of_band_inline, set_out_of_band_inline(true)); test!(reuse_address, set_reuse_address(true)); #[cfg(all( @@ -1343,17 +1369,21 @@ test!(quickack, set_quickack(false)); any(target_os = "android", target_os = "fuchsia", target_os = "linux") ))] test!(thin_linear_timeouts, set_thin_linear_timeouts(true)); +#[cfg(not(target_os = "wasi"))] test!(linger, set_linger(Some(Duration::from_secs(10)))); +#[cfg(not(target_os = "wasi"))] test!( read_timeout, set_read_timeout(Some(Duration::from_secs(10))) ); +#[cfg(not(target_os = "wasi"))] test!(keepalive, set_keepalive(true)); #[cfg(all(feature = "all", any(target_os = "fuchsia", target_os = "linux")))] test!(freebind, set_freebind(true)); #[cfg(all(feature = "all", target_os = "linux"))] test!(IPv6 freebind_ipv6, set_freebind_ipv6(true)); +#[cfg(not(target_os = "wasi"))] test!(IPv4 ttl, set_ttl(40)); #[cfg(not(any( @@ -1361,6 +1391,7 @@ test!(IPv4 ttl, set_ttl(40)); target_os = "redox", target_os = "solaris", target_os = "illumos", + target_os = "wasi", )))] test!(IPv4 tos, set_tos(96)); @@ -1372,19 +1403,22 @@ test!(IPv4 tos, set_tos(96)); target_os = "openbsd", target_os = "redox", target_os = "solaris", + target_os = "wasi", target_os = "windows", )))] test!(IPv4 recv_tos, set_recv_tos(true)); -#[cfg(not(windows))] // TODO: returns `WSAENOPROTOOPT` (10042) on Windows. +#[cfg(not(any(windows, target_os = "wasi")))] // TODO: returns `WSAENOPROTOOPT` (10042) on Windows. test!(IPv4 broadcast, set_broadcast(true)); +#[cfg(not(target_os = "wasi"))] test!(IPv6 unicast_hops_v6, set_unicast_hops_v6(20)); #[cfg(not(any( windows, target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd" + target_os = "openbsd", + target_os = "wasi", )))] test!(IPv6 only_v6, set_only_v6(true)); // IPv6 socket are already IPv6 only on FreeBSD and Windows. @@ -1436,6 +1470,7 @@ test!( target_os = "openbsd", target_os = "redox", target_os = "solaris", + target_os = "wasi", )))] fn join_leave_multicast_v4_n() { let socket = Socket::new(Domain::IPV4, Type::DGRAM, None).unwrap(); @@ -1465,6 +1500,7 @@ fn join_leave_multicast_v4_n() { target_os = "openbsd", target_os = "redox", target_os = "fuchsia", + target_os = "wasi", )))] fn join_leave_ssm_v4() { let socket = Socket::new(Domain::IPV4, Type::DGRAM, None).unwrap(); From 410884b8f1ba7f0aa15f2f3dd93f7151c6b418a8 Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Fri, 25 Aug 2023 16:19:24 +0400 Subject: [PATCH 23/28] Fix 1.72 lints --- src/sys/unix.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sys/unix.rs b/src/sys/unix.rs index 639d26e7..b4bc7f5d 100644 --- a/src/sys/unix.rs +++ b/src/sys/unix.rs @@ -2711,7 +2711,7 @@ impl crate::Socket { .map(|_| { let buf = &payload[..len as usize]; // TODO: use `MaybeUninit::slice_assume_init_ref` once stable. - unsafe { &*(buf as *const [_] as *const [u8]) }.into() + unsafe { &*(buf as *const [u8]) }.into() }) } From d9bef4be4105d8ccf36297bf6e07b19ef35e40d9 Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Fri, 25 Aug 2023 16:28:02 +0400 Subject: [PATCH 24/28] Fix "all" feature tests --- tests/socket.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/tests/socket.rs b/tests/socket.rs index 0bc76d66..153153bc 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -107,7 +107,7 @@ fn type_fmt_debug() { (Type::DGRAM, "SOCK_DGRAM"), #[cfg(feature = "all")] (Type::SEQPACKET, "SOCK_SEQPACKET"), - #[cfg(all(feature = "all", not(target_os = "redox")))] + #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "wasi"))))] (Type::RAW, "SOCK_RAW"), (500.into(), "500"), ]; @@ -1062,7 +1062,6 @@ fn device_v6() { target_os = "macos", target_os = "tvos", target_os = "watchos", - target_os = "wasi", ) ))] #[test] @@ -1137,7 +1136,6 @@ fn sendfile() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", - target_os = "wasi", ) ))] #[test] @@ -1178,7 +1176,6 @@ fn domain() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", - target_os = "wasi", ) ))] #[test] @@ -1227,7 +1224,7 @@ fn r#type() { } } -#[cfg(all(feature = "all", any(target_os = "linux", target_os = "wasi")))] +#[cfg(all(feature = "all", target_os = "linux"))] #[test] fn cpu_affinity() { let socket = Socket::new(Domain::IPV4, Type::STREAM, None).unwrap(); @@ -1512,7 +1509,7 @@ fn join_leave_ssm_v4() { } #[test] -#[cfg(all(feature = "all", not(target_os = "redox")))] +#[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "wasi"))))] fn header_included() { let socket = match Socket::new(Domain::IPV4, Type::RAW, None) { Ok(socket) => socket, From 521d44587b0a64ec77ea0984ff1ec00411fe3566 Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Mon, 28 Aug 2023 15:17:44 +0400 Subject: [PATCH 25/28] Use normal libc for unix, libc-wasix for wasix --- Cargo.toml | 7 +++++-- src/lib.rs | 3 +++ tests/socket.rs | 4 ++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 861bc005..0e9b9b7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,10 +34,13 @@ targets = ["aarch64-apple-ios", "aarch64-linux-android", "x86_64-apple-darwin", [package.metadata.playground] features = ["all"] -[target.'cfg(any(unix, target_os = "wasi"))'.dependencies] +[target.'cfg(unix)'.dependencies] # Temporary, must be updated to point to the official libc package as soon # as WASIX-related changes are merged in. -libc = { git = "https://github.com/wasix-org/libc.git", branch = "main" } +libc = "0.2.147" + +[target.'cfg(target_os = "wasi")'.dependencies] +libc-wasix = "0.2.147" [target.'cfg(windows)'.dependencies.windows-sys] version = "0.48" diff --git a/src/lib.rs b/src/lib.rs index 4f97af4a..3e3bbee1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -174,6 +174,9 @@ mod sockaddr; mod socket; mod sockref; +#[cfg(target_os = "wasi")] +extern crate libc_wasix as libc; + #[cfg_attr(unix, path = "sys/unix.rs")] #[cfg_attr(windows, path = "sys/windows.rs")] #[cfg_attr(target_os = "wasi", path = "sys/wasi.rs")] diff --git a/tests/socket.rs b/tests/socket.rs index 153153bc..106ce65c 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -1,4 +1,8 @@ #![allow(clippy::bool_assert_comparison)] + +#[cfg(target_os = "wasi")] +extern crate libc_wasix as libc; + #[cfg(all( feature = "all", any( From b8f14197739ee256a30088ab658ae6d72c42821e Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Thu, 31 Aug 2023 15:26:57 +0400 Subject: [PATCH 26/28] Fix feature=all tests --- tests/socket.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/socket.rs b/tests/socket.rs index 106ce65c..31c01919 100644 --- a/tests/socket.rs +++ b/tests/socket.rs @@ -109,7 +109,7 @@ fn type_fmt_debug() { let tests = &[ (Type::STREAM, "SOCK_STREAM"), (Type::DGRAM, "SOCK_DGRAM"), - #[cfg(feature = "all")] + #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "wasi"))))] (Type::SEQPACKET, "SOCK_SEQPACKET"), #[cfg(all(feature = "all", not(any(target_os = "redox", target_os = "wasi"))))] (Type::RAW, "SOCK_RAW"), @@ -290,7 +290,6 @@ fn no_common_flags() { target_os = "freebsd", target_os = "fuchsia", target_os = "linux", - target_os = "wasi", target_os = "netbsd", target_os = "openbsd" ) From 4bd0d7ead01234f4d6990249f5e811b92a88791d Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Thu, 31 Aug 2023 17:31:11 +0400 Subject: [PATCH 27/28] Install cargo-wasix from prebuilt binaries --- .github/workflows/main.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6777785a..883926bb 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -52,7 +52,8 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: taiki-e/install-action@cargo-hack - uses: wasmerio/setup-wasmer@v2 - - run: cargo install cargo-wasix + - name: Install cargo-wasix + run: curl --proto '=https' --tlsv1.2 -LsSf https://github.com/wasix-org/cargo-wasix/releases/latest/download/cargo-wasix-installer.sh | sh - run: cargo wasix download-toolchain - name: Run tests run: cargo +wasix hack test --feature-powerset --target wasm32-wasmer-wasi -- -- --nocapture && cargo +wasix hack test --feature-powerset --release --target wasm32-wasmer-wasi -- -- --nocapture @@ -86,7 +87,8 @@ jobs: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable - uses: taiki-e/install-action@cargo-hack - - run: cargo install cargo-wasix + - name: Install cargo-wasix + run: curl --proto '=https' --tlsv1.2 -LsSf https://github.com/wasix-org/cargo-wasix/releases/latest/download/cargo-wasix-installer.sh | sh - run: cargo wasix download-toolchain - name: Run check run: cargo +wasix hack check --feature-powerset --all-targets --examples --bins --tests --target wasm32-wasmer-wasi From 675a53d27e56fd144a2fc69e532134c45d685fed Mon Sep 17 00:00:00 2001 From: Arshia Ghafoori Date: Thu, 31 Aug 2023 17:45:13 +0400 Subject: [PATCH 28/28] Fix a comment in Cargo.toml --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0e9b9b7a..7f46585f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,10 +35,10 @@ targets = ["aarch64-apple-ios", "aarch64-linux-android", "x86_64-apple-darwin", features = ["all"] [target.'cfg(unix)'.dependencies] -# Temporary, must be updated to point to the official libc package as soon -# as WASIX-related changes are merged in. libc = "0.2.147" +# Temporary, must be updated to point to the official libc package as soon +# as WASIX-related changes are merged in. [target.'cfg(target_os = "wasi")'.dependencies] libc-wasix = "0.2.147"