Debian Codegraph @

src/context.rs

raw symbols SCIP
1 use std::{cmp, fmt, fs, io, sync::Arc};
2
3 use crate::{file_handle, name_to_handle_at, Error, LogPriority, Result, UdevEntryList, UdevList};
4
5 pub const RULES_PATH_LEN: usize = 4;
6
7 /// libudev context
8 ///
9 /// The context contains the default values read from the udev config file,
10 /// and is passed to all library operations.
11 #[repr(C)]
12 #[derive(Clone, Debug, Default, PartialEq)]
13 pub struct Udev {
14 sys_path: String,
15 dev_path: String,
16 rules_path: [String; RULES_PATH_LEN],
17 rules_path_ts: [u64; RULES_PATH_LEN],
18 run_path: String,
19 properties_list: Option<UdevList>,
20 log_priority: LogPriority,
21 }
22
23 impl Udev {
24 /// Creates a new [Udev].
25 pub fn new() -> Self {
26 Self {
27 sys_path: String::new(),
28 dev_path: String::new(),
29 rules_path: [""; RULES_PATH_LEN].map(String::from),
30 rules_path_ts: [0; RULES_PATH_LEN],
31 run_path: String::new(),
32 properties_list: None,
33 log_priority: LogPriority::new(),
34 }
35 }
36
37 /// Convenience function for `udev` log messages.
38 pub fn log<M: fmt::Display>(&self, priority: LogPriority, msg: M) {
39 if priority <= self.log_priority {
40 match priority {
41 LogPriority::Emergency
42 | LogPriority::Alert
43 | LogPriority::Critical
44 | LogPriority::Error => log::error!("{priority}: {msg}"),
45 LogPriority::Warning => log::warn!("{priority}: {msg}"),
46 LogPriority::Notice | LogPriority::Info => log::info!("{priority}: {msg}"),
47 LogPriority::Debug => log::debug!("{priority}: {msg}"),
48 }
49 }
50 }
51
52 /// Gets the system path.
53 pub fn sys_path(&self) -> &str {
54 self.sys_path.as_str()
55 }
56
57 /// Sets the system path.
58 pub fn set_sys_path<P: Into<String>>(&mut self, path: P) {
59 self.sys_path = path.into();
60 }
61
62 /// Builder function that sets the system path.
63 pub fn with_sys_path<P: Into<String>>(mut self, path: P) -> Self {
64 self.set_sys_path(path);
65 self
66 }
67
68 /// Gets the device path.
69 pub fn dev_path(&self) -> &str {
70 self.dev_path.as_str()
71 }
72
73 /// Sets the device path.
74 pub fn set_dev_path<P: Into<String>>(&mut self, path: P) {
75 self.dev_path = path.into();
76 }
77
78 /// Builder function that sets the device path.
79 pub fn with_dev_path<P: Into<String>>(mut self, path: P) -> Self {
80 self.set_dev_path(path);
81 self
82 }
83
84 /// Gets a reference to the list of rules paths.
85 pub fn rules_path(&self) -> &[String] {
86 let len = self.rules_path_count();
87 self.rules_path[..len].as_ref()
88 }
89
90 /// Gets a mutable reference to the list of rules paths.
91 pub fn rules_path_mut(&mut self) -> &mut [String] {
92 let len = self.rules_path_count();
93 self.rules_path[..len].as_mut()
94 }
95
96 /// Sets the list of rules paths.
97 pub fn set_rules_path<R: Into<String> + Clone>(&mut self, rules: &[R]) {
98 let len = cmp::min(rules.len(), RULES_PATH_LEN);
99 self.rules_path[..len]
100 .iter_mut()
101 .zip(rules[..len].iter().cloned())
102 .for_each(|(dst, src)| *dst = src.into());
103 self.rules_path[len..]
104 .iter_mut()
105 .for_each(|s| *s = String::new());
106 }
107
108 /// Builder function that sets the list of rules paths.
109 pub fn with_rules_path<R: Into<String> + Clone>(mut self, rules: &[R]) -> Self {
110 self.set_rules_path(rules);
111 self
112 }
113
114 /// Gets a reference to the list of rules path timestamps.
115 pub fn rules_path_ts(&self) -> &[u64] {
116 let len = self.rules_path_count();
117 self.rules_path_ts[..len].as_ref()
118 }
119
120 /// Gets a mutable reference to the list of rules path timestamps.
121 pub fn rules_path_ts_mut(&mut self) -> &mut [u64] {
122 let len = self.rules_path_count();
123 self.rules_path_ts[..len].as_mut()
124 }
125
126 /// Sets the list of rules path timestamps.
127 pub fn set_rules_path_ts<T: Into<u64> + Clone>(&mut self, ts: &[T]) {
128 let len = cmp::min(ts.len(), RULES_PATH_LEN);
129 self.rules_path_ts[..len]
130 .iter_mut()
131 .zip(ts[..len].iter().cloned())
132 .for_each(|(dst, src)| *dst = src.into());
133 }
134
135 /// Builder function that sets the list of rules path timestamps.
136 pub fn with_rules_path_ts<T: Into<u64> + Clone>(mut self, ts: &[T]) -> Self {
137 self.set_rules_path_ts(ts);
138 self
139 }
140
141 /// Gets the number of populated rules path entries.
142 pub fn rules_path_count(&self) -> usize {
143 self.rules_path.iter().filter(|p| !p.is_empty()).count()
144 }
145
146 /// Gets the run path.
147 pub fn run_path(&self) -> &str {
148 self.run_path.as_str()
149 }
150
151 /// Sets the run path.
152 pub fn set_run_path<P: Into<String>>(&mut self, path: P) {
153 self.run_path = path.into();
154 }
155
156 /// Builder function that sets the run path.
157 pub fn with_run_path<P: Into<String>>(mut self, path: P) -> Self {
158 self.set_run_path(path);
159 self
160 }
161
162 /// Gets a reference to the properties list [UdevList].
163 ///
164 /// **NOTE** User is responsible for initializing the [`properties_list`](UdevList) before calling.
165 pub fn properties_list(&self) -> Result<&UdevList> {
166 self.properties_list
167 .as_ref()
168 .ok_or(Error::Udev("context: missing properties_list".into()))
169 }
170
171 /// Gets a mutable reference to the properties list [UdevList].
172 ///
173 /// **NOTE** User is responsible for initializing the [`properties_list`](UdevList) before calling.
174 pub fn properties_list_mut(&mut self) -> Result<&mut UdevList> {
175 self.properties_list
176 .as_mut()
177 .ok_or(Error::Udev("context: missing properties_list".into()))
178 }
179
180 /// Sets the properties list [UdevList].
181 pub fn set_properties_list<L: Into<UdevEntryList>>(arc: &mut Arc<Self>, list: L) {
182 let udev_arc = Arc::clone(arc);
183 let udev = Arc::make_mut(arc);
184
185 match udev.properties_list.as_mut() {
186 Some(prop_list) => prop_list.set_list(list),
187 None => udev.properties_list = Some(UdevList::create(udev_arc, list.into())),
188 }
189 }
190
191 /// Builder function that sets the properties list [UdevList].
192 pub fn with_properties_list<L: Into<UdevEntryList>>(mut arc: Arc<Self>, list: L) -> Arc<Self> {
193 Udev::set_properties_list(&mut arc, list);
194 arc
195 }
196
197 /// Gets the [LogPriority].
198 pub const fn log_priority(&self) -> LogPriority {
199 self.log_priority
200 }
201
202 /// Sets the [LogPriority].
203 pub fn set_log_priority<P: Into<LogPriority>>(&mut self, priority: P) {
204 self.log_priority = priority.into();
205 }
206
207 /// Builder function that sets the [LogPriority].
208 pub fn with_log_priority<P: Into<LogPriority>>(mut self, priority: P) -> Self {
209 self.set_log_priority(priority);
210 self
211 }
212
213 /// Gets whether `/dev` is mounted on `devtmpfs`.
214 pub fn has_devtmpfs(&self) -> bool {
215 use io::BufRead;
216
217 let mut handle = file_handle::new();
218 let mut mount_id = 0i32;
219
220 if let (Ok(f), Ok(_)) = (
221 fs::OpenOptions::new()
222 .read(true)
223 .open("/proc/self/mountinfo"),
224 name_to_handle_at(libc::AT_FDCWD, "/dev", &mut handle, &mut mount_id, 0),
225 ) {
226 let mut reader = io::BufReader::new(f);
227 let mut line = String::new();
228 let mut ret = false;
229
230 while reader.read_line(&mut line).is_ok() {
231 if let Ok(mid) = line.parse::<i32>() {
232 if mid != mount_id {
233 continue;
234 }
235 } else {
236 continue;
237 }
238
239 if let Some(e) = line.find(" - ") {
240 if let Some(p) = line[e..].strip_prefix(" - ") {
241 // accept any name that starts with the currently expected type
242 if p.starts_with("devtmpfs") {
243 ret = true;
244 break;
245 }
246 }
247 }
248 }
249
250 ret
251 } else {
252 false
253 }
254 }
255 }
256
257 #[cfg(test)]
258 mod tests {
259 use super::*;
260 use crate::UdevEntry;
261
262 #[test]
263 fn test_udev() -> Result<()> {
264 let mut null_udev = Udev::new();
265
266 let exp_sys_path = "test_sys_path";
267 let exp_dev_path = "test_dev_path";
268 let exp_rules_path =
269 ["test_rules0", "test_rules1", "test_rules2", "test_rules3"].map(String::from);
270 let exp_rules_ts = [17092390, 17092391, 17092392, 17092393];
271 let exp_run_path = "test_run_path";
272 let exp_prop_list = [UdevEntry::new().with_name("test_entry_name")];
273 let exp_log_prio = LogPriority::Debug;
274
275 let exp_udev = Udev::new()
276 .with_sys_path(exp_sys_path)
277 .with_dev_path(exp_dev_path)
278 .with_rules_path(&exp_rules_path)
279 .with_rules_path_ts(&exp_rules_ts)
280 .with_run_path(exp_run_path)
281 .with_log_priority(exp_log_prio);
282
283 assert_eq!(null_udev.sys_path(), "");
284 assert_eq!(null_udev.dev_path(), "");
285 assert!(null_udev.rules_path().is_empty());
286 assert!(null_udev.rules_path_ts().is_empty());
287 assert_eq!(null_udev.run_path(), "");
288 assert!(null_udev.properties_list().is_err());
289 assert_eq!(null_udev.log_priority(), LogPriority::new());
290
291 assert_eq!(exp_udev.sys_path(), exp_sys_path);
292 assert_eq!(exp_udev.dev_path(), exp_dev_path);
293 assert_eq!(exp_udev.rules_path(), exp_rules_path.as_ref());
294 assert_eq!(exp_udev.rules_path_ts(), exp_rules_ts.as_ref());
295 assert_eq!(exp_udev.run_path(), exp_run_path);
296
297 assert_eq!(exp_udev.log_priority(), exp_log_prio);
298
299 null_udev.set_sys_path(exp_sys_path);
300 assert_eq!(null_udev.sys_path(), exp_sys_path);
301
302 null_udev.set_dev_path(exp_dev_path);
303 assert_eq!(null_udev.dev_path(), exp_dev_path);
304
305 null_udev.set_rules_path(&exp_rules_path);
306 assert_eq!(null_udev.rules_path(), exp_rules_path.as_ref());
307
308 null_udev.set_rules_path_ts(&exp_rules_ts);
309 assert_eq!(null_udev.rules_path_ts(), exp_rules_ts.as_ref());
310
311 null_udev.set_run_path(exp_run_path);
312 assert_eq!(null_udev.run_path(), exp_run_path);
313
314 null_udev.set_log_priority(exp_log_prio);
315 assert_eq!(null_udev.log_priority(), exp_log_prio);
316
317 assert_eq!(null_udev, exp_udev);
318
319 // Check that setting a short rules path only returns the short list.
320 null_udev.set_rules_path(&exp_rules_path[..1]);
321 assert_eq!(null_udev.rules_path(), &exp_rules_path[..1]);
322 assert_eq!(null_udev.rules_path_mut(), &exp_rules_path[..1]);
323 assert_eq!(null_udev.rules_path_ts(), &exp_rules_ts[..1]);
324
325 // Check that a maximum of `RULES_PATH_LEN` items are set
326 let oversize_rules_path = ["over"; RULES_PATH_LEN + 1].map(String::from);
327 null_udev.set_rules_path(&oversize_rules_path);
328 assert_eq!(
329 null_udev.rules_path(),
330 &oversize_rules_path[..RULES_PATH_LEN]
331 );
332 assert_eq!(null_udev.rules_path_ts(), &exp_rules_ts);
333
334 let mut null_udev = Arc::new(null_udev);
335 Udev::set_properties_list(&mut null_udev, exp_prop_list.clone());
336
337 for (prop, exp_prop) in null_udev
338 .properties_list()
339 .unwrap()
340 .iter()
341 .zip(exp_prop_list.iter())
342 {
343 assert_eq!(prop, exp_prop);
344 }
345
346 let exp_udev = Udev::with_properties_list(null_udev.clone(), exp_prop_list.clone());
347
348 for (prop, exp_prop) in exp_udev
349 .properties_list()
350 .unwrap()
351 .iter()
352 .zip(exp_prop_list.iter())
353 {
354 assert_eq!(prop, exp_prop);
355 }
356
357 assert_eq!(null_udev, exp_udev);
358
359 Ok(())
360 }
361 }