sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::cell::OnceCell;
use std::sync::OnceLock;

use windows::Win32::Foundation::SysAllocString;
use windows::Win32::Security::PSECURITY_DESCRIPTOR;
use windows::Win32::System::Com::{
    CLSCTX_INPROC_SERVER, CoCreateInstance, CoInitializeEx, CoInitializeSecurity,
    CoSetProxyBlanket, EOAC_NONE, RPC_C_AUTHN_LEVEL_CALL, RPC_C_AUTHN_LEVEL_DEFAULT,
    RPC_C_IMP_LEVEL_IMPERSONATE,
};
use windows::Win32::System::Rpc::{RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE};
use windows::Win32::System::Variant::{VARIANT, VariantClear};
use windows::Win32::System::Wmi::{
    IEnumWbemClassObject, IWbemLocator, IWbemServices, WBEM_FLAG_FORWARD_ONLY,
    WBEM_FLAG_NONSYSTEM_ONLY, WBEM_FLAG_RETURN_IMMEDIATELY, WBEM_INFINITE, WbemLocator,
};
use windows::core::w;

macro_rules! bstr {
    ($x:literal) => {{ SysAllocString(w!($x)) }};
}

pub(super) struct Connection {
    instance: Option<IWbemLocator>,
    server_connection: Option<IWbemServices>,
    enumerator: Option<IEnumWbemClassObject>,
}

#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl Send for Connection {}
unsafe impl Sync for Connection {}

static SECURITY: OnceLock<Result<(), ()>> = OnceLock::new();
thread_local! {
    pub static CONNECTION: OnceCell<Result<(), ()>> = const { OnceCell::new() };
}

unsafe fn initialize_connection() -> Result<(), ()> {
    if unsafe { CoInitializeEx(None, Default::default()) }.is_err() {
        sinf_debug!("Failed to initialize connection");
        Err(())
    } else {
        Ok(())
    }
}

unsafe fn initialize_security() -> Result<(), ()> {
    if unsafe {
        CoInitializeSecurity(
            Some(PSECURITY_DESCRIPTOR::default()),
            -1,
            None,
            None,
            RPC_C_AUTHN_LEVEL_DEFAULT,
            RPC_C_IMP_LEVEL_IMPERSONATE,
            None,
            EOAC_NONE,
            None,
        )
    }
    .is_err()
    {
        sinf_debug!("Failed to initialize security");
        Err(())
    } else {
        Ok(())
    }
}

impl Connection {
    #[allow(clippy::unnecessary_wraps)]
    pub(super) fn new() -> Option<Connection> {
        if CONNECTION
            .with(|x| *x.get_or_init(|| unsafe { initialize_connection() }))
            .is_err()
            || SECURITY
                .get_or_init(|| unsafe { initialize_security() })
                .is_err()
        {
            return None;
        }
        Some(Connection {
            instance: None,
            server_connection: None,
            enumerator: None,
        })
    }

    pub(super) fn create_instance(mut self) -> Option<Connection> {
        let instance =
            unsafe { CoCreateInstance(&WbemLocator, None, CLSCTX_INPROC_SERVER) }.ok()?;
        self.instance = Some(instance);
        Some(self)
    }

    pub(super) fn connect_server(mut self) -> Option<Connection> {
        let instance = self.instance.as_ref()?;
        let svc = unsafe {
            instance.ConnectServer(
                &bstr!("root\\WMI"),
                &Default::default(),
                &Default::default(),
                &Default::default(),
                0,
                &Default::default(),
                None,
            )
        }
        .ok()?;

        self.server_connection = Some(svc);
        Some(self)
    }

    pub(super) fn set_proxy_blanket(self) -> Option<Connection> {
        unsafe {
            CoSetProxyBlanket(
                self.server_connection.as_ref()?,
                RPC_C_AUTHN_WINNT,
                RPC_C_AUTHZ_NONE,
                None,
                RPC_C_AUTHN_LEVEL_CALL,
                RPC_C_IMP_LEVEL_IMPERSONATE,
                None,
                EOAC_NONE,
            )
        }
        .ok()?;

        Some(self)
    }

    pub(super) fn exec_query(mut self) -> Option<Connection> {
        let server_connection = self.server_connection.as_ref()?;

        let enumerator = unsafe {
            server_connection.ExecQuery(
                &bstr!("WQL"),
                &bstr!("SELECT * FROM MSAcpi_ThermalZoneTemperature"),
                WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                None,
            )
        }
        .ok()?;

        self.enumerator = Some(enumerator);
        Some(self)
    }

    pub(super) fn temperature(&mut self, get_critical: bool) -> Option<(f32, Option<f32>)> {
        let enumerator = self.enumerator.take()?;

        let mut nb_returned = 0;
        let mut obj = [None; 1];

        unsafe {
            let _r = enumerator.Next(
                WBEM_INFINITE, // Time out
                obj.as_mut_slice(),
                &mut nb_returned,
            );

            if nb_returned == 0 {
                return None; // Likely caused by insufficient permissions.
            }

            let class_obj = match &mut obj {
                [Some(co)] => co,
                _ => return None,
            };

            let _r = class_obj.BeginEnumeration(WBEM_FLAG_NONSYSTEM_ONLY.0);

            let mut variant = std::mem::MaybeUninit::<VARIANT>::uninit();
            // `Get` initializes the variant only on success, so an early return is safe.
            class_obj
                .Get(
                    w!("CurrentTemperature"),
                    0,
                    variant.as_mut_ptr(),
                    None,
                    None,
                )
                .ok()?;

            let mut variant = variant.assume_init();

            // The temperature is given in tenths of a degree Kelvin.
            let temp = (variant.Anonymous.decVal.Anonymous2.Lo64 / 10) as f32 - 273.15;
            let _r = VariantClear(&mut variant);

            let mut critical = None;
            if get_critical {
                class_obj
                    .Get(w!("CriticalTripPoint"), 0, &mut variant, None, None)
                    .ok()?;

                // The temperature is given in tenths of a degree Kelvin.
                critical = Some((variant.Anonymous.decVal.Anonymous2.Lo64 / 10) as f32 - 273.15);
                let _r = VariantClear(&mut variant);
            }

            Some((temp, critical))
        }
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        // These three calls enforce the drop order.
        self.enumerator.take();
        self.server_connection.take();
        self.instance.take();
    }
}