dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{
    mem,
    os::fd::{self, AsFd, AsRawFd as _, BorrowedFd},
    ptr,
};

use libc::socklen_t;

use crate::{
    Errno,
    io::{
        socket,
        socket::option::{Kind, Value},
    },
    kernel::{self, errno},
};

/// Native socket option selection and access.
pub trait Source: errno::Source {
    type Listening;

    const KEEP_IDLE: libc::c_int;

    /// Makes closing this exclusively owned connection send a reset.
    fn reset<E: From<Errno>>(file: impl AsFd) -> Result<(), E> {
        let linger = libc::linger {
            l_onoff: 1,
            l_linger: 0,
        };
        // SAFETY: the live descriptor and complete native value outlive the call.
        let raw = unsafe {
            libc::setsockopt(
                file.as_fd().as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_LINGER,
                ptr::from_ref(&linger).cast(),
                mem::size_of_val(&linger) as socklen_t,
            )
        };
        // SAFETY: setsockopt returns zero or -1; errno is captured immediately.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
    }

    /// Observes the socket type of one adopted descriptor.
    fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<socket::Type, E> {
        Self::get_option::<{ libc::SO_TYPE }, E>(file).map(socket::Type)
    }

    /// Whether one adopted descriptor is already listening.
    fn is_listening(file: BorrowedFd<'_>) -> Result<bool, Self::Listening>;

    /// Admits the requested address reuse on one socket.
    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> {
        const {
            assert!(
                OPTION == libc::SO_TYPE
                    || OPTION == libc::SO_ACCEPTCONN
                    || OPTION == libc::SO_ERROR
            );
        }
        let mut value = 0;
        let mut len = mem::size_of::<libc::c_int>() as socklen_t;
        let raw = unsafe {
            libc::getsockopt(
                file.as_raw_fd(),
                libc::SOL_SOCKET,
                OPTION,
                ptr::from_mut(&mut value).cast(),
                &mut len,
            )
        };
        // SAFETY: getsockopt returns exactly zero or minus one.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
        Ok(value)
    }

    fn set_option<E: From<Errno>>(
        file: BorrowedFd<'_>,
        level: libc::c_int,
        option: libc::c_int,
        value: &libc::c_int,
    ) -> Result<(), E> {
        let raw = unsafe {
            libc::setsockopt(
                file.as_raw_fd(),
                level,
                option,
                ptr::from_ref(value).cast(),
                mem::size_of::<libc::c_int>() as socklen_t,
            )
        };
        // SAFETY: setsockopt returns exactly zero or minus one.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
    }

    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())
    }
}