dope-sys 0.77.0

Typed operating-system call contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::{
    mem::{self, MaybeUninit, size_of_val},
    net,
    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,
};

use addr::{Addr, Buffer, CAPACITY, Error, FAMILY_BYTES, Socklen};
pub(super) fn open<S: errno::Source + ?Sized, E: From<Errno>>(
    domain: libc::c_int,
    kind: libc::c_int,
    protocol: libc::c_int,
) -> Result<OwnedFd, E> {
    // SAFETY: socket returns a fresh descriptor or -1 with this thread's errno.
    unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<S, E>(libc::socket(domain, kind, protocol)) }
}

pub(super) fn listen<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    backlog: libc::c_int,
) -> Result<(), E> {
    // SAFETY: listen borrows the descriptor and returns zero or -1 with errno.
    unsafe { io::raw::status::<S, E>(libc::listen(file.as_raw_fd(), backlog)) }
}

pub(super) fn shutdown<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    how: super::How,
) -> Result<(), E> {
    // SAFETY: shutdown borrows the descriptor and returns zero or -1 with errno.
    unsafe { io::raw::status::<S, E>(libc::shutdown(file.as_raw_fd(), how.raw())) }
}

pub(super) fn send<'a, S: errno::Source + ?Sized, E: From<Errno>, const FLAGS: libc::c_int>(
    file: BorrowedFd<'_>,
    input: &'a [u8],
    address: Option<addr::Addr<'_>>,
) -> Result<&'a [u8], E> {
    const { assert!(FLAGS & !(libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT) == 0) };
    let fd = file.as_raw_fd();
    let bytes = input.as_ptr().cast();
    // SAFETY: both native calls borrow this input and return a count within it or -1.
    unsafe {
        let count = match address {
            Some(address) => {
                let (target, len) = address.parts();
                libc::sendto(fd, bytes, input.len(), FLAGS, target.cast(), len.raw())
            }
            None => libc::send(fd, bytes, input.len(), FLAGS),
        };
        io::raw::Buffer::try_native::<S, E>(input, count)
    }
}

pub(super) fn recv<'a, S: errno::Source + ?Sized, E: From<Errno>, const FLAGS: libc::c_int>(
    file: BorrowedFd<'_>,
    output: &'a mut [u8],
    address: Option<&mut addr::Storage>,
) -> Result<&'a mut [u8], E> {
    const { assert!(FLAGS & !(libc::MSG_DONTWAIT | libc::MSG_PEEK | libc::MSG_WAITALL) == 0) };
    let fd = file.as_raw_fd();
    let bytes = output.as_mut_ptr().cast();
    // SAFETY: MSG_TRUNC is excluded. Success initializes at most this output extent.
    unsafe {
        let count = match address {
            Some(address) => {
                let (address, len) = address.prepare();
                libc::recvfrom(
                    fd,
                    bytes,
                    output.len(),
                    FLAGS,
                    ptr::from_mut(address).cast(),
                    len,
                )
            }
            None => libc::recv(fd, bytes, output.len(), FLAGS),
        };
        io::raw::Buffer::try_native::<S, E>(output, count)
    }
}

pub(super) fn get_option<S: errno::Source + ?Sized, E: From<Errno>, const OPTION: libc::c_int>(
    file: BorrowedFd<'_>,
) -> Result<libc::c_int, E> {
    const {
        assert!(matches!(
            OPTION,
            libc::SO_TYPE | libc::SO_ACCEPTCONN | libc::SO_ERROR
        ));
    }
    let mut value = 0;
    let mut len = size_of_val(&value) as libc::socklen_t;
    // SAFETY: all three options write one native integer through this exclusive borrow.
    unsafe {
        io::raw::status::<S, E>(libc::getsockopt(
            file.as_raw_fd(),
            libc::SOL_SOCKET,
            OPTION,
            ptr::from_mut(&mut value).cast(),
            &mut len,
        ))?;
    }
    Ok(value)
}

pub(super) fn set_option<S: errno::Source + ?Sized, E: From<Errno>, const N: usize>(
    file: BorrowedFd<'_>,
    level: libc::c_int,
    name: libc::c_int,
    value: &[libc::c_int; N],
) -> Result<(), E> {
    const {
        assert!(size_of::<[libc::c_int; N]>() <= libc::socklen_t::MAX as usize);
    }
    // SAFETY: the complete native input is initialized and remains borrowed until return.
    unsafe {
        io::raw::status::<S, E>(libc::setsockopt(
            file.as_raw_fd(),
            level,
            name,
            value.as_ptr().cast(),
            size_of_val(value) as libc::socklen_t,
        ))
    }
}

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) }
    }
}

// SAFETY: sockaddr_un is zero-valid; its declared array fixes this platform's capacity.
pub(super) const UNIX_CAPACITY: usize =
    unsafe { mem::zeroed::<libc::sockaddr_un>() }.sun_path.len();

// SAFETY: callers select an integer-only native sockaddr with this two-byte header.
unsafe fn initialized<T>(header: [u8; 2]) -> T {
    let mut native = MaybeUninit::<T>::zeroed();
    unsafe {
        native.as_mut_ptr().cast::<[u8; 2]>().write(header);
        native.assume_init()
    }
}

