| 1 | //! Connects to a device event source. |
| 2 | |
| 3 | use std::{cmp, fmt, fs, io, mem, sync::Arc}; |
| 4 | |
| 5 | use crate::{ |
| 6 | util, Error, Result, Udev, UdevDevice, UdevEntry, UdevEntryList, UdevList, UdevSocket, |
| 7 | }; |
| 8 | |
| 9 | /// UDEV Monitor magic bytes |
| 10 | pub const UDEV_MONITOR_MAGIC: u32 = u32::from_le_bytes([0xfe, 0xed, 0xca, 0xfe]); |
| 11 | // FIXME: put behind a feature flag or conditional compilation for platforms with a different run |
| 12 | // directory. |
| 13 | /// Default filesystem path for the UDEV `run` directory. |
| 14 | pub const UDEV_ROOT_RUN: &str = "/run"; |
| 15 | /// Maximum length of BPF socket filters. |
| 16 | pub const BPF_FILTER_LEN: usize = 512; |
| 17 | |
| 18 | /// Collection of BPF socket filters for kernel events. |
| 19 | #[repr(C)] |
| 20 | pub struct BpfFilters<const N: usize>([libc::sock_filter; N]); |
| 21 | |
| 22 | impl<const N: usize> BpfFilters<N> { |
| 23 | /// Creates a new [BpfFilters]. |
| 24 | pub const fn new() -> Self { |
| 25 | Self( |
| 26 | [libc::sock_filter { |
| 27 | code: 0, |
| 28 | jt: 0, |
| 29 | jf: 0, |
| 30 | k: 0, |
| 31 | }; N], |
| 32 | ) |
| 33 | } |
| 34 | |
| 35 | /// Gets a reference to the list of [`sock_filter`](libc::sock_filter)s. |
| 36 | pub fn filters(&self) -> &[libc::sock_filter] { |
| 37 | self.0.as_ref() |
| 38 | } |
| 39 | |
| 40 | /// Sets the code and data in the BPF socket filter. |
| 41 | /// |
| 42 | /// Increments the filter index on success. |
| 43 | /// |
| 44 | /// Returns: `Err(Error)` if the index is out-of-bounds |
| 45 | pub fn bpf_stmt(&mut self, i: &mut usize, code: u16, data: u32) -> Result<()> { |
| 46 | let len = self.0.len(); |
| 47 | if *i < len { |
| 48 | self.0[*i] = libc::sock_filter { |
| 49 | code, |
| 50 | k: data, |
| 51 | jt: 0, |
| 52 | jf: 0, |
| 53 | }; |
| 54 | *i = i.saturating_add(1); |
| 55 | Ok(()) |
| 56 | } else { |
| 57 | Err(Error::UdevMonitor(format!( |
| 58 | "invalid socket filter index: {i}, length: {len}" |
| 59 | ))) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Sets all the fields in the BPF socket filter. |
| 64 | /// |
| 65 | /// Increments the filter index on success. |
| 66 | /// |
| 67 | /// Returns: `Err(Error)` if the index is out-of-bounds |
| 68 | pub fn bpf_jmp(&mut self, i: &mut usize, code: u16, data: u32, jt: u8, jf: u8) -> Result<()> { |
| 69 | let len = self.0.len(); |
| 70 | if *i < len { |
| 71 | self.0[*i] = libc::sock_filter { |
| 72 | code, |
| 73 | k: data, |
| 74 | jt, |
| 75 | jf, |
| 76 | }; |
| 77 | *i = i.saturating_add(1); |
| 78 | Ok(()) |
| 79 | } else { |
| 80 | Err(Error::UdevMonitor(format!( |
| 81 | "invalid socket filter index: {i}, length: {len}" |
| 82 | ))) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Gets the length of set socket filters in the [BpfFilters]. |
| 87 | pub fn len(&self) -> usize { |
| 88 | self.0 |
| 89 | .iter() |
| 90 | .filter(|f| f.code != 0 || f.jt != 0 || f.jf != 0 || f.k != 0) |
| 91 | .count() |
| 92 | } |
| 93 | |
| 94 | /// Gets whether the [BpfFilters] has any set socket filters. |
| 95 | pub fn is_empty(&self) -> bool { |
| 96 | self.len() == 0 |
| 97 | } |
| 98 | |
| 99 | /// Gets the [BpfFilters] as a [`sock_fprog`](libc::sock_fprog) FFI object. |
| 100 | /// |
| 101 | /// SAFETY: the resulting `sock_fprog` contains a mutable pointer that should not be accessed |
| 102 | /// directly. The result is meant to be passed to Linux API functions that require |
| 103 | /// `sock_fprog`. |
| 104 | pub fn as_sock_fprog(&mut self) -> libc::sock_fprog { |
| 105 | libc::sock_fprog { |
| 106 | len: self.len() as u16, |
| 107 | filter: self.0.as_mut_ptr(), |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | impl<const N: usize> Default for BpfFilters<N> { |
| 112 | fn default() -> Self { |
| 113 | Self::new() |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Handles device event sources. |
| 118 | pub struct UdevMonitor { |
| 119 | udev: Arc<Udev>, |
| 120 | sock: i32, |
| 121 | snl: UdevSocket, |
| 122 | snl_group: UdevMonitorNetlinkGroup, |
| 123 | snl_trusted_sender: UdevSocket, |
| 124 | snl_destination: UdevSocket, |
| 125 | snl_destination_group: UdevMonitorNetlinkGroup, |
| 126 | addrlen: usize, |
| 127 | filter_subsystem_list: UdevList, |
| 128 | filter_tag_list: UdevList, |
| 129 | bound: bool, |
| 130 | filter: BpfFilters<BPF_FILTER_LEN>, |
| 131 | } |
| 132 | |
| 133 | impl UdevMonitor { |
| 134 | /// Creates a new [UdevMonitor]. |
| 135 | pub fn new(udev: Arc<Udev>) -> Result<Self> { |
| 136 | let filter_subsystem_list = UdevList::new(Arc::clone(&udev)); |
| 137 | let filter_tag_list = UdevList::new(Arc::clone(&udev)); |
| 138 | |
| 139 | Ok(Self { |
| 140 | udev, |
| 141 | sock: 0, |
| 142 | snl: UdevSocket::new_nl(libc::AF_NETLINK, 0, 2), |
| 143 | snl_group: UdevMonitorNetlinkGroup::None, |
| 144 | snl_trusted_sender: UdevSocket::new_nl(libc::AF_NETLINK, 0, 0), |
| 145 | snl_destination: UdevSocket::new_nl(libc::AF_NETLINK, 0, 0), |
| 146 | snl_destination_group: UdevMonitorNetlinkGroup::None, |
| 147 | addrlen: mem::size_of::<libc::sockaddr_nl>(), |
| 148 | filter_subsystem_list, |
| 149 | filter_tag_list, |
| 150 | bound: false, |
| 151 | filter: BpfFilters::new(), |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | /// Creates a [UdevMonitor] from group name and socket file descriptor. |
| 156 | pub fn new_from_netlink_fd<N: Into<UdevMonitorNetlinkGroup> + fmt::Display + Copy>( |
| 157 | udev: Arc<Udev>, |
| 158 | name: N, |
| 159 | fd: i32, |
| 160 | ) -> Result<Self> { |
| 161 | let group = match name.into() { |
| 162 | UdevMonitorNetlinkGroup::Udev => { |
| 163 | if fs::OpenOptions::new() |
| 164 | .read(true) |
| 165 | .open(format!("{UDEV_ROOT_RUN}/udev/control")) |
| 166 | .is_ok() |
| 167 | { |
| 168 | let err_msg = "the udev service seems not to be active, disable the monitor"; |
| 169 | log::debug!("{err_msg}"); |
| 170 | Ok(UdevMonitorNetlinkGroup::None) |
| 171 | } else { |
| 172 | Ok(UdevMonitorNetlinkGroup::Udev) |
| 173 | } |
| 174 | } |
| 175 | UdevMonitorNetlinkGroup::Kernel => Ok(UdevMonitorNetlinkGroup::Kernel), |
| 176 | |
| 177 | UdevMonitorNetlinkGroup::None => { |
| 178 | Err(Error::UdevMonitor(format!("invalid netlink group: {name}"))) |
| 179 | } |
| 180 | }?; |
| 181 | |
| 182 | let mut udev_monitor = Self::new(udev)?; |
| 183 | |
| 184 | udev_monitor.set_snl_group(group); |
| 185 | udev_monitor.set_snl_destination_group(UdevMonitorNetlinkGroup::Udev); |
| 186 | |
| 187 | if fd < 0 { |
| 188 | // SAFETY: all arguments are valid, and the return value is checked before use. |
| 189 | udev_monitor.set_sock(unsafe { |
| 190 | libc::socket( |
| 191 | libc::PF_NETLINK, |
| 192 | libc::SOCK_RAW | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, |
| 193 | libc::NETLINK_KOBJECT_UEVENT, |
| 194 | ) |
| 195 | }); |
| 196 | |
| 197 | if udev_monitor.sock() < 0 { |
| 198 | let errno = io::Error::last_os_error(); |
| 199 | let err_msg = format!("error getting socket: {errno}"); |
| 200 | |
| 201 | log::error!("{err_msg}"); |
| 202 | |
| 203 | Err(Error::Io(err_msg)) |
| 204 | } else { |
| 205 | Ok(udev_monitor) |
| 206 | } |
| 207 | } else { |
| 208 | udev_monitor.set_sock(fd); |
| 209 | udev_monitor.set_nl_address()?; |
| 210 | |
| 211 | Ok(udev_monitor.with_bound(true)) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// Creates a new [UdevMonitor] from the provided parameters. |
| 216 | /// |
| 217 | /// Parameters: |
| 218 | /// |
| 219 | /// `udev`: udev library context |
| 220 | /// `name`: name of event source |
| 221 | /// |
| 222 | /// From the `libudev` documentation: |
| 223 | /// |
| 224 | /// ```no_build,no_run |
| 225 | /// Create new udev monitor and connect to a specified event |
| 226 | /// source. Valid sources identifiers are "udev" and "kernel". |
| 227 | /// |
| 228 | /// Applications should usually not connect directly to the |
| 229 | /// "kernel" events, because the devices might not be usable |
| 230 | /// at that time, before `udev` has configured them, and created |
| 231 | /// device nodes. Accessing devices at the same time as `udev`, |
| 232 | /// might result in unpredictable behavior. The "`udev`" events |
| 233 | /// are sent out after `udev` has finished its event processing, |
| 234 | /// all rules have been processed, and needed device nodes are |
| 235 | /// created. |
| 236 | /// ``` |
| 237 | /// |
| 238 | /// Returns: a new [UdevMonitor], or [Error], in case of an error |
| 239 | pub fn new_from_netlink<N: Into<UdevMonitorNetlinkGroup> + fmt::Display + Copy>( |
| 240 | udev: Arc<Udev>, |
| 241 | name: N, |
| 242 | ) -> Result<Self> { |
| 243 | Self::new_from_netlink_fd(udev, name, -1) |
| 244 | } |
| 245 | |
| 246 | fn set_nl_address(&mut self) -> Result<()> { |
| 247 | // SAFETY: `sockaddr_nl` is a well-aligned struct, so zeroing its memory results in a valid |
| 248 | // stack allocation. |
| 249 | let mut snl = unsafe { mem::zeroed::<libc::sockaddr_nl>() }; |
| 250 | let mut snl_len = mem::size_of::<libc::sockaddr_nl>() as u32; |
| 251 | |
| 252 | // get the address the kernel has assigned us |
| 253 | // it is usually, but not necessarily the PID |
| 254 | // |
| 255 | // SAFETY: parameters are initialized properly, and pointers reference valid memory. |
| 256 | match unsafe { |
| 257 | libc::getsockname( |
| 258 | self.sock, |
| 259 | &mut snl as *mut libc::sockaddr_nl as *mut _, |
| 260 | &mut snl_len as *mut _, |
| 261 | ) |
| 262 | } { |
| 263 | i if i >= 0 => { |
| 264 | let pid = snl.nl_pid; |
| 265 | log::debug!("UDEV monitor SNL PID: {pid}"); |
| 266 | self.set_snl(UdevSocket::Netlink(snl)); |
| 267 | Ok(()) |
| 268 | } |
| 269 | _ => { |
| 270 | let errno = io::Error::last_os_error(); |
| 271 | Err(Error::UdevMonitor(format!( |
| 272 | "unable to set SNL address: {errno}" |
| 273 | ))) |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | /// Gets a reference to the [Udev] context. |
| 279 | pub const fn udev(&self) -> &Arc<Udev> { |
| 280 | &self.udev |
| 281 | } |
| 282 | |
| 283 | /// Gets the socket file descriptor. |
| 284 | pub const fn sock(&self) -> i32 { |
| 285 | self.sock |
| 286 | } |
| 287 | |
| 288 | /// Sets the socket file descriptor. |
| 289 | pub fn set_sock(&mut self, val: i32) { |
| 290 | self.sock = val; |
| 291 | } |
| 292 | |
| 293 | /// Builder function that sets the socket file descriptor. |
| 294 | pub fn with_sock(mut self, val: i32) -> Self { |
| 295 | self.set_sock(val); |
| 296 | self |
| 297 | } |
| 298 | |
| 299 | /// Gets a reference to the SNL [UdevSocket]. |
| 300 | pub const fn snl(&self) -> &UdevSocket { |
| 301 | &self.snl |
| 302 | } |
| 303 | |
| 304 | /// Sets the SNL [UdevSocket]. |
| 305 | /// |
| 306 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 307 | pub fn set_snl(&mut self, val: UdevSocket) { |
| 308 | if matches!(val, UdevSocket::Netlink(_)) { |
| 309 | self.snl = val; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// Builder function that sets the SNL [UdevSocket]. |
| 314 | /// |
| 315 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 316 | pub fn with_snl(mut self, val: UdevSocket) -> Self { |
| 317 | self.set_snl(val); |
| 318 | self |
| 319 | } |
| 320 | |
| 321 | /// Gets the SNL [UdevMonitorNetlinkGroup]. |
| 322 | pub const fn snl_group(&self) -> UdevMonitorNetlinkGroup { |
| 323 | self.snl_group |
| 324 | } |
| 325 | |
| 326 | /// Sets the SNL [UdevMonitorNetlinkGroup]. |
| 327 | pub fn set_snl_group<G: Into<UdevMonitorNetlinkGroup>>(&mut self, val: G) { |
| 328 | self.snl_group = val.into(); |
| 329 | } |
| 330 | |
| 331 | /// Builder function that sets the SNL [UdevMonitorNetlinkGroup]. |
| 332 | pub fn with_snl_group<G: Into<UdevMonitorNetlinkGroup>>(mut self, val: G) -> Self { |
| 333 | self.set_snl_group(val); |
| 334 | self |
| 335 | } |
| 336 | |
| 337 | /// Gets a reference to the SNL trusted sender [UdevSocket]. |
| 338 | pub const fn snl_trusted_sender(&self) -> &UdevSocket { |
| 339 | &self.snl_trusted_sender |
| 340 | } |
| 341 | |
| 342 | /// Sets the SNL trusted sender [UdevSocket]. |
| 343 | /// |
| 344 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 345 | pub fn set_snl_trusted_sender(&mut self, val: UdevSocket) { |
| 346 | if matches!(val, UdevSocket::Netlink(_)) { |
| 347 | self.snl = val; |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// Builder function that sets the SNL trusted sender [UdevSocket]. |
| 352 | /// |
| 353 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 354 | pub fn with_snl_trusted_sender(mut self, val: UdevSocket) -> Self { |
| 355 | self.set_snl_trusted_sender(val); |
| 356 | self |
| 357 | } |
| 358 | |
| 359 | /// Gets a reference to the SNL destination [UdevSocket]. |
| 360 | pub const fn snl_destination(&self) -> &UdevSocket { |
| 361 | &self.snl_destination |
| 362 | } |
| 363 | |
| 364 | /// Sets the SNL destination [UdevSocket]. |
| 365 | /// |
| 366 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 367 | pub fn set_snl_destination(&mut self, val: UdevSocket) { |
| 368 | if matches!(val, UdevSocket::Netlink(_)) { |
| 369 | self.snl_destination = val; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// Builder function that sets the SNL destination [UdevSocket]. |
| 374 | /// |
| 375 | /// **NOTE**: the SNL socket is only set for [UdevSocket::Netlink] sockets. |
| 376 | pub fn with_snl_destination(mut self, val: UdevSocket) -> Self { |
| 377 | self.set_snl_destination(val); |
| 378 | self |
| 379 | } |
| 380 | |
| 381 | /// Gets the SNL destination [UdevMonitorNetlinkGroup]. |
| 382 | pub const fn snl_destination_group(&self) -> UdevMonitorNetlinkGroup { |
| 383 | self.snl_destination_group |
| 384 | } |
| 385 | |
| 386 | /// Sets the SNL destination [UdevMonitorNetlinkGroup]. |
| 387 | pub fn set_snl_destination_group<G: Into<UdevMonitorNetlinkGroup>>(&mut self, val: G) { |
| 388 | self.snl_destination_group = val.into(); |
| 389 | } |
| 390 | |
| 391 | /// Builder function that sets the SNL destination [UdevMonitorNetlinkGroup]. |
| 392 | pub fn with_snl_destination_group<G: Into<UdevMonitorNetlinkGroup>>(mut self, val: G) -> Self { |
| 393 | self.set_snl_destination_group(val); |
| 394 | self |
| 395 | } |
| 396 | |
| 397 | /// Gets the socket address length. |
| 398 | pub const fn addrlen(&self) -> usize { |
| 399 | self.addrlen |
| 400 | } |
| 401 | |
| 402 | /// Gets a reference to the filter subsystem [UdevList]. |
| 403 | pub const fn filter_subsystem_list(&self) -> &UdevList { |
| 404 | &self.filter_subsystem_list |
| 405 | } |
| 406 | |
| 407 | /// Gets a mutable reference to the filter subsystem [UdevList]. |
| 408 | pub fn filter_subsystem_list_mut(&mut self) -> &mut UdevList { |
| 409 | &mut self.filter_subsystem_list |
| 410 | } |
| 411 | |
| 412 | /// Sets the filter subsystem [UdevList]. |
| 413 | pub fn set_filter_subsystem_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 414 | self.filter_subsystem_list.set_list(list); |
| 415 | } |
| 416 | |
| 417 | /// Builder function that sets the filter subsystem [UdevList]. |
| 418 | pub fn with_filter_subsystem_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 419 | self.set_filter_subsystem_list(list); |
| 420 | self |
| 421 | } |
| 422 | |
| 423 | /// Gets a reference to the filter tag [UdevList]. |
| 424 | pub const fn filter_tag_list(&self) -> &UdevList { |
| 425 | &self.filter_tag_list |
| 426 | } |
| 427 | |
| 428 | /// Gets a mutable reference to the filter tag [UdevList]. |
| 429 | pub fn filter_tag_list_mut(&mut self) -> &mut UdevList { |
| 430 | &mut self.filter_tag_list |
| 431 | } |
| 432 | |
| 433 | /// Sets the filter tag [UdevList]. |
| 434 | pub fn set_filter_tag_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 435 | self.filter_tag_list.set_list(list); |
| 436 | } |
| 437 | |
| 438 | /// Builder function that sets the filter tag [UdevList]. |
| 439 | pub fn with_filter_tag_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 440 | self.set_filter_tag_list(list); |
| 441 | self |
| 442 | } |
| 443 | |
| 444 | /// Gets whether the [UdevMonitor] is bound to a socket. |
| 445 | pub const fn bound(&self) -> bool { |
| 446 | self.bound |
| 447 | } |
| 448 | |
| 449 | fn set_bound(&mut self, val: bool) { |
| 450 | self.bound = val; |
| 451 | } |
| 452 | |
| 453 | fn with_bound(mut self, val: bool) -> Self { |
| 454 | self.set_bound(val); |
| 455 | self |
| 456 | } |
| 457 | |
| 458 | /// Gets whether the [UdevDevice] passes the [UdevMonitor] filters. |
| 459 | pub fn passes_filter(&self, device: &mut UdevDevice) -> bool { |
| 460 | if self.filter_subsystem_list.is_empty() { |
| 461 | self.filter_tag_list().has_tag(device) |
| 462 | } else { |
| 463 | for list_entry in self.filter_subsystem_list.iter() { |
| 464 | if list_entry.name() == device.get_subsystem() { |
| 465 | let (devtype, ddevtype) = (list_entry.value(), device.devtype()); |
| 466 | |
| 467 | if !ddevtype.is_empty() && (devtype.is_empty() || devtype == ddevtype) { |
| 468 | return self.filter_tag_list().has_tag(device); |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | false |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | /// Updates the monitor socket filter. |
| 477 | /// |
| 478 | /// From the `libudev` documentation: |
| 479 | /// |
| 480 | /// ```no_build,no_run |
| 481 | /// Update the installed socket filter. This is only needed, |
| 482 | /// if the filter was removed or changed. |
| 483 | /// ``` |
| 484 | /// |
| 485 | /// Returns: `Ok(())` on success, `Err(Error)` otherwise. |
| 486 | pub fn filter_update(&mut self) -> Result<()> { |
| 487 | if self.filter_subsystem_list().entry().is_none() |
| 488 | && self.filter_tag_list().entry().is_none() |
| 489 | { |
| 490 | Ok(()) |
| 491 | } else { |
| 492 | let mut ins: BpfFilters<BPF_FILTER_LEN> = BpfFilters::new(); |
| 493 | let mut i = 0usize; |
| 494 | |
| 495 | // load magic in A |
| 496 | ins.bpf_stmt( |
| 497 | &mut i, |
| 498 | (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, |
| 499 | UdevMonitorNetlinkHeader::magic_offset() as u32, |
| 500 | )?; |
| 501 | // jump if magic matches |
| 502 | ins.bpf_jmp( |
| 503 | &mut i, |
| 504 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 505 | UDEV_MONITOR_MAGIC, |
| 506 | 1, |
| 507 | 0, |
| 508 | )?; |
| 509 | // wrong magic, pass packet |
| 510 | ins.bpf_stmt(&mut i, (libc::BPF_RET | libc::BPF_K) as u16, 0xffff_ffff)?; |
| 511 | |
| 512 | if self.filter_tag_list.entry().is_some() { |
| 513 | let mut tag_matches = self.filter_tag_list.len(); |
| 514 | |
| 515 | for list_entry in self.filter_tag_list.iter() { |
| 516 | let tag_bloom_bits = util::string_bloom64(list_entry.name()); |
| 517 | let tag_bloom_hi = (tag_bloom_bits >> 32) as u32; |
| 518 | let tag_bloom_lo = tag_bloom_bits as u32; |
| 519 | |
| 520 | // load device bloom bits in A |
| 521 | ins.bpf_stmt( |
| 522 | &mut i, |
| 523 | (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, |
| 524 | UdevMonitorNetlinkHeader::filter_tag_bloom_hi_offset() as u32, |
| 525 | )?; |
| 526 | // clear bits (tag bits & bloom bits) |
| 527 | ins.bpf_stmt( |
| 528 | &mut i, |
| 529 | (libc::BPF_ALU | libc::BPF_AND | libc::BPF_K) as u16, |
| 530 | UdevMonitorNetlinkHeader::filter_tag_bloom_hi_offset() as u32, |
| 531 | )?; |
| 532 | // jump to next tag if it does not match |
| 533 | ins.bpf_jmp( |
| 534 | &mut i, |
| 535 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 536 | tag_bloom_hi, |
| 537 | 0, |
| 538 | 3, |
| 539 | )?; |
| 540 | |
| 541 | // load device bloom bits in A |
| 542 | ins.bpf_stmt( |
| 543 | &mut i, |
| 544 | (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, |
| 545 | UdevMonitorNetlinkHeader::filter_tag_bloom_lo_offset() as u32, |
| 546 | )?; |
| 547 | // clear bits (tag bits & bloom bits) |
| 548 | ins.bpf_stmt( |
| 549 | &mut i, |
| 550 | (libc::BPF_ALU | libc::BPF_AND | libc::BPF_K) as u16, |
| 551 | tag_bloom_lo, |
| 552 | )?; |
| 553 | // jump behind end of tag match block if tag matches |
| 554 | tag_matches = tag_matches.saturating_sub(1); |
| 555 | ins.bpf_jmp( |
| 556 | &mut i, |
| 557 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 558 | tag_bloom_lo, |
| 559 | 1usize.saturating_add(tag_matches.saturating_mul(6)) as u8, |
| 560 | 0, |
| 561 | )?; |
| 562 | } |
| 563 | |
| 564 | // nothing matched, drop packet |
| 565 | ins.bpf_stmt(&mut i, (libc::BPF_RET | libc::BPF_K) as u16, 0)?; |
| 566 | } |
| 567 | |
| 568 | // add all subsystem matches |
| 569 | if self.filter_subsystem_list().entry().is_some() { |
| 570 | for list_entry in self.filter_subsystem_list().iter() { |
| 571 | let mut hash = util::string_hash32(list_entry.name()); |
| 572 | |
| 573 | // load device subsystem value in A |
| 574 | ins.bpf_stmt( |
| 575 | &mut i, |
| 576 | (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, |
| 577 | UdevMonitorNetlinkHeader::filter_subsystem_hash_offset() as u32, |
| 578 | )?; |
| 579 | |
| 580 | if list_entry.value().is_empty() { |
| 581 | // jump if subsystem does not match |
| 582 | ins.bpf_jmp( |
| 583 | &mut i, |
| 584 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 585 | hash, |
| 586 | 0, |
| 587 | 1, |
| 588 | )?; |
| 589 | } else { |
| 590 | // jump if subsystem does not match |
| 591 | ins.bpf_jmp( |
| 592 | &mut i, |
| 593 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 594 | hash, |
| 595 | 0, |
| 596 | 3, |
| 597 | )?; |
| 598 | |
| 599 | // load device devtype value in A |
| 600 | ins.bpf_stmt( |
| 601 | &mut i, |
| 602 | (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, |
| 603 | UdevMonitorNetlinkHeader::filter_devtype_hash_offset() as u32, |
| 604 | )?; |
| 605 | |
| 606 | // jump if value does not match |
| 607 | hash = util::string_hash32(list_entry.value()); |
| 608 | ins.bpf_jmp( |
| 609 | &mut i, |
| 610 | (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16, |
| 611 | hash, |
| 612 | 0, |
| 613 | 1, |
| 614 | )?; |
| 615 | } |
| 616 | |
| 617 | // matched pass packet |
| 618 | ins.bpf_stmt(&mut i, (libc::BPF_RET | libc::BPF_K) as u16, 0xffff_ffff)?; |
| 619 | } |
| 620 | |
| 621 | // nothing matched, drop packet |
| 622 | ins.bpf_stmt(&mut i, (libc::BPF_RET | libc::BPF_K) as u16, 0)?; |
| 623 | } |
| 624 | |
| 625 | // matched, pass packet |
| 626 | ins.bpf_stmt(&mut i, (libc::BPF_RET | libc::BPF_K) as u16, 0xffff_ffff)?; |
| 627 | |
| 628 | // install filter |
| 629 | self.filter = ins; |
| 630 | let mut filter = self.filter.as_sock_fprog(); |
| 631 | |
| 632 | // SAFETY: arguments are valid, and pointer reference valid memory. |
| 633 | let err = unsafe { |
| 634 | libc::setsockopt( |
| 635 | self.sock, |
| 636 | libc::SOL_SOCKET, |
| 637 | libc::SO_ATTACH_FILTER, |
| 638 | &mut filter as *mut libc::sock_fprog as *mut _, |
| 639 | mem::size_of::<libc::sock_fprog>() as u32, |
| 640 | ) |
| 641 | }; |
| 642 | |
| 643 | if err < 0 { |
| 644 | let errno = io::Error::last_os_error(); |
| 645 | Err(Error::UdevMonitor(format!( |
| 646 | "error setting BPF filter, error: {err}, errno: {errno}" |
| 647 | ))) |
| 648 | } else { |
| 649 | Ok(()) |
| 650 | } |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /// Binds the [UdevMonitor] socket to the event source. |
| 655 | pub fn enable_receiving(&mut self) -> Result<()> { |
| 656 | self.filter_update()?; |
| 657 | |
| 658 | let mut err = if !self.bound { |
| 659 | // SAFETY: all arguments are valid, and pointers reference valid memory. |
| 660 | unsafe { |
| 661 | libc::bind( |
| 662 | self.sock, |
| 663 | self.snl.as_nl_ptr()? as *const _, |
| 664 | mem::size_of::<libc::sockaddr_nl>() as u32, |
| 665 | ) |
| 666 | } |
| 667 | } else { |
| 668 | 0 |
| 669 | }; |
| 670 | |
| 671 | if err < 0 { |
| 672 | let errno = io::Error::last_os_error(); |
| 673 | let err_msg = format!("bind failed, error: {err}, errno: {errno}"); |
| 674 | log::error!("{err_msg}"); |
| 675 | Err(Error::UdevMonitor(err_msg)) |
| 676 | } else { |
| 677 | self.bound = true; |
| 678 | self.set_nl_address()?; |
| 679 | |
| 680 | let on = 1i32; |
| 681 | |
| 682 | // SAFETY: all arguments are valid, and pointers reference valid memory. |
| 683 | err = unsafe { |
| 684 | libc::setsockopt( |
| 685 | self.sock, |
| 686 | libc::SOL_SOCKET, |
| 687 | libc::SO_PASSCRED, |
| 688 | &on as *const i32 as *const _, |
| 689 | mem::size_of::<i32>() as u32, |
| 690 | ) |
| 691 | }; |
| 692 | |
| 693 | if err < 0 { |
| 694 | let errno = io::Error::last_os_error(); |
| 695 | let err_msg = format!("setting SO_PASSCRED failed, error: {err}, errno: {errno}"); |
| 696 | log::error!("{err_msg}"); |
| 697 | Err(Error::UdevMonitor(err_msg)) |
| 698 | } else { |
| 699 | Ok(()) |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | /// Sets the size of the kernel socket buffer. |
| 705 | /// |
| 706 | /// From the `libudev` documentation: |
| 707 | /// |
| 708 | /// ```no_build,no_run |
| 709 | /// Set the size of the kernel socket buffer. This call needs the |
| 710 | /// appropriate privileges to succeed. |
| 711 | /// ``` |
| 712 | /// |
| 713 | /// Returns: `Ok(())` on success, `Err(Error)` otherwise. |
| 714 | pub fn set_receive_buffer_size(&mut self, size: usize) -> Result<()> { |
| 715 | let int_size = size as i32; |
| 716 | // SAFETY: all arguments are valid, and pointers reference valid memory. |
| 717 | let err = unsafe { |
| 718 | libc::setsockopt( |
| 719 | self.sock, |
| 720 | libc::SOL_SOCKET, |
| 721 | libc::SO_RCVBUFFORCE, |
| 722 | &int_size as *const i32 as *const _, |
| 723 | mem::size_of::<i32>() as u32, |
| 724 | ) |
| 725 | }; |
| 726 | if err < 0 { |
| 727 | let errno = io::Error::last_os_error(); |
| 728 | let err_msg = |
| 729 | format!("Error setting receive buffer size, error: {err}, errno: {errno}"); |
| 730 | log::error!("{err_msg}"); |
| 731 | Err(Error::UdevMonitor(err_msg)) |
| 732 | } else { |
| 733 | Ok(()) |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | /// Receives data from the [UdevMonitor] socket. |
| 738 | /// |
| 739 | /// From the `libudev` documentation: |
| 740 | /// |
| 741 | /// ```no_build,no_run |
| 742 | /// Receive data from the udev monitor socket, allocate a new udev |
| 743 | /// device, fill in the received data, and return the device. |
| 744 | /// |
| 745 | /// Only socket connections with uid=0 are accepted. |
| 746 | /// |
| 747 | /// The monitor socket is by default set to NONBLOCK. A variant of poll() on |
| 748 | /// the file descriptor returned by udev_monitor_get_fd() should to be used to |
| 749 | /// wake up when new devices arrive, or alternatively the file descriptor |
| 750 | /// switched into blocking mode. |
| 751 | /// ``` |
| 752 | /// |
| 753 | /// Returns: `Ok(UdevDevice)` on success, `Err(Error)` otherwise. |
| 754 | // FIXME: break this into smaller functions |
| 755 | pub fn receive_device(&mut self) -> Result<UdevDevice> { |
| 756 | // avoid infinite loop, only retry up to a given limit of queued devices |
| 757 | // TODO: should this limit be higher? lower? |
| 758 | // the original implementation retries indefinitely, as long as there are queued devices |
| 759 | for _ in 0..1024 { |
| 760 | let mut buf = [0u8; 8192]; |
| 761 | let mut iov = libc::iovec { |
| 762 | iov_base: buf.as_mut_ptr() as *mut _, |
| 763 | iov_len: 8192, |
| 764 | }; |
| 765 | |
| 766 | let mut cred_msg = [0u8; mem::size_of::<libc::ucred>()]; |
| 767 | |
| 768 | // SAFETY: `libc::sockaddr_nl` has a known-size, and is well-aligned. |
| 769 | // `snl` will also be initialized below by the syscall before being used. |
| 770 | let mut snl: libc::sockaddr_nl = unsafe { mem::zeroed() }; |
| 771 | snl.nl_family = libc::AF_NETLINK as u16; |
| 772 | |
| 773 | // SAFETY: `libc::msghdr` has a known-size, and is well-aligned. |
| 774 | // `smsg` is properly initialized below before further use. |
| 775 | let mut smsg: libc::msghdr = unsafe { mem::zeroed() }; |
| 776 | |
| 777 | smsg.msg_iov = &mut iov as *mut libc::iovec as *mut _; |
| 778 | smsg.msg_iovlen = 1; |
| 779 | smsg.msg_control = cred_msg.as_mut_ptr() as *mut _; |
| 780 | smsg.msg_controllen = cred_msg.len(); |
| 781 | smsg.msg_name = &mut snl as *mut libc::sockaddr_nl as *mut _; |
| 782 | smsg.msg_namelen = mem::size_of::<libc::sockaddr_nl>() as u32; |
| 783 | |
| 784 | // SAFETY: all parameters are properly initialized, and point to valid memory. |
| 785 | let buflen = unsafe { libc::recvmsg(self.sock, &mut smsg as *mut _, 0) }; |
| 786 | |
| 787 | let trusted_pid = self.snl_trusted_sender.pid().unwrap_or(0); |
| 788 | |
| 789 | if buflen < 0 { |
| 790 | let errno = io::Error::last_os_error(); |
| 791 | let err_msg = format!("unable to receive message: {errno}"); |
| 792 | |
| 793 | log::debug!("{err_msg}"); |
| 794 | |
| 795 | Err(Error::UdevMonitor(err_msg)) |
| 796 | } else if buflen < 32 || smsg.msg_flags & libc::MSG_TRUNC != 0 { |
| 797 | let err_msg = format!("invalid message length: {buflen}"); |
| 798 | |
| 799 | log::error!("{err_msg}"); |
| 800 | |
| 801 | Err(Error::UdevMonitor(err_msg)) |
| 802 | } else if snl.nl_groups == 0 && (trusted_pid == 0 || snl.nl_pid != trusted_pid) { |
| 803 | // unicast message, check if we trust the sender |
| 804 | let err_msg = "unicast netlink message ignored".to_owned(); |
| 805 | |
| 806 | log::debug!("{err_msg}"); |
| 807 | |
| 808 | Err(Error::UdevMonitor(err_msg)) |
| 809 | } else if snl.nl_groups == UdevMonitorNetlinkGroup::Kernel as u32 && snl.nl_pid > 0 { |
| 810 | let pid = snl.nl_pid; |
| 811 | let err_msg = format!("multicast kernel netlink message from PID {pid} ignored"); |
| 812 | |
| 813 | log::debug!("{err_msg}"); |
| 814 | |
| 815 | Err(Error::UdevMonitor(err_msg)) |
| 816 | } else { |
| 817 | Ok(()) |
| 818 | }?; |
| 819 | |
| 820 | let libc::ucred { |
| 821 | pid: _, |
| 822 | uid, |
| 823 | gid: _, |
| 824 | } = parse_cmsg(cred_msg.as_ref())?; |
| 825 | |
| 826 | if uid != 0 { |
| 827 | let err_msg = format!("sender uid={uid}, message ignored"); |
| 828 | |
| 829 | log::debug!("{err_msg}"); |
| 830 | |
| 831 | Err(Error::UdevMonitor(err_msg)) |
| 832 | } else { |
| 833 | Ok(()) |
| 834 | }?; |
| 835 | |
| 836 | let (bufpos, is_initialized) = match UdevMonitorNetlinkHeader::try_from(buf.as_ref()) { |
| 837 | Ok(nlh) => { |
| 838 | let prop_off = nlh.properties_off as usize; |
| 839 | log::debug!("NetlinkHeader properties offset: {prop_off:#x}"); |
| 840 | (cmp::min(buf.len(), prop_off), true) |
| 841 | } |
| 842 | Err(_) => { |
| 843 | // kernel message header |
| 844 | let bufpos = buf |
| 845 | .iter() |
| 846 | .position(|&b| b == b'\0') |
| 847 | .map(|b| b + 1) |
| 848 | .unwrap_or(0); |
| 849 | |
| 850 | if bufpos < b"a@/d".len() || bufpos >= buflen as usize { |
| 851 | let err_msg = format!("invalid message length :: buffer length: {buflen}, header length: {bufpos}, expected header: 4"); |
| 852 | |
| 853 | log::debug!("{err_msg}"); |
| 854 | |
| 855 | Err(Error::UdevMonitor(err_msg)) |
| 856 | } else if buf[..2].as_ref() != b"@/".as_ref() { |
| 857 | let err_msg = "unrecognized message header".to_owned(); |
| 858 | |
| 859 | log::debug!("{err_msg}"); |
| 860 | |
| 861 | Err(Error::UdevMonitor(err_msg)) |
| 862 | } else { |
| 863 | Ok((bufpos, false)) |
| 864 | }? |
| 865 | } |
| 866 | }; |
| 867 | |
| 868 | let mut udev_device = |
| 869 | UdevDevice::new_from_nulstr(Arc::clone(&self.udev), buf[bufpos..].as_ref()) |
| 870 | .map_err(|e| { |
| 871 | let err_msg = format!("could not create device: {e}"); |
| 872 | log::debug!("{err_msg}"); |
| 873 | Error::UdevMonitor(err_msg) |
| 874 | })?; |
| 875 | |
| 876 | if is_initialized { |
| 877 | udev_device.set_is_initialized(true); |
| 878 | } |
| 879 | |
| 880 | // skip device, if it does not pass the current filter |
| 881 | if !self.passes_filter(&mut udev_device) { |
| 882 | // if somthing is queued, get next device |
| 883 | let mut pfd = [libc::pollfd { |
| 884 | fd: self.sock, |
| 885 | events: libc::POLLIN, |
| 886 | revents: 0, |
| 887 | }]; |
| 888 | let pfd_len = pfd.len() as libc::nfds_t; |
| 889 | |
| 890 | // SAFETY: call to `poll` is safe because `pollfd` is properly initialized, and the |
| 891 | // resulting mutable pointer references valid memory. |
| 892 | if unsafe { libc::poll(pfd.as_mut_ptr(), pfd_len, 0) } > 0 { |
| 893 | // retry with the next device |
| 894 | Ok(()) |
| 895 | } else { |
| 896 | Err(Error::UdevMonitor( |
| 897 | "device did not pass filter, no queued devices".into(), |
| 898 | )) |
| 899 | }?; |
| 900 | } else { |
| 901 | return Ok(udev_device); |
| 902 | } |
| 903 | } |
| 904 | |
| 905 | Err(Error::UdevMonitor("receive device retries exceeded".into())) |
| 906 | } |
| 907 | |
| 908 | /// Sends an [UdevDevice] from one [UdevMonitor] to another. |
| 909 | // FIXME: break this into smaller functions |
| 910 | pub fn send_device( |
| 911 | &mut self, |
| 912 | mut destination: Option<&mut Self>, |
| 913 | device: &mut UdevDevice, |
| 914 | ) -> Result<isize> { |
| 915 | let mut nlh = UdevMonitorNetlinkHeader::new(); |
| 916 | |
| 917 | let mut iov = [ |
| 918 | libc::iovec { |
| 919 | iov_base: &mut nlh as *mut UdevMonitorNetlinkHeader as *mut _, |
| 920 | iov_len: mem::size_of::<UdevMonitorNetlinkHeader>(), |
| 921 | }, |
| 922 | libc::iovec { |
| 923 | iov_base: core::ptr::null_mut(), |
| 924 | iov_len: 0, |
| 925 | }, |
| 926 | ]; |
| 927 | |
| 928 | let mut smsg = libc::msghdr { |
| 929 | msg_iov: iov.as_mut_ptr() as *mut _, |
| 930 | msg_iovlen: iov.len(), |
| 931 | msg_control: core::ptr::null_mut(), |
| 932 | msg_controllen: 0, |
| 933 | msg_flags: 0, |
| 934 | msg_name: core::ptr::null_mut(), |
| 935 | msg_namelen: 0, |
| 936 | }; |
| 937 | |
| 938 | if device.get_properties_monitor_buf().len() < 32 { |
| 939 | Err(Error::UdevMonitor( |
| 940 | "device buffer is too small to contain a valid device".into(), |
| 941 | )) |
| 942 | } else { |
| 943 | let mut buf = device.get_properties_monitor_buf().to_owned(); |
| 944 | let blen = buf.len(); |
| 945 | |
| 946 | // fill in versioned header |
| 947 | nlh.set_filter_subsystem_hash(util::string_hash32(device.get_subsystem())); |
| 948 | |
| 949 | if !device.devtype().is_empty() { |
| 950 | nlh.set_filter_devtype_hash(util::string_hash32(device.devtype())); |
| 951 | } |
| 952 | |
| 953 | // add tag bloom filter |
| 954 | let mut tag_bloom_bits = 0u64; |
| 955 | device |
| 956 | .tags_list() |
| 957 | .iter() |
| 958 | .for_each(|list_entry| tag_bloom_bits |= util::string_bloom64(list_entry.name())); |
| 959 | |
| 960 | if tag_bloom_bits > 0 { |
| 961 | nlh.set_filter_tag_bloom_hi((tag_bloom_bits >> 32) as u32); |
| 962 | nlh.set_filter_tag_bloom_lo(tag_bloom_bits as u32); |
| 963 | } |
| 964 | |
| 965 | // add properties list |
| 966 | nlh.properties_off = iov[0].iov_len as u32; |
| 967 | nlh.properties_len = blen as u32; |
| 968 | |
| 969 | iov[1].iov_base = buf.as_mut_ptr() as *mut _; |
| 970 | iov[1].iov_len = blen; |
| 971 | |
| 972 | // Use custom address for target, or the default one. |
| 973 | // |
| 974 | // If we send to a multicast group, we will get |
| 975 | // ECONNREFUSED, which is expected. |
| 976 | if let Some(dest) = destination.as_mut() { |
| 977 | smsg.msg_name = &mut dest.snl as *mut UdevSocket as *mut _; |
| 978 | } else { |
| 979 | smsg.msg_name = &mut self.snl_destination as *mut UdevSocket as *mut _; |
| 980 | } |
| 981 | |
| 982 | smsg.msg_namelen = mem::size_of::<libc::sockaddr_nl>() as u32; |
| 983 | // SAFETY: call to `sendmsg` is safe because the parameters are properly initialized |
| 984 | // and the pointers reference valid memory. |
| 985 | let count = unsafe { libc::sendmsg(self.sock, &mut smsg as *mut _, 0) }; |
| 986 | |
| 987 | let mon_pid = if let Some(dest) = destination.as_ref() { |
| 988 | dest.snl.pid()? |
| 989 | } else { |
| 990 | self.snl_destination.pid()? |
| 991 | }; |
| 992 | |
| 993 | if count < 0 |
| 994 | && destination.is_none() |
| 995 | && io::Error::last_os_error().raw_os_error() == Some(libc::ECONNREFUSED) |
| 996 | { |
| 997 | log::debug!("passed device to netlink monitor: PID({mon_pid})"); |
| 998 | Ok(0) |
| 999 | } else if count < 0 { |
| 1000 | let errno = io::Error::last_os_error(); |
| 1001 | Err(Error::UdevMonitor(format!("sending device error: {errno}"))) |
| 1002 | } else { |
| 1003 | log::debug!( |
| 1004 | "monitor: passed {count} byte device to netlink monitor: PID({mon_pid})" |
| 1005 | ); |
| 1006 | Ok(count) |
| 1007 | } |
| 1008 | } |
| 1009 | } |
| 1010 | |
| 1011 | /// Adds an [UdevEntry] into the filter subsystem list. |
| 1012 | /// |
| 1013 | /// From `libudev` documentation: |
| 1014 | /// |
| 1015 | /// Parameters: |
| 1016 | /// |
| 1017 | /// - `subsystem`: the subsystem value to match the incoming devices against |
| 1018 | /// - must be non-empty |
| 1019 | /// - `devtype`: the devtype value to match the incoming devices against |
| 1020 | /// |
| 1021 | /// ```no_build,no_run |
| 1022 | /// This filter is efficiently executed inside the kernel, and libudev subscribers |
| 1023 | /// will usually not be woken up for devices which do not match. |
| 1024 | /// |
| 1025 | /// The filter must be installed before the monitor is switched to listening mode. |
| 1026 | /// ``` |
| 1027 | /// |
| 1028 | /// Returns `Ok` on success, `Err` otherwise. |
| 1029 | pub fn filter_add_match_subsystem_devtype( |
| 1030 | &mut self, |
| 1031 | subsystem: &str, |
| 1032 | devtype: &str, |
| 1033 | ) -> Result<&UdevEntry> { |
| 1034 | if subsystem.is_empty() { |
| 1035 | Err(Error::UdevMonitor("empty subsystem filter".into())) |
| 1036 | } else { |
| 1037 | self.filter_subsystem_list |
| 1038 | .add_entry(subsystem, devtype) |
| 1039 | .ok_or(Error::UdevMonitor( |
| 1040 | "unable to add entry to filter subsystem list".into(), |
| 1041 | )) |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | /// Adds an [UdevEntry] into the filter tag list. |
| 1046 | /// |
| 1047 | /// From `libudev` documentation: |
| 1048 | /// |
| 1049 | /// - `tag`: the name of a tag |
| 1050 | /// - must be non-empty |
| 1051 | /// |
| 1052 | /// ```no_build,no_run |
| 1053 | /// This filter is efficiently executed inside the kernel, and libudev subscribers |
| 1054 | /// will usually not be woken up for devices which do not match. |
| 1055 | /// |
| 1056 | /// The filter must be installed before the monitor is switched to listening mode. |
| 1057 | /// ``` |
| 1058 | /// |
| 1059 | /// Returns `Ok` on success, `Err` otherwise. |
| 1060 | pub fn filter_add_match_tag(&mut self, tag: &str) -> Result<&UdevEntry> { |
| 1061 | if tag.is_empty() { |
| 1062 | Err(Error::UdevMonitor("empty tag filter".into())) |
| 1063 | } else { |
| 1064 | self.filter_tag_list |
| 1065 | .add_entry(tag, "") |
| 1066 | .ok_or(Error::UdevMonitor( |
| 1067 | "unable to add entry to filter tag list".into(), |
| 1068 | )) |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | /// Removes all filters from the [UdevMonitor]. |
| 1073 | /// |
| 1074 | /// Returns `Ok(())` on success, `Err(Error)` otherwise. |
| 1075 | pub fn filter_remove(&mut self) -> Result<()> { |
| 1076 | let mut filter = libc::sock_fprog { |
| 1077 | len: 0, |
| 1078 | filter: std::ptr::null_mut(), |
| 1079 | }; |
| 1080 | |
| 1081 | self.filter_subsystem_list.clear(); |
| 1082 | |
| 1083 | // SAFETY: all arguments are valid, and pointers reference valid memory. |
| 1084 | let ret = unsafe { |
| 1085 | libc::setsockopt( |
| 1086 | self.sock, |
| 1087 | libc::SOL_SOCKET, |
| 1088 | libc::SO_ATTACH_FILTER, |
| 1089 | &mut filter as *mut libc::sock_fprog as *mut _, |
| 1090 | mem::size_of::<libc::sock_fprog>() as u32, |
| 1091 | ) |
| 1092 | }; |
| 1093 | |
| 1094 | if ret != 0 { |
| 1095 | let errno = io::Error::last_os_error(); |
| 1096 | Err(Error::UdevMonitor(format!( |
| 1097 | "unable to remove kernel `SO_ATTACH_FILTER`: {ret}, errno: {errno}" |
| 1098 | ))) |
| 1099 | } else { |
| 1100 | Ok(()) |
| 1101 | } |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | fn parse_cmsg(msg_control: &[u8]) -> Result<libc::ucred> { |
| 1106 | let controllen = msg_control.len(); |
| 1107 | let header_len = mem::size_of::<libc::cmsghdr>(); |
| 1108 | let ucred_len = mem::size_of::<libc::ucred>(); |
| 1109 | let msg_control_len = header_len + ucred_len; |
| 1110 | |
| 1111 | let int_len = mem::size_of::<libc::c_int>(); |
| 1112 | let null_int = [0u8; 4]; |
| 1113 | |
| 1114 | match controllen { |
| 1115 | l if l >= msg_control_len => { |
| 1116 | // skip to the `cmsg_type` index of the `cmsghdr` |
| 1117 | let mut idx = int_len * 3; |
| 1118 | |
| 1119 | let cmsg_type = libc::c_int::from_ne_bytes( |
| 1120 | msg_control[idx..idx + int_len] |
| 1121 | .as_ref() |
| 1122 | .try_into() |
| 1123 | .unwrap_or(null_int), |
| 1124 | ); |
| 1125 | |
| 1126 | idx += int_len; |
| 1127 | |
| 1128 | if cmsg_type != libc::SCM_CREDENTIALS { |
| 1129 | let err_msg = "no sender credentials received, message ignored".to_owned(); |
| 1130 | |
| 1131 | log::debug!("{err_msg}"); |
| 1132 | |
| 1133 | Err(Error::UdevMonitor(err_msg)) |
| 1134 | } else { |
| 1135 | let pid = libc::pid_t::from_ne_bytes( |
| 1136 | msg_control[idx..idx + int_len] |
| 1137 | .as_ref() |
| 1138 | .try_into() |
| 1139 | .unwrap_or(null_int), |
| 1140 | ); |
| 1141 | idx += int_len; |
| 1142 | |
| 1143 | let uid = libc::uid_t::from_ne_bytes( |
| 1144 | msg_control[idx..idx + int_len] |
| 1145 | .as_ref() |
| 1146 | .try_into() |
| 1147 | .unwrap_or(null_int), |
| 1148 | ); |
| 1149 | idx += int_len; |
| 1150 | |
| 1151 | let gid = libc::gid_t::from_ne_bytes( |
| 1152 | msg_control[idx..idx + int_len] |
| 1153 | .as_ref() |
| 1154 | .try_into() |
| 1155 | .unwrap_or(null_int), |
| 1156 | ); |
| 1157 | |
| 1158 | Ok(libc::ucred { pid, uid, gid }) |
| 1159 | } |
| 1160 | } |
| 1161 | l if l >= ucred_len => { |
| 1162 | let mut idx = 0; |
| 1163 | |
| 1164 | let pid = libc::pid_t::from_ne_bytes( |
| 1165 | msg_control[idx..idx + int_len] |
| 1166 | .as_ref() |
| 1167 | .try_into() |
| 1168 | .unwrap_or(null_int), |
| 1169 | ); |
| 1170 | idx += int_len; |
| 1171 | |
| 1172 | let uid = libc::uid_t::from_ne_bytes( |
| 1173 | msg_control[idx..idx + int_len] |
| 1174 | .as_ref() |
| 1175 | .try_into() |
| 1176 | .unwrap_or(null_int), |
| 1177 | ); |
| 1178 | idx += int_len; |
| 1179 | |
| 1180 | let gid = libc::gid_t::from_ne_bytes( |
| 1181 | msg_control[idx..idx + int_len] |
| 1182 | .as_ref() |
| 1183 | .try_into() |
| 1184 | .unwrap_or(null_int), |
| 1185 | ); |
| 1186 | |
| 1187 | Ok(libc::ucred { pid, uid, gid }) |
| 1188 | } |
| 1189 | _ => Err(Error::UdevMonitor(format!( |
| 1190 | "msg_controllen ({controllen}) is too small for a cmsghdr" |
| 1191 | ))), |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | /// Represents the netlink group for the [UdevMonitor]. |
| 1196 | #[repr(u32)] |
| 1197 | #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 1198 | pub enum UdevMonitorNetlinkGroup { |
| 1199 | #[default] |
| 1200 | None, |
| 1201 | Kernel, |
| 1202 | Udev, |
| 1203 | } |
| 1204 | |
| 1205 | impl From<&str> for UdevMonitorNetlinkGroup { |
| 1206 | fn from(val: &str) -> Self { |
| 1207 | match val.to_lowercase().as_str() { |
| 1208 | "kernel" => Self::Kernel, |
| 1209 | "udev" => Self::Udev, |
| 1210 | _ => Self::None, |
| 1211 | } |
| 1212 | } |
| 1213 | } |
| 1214 | |
| 1215 | impl From<u32> for UdevMonitorNetlinkGroup { |
| 1216 | fn from(val: u32) -> Self { |
| 1217 | match val { |
| 1218 | 1 => Self::Kernel, |
| 1219 | 2 => Self::Udev, |
| 1220 | _ => Self::None, |
| 1221 | } |
| 1222 | } |
| 1223 | } |
| 1224 | |
| 1225 | impl From<&UdevMonitorNetlinkGroup> for &'static str { |
| 1226 | fn from(val: &UdevMonitorNetlinkGroup) -> Self { |
| 1227 | match val { |
| 1228 | UdevMonitorNetlinkGroup::None => "none", |
| 1229 | UdevMonitorNetlinkGroup::Kernel => "kernel", |
| 1230 | UdevMonitorNetlinkGroup::Udev => "udev", |
| 1231 | } |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | /// Represents a UDEV Netlink header. |
| 1236 | #[repr(C)] |
| 1237 | #[derive(Clone, Copy, Debug, Default, PartialEq)] |
| 1238 | pub struct UdevMonitorNetlinkHeader { |
| 1239 | prefix: [u8; 8], |
| 1240 | magic: u32, |
| 1241 | header_size: u32, |
| 1242 | properties_off: u32, |
| 1243 | properties_len: u32, |
| 1244 | filter_subsystem_hash: u32, |
| 1245 | filter_devtype_hash: u32, |
| 1246 | filter_tag_bloom_hi: u32, |
| 1247 | filter_tag_bloom_lo: u32, |
| 1248 | } |
| 1249 | |
| 1250 | impl UdevMonitorNetlinkHeader { |
| 1251 | /// Creates a new [UdevMonitorNetlinkHeader]. |
| 1252 | pub const fn new() -> Self { |
| 1253 | Self { |
| 1254 | prefix: [b'l', b'i', b'b', b'u', b'd', b'e', b'v', 0], |
| 1255 | magic: UDEV_MONITOR_MAGIC.to_be(), |
| 1256 | header_size: mem::size_of::<Self>() as u32, |
| 1257 | properties_off: 0, |
| 1258 | properties_len: 0, |
| 1259 | filter_subsystem_hash: 0, |
| 1260 | filter_devtype_hash: 0, |
| 1261 | filter_tag_bloom_hi: 0, |
| 1262 | filter_tag_bloom_lo: 0, |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | /// Gets a string representation of the [UdevMonitorNetlinkHeader] prefix. |
| 1267 | pub fn prefix(&self) -> &str { |
| 1268 | std::str::from_utf8(self.prefix.as_ref()).unwrap_or("") |
| 1269 | } |
| 1270 | |
| 1271 | /// Gets the magic bytes. |
| 1272 | pub const fn magic(&self) -> u32 { |
| 1273 | self.magic |
| 1274 | } |
| 1275 | |
| 1276 | /// Gets the total size of the [UdevMonitorNetlinkHeader]. |
| 1277 | pub const fn header_size(&self) -> u32 { |
| 1278 | self.header_size |
| 1279 | } |
| 1280 | |
| 1281 | /// Gets the properties buffer offset. |
| 1282 | pub const fn properties_off(&self) -> u32 { |
| 1283 | self.properties_off |
| 1284 | } |
| 1285 | |
| 1286 | /// Sets the properties buffer offset. |
| 1287 | pub fn set_properties_off(&mut self, val: u32) { |
| 1288 | self.properties_off = val; |
| 1289 | } |
| 1290 | |
| 1291 | /// Builder function that sets the properties buffer offset. |
| 1292 | pub fn with_properties_off(mut self, val: u32) -> Self { |
| 1293 | self.set_properties_off(val); |
| 1294 | self |
| 1295 | } |
| 1296 | |
| 1297 | /// Gets the properties buffer length. |
| 1298 | pub const fn properties_len(&self) -> u32 { |
| 1299 | self.properties_len |
| 1300 | } |
| 1301 | |
| 1302 | /// Sets the properties buffer legnth. |
| 1303 | pub fn set_properties_len(&mut self, val: u32) { |
| 1304 | self.properties_len = val; |
| 1305 | } |
| 1306 | |
| 1307 | /// Builder function that sets the properties buffer length. |
| 1308 | pub fn with_properties_len(mut self, val: u32) -> Self { |
| 1309 | self.set_properties_len(val); |
| 1310 | self |
| 1311 | } |
| 1312 | |
| 1313 | /// Gets the filter subsystem hash. |
| 1314 | pub const fn filter_subsystem_hash(&self) -> u32 { |
| 1315 | self.filter_subsystem_hash |
| 1316 | } |
| 1317 | |
| 1318 | /// Sets the filter subsystem hash. |
| 1319 | pub fn set_filter_subsystem_hash(&mut self, val: u32) { |
| 1320 | self.filter_subsystem_hash = val; |
| 1321 | } |
| 1322 | |
| 1323 | /// Builder function that sets the filter subsystem hash. |
| 1324 | pub fn with_filter_subsystem_hash(mut self, val: u32) -> Self { |
| 1325 | self.set_filter_subsystem_hash(val); |
| 1326 | self |
| 1327 | } |
| 1328 | |
| 1329 | /// Gets the filter devtype hash. |
| 1330 | pub const fn filter_devtype_hash(&self) -> u32 { |
| 1331 | self.filter_devtype_hash |
| 1332 | } |
| 1333 | |
| 1334 | /// Sets the filter devtype hash. |
| 1335 | pub fn set_filter_devtype_hash(&mut self, val: u32) { |
| 1336 | self.filter_devtype_hash = val; |
| 1337 | } |
| 1338 | |
| 1339 | /// Builder function that sets the filter devtype hash. |
| 1340 | pub fn with_filter_devtype_hash(mut self, val: u32) -> Self { |
| 1341 | self.set_filter_devtype_hash(val); |
| 1342 | self |
| 1343 | } |
| 1344 | |
| 1345 | /// Gets the filter tag bloom hash high bits. |
| 1346 | pub const fn filter_tag_bloom_hi(&self) -> u32 { |
| 1347 | self.filter_tag_bloom_hi |
| 1348 | } |
| 1349 | |
| 1350 | /// Sets the filter tag bloom hash high bits. |
| 1351 | pub fn set_filter_tag_bloom_hi(&mut self, val: u32) { |
| 1352 | self.filter_tag_bloom_hi = val; |
| 1353 | } |
| 1354 | |
| 1355 | /// Builder function that sets the filter tag bloom hash high bits. |
| 1356 | pub fn with_filter_tag_bloom_hi(mut self, val: u32) -> Self { |
| 1357 | self.set_filter_tag_bloom_hi(val); |
| 1358 | self |
| 1359 | } |
| 1360 | |
| 1361 | /// Gets the filter tag bloom hash low bits. |
| 1362 | pub const fn filter_tag_bloom_lo(&self) -> u32 { |
| 1363 | self.filter_tag_bloom_lo |
| 1364 | } |
| 1365 | |
| 1366 | /// Sets the filter tag bloom hash low bits. |
| 1367 | pub fn set_filter_tag_bloom_lo(&mut self, val: u32) { |
| 1368 | self.filter_tag_bloom_lo = val; |
| 1369 | } |
| 1370 | |
| 1371 | /// Builder function that sets the filter tag bloom hash low bits. |
| 1372 | pub fn with_filter_tag_bloom_lo(mut self, val: u32) -> Self { |
| 1373 | self.set_filter_tag_bloom_lo(val); |
| 1374 | self |
| 1375 | } |
| 1376 | |
| 1377 | /// `prefix` field offset. |
| 1378 | pub const fn prefix_offset() -> usize { |
| 1379 | 0 |
| 1380 | } |
| 1381 | |
| 1382 | /// `magic` field offset. |
| 1383 | pub const fn magic_offset() -> usize { |
| 1384 | 8 |
| 1385 | } |
| 1386 | |
| 1387 | /// `header_size` field offset. |
| 1388 | pub const fn header_size_offset() -> usize { |
| 1389 | 12 |
| 1390 | } |
| 1391 | |
| 1392 | /// `properties_off` field offset. |
| 1393 | pub const fn properties_off_offset() -> usize { |
| 1394 | 16 |
| 1395 | } |
| 1396 | |
| 1397 | /// `properties_len` field offset. |
| 1398 | pub const fn properties_len_offset() -> usize { |
| 1399 | 20 |
| 1400 | } |
| 1401 | |
| 1402 | /// `filter_subsystem_hash` field offset. |
| 1403 | pub const fn filter_subsystem_hash_offset() -> usize { |
| 1404 | 24 |
| 1405 | } |
| 1406 | |
| 1407 | /// `filter_devtype_hash` field offset. |
| 1408 | pub const fn filter_devtype_hash_offset() -> usize { |
| 1409 | 28 |
| 1410 | } |
| 1411 | |
| 1412 | /// `filter_tag_bloom_hi` field offset. |
| 1413 | pub const fn filter_tag_bloom_hi_offset() -> usize { |
| 1414 | 32 |
| 1415 | } |
| 1416 | |
| 1417 | /// `filter_tag_bloom_lo` field offset. |
| 1418 | pub const fn filter_tag_bloom_lo_offset() -> usize { |
| 1419 | 36 |
| 1420 | } |
| 1421 | } |
| 1422 | |
| 1423 | impl TryFrom<&[u8]> for UdevMonitorNetlinkHeader { |
| 1424 | type Error = Error; |
| 1425 | |
| 1426 | fn try_from(val: &[u8]) -> Result<Self> { |
| 1427 | let len = val.len(); |
| 1428 | let hdr_len = mem::size_of::<Self>(); |
| 1429 | if len < hdr_len { |
| 1430 | Err(Error::UdevMonitor(format!( |
| 1431 | "invalid buffer length: {len}, expected at least: {hdr_len}" |
| 1432 | ))) |
| 1433 | } else if &val[..8] != b"libudev\0".as_ref() { |
| 1434 | Err(Error::UdevMonitor( |
| 1435 | "invalid monitor netlink prefix, expected: 'libudev'".into(), |
| 1436 | )) |
| 1437 | } else { |
| 1438 | let mut idx = 0; |
| 1439 | |
| 1440 | let prefix: [u8; 8] = val[idx..idx + 8].try_into()?; |
| 1441 | idx += prefix.len(); |
| 1442 | |
| 1443 | let magic = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1444 | idx += mem::size_of::<u32>(); |
| 1445 | |
| 1446 | let header_size = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1447 | idx += mem::size_of::<u32>(); |
| 1448 | |
| 1449 | let properties_off = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1450 | idx += mem::size_of::<u32>(); |
| 1451 | |
| 1452 | let properties_len = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1453 | idx += mem::size_of::<u32>(); |
| 1454 | |
| 1455 | let filter_subsystem_hash = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1456 | idx += mem::size_of::<u32>(); |
| 1457 | |
| 1458 | let filter_devtype_hash = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1459 | idx += mem::size_of::<u32>(); |
| 1460 | |
| 1461 | let filter_tag_bloom_hi = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1462 | idx += mem::size_of::<u32>(); |
| 1463 | |
| 1464 | let filter_tag_bloom_lo = u32::from_le_bytes(val[idx..idx + 4].try_into()?); |
| 1465 | |
| 1466 | if magic != UDEV_MONITOR_MAGIC { |
| 1467 | let err_msg = format!( |
| 1468 | "UDEV magic bytes do not match, expected: {UDEV_MONITOR_MAGIC:#x}, have: {magic:#x}" |
| 1469 | ); |
| 1470 | log::error!("{err_msg}"); |
| 1471 | Err(Error::UdevMonitor(err_msg)) |
| 1472 | } else { |
| 1473 | Ok(Self { |
| 1474 | prefix, |
| 1475 | magic, |
| 1476 | header_size, |
| 1477 | properties_off, |
| 1478 | properties_len, |
| 1479 | filter_subsystem_hash, |
| 1480 | filter_devtype_hash, |
| 1481 | filter_tag_bloom_hi, |
| 1482 | filter_tag_bloom_lo, |
| 1483 | }) |
| 1484 | } |
| 1485 | } |
| 1486 | } |
| 1487 | } |