| 1 | use std::io::{self, Read}; |
| 2 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 3 | use std::sync::Arc; |
| 4 | use std::{env, fs, mem}; |
| 5 | |
| 6 | use crate::{Error, Result, Udev, UdevEntry, UdevList}; |
| 7 | |
| 8 | mod line; |
| 9 | mod trie; |
| 10 | |
| 11 | pub use line::*; |
| 12 | pub use trie::*; |
| 13 | |
| 14 | static NODE_SIZE: AtomicUsize = AtomicUsize::new(24); |
| 15 | static CHILD_ENTRY_SIZE: AtomicUsize = AtomicUsize::new(16); |
| 16 | static VALUE_ENTRY_SIZE: AtomicUsize = AtomicUsize::new(32); |
| 17 | |
| 18 | /// Gets the [Node](TrieNode) size loaded from the [TrieHeader]. |
| 19 | pub fn node_size() -> usize { |
| 20 | NODE_SIZE.load(Ordering::Relaxed) |
| 21 | } |
| 22 | |
| 23 | pub(crate) fn set_node_size(val: usize) { |
| 24 | NODE_SIZE.store(val, Ordering::SeqCst); |
| 25 | } |
| 26 | |
| 27 | /// Gets the [ChildEntry](TrieChildEntry) size loaded from the [TrieHeader]. |
| 28 | pub fn child_entry_size() -> usize { |
| 29 | CHILD_ENTRY_SIZE.load(Ordering::Relaxed) |
| 30 | } |
| 31 | |
| 32 | pub(crate) fn set_child_entry_size(val: usize) { |
| 33 | CHILD_ENTRY_SIZE.store(val, Ordering::SeqCst); |
| 34 | } |
| 35 | |
| 36 | /// Gets the [ValueEntry](TrieValueEntry) size loaded from the [TrieHeader]. |
| 37 | pub fn value_entry_size() -> usize { |
| 38 | VALUE_ENTRY_SIZE.load(Ordering::Relaxed) |
| 39 | } |
| 40 | |
| 41 | pub(crate) fn set_value_entry_size(val: usize) { |
| 42 | VALUE_ENTRY_SIZE.store(val, Ordering::SeqCst); |
| 43 | } |
| 44 | |
| 45 | #[cfg(target_os = "linux")] |
| 46 | const UDEV_LIBEXEC_DIR: &str = "/usr/lib/udev"; |
| 47 | // FIXME: add udev libexec dirs for other OSes |
| 48 | |
| 49 | fn get_hwdb_bin_paths() -> String { |
| 50 | const DEFAULT_LOCATIONS: [&str; 2] = ["/etc/udev", UDEV_LIBEXEC_DIR]; |
| 51 | |
| 52 | if let Ok(by_env) = env::var("UDEV_HWDB_BIN") { |
| 53 | DEFAULT_LOCATIONS |
| 54 | .iter() |
| 55 | .fold(by_env, |path, loc| format!("{path}\0{loc}/hwdb.bin")) |
| 56 | } else { |
| 57 | DEFAULT_LOCATIONS |
| 58 | .iter() |
| 59 | .fold(String::new(), |path, loc| format!("{path}\0{loc}/hwdb.bin")) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /// Represents the on-disk hardware database. |
| 64 | /// |
| 65 | /// Retrieves properties from the hardware database. |
| 66 | #[repr(C)] |
| 67 | pub struct UdevHwdb { |
| 68 | udev: Arc<Udev>, |
| 69 | bin_paths: String, |
| 70 | hwdb_path: String, |
| 71 | head: TrieHeader, |
| 72 | properties_list: UdevList, |
| 73 | } |
| 74 | |
| 75 | impl UdevHwdb { |
| 76 | /// Creates a new [UdevHwdb]. |
| 77 | pub fn new(udev: Arc<Udev>) -> Result<Self> { |
| 78 | let mut hwdb_path = String::new(); |
| 79 | let bin_paths = get_hwdb_bin_paths(); |
| 80 | |
| 81 | let (head, metadata) = { |
| 82 | // In the original `libudev`, they `mmap` the entire on-disk database into a `const char *` |
| 83 | // union, which leads to inherently unsafe access in Rust. |
| 84 | // |
| 85 | // Instead, we'll just parse the header for now, which advances the `File` struct's internal |
| 86 | // cursor, and delay further parsing for subsequent calls to the various node entry, and value calls. |
| 87 | // |
| 88 | // Alternatively, we could parse the properties list now, and avoid keeping the file |
| 89 | // struct, file metadata, and `TrieHeader` in the `UdevHwdb` struct. Instead, we would just |
| 90 | // keep the parsed `properties_list`. |
| 91 | // |
| 92 | // TBD. |
| 93 | |
| 94 | let mut bin_file: Option<fs::File> = None; |
| 95 | |
| 96 | for path in bin_paths.split('\0') { |
| 97 | if let Ok(f) = fs::OpenOptions::new().read(true).open(path) { |
| 98 | bin_file = Some(f); |
| 99 | path.clone_into(&mut hwdb_path); |
| 100 | break; |
| 101 | } |
| 102 | let errno = io::Error::last_os_error(); |
| 103 | if errno.raw_os_error() == Some(libc::ENOENT) { |
| 104 | Ok(()) |
| 105 | } else { |
| 106 | Err(Error::UdevHwdb(format!( |
| 107 | "error reading {path}, errno: {errno}" |
| 108 | ))) |
| 109 | }?; |
| 110 | } |
| 111 | |
| 112 | let mut file = bin_file.ok_or(Error::UdevHwdb( |
| 113 | "unable to find hwdb.bin database file".into(), |
| 114 | ))?; |
| 115 | |
| 116 | let metadata = file.metadata()?; |
| 117 | let mut hwdb_head_buf = [0u8; mem::size_of::<TrieHeader>()]; |
| 118 | |
| 119 | file.read_exact(&mut hwdb_head_buf)?; |
| 120 | |
| 121 | (TrieHeader::try_from(hwdb_head_buf.as_ref())?, metadata) |
| 122 | }; |
| 123 | |
| 124 | let properties_list = UdevList::new(Arc::clone(&udev)); |
| 125 | |
| 126 | set_node_size(head.node_size() as usize); |
| 127 | set_child_entry_size(head.child_entry_size() as usize); |
| 128 | set_value_entry_size(head.value_entry_size() as usize); |
| 129 | |
| 130 | log::debug!("=== trie on-disk ==="); |
| 131 | log::debug!("tool version: {}", head.tool_version()); |
| 132 | log::debug!("file size: {:8} bytes", metadata.len()); |
| 133 | log::debug!("header size: {:8} bytes", head.header_size()); |
| 134 | log::debug!("node size: {:8} bytes", head.node_size()); |
| 135 | log::debug!("child size: {:8} bytes", head.child_entry_size()); |
| 136 | log::debug!("value size: {:8} bytes", head.value_entry_size()); |
| 137 | log::debug!("strings: {:8} bytes", head.strings_len()); |
| 138 | log::debug!("nodes: {:8} bytes", head.nodes_len()); |
| 139 | |
| 140 | Ok(Self { |
| 141 | udev, |
| 142 | bin_paths, |
| 143 | hwdb_path, |
| 144 | head, |
| 145 | properties_list, |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | /// Gets a reference to the [TrieHeader]. |
| 150 | pub const fn header(&self) -> &TrieHeader { |
| 151 | &self.head |
| 152 | } |
| 153 | |
| 154 | /// Looks up a matching device in the hardware database. |
| 155 | /// |
| 156 | /// Parameters: |
| 157 | /// |
| 158 | /// - `modalias`: modalias string |
| 159 | /// - `flags`: (unused), preserved for easier mapping to `libudev` C API |
| 160 | /// |
| 161 | /// From the `libudev` documentation: |
| 162 | /// |
| 163 | /// ```no_build,no_run |
| 164 | /// The lookup key is a `modalias` string, whose formats are defined for the Linux kernel modules. |
| 165 | /// Examples are: pci:v00008086d00001C2D*, usb:v04F2pB221*. The first entry |
| 166 | /// of a list of retrieved properties is returned. |
| 167 | /// ``` |
| 168 | /// |
| 169 | /// Returns: an optional reference to an [UdevEntry]. |
| 170 | pub fn get_properties_list_entry(&mut self, modalias: &str, _flags: u32) -> Option<&UdevEntry> { |
| 171 | // For now, do the naive thing, and read the entire HWDB into memory (12M+!!!) |
| 172 | // |
| 173 | // Using the BufReader to jump around to all the various offsets will probably be |
| 174 | // more efficient, but harder to follow. BufReader only supports relative `Seek`ing. |
| 175 | // |
| 176 | // Nodes are also not sequential in the on-disk format, which would make parsing |
| 177 | // easier, but lose some of the structure of the HWDB. According to the man page |
| 178 | // (`man 7 hwdb`), entries later in the HWDB have higher priority, which some tools |
| 179 | // may rely on. |
| 180 | // |
| 181 | // `libudev` does not appear to track priority. |
| 182 | // |
| 183 | // Loading everything into memory at one time also avoids some other tool updating the |
| 184 | // HWDB while we are parsing it. |
| 185 | let file = fs::OpenOptions::new() |
| 186 | .read(true) |
| 187 | .open(&self.hwdb_path) |
| 188 | .map_err(|err| { |
| 189 | log::warn!("unable to open HWDB file: {err}"); |
| 190 | }) |
| 191 | .ok()?; |
| 192 | |
| 193 | let metadata = file |
| 194 | .metadata() |
| 195 | .map_err(|err| { |
| 196 | log::warn!("unable to get HWDB metadata: {err}"); |
| 197 | }) |
| 198 | .ok()?; |
| 199 | |
| 200 | let file_len = metadata.len() as usize; |
| 201 | |
| 202 | let mut reader = io::BufReader::new(file); |
| 203 | let mut hwdb_buf = Vec::with_capacity(file_len); |
| 204 | |
| 205 | reader |
| 206 | .read_to_end(&mut hwdb_buf) |
| 207 | .map_err(|err| { |
| 208 | log::warn!("error reading HWDB into memory: {err}"); |
| 209 | }) |
| 210 | .ok()?; |
| 211 | |
| 212 | self.properties_list.clear(); |
| 213 | |
| 214 | Self::trie_search(&mut self.properties_list, &self.head, &hwdb_buf, modalias) |
| 215 | .map_err(|err| { |
| 216 | log::warn!("error looking up property list UdevEntry: {err}"); |
| 217 | }) |
| 218 | .ok()?; |
| 219 | |
| 220 | self.properties_list.entry() |
| 221 | } |
| 222 | |
| 223 | /// Looks up a matching device modalias in the hardware database and returns the list of properties. |
| 224 | pub fn query(&mut self, modalias: &str) -> Option<&UdevList> { |
| 225 | self.get_properties_list_entry(modalias, 0)?; |
| 226 | Some(self.properties_list()) |
| 227 | } |
| 228 | |
| 229 | /// Gets a reference to the [properties list](UdevList). |
| 230 | pub const fn properties_list(&self) -> &UdevList { |
| 231 | &self.properties_list |
| 232 | } |
| 233 | |
| 234 | /// Adds a key-value pair to the property list. |
| 235 | pub fn add_property(&mut self, key: &str, value: &str) -> Result<()> { |
| 236 | Self::_add_property(&mut self.properties_list, key, value) |
| 237 | } |
| 238 | |
| 239 | pub(crate) fn _add_property(list: &mut UdevList, key: &str, value: &str) -> Result<()> { |
| 240 | if let Some(nkey) = key.strip_prefix(' ') { |
| 241 | // TODO - should check priority if existing: https://github.com/systemd/systemd/blob/main/src/libsystemd/sd-hwdb/sd-hwdb.c#L134 |
| 242 | // add_entry if UdevList.unique (default) will replace currently |
| 243 | list.add_entry(nkey, value) |
| 244 | .map(|_| ()) |
| 245 | .ok_or(Error::UdevHwdb("unable to add property".into())) |
| 246 | } else { |
| 247 | // Silently ignore all properties which do not start with a |
| 248 | // space; future extensions might use additional prefixes. |
| 249 | Ok(()) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | /// Parses all [TrieEntry] nodes from an in-memory HWDB buffer. |
| 254 | pub fn parse_nodes<'a>( |
| 255 | head: &'a TrieHeader, |
| 256 | hwdb_buf: &'a [u8], |
| 257 | ) -> impl Iterator<Item = TrieEntry> + 'a { |
| 258 | let nodes_len = head.nodes_len() as usize; |
| 259 | let node_start = mem::size_of::<TrieHeader>(); |
| 260 | let node_end = node_start.saturating_add(nodes_len); |
| 261 | |
| 262 | let buf_len = hwdb_buf.len(); |
| 263 | |
| 264 | let mut idx = node_start; |
| 265 | |
| 266 | std::iter::from_fn(move || { |
| 267 | if (0..buf_len).contains(&node_start) |
| 268 | && (0..buf_len).contains(&node_end) |
| 269 | && idx < nodes_len |
| 270 | { |
| 271 | TrieEntry::try_from(&hwdb_buf[idx..]) |
| 272 | .inspect(|entry| { |
| 273 | idx = idx.saturating_add(entry.len()); |
| 274 | }) |
| 275 | .map_err(|err| { |
| 276 | log::error!("Error parsing TrieEntry: {err}"); |
| 277 | }) |
| 278 | .ok() |
| 279 | } else { |
| 280 | None |
| 281 | } |
| 282 | }) |
| 283 | } |
| 284 | |
| 285 | fn trie_search( |
| 286 | list: &mut UdevList, |
| 287 | head: &TrieHeader, |
| 288 | hwdb_buf: &[u8], |
| 289 | search: &str, |
| 290 | ) -> Result<()> { |
| 291 | let mut line_buf = LineBuf::new(); |
| 292 | let mut i = 0usize; |
| 293 | let nodes_root_off = head.nodes_root_off() as usize; |
| 294 | |
| 295 | let mut node = if nodes_root_off < hwdb_buf.len() { |
| 296 | TrieEntry::try_from(&hwdb_buf[nodes_root_off..]).ok() |
| 297 | } else { |
| 298 | None |
| 299 | }; |
| 300 | |
| 301 | log::trace!("Search term: {search}"); |
| 302 | |
| 303 | while let Some(n) = node { |
| 304 | if n.node().prefix_off() > 0 { |
| 305 | let prefix_off = n.node().prefix_off() as usize; |
| 306 | let ts = trie_string(hwdb_buf, prefix_off)?; |
| 307 | |
| 308 | for (p, c) in ts.chars().enumerate() { |
| 309 | if c == '*' || c == '?' || c == '[' { |
| 310 | return line_buf.trie_fnmatch(list, hwdb_buf, &n, p, &search[i + p..]); |
| 311 | } |
| 312 | |
| 313 | if search.chars().nth(i + p) != Some(c) { |
| 314 | return Ok(()); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | i = i.saturating_add(ts.chars().count()); |
| 319 | } |
| 320 | |
| 321 | for wildcard in [b'*', b'?', b'['] { |
| 322 | if let Some(child) = n.lookup_child(hwdb_buf, wildcard) { |
| 323 | line_buf.add_char(wildcard)?; |
| 324 | log::trace!("wildcard ({wildcard:?}) child match: child: {child:?}"); |
| 325 | line_buf.trie_fnmatch(list, hwdb_buf, &child, 0, &search[i..])?; |
| 326 | line_buf.remove_char(); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | if search.chars().nth(i) == Some('\0') { |
| 331 | for value in n.values().iter() { |
| 332 | let key_str = trie_string(hwdb_buf, value.key_off() as usize)?; |
| 333 | let val_str = trie_string(hwdb_buf, value.value_off() as usize)?; |
| 334 | |
| 335 | log::trace!("Matching property, key: {key_str}, value: {val_str}"); |
| 336 | Self::_add_property(list, key_str, val_str)?; |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | node = n.lookup_child(hwdb_buf, *search.as_bytes().get(i).unwrap_or(&0)); |
| 341 | i = i.saturating_add(1); |
| 342 | log::trace!("No match found, searching next child[{i}]: {node:?}"); |
| 343 | } |
| 344 | |
| 345 | Ok(()) |
| 346 | } |
| 347 | } |