Skip to main content

dope_sys/io/socket/
raw.rs

1use std::{
2    mem::MaybeUninit,
3    ops::ControlFlow,
4    os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd},
5    ptr, slice,
6};
7
8use o3::{base::num::bounded, buffer};
9
10use crate::{
11    Errno,
12    io::{
13        self, fd,
14        socket::{Create, Domain, Kind, Setup, accept, addr, msg, record},
15    },
16    kernel::{self, errno},
17    memory,
18};
19
20pub(super) fn name<S: kernel::raw::Source + ?Sized, E: From<Errno>, const PEER: bool>(
21    file: BorrowedFd<'_>,
22    storage: &mut addr::Storage,
23) -> Result<(), E> {
24    let (address, len) = storage.prepare();
25    let address = ptr::from_mut(address).cast();
26    // SAFETY: the kernel receives the full exclusive storage and its writable length.
27    // Either query returns zero or -1 with this thread's errno.
28    unsafe {
29        let status = if PEER {
30            libc::getpeername(file.as_raw_fd(), address, len)
31        } else {
32            libc::getsockname(file.as_raw_fd(), address, len)
33        };
34        io::raw::status::<S, E>(status)
35    }
36}
37
38/// Receives streams or datagrams into caller-owned native storage.
39pub trait Receive {
40    fn recv(&self, output: buffer::raw::Output<'_>) -> Result<ControlFlow<()>, Errno>;
41
42    /// # Safety
43    /// Output belongs to a datagram pool with at least sixteen metadata bytes
44    /// followed by sockaddr_storage and the admitted payload capacity.
45    unsafe fn receive(&self, output: buffer::raw::Output<'_>) -> Result<(), Errno>;
46}
47
48pub trait Open: AsFd + Sized {
49    fn open(domain: Domain, kind: Kind) -> Result<Self, Create>;
50
51    fn adopt(file: OwnedFd) -> Result<Self, Setup>;
52
53    fn accept(&self, addr: Option<&mut addr::Storage>) -> Result<Self, accept::Error>;
54}
55
56/// Native access to operations retaining caller-owned socket storage.
57pub trait Source: errno::Source {
58    fn try_pair(kind: libc::c_int) -> Result<(OwnedFd, OwnedFd), record::Error> {
59        let mut fds = MaybeUninit::<[OwnedFd; 2]>::uninit();
60        // SAFETY: OwnedFd has RawFd's representation. Zero transfers both new descriptors.
61        unsafe {
62            let status = libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr().cast());
63            io::raw::status::<Self, Errno>(status).map_err(record::Error::Open)?;
64            Ok(fds.assume_init().into())
65        }
66    }
67
68    fn accept<E: From<Errno>>(
69        file: BorrowedFd<'_>,
70        addr: Option<&mut addr::Storage>,
71    ) -> Result<OwnedFd, E> {
72        let (addr, len) = match addr {
73            Some(addr) => {
74                let (addr, len) = addr.prepare();
75                (ptr::from_mut(addr).cast(), ptr::from_mut(len))
76            }
77            None => (ptr::null_mut(), ptr::null_mut()),
78        };
79        // SAFETY: both outputs are null or retain one exclusive full address buffer.
80        let raw = unsafe { libc::accept(file.as_raw_fd(), addr, len) };
81        // SAFETY: accept just returned a new descriptor or -1 with unchanged errno.
82        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
83    }
84
85    /// # Safety
86    /// The pointer retains a readable input prefix of exactly `len` bytes for this
87    /// call. Its original extent preserves the ABI bound and owns the input graph.
88    unsafe fn send<X: memory::raw::Extent, E: From<Errno>>(
89        file: BorrowedFd<'_>,
90        ptr: *const u8,
91        len: X::Length,
92    ) -> Result<X::Length, E> {
93        let len: bounded::raw::U32<0, { i32::MAX as u32 }> = len.into();
94        let capacity = len.get() as usize;
95        let raw = unsafe { libc::send(file.as_raw_fd(), ptr.cast(), capacity, libc::MSG_NOSIGNAL) };
96        // SAFETY: send completes at most the admitted c_int-bounded input extent.
97        Ok(
98            unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?
99                .bounded()
100                .into(),
101        )
102    }
103
104    /// # Safety
105    /// Header is the frozen root of a live input graph, with a total byte count
106    /// bounded by `i32::MAX`; its pointees outlive this call.
107    unsafe fn sendmsg<E: From<Errno>>(
108        file: BorrowedFd<'_>,
109        header: &msg::Header,
110        flags: libc::c_int,
111    ) -> Result<bounded::raw::U32<0, { i32::MAX as u32 }>, E> {
112        let raw = unsafe { libc::sendmsg(file.as_raw_fd(), header.as_raw(), flags) };
113        // SAFETY: the retained header has a total extent bounded by c_int.
114        Ok(unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?.bounded())
115    }
116}
117
118impl<T: errno::Source> Source for T {}
119
120/// Projection of a native iovec whose retained input graph proves its lifetime.
121pub trait Iovec {
122    /// # Safety
123    /// The descriptor must point to initialized bytes retained for the returned lifetime.
124    unsafe fn as_slice<'a>(&self) -> &'a [u8];
125}
126
127impl Iovec for msg::Iovec {
128    unsafe fn as_slice<'a>(&self) -> &'a [u8] {
129        if self.is_empty() {
130            return &[];
131        }
132        // SAFETY: the caller retains this nonempty descriptor's complete input bytes.
133        unsafe { slice::from_raw_parts(self.0.iov_base.cast(), self.0.iov_len) }
134    }
135}