use std::{
array, mem,
num::NonZero,
os::fd::{self, AsFd, BorrowedFd},
};
use crate::{
Errno,
io::{
socket,
socket::option::{Kind, Value},
},
kernel::errno,
};
pub trait Source: errno::Source {
type Listening;
const KEEP_IDLE: libc::c_int;
fn reset<E: From<Errno>>(file: impl AsFd) -> Result<(), E> {
const {
assert!(size_of::<libc::linger>() == size_of::<[libc::c_int; 2]>());
assert!(align_of::<libc::linger>() == align_of::<[libc::c_int; 2]>());
assert!(mem::offset_of!(libc::linger, l_onoff) == 0);
assert!(mem::offset_of!(libc::linger, l_linger) == size_of::<libc::c_int>());
}
socket::raw::set_option::<Self, E, 2>(
file.as_fd(),
libc::SOL_SOCKET,
libc::SO_LINGER,
&[1, 0],
)
}
fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<socket::Type, E> {
Self::get_option::<{ libc::SO_TYPE }, E>(file).map(socket::Type)
}
fn take_error(file: BorrowedFd<'_>) -> Result<Option<Errno>, Errno> {
let error = socket::raw::get_option::<Self, Errno, { libc::SO_ERROR }>(file)?;
Ok(NonZero::new(error).map(Errno))
}
fn is_listening(file: BorrowedFd<'_>) -> Result<bool, Self::Listening>;
fn set_reuse<E: From<Errno>>(file: BorrowedFd<'_>, reuse: socket::Reuse) -> Result<(), E> {
let option = match reuse {
socket::Reuse::Address => libc::SO_REUSEADDR,
socket::Reuse::Port => libc::SO_REUSEPORT,
};
Self::set_option(file, libc::SOL_SOCKET, option, &1)
}
fn get_option<const OPTION: libc::c_int, E: From<Errno>>(
file: BorrowedFd<'_>,
) -> Result<libc::c_int, E> {
socket::raw::get_option::<Self, E, OPTION>(file)
}
fn set_option<E: From<Errno>>(
file: BorrowedFd<'_>,
level: libc::c_int,
option: libc::c_int,
value: &libc::c_int,
) -> Result<(), E> {
socket::raw::set_option::<Self, E, 1>(file, level, option, array::from_ref(value))
}
fn option(kind: Kind) -> (libc::c_int, libc::c_int) {
match kind {
Kind::NoDelay => (libc::IPPROTO_TCP, libc::TCP_NODELAY),
Kind::KeepAlive => (libc::SOL_SOCKET, libc::SO_KEEPALIVE),
Kind::RecvBuffer => (libc::SOL_SOCKET, libc::SO_RCVBUF),
Kind::SendBuffer => (libc::SOL_SOCKET, libc::SO_SNDBUF),
Kind::KeepAliveIdle => (libc::IPPROTO_TCP, Self::KEEP_IDLE),
Kind::KeepAliveInterval => (libc::IPPROTO_TCP, libc::TCP_KEEPINTVL),
Kind::KeepAliveRetries => (libc::IPPROTO_TCP, libc::TCP_KEEPCNT),
}
}
fn set(fd: fd::BorrowedFd<'_>, kind: Kind, value: &Value) -> Result<(), Errno> {
let (level, name) = Self::option(kind);
Self::set_option(fd, level, name, &value.raw())
}
}