use std::{
ffi::OsString,
fs::{File, OpenOptions},
io,
os::windows::ffi::OsStringExt,
path::{Path, PathBuf},
ptr,
};
use anyhow::Context;
use windows_sys::Win32::{
Foundation::{CloseHandle, HANDLE},
Security::TOKEN_QUERY,
System::Threading::{GetCurrentProcess, OpenProcessToken},
UI::Shell::GetUserProfileDirectoryW,
};
pub(crate) fn account_lock_path(file_name: &str, what: &str) -> anyhow::Result<PathBuf> {
let home = account_home()
.with_context(|| format!("could not look up the account profile for the {what} lock"))?
.canonicalize()
.context("could not resolve the account profile")?;
if !home.is_dir() {
anyhow::bail!("{what} lock home {} must be a directory", home.display());
}
Ok(home.join(file_name))
}
fn account_home() -> io::Result<PathBuf> {
let mut token: HANDLE = ptr::null_mut();
if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
return Err(io::Error::last_os_error());
}
let mut len = 0;
unsafe { GetUserProfileDirectoryW(token, ptr::null_mut(), &mut len) };
let mut home = vec![0_u16; len as usize];
let read = unsafe { GetUserProfileDirectoryW(token, home.as_mut_ptr(), &mut len) };
let error = io::Error::last_os_error();
unsafe { CloseHandle(token) };
if read == 0 {
return Err(error);
}
let end = home
.iter()
.position(|&unit| unit == 0)
.unwrap_or(home.len());
Ok(OsString::from_wide(&home[..end]).into())
}
pub(crate) fn lock_account_file(path: &Path, what: &str) -> anyhow::Result<File> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.with_context(|| format!("could not open {what} mutation lock {}", path.display()))?;
fs2::FileExt::lock_exclusive(&file)
.with_context(|| format!("could not lock {what} mutations at {}", path.display()))?;
Ok(file)
}