Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
11 changes: 11 additions & 0 deletions docs/design/08-distribution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 5 additions & 0 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
237 changes: 233 additions & 4 deletions src/actions.rs
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -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;
Expand Down Expand Up @@ -150,22 +164,40 @@ pub fn run_all(event: &Event, context: &ActionContext) -> Outcome {
fn start(action: &Action, context: &ActionContext) -> Result<Child> {
let program = context.render(&action.program.to_string_lossy());
let args: Vec<String> = 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);
}
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"
);
Expand All @@ -174,6 +206,71 @@ fn start(action: &Action, context: &ActionContext) -> Result<Child> {
.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<OsString>,
system: PathBuf,
windows: PathBuf,
/// This process's `PATH`, searched last.
process_path: Option<OsString>,
}

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<PathBuf> {
let absolute = |paths: &Option<OsString>| -> Vec<PathBuf> {
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<PathBuf> {
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.
Expand Down Expand Up @@ -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<PathBuf> = 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);
Expand Down
Loading