use std::ptr::null_mut;
use crate::sys::sid::Sid;
use crate::sys::utils::to_utf8_str;
use crate::{Gid, Group, GroupInner};
use windows::Win32::NetworkManagement::NetManagement::{
LG_INCLUDE_INDIRECT, LOCALGROUP_USERS_INFO_0, MAX_PREFERRED_LENGTH, NERR_Success,
NetApiBufferFree, NetUserGetLocalGroups,
};
use windows::Win32::Security::Authentication::Identity::LsaFreeReturnBuffer;
use windows::core::PCWSTR;
pub(super) struct NetApiBuffer<T>(pub(super) *mut T);
impl<T> Drop for NetApiBuffer<T> {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { NetApiBufferFree(Some(self.0.cast())) };
}
}
}
impl<T> Default for NetApiBuffer<T> {
fn default() -> Self {
Self(null_mut())
}
}
impl<T> NetApiBuffer<T> {
pub(super) fn inner_mut(&mut self) -> &mut *mut T {
assert!(self.0.is_null());
&mut self.0
}
pub(super) unsafe fn inner_mut_as_bytes(&mut self) -> &mut *mut u8 {
unsafe { &mut *(self.inner_mut() as *mut *mut T as *mut *mut u8) }
}
}
pub(super) struct LsaBuffer<T>(pub(super) *mut T);
impl<T> Drop for LsaBuffer<T> {
fn drop(&mut self) {
if !self.0.is_null() {
let _r = unsafe { LsaFreeReturnBuffer(self.0 as *mut _) };
}
}
}
impl<T> Default for LsaBuffer<T> {
fn default() -> Self {
Self(null_mut())
}
}
impl<T> LsaBuffer<T> {
pub(super) fn inner_mut(&mut self) -> &mut *mut T {
assert!(self.0.is_null());
&mut self.0
}
}
pub(super) unsafe fn get_groups_for_user(username: PCWSTR) -> Vec<Group> {
let mut buf: NetApiBuffer<LOCALGROUP_USERS_INFO_0> = Default::default();
let mut nb_entries = 0;
let mut total_entries = 0;
let mut groups: Vec<Group>;
let status = unsafe {
NetUserGetLocalGroups(
PCWSTR::null(),
username,
0,
LG_INCLUDE_INDIRECT,
buf.inner_mut_as_bytes(),
MAX_PREFERRED_LENGTH,
&mut nb_entries,
&mut total_entries,
)
};
if status == NERR_Success {
groups = Vec::with_capacity(nb_entries as _);
if !buf.0.is_null() {
unsafe {
let entries = std::slice::from_raw_parts(buf.0, nb_entries as _);
groups.extend(entries.iter().filter_map(|entry| {
let name = to_utf8_str(entry.lgrui0_name);
match Sid::from_account_name(&name) {
Some(sid) => Some(Group {
inner: GroupInner::new(Gid(sid), name),
}),
None => {
sinf_debug!("Failed to resolve the SID for group {name:?}");
None
}
}
}));
}
}
} else {
groups = Vec::new();
sinf_debug!("NetUserGetLocalGroups failed with ret code {}", status);
}
groups
}