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::sys::utils::HandleWrapper;

use windows::Win32::Foundation::MAX_PATH;
use windows::Win32::Storage::FileSystem::{
    BY_HANDLE_FILE_INFORMATION, FILE_ACCESS_RIGHTS, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE,
    FILE_SHARE_READ, FILE_SHARE_WRITE, FindFirstVolumeW, FindNextVolumeW, FindVolumeClose,
    GetDiskFreeSpaceExW, GetFileInformationByHandle, GetLogicalDriveStringsW,
    GetVolumeInformationW, GetVolumePathNamesForVolumeNameW,
};
use windows::Win32::System::SystemServices::FILE_READ_ONLY_VOLUME;
use windows::core::{Error, HRESULT, PCWSTR};

/// Copies the first zero-terminated wide string in `buf`.
fn from_zero_terminated(buf: &[u16]) -> Vec<u16> {
    let end = buf
        .iter()
        .position(|&x| x == 0)
        .map_or(buf.len(), |position| position + 1);
    buf[..end].to_vec()
}

// Volume names are realistically no longer than 44 characters, but the Microsoft documentation example also uses MAX_PATH.
const VOLUME_NAME_SIZE: usize = MAX_PATH as usize + 1;

const ERROR_NO_MORE_FILES: HRESULT = windows::Win32::Foundation::ERROR_NO_MORE_FILES.to_hresult();
const ERROR_MORE_DATA: HRESULT = windows::Win32::Foundation::ERROR_MORE_DATA.to_hresult();

/// Returns a list of zero-terminated wide strings containing volume GUID paths.
pub(super) fn get_volume_guid_paths() -> Vec<Vec<u16>> {
    let mut volume_names = Vec::new();
    unsafe {
        let mut buf = Box::new([0u16; VOLUME_NAME_SIZE]);
        let Ok(handle) = FindFirstVolumeW(&mut buf[..]) else {
            sinf_debug!(
                "Error: FindFirstVolumeW() = {:?}",
                Error::from_thread().code()
            );
            return Vec::new();
        };
        volume_names.push(from_zero_terminated(&buf[..]));
        loop {
            if FindNextVolumeW(handle, &mut buf[..]).is_err() {
                if Error::from_thread().code() != ERROR_NO_MORE_FILES {
                    sinf_debug!("Error: FindNextVolumeW = {}", Error::from_thread().code());
                }
                break;
            }
            volume_names.push(from_zero_terminated(&buf[..]));
        }
        if FindVolumeClose(handle).is_err() {
            sinf_debug!("Error: FindVolumeClose = {:?}", Error::from_thread().code());
        };
    }
    volume_names
}

/// Given a volume GUID path (`\\?\{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}\`), returns all volume paths (drive letters and mount paths) associated with it as
pub(super) unsafe fn get_volume_path_names_for_volume_name(
    volume_guid_path: &[u16],
) -> Vec<Vec<u16>> {
    let volume_guid_path = PCWSTR::from_raw(volume_guid_path.as_ptr());

    // The initial buffer size is a guess.
    let mut path_names_buf = vec![0u16; MAX_PATH as usize];
    let mut path_names_output_size = 0u32;
    for _ in 0..10 {
        let volume_path_names = unsafe {
            GetVolumePathNamesForVolumeNameW(
                volume_guid_path,
                Some(path_names_buf.as_mut_slice()),
                &mut path_names_output_size,
            )
        };
        let code = volume_path_names.map_err(|_| Error::from_thread().code());
        match code {
            Ok(()) => break,
            Err(ERROR_MORE_DATA) => {
                // A larger buffer is required; path_names_output_size holds its size.
                path_names_buf = vec![0u16; path_names_output_size as usize];
                continue;
            }
            Err(_e) => {
                sinf_debug!("Error: GetVolumePathNamesForVolumeNameW() = {}", _e);
                return Vec::new();
            }
        }
    }

    // path_names_buf contains multiple zero-terminated wide strings.
    let mut path_names = Vec::new();
    let mut buf = &path_names_buf[..];
    while !buf.is_empty() && buf[0] != 0 {
        let path = from_zero_terminated(buf);
        buf = &buf[path.len()..];
        path_names.push(path);
    }
    path_names
}

