Skip to main content

dope_sys/io/socket/
raw.rs

1use std::{
2    mem::{self, MaybeUninit, size_of_val},
3    net,
4    ops::ControlFlow,
5    os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd},
6    ptr, slice,
7};
8
9use o3::{base::num::bounded, buffer};
10
11use crate::{
12    Errno,
13    io::{
14        self, fd,
15        socket::{Create, Domain, Kind, Setup, accept, addr, msg, record},
16    },
17    kernel::{self, errno},
18    memory,
19};
20
21use addr::{Addr, Buffer, CAPACITY, Error, FAMILY_BYTES, Socklen};
22pub(super) fn open<S: errno::Source + ?Sized, E: From<Errno>>(
23    domain: libc::c_int,
24    kind: libc::c_int,
25    protocol: libc::c_int,
26) -> Result<OwnedFd, E> {
27    // SAFETY: socket returns a fresh descriptor or -1 with this thread's errno.
28    unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<S, E>(libc::socket(domain, kind, protocol)) }
29}
30
31pub(super) fn listen<S: errno::Source + ?Sized, E: From<Errno>>(
32    file: BorrowedFd<'_>,
33    backlog: libc::c_int,
34) -> Result<(), E> {
35    // SAFETY: listen borrows the descriptor and returns zero or -1 with errno.
36    unsafe { io::raw::status::<S, E>(libc::listen(file.as_raw_fd(), backlog)) }
37}
38
39pub(super) fn shutdown<S: errno::Source + ?Sized, E: From<Errno>>(
40    file: BorrowedFd<'_>,
41    how: super::How,
42) -> Result<(), E> {
43    // SAFETY: shutdown borrows the descriptor and returns zero or -1 with errno.
44    unsafe { io::raw::status::<S, E>(libc::shutdown(file.as_raw_fd(), how.raw())) }
45}
46
47pub(super) fn send<'a, S: errno::Source + ?Sized, E: From<Errno>, const FLAGS: libc::c_int>(
48    file: BorrowedFd<'_>,
49    input: &'a [u8],
50    address: Option<addr::Addr<'_>>,
51) -> Result<&'a [u8], E> {
52    const { assert!(FLAGS & !(libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT) == 0) };
53    let fd = file.as_raw_fd();
54    let bytes = input.as_ptr().cast();
55    // SAFETY: both native calls borrow this input and return a count within it or -1.
56    unsafe {
57        let count = match address {
58            Some(address) => {
59                let (target, len) = address.parts();
60                libc::sendto(fd, bytes, input.len(), FLAGS, target.cast(), len.raw())
61            }
62            None => libc::send(fd, bytes, input.len(), FLAGS),
63        };
64        io::raw::Buffer::try_native::<S, E>(input, count)
65    }
66}
67
68pub(super) fn recv<'a, S: errno::Source + ?Sized, E: From<Errno>, const FLAGS: libc::c_int>(
69    file: BorrowedFd<'_>,
70    output: &'a mut [u8],
71    address: Option<&mut addr::Storage>,
72) -> Result<&'a mut [u8], E> {
73    const { assert!(FLAGS & !(libc::MSG_DONTWAIT | libc::MSG_PEEK | libc::MSG_WAITALL) == 0) };
74    let fd = file.as_raw_fd();
75    let bytes = output.as_mut_ptr().cast();
76    // SAFETY: MSG_TRUNC is excluded. Success initializes at most this output extent.
77    unsafe {
78        let count = match address {
79            Some(address) => {
80                let (address, len) = address.prepare();
81                libc::recvfrom(
82                    fd,
83                    bytes,
84                    output.len(),
85                    FLAGS,
86                    ptr::from_mut(address).cast(),
87                    len,
88                )
89            }
90            None => libc::recv(fd, bytes, output.len(), FLAGS),
91        };
92        io::raw::Buffer::try_native::<S, E>(output, count)
93    }
94}
95
96pub(super) fn get_option<S: errno::Source + ?Sized, E: From<Errno>, const OPTION: libc::c_int>(
97    file: BorrowedFd<'_>,
98) -> Result<libc::c_int, E> {
99    const {
100        assert!(matches!(
101            OPTION,
102            libc::SO_TYPE | libc::SO_ACCEPTCONN | libc::SO_ERROR
103        ));
104    }
105    let mut value = 0;
106    let mut len = size_of_val(&value) as libc::socklen_t;
107    // SAFETY: all three options write one native integer through this exclusive borrow.
108    unsafe {
109        io::raw::status::<S, E>(libc::getsockopt(
110            file.as_raw_fd(),
111            libc::SOL_SOCKET,
112            OPTION,
113            ptr::from_mut(&mut value).cast(),
114            &mut len,
115        ))?;
116    }
117    Ok(value)
118}
119
120pub(super) fn set_option<S: errno::Source + ?Sized, E: From<Errno>, const N: usize>(
121    file: BorrowedFd<'_>,
122    level: libc::c_int,
123    name: libc::c_int,
124    value: &[libc::c_int; N],
125) -> Result<(), E> {
126    const {
127        assert!(size_of::<[libc::c_int; N]>() <= libc::socklen_t::MAX as usize);
128    }
129    // SAFETY: the complete native input is initialized and remains borrowed until return.
130    unsafe {
131        io::raw::status::<S, E>(libc::setsockopt(
132            file.as_raw_fd(),
133            level,
134            name,
135            value.as_ptr().cast(),
136            size_of_val(value) as libc::socklen_t,
137        ))
138    }
139}
140
141pub(super) fn name<S: kernel::raw::Source + ?Sized, E: From<Errno>, const PEER: bool>(
142    file: BorrowedFd<'_>,
143    storage: &mut addr::Storage,
144) -> Result<(), E> {
145    let (address, len) = storage.prepare();
146    let address = ptr::from_mut(address).cast();
147    // SAFETY: the kernel receives the full exclusive storage and its writable length.
148    // Either query returns zero or -1 with this thread's errno.
149    unsafe {
150        let status = if PEER {
151            libc::getpeername(file.as_raw_fd(), address, len)
152        } else {
153            libc::getsockname(file.as_raw_fd(), address, len)
154        };
155        io::raw::status::<S, E>(status)
156    }
157}
158
159/// Receives streams or datagrams into caller-owned native storage.
160pub trait Receive {
161    fn recv(&self, output: buffer::raw::Output<'_>) -> Result<ControlFlow<()>, Errno>;
162
163    /// # Safety
164    /// Output belongs to a datagram pool with at least sixteen metadata bytes
165    /// followed by sockaddr_storage and the admitted payload capacity.
166    unsafe fn receive(&self, output: buffer::raw::Output<'_>) -> Result<(), Errno>;
167}
168
169pub trait Open: AsFd + Sized {
170    fn open(domain: Domain, kind: Kind) -> Result<Self, Create>;
171
172    fn adopt(file: OwnedFd) -> Result<Self, Setup>;
173
174    fn accept(&self, addr: Option<&mut addr::Storage>) -> Result<Self, accept::Error>;
175}
176
177/// Native access to operations retaining caller-owned socket storage.
178pub trait Source: errno::Source {
179    fn try_pair(kind: libc::c_int) -> Result<(OwnedFd, OwnedFd), record::Error> {
180        let mut fds = MaybeUninit::<[OwnedFd; 2]>::uninit();
181        // SAFETY: OwnedFd has RawFd's representation. Zero transfers both new descriptors.
182        unsafe {
183            let status = libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr().cast());
184            io::raw::status::<Self, Errno>(status).map_err(record::Error::Open)?;
185            Ok(fds.assume_init().into())
186        }
187    }
188
189    fn accept<E: From<Errno>>(
190        file: BorrowedFd<'_>,
191        addr: Option<&mut addr::Storage>,
192    ) -> Result<OwnedFd, E> {
193        let (addr, len) = match addr {
194            Some(addr) => {
195                let (addr, len) = addr.prepare();
196                (ptr::from_mut(addr).cast(), ptr::from_mut(len))
197            }
198            None => (ptr::null_mut(), ptr::null_mut()),
199        };
200        // SAFETY: both outputs are null or retain one exclusive full address buffer.
201        let raw = unsafe { libc::accept(file.as_raw_fd(), addr, len) };
202        // SAFETY: accept just returned a new descriptor or -1 with unchanged errno.
203        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
204    }
205
206    /// # Safety
207    /// The pointer retains a readable input prefix of exactly `len` bytes for this
208    /// call. Its original extent preserves the ABI bound and owns the input graph.
209    unsafe fn send<X: memory::raw::Extent, E: From<Errno>>(
210        file: BorrowedFd<'_>,
211        ptr: *const u8,
212        len: X::Length,
213    ) -> Result<X::Length, E> {
214        let len: bounded::raw::U32<0, { i32::MAX as u32 }> = len.into();
215        let capacity = len.get() as usize;
216        let raw = unsafe { libc::send(file.as_raw_fd(), ptr.cast(), capacity, libc::MSG_NOSIGNAL) };
217        // SAFETY: send completes at most the admitted c_int-bounded input extent.
218        Ok(
219            unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?
220                .bounded()
221                .into(),
222        )
223    }
224
225    /// # Safety
226    /// Header is the frozen root of a live input graph, with a total byte count
227    /// bounded by `i32::MAX`; its pointees outlive this call.
228    unsafe fn sendmsg<E: From<Errno>>(
229        file: BorrowedFd<'_>,
230        header: &msg::Header,
231        flags: libc::c_int,
232    ) -> Result<bounded::raw::U32<0, { i32::MAX as u32 }>, E> {
233        let raw = unsafe { libc::sendmsg(file.as_raw_fd(), header.as_raw(), flags) };
234        // SAFETY: the retained header has a total extent bounded by c_int.
235        Ok(unsafe { kernel::raw::Status::from_count(raw).try_count::<Self, E>() }?.bounded())
236    }
237}
238
239impl<T: errno::Source> Source for T {}
240
241/// Projection of a native iovec whose retained input graph proves its lifetime.
242pub trait Iovec {
243    /// # Safety
244    /// The descriptor must point to initialized bytes retained for the returned lifetime.
245    unsafe fn as_slice<'a>(&self) -> &'a [u8];
246}
247
248impl Iovec for msg::Iovec {
249    unsafe fn as_slice<'a>(&self) -> &'a [u8] {
250        if self.is_empty() {
251            return &[];
252        }
253        // SAFETY: the caller retains this nonempty descriptor's complete input bytes.
254        unsafe { slice::from_raw_parts(self.0.iov_base.cast(), self.0.iov_len) }
255    }
256}
257
258// SAFETY: sockaddr_un is zero-valid; its declared array fixes this platform's capacity.
259pub(super) const UNIX_CAPACITY: usize =
260    unsafe { mem::zeroed::<libc::sockaddr_un>() }.sun_path.len();
261
262// SAFETY: callers select an integer-only native sockaddr with this two-byte header.
263unsafe fn initialized<T>(header: [u8; 2]) -> T {
264    let mut native = MaybeUninit::<T>::zeroed();
265    unsafe {
266        native.as_mut_ptr().cast::<[u8; 2]>().write(header);
267        native.assume_init()
268    }
269}
270
271pub(super) fn unix<S: addr::Source>(
272    bytes: &[u8],
273    prefix: usize,
274    len: Socklen,
275) -> libc::sockaddr_un {
276    // SAFETY: sockaddr_un starts with the backend's two header bytes, followed by integer storage.
277    let mut native: libc::sockaddr_un = unsafe { initialized(S::header(Domain::Unix, len)) };
278    for (dst, byte) in native.sun_path.iter_mut().skip(prefix).zip(bytes) {
279        *dst = *byte as libc::c_char;
280    }
281    native
282}
283
284pub(super) fn ipv4<S: addr::Source>(address: &net::SocketAddrV4) -> libc::sockaddr_in {
285    // SAFETY: sockaddr_in starts with the backend's two header bytes; its fields are integers.
286    let mut native: libc::sockaddr_in =
287        unsafe { initialized(S::header(Domain::Inet4, Socklen::of::<libc::sockaddr_in>())) };
288    native.sin_port = address.port().to_be();
289    native.sin_addr.s_addr = u32::from_ne_bytes(address.ip().octets());
290    native
291}
292
293pub(super) fn ipv6<S: addr::Source>(address: &net::SocketAddrV6) -> libc::sockaddr_in6 {
294    // SAFETY: sockaddr_in6 starts with the backend's two header bytes; its fields are integers.
295    let mut native: libc::sockaddr_in6 = unsafe {
296        initialized(S::header(
297            Domain::Inet6,
298            Socklen::of::<libc::sockaddr_in6>(),
299        ))
300    };
301    native.sin6_port = address.port().to_be();
302    native.sin6_flowinfo = address.flowinfo();
303    native.sin6_addr.s6_addr = address.ip().octets();
304    native.sin6_scope_id = address.scope_id();
305    native
306}
307
308pub(super) fn empty() -> libc::sockaddr_storage {
309    // SAFETY: all fields of sockaddr_storage accept zero.
310    unsafe { mem::zeroed() }
311}
312
313pub(super) fn copy(source: Addr<'_>) -> libc::sockaddr_storage {
314    let mut output = empty();
315    let (address, len) = source.parts();
316    // SAFETY: Addr retains the source through the copy, with an extent at most CAPACITY.
317    unsafe {
318        ptr::copy_nonoverlapping(
319            address.cast::<u8>(),
320            ptr::from_mut(&mut output).cast(),
321            len.get(),
322        )
323    };
324    output
325}
326
327pub(super) fn parse(bytes: &[u8]) -> Result<net::SocketAddr, Error> {
328    // SAFETY: every input byte is initialized; decode rejects length before reading.
329    unsafe { decode::<false>(bytes.as_ptr(), bytes.len()) }
330}
331
332pub(super) fn observed(storage: &Buffer, len: usize) -> Result<net::SocketAddr, Error> {
333    // SAFETY: the kernel filled native fields within storage; decode first checks the reported length.
334    unsafe { decode::<false>(ptr::from_ref(storage).cast(), len) }
335}
336
337pub(super) fn decoded(address: Addr<'_>) -> Result<net::SocketAddr, Error> {
338    // SAFETY: the admitted length and native fields belong to this borrowed address.
339    let (address, len) = address.parts();
340    unsafe { decode::<true>(address.cast(), len.get()) }
341}
342
343// SAFETY: after length admission, fields within the reported extent are readable; alignment is optional.
344unsafe fn decode<const ADMITTED: bool>(
345    bytes: *const u8,
346    actual: usize,
347) -> Result<net::SocketAddr, Error> {
348    if !ADMITTED && actual > CAPACITY {
349        return Err(Error::Storage {
350            actual,
351            capacity: CAPACITY,
352        });
353    }
354    if actual < FAMILY_BYTES {
355        return Err(Error::Header {
356            actual,
357            required: FAMILY_BYTES,
358        });
359    }
360    let family = unsafe {
361        bytes
362            .add(mem::offset_of!(libc::sockaddr_storage, ss_family))
363            .cast::<libc::sa_family_t>()
364            .read_unaligned()
365    } as libc::c_int;
366    match family {
367        libc::AF_INET => {
368            let v = unsafe { read::<libc::sockaddr_in>(bytes, actual, family)? };
369            Ok(net::SocketAddrV4::new(
370                net::Ipv4Addr::from(u32::from_be(v.sin_addr.s_addr)),
371                u16::from_be(v.sin_port),
372            )
373            .into())
374        }
375        libc::AF_INET6 => {
376            let v = unsafe { read::<libc::sockaddr_in6>(bytes, actual, family)? };
377            Ok(net::SocketAddrV6::new(
378                net::Ipv6Addr::from(v.sin6_addr.s6_addr),
379                u16::from_be(v.sin6_port),
380                v.sin6_flowinfo,
381                v.sin6_scope_id,
382            )
383            .into())
384        }
385        _ => Err(Error::Unsupported { family, actual }),
386    }
387}
388
389// SAFETY: the selected native type has integer fields initialized when its complete extent fits.
390unsafe fn read<T: Copy>(bytes: *const u8, actual: usize, family: i32) -> Result<T, Error> {
391    let required = mem::size_of::<T>();
392    if actual < required {
393        return Err(Error::Address {
394            family,
395            actual,
396            required,
397        });
398    }
399    Ok(unsafe { bytes.cast::<T>().read_unaligned() })
400}
401
402pub(super) fn apply<S: kernel::raw::Source + ?Sized, E: From<Errno>, const CONNECT: bool>(
403    file: BorrowedFd<'_>,
404    address: Addr<'_>,
405) -> Result<(), E> {
406    let (target, len) = address.parts();
407    // SAFETY: both operations borrow the entire live address and report zero or -1 with errno.
408    unsafe {
409        let status = if CONNECT {
410            libc::connect(file.as_raw_fd(), target.cast(), len.raw())
411        } else {
412            libc::bind(file.as_raw_fd(), target.cast(), len.raw())
413        };
414        io::raw::status::<S, E>(status)
415    }
416}