sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use super::*;

pub(super) fn get_actual_device_name(device: &OsStr) -> String {
    let device_path = PathBuf::from(device);

    std::fs::canonicalize(&device_path)
        .ok()
        .and_then(|path| path.strip_prefix("/dev").ok().map(Path::to_path_buf))
        .unwrap_or(device_path)
        .to_str()
        .map(str::to_owned)
        .unwrap_or_default()
}

pub(super) fn new_disk(
    device_name: &OsStr,
    mount_point: &Path,
    file_system: &OsStr,
    type_: DiskKind,
    removable_entries: &[PathBuf],
    procfs_disk_stats: &HashMap<String, DiskStat>,
    refresh_kind: DiskRefreshKind,
) -> Disk {
    let is_removable = removable_entries
        .iter()
        .any(|e| e.as_os_str() == device_name);

    let device_id = std::fs::metadata(mount_point)
        .ok()
        .map(|metadata| metadata.dev());

    let mut disk = Disk {
        inner: DiskInner {
            type_,
            device_id,
            device_name: device_name.to_owned(),
            actual_device_name: None,
            file_system: file_system.to_owned(),
            mount_point: mount_point.to_owned(),
            total_space: 0,
            available_space: 0,
            is_removable,
            is_read_only: false,
            old_read_bytes: 0,
            old_written_bytes: 0,
            read_bytes: 0,
            written_bytes: 0,
            updated: true,
        },
    };
    disk.inner
        .efficient_refresh(refresh_kind, procfs_disk_stats, true);
    disk
}

pub(super) fn find_type_for_device_name(device_name: &OsStr) -> DiskKind {
    let device_path = fs::canonicalize(device_name).unwrap_or_else(|_| PathBuf::from(device_name));
    let Some(device_name) = device_path.file_name() else {
        return DiskKind::Unknown(-1);
    };

    let device_sysfs_path = Path::new("/sys/class/block").join(device_name);
    let mut device_sysfs_real_path = device_sysfs_path
        .canonicalize()
        .unwrap_or(device_sysfs_path.clone());

    // Partitions (sdX, nvmeXnYpZ, etc.).
    if device_sysfs_path.join("partition").exists() {
        // The path behind the symlink has a hierarchy (e.g. /sys/devices/${some_path}/sda/sda1).
        let Some(parent) = device_sysfs_real_path.parent() else {
            return DiskKind::Unknown(-1);
        };

        device_sysfs_real_path = parent.to_path_buf();
    }

    // The loop device is used to mount files as block devices.
    if device_sysfs_real_path.join("loop/backing_file").exists() {
        return DiskKind::DiskImage;
    }

    // `/sys/devices` has a hierarchy.
    let mut current_sysfs_path = device_sysfs_real_path.clone();
    loop {
        if let Ok(subsystem) = current_sysfs_path.join("subsystem").read_link()
            && let Some(filename) = subsystem.file_name()
            && matches!(
                filename.to_string_lossy().as_ref(),
                "firewire" | "mmc" | "pcmcia" | "sdio" | "usb"
            )
        {
            return DiskKind::External;
        }

        let Some(parent) = current_sysfs_path.parent() else {
            // Reached the root.
            break;
        };
        current_sysfs_path = parent.to_path_buf();
    }

    let rotational_path = device_sysfs_real_path.join("queue/rotational");
    // This file normally contains only '0' or '1', but 8 bytes are read to be safe.
    match get_all_utf8_data(rotational_path, 8)
        .unwrap_or_default()
        .trim()
        .parse()
        .ok()
    {
        // Marked as rotational, so this is an HDD.
        Some(1) => DiskKind::HDD,
        // Marked as non-rotational, so this is very likely an SSD.
        Some(0) => DiskKind::SSD,
        // Normally this should not happen, but unexpected values are preserved.
        Some(x) => DiskKind::Unknown(x),
        // The information is not available.
        None => DiskKind::Unknown(-1),
    }
}

