use core::{cell::Cell, time::Duration};
use rustix::{
fd::{AsFd, OwnedFd},
io::{Errno, FdFlags, fcntl_setfd, ioctl_fionbio},
net::{
AddressFamily, RecvFlags, SendFlags, Shutdown, SocketAddrAny, SocketType,
addr::SocketAddrArg,
sockopt::{
set_socket_keepalive, set_socket_reuseaddr, set_tcp_keepcnt, set_tcp_keepidle,
set_tcp_keepintvl, socket_error,
},
},
};
use crate::{
context::Context,
io::{IoIndex, IoRegistration},
net::retry::Retry,
selector::Direction,
state::State,
strace::{syscall, syscall_end, syscall_start},
};
const LISTEN_BACKLOG: i32 = 1024;
#[cfg(target_os = "macos")]
const STREAM_SEND_FLAGS: SendFlags = SendFlags::empty();
#[cfg(any(target_os = "linux", target_os = "android"))]
const STREAM_SEND_FLAGS: SendFlags = SendFlags::NOSIGNAL;
#[must_use]
pub(crate) struct Socket(OwnedFd, Cell<Option<IoIndex>>);
impl Socket {
pub(crate) fn new(family: AddressFamily, ty: SocketType) -> rustix::io::Result<Self> {
syscall_start!("socket", family, ty, 0);
let fd = rustix::net::socket(family, ty, None);
syscall_end!(fd);
let socket = Self(fd?, Cell::new(None));
socket.configure(ty)?;
Ok(socket)
}
pub(crate) fn bind<A: SocketAddrArg>(&self, addr: &A) -> rustix::io::Result<()> {
syscall_start!("bind", self.0, addr.as_any());
let result = rustix::net::bind(&self.0, addr);
syscall_end!(result);
result
}
pub(crate) fn listen(&self) -> rustix::io::Result<()> {
syscall_start!("listen", self.0, LISTEN_BACKLOG);
let result = rustix::net::listen(&self.0, LISTEN_BACKLOG);
syscall_end!(result);
result
}
pub(crate) fn set_reuseaddr(&self) -> rustix::io::Result<()> {
syscall_start!("setsockopt", self.0, "SOL_SOCKET", "SO_REUSEADDR", true);
let result = set_socket_reuseaddr(&self.0, true);
syscall_end!(result);
result
}
pub(crate) fn set_keepalive(
&self,
idle: Duration,
interval: Duration,
count: u32,
) -> rustix::io::Result<()> {
syscall_start!("setsockopt", self.0, "SOL_SOCKET", "SO_KEEPALIVE", true);
let result = set_socket_keepalive(&self.0, true);
syscall_end!(result);
result?;
syscall_start!("setsockopt", self.0, "IPPROTO_TCP", "TCP_KEEPIDLE", idle);
let result = set_tcp_keepidle(&self.0, idle);
syscall_end!(result);
result?;
syscall_start!(
"setsockopt",
self.0,
"IPPROTO_TCP",
"TCP_KEEPINTVL",
interval
);
let result = set_tcp_keepintvl(&self.0, interval);
syscall_end!(result);
result?;
syscall_start!("setsockopt", self.0, "IPPROTO_TCP", "TCP_KEEPCNT", count);
let result = set_tcp_keepcnt(&self.0, count);
syscall_end!(result);
result?;
#[cfg(any(target_os = "linux", target_os = "android"))]
{
let timeout = interval
.checked_mul(count)
.and_then(|probes| probes.checked_add(idle))
.ok_or(Errno::INVAL)?;
let timeout = u32::try_from(timeout.as_millis()).map_err(|_| Errno::INVAL)?;
syscall_start!(
"setsockopt",
self.0,
"IPPROTO_TCP",
"TCP_USER_TIMEOUT",
timeout
);
let result = rustix::net::sockopt::set_tcp_user_timeout(&self.0, timeout);
syscall_end!(result);
result?;
}
Ok(())
}
pub(crate) fn connect<A: SocketAddrArg>(&self, addr: &A) -> rustix::io::Result<()> {
syscall_start!("connect", self.0, addr.as_any());
let result = rustix::net::connect(&self.0, addr);
syscall_end!(result);
result
}
pub(crate) async fn connect_stream<
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
A: SocketAddrArg,
>(
ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
addr: &A,
) -> rustix::io::Result<Self> {
let socket = Self::new(addr.as_any().address_family(), SocketType::STREAM)?;
syscall_start!("connect", socket.0, addr.as_any());
let result = rustix::net::connect(&socket.0, addr);
syscall_end!(result);
match result {
Ok(()) => return Ok(socket),
Err(Errno::INPROGRESS | Errno::INTR) => {}
Err(errno) => return Err(errno),
}
IoRegistration::new(ctx, socket.0.as_fd(), &socket.1, Direction::Write)
.wait()
.await;
syscall_start!("getsockopt", socket.0, "SOL_SOCKET", "SO_ERROR");
let result = socket_error(&socket.0);
syscall_end!(result; result.ok());
result??;
Ok(socket)
}
pub(crate) async fn accept<
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&self,
ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
) -> rustix::io::Result<(Self, Option<SocketAddrAny>)> {
let (fd, addr) = self
.retry(ctx, Direction::Read, |fd| {
syscall_start!("accept", fd);
let result = rustix::net::acceptfrom(fd);
syscall_end!(result; result.as_ref().ok().and_then(|(_, addr)| addr.as_ref()));
result
})
.await?;
let socket = Self(fd, Cell::new(None));
socket.configure(SocketType::STREAM)?;
Ok((socket, addr))
}
pub(crate) fn read<
'a,
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&'a self,
ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &'a mut [u8],
) -> impl Future<Output = rustix::io::Result<usize>> {
self.retry(ctx, Direction::Read, move |fd| {
syscall_start!("read", fd);
let result = rustix::io::read(fd, &mut *buf);
syscall_end!(result; &buf[..result.unwrap_or(0)], buf.len());
result
})
}
pub(crate) fn write<
'a,
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&'a self,
ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &'a [u8],
) -> impl Future<Output = rustix::io::Result<usize>> {
self.retry(ctx, Direction::Write, move |fd| {
syscall_start!("send", fd, buf, buf.len(), STREAM_SEND_FLAGS);
let result = rustix::net::send(fd, buf, STREAM_SEND_FLAGS);
syscall_end!(result);
result
})
}
pub(crate) fn send<
'a,
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&'a self,
ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &'a [u8],
) -> impl Future<Output = rustix::io::Result<usize>> {
self.retry(ctx, Direction::Write, move |fd| {
syscall_start!("send", fd, buf, buf.len(), SendFlags::empty());
let result = rustix::net::send(fd, buf, SendFlags::empty());
syscall_end!(result);
result
})
}
pub(crate) async fn recv<
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&self,
ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &mut [u8],
) -> rustix::io::Result<usize> {
let (len, _) = self
.retry(ctx, Direction::Read, |fd| {
syscall_start!("recv", fd);
let result = rustix::net::recv(fd, &mut *buf, RecvFlags::empty());
syscall_end!(
result;
&buf[..result.map_or(0, |(len, _)| len)],
buf.len(),
RecvFlags::empty(),
);
result
})
.await?;
Ok(len)
}
pub(crate) fn send_to<
'a,
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
A: SocketAddrArg,
>(
&'a self,
ctx: &'a Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &'a [u8],
addr: &'a A,
) -> impl Future<Output = rustix::io::Result<usize>> {
self.retry(ctx, Direction::Write, move |fd| {
syscall_start!(
"sendto",
fd,
buf,
buf.len(),
SendFlags::empty(),
addr.as_any()
);
let result = rustix::net::sendto(fd, buf, SendFlags::empty(), addr);
syscall_end!(result);
result
})
}
pub(crate) async fn recv_from<
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&self,
ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
buf: &mut [u8],
) -> rustix::io::Result<(usize, Option<SocketAddrAny>)> {
let (len, _, addr) = self
.retry(ctx, Direction::Read, |fd| {
syscall_start!("recvfrom", fd);
let result = rustix::net::recvfrom(fd, &mut *buf, RecvFlags::empty());
syscall_end!(
result;
&buf[..result.as_ref().map_or(0, |(len, _, _)| *len)],
buf.len(),
RecvFlags::empty(),
result.as_ref().ok().and_then(|(_, _, addr)| addr.as_ref()),
);
result
})
.await?;
Ok((len, addr))
}
pub(crate) fn local_addr<A: TryFrom<SocketAddrAny, Error = Errno>>(
&self,
) -> rustix::io::Result<A> {
syscall_start!("getsockname", self.0);
let addr = rustix::net::getsockname(&self.0);
syscall_end!(addr; addr.as_ref().ok());
addr?.try_into()
}
pub(crate) fn peer_addr(&self) -> rustix::io::Result<Option<SocketAddrAny>> {
syscall_start!("getpeername", self.0);
let addr = rustix::net::getpeername(&self.0);
syscall_end!(addr; addr.as_ref().ok().and_then(Option::as_ref));
addr
}
pub(crate) fn shutdown(&self, how: Shutdown) -> rustix::io::Result<()> {
syscall_start!("shutdown", self.0, how);
let result = rustix::net::shutdown(&self.0, how);
syscall_end!(result);
result
}
fn configure(
&self,
#[cfg_attr(
any(target_os = "linux", target_os = "android"),
expect(unused_variables)
)]
ty: SocketType,
) -> rustix::io::Result<()> {
syscall_start!("fcntl", self.0, "F_SETFD", FdFlags::CLOEXEC);
let result = fcntl_setfd(&self.0, FdFlags::CLOEXEC);
syscall_end!(result);
result?;
syscall_start!("ioctl", self.0, "FIONBIO", true);
let result = ioctl_fionbio(&self.0, true);
syscall_end!(result);
result?;
#[cfg(target_os = "macos")]
if ty == SocketType::STREAM {
syscall_start!("setsockopt", self.0, "SOL_SOCKET", "SO_NOSIGPIPE", true);
let result = rustix::net::sockopt::set_socket_nosigpipe(&self.0, true);
syscall_end!(result);
result?;
}
Ok(())
}
pub(crate) async fn ready<
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
>(
&self,
ctx: &Context<'_, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
direction: Direction,
) {
let mut registration = IoRegistration::new(ctx, self.0.as_fd(), &self.1, direction);
registration.wait().await;
}
pub(crate) fn try_read(&self, buf: &mut [u8]) -> rustix::io::Result<usize> {
loop {
syscall_start!("read", self.0);
let result = rustix::io::read(&self.0, &mut *buf);
syscall_end!(result; &buf[..result.unwrap_or(0)], buf.len());
if result != Err(Errno::INTR) {
return result;
}
}
}
pub(crate) fn try_write(&self, buf: &[u8]) -> rustix::io::Result<usize> {
loop {
syscall_start!("send", self.0, buf, buf.len(), STREAM_SEND_FLAGS);
let result = rustix::net::send(&self.0, buf, STREAM_SEND_FLAGS);
syscall_end!(result);
if result != Err(Errno::INTR) {
return result;
}
}
}
const fn retry<
'a,
'ctx,
S: State,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
T,
F: FnMut(&OwnedFd) -> rustix::io::Result<T> + Unpin,
>(
&'a self,
ctx: &'a Context<'ctx, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
direction: Direction,
op: F,
) -> Retry<'a, 'ctx, S, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS, F> {
Retry::new(ctx, &self.0, &self.1, direction, op)
}
}
impl Drop for Socket {
fn drop(&mut self) {
syscall!("close", self.0);
}
}