1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::str;

use std::ffi::{CStr, OsStr};
use std::io::Result;
use std::path::Path;
use std::ptr;
use std::str::FromStr;

use libc::{c_char, dev_t};

use Udev;
use {ffi, util};

use {AsRaw, FromRaw};

/// A structure that provides access to sysfs/kernel devices.
pub struct Device {
    udev: Udev,
    device: *mut ffi::udev_device,
}

impl Clone for Device {
    fn clone(&self) -> Self {
        Self {
            udev: self.udev.clone(),
            device: unsafe { ffi::udev_device_ref(self.device) },
        }
    }
}

impl Drop for Device {
    fn drop(&mut self) {
        unsafe {
            ffi::udev_device_unref(self.device);
        }
    }
}

as_ffi_with_context!(Device, device, ffi::udev_device, ffi::udev_device_ref);

impl Device {
    /// Creates a device for a given syspath.
    ///
    /// The `syspath` parameter should be a path to the device file within the `sysfs` file system,
    /// e.g., `/sys/devices/virtual/tty/tty0`.
    pub fn from_syspath(syspath: &Path) -> Result<Self> {
        // Create a new Udev context for this device
        // It would be more efficient to allow callers to create just one context and use multiple
        // devices, however that would be an API-breaking change.
        //
        // When devices are enumerated using an `Enumerator`, it will use
        // `from_syspath_with_context` which can reuse the existing `Udev` context to avoid this
        // extra overhead.
        let udev = Udev::new()?;

        Self::from_syspath_with_context(udev, syspath)
    }

    /// Creates a device for a given syspath, using an existing `Udev` instance rather than
    /// creating one automatically.
    ///
    /// The `syspath` parameter should be a path to the device file within the `sysfs` file system,
    /// e.g., `/sys/devices/virtual/tty/tty0`.
    pub fn from_syspath_with_context(udev: Udev, syspath: &Path) -> Result<Self> {
        let syspath = util::os_str_to_cstring(syspath)?;

        let ptr = try_alloc!(unsafe {
            ffi::udev_device_new_from_syspath(udev.as_raw(), syspath.as_ptr())
        });

        Ok(Self::from_raw(udev, ptr))
    }

    /// Creates a rust `Device` given an already created libudev `ffi::udev_device*` and a
    /// corresponding `Udev` instance from which the device was created.
    ///
    /// This guarantees that the `Udev` will live longer than the corresponding `Device`
    pub(crate) fn from_raw(udev: Udev, ptr: *mut ffi::udev_device) -> Self {
        Self { udev, device: ptr }
    }

    /// Checks whether the device has already been handled by udev.
    ///
    /// When a new device is connected to the system, udev initializes the device by setting
    /// permissions, renaming network devices, and possibly other initialization routines. This
    /// method returns `true` if udev has performed all of its work to initialize this device.
    ///
    /// This method only applies to devices with device nodes or network interfaces. All other
    /// devices return `true` by default.
    pub fn is_initialized(&self) -> bool {
        unsafe { ffi::udev_device_get_is_initialized(self.device) > 0 }
    }

    /// Gets the device's major/minor number.
    pub fn devnum(&self) -> Option<dev_t> {
        match unsafe { ffi::udev_device_get_devnum(self.device) } {
            0 => None,
            n => Some(n),
        }
    }

    /// Returns the syspath of the device.
    ///
    /// The path is an absolute path and includes the sys mount point. For example, the syspath for
    /// `tty0` could be `/sys/devices/virtual/tty/tty0`, which includes the sys mount point,
    /// `/sys`.
    pub fn syspath(&self) -> &Path {
        Path::new(unsafe {
            util::ptr_to_os_str_unchecked(ffi::udev_device_get_syspath(self.device))
        })
    }

    /// Returns the kernel devpath value of the device.
    ///
    /// The path does not contain the sys mount point, but does start with a `/`. For example, the
    /// devpath for `tty0` could be `/devices/virtual/tty/tty0`.
    pub fn devpath(&self) -> &OsStr {
        unsafe { util::ptr_to_os_str_unchecked(ffi::udev_device_get_devpath(self.device)) }
    }

    /// Returns the path to the device node belonging to the device.
    ///
    /// The path is an absolute path and starts with the device directory. For example, the device
    /// node for `tty0` could be `/dev/tty0`.
    pub fn devnode(&self) -> Option<&Path> {
        util::ptr_to_os_str(unsafe { ffi::udev_device_get_devnode(self.device) })
            .map(|path| Path::new(path))
    }

