sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;

use crate::{Disk, DiskKind, DiskRefreshKind};

use windows::Win32::Storage::FileSystem::GetDriveTypeW;
use windows::Win32::System::WindowsProgramming::{
    DRIVE_CDROM, DRIVE_FIXED, DRIVE_REMOTE, DRIVE_REMOVABLE,
};
use windows::core::PCWSTR;

use super::DiskInner;
use super::volume::{
    get_logical_drive_strings, get_volume_guid_paths, get_volume_information,
    get_volume_path_names_for_volume_name, get_volume_serial_number,
};

pub(crate) unsafe fn get_list(
    disks: &mut Vec<Disk>,
    remove_not_listed_disks: bool,
    refreshes: DiskRefreshKind,
) {
    get_local_volumes(disks, refreshes);
    if refreshes.network() {
        get_remote_volumes(disks, refreshes);
    }

    if remove_not_listed_disks {
        disks.retain_mut(|disk| {
            if !disk.inner.updated {
                return false;
            }
            disk.inner.updated = false;
            true
        });
    } else {
        for c in disks.iter_mut() {
            c.inner.updated = false;
        }
    }
}

fn get_local_volumes(disks: &mut Vec<Disk>, refreshes: DiskRefreshKind) {
    for volume_name in get_volume_guid_paths() {
        let mount_paths = unsafe { get_volume_path_names_for_volume_name(&volume_name[..]) };
        if mount_paths.is_empty() {
            continue;
        }

        let raw_volume_name = PCWSTR::from_raw(volume_name.as_ptr());
        let drive_type = unsafe { GetDriveTypeW(raw_volume_name) };

        if !matches!(drive_type, DRIVE_FIXED | DRIVE_REMOVABLE | DRIVE_CDROM) {
            continue;
        }

        let is_removable = matches!(drive_type, DRIVE_REMOVABLE | DRIVE_CDROM);

        let Some((name, file_system, is_read_only)) = get_volume_information(raw_volume_name)
        else {
            continue;
        };

        // The device path is the volume name without the trailing backslash.
        let device_path = volume_name[..volume_name.len().saturating_sub(2)]
            .iter()
            .copied()
            .chain([0])
            .collect::<Vec<_>>();

        for mount_path in mount_paths {
            if let Some(disk) = disks
                .iter_mut()
                .find(|d| d.inner.mount_point == mount_path && d.inner.file_system == file_system)
            {
                disk.refresh_specifics(refreshes);
                disk.inner.updated = true;
                continue;
            }

            // FIXME: replace with `std::os::windows::fs::MetadataExt::volume_serial_number` once it is stable: https://github.com/rust-lang/rust/issues/63010
            let volume_serial_number = unsafe { get_volume_serial_number(&mount_path) };

            let s_mount_point =
                OsString::from_wide(&mount_path[..mount_path.len().saturating_sub(1)]);

            disks
                .push_mut(new_disk(
                    DiskKind::Unknown(-1),
                    name.clone(),
                    volume_serial_number,
                    file_system.clone(),
                    mount_path,
                    s_mount_point,
                    is_removable,
                    is_read_only,
                    device_path.clone(),
                ))
                .refresh_specifics(refreshes);
        }
    }
}

fn get_remote_volumes(disks: &mut Vec<Disk>, refreshes: DiskRefreshKind) {
    for mount_path in get_logical_drive_strings() {
        let raw_mount_path = PCWSTR::from_raw(mount_path.as_ptr());
        let drive_type = unsafe { GetDriveTypeW(raw_mount_path) };

        if drive_type != DRIVE_REMOTE {
            continue;
        }

        let Some((name, file_system, is_read_only)) = get_volume_information(raw_mount_path) else {
            continue;
        };

        // `CreateFileW` expects `device_path` in the form `\\.\${local_path}`, without a trailing backslash.
        let device_path = r"\\.\"
            .encode_utf16()
            .chain(
                mount_path[..mount_path.len().saturating_sub(2)]
                    .iter()
                    .copied(),
            )
            .chain([0])
            .collect::<Vec<_>>();

        if let Some(disk) = disks
            .iter_mut()
            .find(|d| d.inner.mount_point == mount_path && d.inner.file_system == file_system)
        {
            disk.refresh_specifics(refreshes);
            disk.inner.updated = true;
            continue;
        }

        // FIXME: replace with `std::os::windows::fs::MetadataExt::volume_serial_number` when stable https://github.com/rust-lang/rust/issues/63010
        let volume_serial_number = unsafe { get_volume_serial_number(&mount_path) };

        let s_mount_point = OsString::from_wide(&mount_path[..mount_path.len().saturating_sub(1)]);

        disks
            .push_mut(new_disk(
                DiskKind::Network,
                name,
                volume_serial_number,
                file_system,
                mount_path,
                s_mount_point,
                true,
                is_read_only,
                device_path,
            ))
            .refresh_specifics(refreshes);
    }
}

#[allow(clippy::too_many_arguments)]
fn new_disk(
    type_: DiskKind,
    name: OsString,
    volume_serial_number: Option<u32>,
    file_system: OsString,
    mount_point: Vec<u16>,
    s_mount_point: OsString,
    is_removable: bool,
    is_read_only: bool,
    device_path: Vec<u16>,
) -> Disk {
    Disk {
        inner: DiskInner {
            type_,
            name,
            volume_serial_number,
            file_system,
            mount_point,
            s_mount_point,
            total_space: 0,
            available_space: 0,
            is_removable,
            is_read_only,
            device_path,
            old_written_bytes: 0,
            old_read_bytes: 0,
            written_bytes: 0,
            read_bytes: 0,
            updated: true,
        },
    }
}