#[cfg(feature = "runtime-mock")]
pub mod mock;
#[cfg(feature = "runtime-smol")]
mod smol_runtime;
#[cfg(feature = "runtime-tokio")]
mod tokio_runtime;
#[cfg(feature = "runtime-mock")]
pub use mock::{MockClock, MockNet, MockRuntime};
#[cfg(feature = "runtime-smol")]
pub use smol_runtime::SmolRuntime;
#[cfg(feature = "runtime-tokio")]
pub use tokio_runtime::TokioRuntime;
use shared::stream::{DnsRecord, RecordKind};
use socket2::{Domain, Protocol, SockRef, Socket, Type};
use std::fmt::Debug;
use std::future::Future;
use std::io::{self, IoSliceMut};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU16, Ordering};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait Runtime: Send + Sync + Debug + 'static {
fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle>;
fn now(&self) -> Instant;
fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()>;
fn bind_udp(&self, local: SocketAddr) -> io::Result<Arc<dyn AsyncUdpSocket>>;
fn bind_udp_multicast(&self, config: &MulticastConfig) -> io::Result<Arc<dyn AsyncUdpSocket>>;
fn listen_tcp(
&self,
local: SocketAddr,
reuse_address: bool,
) -> io::Result<Arc<dyn AsyncTcpListener>>;
fn connect_tcp(
&self,
local: SocketAddr,
remote: SocketAddr,
reuse_address: bool,
) -> BoxFuture<'static, io::Result<Arc<dyn AsyncTcpStream>>>;
fn resolve_host(
&self,
host: &str,
port: u16,
) -> BoxFuture<'static, io::Result<Vec<SocketAddr>>>;
fn resolve_family(
&self,
host: &str,
port: u16,
ipv6: bool,
) -> Option<BoxFuture<'static, Vec<SocketAddr>>> {
let _ = (host, port, ipv6);
None
}
fn resolve_records(&self, name: &str, kind: RecordKind) -> BoxFuture<'static, Vec<DnsRecord>> {
let _ = (name, kind);
Box::pin(std::future::ready(Vec::new()))
}
fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>);
fn virtual_clock(&self) -> bool {
false
}
fn interfaces(&self) -> io::Result<Vec<LocalInterface>> {
host_interfaces()
}
fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
host_preferred_source(ipv6)
}
fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
host_route_source(destination)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LocalInterface {
pub name: String,
pub ip: IpAddr,
pub prefix_len: Option<u8>,
pub temporary: bool,
pub deprecated: bool,
}
impl LocalInterface {
pub fn new(name: impl Into<String>, ip: IpAddr) -> Self {
Self {
name: name.into(),
ip,
prefix_len: None,
temporary: false,
deprecated: false,
}
}
#[must_use]
pub fn with_deprecated(mut self, deprecated: bool) -> Self {
self.deprecated = deprecated;
self
}
#[must_use]
pub fn with_prefix_len(mut self, prefix_len: u8) -> Self {
self.prefix_len = Some(prefix_len);
self
}
#[must_use]
pub fn with_temporary(mut self, temporary: bool) -> Self {
self.temporary = temporary;
self
}
}
pub fn host_interfaces() -> io::Result<Vec<LocalInterface>> {
let temporary = shared::ifaces::temporary_ipv6_addresses().unwrap_or_default();
let deprecated = shared::ifaces::deprecated_ipv6_addresses().unwrap_or_default();
let mut out: Vec<LocalInterface> = Vec::new();
for interface in shared::ifaces::ifaces()? {
let Some(addr) = interface.addr else {
continue;
};
let ip = addr.ip();
if out.iter().any(|i| i.ip == ip && i.name == interface.name) {
continue;
}
let prefix_len = interface.mask.map(|mask| prefix_length(mask.ip()));
out.push(LocalInterface {
name: interface.name,
ip,
prefix_len,
temporary: matches!(ip, IpAddr::V6(v6) if temporary.contains(&v6)),
deprecated: matches!(ip, IpAddr::V6(v6) if deprecated.contains(&v6)),
});
}
Ok(out)
}
fn prefix_length(mask: IpAddr) -> u8 {
let ones = match mask {
IpAddr::V4(m) => u32::from(m).leading_ones(),
IpAddr::V6(m) => u128::from(m).leading_ones(),
};
u8::try_from(ones).unwrap_or(u8::MAX)
}
pub fn host_preferred_source(ipv6: bool) -> Option<IpAddr> {
host_route_source(if ipv6 {
IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
} else {
IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))
})
}
pub fn host_route_source(destination: IpAddr) -> Option<IpAddr> {
let bind: SocketAddr = match destination {
IpAddr::V6(_) => (Ipv6Addr::UNSPECIFIED, 0).into(),
IpAddr::V4(_) => (Ipv4Addr::UNSPECIFIED, 0).into(),
};
let socket = std::net::UdpSocket::bind(bind).ok()?;
socket.connect(SocketAddr::new(destination, 9)).ok()?;
let ip = socket.local_addr().ok()?.ip();
(!ip.is_unspecified()).then_some(ip)
}
pub trait JoinHandle: Send + Debug {
fn abort(&self);
fn is_finished(&self) -> bool;
fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()>;
}
impl<'a> dyn JoinHandle + 'a {
pub fn join(&mut self) -> impl Future<Output = ()> + '_ {
std::future::poll_fn(move |cx| self.poll_join(cx))
}
}
#[derive(Debug, Clone, Copy)]
pub struct Transmit<'a> {
pub destination: SocketAddr,
pub contents: &'a [u8],
pub traffic_class: u8,
pub segment_size: Option<usize>,
pub source: Option<IpAddr>,
}
#[derive(Debug, Clone, Copy)]
pub struct RecvMeta {
pub addr: SocketAddr,
pub len: usize,
pub stride: usize,
pub ecn: Option<u8>,
pub dst_ip: Option<IpAddr>,
}
impl Default for RecvMeta {
fn default() -> Self {
Self {
addr: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
len: 0,
stride: 0,
ecn: None,
dst_ip: None,
}
}
}
pub trait AsyncUdpSocket: Send + Sync + Debug {
fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>>;
fn poll_recv(
&self,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
meta: &mut [RecvMeta],
) -> Poll<io::Result<usize>>;
fn local_addr(&self) -> io::Result<SocketAddr>;
fn max_receive_batch(&self) -> usize {
1
}
fn traffic_class(&self) -> io::Result<u32>;
fn unmarked(&self) -> bool {
false
}
fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
let _ = on;
Err(io::ErrorKind::Unsupported.into())
}
}
pub trait AsyncTcpStream: Send + Sync + Debug {
fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>>;
fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>;
fn shutdown_write(&self) -> io::Result<()>;
fn reset_on_close(&self) -> io::Result<()>;
fn set_traffic_class(&self, value: u8) -> io::Result<u32>;
fn local_addr(&self) -> io::Result<SocketAddr>;
fn peer_addr(&self) -> io::Result<SocketAddr>;
}
pub trait AsyncTcpListener: Send + Sync + Debug {
fn poll_accept(
&self,
cx: &mut Context<'_>,
) -> Poll<io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>>;
fn local_addr(&self) -> io::Result<SocketAddr>;
}
impl<'a> dyn AsyncTcpListener + 'a {
pub async fn accept(&self) -> io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)> {
std::future::poll_fn(|cx| self.poll_accept(cx)).await
}
}
impl<'a> dyn AsyncTcpStream + 'a {
pub async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
std::future::poll_fn(|cx| self.poll_read(cx, buf)).await
}
pub async fn write_all(&self, mut buf: &[u8]) -> io::Result<()> {
while !buf.is_empty() {
let n = std::future::poll_fn(|cx| self.poll_write(cx, buf)).await?;
if n == 0 {
return Err(io::ErrorKind::WriteZero.into());
}
buf = &buf[n..];
}
Ok(())
}
}
impl<'a> dyn AsyncUdpSocket + 'a {
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
std::future::poll_fn(|cx| {
let mut meta = [RecvMeta::default()];
let mut bufs = [IoSliceMut::new(&mut *buf)];
match self.poll_recv(cx, &mut bufs, &mut meta) {
Poll::Ready(Ok(_)) => Poll::Ready(Ok((meta[0].len, meta[0].addr))),
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
}
})
.await
}
pub async fn send_to(&self, buf: &[u8], destination: SocketAddr) -> io::Result<usize> {
let transmit = Transmit {
destination,
contents: buf,
traffic_class: 0,
segment_size: None,
source: None,
};
std::future::poll_fn(|cx| self.poll_send(cx, &transmit)).await
}
pub fn try_send(&self, transmit: &Transmit<'_>) -> io::Result<usize> {
let mut cx = Context::from_waker(std::task::Waker::noop());
match self.poll_send(&mut cx, transmit) {
Poll::Ready(result) => result,
Poll::Pending => Err(io::ErrorKind::WouldBlock.into()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MulticastConfig {
pub group: IpAddr,
pub port: u16,
pub interfaces: Vec<IpAddr>,
pub hop_limit: u32,
pub reuse_address: bool,
}
impl MulticastConfig {
pub fn new(group: IpAddr, port: u16) -> Self {
Self {
group,
port,
interfaces: Vec::new(),
hop_limit: 1,
reuse_address: false,
}
}
#[must_use]
pub fn with_interfaces(mut self, interfaces: Vec<IpAddr>) -> Self {
self.interfaces = interfaces;
self
}
#[must_use]
pub fn with_hop_limit(mut self, hop_limit: u32) -> Self {
self.hop_limit = hop_limit;
self
}
#[must_use]
pub fn with_reuse_address(mut self, reuse_address: bool) -> Self {
self.reuse_address = reuse_address;
self
}
pub fn mdns(group: IpAddr, interfaces: Vec<IpAddr>) -> Self {
Self {
group,
port: 5353,
interfaces,
hop_limit: 255,
reuse_address: true,
}
}
pub fn interfaces_of_family(&self) -> impl Iterator<Item = IpAddr> + '_ {
let v4 = self.group.is_ipv4();
self.interfaces
.iter()
.copied()
.filter(move |ip| ip.is_ipv4() == v4 && !ip.is_unspecified())
}
}
pub fn interface_index(ip: Ipv6Addr) -> Option<u32> {
let interfaces = shared::ifaces::ifaces().ok()?;
let entry = interfaces
.iter()
.find(|i| matches!(i.addr, Some(SocketAddr::V6(a)) if *a.ip() == ip))?;
if let Some(SocketAddr::V6(a)) = entry.addr
&& a.scope_id() != 0
{
return Some(a.scope_id());
}
name_to_index(&entry.name)
}
#[cfg(unix)]
fn name_to_index(name: &str) -> Option<u32> {
let name = std::ffi::CString::new(name).ok()?;
let index = unsafe { libc::if_nametoindex(name.as_ptr()) };
(index != 0).then_some(index)
}
#[cfg(not(unix))]
fn name_to_index(_: &str) -> Option<u32> {
None
}
pub fn interface_name(ip: IpAddr) -> Option<String> {
shared::ifaces::ifaces()
.ok()?
.into_iter()
.find(|i| i.addr.is_some_and(|a| a.ip() == ip))
.map(|i| i.name)
}
#[derive(Debug, Default)]
pub struct MulticastInterfaceSelector {
last: std::sync::Mutex<Option<IpAddr>>,
}
impl MulticastInterfaceSelector {
pub fn apply(&self, socket: SockRef<'_>, transmit: &Transmit<'_>) -> io::Result<()> {
let destination = transmit.destination.ip();
let Some(source) = transmit.source.filter(|source| {
destination.is_multicast()
&& !source.is_unspecified()
&& source.is_ipv4() == destination.is_ipv4()
}) else {
return Ok(());
};
let mut last = self
.last
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *last == Some(source) {
return Ok(());
}
match source {
IpAddr::V4(source) => socket.set_multicast_if_v4(&source)?,
IpAddr::V6(source) => {
let index = interface_index(source).ok_or_else(|| {
io::Error::new(
io::ErrorKind::AddrNotAvailable,
format!("no interface holds {source}"),
)
})?;
socket.set_multicast_if_v6(index)?;
}
}
*last = Some(source);
Ok(())
}
}
pub fn sleep(runtime: &dyn Runtime, duration: Duration) -> BoxFuture<'static, ()> {
runtime.sleep_until(runtime.now() + duration)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Elapsed;
impl std::fmt::Display for Elapsed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("deadline elapsed")
}
}
impl std::error::Error for Elapsed {}
pub async fn timeout<T>(
runtime: &dyn Runtime,
duration: Duration,
future: impl Future<Output = T>,
) -> Result<T, Elapsed> {
timeout_at(runtime, runtime.now() + duration, future).await
}
pub async fn timeout_at<T>(
runtime: &dyn Runtime,
deadline: Instant,
future: impl Future<Output = T>,
) -> Result<T, Elapsed> {
let mut future = std::pin::pin!(future);
let mut sleep = runtime.sleep_until(deadline);
std::future::poll_fn(|cx| {
if let Poll::Ready(value) = future.as_mut().poll(cx) {
return Poll::Ready(Ok(value));
}
sleep.as_mut().poll(cx).map(|()| Err(Elapsed))
})
.await
}
pub async fn yield_now() {
let mut yielded = false;
std::future::poll_fn(|cx| {
if yielded {
return Poll::Ready(());
}
yielded = true;
cx.waker().wake_by_ref();
Poll::Pending
})
.await
}
#[derive(Debug)]
pub struct TrafficClassMarker {
state: AtomicU16,
}
impl Default for TrafficClassMarker {
fn default() -> Self {
Self {
state: AtomicU16::new(0),
}
}
}
impl TrafficClassMarker {
const REFUSED: u16 = 0x100;
pub fn apply(&self, socket: SockRef<'_>, ipv6: bool, value: u8) -> u8 {
let current = self.state.load(Ordering::Relaxed);
if current == Self::REFUSED {
return 0;
}
if current == u16::from(value) {
return value;
}
match crate::sockets::set_traffic_class(socket, ipv6, value) {
Ok(()) => {
self.state.store(u16::from(value), Ordering::Relaxed);
value
}
Err(_) => {
self.state.store(Self::REFUSED, Ordering::Relaxed);
0
}
}
}
pub fn refused(&self) -> bool {
self.state.load(Ordering::Relaxed) == Self::REFUSED
}
}
pub fn std_udp(local: SocketAddr) -> io::Result<std::net::UdpSocket> {
let socket = std::net::UdpSocket::bind(local)?;
socket.set_nonblocking(true)?;
Ok(socket)
}
pub fn std_multicast(config: &MulticastConfig) -> io::Result<std::net::UdpSocket> {
let domain = match config.group {
IpAddr::V4(_) => Domain::IPV4,
IpAddr::V6(_) => Domain::IPV6,
};
let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
if config.group.is_ipv6() {
socket.set_only_v6(true)?;
}
if config.reuse_address {
socket.set_reuse_address(true)?;
#[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
socket.set_reuse_port(true)?;
}
socket.set_nonblocking(true)?;
let interfaces: Vec<IpAddr> = config.interfaces_of_family().collect();
match config.group {
IpAddr::V4(group) => {
socket.set_multicast_ttl_v4(config.hop_limit)?;
socket.set_ttl_v4(config.hop_limit)?;
let local = if cfg!(target_os = "linux") {
group
} else {
Ipv4Addr::UNSPECIFIED
};
socket.bind(&SocketAddr::new(local.into(), config.port).into())?;
join_each(&interfaces, |interface| match interface {
Some(IpAddr::V4(interface)) => {
if cfg!(windows) && interface.is_loopback() {
warn_loopback_join_on_windows(group);
}
socket.join_multicast_v4(&group, &interface)
}
_ => socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED),
})?;
}
IpAddr::V6(group) => {
socket.set_multicast_hops_v6(config.hop_limit)?;
socket.set_unicast_hops_v6(config.hop_limit)?;
socket.bind(&SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), config.port).into())?;
join_each(&interfaces, |interface| {
let index = match interface {
Some(IpAddr::V6(ip)) => interface_index(ip).ok_or_else(|| {
io::Error::new(
io::ErrorKind::AddrNotAvailable,
format!("no interface holds {ip}"),
)
})?,
_ => 0,
};
socket.join_multicast_v6(&group, index)
})?;
}
}
Ok(socket.into())
}
fn warn_loopback_join_on_windows(group: Ipv4Addr) {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
log::warn!(
"joining {group} on the loopback interface: on Windows mDNS sent there leaves the \
group's destination-cache route on loopback after this process, for other \
processes too (netsh interface ipv4 delete destinationcache, as administrator)"
);
});
}
fn join_each(
interfaces: &[IpAddr],
mut join: impl FnMut(Option<IpAddr>) -> io::Result<()>,
) -> io::Result<()> {
if interfaces.is_empty() {
return join(None);
}
let mut first_error = None;
let mut joined = false;
for interface in interfaces {
match join(Some(*interface)) {
Ok(()) => joined = true,
Err(e) if e.kind() == io::ErrorKind::AddrInUse => joined = true,
Err(e) => {
first_error.get_or_insert(e);
}
}
}
match (joined, first_error) {
(false, Some(e)) => Err(e),
_ => Ok(()),
}
}
fn tcp_socket(addr: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
let socket = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
if reuse_address {
socket.set_reuse_address(true)?;
#[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
socket.set_reuse_port(true)?;
}
socket.set_nonblocking(true)?;
Ok(socket)
}
pub fn std_tcp_listener(
local: SocketAddr,
reuse_address: bool,
) -> io::Result<std::net::TcpListener> {
let socket = tcp_socket(local, reuse_address)?;
socket.bind(&local.into())?;
socket.listen(128)?;
Ok(socket.into())
}
pub fn std_tcp_bound(local: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
let socket = tcp_socket(local, reuse_address)?;
socket.bind(&local.into())?;
Ok(socket)
}
pub fn std_tcp_connect_start(
local: SocketAddr,
remote: SocketAddr,
reuse_address: bool,
) -> io::Result<std::net::TcpStream> {
let socket = std_tcp_bound(local, reuse_address)?;
match socket.connect(&remote.into()) {
Ok(()) => {}
Err(e) if connect_in_progress(&e) => {}
Err(e) => return Err(e),
}
Ok(socket.into())
}
fn connect_in_progress(e: &io::Error) -> bool {
#[cfg(unix)]
if e.raw_os_error() == Some(libc::EINPROGRESS) {
return true;
}
e.kind() == io::ErrorKind::WouldBlock
}
pub fn reset_on_close(socket: SockRef<'_>) -> io::Result<()> {
socket.set_linger(Some(Duration::ZERO))
}
pub fn set_and_read_traffic_class(socket: SockRef<'_>, ipv6: bool, value: u8) -> io::Result<u32> {
crate::sockets::set_traffic_class(SockRef::from(&*socket), ipv6, value)?;
crate::sockets::traffic_class(socket, ipv6)
}
#[cfg(unix)]
pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
use std::os::fd::AsRawFd;
let on: libc::c_int = 1;
let (level, name) = if ipv6 {
(libc::IPPROTO_IPV6, libc::IPV6_RECVTCLASS)
} else {
(libc::IPPROTO_IP, libc::IP_RECVTOS)
};
let r = unsafe {
libc::setsockopt(
socket.as_raw_fd(),
level,
name,
(&on as *const libc::c_int).cast(),
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
)
};
if r == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
let _ = (socket, ipv6);
Err(io::ErrorKind::Unsupported.into())
}
#[cfg(unix)]
pub fn recv_from_with_ecn(
socket: SockRef<'_>,
buf: &mut [u8],
) -> io::Result<(usize, SocketAddr, Option<u8>)> {
use std::os::fd::AsRawFd;
let mut name: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
let mut iov = libc::iovec {
iov_base: buf.as_mut_ptr().cast(),
iov_len: buf.len(),
};
let mut control = [0u64; 16];
let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
msg.msg_name = (&mut name as *mut libc::sockaddr_storage).cast();
msg.msg_namelen = std::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
msg.msg_iov = &mut iov;
msg.msg_iovlen = 1 as _;
msg.msg_control = control.as_mut_ptr().cast();
msg.msg_controllen = std::mem::size_of_val(&control) as _;
let n = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut msg, 0) };
if n < 0 {
return Err(io::Error::last_os_error());
}
let mut ecn = None;
unsafe {
let mut cmsg = libc::CMSG_FIRSTHDR(&msg);
while !cmsg.is_null() {
let header = &*cmsg;
let data = libc::CMSG_DATA(cmsg);
let byte = if header.cmsg_level == libc::IPPROTO_IP
&& (header.cmsg_type == libc::IP_TOS || header.cmsg_type == libc::IP_RECVTOS)
{
Some(std::ptr::read_unaligned(data))
} else if header.cmsg_level == libc::IPPROTO_IPV6
&& header.cmsg_type == libc::IPV6_TCLASS
{
Some(std::ptr::read_unaligned(data.cast::<libc::c_int>()) as u8)
} else {
None
};
if let Some(byte) = byte {
ecn = Some(byte & 0b11);
}
cmsg = libc::CMSG_NXTHDR(&msg, cmsg);
}
}
let from = socket_addr_of(&name)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no sender address"))?;
Ok((n as usize, from, ecn))
}
#[cfg(unix)]
fn socket_addr_of(name: &libc::sockaddr_storage) -> Option<SocketAddr> {
match libc::c_int::from(name.ss_family) {
libc::AF_INET => {
let v4 =
unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in>() };
Some(SocketAddr::new(
Ipv4Addr::from(u32::from_be(v4.sin_addr.s_addr)).into(),
u16::from_be(v4.sin_port),
))
}
libc::AF_INET6 => {
let v6 =
unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in6>() };
Some(SocketAddr::V6(std::net::SocketAddrV6::new(
Ipv6Addr::from(v6.sin6_addr.s6_addr),
u16::from_be(v6.sin6_port),
v6.sin6_flowinfo,
v6.sin6_scope_id,
)))
}
_ => None,
}
}
pub fn set_dont_fragment(socket: SockRef<'_>, ipv6: bool, on: bool) -> io::Result<()> {
#[cfg(any(target_os = "linux", target_os = "android"))]
let (level, name, value) = match (ipv6, on) {
(false, true) => (
libc::IPPROTO_IP,
libc::IP_MTU_DISCOVER,
libc::IP_PMTUDISC_DO,
),
(false, false) => (
libc::IPPROTO_IP,
libc::IP_MTU_DISCOVER,
libc::IP_PMTUDISC_DONT,
),
(true, true) => (
libc::IPPROTO_IPV6,
libc::IPV6_MTU_DISCOVER,
libc::IPV6_PMTUDISC_DO,
),
(true, false) => (
libc::IPPROTO_IPV6,
libc::IPV6_MTU_DISCOVER,
libc::IPV6_PMTUDISC_DONT,
),
};
#[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
let (level, name, value) = if ipv6 {
(
libc::IPPROTO_IPV6,
libc::IPV6_DONTFRAG,
libc::c_int::from(on),
)
} else {
(libc::IPPROTO_IP, libc::IP_DONTFRAG, libc::c_int::from(on))
};
#[cfg(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd"
))]
{
use std::os::fd::AsRawFd;
let r = unsafe {
libc::setsockopt(
socket.as_raw_fd(),
level,
name,
(&value as *const libc::c_int).cast(),
std::mem::size_of::<libc::c_int>() as libc::socklen_t,
)
};
if r == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd"
)))]
{
let _ = (socket, ipv6, on);
Err(io::ErrorKind::Unsupported.into())
}
}
pub fn dont_fragment(socket: SockRef<'_>, ipv6: bool) -> io::Result<bool> {
#[cfg(any(target_os = "linux", target_os = "android"))]
let (level, name) = if ipv6 {
(libc::IPPROTO_IPV6, libc::IPV6_MTU_DISCOVER)
} else {
(libc::IPPROTO_IP, libc::IP_MTU_DISCOVER)
};
#[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
let (level, name) = if ipv6 {
(libc::IPPROTO_IPV6, libc::IPV6_DONTFRAG)
} else {
(libc::IPPROTO_IP, libc::IP_DONTFRAG)
};
#[cfg(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd"
))]
{
use std::os::fd::AsRawFd;
let mut value: libc::c_int = 0;
let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
let r = unsafe {
libc::getsockopt(
socket.as_raw_fd(),
level,
name,
(&mut value as *mut libc::c_int).cast(),
&mut len,
)
};
if r != 0 {
return Err(io::Error::last_os_error());
}
#[cfg(any(target_os = "linux", target_os = "android"))]
let on = value == libc::IP_PMTUDISC_DO;
#[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
let on = value != 0;
Ok(on)
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd"
)))]
{
let _ = (socket, ipv6);
Err(io::ErrorKind::Unsupported.into())
}
}