    /// Returns the parent of the device.
    pub fn parent(&self) -> Option<Self> {
        let ptr = unsafe { ffi::udev_device_get_parent(self.device) };

        if ptr.is_null() {
            return None;
        }

        Some(Self::from_raw(self.udev.clone(), unsafe {
            ffi::udev_device_ref(ptr)
        }))
    }

    /// Returns the parent of the device with the matching subsystem and devtype if any.
    pub fn parent_with_subsystem<T: AsRef<OsStr>>(&self, subsystem: T) -> Result<Option<Self>> {
        let subsystem = util::os_str_to_cstring(subsystem)?;
        let ptr = unsafe {
            ffi::udev_device_get_parent_with_subsystem_devtype(
                self.device,
                subsystem.as_ptr(),
                ptr::null(),
            )
        };

        if ptr.is_null() {
            return Ok(None);
        }

        Ok(Some(Self::from_raw(self.udev.clone(), unsafe {
            ffi::udev_device_ref(ptr)
        })))
    }

    /// Returns the parent of the device with the matching subsystem and devtype if any.
    pub fn parent_with_subsystem_devtype<T: AsRef<OsStr>, U: AsRef<OsStr>>(
        &self,
        subsystem: T,
        devtype: U,
    ) -> Result<Option<Self>> {
        let subsystem = util::os_str_to_cstring(subsystem)?;
        let devtype = util::os_str_to_cstring(devtype)?;
        let ptr = unsafe {
            ffi::udev_device_get_parent_with_subsystem_devtype(
                self.device,
                subsystem.as_ptr(),
                devtype.as_ptr(),
            )
        };

        if ptr.is_null() {
            return Ok(None);
        }

        Ok(Some(Self::from_raw(self.udev.clone(), unsafe {
            ffi::udev_device_ref(ptr)
        })))
    }

    /// Returns the subsystem name of the device.
    ///
    /// The subsystem name is a string that indicates which kernel subsystem the device belongs to.
    /// Examples of subsystem names are `tty`, `vtconsole`, `block`, `scsi`, and `net`.
    pub fn subsystem(&self) -> Option<&OsStr> {
        util::ptr_to_os_str(unsafe { ffi::udev_device_get_subsystem(self.device) })
    }

    /// Returns the kernel device name for the device.
    ///
    /// The sysname is a string that differentiates the device from others in the same subsystem.
    /// For example, `tty0` is the sysname for a TTY device that differentiates it from others,
    /// such as `tty1`.
    pub fn sysname(&self) -> &OsStr {
        unsafe { util::ptr_to_os_str_unchecked(ffi::udev_device_get_sysname(self.device)) }
    }

    /// Returns the instance number of the device.
    ///
    /// The instance number is used to differentiate many devices of the same type. For example,
    /// `/dev/tty0` and `/dev/tty1` are both TTY devices but have instance numbers of 0 and 1,
    /// respectively.
    ///
    /// Some devices don't have instance numbers, such as `/dev/console`, in which case the method
    /// returns `None`.
    pub fn sysnum(&self) -> Option<usize> {
        let ptr = unsafe { ffi::udev_device_get_sysnum(self.device) };

        if ptr.is_null() {
            return None;
        }

        match str::from_utf8(unsafe { CStr::from_ptr(ptr) }.to_bytes()) {
            Err(_) => None,
            Ok(s) => FromStr::from_str(s).ok(),
        }
    }

    /// Returns the devtype name of the device.
    pub fn devtype(&self) -> Option<&OsStr> {
        util::ptr_to_os_str(unsafe { ffi::udev_device_get_devtype(self.device) })
    }

    /// Returns the name of the kernel driver attached to the device.
    pub fn driver(&self) -> Option<&OsStr> {
        util::ptr_to_os_str(unsafe { ffi::udev_device_get_driver(self.device) })
    }

    /// Retreives the value of a device property.
    pub fn property_value<T: AsRef<OsStr>>(&self, property: T) -> Option<&OsStr> {
        let prop = match util::os_str_to_cstring(property) {
            Ok(s) => s,
            Err(_) => return None,
        };

        util::ptr_to_os_str(unsafe {
            ffi::udev_device_get_property_value(self.device, prop.as_ptr())
        })
    }

