dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{
    mem::MaybeUninit,
    ops::ControlFlow,
    os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd},
    ptr, slice,
};

use o3::{base::num::bounded, buffer};

use crate::{
    Errno,
    io::{
        self, fd,
        socket::{Create, Domain, Kind, Setup, accept, addr, msg, record},
    },
    kernel::{self, errno},
    memory,
};

pub(super) fn name<S: kernel::raw::Source + ?Sized, E: From<Errno>, const PEER: bool>(
    file: BorrowedFd<'_>,
    storage: &mut addr::Storage,
) -> Result<(), E> {
    let (address, len) = storage.prepare();
    let address = ptr::from_mut(address).cast();
    // SAFETY: the kernel receives the full exclusive storage and its writable length.
    // Either query returns zero or -1 with this thread's errno.
    unsafe {
        let status = if PEER {
            libc::getpeername(file.as_raw_fd(), address, len)
        } else {
            libc::getsockname(file.as_raw_fd(), address, len)
        };
        io::raw::status::<S, E>(status)
    }
}

/// Receives streams or datagrams into caller-owned native storage.
pub trait Receive {
    fn recv(&self, output: buffer::raw::Output<'_>) -> Result<ControlFlow<()>, Errno>;

    /// # Safety
    /// Output belongs to a datagram pool with at least sixteen metadata bytes
    /// followed by sockaddr_storage and the admitted payload capacity.
    unsafe fn receive(&self, output: buffer::raw::Output<'_>) -> Result<(), Errno>;
}

pub trait Open: AsFd + Sized {
    fn open(domain: Domain, kind: Kind) -> Result<Self, Create>;

    fn adopt(file: OwnedFd) -> Result<Self, Setup>;

    fn accept(&self, addr: Option<&mut addr::Storage>) -> Result<Self, accept::Error>;
}

/// Native access to operations retaining caller-owned socket storage.
pub trait Source: errno::Source {
    fn try_pair(kind: libc::c_int) -> Result<(OwnedFd, OwnedFd), record::Error> {
        let mut fds = MaybeUninit::<[OwnedFd; 2]>::uninit();
        // SAFETY: OwnedFd has RawFd's representation. Zero transfers both new descriptors.
        unsafe {
            let status = libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr().cast());
            io::raw::status::<Self, Errno>(status).map_err(record::Error::Open)?;
            Ok(fds.assume_init().into())
        }
    }

    fn accept<E: From<Errno>>(
        file: BorrowedFd<'_>,
        addr: Option<&mut addr::Storage>,
    ) -> Result<OwnedFd, E> {
        let (addr, len) = match addr {
            Some(addr) => {
                let (addr, len) = addr.prepare();
                (ptr::from_mut(addr).cast(), ptr::from_mut(len))
            }
            None => (ptr::null_mut(), ptr::null_mut()),
        };
        // SAFETY: both outputs are null or retain one exclusive full address buffer.
        let raw = unsafe { libc::accept(file.as_raw_fd(), addr, len) };
        // SAFETY: accept just returned a new descriptor or -1 with unchanged errno.
        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
    }

    /// # Safety
    /// The pointer retains a readable input prefix of exactly `len` bytes for this
    /// call. Its original extent preserves the ABI bound and owns the input graph.
    unsafe fn send<X: memory::raw::Extent, E: From<Errno>>(
        file: BorrowedFd<'_>,
        ptr: *const u8,
        len: X::Length,
    ) -> Result<X::Length, E> {
        let len: bounded::raw::U32<0, { i32::MAX as u32 }> = len.into();
        let capacity = len.get() as usize;
        let raw = unsafe { libc::send(file.as_raw_fd(), ptr.cast(), capacity, libc::MSG_NOSIGNAL) };
        // SAFETY: send completes at most the admitted c_int-bounded input extent.
        Ok(
            unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?
                .bounded()
                .into(),
        )
    }

    /// # Safety
    /// Header is the frozen root of a live input graph, with a total byte count
    /// bounded by `i32::MAX`; its pointees outlive this call.
    unsafe fn sendmsg<E: From<Errno>>(
        file: BorrowedFd<'_>,
        header: &msg::Header,
        flags: libc::c_int,
    ) -> Result<bounded::raw::U32<0, { i32::MAX as u32 }>, E> {
        let raw = unsafe { libc::sendmsg(file.as_raw_fd(), header.as_raw(), flags) };
        // SAFETY: the retained header has a total extent bounded by c_int.
        Ok(unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?.bounded())
    }
}

impl<T: errno::Source> Source for T {}

/// Projection of a native iovec whose retained input graph proves its lifetime.
pub trait Iovec {
    /// # Safety
    /// The descriptor must point to initialized bytes retained for the returned lifetime.
    unsafe fn as_slice<'a>(&self) -> &'a [u8];
}

impl Iovec for msg::Iovec {
    unsafe fn as_slice<'a>(&self) -> &'a [u8] {
        if self.is_empty() {
            return &[];
        }
        // SAFETY: the caller retains this nonempty descriptor's complete input bytes.
        unsafe { slice::from_raw_parts(self.0.iov_base.cast(), self.0.iov_len) }
    }
}