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
use core::time::Duration;
use ax_errno::{AxError, AxResult, LinuxError};
use enum_dispatch::enum_dispatch;
macro_rules! define_options {
($($name:ident($value:ty),)*) => {
/// Operation to get a socket option.
///
/// See [`Configurable::get_option`].
#[allow(missing_docs)]
pub enum GetSocketOption<'a> {
$(
$name(&'a mut $value),
)*
}
/// Operation to set a socket option.
///
/// See [`Configurable::set_option`].
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum SetSocketOption<'a> {
$(
$name(&'a $value),
)*
}
};
}
/// Corresponds to `struct ucred` in Linux.
#[repr(C)]
#[derive(Default, Debug, Clone)]
pub struct UnixCredentials {
/// Process ID.
pub pid: u32,
/// User ID.
pub uid: u32,
/// Group ID.
pub gid: u32,
}
impl UnixCredentials {
/// Create a new `UnixCredentials` with the given PID and default UID/GID.
pub fn new(pid: u32) -> Self {
UnixCredentials {
pid,
uid: 0,
gid: 0,
}
}
}
define_options! {
// ---- Socket level options (SO_*) ----
ReuseAddress(bool),
Error(i32),
DontRoute(bool),
SendBuffer(usize),
ReceiveBuffer(usize),
KeepAlive(bool),
SendTimeout(Duration),
ReceiveTimeout(Duration),
SendBufferForce(usize),
PassCredentials(bool),
PeerCredentials(UnixCredentials),
// --- TCP level options (TCP_*) ----
NoDelay(bool),
MaxSegment(usize),
TcpInfo(()),
// ---- IP level options (IP_*) ----
Ttl(u8),
// ---- Extra options ----
NonBlocking(bool),
}
/// Trait for configurable socket-like objects.
#[enum_dispatch]
pub trait Configurable {
/// Get a socket option, returns `true` if the socket supports the option.
fn get_option_inner(&self, opt: &mut GetSocketOption) -> AxResult<bool>;
/// Set a socket option, returns `true` if the socket supports the option.
fn set_option_inner(&self, opt: SetSocketOption) -> AxResult<bool>;
/// Get a socket option. Dispatches to [`Configurable::get_option_inner`].
fn get_option(&self, mut opt: GetSocketOption) -> AxResult {
self.get_option_inner(&mut opt).and_then(|supported| {
if !supported {
Err(AxError::from(LinuxError::ENOPROTOOPT))
} else {
Ok(())
}
})
}
/// Set a socket option. Dispatches to [`Configurable::set_option_inner`].
fn set_option(&self, opt: SetSocketOption) -> AxResult {
self.set_option_inner(opt).and_then(|supported| {
if !supported {
Err(AxError::from(LinuxError::ENOPROTOOPT))
} else {
Ok(())
}
})
}
}