    /// Retreives the value of a device attribute.
    pub fn attribute_value<T: AsRef<OsStr>>(&self, attribute: T) -> Option<&OsStr> {
        let attr = match util::os_str_to_cstring(attribute) {
            Ok(s) => s,
            Err(_) => return None,
        };

        util::ptr_to_os_str(unsafe {
            ffi::udev_device_get_sysattr_value(self.device, attr.as_ptr())
        })
    }

    /// Sets the value of a device attribute.
    pub fn set_attribute_value<T: AsRef<OsStr>, U: AsRef<OsStr>>(
        &mut self,
        attribute: T,
        value: U,
    ) -> Result<()> {
        let attribute = util::os_str_to_cstring(attribute)?;
        let value = util::os_str_to_cstring(value)?;

        util::errno_to_result(unsafe {
            ffi::udev_device_set_sysattr_value(
                self.device,
                attribute.as_ptr(),
                value.as_ptr() as *mut c_char,
            )
        })
    }

    /// Returns an iterator over the device's properties.
    ///
    /// ## Example
    ///
    /// This example prints out all of a device's properties:
    ///
    /// ```no_run
    /// # use std::path::Path;
    /// # let device = udev::Device::from_syspath(Path::new("/sys/devices/virtual/tty/tty0")).unwrap();
    /// for property in device.properties() {
    ///     println!("{:?} = {:?}", property.name(), property.value());
    /// }
    /// ```
    pub fn properties(&self) -> Properties<'_> {
        Properties {
            entry: unsafe { ffi::udev_device_get_properties_list_entry(self.device) },
            _device: self,
        }
    }

    /// Returns an iterator over the device's attributes.
    ///
    /// ## Example
    ///
    /// This example prints out all of a device's attributes:
    ///
    /// ```no_run
    /// # use std::path::Path;
    /// # let device = udev::Device::from_syspath(Path::new("/sys/devices/virtual/tty/tty0")).unwrap();
    /// for attribute in device.attributes() {
    ///     println!("{:?} = {:?}", attribute.name(), attribute.value());
    /// }
    /// ```
    pub fn attributes(&self) -> Attributes<'_> {
        Attributes {
            entry: unsafe { ffi::udev_device_get_sysattr_list_entry(self.device) },
            device: self,
        }
    }
}

/// Iterator over a device's properties.
pub struct Properties<'a> {
    entry: *mut ffi::udev_list_entry,
    _device: &'a Device,
}

impl<'a> Iterator for Properties<'a> {
    type Item = Property<'a>;

    fn next(&mut self) -> Option<Property<'a>> {
        if self.entry.is_null() {
            None
        } else {
            let name =
                unsafe { util::ptr_to_os_str_unchecked(ffi::udev_list_entry_get_name(self.entry)) };
            let value = unsafe {
                util::ptr_to_os_str_unchecked(ffi::udev_list_entry_get_value(self.entry))
            };

            self.entry = unsafe { ffi::udev_list_entry_get_next(self.entry) };

            Some(Property { name, value })
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

/// A device property.
pub struct Property<'a> {
    name: &'a OsStr,
    value: &'a OsStr,
}

impl<'a> Property<'a> {
    /// Returns the property name.
    pub fn name(&self) -> &OsStr {
        self.name
    }

    /// Returns the property value.
    pub fn value(&self) -> &OsStr {
        self.value
    }
}

/// Iterator over a device's attributes.
pub struct Attributes<'a> {
    device: &'a Device,
    entry: *mut ffi::udev_list_entry,
}

impl<'a> Iterator for Attributes<'a> {
    type Item = Attribute<'a>;

    fn next(&mut self) -> Option<Attribute<'a>> {
        if self.entry.is_null() {
            return None;
        }

        let name =
            unsafe { util::ptr_to_os_str_unchecked(ffi::udev_list_entry_get_name(self.entry)) };

        self.entry = unsafe { ffi::udev_list_entry_get_next(self.entry) };

        Some(Attribute {
            device: self.device,
            name,
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

/// A device attribute.
pub struct Attribute<'a> {
    device: &'a Device,
    name: &'a OsStr,
}

impl<'a> Attribute<'a> {
    /// Returns the attribute name.
    pub fn name(&self) -> &'a OsStr {
        self.name
    }

    /// Returns the attribute value.
    pub fn value(&self) -> Option<&'a OsStr> {
        self.device.attribute_value(self.name)
    }
}