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;
}
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;
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;
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) {
unsafe { CloseHandle(self.0) };
}
}
pub fn state_file(name: &str) -> Option<PathBuf> {
crate::config::state_dir().map(|d| d.join(name))
}
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()
}
fn keep_own_output() {
const HANDLE_FLAG_INHERIT: u32 = 1;
for which in [-10i32, -11, -12] {
unsafe { SetHandleInformation(GetStdHandle(which as u32), HANDLE_FLAG_INHERIT, 0) };
}
}
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;
unsafe {
let handle = OpenProcess(SYNCHRONIZE, 0, id);
if handle == 0 {
return false;
}
let running = WaitForSingleObject(handle, 0) == WAIT_TIMEOUT;
CloseHandle(handle);
running
}
}
pub fn secret_key() -> Option<String> {
const USE_SYSTEM_PREFERRED: u32 = 2;
let mut bytes = [0u8; 24];
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);
}
}