sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::sys::sid::Sid;
use crate::sys::utils::to_utf8_str;
use crate::{Error, Gid, Group, Uid, User};

use windows::Win32::Foundation::{ERROR_MORE_DATA, LUID};
use windows::Win32::NetworkManagement::NetManagement::{
    FILTER_NORMAL_ACCOUNT, MAX_PREFERRED_LENGTH, NERR_Success, NetUserEnum, NetUserGetInfo,
    USER_INFO_0, USER_INFO_4, USER_INFO_23,
};
use windows::Win32::Security::Authentication::Identity::{
    LsaEnumerateLogonSessions, LsaGetLogonSessionData, SECURITY_LOGON_SESSION_DATA,
    SECURITY_LOGON_TYPE,
};
use windows::core::PCWSTR;

mod groups;

use self::groups::{LsaBuffer, NetApiBuffer, get_groups_for_user};

fn primary_group_sid(user_name: PCWSTR) -> Option<Gid> {
    unsafe {
        let mut info: NetApiBuffer<USER_INFO_4> = Default::default();
        if NetUserGetInfo(PCWSTR::null(), user_name, 4, info.inner_mut_as_bytes()) != NERR_Success
            || info.0.is_null()
        {
            return None;
        }
        let info = &*info.0;
        if info.usri4_primary_group_id == 0 {
            return None;
        }
        let user_sid = Sid::from_psid(info.usri4_user_sid)?;
        user_sid.with_rid(info.usri4_primary_group_id).map(Gid)
    }
}

pub(crate) struct UserInner {
    pub(crate) uid: Uid,
    pub(crate) gid: Option<Gid>,
    pub(crate) name: String,
    c_user_name: Option<Vec<u16>>,
    is_local: bool,
}

impl UserInner {
    fn new(uid: Uid, gid: Option<Gid>, name: String, c_name: PCWSTR, is_local: bool) -> Self {
        let c_user_name = if c_name.is_null() {
            None
        } else {
            Some(unsafe { c_name.as_wide() }.into())
        };
        Self {
            uid,
            gid,
            name,
            c_user_name,
            is_local,
        }
    }

    pub(crate) fn id(&self) -> &Uid {
        &self.uid
    }

    pub(crate) fn group_id(&self) -> Option<Gid> {
        self.gid.clone()
    }

    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    pub(crate) fn groups(&self) -> Vec<Group> {
        if let (Some(c_user_name), true) = (&self.c_user_name, self.is_local) {
            // Convert the wide string to a PCWSTR and ensure it has a null terminator.
            let username = {
                let mut null_terminated = c_user_name.to_vec();
                if null_terminated.last().is_some_and(|v| *v != 0) {
                    null_terminated.push(0);
                }
                null_terminated
            };
            unsafe { get_groups_for_user(PCWSTR::from_raw(username.as_ptr())) }
        } else {
            Vec::new()
        }
    }
}

pub(crate) fn get_users(users: &mut Vec<User>) {
    users.clear();

    let mut resume_handle: u32 = 0;
    unsafe {
        loop {
            let mut buffer: NetApiBuffer<USER_INFO_0> = Default::default();
            let mut nb_read = 0;
            let mut total = 0;
            let status = NetUserEnum(
                PCWSTR::null(),
                0,
                FILTER_NORMAL_ACCOUNT,
                buffer.inner_mut_as_bytes(),
                MAX_PREFERRED_LENGTH,
                &mut nb_read,
                &mut total,
                Some(&mut resume_handle),
            );
            if status == NERR_Success || status == ERROR_MORE_DATA.0 {
                let entries = std::slice::from_raw_parts(buffer.0, nb_read as _);
                for entry in entries {
                    if entry.usri0_name.is_null() {
                        continue;
                    }

                    let mut user: NetApiBuffer<USER_INFO_23> = Default::default();
                    if NetUserGetInfo(
                        PCWSTR::null(),
                        PCWSTR::from_raw(entry.usri0_name.as_ptr()),
                        23,
                        user.inner_mut_as_bytes(),
                    ) == NERR_Success
                        && let Some(sid) = Sid::from_psid((*user.0).usri23_user_sid)
                    {
                        // Prefer the account name derived from the SID, which is usually better, and fall back to the name supplied by
                        let name = sid
                            .account_name()
                            .unwrap_or_else(|| to_utf8_str(entry.usri0_name));
                        let c_name = PCWSTR(entry.usri0_name.0 as *const _);
                        let gid = primary_group_sid(c_name);
                        users.push(User {
                            inner: UserInner::new(Uid(sid), gid, name, c_name, true),
                        });
                    }
                }
            } else {
                sinf_debug!(
                    "NetUserEnum error: {}",
                    if status == windows::Win32::Foundation::ERROR_ACCESS_DENIED.0 {
                        "access denied"
                    } else if status == windows::Win32::Foundation::ERROR_INVALID_LEVEL.0 {
                        "invalid level"
                    } else {
                        "unknown error"
                    }
                );
            }
            if status != ERROR_MORE_DATA.0 {
                break;
            }
        }

        // The first pass is complete; start the second.
        let mut nb_sessions = 0;
        let mut uids: LsaBuffer<LUID> = Default::default();
        if LsaEnumerateLogonSessions(&mut nb_sessions, uids.inner_mut()).is_err() {
            sinf_debug!("LsaEnumerateLogonSessions failed");
        } else {
            let entries = std::slice::from_raw_parts_mut(uids.0, nb_sessions as _);
            for entry in entries {
                let mut data: LsaBuffer<SECURITY_LOGON_SESSION_DATA> = Default::default();
                if LsaGetLogonSessionData(entry, data.inner_mut()).is_ok() && !data.0.is_null() {
                    let data = *data.0;
                    if data.LogonType == SECURITY_LOGON_TYPE::Network.0 as u32 {
                        continue;
                    }

                    let sid = match Sid::from_psid(data.Sid) {
                        Some(sid) => sid,
                        None => continue,
                    };

                    if users.iter().any(|u| u.inner.uid.0 == sid) {
                        continue;
                    }

                    // Prefer the account name derived from the SID, which is usually better, and fall back to the name supplied by
                    let name = sid.account_name().unwrap_or_else(|| {
                        String::from_utf16(std::slice::from_raw_parts(
                            data.UserName.Buffer.as_ptr(),
                            data.UserName.Length as usize / std::mem::size_of::<u16>(),
                        ))
                        .unwrap_or_else(|_err| {
                            sinf_debug!("Failed to convert from UTF-16 string: {}", _err);
                            String::new()
                        })
                    });

                    let mut name_wide: Vec<u16> = name.encode_utf16().collect();
                    name_wide.push(0);
                    let gid = primary_group_sid(PCWSTR::from_raw(name_wide.as_ptr()));
                    users.push(User {
                        inner: UserInner::new(Uid(sid), gid, name, PCWSTR::null(), false),
                    });
                }
            }
        }
    }
}

pub(crate) fn new_users() -> Result<Vec<User>, Error> {
    Ok(Vec::new())
}