dope-sys 0.29.1

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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use std::{
    mem, net, num,
    os::fd::{AsFd, AsRawFd as _, BorrowedFd, OwnedFd},
    ptr,
};

use libc::socklen_t;
use option::fast;

use crate::{
    Cloexec, Errno, Nonblock,
    io::{self, fd},
    kernel::{self, errno},
};

pub mod accept;
pub mod addr;
pub mod gso;
pub mod msg;
pub mod option;
pub mod raw;
pub mod record;
pub mod route;

/// Exact backlog bound the host admits for one listening socket.
pub const BACKLOG: i32 = libc::SOMAXCONN;

/// Exact synchronous connect failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct Connect(Errno);

impl Connect {
    pub const fn errno(self) -> Errno {
        self.0
    }
}

impl From<Errno> for Connect {
    fn from(errno: Errno) -> Self {
        Self(errno)
    }
}

const _: () = assert!(size_of::<Connect>() == size_of::<Errno>());

/// Exact failure to create and initialize one socket descriptor.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Create {
    fault: Errno,
    kind: Option<SetupKind>,
}

/// Concrete leaf retained by one compact creation failure.
pub enum Origin {
    Socket(Errno),
    Setup(Setup),
}

impl Create {
    /// Records failure of the descriptor-creation syscall itself.
    pub const fn socket(fault: Errno) -> Self {
        Self { fault, kind: None }
    }

    /// Records the exact descriptor setup operation that failed after creation.
    pub const fn setup(error: Setup) -> Self {
        Self {
            fault: error.fault,
            kind: Some(error.kind),
        }
    }

    pub const fn origin(self) -> Origin {
        match self.kind {
            Some(kind) => Origin::Setup(Setup {
                fault: self.fault,
                kind,
            }),
            None => Origin::Socket(self.fault),
        }
    }
}

const _: () = assert!(mem::size_of::<Create>() == 2 * mem::size_of::<u32>());

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Domain {
    Inet4,
    Inet6,
    Unix,
}

impl Domain {
    pub fn for_addr(addr: &net::SocketAddr) -> Self {
        if addr.is_ipv4() {
            Self::Inet4
        } else {
            Self::Inet6
        }
    }

    pub const fn raw(self) -> libc::c_int {
        use libc::{AF_INET, AF_INET6};
        match self {
            Self::Inet4 => AF_INET,
            Self::Inet6 => AF_INET6,
            Self::Unix => libc::AF_UNIX,
        }
    }
}

/// One observed `SO_TYPE` value of an adopted descriptor.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct Type(libc::c_int);

impl Type {
    /// Whether this descriptor is one connected byte stream.
    pub const fn is_stream(self) -> bool {
        self.0 == libc::SOCK_STREAM
    }

    /// Whether this descriptor is one datagram socket.
    pub const fn is_datagram(self) -> bool {
        self.0 == libc::SOCK_DGRAM
    }

    /// Raw observed value, for exact diagnostics.
    pub const fn raw(self) -> i32 {
        self.0
    }
}

/// One half-close direction for [`Socket::shutdown`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct How(libc::c_int);

impl How {
    pub const READ: Self = Self(libc::SHUT_RD);
    pub const WRITE: Self = Self(libc::SHUT_WR);
    pub const BOTH: Self = Self(libc::SHUT_RDWR);

    pub const fn raw(self) -> libc::c_int {
        self.0
    }
}

/// One requested address reuse admitted before binding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Reuse {
    Address,
    Port,
}

/// Exact failure while opening a close-on-exec socket.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Failure {
    Socket(Errno),
    Cloexec(Cloexec),
}

impl From<Errno> for Failure {
    fn from(error: Errno) -> Self {
        Self::Socket(error)
    }
}

impl From<Cloexec> for Failure {
    fn from(error: Cloexec) -> Self {
        Self::Cloexec(error)
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Stream,
    Dgram,
}

impl Kind {
    pub const fn raw(self) -> libc::c_int {
        use libc::{SOCK_DGRAM, SOCK_STREAM};
        match self {
            Self::Stream => SOCK_STREAM,
            Self::Dgram => SOCK_DGRAM,
        }
    }
}

/// Native socket ownership and fast-open support before driver installation.
pub trait Prepare: Socket {
    type Handle: AsFd;
    type Fast;

    fn fast_open(depth: Option<num::NonZero<i32>>) -> Result<Option<Self::Fast>, fast::Error>;
    fn open(domain: Domain, kind: Kind) -> Result<Self::Handle, Create>;
    fn listener(domain: Domain) -> Result<Self::Handle, Create>;
    fn adopt(file: OwnedFd) -> Result<Self::Handle, Setup>;
    /// Transfers the prepared socket's descriptor without changing its native configuration.
    fn into_fd(handle: Self::Handle) -> OwnedFd;
    fn set_fast(file: BorrowedFd<'_>, fast: Self::Fast) -> Result<(), Errno>;
}

/// Exact socket descriptor setup failure.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Setup {
    fault: Errno,
    kind: SetupKind,
}

/// Concrete leaf retained by one compact setup failure.
pub enum SetupOrigin {
    Cloexec(Cloexec),
    Nonblock(Nonblock),
    Sigpipe(Errno),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
enum SetupKind {
    GetFd,
    SetFd,
    GetFlags,
    SetFlags,
    Sigpipe,
}

impl Setup {
    pub const fn cloexec(error: Cloexec) -> Self {
        match error {
            Cloexec::Get(fault) => Self {
                fault,
                kind: SetupKind::GetFd,
            },
            Cloexec::Set(fault) => Self {
                fault,
                kind: SetupKind::SetFd,
            },
        }
    }

