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
use crate::pci_attributes::PciAttributes;
use crate::uevent::UEvent;
use crate::usb_attributes::UsbAttributes;
#[cfg(feature = "serde")]
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use std::fs::*;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::str::FromStr;

/// De-serialized generic SysFs /sys/class/* to a Rust structure.
/// Note most fields are stored in raw format in the HashMap<String, String>
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Default)]
pub struct GenericClassAttributes {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub uevent: Option<UEvent>,
    #[cfg_attr(
        feature = "serde",
        serde(flatten, skip_serializing_if = "HashMap::is_empty")
    )]
    pub attributes: HashMap<String, String>,
}

type SysPath = String;
pub type UsbDevices = HashMap<SysPath, UsbAttributes>;
pub type PciDevices = HashMap<SysPath, PciAttributes>;
pub type DmiInfo = HashMap<SysPath, GenericClassAttributes>;
pub type ThermalInfo = HashMap<SysPath, GenericClassAttributes>;

/// De-serialized SysFs bus/class types supported by this crate
pub enum SysFsType {
    BusUSB(UsbDevices),
    BusPCI(PciDevices),
    ClassDMI(DmiInfo),
    ClassThermal(ThermalInfo),
}

impl fmt::Display for SysFsType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::SysFsType::*;
        write!(
            f,
            "{}",
            match self {
                BusUSB(_) => "USB",
                BusPCI(_) => "PCI",
                ClassDMI(_) => "DMI",
                ClassThermal(_) => "Thermal",
            }
        )
    }
}

impl From<&mut SysFsType> for &Path {
    fn from(kind: &mut SysFsType) -> Self {
        use crate::SysFsType::*;
        match kind {
            BusUSB(_) => Path::new("/sys/bus/usb/devices/"),
            BusPCI(_) => Path::new("/sys/bus/pci/devices/"),
            ClassDMI(_) => Path::new("/sys/class/dmi/"),
            ClassThermal(_) => Path::new("/sys/class/thermal"),
        }
    }
}

/// Builds up Rust struct based on what kind of SysFs type.
/// See [`SysFsType`] for supported types.
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Default)]
pub struct SysFs {}
impl SysFs {
    /// Read path and pass it to anonymous function
    fn read_generic<F, P>(path: P, mut f: F) -> Result<(), std::io::Error>
    where
        F: FnMut(&str, Result<Vec<u8>, std::io::Error>),
        P: AsRef<Path>,
    {
        for entry in read_dir(path)? {
            if let Ok(entry) = entry {
                if metadata(entry.path())?.mode() & 0o400 != 0 && entry.path().is_file() {
                    if let Some(key) = entry.path().file_name() {
                        let key = &key.to_string_lossy();
                        match std::fs::read(&mut entry.path()) {
                            Ok(value) => {
                                f(&key, Ok(value));
                            }
                            Err(e) => {
                                f(&key, Err(e));
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn iterate(kind: &mut SysFsType) -> Result<(), std::io::Error> {
        let path: &Path = (kind).into();
        if path.is_dir() {
            for entry in read_dir(&path)? {
                if let Ok(entry) = entry {
                    if entry.path().is_dir() {
                        if let Ok(link) = read_link(entry.path()) {
                            let p = Path::new(&path).join(link).canonicalize();
                            if let Ok(ref p) = p {
                                let key: String =
                                    p.clone().into_os_string().to_string_lossy().into();
                                match kind {
                                    SysFsType::BusUSB(map) => {
                                        let mut attrs = UsbAttributes::default();
                                        Self::read_generic(p, |key, value| match value {
                                            Ok(value) => {
                                                attrs.add(
                                                    key, value,
                                                )
                                                .unwrap_or_else(|e| {
                                                    log::error!(
                                                        "Ignored attribute: '{}' for {} cause of: {}",
                                                        key,
                                                        p.display(),
                                                        e
                                                    );
                                                });
                                            }
                                            Err(e) => {
                                                log::warn!(
                                                    "Could not read read USB: {}/{} cause: {}",
                                                    p.to_string_lossy(),
                                                    key,
                                                    e
                                                );
                                            }
                                        })?;
                                        if !attrs.descriptors.is_empty() {
                                            map.insert(key, attrs);
                                        }
                                    }
                                    SysFsType::BusPCI(map) => {
                                        let mut attrs = PciAttributes::default();
                                        Self::read_generic(p, |key, value| match value {
                                            Ok(value) => {
                                                attrs.add(key, value).unwrap();
                                            }
                                            Err(e) => {
                                                log::warn!(
                                                    "Could not read read pci: {}/{} cause: {}",
                                                    p.to_string_lossy(),
                                                    key,
                                                    e
                                                );
                                            }
                                        })?;
                                        map.insert(key, attrs);
                                    }
                                    SysFsType::ClassDMI(map) => {
                                        map.insert(key, Self::iterate_generic_attributes(p)?);
                                    }
                                    SysFsType::ClassThermal(map) => {
                                        map.insert(key, Self::iterate_generic_attributes(p)?);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn iterate_generic_attributes(p: &Path) -> Result<GenericClassAttributes, std::io::Error> {
        let mut inner = GenericClassAttributes::default();
        Self::read_generic(p, |key, value| match value {
            Ok(value) => {
                let value = String::from_utf8_lossy(&value)
                    .to_string()
                    .trim()
                    .to_string();
                match &key[0..] {
                    "uevent" => inner.uevent = UEvent::from_str(&value).ok(),
                    _ => {
                        inner.attributes.insert(key.to_string(), value);
                    }
                }
            }
            Err(e) => {
                log::warn!("Could not read {} key: '{}' cause: {}", p.display(), key, e);
            }
        })?;
        Ok(inner)
    }

    /// Get all USB devices found on system.
    pub fn usb_devices() -> Result<UsbDevices, std::io::Error> {
        let mut kind = SysFsType::BusUSB(UsbDevices::new());
        Self::iterate(&mut kind)?;
        match kind {
            SysFsType::BusUSB(usb) => Ok(usb),
            _ => panic!(""),
        }
    }

    /// Get all PCI devices found on system.
    pub fn pci_devices() -> Result<PciDevices, std::io::Error> {
        let mut kind = SysFsType::BusPCI(PciDevices::new());
        Self::iterate(&mut kind)?;
        match kind {
            SysFsType::BusPCI(pci) => Ok(pci),
            _ => panic!(""),
        }
    }

    /// Get DMI info
    pub fn dmi_info() -> Result<DmiInfo, std::io::Error> {
        let mut kind = SysFsType::ClassDMI(DmiInfo::new());
        Self::iterate(&mut kind)?;
        match kind {
            SysFsType::ClassDMI(dmi) => Ok(dmi),
            _ => panic!(""),
        }
    }

    /// Get all thermal devices on the system.
    pub fn thermal_info() -> Result<ThermalInfo, std::io::Error> {
        let mut kind = SysFsType::ClassThermal(ThermalInfo::new());
        Self::iterate(&mut kind)?;
        match kind {
            SysFsType::ClassThermal(temp) => Ok(temp),
            _ => panic!(""),
        }
    }
}