dope-sys 0.78.0

Typed operating-system call contracts
Documentation
use std::{
    mem, net, num,
    os::fd::{AsFd, BorrowedFd, OwnedFd},
};

use option::fast;

use crate::{Cloexec, Errno, Nonblock, kernel::errno};

pub mod accept;
pub mod addr;
pub mod gso;
pub mod msg;
pub mod option;
pub mod raw;
pub mod record;
pub mod route;

/// Exact backlog bound the host admits for one listening socket.
pub const BACKLOG: i32 = libc::SOMAXCONN;

/// Exact failure to create and initialize one socket descriptor.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Create {
    fault: Errno,
    kind: Option<SetupKind>,
}

/// Concrete leaf retained by one compact creation failure.
pub enum Origin {
    Socket(Errno),
    Setup(Setup),
}

impl Create {
    /// Records failure of the descriptor-creation syscall itself.
    pub const fn socket(fault: Errno) -> Self {
        Self { fault, kind: None }
    }

    /// Records the exact descriptor setup operation that failed after creation.
    pub const fn setup(error: Setup) -> Self {
        Self {
            fault: error.fault,
            kind: Some(error.kind),
        }
    }

    pub const fn origin(self) -> Origin {
        match self.kind {
            Some(kind) => Origin::Setup(Setup {
                fault: self.fault,
                kind,
            }),
            None => Origin::Socket(self.fault),
        }
    }
}

const _: () = assert!(mem::size_of::<Create>() == 2 * mem::size_of::<u32>());

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Domain {
    Inet4,
    Inet6,
    Unix,
}

impl Domain {
    pub fn for_addr(addr: &net::SocketAddr) -> Self {
        if addr.is_ipv4() {
            Self::Inet4
        } else {
            Self::Inet6
        }
    }

    pub const fn raw(self) -> libc::c_int {
        use libc::{AF_INET, AF_INET6};
        match self {
            Self::Inet4 => AF_INET,
            Self::Inet6 => AF_INET6,
            Self::Unix => libc::AF_UNIX,
        }
    }
}

/// One observed `SO_TYPE` value of an adopted descriptor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct Type(libc::c_int);

impl Type {
    /// Whether this descriptor is one connected byte stream.
    pub const fn is_stream(self) -> bool {
        self.0 == libc::SOCK_STREAM
    }

    /// Whether this descriptor is one datagram socket.
    pub const fn is_datagram(self) -> bool {
        self.0 == libc::SOCK_DGRAM
    }

    /// Raw observed value, for exact diagnostics.
    pub const fn raw(self) -> i32 {
        self.0
    }
}

/// One half-close direction for [`Socket::shutdown`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct How(libc::c_int);

impl How {
    pub const READ: Self = Self(libc::SHUT_RD);
    pub const WRITE: Self = Self(libc::SHUT_WR);
    pub const BOTH: Self = Self(libc::SHUT_RDWR);

    pub const fn raw(self) -> libc::c_int {
        self.0
    }
}

/// One requested address reuse admitted before binding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Reuse {
    Address,
    Port,
}

/// Exact failure while opening a close-on-exec socket.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Failure {
    Socket(Errno),
    Cloexec(Cloexec),
}

impl From<Errno> for Failure {
    fn from(error: Errno) -> Self {
        Self::Socket(error)
    }
}

impl From<Cloexec> for Failure {
    fn from(error: Cloexec) -> Self {
        Self::Cloexec(error)
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Stream,
    Dgram,
}

impl Kind {
    pub const fn raw(self) -> libc::c_int {
        use libc::{SOCK_DGRAM, SOCK_STREAM};
        match self {
            Self::Stream => SOCK_STREAM,
            Self::Dgram => SOCK_DGRAM,
        }
    }
}

/// Native socket ownership and fast-open support before driver installation.
pub trait Prepare: Socket {
    type Handle: AsFd;
    type Fast;