pub(super) fn get_logical_drive_strings() -> Vec<Vec<u16>> {
    unsafe {
        let required = GetLogicalDriveStringsW(None);

        if required == 0 {
            sinf_debug!(
                "GetLogicalDriveStringsW failed: {:?}",
                windows::core::Error::from_thread().code()
            );
            return Vec::new();
        }

        // The return value of `GetLogicalDriveStringsW` does not include '\0'
        let mut buffer = vec![0u16; required as usize + 1];

        for _ in 0..3 {
            let len = GetLogicalDriveStringsW(Some(&mut buffer));

            if len == 0 {
                sinf_debug!(
                    "GetLogicalDriveStringsW failed: {:?}",
                    windows::core::Error::from_thread().code()
                );
                return Vec::new();
            }

            if len as usize <= buffer.len() {
                // `GetLogicalDriveStringsW` returns a multi-string: '\0' terminates a string, and an additional '\0' terminates the list.
                return buffer[..(len as usize)]
                    .split_inclusive(|w| *w == 0)
                    .filter(|s| s.len() > 1) // A length of 1 or less means only `\0` is present
                    .map(|s| s.to_vec())
                    .collect();
            }

            buffer.resize(len as usize + 1, 0);
        }

        sinf_debug!("GetLogicalDriveStringsW failed after 3 retries");
        Vec::new()
    }
}

pub(super) unsafe fn get_drive_size(mount_point: &[u16]) -> Option<(u64, u64)> {
    let mut total_size = 0;
    let mut available_space = 0;
    let lpdirectoryname = PCWSTR::from_raw(mount_point.as_ptr());
    if unsafe {
        GetDiskFreeSpaceExW(
            lpdirectoryname,
            None,
            Some(&mut total_size),
            Some(&mut available_space),
        )
    }
    .is_ok()
    {
        Some((total_size, available_space))
    } else {
        None
    }
}

// Returns a tuple of (name, file system, read-only flag).
pub(super) fn get_volume_information(volume: PCWSTR) -> Option<(OsString, OsString, bool)> {
    let mut name = [0u16; MAX_PATH as usize + 1];
    let mut file_system = [0u16; 32];
    let mut flags = 0;
    let volume_info_res = unsafe {
        GetVolumeInformationW(
            volume,
            Some(&mut name),
            None,
            None,
            Some(&mut flags),
            Some(&mut file_system),
        )
    }
    .is_ok();

    if volume_info_res {
        let name = os_string_from_zero_terminated(&name);
        let file_system = os_string_from_zero_terminated(&file_system);
        let is_read_only = (flags & FILE_READ_ONLY_VOLUME) != 0;

        Some((name, file_system, is_read_only))
    } else {
        sinf_debug!(
            "Error: GetVolumeInformationW = {:?}",
            windows::core::Error::from_thread().code()
        );
        None
    }
}

/// # Safety The `path` argument must be a NULL-terminated wide string.
pub(super) unsafe fn get_volume_serial_number(path: &[u16]) -> Option<u32> {
    unsafe {
        if let Some(handle) = HandleWrapper::new_from_file(
            path,
            FILE_ACCESS_RIGHTS(0),
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            FILE_FLAG_BACKUP_SEMANTICS,
        ) {
            let mut info = std::mem::MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();

            if GetFileInformationByHandle(handle.0, info.as_mut_ptr()).is_ok() {
                Some(info.assume_init().dwVolumeSerialNumber)
            } else {
                None
            }
        } else {
            None
        }
    }
}

fn os_string_from_zero_terminated(name: &[u16]) -> OsString {
    let len = name.iter().position(|&x| x == 0).unwrap_or(name.len());
    OsString::from_wide(&name[..len])
}

#[cfg(test)]
mod tests {
    use super::from_zero_terminated;

    #[test]
    fn from_zero_terminated_keeps_terminator() {
        assert_eq!(
            from_zero_terminated(&[b'A' as u16, b'B' as u16, 0, 0]),
            [65, 66, 0]
        );
    }

    #[test]
    fn from_zero_terminated_without_nul_keeps_entire_buffer() {
        assert_eq!(from_zero_terminated(&[1, 2, 3]), [1, 2, 3]);
    }

    #[test]
    fn from_zero_terminated_empty_buffer() {
        assert_eq!(from_zero_terminated(&[]), Vec::<u16>::new());
    }
}