| 1 | //! Lookup and sort `sys` devices. |
| 2 | //! |
| 3 | //! Lookup devices in the `sys` filesystem, filter devices by properties, |
| 4 | //! and return a sorted list of devices. |
| 5 | //! |
| 6 | //! From [`libudev-enumerate`](https://github.com/eudev-project/eudev/blob/master/src/libudev/libudev-enumerate.c) documentation. |
| 7 | |
| 8 | use std::{fs, sync::Arc}; |
| 9 | |
| 10 | use crate::util; |
| 11 | use crate::UDEV_ROOT_RUN; |
| 12 | use crate::{Error, Result, Udev, UdevDevice, UdevEntry, UdevEntryList, UdevList}; |
| 13 | |
| 14 | const LOG_PREFIX: &str = "udev enumerate:"; |
| 15 | |
| 16 | /// Represents the file path in the `sys` filesystem. |
| 17 | #[repr(C)] |
| 18 | #[derive(Clone, Debug, Default, PartialEq)] |
| 19 | pub struct Syspath { |
| 20 | syspath: String, |
| 21 | } |
| 22 | |
| 23 | impl Syspath { |
| 24 | /// Creates a new [Syspath]. |
| 25 | pub const fn new() -> Self { |
| 26 | Self { |
| 27 | syspath: String::new(), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /// Gets a reference to the syspath string. |
| 32 | pub fn syspath(&self) -> &str { |
| 33 | self.syspath.as_str() |
| 34 | } |
| 35 | |
| 36 | /// Sets the syspath. |
| 37 | pub fn set_syspath<S: Into<String>>(&mut self, syspath: S) { |
| 38 | self.syspath = syspath.into(); |
| 39 | } |
| 40 | |
| 41 | /// Builder function that sets the syspath. |
| 42 | pub fn with_syspath<S: Into<String>>(mut self, syspath: S) -> Self { |
| 43 | self.set_syspath(syspath); |
| 44 | self |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | /// Represents one device lookup/sort context.. |
| 49 | #[repr(C)] |
| 50 | #[derive(Clone, Debug, Default, PartialEq)] |
| 51 | pub struct UdevEnumerate { |
| 52 | udev: Arc<Udev>, |
| 53 | sysattr_match_list: UdevList, |
| 54 | sysattr_nomatch_list: UdevList, |
| 55 | subsystem_match_list: UdevList, |
| 56 | subsystem_nomatch_list: UdevList, |
| 57 | sysname_match_list: UdevList, |
| 58 | properties_match_list: UdevList, |
| 59 | tags_match_list: UdevList, |
| 60 | devices_list: UdevList, |
| 61 | parent: Option<Arc<UdevDevice>>, |
| 62 | devices: Vec<Syspath>, |
| 63 | devices_cur: usize, |
| 64 | devices_max: usize, |
| 65 | devices_uptodate: bool, |
| 66 | match_is_initialized: bool, |
| 67 | } |
| 68 | |
| 69 | impl UdevEnumerate { |
| 70 | /// Creates a new [UdevEnumerate]. |
| 71 | pub fn new(udev: Arc<Udev>) -> Self { |
| 72 | let sysattr_match_list = UdevList::new(Arc::clone(&udev)); |
| 73 | let sysattr_nomatch_list = UdevList::new(Arc::clone(&udev)); |
| 74 | let subsystem_match_list = UdevList::new(Arc::clone(&udev)); |
| 75 | let subsystem_nomatch_list = UdevList::new(Arc::clone(&udev)); |
| 76 | let sysname_match_list = UdevList::new(Arc::clone(&udev)); |
| 77 | let properties_match_list = UdevList::new(Arc::clone(&udev)); |
| 78 | let tags_match_list = UdevList::new(Arc::clone(&udev)); |
| 79 | let devices_list = UdevList::new(Arc::clone(&udev)); |
| 80 | |
| 81 | Self { |
| 82 | udev, |
| 83 | sysattr_match_list, |
| 84 | sysattr_nomatch_list, |
| 85 | subsystem_match_list, |
| 86 | subsystem_nomatch_list, |
| 87 | sysname_match_list, |
| 88 | properties_match_list, |
| 89 | tags_match_list, |
| 90 | devices_list, |
| 91 | parent: None, |
| 92 | devices: Vec::new(), |
| 93 | devices_cur: 0, |
| 94 | devices_max: 0, |
| 95 | devices_uptodate: false, |
| 96 | match_is_initialized: false, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// Gets a reference to the [Udev] object. |
| 101 | pub fn udev(&self) -> &Arc<Udev> { |
| 102 | &self.udev |
| 103 | } |
| 104 | |
| 105 | /// Gets a reference to the sysattr match list [UdevList]. |
| 106 | pub const fn sysattr_match_list(&self) -> &UdevList { |
| 107 | &self.sysattr_match_list |
| 108 | } |
| 109 | |
| 110 | /// Gets a mutable reference to the sysattr match list [UdevList]. |
| 111 | pub fn sysattr_match_list_mut(&mut self) -> &mut UdevList { |
| 112 | &mut self.sysattr_match_list |
| 113 | } |
| 114 | |
| 115 | /// Sets the sysattr match list [UdevList]. |
| 116 | pub fn set_sysattr_match_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 117 | self.sysattr_match_list.set_list(list); |
| 118 | } |
| 119 | |
| 120 | /// Builder function that sets the sysattr match list [UdevList]. |
| 121 | pub fn with_sysattr_match_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 122 | self.set_sysattr_match_list(list); |
| 123 | self |
| 124 | } |
| 125 | |
| 126 | /// Adds an entry to the match sysattr [UdevEntry] list. |
| 127 | /// |
| 128 | /// From the `libudev` documentation: |
| 129 | /// |
| 130 | /// ```no_build,no_run |
| 131 | /// Match only devices with a given /sys device attribute. |
| 132 | /// ``` |
| 133 | /// |
| 134 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 135 | pub fn add_match_sysattr(&mut self, sysattr: &str) -> Result<&UdevEntry> { |
| 136 | if sysattr.is_empty() { |
| 137 | Err(Error::UdevEnumerate("sysattr is null".into())) |
| 138 | } else { |
| 139 | self.sysattr_match_list |
| 140 | .add_entry(sysattr, "") |
| 141 | .ok_or(Error::UdevEnumerate( |
| 142 | "unable to add match sysattr entry".into(), |
| 143 | )) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | /// Gets a reference to the sysattr nomatch list [UdevList]. |
| 148 | pub const fn sysattr_nomatch_list(&self) -> &UdevList { |
| 149 | &self.sysattr_nomatch_list |
| 150 | } |
| 151 | |
| 152 | /// Gets a mutable reference to the sysattr nomatch list [UdevList]. |
| 153 | pub fn sysattr_nomatch_list_mut(&mut self) -> &mut UdevList { |
| 154 | &mut self.sysattr_nomatch_list |
| 155 | } |
| 156 | |
| 157 | /// Sets the sysattr nomatch list [UdevList]. |
| 158 | pub fn set_sysattr_nomatch_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 159 | self.sysattr_nomatch_list.set_list(list); |
| 160 | } |
| 161 | |
| 162 | /// Builder function that sets the sysattr nomatch list [UdevList]. |
| 163 | pub fn with_sysattr_nomatch_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 164 | self.set_sysattr_nomatch_list(list); |
| 165 | self |
| 166 | } |
| 167 | |
| 168 | /// Adds an entry to the no-match sysattr [UdevEntry] list. |
| 169 | /// |
| 170 | /// From the `libudev` documentation: |
| 171 | /// |
| 172 | /// ```no_build,no_run |
| 173 | /// Match only devices without a given /sys device attribute. |
| 174 | /// ``` |
| 175 | /// |
| 176 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 177 | pub fn add_nomatch_sysattr(&mut self, sysattr: &str) -> Result<&UdevEntry> { |
| 178 | if sysattr.is_empty() { |
| 179 | Err(Error::UdevEnumerate("sysattr is null".into())) |
| 180 | } else { |
| 181 | self.sysattr_nomatch_list |
| 182 | .add_entry(sysattr, "") |
| 183 | .ok_or(Error::UdevEnumerate( |
| 184 | "unable to add no-match sysattr entry".into(), |
| 185 | )) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Gets a reference to the subsystem match list [UdevList]. |
| 190 | pub const fn subsystem_match_list(&self) -> &UdevList { |
| 191 | &self.subsystem_match_list |
| 192 | } |
| 193 | |
| 194 | /// Gets a mutable reference to the subsystem match list [UdevList]. |
| 195 | pub fn subsystem_match_list_mut(&mut self) -> &mut UdevList { |
| 196 | &mut self.subsystem_match_list |
| 197 | } |
| 198 | |
| 199 | /// Sets the subsystem match list [UdevList]. |
| 200 | pub fn set_subsystem_match_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 201 | self.subsystem_match_list.set_list(list); |
| 202 | } |
| 203 | |
| 204 | /// Builder function that sets the subsystem match list [UdevList]. |
| 205 | pub fn with_subsystem_match_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 206 | self.set_subsystem_match_list(list); |
| 207 | self |
| 208 | } |
| 209 | |
| 210 | /// Adds an entry to the match subsystem [UdevEntry] list. |
| 211 | /// |
| 212 | /// From the `libudev` documentation: |
| 213 | /// |
| 214 | /// ```no_build,no_run |
| 215 | /// Match only devices belonging to a certain kernel subsystem. |
| 216 | /// ``` |
| 217 | /// |
| 218 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 219 | pub fn add_match_subsystem(&mut self, subsystem: &str) -> Result<&UdevEntry> { |
| 220 | if subsystem.is_empty() { |
| 221 | Err(Error::UdevEnumerate("subsystem is null".into())) |
| 222 | } else { |
| 223 | self.subsystem_match_list |
| 224 | .add_entry(subsystem, "") |
| 225 | .ok_or(Error::UdevEnumerate( |
| 226 | "unable to add match subsystem entry".into(), |
| 227 | )) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | /// Gets a reference to the subsystem nomatch list [UdevList]. |
| 232 | pub const fn subsystem_nomatch_list(&self) -> &UdevList { |
| 233 | &self.subsystem_nomatch_list |
| 234 | } |
| 235 | |
| 236 | /// Gets a mutable reference to the subsystem nomatch list [UdevList]. |
| 237 | pub fn subsystem_nomatch_list_mut(&mut self) -> &mut UdevList { |
| 238 | &mut self.subsystem_nomatch_list |
| 239 | } |
| 240 | |
| 241 | /// Sets the subsystem nomatch list [UdevList]. |
| 242 | pub fn set_subsystem_nomatch_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 243 | self.subsystem_nomatch_list.set_list(list); |
| 244 | } |
| 245 | |
| 246 | /// Builder function that sets the subsystem nomatch list [UdevList]. |
| 247 | pub fn with_subsystem_nomatch_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 248 | self.set_subsystem_nomatch_list(list); |
| 249 | self |
| 250 | } |
| 251 | |
| 252 | /// Adds an entry to the no-match subsystem [UdevEntry] list. |
| 253 | /// |
| 254 | /// From the `libudev` documentation: |
| 255 | /// |
| 256 | /// ```no_build,no_run |
| 257 | /// Match only devices not belonging to a certain kernel subsystem. |
| 258 | /// ``` |
| 259 | /// |
| 260 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 261 | pub fn add_nomatch_subsystem(&mut self, subsystem: &str) -> Result<&UdevEntry> { |
| 262 | if subsystem.is_empty() { |
| 263 | Err(Error::UdevEnumerate("subsystem is null".into())) |
| 264 | } else { |
| 265 | self.subsystem_nomatch_list |
| 266 | .add_entry(subsystem, "") |
| 267 | .ok_or(Error::UdevEnumerate( |
| 268 | "unable to add no-match subsystem entry".into(), |
| 269 | )) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Gets a reference to the sysname match list [UdevList]. |
| 274 | pub const fn sysname_match_list(&self) -> &UdevList { |
| 275 | &self.sysname_match_list |
| 276 | } |
| 277 | |
| 278 | /// Gets a mutable reference to the sysname match list [UdevList]. |
| 279 | pub fn sysname_match_list_mut(&mut self) -> &mut UdevList { |
| 280 | &mut self.sysname_match_list |
| 281 | } |
| 282 | |
| 283 | /// Sets the sysname match list [UdevList]. |
| 284 | pub fn set_sysname_match_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 285 | self.sysname_match_list.set_list(list); |
| 286 | } |
| 287 | |
| 288 | /// Builder function that sets the sysname match list [UdevList]. |
| 289 | pub fn with_sysname_match_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 290 | self.set_sysname_match_list(list); |
| 291 | self |
| 292 | } |
| 293 | |
| 294 | /// Adds an entry to the match sysname [UdevEntry] list. |
| 295 | /// |
| 296 | /// From the `libudev` documentation: |
| 297 | /// |
| 298 | /// ```no_build,no_run |
| 299 | /// Match only devices with a given /sys device name. |
| 300 | /// ``` |
| 301 | /// |
| 302 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 303 | pub fn add_match_sysname(&mut self, sysname: &str) -> Result<&UdevEntry> { |
| 304 | if sysname.is_empty() { |
| 305 | Err(Error::UdevEnumerate("sysname is null".into())) |
| 306 | } else { |
| 307 | self.sysname_match_list |
| 308 | .add_entry(sysname, "") |
| 309 | .ok_or(Error::UdevEnumerate( |
| 310 | "unable to add match sysname entry".into(), |
| 311 | )) |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | /// Gets a reference to the properties match list [UdevList]. |
| 316 | pub const fn properties_match_list(&self) -> &UdevList { |
| 317 | &self.properties_match_list |
| 318 | } |
| 319 | |
| 320 | /// Gets a mutable reference to the properties match list [UdevList]. |
| 321 | pub fn properties_match_list_mut(&mut self) -> &mut UdevList { |
| 322 | &mut self.properties_match_list |
| 323 | } |
| 324 | |
| 325 | /// Sets the properties match list [UdevList]. |
| 326 | pub fn set_properties_match_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 327 | self.properties_match_list.set_list(list); |
| 328 | } |
| 329 | |
| 330 | /// Builder function that sets the properties match list [UdevList]. |
| 331 | pub fn with_properties_match_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 332 | self.set_properties_match_list(list); |
| 333 | self |
| 334 | } |
| 335 | |
| 336 | /// Adds an entry to the match properties [UdevEntry] list. |
| 337 | /// |
| 338 | /// From the `libudev` documentation: |
| 339 | /// |
| 340 | /// ```no_build,no_run |
| 341 | /// Match only devices with a certain property. |
| 342 | /// ``` |
| 343 | /// |
| 344 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 345 | pub fn add_match_property(&mut self, property: &str, value: &str) -> Result<&UdevEntry> { |
| 346 | if property.is_empty() { |
| 347 | Err(Error::UdevEnumerate("property is null".into())) |
| 348 | } else { |
| 349 | self.properties_match_list |
| 350 | .add_entry(property, value) |
| 351 | .ok_or(Error::UdevEnumerate( |
| 352 | "unable to add match property entry".into(), |
| 353 | )) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// Gets a reference to the tags match list [UdevList]. |
| 358 | pub const fn tags_match_list(&self) -> &UdevList { |
| 359 | &self.tags_match_list |
| 360 | } |
| 361 | |
| 362 | /// Gets a mutable reference to the tags match list [UdevList]. |
| 363 | pub fn tags_match_list_mut(&mut self) -> &mut UdevList { |
| 364 | &mut self.tags_match_list |
| 365 | } |
| 366 | |
| 367 | /// Sets the tags match list [UdevList]. |
| 368 | pub fn set_tags_match_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 369 | self.tags_match_list.set_list(list); |
| 370 | } |
| 371 | |
| 372 | /// Builder function that sets the tags match list [UdevList]. |
| 373 | pub fn with_tags_match_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 374 | self.set_tags_match_list(list); |
| 375 | self |
| 376 | } |
| 377 | |
| 378 | /// Adds an entry to the match tags [UdevEntry] list. |
| 379 | /// |
| 380 | /// From the `libudev` documentation: |
| 381 | /// |
| 382 | /// ```no_build,no_run |
| 383 | /// Match only devices with a certain tag. |
| 384 | /// ``` |
| 385 | /// |
| 386 | /// Returns `Ok(UdevEntry)` on success, `Err(Error)` otherwise. |
| 387 | pub fn add_match_tag(&mut self, tag: &str) -> Result<&UdevEntry> { |
| 388 | if tag.is_empty() { |
| 389 | Err(Error::UdevEnumerate("tag is null".into())) |
| 390 | } else { |
| 391 | self.tags_match_list |
| 392 | .add_entry(tag, "") |
| 393 | .ok_or(Error::UdevEnumerate("unable to add match tag entry".into())) |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | /// Gets a reference to the devices list [UdevList]. |
| 398 | pub const fn devices_list(&self) -> &UdevList { |
| 399 | &self.devices_list |
| 400 | } |
| 401 | |
| 402 | /// Gets a mutable reference to the devices list [UdevList]. |
| 403 | pub fn devices_list_mut(&mut self) -> &mut UdevList { |
| 404 | &mut self.devices_list |
| 405 | } |
| 406 | |
| 407 | /// Sets the devices list [UdevList]. |
| 408 | pub fn set_devices_list<L: Into<UdevEntryList>>(&mut self, list: L) { |
| 409 | self.devices_list.set_list(list); |
| 410 | } |
| 411 | |
| 412 | /// Builder function that sets the devices list [UdevList]. |
| 413 | pub fn with_devices_list<L: Into<UdevEntryList>>(mut self, list: L) -> Self { |
| 414 | self.set_devices_list(list); |
| 415 | self |
| 416 | } |
| 417 | |
| 418 | /// Gets an optional reference to the parent [UdevDevice]. |
| 419 | pub fn parent(&self) -> Option<&Arc<UdevDevice>> { |
| 420 | self.parent.as_ref() |
| 421 | } |
| 422 | |
| 423 | /// Sets the parent [UdevDevice]. |
| 424 | pub fn set_parent(&mut self, parent: Arc<UdevDevice>) { |
| 425 | self.parent.replace(parent); |
| 426 | } |
| 427 | |
| 428 | /// Builder function that sets the parent [UdevDevice]. |
| 429 | pub fn with_parent(mut self, parent: Arc<UdevDevice>) -> Self { |
| 430 | self.set_parent(parent); |
| 431 | self |
| 432 | } |
| 433 | |
| 434 | /// Gets a reference to the [Syspath] devices list. |
| 435 | pub fn devices(&self) -> &[Syspath] { |
| 436 | self.devices.as_ref() |
| 437 | } |
| 438 | |
| 439 | /// Sets the [Syspath] devices list. |
| 440 | pub fn set_devices<S: IntoIterator<Item = Syspath>>(&mut self, devices: S) { |
| 441 | self.devices = devices.into_iter().collect(); |
| 442 | } |
| 443 | |
| 444 | /// Builder function that sets the [Syspath] devices list. |
| 445 | pub fn with_devices<S: IntoIterator<Item = Syspath>>(mut self, devices: S) -> Self { |
| 446 | self.set_devices(devices); |
| 447 | self |
| 448 | } |
| 449 | |
| 450 | /// Gets the current index into the [Syspath] devices list. |
| 451 | pub const fn devices_cur(&self) -> usize { |
| 452 | self.devices_cur |
| 453 | } |
| 454 | |
| 455 | /// Sets the current index into the [Syspath] devices list. |
| 456 | /// |
| 457 | /// **NOTE**: `cur` must be in-bounds to set the current index, otherwise this function is a |
| 458 | /// no-op. |
| 459 | pub fn set_devices_cur(&mut self, cur: usize) { |
| 460 | if cur < self.devices.len() { |
| 461 | self.devices_cur = cur; |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | /// Builder function that sets the current index into the [Syspath] devices list. |
| 466 | /// |
| 467 | /// **NOTE**: `cur` must be in-bounds to set the current index, otherwise this function is a |
| 468 | /// no-op. |
| 469 | pub fn with_devices_cur(mut self, cur: usize) -> Self { |
| 470 | self.set_devices_cur(cur); |
| 471 | self |
| 472 | } |
| 473 | |
| 474 | /// Gets the maximum number of [Syspath] devices. |
| 475 | pub const fn devices_max(&self) -> usize { |
| 476 | self.devices_max |
| 477 | } |
| 478 | |
| 479 | /// Sets the maximum number of [Syspath] devices. |
| 480 | /// |
| 481 | /// **NOTE** if `max` is greater than the current [Syspath] devices list capacity, |
| 482 | /// additional space will be reserved to avoid frequent reallocations. |
| 483 | pub fn set_devices_max(&mut self, max: usize) { |
| 484 | self.devices_max = max; |
| 485 | let cap = self.devices.capacity(); |
| 486 | self.devices.reserve(self.devices_max.saturating_sub(cap)); |
| 487 | } |
| 488 | |
| 489 | /// Builder function that sets the maximum number of [Syspath] devices. |
| 490 | /// |
| 491 | /// **NOTE** if `max` is greater than the current [Syspath] devices list capacity, |
| 492 | /// additional space will be reserved to avoid frequent reallocations. |
| 493 | pub fn with_devices_max(mut self, max: usize) -> Self { |
| 494 | self.set_devices_max(max); |
| 495 | self |
| 496 | } |
| 497 | |
| 498 | /// Gets whether the [Syspath] devices list is up-to-date. |
| 499 | pub const fn devices_uptodate(&self) -> bool { |
| 500 | self.devices_uptodate |
| 501 | } |
| 502 | |
| 503 | /// Sets whether the [Syspath] devices list is up-to-date. |
| 504 | pub fn set_devices_uptodate(&mut self, val: bool) { |
| 505 | self.devices_uptodate = val; |
| 506 | } |
| 507 | |
| 508 | /// Builder function that sets whether the [Syspath] devices list is up-to-date. |
| 509 | pub fn with_devices_uptodate(mut self, val: bool) -> Self { |
| 510 | self.set_devices_uptodate(val); |
| 511 | self |
| 512 | } |
| 513 | |
| 514 | /// Gets whether the match lists are initialized. |
| 515 | pub const fn match_is_initialized(&self) -> bool { |
| 516 | self.match_is_initialized |
| 517 | } |
| 518 | |
| 519 | /// Sets whether the match lists are initialized. |
| 520 | pub fn set_match_is_initialized(&mut self, val: bool) { |
| 521 | self.match_is_initialized = val; |
| 522 | } |
| 523 | |
| 524 | /// Builder function that sets whether the match lists are initialized. |
| 525 | pub fn with_match_is_initialized(mut self, val: bool) -> Self { |
| 526 | self.set_match_is_initialized(val); |
| 527 | self |
| 528 | } |
| 529 | |
| 530 | /// Adds a devices to the list of devices. |
| 531 | /// |
| 532 | /// From the `libudev` documentation: |
| 533 | /// |
| 534 | /// ```no_build,no_run |
| 535 | /// Add a device to the list of devices, to retrieve it back sorted in dependency order. |
| 536 | /// ``` |
| 537 | /// |
| 538 | /// Returns: `Ok(())` on success, `Err(Error)` otherwise. |
| 539 | pub fn add_syspath(&mut self, syspath: &str) -> Result<()> { |
| 540 | if syspath.is_empty() { |
| 541 | Err(Error::UdevEnumerate("empty syspath".into())) |
| 542 | } else { |
| 543 | let dev = UdevDevice::new_from_syspath(Arc::clone(&self.udev), syspath)?; |
| 544 | self.syspath_add(dev.syspath()) |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | fn syspath_add(&mut self, syspath: &str) -> Result<()> { |
| 549 | if self.devices_cur >= self.devices_max { |
| 550 | self.devices_max = self.devices_max.saturating_add(1024); |
| 551 | self.devices.reserve(1024); |
| 552 | } |
| 553 | |
| 554 | self.devices.push(Syspath::new().with_syspath(syspath)); |
| 555 | |
| 556 | self.devices_cur = self.devices_cur.saturating_add(1); |
| 557 | self.devices_uptodate = false; |
| 558 | |
| 559 | Ok(()) |
| 560 | } |
| 561 | |
| 562 | /// Scan `/sys` for devices which match the given filters. |
| 563 | /// |
| 564 | /// From the `libudev` documentation: |
| 565 | /// |
| 566 | /// ```no_build,no_run |
| 567 | /// Scan /sys for all devices which match the given filters. No matches |
| 568 | /// will return all currently available devices. |
| 569 | /// ``` |
| 570 | /// |
| 571 | /// Returns: `Ok(())` on success, `Err(Error)` otherwise. |
| 572 | pub fn scan_devices(&mut self) -> Result<()> { |
| 573 | if self.tags_match_list.entry().is_some() { |
| 574 | self.scan_devices_tags() |
| 575 | } else if self.parent.is_some() { |
| 576 | self.scan_devices_children() |
| 577 | } else { |
| 578 | self.scan_devices_all() |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | fn scan_devices_tags(&mut self) -> Result<()> { |
| 583 | // scan only tagged devices. |
| 584 | // use tags reverse-index, instead of searching all deivces in /sys |
| 585 | let mut add_syspaths: Vec<String> = Vec::new(); |
| 586 | |
| 587 | for list_entry in self.tags_match_list.iter() { |
| 588 | let tag_name = list_entry.name(); |
| 589 | let path = format!("{UDEV_ROOT_RUN}/udev/tags/{tag_name}"); |
| 590 | |
| 591 | for dir_entry in fs::read_dir(path.as_str()) |
| 592 | .map_err(|err| Error::UdevEnumerate(format!("unable to open tags path: {err}")))? |
| 593 | .filter(|e| e.is_ok()) |
| 594 | { |
| 595 | let d_name = dir_entry? |
| 596 | .file_name() |
| 597 | .into_string() |
| 598 | .unwrap_or(String::new()); |
| 599 | if d_name.is_empty() { |
| 600 | log::trace!("{LOG_PREFIX} empty/invalid entry"); |
| 601 | } else if d_name.starts_with('.') { |
| 602 | log::trace!("{LOG_PREFIX} private entry"); |
| 603 | } else { |
| 604 | let mut dev = |
| 605 | UdevDevice::new_from_device_id(Arc::clone(&self.udev), d_name.as_str())?; |
| 606 | let dev_syspath = dev.syspath().to_owned(); |
| 607 | |
| 608 | if !self.match_subsystem(dev.subsystem()) { |
| 609 | log::trace!("{LOG_PREFIX} no subsystem match"); |
| 610 | } else if !self.match_sysname(dev.sysname()) { |
| 611 | log::trace!("{LOG_PREFIX} no sysname match"); |
| 612 | } else if !self.match_parent(&dev) { |
| 613 | log::trace!("{LOG_PREFIX} no parent match"); |
| 614 | } else if !self.match_property(&dev) { |
| 615 | log::trace!("{LOG_PREFIX} no property match"); |
| 616 | } else if !self.match_sysattr(&mut dev) { |
| 617 | log::trace!("{LOG_PREFIX} no sys attribute match"); |
| 618 | } else { |
| 619 | add_syspaths.push(dev_syspath); |
| 620 | } |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | for path in add_syspaths.iter() { |
| 626 | self.syspath_add(path)?; |
| 627 | } |
| 628 | |
| 629 | Ok(()) |
| 630 | } |
| 631 | |
| 632 | fn match_subsystem(&self, subsystem: &str) -> bool { |
| 633 | !subsystem.is_empty() |
| 634 | && !self |
| 635 | .subsystem_nomatch_list |
| 636 | .iter() |
| 637 | .any(|f| f.name() == subsystem) |
| 638 | && (self.subsystem_match_list.is_empty() |
| 639 | || self |
| 640 | .subsystem_match_list |
| 641 | .iter() |
| 642 | .any(|f| f.name() == subsystem)) |
| 643 | } |
| 644 | |
| 645 | fn match_sysname(&self, sysname: &str) -> bool { |
| 646 | !sysname.is_empty() |
| 647 | && (self.sysname_match_list.is_empty() |
| 648 | || self.sysname_match_list.iter().any(|f| f.name() == sysname)) |
| 649 | } |
| 650 | |
| 651 | fn match_parent(&self, dev: &UdevDevice) -> bool { |
| 652 | match self.parent.as_ref() { |
| 653 | Some(parent) => dev.devpath().starts_with(parent.devpath()), |
| 654 | None => true, |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | fn match_tag(&self, dev: &mut UdevDevice) -> bool { |
| 659 | // no match always matches |
| 660 | self.tags_match_list.is_empty() || |
| 661 | // loop over matches |
| 662 | // if any tag is a mismatch, return false |
| 663 | self.tags_match_list.iter().filter(|f| !dev.has_tag(f.name())).count() == 0 |
| 664 | } |
| 665 | |
| 666 | fn match_property(&self, dev: &UdevDevice) -> bool { |
| 667 | if self.properties_match_list.is_empty() { |
| 668 | true |
| 669 | } else { |
| 670 | let mut ret = false; |
| 671 | for list_entry in self.properties_match_list.iter() { |
| 672 | let match_key = list_entry.name(); |
| 673 | let match_value = list_entry.value(); |
| 674 | |
| 675 | for property_entry in dev.properties_list().iter() { |
| 676 | let dev_key = property_entry.name(); |
| 677 | let dev_value = property_entry.value(); |
| 678 | |
| 679 | if let Ok(key_pattern) = glob::Pattern::new(match_key) { |
| 680 | if !key_pattern.matches(dev_key) { |
| 681 | log::trace!( |
| 682 | "no key match found, entry key: {match_key}, device key {dev_key}" |
| 683 | ); |
| 684 | } else if match_value.is_empty() && dev_value.is_empty() { |
| 685 | ret = true; |
| 686 | break; |
| 687 | } else if let Ok(val_pattern) = glob::Pattern::new(match_value) { |
| 688 | if val_pattern.matches(dev_value) { |
| 689 | ret = true; |
| 690 | break; |
| 691 | } |
| 692 | } else { |
| 693 | log::trace!("no value match found, entry value: {match_value}, device value: {dev_value}"); |
| 694 | } |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | if ret { |
| 699 | break; |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | ret |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | fn match_sysattr(&self, dev: &mut UdevDevice) -> bool { |
| 708 | !self |
| 709 | .sysattr_nomatch_list |
| 710 | .iter() |
| 711 | .any(|f| dev.match_sysattr_value(f.name(), f.value())) |
| 712 | && self |
| 713 | .sysattr_match_list |
| 714 | .iter() |
| 715 | .filter(|f| !dev.match_sysattr_value(f.name(), f.value())) |
| 716 | .count() |
| 717 | == 0 |
| 718 | && self |
| 719 | .sysattr_match_list |
| 720 | .iter() |
| 721 | .any(|f| dev.match_sysattr_value(f.name(), f.value())) |
| 722 | } |
| 723 | |
| 724 | fn scan_devices_children(&mut self) -> Result<()> { |
| 725 | Err(Error::UdevEnumerate("unimplemented".into())) |
| 726 | } |
| 727 | |
| 728 | fn scan_devices_all(&mut self) -> Result<()> { |
| 729 | Err(Error::UdevEnumerate("unimplemented".into())) |
| 730 | } |
| 731 | |
| 732 | /// Scans `/sys` for all kernel subsystems. |
| 733 | /// |
| 734 | /// From `libudev` documentation: |
| 735 | /// |
| 736 | /// ```no_build,no_run |
| 737 | /// Scan /sys for all kernel subsystems, including buses, classes, drivers. |
| 738 | /// ``` |
| 739 | /// |
| 740 | /// Returns: `Ok(())` on success, `Err(Error)` otherwise. |
| 741 | pub fn scan_subsystems(&mut self) -> Result<()> { |
| 742 | // all kernel modules |
| 743 | if self.match_subsystem("module") { |
| 744 | self.scan_dir_and_add_devices("module", "", "")?; |
| 745 | } |
| 746 | |
| 747 | let subsysdir = if fs::metadata("/sys/subsystem").is_ok() { |
| 748 | "subsystem" |
| 749 | } else { |
| 750 | "bus" |
| 751 | }; |
| 752 | |
| 753 | // all subsystems (only buses support coldplug) |
| 754 | if self.match_subsystem("subsystem") { |
| 755 | self.scan_dir_and_add_devices(subsysdir, "", "")?; |
| 756 | } |
| 757 | |
| 758 | // all subsystem drivers |
| 759 | if self.match_subsystem("drivers") { |
| 760 | self.scan_dir(subsysdir, "drivers", "drivers")?; |
| 761 | } |
| 762 | |
| 763 | Ok(()) |
| 764 | } |
| 765 | |
| 766 | fn scan_dir_and_add_devices( |
| 767 | &mut self, |
| 768 | basedir: &str, |
| 769 | subdir1: &str, |
| 770 | subdir2: &str, |
| 771 | ) -> Result<()> { |
| 772 | let path = if !subdir1.is_empty() && !subdir2.is_empty() { |
| 773 | format!("/sys/{basedir}/{subdir1}/{subdir2}") |
| 774 | } else if !subdir1.is_empty() { |
| 775 | format!("/sys/{basedir}/{subdir1}") |
| 776 | } else if !subdir2.is_empty() { |
| 777 | format!("/sys/{basedir}/{subdir2}") |
| 778 | } else { |
| 779 | format!("/sys/{basedir}") |
| 780 | }; |
| 781 | |
| 782 | let mut add_syspaths: Vec<String> = Vec::new(); |
| 783 | |
| 784 | for dir_entry in fs::read_dir(path.as_str()) |
| 785 | .map_err(|err| Error::UdevEnumerate(format!("unable to open {path} path: {err}")))? |
| 786 | { |
| 787 | let d_name = dir_entry? |
| 788 | .file_name() |
| 789 | .into_string() |
| 790 | .unwrap_or(String::new()); |
| 791 | |
| 792 | if d_name.is_empty() { |
| 793 | log::trace!("{LOG_PREFIX} empty/invalid entry"); |
| 794 | } else if d_name.starts_with('.') { |
| 795 | log::trace!("{LOG_PREFIX} private entry"); |
| 796 | } else if !self.match_sysname(d_name.as_str()) { |
| 797 | log::trace!("{LOG_PREFIX} no /sys name match"); |
| 798 | } else { |
| 799 | let syspath = format!("{path}/{d_name}"); |
| 800 | if let Ok(mut dev) = |
| 801 | UdevDevice::new_from_syspath(Arc::clone(&self.udev), syspath.as_str()) |
| 802 | { |
| 803 | if self.match_is_initialized { |
| 804 | // From `libudev` documentation: |
| 805 | // |
| 806 | // ``` |
| 807 | // All devices with a device node or network interfaces |
| 808 | // possibly need udev to adjust the device node permission |
| 809 | // or context, or rename the interface before it can be |
| 810 | // reliably used from other processes. |
| 811 | // |
| 812 | // For now, we can only check these types of devices, we |
| 813 | // might not store a database, and have no way to find out |
| 814 | // for all other types of devices. |
| 815 | // ``` |
| 816 | if dev.get_is_initialized() |
| 817 | && (util::major(dev.devnum()) > 0 || dev.get_ifindex() > 0) |
| 818 | { |
| 819 | break; |
| 820 | } |
| 821 | } |
| 822 | let dev_syspath = dev.syspath().to_owned(); |
| 823 | if !self.match_parent(&dev) { |
| 824 | log::trace!("{LOG_PREFIX} no parent match"); |
| 825 | break; |
| 826 | } else if !self.match_tag(&mut dev) { |
| 827 | log::trace!("{LOG_PREFIX} no tag match"); |
| 828 | break; |
| 829 | } else if !self.match_property(&dev) { |
| 830 | log::trace!("{LOG_PREFIX} no property match"); |
| 831 | break; |
| 832 | } else if !self.match_sysattr(&mut dev) { |
| 833 | log::trace!("{LOG_PREFIX} no /sys attribute match"); |
| 834 | break; |
| 835 | } else { |
| 836 | add_syspaths.push(dev_syspath); |
| 837 | } |
| 838 | } |
| 839 | } |
| 840 | } |
| 841 | |
| 842 | for syspath in add_syspaths.iter() { |
| 843 | self.add_syspath(syspath)?; |
| 844 | } |
| 845 | |
| 846 | Ok(()) |
| 847 | } |
| 848 | |
| 849 | fn scan_dir(&mut self, basedir: &str, subdir: &str, subsystem: &str) -> Result<()> { |
| 850 | let path = format!("/sys/{basedir}"); |
| 851 | |
| 852 | for dir_entry in fs::read_dir(path.as_str()) |
| 853 | .map_err(|err| Error::UdevEnumerate(format!("unable to open {path} path: {err}")))? |
| 854 | { |
| 855 | let d_name = dir_entry? |
| 856 | .file_name() |
| 857 | .into_string() |
| 858 | .unwrap_or(String::new()); |
| 859 | |
| 860 | if d_name.is_empty() { |
| 861 | log::trace!("{LOG_PREFIX} empty/invalid entry"); |
| 862 | } else if d_name.starts_with('.') { |
| 863 | log::trace!("{LOG_PREFIX} private entry"); |
| 864 | } else if !self.match_sysname(if subsystem.is_empty() { |
| 865 | d_name.as_str() |
| 866 | } else { |
| 867 | subsystem |
| 868 | }) { |
| 869 | log::trace!("{LOG_PREFIX} no /sys subsystem name match"); |
| 870 | } else { |
| 871 | self.scan_dir_and_add_devices(basedir, d_name.as_str(), subdir)?; |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | Ok(()) |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | impl UdevDevice { |
| 880 | pub(crate) fn match_sysattr_value(&mut self, sysattr: &str, match_val: &str) -> bool { |
| 881 | match self.get_sysattr_value(sysattr) { |
| 882 | Some(val) => { |
| 883 | if match_val.is_empty() { |
| 884 | true |
| 885 | } else if let Ok(pattern) = glob::Pattern::new(match_val) { |
| 886 | pattern.matches(val.as_str()) |
| 887 | } else { |
| 888 | false |
| 889 | } |
| 890 | } |
| 891 | None => false, |
| 892 | } |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | #[cfg(test)] |
| 897 | mod tests { |
| 898 | use super::*; |
| 899 | use crate::UdevEntry; |
| 900 | |
| 901 | #[test] |
| 902 | fn test_udev_enumerate() { |
| 903 | let udev = Arc::new(Udev::new()); |
| 904 | |
| 905 | let mut null_enum = UdevEnumerate::new(Arc::clone(&udev)); |
| 906 | |
| 907 | assert_eq!(null_enum.udev(), &udev); |
| 908 | assert!(null_enum.sysattr_match_list().is_empty()); |
| 909 | assert!(null_enum.sysattr_nomatch_list().is_empty()); |
| 910 | assert!(null_enum.subsystem_match_list().is_empty()); |
| 911 | assert!(null_enum.subsystem_nomatch_list().is_empty()); |
| 912 | assert!(null_enum.sysname_match_list().is_empty()); |
| 913 | assert!(null_enum.properties_match_list().is_empty()); |
| 914 | assert!(null_enum.tags_match_list().is_empty()); |
| 915 | assert!(null_enum.devices_list().is_empty()); |
| 916 | assert!(null_enum.parent().is_none()); |
| 917 | assert!(null_enum.devices().is_empty()); |
| 918 | assert_eq!(null_enum.devices_cur(), 0); |
| 919 | assert_eq!(null_enum.devices_max(), 0); |
| 920 | assert!(!null_enum.devices_uptodate()); |
| 921 | assert!(!null_enum.match_is_initialized()); |
| 922 | |
| 923 | let exp_sysattr_match_list = [UdevEntry::new().with_name("test_sysattr_match_list")]; |
| 924 | let exp_sysattr_nomatch_list = [UdevEntry::new().with_name("test_sysattr_nomatch_list")]; |
| 925 | let exp_subsystem_match_list = [UdevEntry::new().with_name("test_subsystem_match_list")]; |
| 926 | let exp_subsystem_nomatch_list = |
| 927 | [UdevEntry::new().with_name("test_subsystem_nomatch_list")]; |
| 928 | let exp_sysname_match_list = [UdevEntry::new().with_name("test_sysname_match_list")]; |
| 929 | let exp_properties_match_list = [UdevEntry::new().with_name("test_properties_match_list")]; |
| 930 | let exp_tags_match_list = [UdevEntry::new().with_name("test_tags_match_list")]; |
| 931 | let exp_devices_list = [UdevEntry::new().with_name("test_devices_list")]; |
| 932 | let exp_parent = Arc::new(UdevDevice::new(Arc::clone(&udev))); |
| 933 | let exp_devices = [Syspath::new(), Syspath::new()]; |
| 934 | let exp_devices_cur = 1; |
| 935 | let exp_devices_max = 4; |
| 936 | let exp_devices_uptodate = true; |
| 937 | let exp_match_is_initialized = true; |
| 938 | |
| 939 | let exp_enum = UdevEnumerate::new(Arc::clone(&udev)) |
| 940 | .with_sysattr_match_list(exp_sysattr_match_list.clone()) |
| 941 | .with_sysattr_nomatch_list(exp_sysattr_nomatch_list.clone()) |
| 942 | .with_subsystem_match_list(exp_subsystem_match_list.clone()) |
| 943 | .with_subsystem_nomatch_list(exp_subsystem_nomatch_list.clone()) |
| 944 | .with_sysname_match_list(exp_sysname_match_list.clone()) |
| 945 | .with_properties_match_list(exp_properties_match_list.clone()) |
| 946 | .with_tags_match_list(exp_tags_match_list.clone()) |
| 947 | .with_devices_list(exp_devices_list.clone()) |
| 948 | .with_parent(exp_parent.clone()) |
| 949 | .with_devices(exp_devices.clone()) |
| 950 | .with_devices_cur(exp_devices_cur) |
| 951 | .with_devices_max(exp_devices_max) |
| 952 | .with_devices_uptodate(exp_devices_uptodate) |
| 953 | .with_match_is_initialized(exp_match_is_initialized); |
| 954 | |
| 955 | assert_eq!(exp_enum.udev(), &udev); |
| 956 | |
| 957 | for iter in [ |
| 958 | exp_enum |
| 959 | .sysattr_match_list() |
| 960 | .iter() |
| 961 | .zip(exp_sysattr_match_list.iter()), |
| 962 | exp_enum |
| 963 | .sysattr_nomatch_list() |
| 964 | .iter() |
| 965 | .zip(exp_sysattr_nomatch_list.iter()), |
| 966 | exp_enum |
| 967 | .subsystem_match_list() |
| 968 | .iter() |
| 969 | .zip(exp_subsystem_match_list.iter()), |
| 970 | exp_enum |
| 971 | .subsystem_nomatch_list() |
| 972 | .iter() |
| 973 | .zip(exp_subsystem_nomatch_list.iter()), |
| 974 | exp_enum |
| 975 | .sysname_match_list() |
| 976 | .iter() |
| 977 | .zip(exp_sysname_match_list.iter()), |
| 978 | exp_enum |
| 979 | .properties_match_list() |
| 980 | .iter() |
| 981 | .zip(exp_properties_match_list.iter()), |
| 982 | exp_enum |
| 983 | .tags_match_list() |
| 984 | .iter() |
| 985 | .zip(exp_tags_match_list.iter()), |
| 986 | exp_enum.devices_list().iter().zip(exp_devices_list.iter()), |
| 987 | ] { |
| 988 | for (entry, exp_entry) in iter { |
| 989 | assert_eq!(entry, exp_entry); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | assert_eq!(exp_enum.parent(), Some(&exp_parent)); |
| 994 | assert_eq!(exp_enum.devices(), exp_devices.as_ref()); |
| 995 | assert_eq!(exp_enum.devices_cur(), exp_devices_cur); |
| 996 | assert_eq!(exp_enum.devices_max(), exp_devices_max); |
| 997 | assert_eq!(exp_enum.devices_uptodate(), exp_devices_uptodate); |
| 998 | assert_eq!(exp_enum.match_is_initialized(), exp_match_is_initialized); |
| 999 | |
| 1000 | null_enum.set_sysattr_match_list(exp_sysattr_match_list.clone()); |
| 1001 | null_enum.set_sysattr_nomatch_list(exp_sysattr_nomatch_list.clone()); |
| 1002 | null_enum.set_subsystem_match_list(exp_subsystem_match_list.clone()); |
| 1003 | null_enum.set_subsystem_nomatch_list(exp_subsystem_nomatch_list.clone()); |
| 1004 | null_enum.set_sysname_match_list(exp_sysname_match_list.clone()); |
| 1005 | null_enum.set_properties_match_list(exp_properties_match_list.clone()); |
| 1006 | null_enum.set_tags_match_list(exp_tags_match_list.clone()); |
| 1007 | null_enum.set_devices_list(exp_devices_list.clone()); |
| 1008 | null_enum.set_parent(exp_parent.clone()); |
| 1009 | null_enum.set_devices(exp_devices.clone()); |
| 1010 | null_enum.set_devices_cur(exp_devices_cur); |
| 1011 | null_enum.set_devices_max(exp_devices_max); |
| 1012 | null_enum.set_devices_uptodate(exp_devices_uptodate); |
| 1013 | null_enum.set_match_is_initialized(exp_match_is_initialized); |
| 1014 | |
| 1015 | assert_eq!(null_enum, exp_enum); |
| 1016 | } |
| 1017 | } |