    fn fast_open(depth: Option<num::NonZero<i32>>) -> Result<Option<Self::Fast>, fast::Error>;
    fn open(domain: Domain, kind: Kind) -> Result<Self::Handle, Create>;
    fn listener(domain: Domain) -> Result<Self::Handle, Create>;
    fn adopt(file: OwnedFd) -> Result<Self::Handle, Setup>;
    /// Transfers the prepared socket's descriptor without changing its native configuration.
    fn into_fd(handle: Self::Handle) -> OwnedFd;
    fn set_fast(file: BorrowedFd<'_>, fast: Self::Fast) -> Result<(), Errno>;
}

/// Exact socket descriptor setup failure.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Setup {
    pub fault: Errno,
    pub kind: SetupKind,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum SetupKind {
    GetFd,
    SetFd,
    GetFlags,
    SetFlags,
    Sigpipe,
}

impl Setup {
    pub const fn cloexec(error: Cloexec) -> Self {
        match error {
            Cloexec::Get(fault) => Self {
                fault,
                kind: SetupKind::GetFd,
            },
            Cloexec::Set(fault) => Self {
                fault,
                kind: SetupKind::SetFd,
            },
        }
    }

    pub const fn nonblock(error: Nonblock) -> Self {
        match error {
            Nonblock::Get(fault) => Self {
                fault,
                kind: SetupKind::GetFlags,
            },
            Nonblock::Set(fault) => Self {
                fault,
                kind: SetupKind::SetFlags,
            },
        }
    }

    pub const fn sigpipe(fault: Errno) -> Self {
        Self {
            fault,
            kind: SetupKind::Sigpipe,
        }
    }
}

const _: () = assert!(mem::size_of::<Setup>() == 2 * mem::size_of::<u32>());

/// Native socket creation and synchronous transfer.
pub trait Socket: errno::Source {
    const MAX_IOVECS: usize;
    type Error;

    fn socket(domain: libc::c_int, kind: libc::c_int) -> Result<OwnedFd, Self::Error>;
    /// Creates exclusively owned local socket endpoints.
    fn pair() -> Result<(OwnedFd, OwnedFd), record::Error>;

    /// Creates one datagram descriptor without changing its descriptor flags.
    fn datagram<E: From<Errno>>(domain: Domain) -> Result<OwnedFd, E> {
        let protocol = match domain {
            Domain::Inet4 | Domain::Inet6 => libc::IPPROTO_UDP,
            Domain::Unix => 0,
        };
        Self::try_open(domain.raw(), libc::SOCK_DGRAM, protocol)
    }

    fn try_open<E: From<Errno>>(
        domain: libc::c_int,
        kind: libc::c_int,
        protocol: libc::c_int,
    ) -> Result<OwnedFd, E> {
        raw::open::<Self, E>(domain, kind, protocol)
    }

    fn listen<E: From<Errno>>(file: BorrowedFd<'_>, backlog: libc::c_int) -> Result<(), E> {
        raw::listen::<Self, E>(file, backlog)
    }

    /// Half-closes one socket in the requested direction.
    fn shutdown<E: From<Errno>>(file: BorrowedFd<'_>, how: How) -> Result<(), E> {
        raw::shutdown::<Self, E>(file, how)
    }

    /// Observes the connected peer into caller-owned native address storage.
    fn peer_addr<E: From<Errno>>(
        file: BorrowedFd<'_>,
        address: &mut addr::Storage,
    ) -> Result<(), E> {
        raw::name::<Self, E, true>(file, address)
    }

    /// Sends one byte string without raising the termination signal.
    fn send_quiet<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
    ) -> Result<&'a [u8], E> {
        Self::send::<{ libc::MSG_NOSIGNAL }, E>(file, input)
    }

    /// Sends without waiting or raising the termination signal.
    fn send_now<'a, E: From<Errno>>(file: BorrowedFd<'_>, input: &'a [u8]) -> Result<&'a [u8], E> {
        Self::send::<{ libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL }, E>(file, input)
    }

    fn send<'a, const FLAGS: libc::c_int, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
    ) -> Result<&'a [u8], E> {
        raw::send::<Self, E, FLAGS>(file, input, None)
    }

    fn recv<'a, const FLAGS: libc::c_int, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
    ) -> Result<&'a mut [u8], E> {
        raw::recv::<Self, E, FLAGS>(file, output, None)
    }

    fn recv_now<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
    ) -> Result<&'a mut [u8], E> {
        Self::recv::<{ libc::MSG_DONTWAIT }, E>(file, output)
    }

    /// Sends one datagram to the retained native destination.
    fn send_to<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
        address: addr::Addr<'_>,
    ) -> Result<&'a [u8], E> {
        raw::send::<Self, E, { libc::MSG_NOSIGNAL }>(file, input, Some(address))
    }

    /// Receives one datagram and its source into caller-owned storage.
    fn recv_from<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
        address: &mut addr::Storage,
    ) -> Result<&'a mut [u8], E> {
        raw::recv::<Self, E, 0>(file, output, Some(address))
    }
}