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
use super::listener;
use anyhow::{Context, Result};
use listener::Listen;
use listener::{Connection, ConnectionMetadata};
use log::{error, warn};
use std::fs;
use std::fs::Permissions;
use std::io::{Error, ErrorKind};
use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::io::FromRawFd;
use std::os::unix::net::UnixListener;
use std::path::PathBuf;
use std::time::Duration;
static DEFAULT_SOCKET_PATH: &str = "/run/parsec/parsec.sock";
#[derive(Debug)]
pub struct DomainSocketListener {
listener: UnixListener,
timeout: Duration,
}
impl DomainSocketListener {
pub fn new(timeout: Duration, socket_path: PathBuf) -> Result<Self> {
let listener = match sd_notify::listen_fds()? {
0 => {
if socket_path.exists() {
let meta = fs::metadata(&socket_path)?;
if meta.file_type().is_socket() {
warn!(
"Removing the existing socket file at {}.",
socket_path.display()
);
fs::remove_file(&socket_path)?;
} else {
error!(
"A file exists at {} but is not a Unix Domain Socket.",
socket_path.display()
);
}
}
let listener = UnixListener::bind(&socket_path).with_context(|| {
format!("Failed to bind to Unix socket at {:?}", socket_path)
})?;
listener.set_nonblocking(true)?;
let permissions = Permissions::from_mode(0o666);
fs::set_permissions(socket_path, permissions)?;
listener
}
1 => {
let nfd = sd_notify::SD_LISTEN_FDS_START;
unsafe { UnixListener::from_raw_fd(nfd) }
}
n => {
error!(
"Received too many file descriptors ({} received, 0 or 1 expected).",
n
);
return Err(Error::new(
ErrorKind::InvalidData,
"too many file descriptors received",
)
.into());
}
};
Ok(Self { listener, timeout })
}
}
impl Listen for DomainSocketListener {
fn set_timeout(&mut self, duration: Duration) {
self.timeout = duration;
}
fn accept(&self) -> Option<Connection> {
let stream_result = self.listener.accept();
match stream_result {
Ok((stream, _)) => {
if let Err(err) = stream.set_read_timeout(Some(self.timeout)) {
format_error!("Failed to set read timeout", err);
None
} else if let Err(err) = stream.set_write_timeout(Some(self.timeout)) {
format_error!("Failed to set write timeout", err);
None
} else if let Err(err) = stream.set_nonblocking(false) {
format_error!("Failed to set stream as blocking", err);
None
} else {
let ucred = peer_credentials::peer_cred(&stream)
.map_err(|err| {
format_error!(
"Failed to grab peer credentials metadata from UnixStream",
err
);
err
})
.ok()?;
Some(Connection {
stream: Box::new(stream),
metadata: Some(ConnectionMetadata::UnixPeerCredentials {
uid: ucred.uid,
gid: ucred.gid,
pid: ucred.pid,
}),
})
}
}
Err(err) => {
if err.kind() != ErrorKind::WouldBlock {
format_error!("Failed to connect with a UnixStream", err);
}
None
}
}
}
}
#[derive(Clone, Debug, Default)]
pub struct DomainSocketListenerBuilder {
timeout: Option<Duration>,
socket_path: Option<PathBuf>,
}
impl DomainSocketListenerBuilder {
pub fn new() -> Self {
DomainSocketListenerBuilder {
timeout: None,
socket_path: None,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn with_socket_path(mut self, socket_path: Option<PathBuf>) -> Self {
self.socket_path = socket_path;
self
}
pub fn build(self) -> Result<DomainSocketListener> {
DomainSocketListener::new(
self.timeout.ok_or_else(|| {
error!("The listener timeout was not set.");
Error::new(ErrorKind::InvalidInput, "listener timeout missing")
})?,
self.socket_path
.unwrap_or_else(|| DEFAULT_SOCKET_PATH.into()),
)
}
}
pub mod peer_credentials {
use libc::{gid_t, pid_t, uid_t};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct UCred {
pub uid: uid_t,
pub gid: gid_t,
pub pid: Option<pid_t>,
}
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use self::impl_linux::peer_cred;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
target_os = "macos",
target_os = "openbsd"
))]
pub use self::impl_bsd::peer_cred;
#[cfg(any(target_os = "linux", target_os = "android"))]
#[allow(missing_docs, trivial_casts)]
pub mod impl_linux {
use super::UCred;
use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED};
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixStream;
use std::{io, mem};
pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
let ucred_size = mem::size_of::<ucred>();
assert!(mem::size_of::<u32>() <= mem::size_of::<usize>());
assert!(ucred_size <= u32::MAX as usize);
let mut ucred_size = ucred_size as socklen_t;
let mut ucred: ucred = ucred {
pid: 1,
uid: 1,
gid: 1,
};
unsafe {
let ret = getsockopt(
socket.as_raw_fd(),
SOL_SOCKET,
SO_PEERCRED,
&mut ucred as *mut ucred as *mut c_void,
&mut ucred_size,
);
if ret == 0 && ucred_size as usize == mem::size_of::<ucred>() {
Ok(UCred {
uid: ucred.uid,
gid: ucred.gid,
pid: Some(ucred.pid),
})
} else {
Err(io::Error::last_os_error())
}
}
}
}
#[cfg(any(
target_os = "dragonfly",
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd"
))]
#[allow(missing_docs)]
pub mod impl_bsd {
use super::UCred;
use std::io;
use std::os::unix::io::AsRawFd;
use std::os::unix::net::UnixStream;
pub fn peer_cred(socket: &UnixStream) -> io::Result<UCred> {
let mut cred = UCred {
uid: 1,
gid: 1,
pid: None,
};
unsafe {
let ret = libc::getpeereid(socket.as_raw_fd(), &mut cred.uid, &mut cred.gid);
if ret == 0 {
Ok(cred)
} else {
Err(io::Error::last_os_error())
}
}
}
}
}