Skip to main content

dope_sys/io/socket/
raw.rs

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