Skip to main content

dope_sys/io/socket/
mod.rs

1use std::{
2    mem, net, num,
3    os::fd::{AsFd, AsRawFd as _, BorrowedFd, OwnedFd},
4    ptr,
5};
6
7use libc::socklen_t;
8use option::fast;
9
10use crate::{
11    Cloexec, Errno, Nonblock,
12    io::{self, fd},
13    kernel::{self, errno},
14};
15
16pub mod accept;
17pub mod addr;
18pub mod gso;
19pub mod msg;
20pub mod option;
21pub mod raw;
22pub mod record;
23pub mod route;
24
25/// Exact backlog bound the host admits for one listening socket.
26pub const BACKLOG: i32 = libc::SOMAXCONN;
27
28/// Exact synchronous connect failure.
29#[derive(Clone, Copy, Debug, Eq, PartialEq)]
30#[repr(transparent)]
31pub struct Connect(Errno);
32
33impl Connect {
34    pub const fn errno(self) -> Errno {
35        self.0
36    }
37}
38
39impl From<Errno> for Connect {
40    fn from(errno: Errno) -> Self {
41        Self(errno)
42    }
43}
44
45const _: () = assert!(size_of::<Connect>() == size_of::<Errno>());
46
47/// Exact failure to create and initialize one socket descriptor.
48#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49#[repr(C)]
50pub struct Create {
51    fault: Errno,
52    kind: Option<SetupKind>,
53}
54
55/// Concrete leaf retained by one compact creation failure.
56pub enum Origin {
57    Socket(Errno),
58    Setup(Setup),
59}
60
61impl Create {
62    /// Records failure of the descriptor-creation syscall itself.
63    pub const fn socket(fault: Errno) -> Self {
64        Self { fault, kind: None }
65    }
66
67    /// Records the exact descriptor setup operation that failed after creation.
68    pub const fn setup(error: Setup) -> Self {
69        Self {
70            fault: error.fault,
71            kind: Some(error.kind),
72        }
73    }
74
75    pub const fn origin(self) -> Origin {
76        match self.kind {
77            Some(kind) => Origin::Setup(Setup {
78                fault: self.fault,
79                kind,
80            }),
81            None => Origin::Socket(self.fault),
82        }
83    }
84}
85
86const _: () = assert!(mem::size_of::<Create>() == 2 * mem::size_of::<u32>());
87
88#[derive(Clone, Copy, PartialEq, Eq)]
89pub enum Domain {
90    Inet4,
91    Inet6,
92    Unix,
93}
94
95impl Domain {
96    pub fn for_addr(addr: &net::SocketAddr) -> Self {
97        if addr.is_ipv4() {
98            Self::Inet4
99        } else {
100            Self::Inet6
101        }
102    }
103
104    pub const fn raw(self) -> libc::c_int {
105        use libc::{AF_INET, AF_INET6};
106        match self {
107            Self::Inet4 => AF_INET,
108            Self::Inet6 => AF_INET6,
109            Self::Unix => libc::AF_UNIX,
110        }
111    }
112}
113
114/// One observed `SO_TYPE` value of an adopted descriptor.
115#[derive(Clone, Copy, Debug, Eq, PartialEq)]
116#[repr(transparent)]
117pub struct Type(libc::c_int);
118
119impl Type {
120    /// Whether this descriptor is one connected byte stream.
121    pub const fn is_stream(self) -> bool {
122        self.0 == libc::SOCK_STREAM
123    }
124
125    /// Whether this descriptor is one datagram socket.
126    pub const fn is_datagram(self) -> bool {
127        self.0 == libc::SOCK_DGRAM
128    }
129
130    /// Raw observed value, for exact diagnostics.
131    pub const fn raw(self) -> i32 {
132        self.0
133    }
134}
135
136/// One half-close direction for [`Socket::shutdown`].
137#[derive(Clone, Copy, Debug, Eq, PartialEq)]
138#[repr(transparent)]
139pub struct How(libc::c_int);
140
141impl How {
142    pub const READ: Self = Self(libc::SHUT_RD);
143    pub const WRITE: Self = Self(libc::SHUT_WR);
144    pub const BOTH: Self = Self(libc::SHUT_RDWR);
145
146    pub const fn raw(self) -> libc::c_int {
147        self.0
148    }
149}
150
151/// One requested address reuse admitted before binding.
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub enum Reuse {
154    Address,
155    Port,
156}
157
158/// Exact failure while opening a close-on-exec socket.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum Failure {
161    Socket(Errno),
162    Cloexec(Cloexec),
163}
164
165impl From<Errno> for Failure {
166    fn from(error: Errno) -> Self {
167        Self::Socket(error)
168    }
169}
170
171impl From<Cloexec> for Failure {
172    fn from(error: Cloexec) -> Self {
173        Self::Cloexec(error)
174    }
175}
176
177#[derive(Clone, Copy, PartialEq, Eq)]
178pub enum Kind {
179    Stream,
180    Dgram,
181}
182
183impl Kind {
184    pub const fn raw(self) -> libc::c_int {
185        use libc::{SOCK_DGRAM, SOCK_STREAM};
186        match self {
187            Self::Stream => SOCK_STREAM,
188            Self::Dgram => SOCK_DGRAM,
189        }
190    }
191}
192
193/// Native socket ownership and fast-open support before driver installation.
194pub trait Prepare: Socket {
195    type Handle: AsFd;
196    type Fast;
197
198    fn fast_open(depth: Option<num::NonZero<i32>>) -> Result<Option<Self::Fast>, fast::Error>;
199    fn open(domain: Domain, kind: Kind) -> Result<Self::Handle, Create>;
200    fn listener(domain: Domain) -> Result<Self::Handle, Create>;
201    fn adopt(file: OwnedFd) -> Result<Self::Handle, Setup>;
202    /// Transfers the prepared socket's descriptor without changing its native configuration.
203    fn into_fd(handle: Self::Handle) -> OwnedFd;
204    fn set_fast(file: BorrowedFd<'_>, fast: Self::Fast) -> Result<(), Errno>;
205}
206
207/// Exact socket descriptor setup failure.
208#[derive(Clone, Copy, PartialEq, Eq, Debug)]
209#[repr(C)]
210pub struct Setup {
211    fault: Errno,
212    kind: SetupKind,
213}
214
215/// Concrete leaf retained by one compact setup failure.
216pub enum SetupOrigin {
217    Cloexec(Cloexec),
218    Nonblock(Nonblock),
219    Sigpipe(Errno),
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223#[repr(u8)]
224enum SetupKind {
225    GetFd,
226    SetFd,
227    GetFlags,
228    SetFlags,
229    Sigpipe,
230}
231
232impl Setup {
233    pub const fn cloexec(error: Cloexec) -> Self {
234        match error {
235            Cloexec::Get(fault) => Self {
236                fault,
237                kind: SetupKind::GetFd,
238            },
239            Cloexec::Set(fault) => Self {
240                fault,
241                kind: SetupKind::SetFd,
242            },
243        }
244    }
245
246    pub const fn nonblock(error: Nonblock) -> Self {
247        match error {
248            Nonblock::Get(fault) => Self {
249                fault,
250                kind: SetupKind::GetFlags,
251            },
252            Nonblock::Set(fault) => Self {
253                fault,
254                kind: SetupKind::SetFlags,
255            },
256        }
257    }
258
259    pub const fn sigpipe(fault: Errno) -> Self {
260        Self {
261            fault,
262            kind: SetupKind::Sigpipe,
263        }
264    }
265
266    pub const fn origin(self) -> SetupOrigin {
267        match self.kind {
268            SetupKind::GetFd => SetupOrigin::Cloexec(Cloexec::Get(self.fault)),
269            SetupKind::SetFd => SetupOrigin::Cloexec(Cloexec::Set(self.fault)),
270            SetupKind::GetFlags => SetupOrigin::Nonblock(Nonblock::Get(self.fault)),
271            SetupKind::SetFlags => SetupOrigin::Nonblock(Nonblock::Set(self.fault)),
272            SetupKind::Sigpipe => SetupOrigin::Sigpipe(self.fault),
273        }
274    }
275}
276
277const _: () = assert!(mem::size_of::<Setup>() == 2 * mem::size_of::<u32>());
278
279/// Native socket creation and asynchronous tuning capability.
280pub trait Socket: errno::Source {
281    const MAX_IOVECS: usize;
282    type Error;
283
284    fn socket(domain: libc::c_int, kind: libc::c_int) -> Result<OwnedFd, Self::Error>;
285    /// Creates exclusively owned local socket endpoints.
286    fn pair() -> Result<(OwnedFd, OwnedFd), record::Error>;
287
288    /// Creates one datagram descriptor without changing its descriptor flags.
289    fn datagram<E: From<Errno>>(domain: Domain) -> Result<OwnedFd, E> {
290        let protocol = match domain {
291            Domain::Inet4 | Domain::Inet6 => libc::IPPROTO_UDP,
292            Domain::Unix => 0,
293        };
294        Self::try_open(domain.raw(), libc::SOCK_DGRAM, protocol)
295    }
296
297    fn try_open<E: From<Errno>>(
298        domain: libc::c_int,
299        kind: libc::c_int,
300        protocol: libc::c_int,
301    ) -> Result<OwnedFd, E> {
302        let raw = unsafe { libc::socket(domain, kind, protocol) };
303        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
304    }
305
306    fn listen<E: From<Errno>>(file: BorrowedFd<'_>, backlog: libc::c_int) -> Result<(), E> {
307        // SAFETY: listen returns exactly zero or minus one; errno is read immediately.
308        unsafe {
309            kernel::raw::Status::new(libc::listen(file.as_raw_fd(), backlog)).try_zero::<Self, E>()
310        }
311    }
312
313    /// Half-closes one socket in the requested direction.
314    fn shutdown<E: From<Errno>>(file: BorrowedFd<'_>, how: How) -> Result<(), E> {
315        // SAFETY: shutdown returns exactly zero or minus one; errno is read immediately.
316        unsafe {
317            kernel::raw::Status::new(libc::shutdown(file.as_raw_fd(), how.raw()))
318                .try_zero::<Self, E>()
319        }
320    }
321
322    /// Observes the connected peer into caller-owned native address storage.
323    fn peer_addr<E: From<Errno>>(
324        file: BorrowedFd<'_>,
325        address: &mut addr::Storage,
326    ) -> Result<(), E> {
327        let (storage, len) = address.output_mut();
328        *len = mem::size_of_val(storage) as socklen_t;
329        // SAFETY: both exclusive output borrows retain their full native extents.
330        let raw =
331            unsafe { libc::getpeername(file.as_raw_fd(), ptr::from_mut(storage).cast(), len) };
332        // SAFETY: getpeername returns zero or -1; errno is captured immediately.
333        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
334    }
335
336    /// Makes closing this exclusively owned connection send a reset.
337    fn reset_on_close<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<(), E> {
338        let linger = libc::linger {
339            l_onoff: 1,
340            l_linger: 0,
341        };
342        // SAFETY: the live descriptor and complete native value outlive the call.
343        let raw = unsafe {
344            libc::setsockopt(
345                file.as_raw_fd(),
346                libc::SOL_SOCKET,
347                libc::SO_LINGER,
348                ptr::from_ref(&linger).cast(),
349                mem::size_of_val(&linger) as socklen_t,
350            )
351        };
352        // SAFETY: setsockopt returns zero or -1; errno is captured immediately.
353        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
354    }
355
356    /// Observes the socket type of one adopted descriptor.
357    fn kind<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<Type, E> {
358        Self::get_option::<{ libc::SO_TYPE }, E>(file).map(Type)
359    }
360
361    /// Whether one adopted descriptor is already listening.
362    fn is_listening<E: From<Errno>>(file: BorrowedFd<'_>) -> Result<bool, E> {
363        Ok(Self::get_option::<{ libc::SO_ACCEPTCONN }, E>(file)? != 0)
364    }
365
366    /// Admits the requested address reuse on one socket.
367    fn set_reuse<E: From<Errno>>(file: BorrowedFd<'_>, reuse: Reuse) -> Result<(), E> {
368        let option = match reuse {
369            Reuse::Address => libc::SO_REUSEADDR,
370            Reuse::Port => libc::SO_REUSEPORT,
371        };
372        Self::set_option(file, libc::SOL_SOCKET, option, &1)
373    }
374
375    /// Sends one byte string without raising the termination signal.
376    fn send_quiet<'a, E: From<Errno>>(
377        file: BorrowedFd<'_>,
378        input: &'a [u8],
379    ) -> Result<&'a [u8], E> {
380        Self::send::<{ libc::MSG_NOSIGNAL }, E>(file, input)
381    }
382
383    /// Sends without waiting or raising the termination signal.
384    fn send_now<'a, E: From<Errno>>(file: BorrowedFd<'_>, input: &'a [u8]) -> Result<&'a [u8], E> {
385        Self::send::<{ libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL }, E>(file, input)
386    }
387
388    fn get_option<const OPTION: libc::c_int, E: From<Errno>>(
389        file: BorrowedFd<'_>,
390    ) -> Result<libc::c_int, E> {
391        const {
392            assert!(
393                OPTION == libc::SO_TYPE
394                    || OPTION == libc::SO_ACCEPTCONN
395                    || OPTION == libc::SO_ERROR
396            );
397        }
398        let mut value = 0;
399        let mut len = mem::size_of::<libc::c_int>() as socklen_t;
400        let raw = unsafe {
401            libc::getsockopt(
402                file.as_raw_fd(),
403                libc::SOL_SOCKET,
404                OPTION,
405                ptr::from_mut(&mut value).cast(),
406                &mut len,
407            )
408        };
409        // SAFETY: getsockopt returns exactly zero or minus one.
410        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }?;
411        Ok(value)
412    }
413
414    fn set_option<E: From<Errno>>(
415        file: BorrowedFd<'_>,
416        level: libc::c_int,
417        option: libc::c_int,
418        value: &libc::c_int,
419    ) -> Result<(), E> {
420        let raw = unsafe {
421            libc::setsockopt(
422                file.as_raw_fd(),
423                level,
424                option,
425                ptr::from_ref(value).cast(),
426                mem::size_of::<libc::c_int>() as socklen_t,
427            )
428        };
429        // SAFETY: setsockopt returns exactly zero or minus one.
430        unsafe { kernel::raw::Status::new(raw).try_zero::<Self, E>() }
431    }
432
433    fn send<'a, const FLAGS: libc::c_int, E: From<Errno>>(
434        file: BorrowedFd<'_>,
435        input: &'a [u8],
436    ) -> Result<&'a [u8], E> {
437        const { assert!(FLAGS & !(libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT) == 0) };
438        let raw =
439            unsafe { libc::send(file.as_raw_fd(), input.as_ptr().cast(), input.len(), FLAGS) };
440        // SAFETY: send returns minus one or a count within the supplied input.
441        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
442    }
443
444    fn recv<'a, const FLAGS: libc::c_int, E: From<Errno>>(
445        file: BorrowedFd<'_>,
446        output: &'a mut [u8],
447    ) -> Result<&'a mut [u8], E> {
448        const { assert!(FLAGS & !(libc::MSG_DONTWAIT | libc::MSG_PEEK | libc::MSG_WAITALL) == 0) };
449        let raw = unsafe {
450            libc::recv(
451                file.as_raw_fd(),
452                output.as_mut_ptr().cast(),
453                output.len(),
454                FLAGS,
455            )
456        };
457        // SAFETY: the admitted flags exclude MSG_TRUNC, so recv cannot report a
458        // successful count beyond the supplied output capacity.
459        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
460    }
461
462    fn recv_now<'a, E: From<Errno>>(
463        file: BorrowedFd<'_>,
464        output: &'a mut [u8],
465    ) -> Result<&'a mut [u8], E> {
466        Self::recv::<{ libc::MSG_DONTWAIT }, E>(file, output)
467    }
468
469    /// Sends one datagram to the retained native destination.
470    fn send_to<'a, E: From<Errno>>(
471        file: BorrowedFd<'_>,
472        input: &'a [u8],
473        address: addr::Addr<'_>,
474    ) -> Result<&'a [u8], E> {
475        let (address, len) = address.parts();
476        // SAFETY: the input and admitted address retain their complete extents.
477        let raw = unsafe {
478            libc::sendto(
479                file.as_raw_fd(),
480                input.as_ptr().cast(),
481                input.len(),
482                libc::MSG_NOSIGNAL,
483                address,
484                len.raw(),
485            )
486        };
487        // SAFETY: sendto returns -1 or a count within this exact input extent.
488        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
489    }
490
491    /// Receives one datagram and its source into caller-owned storage.
492    fn recv_from<'a, E: From<Errno>>(
493        file: BorrowedFd<'_>,
494        output: &'a mut [u8],
495        address: &mut addr::Storage,
496    ) -> Result<&'a mut [u8], E> {
497        let (storage, len) = address.output_mut();
498        *len = mem::size_of_val(storage) as socklen_t;
499        // SAFETY: the exclusive output and address borrows retain their full extents.
500        let raw = unsafe {
501            libc::recvfrom(
502                file.as_raw_fd(),
503                output.as_mut_ptr().cast(),
504                output.len(),
505                0,
506                ptr::from_mut(storage).cast(),
507                len,
508            )
509        };
510        // SAFETY: without MSG_TRUNC, recvfrom returns -1 or initializes at most output.len().
511        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
512    }
513
514    fn try_pair<E: From<Errno>>(kind: libc::c_int) -> Result<(OwnedFd, OwnedFd), E> {
515        let mut fds = [-1; 2];
516        let raw = unsafe { libc::socketpair(libc::AF_UNIX, kind, 0, fds.as_mut_ptr()) };
517        // SAFETY: socketpair just returned on this thread and `fds` is its exact destination.
518        unsafe { fd::raw::Pair::new(fds).try_adopt::<Self, E>(raw) }
519    }
520}