1#![allow(unsafe_code)]
20
21use std::io::{self, Read};
22use std::mem::{size_of, zeroed};
23use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
24use std::os::unix::net::UnixStream;
25use std::path::{Path, PathBuf};
26use std::process::{Child, Command, Stdio};
27use std::sync::{Mutex, OnceLock, PoisonError};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum Kind {
33 Datagram = 1,
35 Raw = 2,
37 Launch = 3,
48}
49
50impl Kind {
51 fn from_octet(octet: u8) -> Option<Self> {
52 match octet {
53 1 => Some(Self::Datagram),
54 2 => Some(Self::Raw),
55 3 => Some(Self::Launch),
56 _ => None,
57 }
58 }
59
60 fn socket_type(self) -> libc::c_int {
61 match self {
62 Self::Datagram => libc::SOCK_DGRAM,
63 Self::Raw | Self::Launch => libc::SOCK_RAW,
64 }
65 }
66}
67
68fn make(kind: Kind) -> io::Result<OwnedFd> {
72 let fd = packet_socket(kind)?;
73 if kind == Kind::Launch {
74 launch_on_tai(&fd)?;
75 }
76 Ok(fd)
77}
78
79fn packet_socket(kind: Kind) -> io::Result<OwnedFd> {
81 let raw = unsafe { libc::socket(libc::AF_PACKET, kind.socket_type() | libc::SOCK_CLOEXEC, 0) };
83 if raw < 0 {
84 return Err(io::Error::last_os_error());
85 }
86 Ok(unsafe { OwnedFd::from_raw_fd(raw) })
88}
89
90fn launch_on_tai(fd: &OwnedFd) -> io::Result<()> {
94 let timing = libc::sock_txtime {
95 clockid: libc::CLOCK_TAI,
96 flags: libc::SOF_TXTIME_REPORT_ERRORS,
97 };
98 let set = unsafe {
101 libc::setsockopt(
102 fd.as_raw_fd(),
103 libc::SOL_SOCKET,
104 libc::SO_TXTIME,
105 (&raw const timing).cast(),
106 size_of::<libc::sock_txtime>() as libc::socklen_t,
107 )
108 };
109 if set < 0 {
110 return Err(io::Error::last_os_error());
111 }
112 Ok(())
113}
114
115fn launch_capability(program: Option<&Path>) -> io::Error {
118 let grant = match program {
119 Some(program) => format!(
120 "; grant it with: sudo setcap cap_net_raw,cap_net_admin+ep {}",
121 program.display()
122 ),
123 None => String::new(),
124 };
125 io::Error::new(
126 io::ErrorKind::PermissionDenied,
127 format!("launch times on CLOCK_TAI need CAP_NET_ADMIN as well as CAP_NET_RAW{grant}"),
128 )
129}
130
131struct Installed {
133 broker: Mutex<Broker>,
134 program: PathBuf,
135}
136
137static INSTALLED: OnceLock<Installed> = OnceLock::new();
138
139static FOUND: Mutex<Option<PathBuf>> = Mutex::new(None);
142
143pub fn open(kind: Kind) -> io::Result<OwnedFd> {
150 let result = match INSTALLED.get() {
151 Some(installed) => {
152 let made = installed
153 .broker
154 .lock()
155 .unwrap_or_else(PoisonError::into_inner)
156 .socket(kind);
157 match made {
158 Err(error) if kind == Kind::Launch && error.raw_os_error() == Some(libc::EPERM) => {
161 return Err(launch_capability(Some(&installed.program)));
162 }
163 made => made,
164 }
165 }
166 None => match packet_socket(kind) {
167 Ok(fd) if kind == Kind::Launch => match launch_on_tai(&fd) {
168 Ok(()) => Ok(fd),
169 Err(error) if error.raw_os_error() == Some(libc::EPERM) => {
170 let program = std::env::current_exe().ok();
171 return Err(launch_capability(program.as_deref()));
172 }
173 Err(error) => Err(error),
174 },
175 made => made,
176 },
177 };
178 result.map_err(|error| match error.raw_os_error() {
179 Some(libc::EPERM | libc::EACCES) => crate::socket::raw_capability(),
180 _ => error,
181 })
182}
183
184pub fn needs_capability() -> Option<PathBuf> {
188 INSTALLED
189 .get()
190 .map(|installed| installed.program.clone())
191 .or_else(|| FOUND.lock().unwrap_or_else(PoisonError::into_inner).clone())
192 .or_else(|| std::env::current_exe().ok())
193}
194
195pub fn install(broker: Broker) {
199 let program = broker.program.clone();
200 let _ = INSTALLED.set(Installed {
201 broker: Mutex::new(broker),
202 program,
203 });
204}
205
206pub fn installed() -> bool {
208 INSTALLED.get().is_some()
209}
210
211pub fn use_helper(name: &str, folders: &[&Path]) -> io::Result<()> {
217 static STARTING: Mutex<()> = Mutex::new(());
218 let _one_at_a_time = STARTING.lock().unwrap_or_else(PoisonError::into_inner);
219 if installed() {
220 return Ok(());
221 }
222 let program = find(name, folders).ok_or_else(|| {
223 io::Error::new(
224 io::ErrorKind::NotFound,
225 format!("the raw Ethernet helper, {name}, is not installed beside this program"),
226 )
227 })?;
228 *FOUND.lock().unwrap_or_else(PoisonError::into_inner) = Some(program.clone());
229 install(Broker::start(&program)?);
230 Ok(())
231}
232
233fn find(name: &str, folders: &[&Path]) -> Option<PathBuf> {
235 let beside = std::env::current_exe()
236 .ok()
237 .and_then(|program| program.parent().map(Path::to_path_buf));
238 let mut places = Vec::new();
239 if let Some(folder) = beside {
240 places.push(folder.join(name));
241 if let Some(parent) = folder.parent() {
242 places.push(parent.join(name));
243 }
244 }
245 places.extend(folders.iter().map(|folder| folder.join(name)));
246 places.into_iter().find(|place| place.is_file())
247}
248
249pub struct Broker {
251 stream: UnixStream,
252 child: Child,
253 program: PathBuf,
254}
255
256impl Broker {
257 pub fn start(program: &Path) -> io::Result<Self> {
261 let (ours, theirs) = UnixStream::pair()?;
262 let child = Command::new(program)
263 .stdin(Stdio::from(OwnedFd::from(theirs)))
264 .stdout(Stdio::null())
265 .spawn()?;
266 let mut broker = Self {
267 stream: ours,
268 child,
269 program: program.to_owned(),
270 };
271 match broker.socket(Kind::Datagram) {
272 Ok(_) => Ok(broker),
273 Err(error) if matches!(error.raw_os_error(), Some(libc::EPERM | libc::EACCES)) => {
274 let program = program.display();
275 Err(io::Error::new(
276 io::ErrorKind::PermissionDenied,
277 format!(
278 "raw Ethernet needs CAP_NET_RAW on the helper; grant it with: sudo \
279 setcap cap_net_raw+ep {program}"
280 ),
281 ))
282 }
283 Err(error) => Err(error),
284 }
285 }
286
287 fn socket(&mut self, kind: Kind) -> io::Result<OwnedFd> {
289 use std::io::Write;
290 self.stream.write_all(&[kind as u8])?;
291 let (status, fd) = receive(self.stream.as_raw_fd())?;
292 match (status, fd) {
293 (0, Some(fd)) => Ok(fd),
294 (0, None) => Err(io::Error::other("the helper sent no socket")),
295 (errno, _) => Err(io::Error::from_raw_os_error(errno)),
296 }
297 }
298}
299
300impl Drop for Broker {
301 fn drop(&mut self) {
302 let _ = self.stream.shutdown(std::net::Shutdown::Both);
304 let _ = self.child.wait();
305 }
306}
307
308fn control_room() -> usize {
310 unsafe { libc::CMSG_SPACE(size_of::<RawFd>() as u32) as usize }
312}
313
314fn send(socket: RawFd, status: i32, fd: Option<RawFd>) -> io::Result<()> {
316 let mut data = status.to_ne_bytes();
317 let mut iov = libc::iovec {
318 iov_base: data.as_mut_ptr().cast(),
319 iov_len: data.len(),
320 };
321 let mut control = vec![0u8; control_room()];
322 let mut message: libc::msghdr = unsafe { zeroed() };
324 message.msg_iov = &raw mut iov;
325 message.msg_iovlen = 1;
326 if let Some(fd) = fd {
327 message.msg_control = control.as_mut_ptr().cast();
328 message.msg_controllen = control.len() as _;
329 unsafe {
332 let header = libc::CMSG_FIRSTHDR(&raw const message);
333 (*header).cmsg_level = libc::SOL_SOCKET;
334 (*header).cmsg_type = libc::SCM_RIGHTS;
335 (*header).cmsg_len = libc::CMSG_LEN(size_of::<RawFd>() as u32) as _;
336 libc::CMSG_DATA(header).cast::<RawFd>().write_unaligned(fd);
337 }
338 }
339 if unsafe { libc::sendmsg(socket, &raw const message, 0) } < 0 {
341 return Err(io::Error::last_os_error());
342 }
343 Ok(())
344}
345
346fn receive(socket: RawFd) -> io::Result<(i32, Option<OwnedFd>)> {
348 let mut data = [0u8; 4];
349 let mut iov = libc::iovec {
350 iov_base: data.as_mut_ptr().cast(),
351 iov_len: data.len(),
352 };
353 let mut control = vec![0u8; control_room()];
354 let mut message: libc::msghdr = unsafe { zeroed() };
356 message.msg_iov = &raw mut iov;
357 message.msg_iovlen = 1;
358 message.msg_control = control.as_mut_ptr().cast();
359 message.msg_controllen = control.len() as _;
360 let read = unsafe { libc::recvmsg(socket, &raw mut message, libc::MSG_CMSG_CLOEXEC) };
362 if read < 0 {
363 return Err(io::Error::last_os_error());
364 }
365 if read as usize != data.len() {
366 return Err(io::Error::new(
367 io::ErrorKind::UnexpectedEof,
368 "the helper stopped",
369 ));
370 }
371 let mut fd = None;
372 unsafe {
375 let mut header = libc::CMSG_FIRSTHDR(&raw const message);
376 while !header.is_null() {
377 if (*header).cmsg_level == libc::SOL_SOCKET && (*header).cmsg_type == libc::SCM_RIGHTS {
378 let raw = libc::CMSG_DATA(header).cast::<RawFd>().read_unaligned();
379 fd = Some(OwnedFd::from_raw_fd(raw));
380 }
381 header = libc::CMSG_NXTHDR(&raw const message, header);
382 }
383 }
384 Ok((i32::from_ne_bytes(data), fd))
385}
386
387pub fn serve() -> i32 {
390 let input = 0;
391 let mut kind: libc::c_int = 0;
393 let mut length = size_of::<libc::c_int>() as libc::socklen_t;
394 let is_socket = unsafe {
396 libc::getsockopt(
397 input,
398 libc::SOL_SOCKET,
399 libc::SO_TYPE,
400 (&raw mut kind).cast(),
401 &raw mut length,
402 )
403 } == 0;
404 if !is_socket {
405 eprintln!("this helper opens raw Ethernet sockets for the app that starts it");
406 return 2;
407 }
408 let mut requests = unsafe { UnixStream::from_raw_fd(input) };
410 let mut octet = [0u8];
411 loop {
412 match requests.read(&mut octet) {
413 Ok(0) | Err(_) => return 0,
414 Ok(_) => {}
415 }
416 let made = Kind::from_octet(octet[0])
417 .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))
418 .and_then(make);
419 let sent = match &made {
420 Ok(fd) => send(requests.as_raw_fd(), 0, Some(fd.as_raw_fd())),
421 Err(error) => send(
422 requests.as_raw_fd(),
423 error.raw_os_error().unwrap_or(libc::EIO),
424 None,
425 ),
426 };
427 drop(made);
429 if sent.is_err() {
430 return 0;
431 }
432 }
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438
439 #[test]
442 fn a_descriptor_crosses() {
443 let (helper, app) = UnixStream::pair().unwrap();
444 let (left, mut right) = UnixStream::pair().unwrap();
445 send(helper.as_raw_fd(), 0, Some(left.as_raw_fd())).unwrap();
446 let (status, fd) = receive(app.as_raw_fd()).unwrap();
447 assert_eq!(status, 0);
448 let mut received = UnixStream::from(fd.expect("a descriptor"));
449 use std::io::Write;
450 received.write_all(b"hi").unwrap();
451 let mut heard = [0u8; 2];
452 right.read_exact(&mut heard).unwrap();
453 assert_eq!(&heard, b"hi");
454 send(helper.as_raw_fd(), libc::EPERM, None).unwrap();
456 let (status, fd) = receive(app.as_raw_fd()).unwrap();
457 assert_eq!(status, libc::EPERM);
458 assert!(fd.is_none());
459 }
460
461 #[test]
462 fn only_packet_sockets_are_asked_for() {
463 assert_eq!(Kind::from_octet(1), Some(Kind::Datagram));
464 assert_eq!(Kind::from_octet(2), Some(Kind::Raw));
465 assert_eq!(Kind::from_octet(3), Some(Kind::Launch));
466 assert_eq!(Kind::from_octet(4), None);
467 for kind in [Kind::Datagram, Kind::Raw, Kind::Launch] {
468 assert_eq!(Kind::from_octet(kind as u8), Some(kind));
469 }
470 }
471
472 #[test]
473 fn a_launch_socket_refused_names_cap_net_admin() {
474 let error = launch_capability(Some(Path::new("/usr/lib/app/helper")));
475 assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
476 assert_eq!(error.raw_os_error(), None);
478 let text = error.to_string();
479 assert!(text.contains("CAP_NET_ADMIN"), "{text}");
480 assert!(
481 text.ends_with("setcap cap_net_raw,cap_net_admin+ep /usr/lib/app/helper"),
482 "{text}"
483 );
484 assert!(!launch_capability(None).to_string().contains("setcap"));
485 }
486}