use std::ptr;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE, REG_CREATED_NEW_KEY,
REG_OPTION_VOLATILE, REG_QWORD, RegCloseKey, RegCreateKeyExW, RegQueryValueExW, RegSetValueExW,
};
const KEY: &str = r"Software\kaeru\Session";
const VALUE: &str = "Id";
pub fn session_id() -> Result<String> {
session_id_at(KEY)
}
fn session_id_at(path: &str) -> Result<String> {
let (key, created) = Key::create_volatile(path)?;
if !created {
for _ in 0..50 {
if let Some(id) = key.read_u64(VALUE)? {
return Ok(format!("win-{id}"));
}
thread::sleep(Duration::from_millis(2));
}
}
let id = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_millis() as u64);
key.write_u64(VALUE, id)?;
Ok(format!("win-{id}"))
}
struct Key(HKEY);
impl Key {
fn create_volatile(path: &str) -> Result<(Key, bool)> {
let wide_path = wide(path);
let mut key: HKEY = ptr::null_mut();
let mut disposition = 0;
let status = unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
wide_path.as_ptr(),
0,
ptr::null(),
REG_OPTION_VOLATILE,
KEY_QUERY_VALUE | KEY_SET_VALUE,
ptr::null(),
&mut key,
&mut disposition,
)
};
if status != ERROR_SUCCESS {
bail!("can't open the registry key {path} (error {status})");
}
Ok((Key(key), disposition == REG_CREATED_NEW_KEY))
}
fn read_u64(&self, name: &str) -> Result<Option<u64>> {
let wide_name = wide(name);
let mut kind = 0;
let mut data = [0u8; 8];
let mut size = data.len() as u32;
let status = unsafe {
RegQueryValueExW(
self.0,
wide_name.as_ptr(),
ptr::null(),
&mut kind,
data.as_mut_ptr(),
&mut size,
)
};
match status {
ERROR_SUCCESS if kind == REG_QWORD && size == 8 => Ok(Some(u64::from_le_bytes(data))),
ERROR_SUCCESS | ERROR_FILE_NOT_FOUND => Ok(None),
_ => bail!("can't read the registry value {name} (error {status})"),
}
}
fn write_u64(&self, name: &str, value: u64) -> Result<()> {
let wide_name = wide(name);
let data = value.to_le_bytes();
let status = unsafe {
RegSetValueExW(
self.0,
wide_name.as_ptr(),
0,
REG_QWORD,
data.as_ptr(),
data.len() as u32,
)
};
if status != ERROR_SUCCESS {
bail!("can't write the registry value {name} (error {status})");
}
Ok(())
}
}
impl Drop for Key {
fn drop(&mut self) {
unsafe { RegCloseKey(self.0) };
}
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(Some(0)).collect()
}
#[cfg(test)]
mod tests {
use windows_sys::Win32::System::Registry::RegDeleteTreeW;
use super::*;
fn delete(path: &str) {
let wide_path = wide(path);
unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, wide_path.as_ptr()) };
}
#[test]
fn the_id_stays_the_same_within_a_session() {
let root = format!(r"Software\kaeru-test-{}", std::process::id());
let path = format!(r"{root}\Session");
let first = session_id_at(&path);
let second = session_id_at(&path);
delete(&root);
let first = first.unwrap();
assert!(first.starts_with("win-"));
assert_eq!(second.unwrap(), first);
}
}