    pub const fn nonblock(error: Nonblock) -> Self {
        match error {
            Nonblock::Get(fault) => Self {
                fault,
                kind: SetupKind::GetFlags,
            },
            Nonblock::Set(fault) => Self {
                fault,
                kind: SetupKind::SetFlags,
            },
        }
    }

    pub const fn sigpipe(fault: Errno) -> Self {
        Self {
            fault,
            kind: SetupKind::Sigpipe,
        }
    }

    pub const fn origin(self) -> SetupOrigin {
        match self.kind {
            SetupKind::GetFd => SetupOrigin::Cloexec(Cloexec::Get(self.fault)),
            SetupKind::SetFd => SetupOrigin::Cloexec(Cloexec::Set(self.fault)),
            SetupKind::GetFlags => SetupOrigin::Nonblock(Nonblock::Get(self.fault)),
            SetupKind::SetFlags => SetupOrigin::Nonblock(Nonblock::Set(self.fault)),
            SetupKind::Sigpipe => SetupOrigin::Sigpipe(self.fault),
        }
    }
}

const _: () = assert!(mem::size_of::<Setup>() == 2 * mem::size_of::<u32>());

/// Native socket creation and asynchronous tuning capability.
pub trait Socket: errno::Source {
    const MAX_IOVECS: usize;
    type Error;

    fn socket(domain: libc::c_int, kind: libc::c_int) -> Result<OwnedFd, Self::Error>;
    /// Creates exclusively owned local socket endpoints.
    fn pair() -> Result<(OwnedFd, OwnedFd), record::Error>;

    /// Creates one datagram descriptor without changing its descriptor flags.
    fn datagram<E: From<Errno>>(domain: Domain) -> Result<OwnedFd, E> {
        let protocol = match domain {
            Domain::Inet4 | Domain::Inet6 => libc::IPPROTO_UDP,
            Domain::Unix => 0,
        };
        Self::try_open(domain.raw(), libc::SOCK_DGRAM, protocol)
    }

    fn try_open<E: From<Errno>>(
        domain: libc::c_int,
        kind: libc::c_int,
        protocol: libc::c_int,
    ) -> Result<OwnedFd, E> {
        let raw = unsafe { libc::socket(domain, kind, protocol) };
        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
    }

    fn listen<E: From<Errno>>(file: BorrowedFd<'_>, backlog: libc::c_int) -> Result<(), E> {
        // SAFETY: listen returns exactly zero or minus one; errno is read immediately.
        unsafe {
            kernel::raw::Status::new(libc::listen(file.as_raw_fd(), backlog)).try_zero::<Self, E>()
        }
    }

    /// Half-closes one socket in the requested direction.
    fn shutdown<E: From<Errno>>(file: BorrowedFd<'_>, how: How) -> Result<(), E> {
        // SAFETY: shutdown returns exactly zero or minus one; errno is read immediately.
        unsafe {
            kernel::raw::Status::new(libc::shutdown(file.as_raw_fd(), how.raw()))
                .try_zero::<Self, E>()
        }
    }

    /// Observes the connected peer into caller-owned native address storage.
    fn peer_addr<E: From<Errno>>(
        file: BorrowedFd<'_>,
        address: &mut addr::Storage,
    ) -> Result<(), E> {
        let (storage, len) = address.output_mut();
        *len = mem::size_of_val(storage) as socklen_t;
        // SAFETY: both exclusive output borrows retain their full native extents.
        let raw =
            unsafe { libc::getpeername(file.as_raw_fd(), ptr::from_mut(storage).cast(), len) };
        // SAFETY: getpeername returns zero or -1; errno is captured immediately.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
    }

    /// Makes closing this exclusively owned connection send a reset.
    fn reset_on_close<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
        let linger = libc::linger {
            l_onoff: 1,
            l_linger: 0,
        };
        // SAFETY: the live descriptor and complete native value outlive the call.
        let raw = unsafe {
            libc::setsockopt(
                file.as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_LINGER,
                ptr::from_ref(&linger).cast(),
                mem::size_of_val(&linger) as socklen_t,
            )
        };
        // SAFETY: setsockopt returns zero or -1; errno is captured immediately.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
    }

    /// Observes the socket type of one adopted descriptor.
    fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<Type, E> {
        Self::get_option::<{ libc::SO_TYPE }, E>(file).map(Type)
    }

    /// Whether one adopted descriptor is already listening.
    fn is_listening<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<bool, E> {
        Ok(Self::get_option::<{ libc::SO_ACCEPTCONN }, E>(file)? != 0)
    }