pub(super) fn unix<S: addr::Source>(
    bytes: &[u8],
    prefix: usize,
    len: Socklen,
) -> libc::sockaddr_un {
    // SAFETY: sockaddr_un starts with the backend's two header bytes, followed by integer storage.
    let mut native: libc::sockaddr_un = unsafe { initialized(S::header(Domain::Unix, len)) };
    for (dst, byte) in native.sun_path.iter_mut().skip(prefix).zip(bytes) {
        *dst = *byte as libc::c_char;
    }
    native
}

pub(super) fn ipv4<S: addr::Source>(address: &net::SocketAddrV4) -> libc::sockaddr_in {
    // SAFETY: sockaddr_in starts with the backend's two header bytes; its fields are integers.
    let mut native: libc::sockaddr_in =
        unsafe { initialized(S::header(Domain::Inet4, Socklen::of::<libc::sockaddr_in>())) };
    native.sin_port = address.port().to_be();
    native.sin_addr.s_addr = u32::from_ne_bytes(address.ip().octets());
    native
}

pub(super) fn ipv6<S: addr::Source>(address: &net::SocketAddrV6) -> libc::sockaddr_in6 {
    // SAFETY: sockaddr_in6 starts with the backend's two header bytes; its fields are integers.
    let mut native: libc::sockaddr_in6 = unsafe {
        initialized(S::header(
            Domain::Inet6,
            Socklen::of::<libc::sockaddr_in6>(),
        ))
    };
    native.sin6_port = address.port().to_be();
    native.sin6_flowinfo = address.flowinfo();
    native.sin6_addr.s6_addr = address.ip().octets();
    native.sin6_scope_id = address.scope_id();
    native
}

pub(super) fn empty() -> libc::sockaddr_storage {
    // SAFETY: all fields of sockaddr_storage accept zero.
    unsafe { mem::zeroed() }
}

pub(super) fn copy(source: Addr<'_>) -> libc::sockaddr_storage {
    let mut output = empty();
    let (address, len) = source.parts();
    // SAFETY: Addr retains the source through the copy, with an extent at most CAPACITY.
    unsafe {
        ptr::copy_nonoverlapping(
            address.cast::<u8>(),
            ptr::from_mut(&mut output).cast(),
            len.get(),
        )
    };
    output
}

pub(super) fn parse(bytes: &[u8]) -> Result<net::SocketAddr, Error> {
    // SAFETY: every input byte is initialized; decode rejects length before reading.
    unsafe { decode::<false>(bytes.as_ptr(), bytes.len()) }
}

pub(super) fn observed(storage: &Buffer, len: usize) -> Result<net::SocketAddr, Error> {
    // SAFETY: the kernel filled native fields within storage; decode first checks the reported length.
    unsafe { decode::<false>(ptr::from_ref(storage).cast(), len) }
}

pub(super) fn decoded(address: Addr<'_>) -> Result<net::SocketAddr, Error> {
    // SAFETY: the admitted length and native fields belong to this borrowed address.
    let (address, len) = address.parts();
    unsafe { decode::<true>(address.cast(), len.get()) }
}

// SAFETY: after length admission, fields within the reported extent are readable; alignment is optional.
unsafe fn decode<const ADMITTED: bool>(
    bytes: *const u8,
    actual: usize,
) -> Result<net::SocketAddr, Error> {
    if !ADMITTED && actual > CAPACITY {
        return Err(Error::Storage {
            actual,
            capacity: CAPACITY,
        });
    }
    if actual < FAMILY_BYTES {
        return Err(Error::Header {
            actual,
            required: FAMILY_BYTES,
        });
    }
    let family = unsafe {
        bytes
            .add(mem::offset_of!(libc::sockaddr_storage, ss_family))
            .cast::<libc::sa_family_t>()
            .read_unaligned()
    } as libc::c_int;
    match family {
        libc::AF_INET => {
            let v = unsafe { read::<libc::sockaddr_in>(bytes, actual, family)? };
            Ok(net::SocketAddrV4::new(
                net::Ipv4Addr::from(u32::from_be(v.sin_addr.s_addr)),
                u16::from_be(v.sin_port),
            )
            .into())
        }
        libc::AF_INET6 => {
            let v = unsafe { read::<libc::sockaddr_in6>(bytes, actual, family)? };
            Ok(net::SocketAddrV6::new(
                net::Ipv6Addr::from(v.sin6_addr.s6_addr),
                u16::from_be(v.sin6_port),
                v.sin6_flowinfo,
                v.sin6_scope_id,
            )
            .into())
        }
        _ => Err(Error::Unsupported { family, actual }),
    }
}

// SAFETY: the selected native type has integer fields initialized when its complete extent fits.
unsafe fn read<T: Copy>(bytes: *const u8, actual: usize, family: i32) -> Result<T, Error> {
    let required = mem::size_of::<T>();
    if actual < required {
        return Err(Error::Address {
            family,
            actual,
            required,
        });
    }
    Ok(unsafe { bytes.cast::<T>().read_unaligned() })
}

pub(super) fn apply<S: kernel::raw::Source + ?Sized, E: From<Errno>, const CONNECT: bool>(
    file: BorrowedFd<'_>,
    address: Addr<'_>,
) -> Result<(), E> {
    let (target, len) = address.parts();
    // SAFETY: both operations borrow the entire live address and report zero or -1 with errno.
    unsafe {
        let status = if CONNECT {
            libc::connect(file.as_raw_fd(), target.cast(), len.raw())
        } else {
            libc::bind(file.as_raw_fd(), target.cast(), len.raw())
        };
        io::raw::status::<S, E>(status)
    }
}