A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
deduplicate ip_name_lookup & relocate util helpers (#13944)
Dave Bakker09ec25294422
diff --git a/crates/wasi/src/p2/host/network.rs b/crates/wasi/src/p2/host/network.rsindex 07dcc478b7..501483a872 100644--- a/crates/wasi/src/p2/host/network.rs+++ b/crates/wasi/src/p2/host/network.rs@@ -2,8 +2,9 @@ use crate::p2::SocketError;use crate::p2::bindings::sockets::network::{self, ErrorCode, IpAddress, IpSocketAddress, Ipv4SocketAddress, Ipv6SocketAddress,};-use crate::sockets::WasiSocketsCtxView;-use crate::sockets::util::{from_ipv4_addr, from_ipv6_addr, to_ipv4_addr, to_ipv6_addr};+use crate::sockets::{+ WasiSocketsCtxView, from_ipv4_addr, from_ipv6_addr, to_ipv4_addr, to_ipv6_addr,+};use rustix::io::Errno;use std::io;use wasmtime::Error;diff --git a/crates/wasi/src/p2/ip_name_lookup.rs b/crates/wasi/src/p2/ip_name_lookup.rsindex 5f73ee1deb..7a228bb8f1 100644--- a/crates/wasi/src/p2/ip_name_lookup.rs+++ b/crates/wasi/src/p2/ip_name_lookup.rs@@ -1,22 +1,16 @@use crate::p2::SocketError;use crate::p2::bindings::sockets::ip_name_lookup::{Host, HostResolveAddressStream};use crate::p2::bindings::sockets::network::{ErrorCode, IpAddress, Network};-use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking};-use crate::sockets::WasiSocketsCtxView;-use std::mem;-use std::net::ToSocketAddrs;-use std::pin::Pin;+use crate::sockets::ip_name_lookup::resolve_addresses;+use crate::sockets::{MaybeReady, WasiSocketsCtxView, noop_cx};+use std::net::IpAddr;+use std::task::Poll;use std::vec;use wasmtime::Result;use wasmtime::component::Resource;use wasmtime_wasi_io::poll::{DynPollable, Pollable, subscribe};-use crate::sockets::util::{from_ipv4_addr, from_ipv6_addr, parse_host};--pub enum ResolveAddressStream {- Waiting(AbortOnDropJoinHandle<Result<Vec<IpAddress>, SocketError>>),- Done(Result<vec::IntoIter<IpAddress>, SocketError>),-}+pub struct ResolveAddressStream(MaybeReady<Result<vec::IntoIter<IpAddr>, ErrorCode>>);impl Host for WasiSocketsCtxView<'_> {fn resolve_addresses(@@ -29,15 +23,16 @@ impl Host for WasiSocketsCtxView<'_> {// use for it._ = self.table.get(&network)?;- let host = parse_host(&name)?;+ let fut = resolve_addresses(&self.ctx, name);+ let stream = ResolveAddressStream(MaybeReady::poll_or_spawn(async move {+ Ok(fut.await?.into_iter())+ }));- if !self.ctx.allowed_network_uses.ip_name_lookup {- return Err(ErrorCode::PermanentResolverFailure.into());+ // Attempt to surface errors immediately.+ if let MaybeReady::Ready(Err(err)) = &stream.0 {+ return Err((*err).into());}-- let task = spawn_blocking(move || blocking_resolve(&host));- let resource = self.table.push(ResolveAddressStream::Waiting(task))?;- Ok(resource)+ Ok(self.table.push(stream)?)}}@@ -47,22 +42,13 @@ impl HostResolveAddressStream for WasiSocketsCtxView<'_> {resource: Resource<ResolveAddressStream>,) -> Result<Option<IpAddress>, SocketError> {let stream: &mut ResolveAddressStream = self.table.get_mut(&resource)?;- loop {- match stream {- ResolveAddressStream::Waiting(future) => {- match crate::runtime::poll_noop(Pin::new(future)) {- Some(result) => {- *stream = ResolveAddressStream::Done(result.map(|v| v.into_iter()));- }- None => return Err(ErrorCode::WouldBlock.into()),- }- }- ResolveAddressStream::Done(slot @ Err(_)) => {- mem::replace(slot, Ok(Vec::new().into_iter()))?;- unreachable!();- }- ResolveAddressStream::Done(Ok(iter)) => return Ok(iter.next()),- }+ let Poll::Ready(result) = stream.0.poll_ready(&mut noop_cx()) else {+ return Err(ErrorCode::WouldBlock.into());+ };++ match result {+ Ok(iter) => Ok(iter.next().map(|addr| addr.into())),+ Err(err) => Err((*err).into()),}}@@ -82,27 +68,6 @@ impl HostResolveAddressStream for WasiSocketsCtxView<'_> {#[async_trait::async_trait]impl Pollable for ResolveAddressStream {async fn ready(&mut self) {- if let ResolveAddressStream::Waiting(future) = self {- *self = ResolveAddressStream::Done(future.await.map(|v| v.into_iter()));- }- }-}--fn blocking_resolve(host: &url::Host) -> Result<Vec<IpAddress>, SocketError> {- match host {- url::Host::Ipv4(v4addr) => Ok(vec![IpAddress::Ipv4(from_ipv4_addr(*v4addr))]),- url::Host::Ipv6(v6addr) => Ok(vec![IpAddress::Ipv6(from_ipv6_addr(*v6addr))]),- url::Host::Domain(domain) => {- // For now use the standard library to perform actual resolution through- // the usage of the `ToSocketAddrs` trait. This is only- // resolving names, not ports, so force the port to be 0.- let addresses = (domain.as_str(), 0)- .to_socket_addrs()- .map_err(|_| ErrorCode::NameUnresolvable)? // If/when we use `getaddrinfo` directly, map the error properly.- .map(|addr| addr.ip().to_canonical().into())- .collect();-- Ok(addresses)- }+ std::future::poll_fn(|cx| self.0.poll_ready(cx).map(|_| ())).await}}diff --git a/crates/wasi/src/p2/network.rs b/crates/wasi/src/p2/network.rsindex b7f33575cb..442181d9f8 100644--- a/crates/wasi/src/p2/network.rs+++ b/crates/wasi/src/p2/network.rs@@ -24,30 +24,47 @@ impl From<rustix::io::Errno> for SocketError {}}-impl From<crate::sockets::util::ErrorCode> for SocketError {- fn from(error: crate::sockets::util::ErrorCode) -> Self {+impl From<crate::sockets::ErrorCode> for SocketError {+ fn from(error: crate::sockets::ErrorCode) -> Self {ErrorCode::from(error).into()}}-impl From<crate::sockets::util::ErrorCode> for ErrorCode {- fn from(error: crate::sockets::util::ErrorCode) -> Self {+impl From<crate::sockets::ErrorCode> for ErrorCode {+ fn from(error: crate::sockets::ErrorCode) -> Self {match error {- crate::sockets::util::ErrorCode::Other => Self::Unknown,- crate::sockets::util::ErrorCode::AccessDenied => Self::AccessDenied,- crate::sockets::util::ErrorCode::NotSupported => Self::NotSupported,- crate::sockets::util::ErrorCode::InvalidArgument => Self::InvalidArgument,- crate::sockets::util::ErrorCode::OutOfMemory => Self::OutOfMemory,- crate::sockets::util::ErrorCode::Timeout => Self::Timeout,- crate::sockets::util::ErrorCode::InvalidState => Self::InvalidState,- crate::sockets::util::ErrorCode::AddressNotBindable => Self::AddressNotBindable,- crate::sockets::util::ErrorCode::AddressInUse => Self::AddressInUse,- crate::sockets::util::ErrorCode::RemoteUnreachable => Self::RemoteUnreachable,- crate::sockets::util::ErrorCode::ConnectionRefused => Self::ConnectionRefused,- crate::sockets::util::ErrorCode::ConnectionBroken => Self::Unknown,- crate::sockets::util::ErrorCode::ConnectionReset => Self::ConnectionReset,- crate::sockets::util::ErrorCode::ConnectionAborted => Self::ConnectionAborted,- crate::sockets::util::ErrorCode::DatagramTooLarge => Self::DatagramTooLarge,+ crate::sockets::ErrorCode::Other => Self::Unknown,+ crate::sockets::ErrorCode::AccessDenied => Self::AccessDenied,+ crate::sockets::ErrorCode::NotSupported => Self::NotSupported,+ crate::sockets::ErrorCode::InvalidArgument => Self::InvalidArgument,+ crate::sockets::ErrorCode::OutOfMemory => Self::OutOfMemory,+ crate::sockets::ErrorCode::Timeout => Self::Timeout,+ crate::sockets::ErrorCode::InvalidState => Self::InvalidState,+ crate::sockets::ErrorCode::AddressNotBindable => Self::AddressNotBindable,+ crate::sockets::ErrorCode::AddressInUse => Self::AddressInUse,+ crate::sockets::ErrorCode::RemoteUnreachable => Self::RemoteUnreachable,+ crate::sockets::ErrorCode::ConnectionRefused => Self::ConnectionRefused,+ crate::sockets::ErrorCode::ConnectionBroken => Self::Unknown,+ crate::sockets::ErrorCode::ConnectionReset => Self::ConnectionReset,+ crate::sockets::ErrorCode::ConnectionAborted => Self::ConnectionAborted,+ crate::sockets::ErrorCode::DatagramTooLarge => Self::DatagramTooLarge,+ }+ }+}++impl From<crate::sockets::ip_name_lookup::ErrorCode> for ErrorCode {+ fn from(code: crate::sockets::ip_name_lookup::ErrorCode) -> Self {+ match code {+ crate::sockets::ip_name_lookup::ErrorCode::AccessDenied => Self::AccessDenied,+ crate::sockets::ip_name_lookup::ErrorCode::InvalidArgument => Self::InvalidArgument,+ crate::sockets::ip_name_lookup::ErrorCode::NameUnresolvable => Self::NameUnresolvable,+ crate::sockets::ip_name_lookup::ErrorCode::TemporaryResolverFailure => {+ Self::TemporaryResolverFailure+ }+ crate::sockets::ip_name_lookup::ErrorCode::PermanentResolverFailure => {+ Self::PermanentResolverFailure+ }+ crate::sockets::ip_name_lookup::ErrorCode::Other => Self::Unknown,}}}diff --git a/crates/wasi/src/p2/tcp.rs b/crates/wasi/src/p2/tcp.rsindex 72e3ab5ab7..f779f0ae30 100644--- a/crates/wasi/src/p2/tcp.rs+++ b/crates/wasi/src/p2/tcp.rs@@ -197,7 +197,7 @@ impl WriteState {Ok(n) => {let _ = bytes.split_to(n);}- Err(crate::sockets::util::ErrorCode::ConnectionBroken) => {+ Err(crate::sockets::ErrorCode::ConnectionBroken) => {return Err(WriteError::Closed);}Err(e) => {diff --git a/crates/wasi/src/p2/udp.rs b/crates/wasi/src/p2/udp.rsindex 49a6bf9541..5a188b766d 100644--- a/crates/wasi/src/p2/udp.rs+++ b/crates/wasi/src/p2/udp.rs@@ -81,7 +81,11 @@ impl IncomingDatagramStream {self.current_recv = Some(recv);}- self.current_recv.as_mut().unwrap().poll_ready(cx)+ self.current_recv+ .as_mut()+ .unwrap()+ .poll_ready(cx)+ .map(|_| ())}pub(crate) fn try_recv(&mut self) -> Result<(Vec<u8>, SocketAddr), ErrorCode> {@@ -113,7 +117,7 @@ impl OutgoingDatagramStream {cx: &mut std::task::Context<'_>,) -> std::task::Poll<()> {match &mut self.prev_send {- Some(send) => send.poll_ready(cx),+ Some(send) => send.poll_ready(cx).map(|_| ()),None => std::task::Poll::Ready(()),}}diff --git a/crates/wasi/src/p3/sockets/conv.rs b/crates/wasi/src/p3/sockets/conv.rsindex 8c3601f217..881c1f445f 100644--- a/crates/wasi/src/p3/sockets/conv.rs+++ b/crates/wasi/src/p3/sockets/conv.rs@@ -1,7 +1,8 @@use crate::p3::bindings::sockets::types;use crate::p3::sockets::SocketError;-use crate::sockets::SocketAddressFamily;-use crate::sockets::util::{from_ipv4_addr, from_ipv6_addr, to_ipv4_addr, to_ipv6_addr};+use crate::sockets::{+ SocketAddressFamily, from_ipv4_addr, from_ipv6_addr, to_ipv4_addr, to_ipv6_addr,+};use core::net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6};use rustix::io::Errno;use std::net::ToSocketAddrs;@@ -204,30 +205,49 @@ impl From<&Errno> for types::ErrorCode {}}-impl From<crate::sockets::util::ErrorCode> for types::ErrorCode {- fn from(code: crate::sockets::util::ErrorCode) -> Self {+impl From<crate::sockets::ErrorCode> for types::ErrorCode {+ fn from(code: crate::sockets::ErrorCode) -> Self {match code {- crate::sockets::util::ErrorCode::Other => Self::Other(None),- crate::sockets::util::ErrorCode::AccessDenied => Self::AccessDenied,- crate::sockets::util::ErrorCode::NotSupported => Self::NotSupported,- crate::sockets::util::ErrorCode::InvalidArgument => Self::InvalidArgument,- crate::sockets::util::ErrorCode::OutOfMemory => Self::OutOfMemory,- crate::sockets::util::ErrorCode::Timeout => Self::Timeout,- crate::sockets::util::ErrorCode::InvalidState => Self::InvalidState,- crate::sockets::util::ErrorCode::AddressNotBindable => Self::AddressNotBindable,- crate::sockets::util::ErrorCode::AddressInUse => Self::AddressInUse,- crate::sockets::util::ErrorCode::RemoteUnreachable => Self::RemoteUnreachable,- crate::sockets::util::ErrorCode::ConnectionRefused => Self::ConnectionRefused,- crate::sockets::util::ErrorCode::ConnectionBroken => Self::ConnectionBroken,- crate::sockets::util::ErrorCode::ConnectionReset => Self::ConnectionReset,- crate::sockets::util::ErrorCode::ConnectionAborted => Self::ConnectionAborted,- crate::sockets::util::ErrorCode::DatagramTooLarge => Self::DatagramTooLarge,+ crate::sockets::ErrorCode::Other => Self::Other(None),+ crate::sockets::ErrorCode::AccessDenied => Self::AccessDenied,+ crate::sockets::ErrorCode::NotSupported => Self::NotSupported,+ crate::sockets::ErrorCode::InvalidArgument => Self::InvalidArgument,+ crate::sockets::ErrorCode::OutOfMemory => Self::OutOfMemory,+ crate::sockets::ErrorCode::Timeout => Self::Timeout,+ crate::sockets::ErrorCode::InvalidState => Self::InvalidState,+ crate::sockets::ErrorCode::AddressNotBindable => Self::AddressNotBindable,+ crate::sockets::ErrorCode::AddressInUse => Self::AddressInUse,+ crate::sockets::ErrorCode::RemoteUnreachable => Self::RemoteUnreachable,+ crate::sockets::ErrorCode::ConnectionRefused => Self::ConnectionRefused,+ crate::sockets::ErrorCode::ConnectionBroken => Self::ConnectionBroken,+ crate::sockets::ErrorCode::ConnectionReset => Self::ConnectionReset,+ crate::sockets::ErrorCode::ConnectionAborted => Self::ConnectionAborted,+ crate::sockets::ErrorCode::DatagramTooLarge => Self::DatagramTooLarge,}}}-impl From<crate::sockets::util::ErrorCode> for SocketError {- fn from(code: crate::sockets::util::ErrorCode) -> Self {+impl From<crate::sockets::ErrorCode> for SocketError {+ fn from(code: crate::sockets::ErrorCode) -> Self {SocketError::from(types::ErrorCode::from(code))}}++impl From<crate::sockets::ip_name_lookup::ErrorCode>+ for crate::p3::bindings::sockets::ip_name_lookup::ErrorCode+{+ fn from(code: crate::sockets::ip_name_lookup::ErrorCode) -> Self {+ match code {+ crate::sockets::ip_name_lookup::ErrorCode::AccessDenied => Self::AccessDenied,+ crate::sockets::ip_name_lookup::ErrorCode::InvalidArgument => Self::InvalidArgument,+ crate::sockets::ip_name_lookup::ErrorCode::NameUnresolvable => Self::NameUnresolvable,+ crate::sockets::ip_name_lookup::ErrorCode::TemporaryResolverFailure => {+ Self::TemporaryResolverFailure+ }+ crate::sockets::ip_name_lookup::ErrorCode::PermanentResolverFailure => {+ Self::PermanentResolverFailure+ }+ crate::sockets::ip_name_lookup::ErrorCode::Other => Self::Other(None),+ }+ }+}diff --git a/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs b/crates/wasi/src/p3/sockets/host/ip_name_lookup.rsindex 9a024761b9..084e9af317 100644--- a/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs+++ b/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs@@ -1,38 +1,20 @@-use tokio::net::lookup_host;-use wasmtime::component::Accessor;-use crate::p3::bindings::sockets::ip_name_lookup::{ErrorCode, Host, HostWithStore};use crate::p3::bindings::sockets::types;use crate::p3::sockets::WasiSockets;use crate::sockets::WasiSocketsCtxView;-use crate::sockets::util::{from_ipv4_addr, from_ipv6_addr, parse_host};+use crate::sockets::ip_name_lookup::resolve_addresses;+use wasmtime::component::Accessor;impl<U> HostWithStore<U> for WasiSockets {async fn resolve_addresses(store: &Accessor<U, Self>,name: String,) -> wasmtime::Result<Result<Vec<types::IpAddress>, ErrorCode>> {- let Ok(host) = parse_host(&name) else {- return Ok(Err(ErrorCode::InvalidArgument));- };- if !store.with(|mut view| view.get().ctx.allowed_network_uses.ip_name_lookup) {- return Ok(Err(ErrorCode::PermanentResolverFailure));- }- match host {- url::Host::Ipv4(addr) => Ok(Ok(vec![types::IpAddress::Ipv4(from_ipv4_addr(addr))])),- url::Host::Ipv6(addr) => Ok(Ok(vec![types::IpAddress::Ipv6(from_ipv6_addr(addr))])),- url::Host::Domain(domain) => {- // This is only resolving names, not ports, so force the port to be 0.- if let Ok(addrs) = lookup_host((domain.as_str(), 0)).await {- Ok(Ok(addrs- .map(|addr| addr.ip().to_canonical().into())- .collect()))- } else {- // If/when we use `getaddrinfo` directly, map the error properly.- Ok(Err(ErrorCode::NameUnresolvable))- }- }- }+ let fut = store.with(|mut view| resolve_addresses(&view.get().ctx, name));+ Ok(match fut.await {+ Ok(addrs) => Ok(addrs.into_iter().map(|addr| addr.into()).collect()),+ Err(err) => Err(err.into()),+ })}}diff --git a/crates/wasi/src/sockets/ip_name_lookup.rs b/crates/wasi/src/sockets/ip_name_lookup.rsnew file mode 100644index 0000000000..a88306e279--- /dev/null+++ b/crates/wasi/src/sockets/ip_name_lookup.rs@@ -0,0 +1,52 @@+use tracing::debug;++use crate::sockets::WasiSocketsCtx;+use std::{net::IpAddr, str::FromStr};++#[derive(Debug, Clone)]+#[allow(unused, reason = "want to retain parity with the WIT enum")]+pub enum ErrorCode {+ AccessDenied,+ InvalidArgument,+ NameUnresolvable,+ TemporaryResolverFailure,+ PermanentResolverFailure,+ Other,+}++pub(crate) fn resolve_addresses(+ ctx: &WasiSocketsCtx,+ name: String,+) -> impl Future<Output = Result<Vec<IpAddr>, ErrorCode>> + Send + use<> {+ let allowed = ctx.allowed_network_uses.ip_name_lookup;++ async move {+ if !allowed {+ return Err(ErrorCode::PermanentResolverFailure);+ }++ // `url::Host::parse` serves us two purposes:+ // 1. validate the input is a valid domain name or IP,+ // 2. convert unicode domains to punycode.+ let domain = match url::Host::parse(&name) {+ Ok(url::Host::Domain(domain)) => domain,+ Ok(url::Host::Ipv4(addr)) => return Ok(vec![IpAddr::V4(addr)]),+ Ok(url::Host::Ipv6(addr)) => return Ok(vec![IpAddr::V6(addr)]),+ // `url::Host::parse` doesn't understand bare IPv6 addresses without [brackets]+ Err(_) if let Ok(addr) = std::net::Ipv6Addr::from_str(&name) => {+ return Ok(vec![IpAddr::V6(addr)]);+ }+ Err(_) => return Err(ErrorCode::InvalidArgument),+ };++ let addrs = tokio::net::lookup_host((domain.as_str(), 0))+ .await+ .map_err(|e| {+ debug!("DNS resolution of `{}` failed because: {}", domain, e);+ // If/when we use `getaddrinfo` directly, map the error properly.+ ErrorCode::NameUnresolvable+ })?;++ Ok(addrs.map(|addr| addr.ip().to_canonical()).collect())+ }+}diff --git a/crates/wasi/src/sockets/mod.rs b/crates/wasi/src/sockets/mod.rsindex e4013e4fe1..4d072d50b2 100644--- a/crates/wasi/src/sockets/mod.rs+++ b/crates/wasi/src/sockets/mod.rs@@ -1,13 +1,19 @@+use core::fmt;use core::future::Future;+use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};use core::ops::Deref;+use rustix::fd::AsFd;+use rustix::io::Errno;+use rustix::net::sockopt;use std::pin::Pin;use std::sync::Arc;-use std::{net::SocketAddr, task::Poll};+use std::task::Poll;+use tracing::debug;use wasmtime::component::{HasData, ResourceTable};+pub(crate) mod ip_name_lookup;mod tcp;mod udp;-pub(crate) mod util;pub use tcp::TcpSocket;pub(crate) use tcp::{TcpListenStream, TcpReceiveStream, TcpSendStream};pub use udp::UdpSocket;@@ -56,14 +62,6 @@ impl HasData for WasiSockets {type Data<'a> = WasiSocketsCtxView<'a>;}-/// Value taken from rust std library.-pub(crate) const DEFAULT_TCP_BACKLOG: u32 = 128;--/// Theoretical maximum byte size of a UDP datagram, the real limit is lower,-/// but we do not account for e.g. the transport layer here for simplicity.-/// In practice, datagrams are typically less than 1500 bytes.-pub(crate) const MAX_UDP_DATAGRAM_SIZE: usize = u16::MAX as usize;-#[derive(Clone, Default)]pub struct WasiSocketsCtx {pub(crate) socket_addr_check: SocketAddrCheck,@@ -249,7 +247,7 @@ impl<T> MaybeReady<T> {T: Send + 'static,{let mut fut = Box::pin(fut);- match fut.as_mut().poll(&mut noop_cx()) {+ match crate::runtime::with_ambient_tokio_runtime(|| fut.as_mut().poll(&mut noop_cx())) {Poll::Ready(val) => Self::Ready(val),Poll::Pending => Self::new(crate::runtime::spawn(fut)),}@@ -260,16 +258,19 @@ impl<T> MaybeReady<T> {Self::Pending(_) => panic!("future not ready"),}}- pub(crate) fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<()> {+ pub(crate) fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<&mut T> {match self {Self::Pending(fut) => match fut.as_mut().poll(cx) {Poll::Ready(val) => {*self = Self::Ready(val);- Poll::Ready(())+ Poll::Ready(match self {+ Self::Ready(val) => val,+ _ => unreachable!(),+ })}Poll::Pending => Poll::Pending,},- Self::Ready(_) => Poll::Ready(()),+ Self::Ready(val) => Poll::Ready(val),}}pub(crate) async fn into_future(self) -> T {@@ -283,3 +284,296 @@ impl<T> MaybeReady<T> {pub(crate) fn noop_cx() -> std::task::Context<'static> {std::task::Context::from_waker(futures::task::noop_waker_ref())}++#[derive(Clone, Copy, Debug)]+pub enum ErrorCode {+ AccessDenied,+ NotSupported,+ InvalidArgument,+ OutOfMemory,+ Timeout,+ InvalidState,+ AddressNotBindable,+ AddressInUse,+ RemoteUnreachable,+ ConnectionRefused,+ ConnectionBroken,+ ConnectionReset,+ ConnectionAborted,+ DatagramTooLarge,+ Other,+}++impl fmt::Display for ErrorCode {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ fmt::Debug::fmt(self, f)+ }+}++impl std::error::Error for ErrorCode {}++impl From<std::io::Error> for ErrorCode {+ fn from(value: std::io::Error) -> Self {+ (&value).into()+ }+}++impl From<&std::io::Error> for ErrorCode {+ fn from(value: &std::io::Error) -> Self {+ // Attempt the more detailed native error code first:+ if let Some(errno) = Errno::from_io_error(value) {+ return errno.into();+ }++ match value.kind() {+ std::io::ErrorKind::AddrInUse => Self::AddressInUse,+ std::io::ErrorKind::AddrNotAvailable => Self::AddressNotBindable,+ std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,+ std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,+ std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,+ std::io::ErrorKind::InvalidInput => Self::InvalidArgument,+ std::io::ErrorKind::NotConnected => Self::InvalidState,+ std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,+ std::io::ErrorKind::PermissionDenied => Self::AccessDenied,+ std::io::ErrorKind::TimedOut => Self::Timeout,+ std::io::ErrorKind::Unsupported => Self::NotSupported,+ std::io::ErrorKind::HostUnreachable => Self::RemoteUnreachable,+ std::io::ErrorKind::NetworkUnreachable => Self::RemoteUnreachable,+ std::io::ErrorKind::NetworkDown => Self::RemoteUnreachable,+ std::io::ErrorKind::BrokenPipe => Self::ConnectionBroken,+ _ => {+ debug!("unknown I/O error: {value}");+ Self::Other+ }+ }+ }+}++impl From<Errno> for ErrorCode {+ fn from(value: Errno) -> Self {+ (&value).into()+ }+}++impl From<&Errno> for ErrorCode {+ fn from(value: &Errno) -> Self {+ match *value {+ #[cfg(not(windows))]+ Errno::PERM => Self::AccessDenied,+ Errno::ACCESS => Self::AccessDenied,+ Errno::ADDRINUSE => Self::AddressInUse,+ Errno::ADDRNOTAVAIL => Self::AddressNotBindable,+ Errno::TIMEDOUT => Self::Timeout,+ #[cfg(not(windows))]+ Errno::PIPE => Self::ConnectionBroken,+ Errno::CONNREFUSED => Self::ConnectionRefused,+ Errno::CONNRESET => Self::ConnectionReset,+ Errno::CONNABORTED => Self::ConnectionAborted,+ Errno::INVAL => Self::InvalidArgument,+ Errno::HOSTUNREACH => Self::RemoteUnreachable,+ Errno::HOSTDOWN => Self::RemoteUnreachable,+ Errno::NETDOWN => Self::RemoteUnreachable,+ Errno::NETUNREACH => Self::RemoteUnreachable,+ #[cfg(target_os = "linux")]+ Errno::NONET => Self::RemoteUnreachable,+ Errno::ISCONN => Self::InvalidState,+ Errno::NOTCONN => Self::InvalidState,+ Errno::DESTADDRREQ => Self::InvalidState,+ Errno::MSGSIZE => Self::DatagramTooLarge,+ #[cfg(not(windows))]+ Errno::NOMEM => Self::OutOfMemory,+ Errno::NOBUFS => Self::OutOfMemory,+ Errno::OPNOTSUPP => Self::NotSupported,+ Errno::NOPROTOOPT => Self::NotSupported,+ Errno::PFNOSUPPORT => Self::NotSupported,+ Errno::PROTONOSUPPORT => Self::NotSupported,+ Errno::PROTOTYPE => Self::NotSupported,+ Errno::SOCKTNOSUPPORT => Self::NotSupported,+ Errno::AFNOSUPPORT => Self::NotSupported,++ // FYI, EINPROGRESS should have already been handled by connect.+ _ => {+ debug!("unknown I/O error: {value}");+ Self::Other+ }+ }+ }+}++fn is_deprecated_ipv4_compatible(addr: Ipv6Addr) -> bool {+ matches!(addr.segments(), [0, 0, 0, 0, 0, 0, _, _])+ && addr != Ipv6Addr::UNSPECIFIED+ && addr != Ipv6Addr::LOCALHOST+}++pub(crate) fn is_valid_address_family(addr: IpAddr, socket_family: SocketAddressFamily) -> bool {+ match (socket_family, addr) {+ (SocketAddressFamily::Ipv4, IpAddr::V4(..)) => true,+ (SocketAddressFamily::Ipv6, IpAddr::V6(ipv6)) => {+ // Reject IPv4-*compatible* IPv6 addresses. They have been deprecated+ // since 2006, OS handling of them is inconsistent and our own+ // validations don't take them into account either.+ // Note that these are not the same as IPv4-*mapped* IPv6 addresses.+ !is_deprecated_ipv4_compatible(ipv6) && ipv6.to_ipv4_mapped().is_none()+ }+ _ => false,+ }+}++pub(crate) fn is_valid_remote_address(addr: SocketAddr) -> bool {+ !addr.ip().to_canonical().is_unspecified() && addr.port() != 0+}++pub(crate) fn is_valid_unicast_address(addr: IpAddr) -> bool {+ match addr.to_canonical() {+ IpAddr::V4(ipv4) => !ipv4.is_multicast() && !ipv4.is_broadcast(),+ IpAddr::V6(ipv6) => !ipv6.is_multicast(),+ }+}++pub(crate) fn to_ipv4_addr(addr: (u8, u8, u8, u8)) -> Ipv4Addr {+ let (x0, x1, x2, x3) = addr;+ Ipv4Addr::new(x0, x1, x2, x3)+}++pub(crate) fn from_ipv4_addr(addr: Ipv4Addr) -> (u8, u8, u8, u8) {+ let [x0, x1, x2, x3] = addr.octets();+ (x0, x1, x2, x3)+}++pub(crate) fn to_ipv6_addr(addr: (u16, u16, u16, u16, u16, u16, u16, u16)) -> Ipv6Addr {+ let (x0, x1, x2, x3, x4, x5, x6, x7) = addr;+ Ipv6Addr::new(x0, x1, x2, x3, x4, x5, x6, x7)+}++pub(crate) fn from_ipv6_addr(addr: Ipv6Addr) -> (u16, u16, u16, u16, u16, u16, u16, u16) {+ let [x0, x1, x2, x3, x4, x5, x6, x7] = addr.segments();+ (x0, x1, x2, x3, x4, x5, x6, x7)+}++/*+ * Syscalls wrappers with (opinionated) portability fixes.+ */++fn normalize_get_buffer_size(value: usize) -> usize {+ if cfg!(target_os = "linux") {+ // Linux doubles the value passed to setsockopt to allow space for bookkeeping overhead.+ // getsockopt returns this internally doubled value.+ // We'll half the value to at least get it back into the same ballpark that the application requested it in.+ //+ // This normalized behavior is tested for in: test-programs/src/bin/preview2_tcp_sockopts.rs+ value / 2+ } else {+ value+ }+}++fn normalize_set_buffer_size(value: usize) -> usize {+ value.clamp(1, i32::MAX as usize)+}++fn get_ip_ttl(fd: impl AsFd) -> Result<u8, ErrorCode> {+ let v = sockopt::ip_ttl(fd)?;+ let Ok(v) = v.try_into() else {+ return Err(ErrorCode::NotSupported);+ };+ Ok(v)+}++fn get_ipv6_unicast_hops(fd: impl AsFd) -> Result<u8, ErrorCode> {+ let v = sockopt::ipv6_unicast_hops(fd)?;+ Ok(v)+}++pub(crate) fn get_unicast_hop_limit(+ fd: impl AsFd,+ family: SocketAddressFamily,+) -> Result<u8, ErrorCode> {+ match family {+ SocketAddressFamily::Ipv4 => get_ip_ttl(fd),+ SocketAddressFamily::Ipv6 => get_ipv6_unicast_hops(fd),+ }+}++pub(crate) fn set_unicast_hop_limit(+ fd: impl AsFd,+ family: SocketAddressFamily,+ value: u8,+) -> Result<(), ErrorCode> {+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ //+ // A well-behaved IP application should never send out new packets with TTL 0.+ // We validate the value ourselves because OS'es are not consistent in this.+ // On Linux the validation is even inconsistent between their IPv4 and IPv6 implementation.+ return Err(ErrorCode::InvalidArgument);+ }+ match family {+ SocketAddressFamily::Ipv4 => {+ sockopt::set_ip_ttl(fd, value.into())?;+ }+ SocketAddressFamily::Ipv6 => {+ sockopt::set_ipv6_unicast_hops(fd, Some(value))?;+ }+ }+ Ok(())+}++pub(crate) fn get_receive_buffer_size(fd: impl AsFd) -> Result<u64, ErrorCode> {+ let v = sockopt::socket_recv_buffer_size(fd)?;+ Ok(normalize_get_buffer_size(v).try_into().unwrap_or(u64::MAX))+}++pub(crate) fn set_receive_buffer_size(fd: impl AsFd, value: u64) -> Result<usize, ErrorCode> {+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ return Err(ErrorCode::InvalidArgument);+ }+ let value = value.try_into().unwrap_or(usize::MAX);+ let value = normalize_set_buffer_size(value);+ match sockopt::set_socket_recv_buffer_size(fd, value) {+ // Most platforms (Linux, Windows, Fuchsia, Solaris, Illumos, Haiku, ESP-IDF, ..and more?) treat the value+ // passed to SO_SNDBUF/SO_RCVBUF as a performance tuning hint and silently clamp the input if it exceeds+ // their capability.+ // As far as I can see, only the *BSD family views this option as a hard requirement and fails when the+ // value is out of range. We normalize this behavior in favor of the more commonly understood+ // "performance hint" semantics. In other words; even ENOBUFS is "Ok".+ // A future improvement could be to query the corresponding sysctl on *BSD platforms and clamp the input+ // `size` ourselves, to completely close the gap with other platforms.+ //+ // This normalized behavior is tested for in: test-programs/src/bin/preview2_tcp_sockopts.rs+ Err(Errno::NOBUFS) => {}+ Err(err) => return Err(err.into()),+ _ => {}+ };+ Ok(value)+}++pub(crate) fn get_send_buffer_size(fd: impl AsFd) -> Result<u64, ErrorCode> {+ let v = sockopt::socket_send_buffer_size(fd)?;+ Ok(normalize_get_buffer_size(v).try_into().unwrap_or(u64::MAX))+}++pub(crate) fn set_send_buffer_size(fd: impl AsFd, value: u64) -> Result<usize, ErrorCode> {+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ return Err(ErrorCode::InvalidArgument);+ }+ let value = value.try_into().unwrap_or(usize::MAX);+ let value = normalize_set_buffer_size(value);+ match sockopt::set_socket_send_buffer_size(fd, value) {+ // See comment in `set_receive_buffer_size` for why we ignore NOBUFS.+ Err(Errno::NOBUFS) => {}+ Err(err) => return Err(err.into()),+ _ => {}+ };+ Ok(value)+}++pub(crate) fn unspecified_addr(family: SocketAddressFamily) -> SocketAddr {+ let ip = match family {+ SocketAddressFamily::Ipv4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED),+ SocketAddressFamily::Ipv6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED),+ };+ SocketAddr::new(ip, 0)+}diff --git a/crates/wasi/src/sockets/tcp.rs b/crates/wasi/src/sockets/tcp.rsindex 44b7c88e06..0d8c249e1d 100644--- a/crates/wasi/src/sockets/tcp.rs+++ b/crates/wasi/src/sockets/tcp.rs@@ -1,14 +1,9 @@use crate::runtime::with_ambient_tokio_runtime;-use crate::sockets::util::{- ErrorCode, get_unicast_hop_limit, is_valid_address_family, is_valid_remote_address,- is_valid_unicast_address, receive_buffer_size, send_buffer_size, set_keep_alive_count,- set_keep_alive_idle_time, set_keep_alive_interval, set_receive_buffer_size,- set_send_buffer_size, set_unicast_hop_limit, shutdown, tcp_accept, tcp_bind, tcp_reset,- unspecified_addr,-};use crate::sockets::{- DEFAULT_TCP_BACKLOG, MaybeReady, SocketAddrCheck, SocketAddrUse, SocketAddressFamily,- WasiSocketsCtx,+ ErrorCode, MaybeReady, SocketAddrCheck, SocketAddrUse, SocketAddressFamily, WasiSocketsCtx,+ get_receive_buffer_size, get_send_buffer_size, get_unicast_hop_limit, is_valid_address_family,+ is_valid_remote_address, is_valid_unicast_address, set_receive_buffer_size,+ set_send_buffer_size, set_unicast_hop_limit, unspecified_addr,};use rustix::fd::AsFd;use rustix::io::Errno;@@ -16,11 +11,16 @@ use rustix::net::sockopt;use std::fmt::Debug;use std::future::poll_fn;use std::mem;-use std::net::{Shutdown, SocketAddr};+use std::net::SocketAddr;use std::sync::Arc;use std::task::{Poll, ready};use std::time::Duration;+/// Value taken from rust std library.+const DEFAULT_BACKLOG: u32 = 128;++const NANOS_PER_SEC: u64 = 1_000_000_000;+/// The state of a TCP socket.////// This represents the various states a socket can be in during the@@ -116,24 +116,15 @@ impl TcpSocket {) -> Result<Self, ErrorCode> {ctx.allowed_network_uses.check_allowed_tcp()?;- with_ambient_tokio_runtime(|| {- let socket = match family {- SocketAddressFamily::Ipv4 => tokio::net::TcpSocket::new_v4()?,- SocketAddressFamily::Ipv6 => {- let socket = tokio::net::TcpSocket::new_v6()?;- sockopt::set_ipv6_v6only(&socket, true)?;- socket- }- };+ let socket = with_ambient_tokio_runtime(|| socket(family))?;- Ok(Self {- tcp_state: TcpState::Default(socket),- listen_backlog_size: DEFAULT_TCP_BACKLOG,- family,- is_bound: false,- listener_options: Default::default(),- permissions: ctx.socket_addr_check.clone(),- })+ Ok(Self {+ tcp_state: TcpState::Default(socket),+ listen_backlog_size: DEFAULT_BACKLOG,+ family,+ is_bound: false,+ listener_options: Default::default(),+ permissions: ctx.socket_addr_check.clone(),})}@@ -176,7 +167,7 @@ impl TcpSocket {}self.permissions.check(addr, SocketAddrUse::TcpBind).await?;- tcp_bind(sock, addr)?;+ bind(sock, addr)?;Ok(())}@@ -310,7 +301,7 @@ impl TcpSocket {// > socket.if !already_bound {let implicit = unspecified_addr(self.family);- tcp_bind(&sock, implicit)?;+ bind(&sock, implicit)?;}let listener = sock.listen(self.listen_backlog_size).map_err(|err| {@@ -455,10 +446,13 @@ impl TcpSocket {}pub(crate) fn set_keep_alive_idle_time(&mut self, value: u64) -> Result<(), ErrorCode> {- let value = {- let fd = self.as_fd()?;- set_keep_alive_idle_time(fd, value)?- };+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ return Err(ErrorCode::InvalidArgument);+ }+ let fd = self.as_fd()?;+ let value = clamp_keep_alive_time(value);+ sockopt::set_tcp_keepidle(fd, Duration::from_nanos(value))?;self.listener_options.set_keep_alive_idle_time(value);Ok(())}@@ -470,8 +464,13 @@ impl TcpSocket {}pub(crate) fn set_keep_alive_interval(&self, value: u64) -> Result<(), ErrorCode> {+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ return Err(ErrorCode::InvalidArgument);+ }let fd = self.as_fd()?;- set_keep_alive_interval(fd, Duration::from_nanos(value))?;+ let value = clamp_keep_alive_time(value);+ sockopt::set_tcp_keepintvl(fd, Duration::from_nanos(value))?;Ok(())}@@ -482,8 +481,13 @@ impl TcpSocket {}pub(crate) fn set_keep_alive_count(&self, value: u32) -> Result<(), ErrorCode> {+ if value == 0 {+ // WIT: "If the provided value is 0, an `invalid-argument` error is returned."+ return Err(ErrorCode::InvalidArgument);+ }+ let value = clamp_keep_alive_count(value);let fd = self.as_fd()?;- set_keep_alive_count(fd, value)?;+ sockopt::set_tcp_keepcnt(fd, value)?;Ok(())}@@ -504,7 +508,7 @@ impl TcpSocket {pub(crate) fn receive_buffer_size(&self) -> Result<u64, ErrorCode> {let fd = self.as_fd()?;- let n = receive_buffer_size(fd)?;+ let n = get_receive_buffer_size(fd)?;Ok(n)}@@ -519,7 +523,7 @@ impl TcpSocket {pub(crate) fn send_buffer_size(&self) -> Result<u64, ErrorCode> {let fd = self.as_fd()?;- let n = send_buffer_size(fd)?;+ let n = get_send_buffer_size(fd)?;Ok(n)}@@ -552,7 +556,7 @@ impl TcpListenStream {}Err(err) => TcpState::Closed(err),},- listen_backlog_size: DEFAULT_TCP_BACKLOG,+ listen_backlog_size: DEFAULT_BACKLOG,family: self.family,is_bound: true,listener_options: Default::default(),@@ -567,7 +571,7 @@ impl TcpListenStream {self.pending_accept = Some(MaybeReady::new(async move {loop {- match tcp_accept(&listener).await {+ match accept(&listener).await {Ok((client, addr)) => {if permissions.check(addr, SocketAddrUse::TcpAccept)@@ -576,7 +580,7 @@ impl TcpListenStream {{return Ok(client);} else {- tcp_reset(client);+ reset(client);continue;}}@@ -588,7 +592,13 @@ impl TcpListenStream {}));}- with_ambient_tokio_runtime(|| self.pending_accept.as_mut().unwrap().poll_ready(cx))+ with_ambient_tokio_runtime(|| {+ self.pending_accept+ .as_mut()+ .unwrap()+ .poll_ready(cx)+ .map(|_| ())+ })}}@@ -632,7 +642,7 @@ impl TcpSendStream {}impl Drop for TcpSendStream {fn drop(&mut self) {- _ = shutdown(&self.inner, Shutdown::Write);+ _ = rustix::net::shutdown(&self.inner, rustix::net::Shutdown::Write);}}@@ -670,7 +680,7 @@ impl TcpReceiveStream {}impl Drop for TcpReceiveStream {fn drop(&mut self) {- _ = shutdown(&self.inner, Shutdown::Read);+ _ = rustix::net::shutdown(&self.inner, rustix::net::Shutdown::Read);}}@@ -773,3 +783,113 @@ mod does_not_inherit_options {}}}++fn socket(family: SocketAddressFamily) -> std::io::Result<tokio::net::TcpSocket> {+ match family {+ SocketAddressFamily::Ipv4 => tokio::net::TcpSocket::new_v4(),+ SocketAddressFamily::Ipv6 => {+ let socket = tokio::net::TcpSocket::new_v6()?;++ // From the WASI spec:+ // > On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't+ // > be configured otherwise.+ sockopt::set_ipv6_v6only(&socket, true)?;+ Ok(socket)+ }+ }+}++fn bind(socket: &tokio::net::TcpSocket, local_address: SocketAddr) -> Result<(), ErrorCode> {+ // From the WASI spec:+ // > The bind operation shouldn't be affected by the TIME_WAIT state of a+ // > recently closed socket on the same local address. In practice this+ // > means that the SO_REUSEADDR socket option should be set implicitly on+ // > all platforms, except on Windows where this is the default behavior+ // > and SO_REUSEADDR performs something different.+ #[cfg(not(windows))]+ {+ _ = sockopt::set_socket_reuseaddr(&socket, true);+ }++ // Perform the OS bind call.+ socket+ .bind(local_address)+ .map_err(|err| match Errno::from_io_error(&err) {+ // From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:+ // > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket+ //+ // The most common reasons for this error should have already+ // been handled by our own validation.. This error mapping is here+ // just in case there is an edge case we didn't catch.+ Some(Errno::AFNOSUPPORT) => ErrorCode::InvalidArgument,+ // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS+ // Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.+ #[cfg(windows)]+ Some(Errno::NOBUFS) => ErrorCode::AddressInUse,+ _ => err.into(),+ })+}++async fn accept(+ listener: &tokio::net::TcpListener,+) -> std::io::Result<(tokio::net::TcpStream, SocketAddr)> {+ listener+ .accept()+ .await+ .map_err(|err| match Errno::from_io_error(&err) {+ // From: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept#:~:text=WSAEINPROGRESS+ // > WSAEINPROGRESS: A blocking Windows Sockets 1.1 call is in progress,+ // > or the service provider is still processing a callback function.+ //+ // wasi-sockets doesn't have an equivalent to the EINPROGRESS error,+ // because in POSIX this error is only returned by a non-blocking+ // `connect` and wasi-sockets has a different solution for that.+ #[cfg(windows)]+ Some(Errno::INPROGRESS) => Errno::INTR.into(),++ // Normalize Linux' non-standard behavior.+ //+ // From https://man7.org/linux/man-pages/man2/accept.2.html:+ // > Linux accept() passes already-pending network errors on the+ // > new socket as an error code from accept(). This behavior+ // > differs from other BSD socket implementations. (...)+ #[cfg(target_os = "linux")]+ Some(+ Errno::CONNRESET+ | Errno::NETRESET+ | Errno::HOSTUNREACH+ | Errno::HOSTDOWN+ | Errno::NETDOWN+ | Errno::NETUNREACH+ | Errno::PROTO+ | Errno::NOPROTOOPT+ | Errno::NONET+ | Errno::OPNOTSUPP,+ ) => Errno::CONNABORTED.into(),++ _ => err,+ })+}++fn reset(socket: tokio::net::TcpStream) {+ _ = socket.set_zero_linger();+ drop(socket);+}++fn clamp_keep_alive_time(value: u64) -> u64 {+ // Ensure that the value passed to the actual syscall never gets rounded down to 0.+ const MIN: u64 = 1 * NANOS_PER_SEC;++ // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.+ const MAX: u64 = (i16::MAX as u64) * NANOS_PER_SEC;++ value.clamp(MIN, MAX)+}++fn clamp_keep_alive_count(value: u32) -> u32 {+ const MIN_CNT: u32 = 1;+ // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.+ const MAX_CNT: u32 = i8::MAX as u32;++ value.clamp(MIN_CNT, MAX_CNT)+}diff --git a/crates/wasi/src/sockets/udp.rs b/crates/wasi/src/sockets/udp.rsindex c833bd794a..9c236a3e66 100644--- a/crates/wasi/src/sockets/udp.rs+++ b/crates/wasi/src/sockets/udp.rs@@ -1,17 +1,21 @@use crate::runtime::with_ambient_tokio_runtime;-use crate::sockets::util::{- ErrorCode, get_unicast_hop_limit, is_valid_address_family, is_valid_remote_address,- receive_buffer_size, send_buffer_size, set_receive_buffer_size, set_send_buffer_size,- set_unicast_hop_limit, udp_bind, udp_connect, udp_disconnect, udp_socket, unspecified_addr,-};use crate::sockets::{- MAX_UDP_DATAGRAM_SIZE, SocketAddrCheck, SocketAddrUse, SocketAddressFamily, WasiSocketsCtx,+ ErrorCode, SocketAddrCheck, SocketAddrUse, SocketAddressFamily, WasiSocketsCtx,+ get_receive_buffer_size, get_send_buffer_size, get_unicast_hop_limit, is_valid_address_family,+ is_valid_remote_address, set_receive_buffer_size, set_send_buffer_size, set_unicast_hop_limit,+ unspecified_addr,};+use rustix::fd::AsFd;use rustix::io::Errno;use std::net::SocketAddr;use std::sync::Arc;use tracing::debug;+/// Theoretical maximum byte size of a UDP datagram, the real limit is lower,+/// but we do not account for e.g. the transport layer here for simplicity.+/// In practice, datagrams are typically less than 1500 bytes.+pub(crate) const MAX_DATAGRAM_SIZE: usize = u16::MAX as usize;+/// A host UDP socket, plus associated bookkeeping.////// The inner state is wrapped in an Arc because the same underlying socket is@@ -40,15 +44,7 @@ impl UdpSocket {) -> Result<Self, ErrorCode> {cx.allowed_network_uses.check_allowed_udp()?;- let socket = with_ambient_tokio_runtime(|| {- // Manually construct a new socket, because neither std nor tokio- // provides a way to create an unbound UDP socket.- let fd = udp_socket(family)?;- if family == SocketAddressFamily::Ipv6 {- rustix::net::sockopt::set_ipv6_v6only(&fd, true)?;- }- tokio::net::UdpSocket::try_from(std::net::UdpSocket::from(fd))- })?;+ let socket = with_ambient_tokio_runtime(|| socket(family))?;// Native UDP sockets are immediately writable after creation and// existing guest code out in the wild depends on that. However, due to@@ -108,7 +104,7 @@ impl UdpSocket {self.permissions.check(addr, SocketAddrUse::UdpBind).await?;- udp_bind(&self.socket, addr)?;+ bind(&self.socket, addr)?;Ok(())}@@ -144,20 +140,9 @@ impl UdpSocket {}}- let result = udp_connect(&self.socket, addr).map_err(|e| match e {- // The most common reason for AFNOSUPPORT is an invalid address- // family. This should have already been handled by our own- // validation slightly higher up in this function. This error- // mapping is here just in case there is an edge case we didn't catch.- Errno::AFNOSUPPORT => ErrorCode::InvalidArgument,- Errno::INPROGRESS => {- debug!("UDP connect returned EINPROGRESS, which should never happen");- ErrorCode::Other- }- err => err.into(),- });+ let result = connect(&self.socket, addr);self.update_remote_address();- result+ result.map_err(|e| e.into())}pub(crate) fn disconnect(&mut self) -> Result<(), ErrorCode> {@@ -173,9 +158,9 @@ impl UdpSocket {// manually settle the `is_bound` state here:self.is_bound = true;- let result = udp_disconnect(&self.socket).map_err(|e| e.into());+ let result = disconnect(&self.socket);self.update_remote_address();- result+ result.map_err(|e| e.into())}/// Update our internal bookkeeping based on the actual state of the socket.@@ -203,7 +188,7 @@ impl UdpSocket {let is_bound = self.is_bound();async move {- if data.len() > MAX_UDP_DATAGRAM_SIZE {+ if data.len() > MAX_DATAGRAM_SIZE {return Err(ErrorCode::DatagramTooLarge);}@@ -264,7 +249,7 @@ impl UdpSocket {}loop {- let mut data = vec![0; super::MAX_UDP_DATAGRAM_SIZE];+ let mut data = vec![0; MAX_DATAGRAM_SIZE];let (len, addr) = socket.recv_from(&mut data).await?;data.truncate(len);@@ -294,7 +279,7 @@ impl UdpSocket {}pub(crate) fn receive_buffer_size(&self) -> Result<u64, ErrorCode> {- let n = receive_buffer_size(&self.socket)?;+ let n = get_receive_buffer_size(&self.socket)?;Ok(n)}@@ -304,7 +289,7 @@ impl UdpSocket {}pub(crate) fn send_buffer_size(&self) -> Result<u64, ErrorCode> {- let n = send_buffer_size(&self.socket)?;+ let n = get_send_buffer_size(&self.socket)?;Ok(n)}@@ -313,3 +298,114 @@ impl UdpSocket {Ok(())}}++/// Creates a non-blocking/cloexec UDP socket.+fn socket(family: SocketAddressFamily) -> std::io::Result<tokio::net::UdpSocket> {+ // Let the standard library be responsible for handling `WSAStartup`.+ #[cfg(windows)]+ static INIT: std::sync::Once = std::sync::Once::new();+ #[cfg(windows)]+ INIT.call_once(|| {+ let _ = std::net::TcpStream::connect(std::net::SocketAddrV4::new(+ std::net::Ipv4Addr::UNSPECIFIED,+ 0,+ ));+ });++ #[cfg(not(any(windows, target_vendor = "apple")))]+ let flags = rustix::net::SocketFlags::CLOEXEC | rustix::net::SocketFlags::NONBLOCK;+ #[cfg(any(windows, target_vendor = "apple"))]+ let flags = rustix::net::SocketFlags::empty();++ let socket = rustix::net::socket_with(+ match family {+ SocketAddressFamily::Ipv4 => rustix::net::AddressFamily::INET,+ SocketAddressFamily::Ipv6 => rustix::net::AddressFamily::INET6,+ },+ rustix::net::SocketType::DGRAM,+ flags,+ None,+ )?;+ #[cfg(target_vendor = "apple")]+ rustix::io::ioctl_fioclex(&socket)?;+ #[cfg(any(windows, target_vendor = "apple"))]+ rustix::io::ioctl_fionbio(&socket, true)?;++ // From the WASI spec:+ // > On IPv6 sockets, IPV6_V6ONLY is enabled by default and can't+ // > be configured otherwise.+ if family == SocketAddressFamily::Ipv6 {+ rustix::net::sockopt::set_ipv6_v6only(&socket, true)?;+ }++ Ok(tokio::net::UdpSocket::try_from(std::net::UdpSocket::from(+ socket,+ ))?)+}++fn bind(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), Errno> {+ rustix::net::bind(sockfd, &addr).map_err(|err| match err {+ // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS+ // Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.+ #[cfg(windows)]+ Errno::NOBUFS => Errno::ADDRINUSE,+ // From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:+ // > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket+ //+ // The most common reasons for this error should have already+ // been handled by our own validation. This error mapping is here just+ // in case there is an edge case we didn't catch.+ Errno::AFNOSUPPORT => Errno::INVAL,+ _ => err,+ })+}++fn connect(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), Errno> {+ match rustix::net::connect(sockfd.as_fd(), &addr) {+ // When connecting a UDP socket, the OS looks up the best route to the+ // remote address and selects an appropriate outgoing interface.+ // If the new destination routes through an interface different than the+ // previously selected interface, most operating systems will+ // automatically update the socket's local address to match that route.+ //+ // Linux however doesn't do that automatically and we manually+ // dissolve the existing association and then connect again to the+ // new destination.+ #[cfg(target_os = "linux")]+ Err(Errno::INVAL) => {+ _ = disconnect(sockfd.as_fd());+ return rustix::net::connect(sockfd.as_fd(), &addr);+ }+ // The most common reason for AFNOSUPPORT is an invalid address+ // family. This should have already been handled by our own+ // validation. This error mapping is here just in case there is an+ // edge case we didn't catch.+ Err(Errno::AFNOSUPPORT) => Err(Errno::INVAL),+ // EINPROGRESS should only returned by non-blocking TCP sockets,+ // not UDP sockets.+ Err(Errno::INPROGRESS) => {+ debug!("UDP connect returned EINPROGRESS, which should never happen");+ Ok(())+ }+ r => r,+ }+}++fn disconnect(sockfd: impl AsFd) -> Result<(), Errno> {+ match rustix::net::connect_unspec(sockfd) {+ // BSD platforms return an error even if the UDP socket was disconnected successfully.+ //+ // MacOS was kind enough to document this: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html+ // > Datagram sockets may dissolve the association by connecting to an+ // > invalid address, such as a null address or an address with the address+ // > family set to AF_UNSPEC (the error EAFNOSUPPORT will be harmlessly+ // > returned).+ //+ // ... except that this appears to be incomplete, because experiments+ // have shown that MacOS actually returns EINVAL, depending on the+ // address family of the socket.+ #[cfg(target_os = "macos")]+ Err(Errno::INVAL | Errno::AFNOSUPPORT) => Ok(()),+ r => r,+ }+}diff --git a/crates/wasi/src/sockets/util.rs b/crates/wasi/src/sockets/util.rsdeleted file mode 100644index 687bc9ee54..0000000000--- a/crates/wasi/src/sockets/util.rs+++ /dev/null@@ -1,549 +0,0 @@-use crate::sockets::SocketAddressFamily;-use core::fmt;-use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};-use core::str::FromStr as _;-use core::time::Duration;-use rustix::fd::AsFd;-use rustix::io::Errno;-use rustix::net::{bind, connect, connect_unspec, sockopt};-use tracing::debug;--#[derive(Clone, Copy, Debug)]-pub enum ErrorCode {- AccessDenied,- NotSupported,- InvalidArgument,- OutOfMemory,- Timeout,- InvalidState,- AddressNotBindable,- AddressInUse,- RemoteUnreachable,- ConnectionRefused,- ConnectionBroken,- ConnectionReset,- ConnectionAborted,- DatagramTooLarge,- Other,-}--impl fmt::Display for ErrorCode {- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- fmt::Debug::fmt(self, f)- }-}--impl std::error::Error for ErrorCode {}--fn is_deprecated_ipv4_compatible(addr: Ipv6Addr) -> bool {- matches!(addr.segments(), [0, 0, 0, 0, 0, 0, _, _])- && addr != Ipv6Addr::UNSPECIFIED- && addr != Ipv6Addr::LOCALHOST-}--pub fn is_valid_address_family(addr: IpAddr, socket_family: SocketAddressFamily) -> bool {- match (socket_family, addr) {- (SocketAddressFamily::Ipv4, IpAddr::V4(..)) => true,- (SocketAddressFamily::Ipv6, IpAddr::V6(ipv6)) => {- // Reject IPv4-*compatible* IPv6 addresses. They have been deprecated- // since 2006, OS handling of them is inconsistent and our own- // validations don't take them into account either.- // Note that these are not the same as IPv4-*mapped* IPv6 addresses.- !is_deprecated_ipv4_compatible(ipv6) && ipv6.to_ipv4_mapped().is_none()- }- _ => false,- }-}--pub fn is_valid_remote_address(addr: SocketAddr) -> bool {- !addr.ip().to_canonical().is_unspecified() && addr.port() != 0-}--pub fn is_valid_unicast_address(addr: IpAddr) -> bool {- match addr.to_canonical() {- IpAddr::V4(ipv4) => !ipv4.is_multicast() && !ipv4.is_broadcast(),- IpAddr::V6(ipv6) => !ipv6.is_multicast(),- }-}--pub fn to_ipv4_addr(addr: (u8, u8, u8, u8)) -> Ipv4Addr {- let (x0, x1, x2, x3) = addr;- Ipv4Addr::new(x0, x1, x2, x3)-}--pub fn from_ipv4_addr(addr: Ipv4Addr) -> (u8, u8, u8, u8) {- let [x0, x1, x2, x3] = addr.octets();- (x0, x1, x2, x3)-}--pub fn to_ipv6_addr(addr: (u16, u16, u16, u16, u16, u16, u16, u16)) -> Ipv6Addr {- let (x0, x1, x2, x3, x4, x5, x6, x7) = addr;- Ipv6Addr::new(x0, x1, x2, x3, x4, x5, x6, x7)-}--pub fn from_ipv6_addr(addr: Ipv6Addr) -> (u16, u16, u16, u16, u16, u16, u16, u16) {- let [x0, x1, x2, x3, x4, x5, x6, x7] = addr.segments();- (x0, x1, x2, x3, x4, x5, x6, x7)-}--/*- * Syscalls wrappers with (opinionated) portability fixes.- */--pub fn normalize_get_buffer_size(value: usize) -> usize {- if cfg!(target_os = "linux") {- // Linux doubles the value passed to setsockopt to allow space for bookkeeping overhead.- // getsockopt returns this internally doubled value.- // We'll half the value to at least get it back into the same ballpark that the application requested it in.- //- // This normalized behavior is tested for in: test-programs/src/bin/preview2_tcp_sockopts.rs- value / 2- } else {- value- }-}--pub fn normalize_set_buffer_size(value: usize) -> usize {- value.clamp(1, i32::MAX as usize)-}--impl From<std::io::Error> for ErrorCode {- fn from(value: std::io::Error) -> Self {- (&value).into()- }-}--impl From<&std::io::Error> for ErrorCode {- fn from(value: &std::io::Error) -> Self {- // Attempt the more detailed native error code first:- if let Some(errno) = Errno::from_io_error(value) {- return errno.into();- }-- match value.kind() {- std::io::ErrorKind::AddrInUse => Self::AddressInUse,- std::io::ErrorKind::AddrNotAvailable => Self::AddressNotBindable,- std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,- std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,- std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,- std::io::ErrorKind::InvalidInput => Self::InvalidArgument,- std::io::ErrorKind::NotConnected => Self::InvalidState,- std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,- std::io::ErrorKind::PermissionDenied => Self::AccessDenied,- std::io::ErrorKind::TimedOut => Self::Timeout,- std::io::ErrorKind::Unsupported => Self::NotSupported,- std::io::ErrorKind::HostUnreachable => Self::RemoteUnreachable,- std::io::ErrorKind::NetworkUnreachable => Self::RemoteUnreachable,- std::io::ErrorKind::NetworkDown => Self::RemoteUnreachable,- std::io::ErrorKind::BrokenPipe => Self::ConnectionBroken,- _ => {- debug!("unknown I/O error: {value}");- Self::Other- }- }- }-}--impl From<Errno> for ErrorCode {- fn from(value: Errno) -> Self {- (&value).into()- }-}--impl From<&Errno> for ErrorCode {- fn from(value: &Errno) -> Self {- match *value {- #[cfg(not(windows))]- Errno::PERM => Self::AccessDenied,- Errno::ACCESS => Self::AccessDenied,- Errno::ADDRINUSE => Self::AddressInUse,- Errno::ADDRNOTAVAIL => Self::AddressNotBindable,- Errno::TIMEDOUT => Self::Timeout,- #[cfg(not(windows))]- Errno::PIPE => Self::ConnectionBroken,- Errno::CONNREFUSED => Self::ConnectionRefused,- Errno::CONNRESET => Self::ConnectionReset,- Errno::CONNABORTED => Self::ConnectionAborted,- Errno::INVAL => Self::InvalidArgument,- Errno::HOSTUNREACH => Self::RemoteUnreachable,- Errno::HOSTDOWN => Self::RemoteUnreachable,- Errno::NETDOWN => Self::RemoteUnreachable,- Errno::NETUNREACH => Self::RemoteUnreachable,- #[cfg(target_os = "linux")]- Errno::NONET => Self::RemoteUnreachable,- Errno::ISCONN => Self::InvalidState,- Errno::NOTCONN => Self::InvalidState,- Errno::DESTADDRREQ => Self::InvalidState,- Errno::MSGSIZE => Self::DatagramTooLarge,- #[cfg(not(windows))]- Errno::NOMEM => Self::OutOfMemory,- Errno::NOBUFS => Self::OutOfMemory,- Errno::OPNOTSUPP => Self::NotSupported,- Errno::NOPROTOOPT => Self::NotSupported,- Errno::PFNOSUPPORT => Self::NotSupported,- Errno::PROTONOSUPPORT => Self::NotSupported,- Errno::PROTOTYPE => Self::NotSupported,- Errno::SOCKTNOSUPPORT => Self::NotSupported,- Errno::AFNOSUPPORT => Self::NotSupported,-- // FYI, EINPROGRESS should have already been handled by connect.- _ => {- debug!("unknown I/O error: {value}");- Self::Other- }- }- }-}--pub fn get_ip_ttl(fd: impl AsFd) -> Result<u8, ErrorCode> {- let v = sockopt::ip_ttl(fd)?;- let Ok(v) = v.try_into() else {- return Err(ErrorCode::NotSupported);- };- Ok(v)-}--pub fn get_ipv6_unicast_hops(fd: impl AsFd) -> Result<u8, ErrorCode> {- let v = sockopt::ipv6_unicast_hops(fd)?;- Ok(v)-}--pub fn get_unicast_hop_limit(fd: impl AsFd, family: SocketAddressFamily) -> Result<u8, ErrorCode> {- match family {- SocketAddressFamily::Ipv4 => get_ip_ttl(fd),- SocketAddressFamily::Ipv6 => get_ipv6_unicast_hops(fd),- }-}--pub fn set_unicast_hop_limit(- fd: impl AsFd,- family: SocketAddressFamily,- value: u8,-) -> Result<(), ErrorCode> {- if value == 0 {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- //- // A well-behaved IP application should never send out new packets with TTL 0.- // We validate the value ourselves because OS'es are not consistent in this.- // On Linux the validation is even inconsistent between their IPv4 and IPv6 implementation.- return Err(ErrorCode::InvalidArgument);- }- match family {- SocketAddressFamily::Ipv4 => {- sockopt::set_ip_ttl(fd, value.into())?;- }- SocketAddressFamily::Ipv6 => {- sockopt::set_ipv6_unicast_hops(fd, Some(value))?;- }- }- Ok(())-}--pub fn receive_buffer_size(fd: impl AsFd) -> Result<u64, ErrorCode> {- let v = sockopt::socket_recv_buffer_size(fd)?;- Ok(normalize_get_buffer_size(v).try_into().unwrap_or(u64::MAX))-}--pub fn set_receive_buffer_size(fd: impl AsFd, value: u64) -> Result<usize, ErrorCode> {- if value == 0 {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- return Err(ErrorCode::InvalidArgument);- }- let value = value.try_into().unwrap_or(usize::MAX);- let value = normalize_set_buffer_size(value);- match sockopt::set_socket_recv_buffer_size(fd, value) {- // Most platforms (Linux, Windows, Fuchsia, Solaris, Illumos, Haiku, ESP-IDF, ..and more?) treat the value- // passed to SO_SNDBUF/SO_RCVBUF as a performance tuning hint and silently clamp the input if it exceeds- // their capability.- // As far as I can see, only the *BSD family views this option as a hard requirement and fails when the- // value is out of range. We normalize this behavior in favor of the more commonly understood- // "performance hint" semantics. In other words; even ENOBUFS is "Ok".- // A future improvement could be to query the corresponding sysctl on *BSD platforms and clamp the input- // `size` ourselves, to completely close the gap with other platforms.- //- // This normalized behavior is tested for in: test-programs/src/bin/preview2_tcp_sockopts.rs- Err(Errno::NOBUFS) => {}- Err(err) => return Err(err.into()),- _ => {}- };- Ok(value)-}--pub fn send_buffer_size(fd: impl AsFd) -> Result<u64, ErrorCode> {- let v = sockopt::socket_send_buffer_size(fd)?;- Ok(normalize_get_buffer_size(v).try_into().unwrap_or(u64::MAX))-}--pub fn set_send_buffer_size(fd: impl AsFd, value: u64) -> Result<usize, ErrorCode> {- if value == 0 {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- return Err(ErrorCode::InvalidArgument);- }- let value = value.try_into().unwrap_or(usize::MAX);- let value = normalize_set_buffer_size(value);- match sockopt::set_socket_send_buffer_size(fd, value) {- Err(Errno::NOBUFS) => {}- Err(err) => return Err(err.into()),- _ => {}- };- Ok(value)-}--pub fn set_keep_alive_idle_time(fd: impl AsFd, value: u64) -> Result<u64, ErrorCode> {- const NANOS_PER_SEC: u64 = 1_000_000_000;-- // Ensure that the value passed to the actual syscall never gets rounded down to 0.- const MIN: u64 = NANOS_PER_SEC;-- // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.- const MAX: u64 = (i16::MAX as u64) * NANOS_PER_SEC;-- if value <= 0 {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- return Err(ErrorCode::InvalidArgument);- }- let value = value.clamp(MIN, MAX);- sockopt::set_tcp_keepidle(fd, Duration::from_nanos(value))?;- Ok(value)-}--pub fn set_keep_alive_interval(fd: impl AsFd, value: Duration) -> Result<(), ErrorCode> {- // Ensure that any fractional value passed to the actual syscall never gets rounded down to 0.- const MIN: Duration = Duration::from_secs(1);-- // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.- const MAX: Duration = Duration::from_secs(i16::MAX as u64);-- if value <= Duration::ZERO {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- return Err(ErrorCode::InvalidArgument);- }- sockopt::set_tcp_keepintvl(fd, value.clamp(MIN, MAX))?;- Ok(())-}--pub fn set_keep_alive_count(fd: impl AsFd, value: u32) -> Result<(), ErrorCode> {- const MIN_CNT: u32 = 1;- // Cap it at Linux' maximum, which appears to have the lowest limit across our supported platforms.- const MAX_CNT: u32 = i8::MAX as u32;-- if value == 0 {- // WIT: "If the provided value is 0, an `invalid-argument` error is returned."- return Err(ErrorCode::InvalidArgument);- }- sockopt::set_tcp_keepcnt(fd, value.clamp(MIN_CNT, MAX_CNT))?;- Ok(())-}--pub fn tcp_bind(- socket: &tokio::net::TcpSocket,- local_address: SocketAddr,-) -> Result<(), ErrorCode> {- // From the WASI spec:- // > The bind operation shouldn't be affected by the TIME_WAIT state of a- // > recently closed socket on the same local address. In practice this- // > means that the SO_REUSEADDR socket option should be set implicitly on- // > all platforms, except on Windows where this is the default behavior- // > and SO_REUSEADDR performs something different.- #[cfg(not(windows))]- {- _ = sockopt::set_socket_reuseaddr(&socket, true);- }-- // Perform the OS bind call.- socket- .bind(local_address)- .map_err(|err| match Errno::from_io_error(&err) {- // From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:- // > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket- //- // The most common reasons for this error should have already- // been handled by our own validation slightly higher up in this- // function. This error mapping is here just in case there is- // an edge case we didn't catch.- Some(Errno::AFNOSUPPORT) => ErrorCode::InvalidArgument,- // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS- // Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.- #[cfg(windows)]- Some(Errno::NOBUFS) => ErrorCode::AddressInUse,- _ => err.into(),- })-}--pub async fn tcp_accept(- listener: &tokio::net::TcpListener,-) -> std::io::Result<(tokio::net::TcpStream, SocketAddr)> {- listener- .accept()- .await- .map_err(|err| match Errno::from_io_error(&err) {- // From: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-accept#:~:text=WSAEINPROGRESS- // > WSAEINPROGRESS: A blocking Windows Sockets 1.1 call is in progress,- // > or the service provider is still processing a callback function.- //- // wasi-sockets doesn't have an equivalent to the EINPROGRESS error,- // because in POSIX this error is only returned by a non-blocking- // `connect` and wasi-sockets has a different solution for that.- #[cfg(windows)]- Some(Errno::INPROGRESS) => Errno::INTR.into(),-- // Normalize Linux' non-standard behavior.- //- // From https://man7.org/linux/man-pages/man2/accept.2.html:- // > Linux accept() passes already-pending network errors on the- // > new socket as an error code from accept(). This behavior- // > differs from other BSD socket implementations. (...)- #[cfg(target_os = "linux")]- Some(- Errno::CONNRESET- | Errno::NETRESET- | Errno::HOSTUNREACH- | Errno::HOSTDOWN- | Errno::NETDOWN- | Errno::NETUNREACH- | Errno::PROTO- | Errno::NOPROTOOPT- | Errno::NONET- | Errno::OPNOTSUPP,- ) => Errno::CONNABORTED.into(),-- _ => err,- })-}--pub fn tcp_reset(socket: tokio::net::TcpStream) {- _ = socket.set_zero_linger();- drop(socket);-}--/// Creates a non-blocking/cloexec UDP socket.-pub fn udp_socket(family: SocketAddressFamily) -> std::io::Result<rustix::fd::OwnedFd> {- // Let the standard library be responsible for handling `WSAStartup`.- #[cfg(windows)]- static INIT: std::sync::Once = std::sync::Once::new();- #[cfg(windows)]- INIT.call_once(|| {- let _ = std::net::TcpStream::connect(std::net::SocketAddrV4::new(- std::net::Ipv4Addr::UNSPECIFIED,- 0,- ));- });-- #[cfg(not(any(windows, target_vendor = "apple")))]- let flags = rustix::net::SocketFlags::CLOEXEC | rustix::net::SocketFlags::NONBLOCK;- #[cfg(any(windows, target_vendor = "apple"))]- let flags = rustix::net::SocketFlags::empty();-- let socket = rustix::net::socket_with(- match family {- SocketAddressFamily::Ipv4 => rustix::net::AddressFamily::INET,- SocketAddressFamily::Ipv6 => rustix::net::AddressFamily::INET6,- },- rustix::net::SocketType::DGRAM,- flags,- None,- )?;- #[cfg(target_vendor = "apple")]- rustix::io::ioctl_fioclex(&socket)?;- #[cfg(any(windows, target_vendor = "apple"))]- rustix::io::ioctl_fionbio(&socket, true)?;-- if family == SocketAddressFamily::Ipv6 {- rustix::net::sockopt::set_ipv6_v6only(&socket, true)?;- }- Ok(socket)-}--pub fn udp_bind(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), ErrorCode> {- bind(sockfd, &addr).map_err(|err| match err {- // See: https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-bind#:~:text=WSAENOBUFS- // Windows returns WSAENOBUFS when the ephemeral ports have been exhausted.- #[cfg(windows)]- Errno::NOBUFS => ErrorCode::AddressInUse,- // From https://pubs.opengroup.org/onlinepubs/9699919799/functions/bind.html:- // > [EAFNOSUPPORT] The specified address is not a valid address for the address family of the specified socket- //- // The most common reasons for this error should have already- // been handled by our own validation slightly higher up in this- // function. This error mapping is here just in case there is- // an edge case we didn't catch.- Errno::AFNOSUPPORT => ErrorCode::InvalidArgument,- _ => err.into(),- })-}--pub fn udp_connect(sockfd: impl AsFd, addr: SocketAddr) -> Result<(), Errno> {- match connect(sockfd.as_fd(), &addr) {- // When connecting a UDP socket, the OS looks up the best route to the- // remote address and selects an appropriate outgoing interface.- // If the new destination routes through an interface different than the- // previously selected interface, most operating systems will- // automatically update the socket's local address to match that route.- //- // Linux however doesn't do that automatically and we manually- // dissolve the existing association and then connect again to the- // new destination.- #[cfg(target_os = "linux")]- Err(Errno::INVAL) => {- _ = udp_disconnect(sockfd.as_fd());- return connect(sockfd.as_fd(), &addr);- }- r => r,- }-}--pub fn udp_disconnect(sockfd: impl AsFd) -> Result<(), Errno> {- match connect_unspec(sockfd) {- // BSD platforms return an error even if the UDP socket was disconnected successfully.- //- // MacOS was kind enough to document this: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html- // > Datagram sockets may dissolve the association by connecting to an- // > invalid address, such as a null address or an address with the address- // > family set to AF_UNSPEC (the error EAFNOSUPPORT will be harmlessly- // > returned).- //- // ... except that this appears to be incomplete, because experiments- // have shown that MacOS actually returns EINVAL, depending on the- // address family of the socket.- #[cfg(target_os = "macos")]- Err(Errno::INVAL | Errno::AFNOSUPPORT) => Ok(()),- r => r,- }-}--pub fn parse_host(name: &str) -> Result<url::Host, ErrorCode> {- // `url::Host::parse` serves us two functions:- // 1. validate the input is a valid domain name or IP,- // 2. convert unicode domains to punycode.- match url::Host::parse(&name) {- Ok(host) => Ok(host),-- // `url::Host::parse` doesn't understand bare IPv6 addresses without [brackets]- Err(_) => {- if let Ok(addr) = Ipv6Addr::from_str(name) {- Ok(url::Host::Ipv6(addr))- } else {- Err(ErrorCode::InvalidArgument)- }- }- }-}--pub fn unspecified_addr(family: SocketAddressFamily) -> SocketAddr {- let ip = match family {- SocketAddressFamily::Ipv4 => IpAddr::V4(Ipv4Addr::UNSPECIFIED),- SocketAddressFamily::Ipv6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED),- };- SocketAddr::new(ip, 0)-}--pub fn shutdown(socket: &tokio::net::TcpStream, how: std::net::Shutdown) -> Result<(), Errno> {- rustix::net::shutdown(- socket,- match how {- std::net::Shutdown::Read => rustix::net::Shutdown::Read,- std::net::Shutdown::Write => rustix::net::Shutdown::Write,- std::net::Shutdown::Both => rustix::net::Shutdown::Both,- },- )-}