    /// Admits the requested address reuse on one socket.
    fn set_reuse<E: From<Errno>>(file: BorrowedFd<'_>, reuse: Reuse) -> Result<(), E> {
        let option = match reuse {
            Reuse::Address => libc::SO_REUSEADDR,
            Reuse::Port => libc::SO_REUSEPORT,
        };
        Self::set_option(file, libc::SOL_SOCKET, option, &1)
    }

    /// Sends one byte string without raising the termination signal.
    fn send_quiet<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
    ) -> Result<&'a [u8], E> {
        Self::send::<{ libc::MSG_NOSIGNAL }, E>(file, input)
    }

    /// Sends without waiting or raising the termination signal.
    fn send_now<'a, E: From<Errno>>(file: BorrowedFd<'_>, input: &'a [u8]) -> Result<&'a [u8], E> {
        Self::send::<{ libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL }, E>(file, input)
    }

    fn get_option<const OPTION: libc::c_int, E: From<Errno>>(
        file: BorrowedFd<'_>,
    ) -> Result<libc::c_int, E> {
        const {
            assert!(
                OPTION == libc::SO_TYPE
                    || OPTION == libc::SO_ACCEPTCONN
                    || OPTION == libc::SO_ERROR
            );
        }
        let mut value = 0;
        let mut len = mem::size_of::<libc::c_int>() as socklen_t;
        let raw = unsafe {
            libc::getsockopt(
                file.as_raw_fd(),
                libc::SOL_SOCKET,
                OPTION,
                ptr::from_mut(&mut value).cast(),
                &mut len,
            )
        };
        // SAFETY: getsockopt returns exactly zero or minus one.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
        Ok(value)
    }

    fn set_option<E: From<Errno>>(
        file: BorrowedFd<'_>,
        level: libc::c_int,
        option: libc::c_int,
        value: &libc::c_int,
    ) -> Result<(), E> {
        let raw = unsafe {
            libc::setsockopt(
                file.as_raw_fd(),
                level,
                option,
                ptr::from_ref(value).cast(),
                mem::size_of::<libc::c_int>() as socklen_t,
            )
        };
        // SAFETY: setsockopt returns exactly zero or minus one.
        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
    }

    fn send<'a, const FLAGS: libc::c_int, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
    ) -> Result<&'a [u8], E> {
        const { assert!(FLAGS & !(libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT) == 0) };
        let raw =
            unsafe { libc::send(file.as_raw_fd(), input.as_ptr().cast(), input.len(), FLAGS) };
        // SAFETY: send returns minus one or a count within the supplied input.
        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
    }

    fn recv<'a, const FLAGS: libc::c_int, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
    ) -> Result<&'a mut [u8], E> {
        const { assert!(FLAGS & !(libc::MSG_DONTWAIT | libc::MSG_PEEK | libc::MSG_WAITALL) == 0) };
        let raw = unsafe {
            libc::recv(
                file.as_raw_fd(),
                output.as_mut_ptr().cast(),
                output.len(),
                FLAGS,
            )
        };
        // SAFETY: the admitted flags exclude MSG_TRUNC, so recv cannot report a
        // successful count beyond the supplied output capacity.
        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
    }

    fn recv_now<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
    ) -> Result<&'a mut [u8], E> {
        Self::recv::<{ libc::MSG_DONTWAIT }, E>(file, output)
    }

    /// Sends one datagram to the retained native destination.
    fn send_to<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        input: &'a [u8],
        address: addr::Addr<'_>,
    ) -> Result<&'a [u8], E> {
        let (address, len) = address.parts();
        // SAFETY: the input and admitted address retain their complete extents.
        let raw = unsafe {
            libc::sendto(
                file.as_raw_fd(),
                input.as_ptr().cast(),
                input.len(),
                libc::MSG_NOSIGNAL,
                address,
                len.raw(),
            )
        };
        // SAFETY: sendto returns -1 or a count within this exact input extent.
        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
    }

    /// Receives one datagram and its source into caller-owned storage.
    fn recv_from<'a, E: From<Errno>>(
        file: BorrowedFd<'_>,
        output: &'a mut [u8],
        address: &mut addr::Storage,
    ) -> Result<&'a mut [u8], E> {
        let (storage, len) = address.output_mut();
        *len = mem::size_of_val(storage) as socklen_t;
        // SAFETY: the exclusive output and address borrows retain their full extents.
        let raw = unsafe {
            libc::recvfrom(
                file.as_raw_fd(),
                output.as_mut_ptr().cast(),
                output.len(),
                0,
                ptr::from_mut(storage).cast(),
                len,
            )
        };
        // SAFETY: without MSG_TRUNC, recvfrom returns -1 or initializes at most output.len().
        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
    }

    fn try_pair<E: From<Errno>>(kind: libc::c_int) -> Result<(OwnedFd, OwnedFd), E> {
        let mut fds = [-1; 2];
        let raw = unsafe { libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr()) };
        // SAFETY: socketpair just returned on this thread and `fds` is its exact destination.
        unsafe { fd::raw::Pair::new(fds).try_adopt::<Self, E>(raw) }
    }
}