kaeru 0.1.4

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
//! Windows: the session id lives in a volatile registry key. Windows deletes
//! volatile keys when the user signs out or the computer restarts, which also
//! covers Fast Startup, where the boot time stays the same. This module also
//! tells whether kaeru reads from a console.

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, INVALID_HANDLE_VALUE};
use windows_sys::Win32::System::Console::{GetConsoleMode, GetStdHandle, STD_INPUT_HANDLE};
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,
};

/// The volatile key, under the current user's part of the registry.
const KEY: &str = r"Software\kaeru\Session";

/// The value that holds the id: the time the key was created, in
/// milliseconds since the Unix epoch.
const VALUE: &str = "Id";

/// Returns the id of the current sign-in, creating it on first use.
///
/// # Errors
///
/// Fails when the registry key can't be created, read or written.
pub fn session_id() -> Result<String> {
    session_id_at(KEY)
}

/// Returns the id stored in the volatile key at `path`, creating it on first
/// use.
fn session_id_at(path: &str) -> Result<String> {
    let (key, created) = Key::create_volatile(path)?;
    if !created {
        // Another process created the key and writes the id right after, so
        // a missing id is given a moment to appear.
        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}"))
}

/// An open registry key, closed when dropped.
struct Key(HKEY);

impl Key {
    /// Opens the volatile key at `path` under the current user, creating it
    /// and its missing parents. Returns whether this call created it.
    fn create_volatile(path: &str) -> Result<(Key, bool)> {
        let wide_path = wide(path);
        let mut key: HKEY = ptr::null_mut();
        let mut disposition = 0;
        // SAFETY: `wide_path` is a null-terminated UTF-16 string that lives
        // until the call returns, the class and security pointers may be
        // null, and the two out pointers point to live local variables.
        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))
    }

    /// Returns the 64-bit number in the value `name`, or `None` when the
    /// value is missing or holds something else.
    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;
        // SAFETY: the key is open, `wide_name` is a null-terminated UTF-16
        // string, and `data` has room for the `size` bytes the call may
        // write.
        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})"),
        }
    }

    /// Writes a 64-bit number to the value `name`.
    fn write_u64(&self, name: &str, value: u64) -> Result<()> {
        let wide_name = wide(name);
        let data = value.to_le_bytes();
        // SAFETY: the key is open, `wide_name` is a null-terminated UTF-16
        // string, and `data` holds the `data.len()` bytes that are passed.
        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) {
        // SAFETY: the key was opened by `create_volatile` and is closed only
        // here, once.
        unsafe { RegCloseKey(self.0) };
    }
}

/// Returns whether kaeru's standard input is a Windows console, which the
/// picker needs. In mintty, a Windows program reads from a pipe, which Rust's
/// `is_terminal` counts as a terminal, because MSYS programs can use it as
/// one.
pub fn has_console_input() -> bool {
    // SAFETY: GetStdHandle takes no pointers, and returns a handle, a null
    // handle or INVALID_HANDLE_VALUE.
    let input = unsafe { GetStdHandle(STD_INPUT_HANDLE) };
    if input.is_null() || input == INVALID_HANDLE_VALUE {
        return false;
    }
    let mut mode = 0;
    // SAFETY: `input` is this process's standard input handle, and `mode`
    // is a valid place for the call to write the console's mode to.
    unsafe { GetConsoleMode(input, &mut mode) != 0 }
}

/// Returns `text` as a null-terminated UTF-16 string, as the Windows API
/// takes it.
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::*;

    /// Deletes the test's key tree, so that the test leaves the registry as
    /// it found it.
    fn delete(path: &str) {
        let wide_path = wide(path);
        // SAFETY: `wide_path` is a null-terminated UTF-16 string that lives
        // until the call returns.
        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);
    }
}