pub(super) fn get_all_list(
    container: &mut Vec<Disk>,
    content: &str,
    refresh_kind: DiskRefreshKind,
) {
    // This list holds every removable device (those whose name starts with "usb-").
    let removable_entries = match fs::read_dir("/dev/disk/by-id/") {
        Ok(r) => r
            .filter_map(|res| Some(res.ok()?.path()))
            .filter_map(|e| {
                if e.file_name()
                    .and_then(|x| Some(x.to_str()?.starts_with("usb-")))
                    .unwrap_or_default()
                {
                    e.canonicalize().ok()
                } else {
                    None
                }
            })
            .collect::<Vec<PathBuf>>(),
        _ => Vec::new(),
    };

    let procfs_disk_stats = disk_stats(&refresh_kind);

    for (fs_spec, fs_file, fs_vfstype) in content
        .lines()
        .map(|line| {
            let line = line.trim_start();
            // Mount entry format: http://man7.org/linux/man-pages/man5/fstab.5.html
            let mut fields = line.split_whitespace();
            let fs_spec = fields.next().unwrap_or("");
            let fs_file = fields
                .next()
                .unwrap_or("")
                .replace("\\134", "\\")
                .replace("\\040", " ")
                .replace("\\011", "\t")
                .replace("\\012", "\n");
            let fs_vfstype = fields.next().unwrap_or("");
            (fs_spec, fs_file, fs_vfstype)
        })
        .filter(|(fs_spec, fs_file, fs_vfstype)| {
            // Check whether fs_vfstype belongs to the ignored file systems.
            let filtered = match *fs_vfstype {
                "rootfs" | // https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt
                "sysfs" | // Pseudo file system for kernel objects.
                "proc" |  // Another pseudo file system.
                "devtmpfs" |
                "cgroup" |
                "cgroup2" |
                "pstore" | // https://www.kernel.org/doc/Documentation/ABI/testing/pstore
                "squashfs" | // Compressed read-only file system (used by snaps).
                "rpc_pipefs" | // The pipefs pseudo file system service.
                "iso9660" | // Optical media.
                "devpts" | // https://www.kernel.org/doc/Documentation/filesystems/devpts.txt
                "hugetlbfs" | // https://www.kernel.org/doc/Documentation/vm/hugetlbfs_reserv.txt
                "mqueue" // https://man7.org/linux/man-pages/man7/mq_overview.7.html
                => true,
                "tmpfs" => !cfg!(feature = "linux-tmpfs"),
                // Calling statvfs on a mounted CIFS or NFS file system, or through autofs, may hang when mounted with the `hard` option.
                "cifs" | "nfs" | "nfs4" | "autofs" => !refresh_kind.network(),
                _ => false,
            };

            !(filtered ||
               fs_file.starts_with("/sys") || // Ignored mount point.
               fs_file.starts_with("/proc") ||
               (fs_file.starts_with("/run") && !fs_file.starts_with("/run/media")) ||
               fs_spec.starts_with("sunrpc"))
        })
    {
        let mount_point = Path::new(&fs_file);
        if let Some(disk) = container.iter_mut().find(|d| {
            d.inner.mount_point == mount_point
                && d.inner.device_name == fs_spec
                && d.inner.file_system == fs_vfstype
        }) {
            disk.inner
                .efficient_refresh(refresh_kind, &procfs_disk_stats, false);
            disk.inner.updated = true;
            continue;
        }

        let type_ = match fs_vfstype {
            "cifs" | "nfs" | "nfs4" => DiskKind::Network, //  `cifs` includes SMB1 (CIFS), SMB2 and SMB3
            _ => DiskKind::Unknown(-1),                   //  Updated in `new_disk`.
        };

        container.push(new_disk(
            fs_spec.as_ref(),
            mount_point,
            fs_vfstype.as_ref(),
            type_,
            &removable_entries,
            &procfs_disk_stats,
            refresh_kind,
        ));
    }
}