rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! What it takes to run a local server out of sight: used for T3 Code's and VS Code's.

use std::net::{Ipv4Addr, TcpListener};
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};

pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;

#[repr(C)]
#[derive(Default)]
struct BasicLimits {
    process_time: i64,
    job_time: i64,
    flags: u32,
    min_working_set: usize,
    max_working_set: usize,
    active_processes: u32,
    affinity: usize,
    priority: u32,
    scheduling: u32,
}

#[repr(C)]
#[derive(Default)]
struct ExtendedLimits {
    basic: BasicLimits,
    io: [u64; 6],
    process_memory: usize,
    job_memory: usize,
    peak_process_memory: usize,
    peak_job_memory: usize,
}

use super::win32::{CloseHandle, GetStdHandle};

#[link(name = "kernel32")]
unsafe extern "system" {
    fn CreateJobObjectW(attributes: *const u8, name: *const u16) -> isize;
    fn SetInformationJobObject(job: isize, class: i32, info: *const ExtendedLimits, size: u32) -> i32;
    fn AssignProcessToJobObject(job: isize, process: isize) -> i32;
    fn SetHandleInformation(handle: isize, mask: u32, flags: u32) -> i32;
    fn OpenProcess(access: u32, inherit: i32, id: u32) -> isize;
    fn WaitForSingleObject(handle: isize, milliseconds: u32) -> u32;
}

#[link(name = "bcrypt")]
unsafe extern "system" {
    fn BCryptGenRandom(algorithm: isize, buffer: *mut u8, length: u32, flags: u32) -> i32;
}

/// A group of processes that Windows ends together when this is dropped, or when the
/// process holding it ends for any reason, so a server can't be left behind unwatched.
pub struct Job(isize);

impl Job {
    pub fn holding(child: &Child) -> Option<Job> {
        const EXTENDED_LIMIT_INFORMATION: i32 = 9;
        const KILL_ON_JOB_CLOSE: u32 = 0x2000;
        // SAFETY: a new unnamed job; its handle is closed by `Drop`.
        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if job == 0 {
            return None;
        }
        let job = Job(job);
        let mut limits = ExtendedLimits::default();
        limits.basic.flags = KILL_ON_JOB_CLOSE;
        // SAFETY: `limits` is the structure this class takes, passed with its own size,
        // and the child's handle is open for as long as `child` is borrowed.
        let done = unsafe {
            SetInformationJobObject(job.0, EXTENDED_LIMIT_INFORMATION, &limits, size_of::<ExtendedLimits>() as u32) != 0
                && AssignProcessToJobObject(job.0, child.as_raw_handle() as isize) != 0
        };
        done.then_some(job)
    }
}

impl Drop for Job {
    fn drop(&mut self) {
        // SAFETY: the handle came from `CreateJobObjectW` and is closed only here.
        unsafe { CloseHandle(self.0) };
    }
}

/// A file in rustimal's own folder in the user's profile.
pub fn state_file(name: &str) -> Option<PathBuf> {
    crate::config::state_dir().map(|d| d.join(name))
}

/// Start this exe again with `argument`, as a process of its own that carries on after
/// this one ends and shows nothing.
pub fn start_watcher(argument: &str) -> std::io::Result<Child> {
    keep_own_output();
    Command::new(std::env::current_exe()?)
        .arg(argument)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP)
        .spawn()
}

/// A process started from here must not keep hold of this one's output: whoever reads it
/// would wait for as long as that process runs.
fn keep_own_output() {
    const HANDLE_FLAG_INHERIT: u32 = 1;
    // Standard input, output and error.
    for which in [-10i32, -11, -12] {
        // SAFETY: only changes whether this process's own handle is passed on.
        unsafe { SetHandleInformation(GetStdHandle(which as u32), HANDLE_FLAG_INHERIT, 0) };
    }
}

/// The preferred port if it is free, or else any that is.
pub fn free_port(preferred: u16) -> u16 {
    let bind = |port| TcpListener::bind((Ipv4Addr::LOCALHOST, port));
    if bind(preferred).is_ok() {
        return preferred;
    }
    bind(0).ok().and_then(|l| l.local_addr().ok()).map_or(preferred, |a| a.port())
}

pub fn process_alive(id: u32) -> bool {
    const SYNCHRONIZE: u32 = 0x0010_0000;
    const WAIT_TIMEOUT: u32 = 0x102;
    // SAFETY: the handle, if one is given, is only waited on and then closed.
    unsafe {
        let handle = OpenProcess(SYNCHRONIZE, 0, id);
        if handle == 0 {
            return false;
        }
        // Still running if waiting for it to end times out at once.
        let running = WaitForSingleObject(handle, 0) == WAIT_TIMEOUT;
        CloseHandle(handle);
        running
    }
}

/// A key nobody can guess: 48 hexadecimal digits from Windows' random numbers.
pub fn secret_key() -> Option<String> {
    const USE_SYSTEM_PREFERRED: u32 = 2;
    let mut bytes = [0u8; 24];
    // SAFETY: the buffer is passed with its own length.
    let status = unsafe { BCryptGenRandom(0, bytes.as_mut_ptr(), bytes.len() as u32, USE_SYSTEM_PREFERRED) };
    (status == 0).then(|| bytes.iter().map(|b| format!("{b:02x}")).collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, Instant};

    #[test]
    fn the_job_structure_is_the_size_windows_expects() {
        assert_eq!(size_of::<ExtendedLimits>(), if cfg!(target_pointer_width = "64") { 144 } else { 112 });
    }

    #[test]
    fn closing_the_job_ends_what_it_holds() {
        let mut child = Command::new("cmd.exe")
            .args(["/d", "/c", "ping -n 30 127.0.0.1"])
            .stdout(Stdio::null())
            .creation_flags(CREATE_NO_WINDOW)
            .spawn()
            .unwrap();
        let id = child.id();
        let job = Job::holding(&child).expect("a job");
        assert!(process_alive(id), "still running");
        drop(job);
        let began = Instant::now();
        while child.try_wait().unwrap().is_none() {
            assert!(began.elapsed() < Duration::from_secs(5), "it should have ended");
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(!process_alive(id));
    }

    #[test]
    fn a_taken_port_is_stepped_around() {
        let taken = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = taken.local_addr().unwrap().port();
        assert_ne!(free_port(port), port);
        drop(taken);
        assert_eq!(free_port(port), port);
    }

    #[test]
    fn keys_are_long_and_different() {
        let (a, b) = (secret_key().unwrap(), secret_key().unwrap());
        assert!(a.len() == 48 && a.bytes().all(|c| c.is_ascii_hexdigit()), "{}", a.len());
        assert_ne!(a, b);
    }
}