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 option::fast;
8
9use crate::{
10    Cloexec, Errno, Nonblock,
11    io::{self, fd},
12    kernel::errno,
13};
14
15pub mod accept;
16pub mod addr;
17pub mod gso;
18pub mod msg;
19pub mod option;
20pub mod raw;
21pub mod record;
22pub mod route;
23
24/// Exact backlog bound the host admits for one listening socket.
25pub const BACKLOG: i32 = libc::SOMAXCONN;
26
27/// Exact failure to create and initialize one socket descriptor.
28#[derive(Clone, Copy, PartialEq, Eq, Debug)]
29#[repr(C)]
30pub struct Create {
31    fault: Errno,
32    kind: Option<SetupKind>,
33}
34
35/// Concrete leaf retained by one compact creation failure.
36pub enum Origin {
37    Socket(Errno),
38    Setup(Setup),
39}
40
41impl Create {
42    /// Records failure of the descriptor-creation syscall itself.
43    pub const fn socket(fault: Errno) -> Self {
44        Self { fault, kind: None }
45    }
46
47    /// Records the exact descriptor setup operation that failed after creation.
48    pub const fn setup(error: Setup) -> Self {
49        Self {
50            fault: error.fault,
51            kind: Some(error.kind),
52        }
53    }
54
55    pub const fn origin(self) -> Origin {
56        match self.kind {
57            Some(kind) => Origin::Setup(Setup {
58                fault: self.fault,
59                kind,
60            }),
61            None => Origin::Socket(self.fault),
62        }
63    }
64}
65
66const _: () = assert!(mem::size_of::<Create>() == 2 * mem::size_of::<u32>());
67
68#[derive(Clone, Copy, PartialEq, Eq)]
69pub enum Domain {
70    Inet4,
71    Inet6,
72    Unix,
73}
74
75impl Domain {
76    pub fn for_addr(addr: &net::SocketAddr) -> Self {
77        if addr.is_ipv4() {
78            Self::Inet4
79        } else {
80            Self::Inet6
81        }
82    }
83
84    pub const fn raw(self) -> libc::c_int {
85        use libc::{AF_INET, AF_INET6};
86        match self {
87            Self::Inet4 => AF_INET,
88            Self::Inet6 => AF_INET6,
89            Self::Unix => libc::AF_UNIX,
90        }
91    }
92}
93
94/// One observed `SO_TYPE` value of an adopted descriptor.
95#[derive(Clone, Copy, Debug, Eq, PartialEq)]
96#[repr(transparent)]
97pub struct Type(libc::c_int);
98
99impl Type {
100    /// Whether this descriptor is one connected byte stream.
101    pub const fn is_stream(self) -> bool {
102        self.0 == libc::SOCK_STREAM
103    }
104
105    /// Whether this descriptor is one datagram socket.
106    pub const fn is_datagram(self) -> bool {
107        self.0 == libc::SOCK_DGRAM
108    }
109
110    /// Raw observed value, for exact diagnostics.
111    pub const fn raw(self) -> i32 {
112        self.0
113    }
114}
115
116/// One half-close direction for [`Socket::shutdown`].
117#[derive(Clone, Copy, Debug, Eq, PartialEq)]
118#[repr(transparent)]
119pub struct How(libc::c_int);
120
121impl How {
122    pub const READ: Self = Self(libc::SHUT_RD);
123    pub const WRITE: Self = Self(libc::SHUT_WR);
124    pub const BOTH: Self = Self(libc::SHUT_RDWR);
125
126    pub const fn raw(self) -> libc::c_int {
127        self.0
128    }
129}
130
131/// One requested address reuse admitted before binding.
132#[derive(Clone, Copy, Debug, Eq, PartialEq)]
133pub enum Reuse {
134    Address,
135    Port,
136}
137
138/// Exact failure while opening a close-on-exec socket.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum Failure {
141    Socket(Errno),
142    Cloexec(Cloexec),
143}
144
145impl From<Errno> for Failure {
146    fn from(error: Errno) -> Self {
147        Self::Socket(error)
148    }
149}
150
151impl From<Cloexec> for Failure {
152    fn from(error: Cloexec) -> Self {
153        Self::Cloexec(error)
154    }
155}
156
157#[derive(Clone, Copy, PartialEq, Eq)]
158pub enum Kind {
159    Stream,
160    Dgram,
161}
162
163impl Kind {
164    pub const fn raw(self) -> libc::c_int {
165        use libc::{SOCK_DGRAM, SOCK_STREAM};
166        match self {
167            Self::Stream => SOCK_STREAM,
168            Self::Dgram => SOCK_DGRAM,
169        }
170    }
171}
172
173/// Native socket ownership and fast-open support before driver installation.
174pub trait Prepare: Socket {
175    type Handle: AsFd;
176    type Fast;
177
178    fn fast_open(depth: Option<num::NonZero<i32>>) -> Result<Option<Self::Fast>, fast::Error>;
179    fn open(domain: Domain, kind: Kind) -> Result<Self::Handle, Create>;
180    fn listener(domain: Domain) -> Result<Self::Handle, Create>;
181    fn adopt(file: OwnedFd) -> Result<Self::Handle, Setup>;
182    /// Transfers the prepared socket's descriptor without changing its native configuration.
183    fn into_fd(handle: Self::Handle) -> OwnedFd;
184    fn set_fast(file: BorrowedFd<'_>, fast: Self::Fast) -> Result<(), Errno>;
185}
186
187/// Exact socket descriptor setup failure.
188#[derive(Clone, Copy, PartialEq, Eq, Debug)]
189#[repr(C)]
190pub struct Setup {
191    pub fault: Errno,
192    pub kind: SetupKind,
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196#[repr(u8)]
197pub enum SetupKind {
198    GetFd,
199    SetFd,
200    GetFlags,
201    SetFlags,
202    Sigpipe,
203}
204
205impl Setup {
206    pub const fn cloexec(error: Cloexec) -> Self {
207        match error {
208            Cloexec::Get(fault) => Self {
209                fault,
210                kind: SetupKind::GetFd,
211            },
212            Cloexec::Set(fault) => Self {
213                fault,
214                kind: SetupKind::SetFd,
215            },
216        }
217    }
218
219    pub const fn nonblock(error: Nonblock) -> Self {
220        match error {
221            Nonblock::Get(fault) => Self {
222                fault,
223                kind: SetupKind::GetFlags,
224            },
225            Nonblock::Set(fault) => Self {
226                fault,
227                kind: SetupKind::SetFlags,
228            },
229        }
230    }
231
232    pub const fn sigpipe(fault: Errno) -> Self {
233        Self {
234            fault,
235            kind: SetupKind::Sigpipe,
236        }
237    }
238}
239
240const _: () = assert!(mem::size_of::<Setup>() == 2 * mem::size_of::<u32>());
241
242/// Native socket creation and synchronous transfer.
243pub trait Socket: errno::Source {
244    const MAX_IOVECS: usize;
245    type Error;
246
247    fn socket(domain: libc::c_int, kind: libc::c_int) -> Result<OwnedFd, Self::Error>;
248    /// Creates exclusively owned local socket endpoints.
249    fn pair() -> Result<(OwnedFd, OwnedFd), record::Error>;
250
251    /// Creates one datagram descriptor without changing its descriptor flags.
252    fn datagram<E: From<Errno>>(domain: Domain) -> Result<OwnedFd, E> {
253        let protocol = match domain {
254            Domain::Inet4 | Domain::Inet6 => libc::IPPROTO_UDP,
255            Domain::Unix => 0,
256        };
257        Self::try_open(domain.raw(), libc::SOCK_DGRAM, protocol)
258    }
259
260    fn try_open<E: From<Errno>>(
261        domain: libc::c_int,
262        kind: libc::c_int,
263        protocol: libc::c_int,
264    ) -> Result<OwnedFd, E> {
265        let raw = unsafe { libc::socket(domain, kind, protocol) };
266        unsafe { <OwnedFd as fd::raw::Adopt>::try_adopt::<Self, E>(raw) }
267    }
268
269    fn listen<E: From<Errno>>(file: BorrowedFd<'_>, backlog: libc::c_int) -> Result<(), E> {
270        // SAFETY: listen returns exactly zero or minus one; errno is read immediately.
271        unsafe { io::raw::status::<Self, E>(libc::listen(file.as_raw_fd(), backlog)) }
272    }
273
274    /// Half-closes one socket in the requested direction.
275    fn shutdown<E: From<Errno>>(file: BorrowedFd<'_>, how: How) -> Result<(), E> {
276        // SAFETY: shutdown returns exactly zero or minus one; errno is read immediately.
277        unsafe { io::raw::status::<Self, E>(libc::shutdown(file.as_raw_fd(), how.raw())) }
278    }
279
280    /// Observes the connected peer into caller-owned native address storage.
281    fn peer_addr<E: From<Errno>>(
282        file: BorrowedFd<'_>,
283        address: &mut addr::Storage,
284    ) -> Result<(), E> {
285        raw::name::<Self, E, true>(file, address)
286    }
287
288    /// Sends one byte string without raising the termination signal.
289    fn send_quiet<'a, E: From<Errno>>(
290        file: BorrowedFd<'_>,
291        input: &'a [u8],
292    ) -> Result<&'a [u8], E> {
293        Self::send::<{ libc::MSG_NOSIGNAL }, E>(file, input)
294    }
295
296    /// Sends without waiting or raising the termination signal.
297    fn send_now<'a, E: From<Errno>>(file: BorrowedFd<'_>, input: &'a [u8]) -> Result<&'a [u8], E> {
298        Self::send::<{ libc::MSG_DONTWAIT | libc::MSG_NOSIGNAL }, E>(file, input)
299    }
300
301    fn send<'a, const FLAGS: libc::c_int, E: From<Errno>>(
302        file: BorrowedFd<'_>,
303        input: &'a [u8],
304    ) -> Result<&'a [u8], E> {
305        const { assert!(FLAGS & !(libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT) == 0) };
306        let raw =
307            unsafe { libc::send(file.as_raw_fd(), input.as_ptr().cast(), input.len(), FLAGS) };
308        // SAFETY: send returns minus one or a count within the supplied input.
309        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
310    }
311
312    fn recv<'a, const FLAGS: libc::c_int, E: From<Errno>>(
313        file: BorrowedFd<'_>,
314        output: &'a mut [u8],
315    ) -> Result<&'a mut [u8], E> {
316        const { assert!(FLAGS & !(libc::MSG_DONTWAIT | libc::MSG_PEEK | libc::MSG_WAITALL) == 0) };
317        let raw = unsafe {
318            libc::recv(
319                file.as_raw_fd(),
320                output.as_mut_ptr().cast(),
321                output.len(),
322                FLAGS,
323            )
324        };
325        // SAFETY: the admitted flags exclude MSG_TRUNC, so recv cannot report a
326        // successful count beyond the supplied output capacity.
327        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
328    }
329
330    fn recv_now<'a, E: From<Errno>>(
331        file: BorrowedFd<'_>,
332        output: &'a mut [u8],
333    ) -> Result<&'a mut [u8], E> {
334        Self::recv::<{ libc::MSG_DONTWAIT }, E>(file, output)
335    }
336
337    /// Sends one datagram to the retained native destination.
338    fn send_to<'a, E: From<Errno>>(
339        file: BorrowedFd<'_>,
340        input: &'a [u8],
341        address: addr::Addr<'_>,
342    ) -> Result<&'a [u8], E> {
343        let (address, len) = address.parts();
344        // SAFETY: the input and admitted address retain their complete extents.
345        let raw = unsafe {
346            libc::sendto(
347                file.as_raw_fd(),
348                input.as_ptr().cast(),
349                input.len(),
350                libc::MSG_NOSIGNAL,
351                address.cast(),
352                len.raw(),
353            )
354        };
355        // SAFETY: sendto returns -1 or a count within this exact input extent.
356        unsafe { io::raw::Buffer::try_native::<Self, E>(input, raw) }
357    }
358
359    /// Receives one datagram and its source into caller-owned storage.
360    fn recv_from<'a, E: From<Errno>>(
361        file: BorrowedFd<'_>,
362        output: &'a mut [u8],
363        address: &mut addr::Storage,
364    ) -> Result<&'a mut [u8], E> {
365        let (storage, len) = address.prepare();
366        // SAFETY: the exclusive output and address borrows retain their full extents.
367        let raw = unsafe {
368            libc::recvfrom(
369                file.as_raw_fd(),
370                output.as_mut_ptr().cast(),
371                output.len(),
372                0,
373                ptr::from_mut(storage).cast(),
374                len,
375            )
376        };
377        // SAFETY: without MSG_TRUNC, recvfrom returns -1 or initializes at most output.len().
378        unsafe { io::raw::Buffer::try_native::<Self, E>(output, raw) }
379    }
380}