diff --git a/AGENTS.md b/AGENTS.md index 96c5888..4478745 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -179,7 +179,7 @@ This file says how to work here. The *why* is in `EnumWindows`. - `Command::new` given a bare name searches the executable's own folder before System32 and `PATH`: start a Windows program by full path, from - `win::system_dir`. + `win::system_dir`; a configured one goes through `actions::locate`. - A process started after `WM_QUERYENDSESSION` dies with `STATUS_DLL_INIT_FAILED`: nothing runs at logoff, so the session marker runs the stop commands at the next start. diff --git a/CHANGELOG.md b/CHANGELOG.md index 711425d..8723dff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ a section is written. - Windows PowerShell and `schtasks.exe` are started from Windows' system folder, never found by name: a copy unpacked in Downloads could run a program of that name lying beside it. +- A command's `program` given as a name alone is looked for in Windows' + folders, then `PATH`, never beside this program: with the FanControl + recipe, a copy unpacked in Downloads could run a `schtasks.exe` lying + beside it at every game start and stop. - The DLLs the program needs are loaded from Windows' system folder only: a copy unpacked in Downloads loaded an `msi.dll` lying beside it. - The program no longer needs the Visual C++ Redistributable: the C diff --git a/config.example.toml b/config.example.toml index f2e918f..974269d 100644 --- a/config.example.toml +++ b/config.example.toml @@ -102,7 +102,9 @@ gpu_sample = "1s" # Every command accepts: # # name label used in the log; defaults to the program path -# program the executable to run +# program the executable to run; a name alone is looked for in the +# system folder, the Windows folder, then PATH, never beside +# this program # args its arguments, one string per argument # working_dir directory to run it from # env extra environment variables, as key = "value" diff --git a/docs/design/08-distribution.md b/docs/design/08-distribution.md index d736384..adb1f2d 100644 --- a/docs/design/08-distribution.md +++ b/docs/design/08-distribution.md @@ -145,6 +145,17 @@ copied beside a stand-in `schtasks.exe`, ran it while `purge` drew its plan, and announced a logon task that does not exist; this build ran Windows' own.* +*The configured commands, the same day: a `program` named without a folder +went through the same search, so a copy unpacked in Downloads with the +FanControl recipe would have run a `schtasks.exe` lying beside it at every +game start and stop. `actions::locate` now looks a bare name up in std's +order without the executable's folder — the command's own `PATH`, the +system folder, the Windows folder, the process's `PATH`, absolute entries +only, `.exe` added to a name with no dot — and the log names the file it +started. Measured with `trigger start` and a stand-in `schtasks.exe` beside +each copy: build `909f77b7` ran the stand-in, this one +`C:\WINDOWS\system32\schtasks.exe`. The recipes keep their bare names.* + *The same day, the DLLs: those the executables import that are not known DLLs — `msi.dll`, `winhttp.dll`, `bcrypt.dll`, `VCRUNTIME140.dll` — were looked for in the executable's folder first. `build.rs` now links with diff --git a/docs/getting-started.md b/docs/getting-started.md index 42d390d..31c8c8c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -55,7 +55,9 @@ program = "powercfg.exe" args = ["/setactive", "SCHEME_BALANCED"] ``` -Write paths between single quotes, so backslashes need no doubling: +A name alone, like `powercfg.exe`, is looked for in Windows' own folders, +then `PATH`, never beside this program. Write paths between single quotes, +so backslashes need no doubling: `program = 'C:\Program Files\Something\tool.exe'`. The starter file has two beeps, commented out, to hear a detection before writing anything real. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index d3cedcb..883e8f2 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -136,6 +136,11 @@ usable file is saved. It never falls back to the last good file, which would run something other than what the file says. `log_dir` and `log_days` wait for the next start. +A command's `program` given as a name alone is looked for in Windows' system +folder, the Windows folder, then `PATH`, never in the program's own folder: +a copy unpacked in Downloads runs Windows' `schtasks.exe`, not one lying +beside it. The log names the file each command started from. + ## Updating itself *Check for updates* asks GitHub where `releases/latest` points — one request, diff --git a/docs/reference.md b/docs/reference.md index 0d37e88..6f149e5 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -80,7 +80,7 @@ starts them all, then waits. A command that fails never stops the others. | Field | Default | Meaning | | --- | --- | --- | | `name` | the program | label in the log | -| `program` | required | path or name of the executable | +| `program` | required | path or name of the executable; a name alone is looked for in the command's own `PATH`, the system folder, the Windows folder, then `PATH`, never beside this program, with `.exe` added when it has no extension | | `args` | `[]` | one string per argument | | `working_dir` | inherited | | | `env` | `{}` | extra environment variables | diff --git a/src/actions.rs b/src/actions.rs index 08c988f..4c178aa 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1,6 +1,19 @@ //! Running the configured executables. - +//! +//! A program named without a folder -- `schtasks.exe`, `powershell.exe` -- +//! is looked for here, not by std: `Command::new` given a bare name searches +//! the running executable's own folder before the system folder and `PATH`, +//! so a copy unpacked in Downloads would run a `schtasks.exe` lying beside +//! it at every game start and stop. `locate` keeps std's order without +//! that folder: the `PATH` the command's own `env` sets, if any; the system +//! folder; the Windows folder; this process's `PATH`. Only absolute entries +//! of a `PATH` count, the current folder never does, and a name without an +//! extension gets `.exe`, std's rule. A program given with a folder is the +//! person's explicit choice and starts as written. + +use std::ffi::OsString; use std::os::windows::process::CommandExt; +use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use std::time::{Duration, Instant}; @@ -9,6 +22,7 @@ use anyhow::{Context, Result}; use crate::config::{Action, Event, Mode}; use crate::detect::GameSignal; use crate::logging::target; +use crate::win; /// CREATE_NO_WINDOW: no console window for the child process. const CREATE_NO_WINDOW: u32 = 0x0800_0000; @@ -150,8 +164,25 @@ pub fn run_all(event: &Event, context: &ActionContext) -> Outcome { fn start(action: &Action, context: &ActionContext) -> Result { let program = context.render(&action.program.to_string_lossy()); let args: Vec = action.args.iter().map(|arg| context.render(arg)).collect(); + let env: Vec<(&String, String)> = action + .env + .iter() + .map(|(key, value)| (key, context.render(value))) + .collect(); + + let search = Search { + // Windows' variable names ignore case, and so does std's own check. + command_path: env + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case("PATH")) + .map(|(_, value)| OsString::from(value)), + system: win::system_dir()?, + windows: win::windows_dir()?, + process_path: std::env::var_os("PATH"), + }; + let path = locate(&program, &search, Path::is_file)?; - let mut command = Command::new(&program); + let mut command = Command::new(&path); command.args(&args); if action.no_window { command.creation_flags(CREATE_NO_WINDOW); @@ -159,13 +190,14 @@ fn start(action: &Action, context: &ActionContext) -> Result { if let Some(dir) = &action.working_dir { command.current_dir(context.render(&dir.to_string_lossy())); } - for (key, value) in &action.env { - command.env(key, context.render(value)); + for (key, value) in env { + command.env(key, value); } tracing::debug!( target: target::COMMANDS, program, + path = %path.display(), args = %shown_arguments(&args), "Starting a command" ); @@ -174,6 +206,71 @@ fn start(action: &Action, context: &ActionContext) -> Result { .with_context(|| format!("cannot start `{program}`")) } +/// The folders a program named without a folder is looked for in. +struct Search { + /// `PATH` as the command's own `env` sets it: searched first, as std + /// does, since the person wrote it for this command. + command_path: Option, + system: PathBuf, + windows: PathBuf, + /// This process's `PATH`, searched last. + process_path: Option, +} + +impl Search { + /// The folders in the order they are searched. A relative `PATH` entry + /// -- `.`, `tools`, `\bin`, `C:bin` -- would be read against the current + /// folder, which is the search this module exists to avoid. + fn folders(&self) -> Vec { + let absolute = |paths: &Option| -> Vec { + paths + .iter() + .flat_map(std::env::split_paths) + .filter(|folder| folder.is_absolute()) + .collect() + }; + let mut folders = absolute(&self.command_path); + folders.push(self.system.clone()); + folders.push(self.windows.clone()); + folders.extend(absolute(&self.process_path)); + folders + } +} + +/// Where `program` starts from: as written when it names a folder, else +/// the first file `exists` finds in `search`'s folders. +fn locate(program: &str, search: &Search, exists: impl Fn(&Path) -> bool) -> Result { + if program.contains(['\\', '/']) { + return Ok(PathBuf::from(program)); + } + if program.is_empty() { + anyhow::bail!("the program is empty once its placeholders are filled in"); + } + // `CreateProcessW`'s rule, which std applies when it searches: a name + // with no dot in it gets `.exe`. + let name = if program.contains('.') { + program.to_owned() + } else { + format!("{program}.exe") + }; + search + .folders() + .into_iter() + .map(|folder| folder.join(&name)) + .find(|candidate| exists(candidate)) + .with_context(|| { + format!( + "`{name}` is not in {}the system folder, the Windows folder or a folder of PATH, \ + and it is never looked for beside GameModeExecutor", + if search.command_path.is_some() { + "the command's PATH, " + } else { + "" + } + ) + }) +} + /// The arguments as a person would type them after the program, for the /// log: one holding a space between quotes, nothing escaped, so a path /// reads as Windows writes it. Not the command line `Command` builds. @@ -401,6 +498,138 @@ mod tests { ); } + /// Invented folders: `C:\Win` stands for the Windows folder, `C:\Copy` + /// for the folder a copy was unpacked in, which no search may reach. + fn search(command_path: Option<&str>, process_path: &str) -> Search { + Search { + command_path: command_path.map(OsString::from), + system: PathBuf::from(r"C:\Win\System32"), + windows: PathBuf::from(r"C:\Win"), + process_path: Some(OsString::from(process_path)), + } + } + + /// An `exists` that knows exactly these files. + fn only(files: &[&str]) -> impl Fn(&Path) -> bool { + let files: Vec = files.iter().map(PathBuf::from).collect(); + move |path| files.iter().any(|file| file == path) + } + + #[test] + fn a_bare_name_is_found_in_the_system_folder_before_path() { + let found = locate( + "schtasks.exe", + &search(None, r"D:\Tools"), + only(&[r"D:\Tools\schtasks.exe", r"C:\Win\System32\schtasks.exe"]), + ); + assert_eq!(found.unwrap(), Path::new(r"C:\Win\System32\schtasks.exe")); + } + + #[test] + fn the_windows_folder_comes_after_the_system_folder_and_path_last() { + let paths = search(None, r"D:\Tools").folders(); + assert_eq!( + paths, + [r"C:\Win\System32", r"C:\Win", r"D:\Tools"].map(PathBuf::from) + ); + let found = locate( + "tool.exe", + &search(None, r"D:\Tools"), + only(&[r"D:\Tools\tool.exe"]), + ); + assert_eq!(found.unwrap(), Path::new(r"D:\Tools\tool.exe")); + } + + #[test] + fn the_copys_own_folder_and_the_current_folder_are_never_searched() { + let error = locate( + "schtasks.exe", + &search(None, r".;Copy;\Copy;C:Copy"), + only(&[ + r"C:\Copy\schtasks.exe", + r".\schtasks.exe", + r"Copy\schtasks.exe", + r"\Copy\schtasks.exe", + r"C:Copy\schtasks.exe", + ]), + ) + .unwrap_err(); + assert_eq!( + error.to_string(), + "`schtasks.exe` is not in the system folder, the Windows folder or a folder of PATH, \ + and it is never looked for beside GameModeExecutor" + ); + } + + #[test] + fn exe_is_added_only_to_a_name_without_an_extension() { + let files = only(&[ + r"C:\Win\System32\powershell.exe", + r"D:\Tools\sync.cmd", + r"D:\Tools\my.tool", + ]); + let tools = search(None, r"D:\Tools"); + assert_eq!( + locate("powershell", &tools, &files).unwrap(), + Path::new(r"C:\Win\System32\powershell.exe") + ); + assert_eq!( + locate("sync.cmd", &tools, &files).unwrap(), + Path::new(r"D:\Tools\sync.cmd") + ); + assert_eq!( + locate("my.tool", &tools, &files).unwrap(), + Path::new(r"D:\Tools\my.tool") + ); + } + + #[test] + fn the_commands_own_path_is_searched_first() { + let found = locate( + "powershell.exe", + &search(Some(r"E:\Mine"), r"D:\Tools"), + only(&[r"E:\Mine\powershell.exe", r"C:\Win\System32\powershell.exe"]), + ); + assert_eq!(found.unwrap(), Path::new(r"E:\Mine\powershell.exe")); + let missing = locate( + "absent.exe", + &search(Some(r"E:\Mine"), r"D:\Tools"), + only(&[]), + ); + assert!( + missing + .unwrap_err() + .to_string() + .starts_with("`absent.exe` is not in the command's PATH, the system folder") + ); + } + + #[test] + fn a_quoted_path_entry_is_read_without_its_quotes() { + let found = locate( + "tool.exe", + &search(None, r#""D:\Program Files\Tool";D:\Other"#), + only(&[r"D:\Program Files\Tool\tool.exe"]), + ); + assert_eq!(found.unwrap(), Path::new(r"D:\Program Files\Tool\tool.exe")); + } + + #[test] + fn a_program_with_a_folder_starts_as_written() { + let never = |_: &Path| -> bool { panic!("a program with a folder is not searched for") }; + for program in [r"C:\Tools\fan.exe", r"tools\fan.exe", "./fan.exe"] { + assert_eq!( + locate(program, &search(None, r"D:\Tools"), never).unwrap(), + Path::new(program) + ); + } + } + + #[test] + fn an_empty_program_is_an_error() { + assert!(locate("", &search(None, r"D:\Tools"), only(&[])).is_err()); + } + #[test] fn missing_signal_renders_empty_placeholders() { let context = ActionContext::new("game_stop", None); diff --git a/src/win.rs b/src/win.rs index b1639f9..1a7fda6 100644 --- a/src/win.rs +++ b/src/win.rs @@ -17,7 +17,7 @@ use windows::Win32::Storage::FileSystem::{ FindCloseChangeNotification, FindFirstChangeNotificationW, FindNextChangeNotification, }; use windows::Win32::System::LibraryLoader::GetModuleHandleW; -use windows::Win32::System::SystemInformation::GetSystemDirectoryW; +use windows::Win32::System::SystemInformation::{GetSystemDirectoryW, GetWindowsDirectoryW}; use windows::Win32::System::Threading::{ CreateEventW, CreateMutexW, INFINITE, OpenMutexW, ResetEvent, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, WaitForMultipleObjects, WaitForSingleObject, @@ -520,16 +520,31 @@ pub fn declare_dpi_awareness() { /// which is whatever the parent process passed down; and no fallback to the /// name, which would bring the search back. pub fn system_dir() -> Result { - // MAX_PATH is the size Microsoft documents for this buffer. - let mut buffer = [0u16; MAX_PATH as usize]; // SAFETY: the slice is the buffer and passes its own length; the call // writes at most that many characters, the terminating zero included. - let len = unsafe { GetSystemDirectoryW(Some(&mut buffer)) } as usize; + asked_folder("the system folder", |buffer| unsafe { + GetSystemDirectoryW(Some(buffer)) + }) +} + +/// The Windows folder, `C:\Windows` on a stock install: the folder searched +/// after the system folder for a configured program named without a folder +/// (`actions`), as `CreateProcessW` and std search it. Asked of +/// `GetWindowsDirectoryW` for the reason `system_dir` gives. +pub fn windows_dir() -> Result { + // SAFETY: as in `system_dir`. + asked_folder("the Windows folder", |buffer| unsafe { + GetWindowsDirectoryW(Some(buffer)) + }) +} + +/// A folder Windows writes into a buffer of `MAX_PATH` characters, the size +/// Microsoft documents for both calls, which return the length written or 0. +fn asked_folder(what: &str, call: impl FnOnce(&mut [u16]) -> u32) -> Result { + let mut buffer = [0u16; MAX_PATH as usize]; + let len = call(&mut buffer) as usize; if len == 0 || len >= buffer.len() { - anyhow::bail!( - "cannot find the system folder: {}", - std::io::Error::last_os_error() - ); + anyhow::bail!("cannot find {what}: {}", std::io::Error::last_os_error()); } Ok(PathBuf::from(OsString::from_wide(&buffer[..len]))) }