Skip to main content

dope_sys/io/socket/
mod.rs

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