diff --git a/README.md b/README.md index f129c09..a282014 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ The app lists other NZXT devices as "no driver yet". If you have one, *Settings ### Windows 1. Quit NZXT CAM, and turn it off in *Task Manager → Startup apps* so it does not come back at the next logon. While CAM's app runs, it holds the devices and camless cannot open them. CAM Service can keep running. -2. Run [camless-setup.exe](https://github.com/kleju13/camless/releases/latest/download/camless-setup.exe). It needs no administrator rights. It is not code-signed, so SmartScreen may stop it: *More info → Run anyway*. Or install from PowerShell, which also checks the download's SHA-256: +2. Run [camless-setup.exe](https://github.com/kleju13/camless/releases/latest/download/camless-setup.exe). It asks for administrator rights and installs in `C:\Program Files\camless`. It is not code-signed, so SmartScreen may stop it: *More info → Run anyway*. Or install from PowerShell, which also checks the download's SHA-256: ``` irm https://raw.githubusercontent.com/kleju13/camless/main/scripts/install.ps1 | iex ``` @@ -104,7 +104,7 @@ The app lists other NZXT devices as "no driver yet". If you have one, *Settings The app checks for a new release each time it starts and shows *Update available* under the service in the sidebar. *Update* there, or in *Settings → About*, installs it. Uninstall camless from *Settings → Apps* in Windows. It keeps your settings in `%APPDATA%\camless` unless you choose to delete them. -CPU temperature also needs [PawnIO](https://pawnio.eu) and its signed module for your CPU in `%LOCALAPPDATA%\Programs\camless`: `IntelMSR.bin` on Intel, `AMDFamily17.bin` on AMD Ryzen. Both are in the zip of the latest [PawnIO.Modules release](https://github.com/namazso/PawnIO.Modules/releases/latest). Without them, curves on CPU temperature hold the failsafe duty. When they are missing, the app says so when it starts, with the file this CPU needs, and *Settings → Software from elsewhere* shows what camless found. CPU temperature starts within seconds of putting them in place. The Kraken's liquid temperature needs none of this, so new curves use it by default. +CPU temperature also needs [PawnIO](https://pawnio.eu) and its signed module for your CPU in `C:\Program Files\camless`: `IntelMSR.bin` on Intel, `AMDFamily17.bin` on AMD Ryzen. Both are in the zip of the latest [PawnIO.Modules release](https://github.com/namazso/PawnIO.Modules/releases/latest). Without them, curves on CPU temperature hold the failsafe duty. When they are missing, the app says so when it starts, with the file this CPU needs, and *Settings → Software from elsewhere* shows what camless found. CPU temperature starts within seconds of putting them in place. The Kraken's liquid temperature needs none of this, so new curves use it by default. GPU temperature, load and power come from NVIDIA's driver (NVML) on an NVIDIA card. Any other card, such as AMD's or Intel's, gives the temperature and load that Task Manager shows, which Windows keeps for every card. An AMD card's power comes from AMD's driver (ADL), from the log the driver keeps, as LibreHardwareMonitor reads it, or else from a reading of the moment; an Intel card has none. If an AMD card shows no power, or power that jumps, `camless report` says which way it was read and what it read over the last minute. diff --git a/core/src/config.rs b/core/src/config.rs index 64e2973..66eeca7 100644 --- a/core/src/config.rs +++ b/core/src/config.rs @@ -463,6 +463,15 @@ pub fn xdg_dir(var: &str, fallback: &str) -> PathBuf { } } +/// Whether `path` is below the folder `dir`, as Windows compares names: without +/// regard to case, and with either slash. A path that climbs back out with `..` is not. +pub fn is_inside(path: &Path, dir: &Path) -> bool { + let lower = |p: &Path| p.to_string_lossy().to_lowercase().replace('/', "\\"); + let (path, dir) = (lower(path), lower(dir)); + let dir = dir.trim_end_matches('\\'); + !dir.is_empty() && path.strip_prefix(dir).is_some_and(|rest| rest.starts_with('\\') && !rest.contains("\\..\\")) +} + fn split_channel(channel: &str) -> Option<(&str, &str)> { channel.split_once('/').filter(|(d, c)| !d.is_empty() && !c.is_empty() && !c.contains('/')) } @@ -817,6 +826,19 @@ pub fn curve_order(curves: &[CurveSpec]) -> Result> { mod tests { use super::*; + #[test] + fn a_path_is_inside_a_folder_the_way_windows_compares() { + let pf = Path::new(r"C:\Program Files"); + assert!(is_inside(Path::new(r"C:\Program Files\camless\camless-gui.exe"), pf)); + assert!(is_inside(Path::new(r"c:\program files/camless/camless-gui.exe"), Path::new(r"C:\Program Files\"))); + // A folder of the user's, a look-alike next to Program Files, and a way back out. + assert!(!is_inside(Path::new(r"C:\Users\A\AppData\Local\Programs\camless\camless-gui.exe"), pf)); + assert!(!is_inside(Path::new(r"C:\Program Files Evil\camless-gui.exe"), pf)); + assert!(!is_inside(Path::new(r"C:\Program Files\..\Users\A\camless-gui.exe"), pf)); + assert!(!is_inside(Path::new(r"C:\Program Files"), pf)); + assert!(!is_inside(Path::new(r"C:\x.exe"), Path::new(""))); + } + pub const SAMPLE: &str = r#" interval_ms = 1000 failsafe_duty = 70 diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 9a9bd47..46c72c3 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -6,7 +6,14 @@ camless is two programs, `camless` and `camless-gui` on [Linux](#linux): The app starts the service if it is not running. On Windows, it asks for administrator rights (UAC), so CPU temperature works. If the answer is no, the service runs without them and the app says so. The bottom of the sidebar always shows the service's state with a start or restart button, and *Settings → Service* starts, restarts and stops it. -*Settings → Service → Start as administrator without asking* stops the prompts. It is off until you turn it on, and Windows asks once then. The app sets up a scheduled task, `camless ()`, that runs `camless-gui.exe --start-service` with your full rights, and from then on starts the service through it, also at logon with *Start with Windows*. The task has no trigger of its own. You may run and delete it without administrator rights, so turning the switch off and uninstalling need none. The trade-off: camless sits in a folder you can write to, so any program you run could replace it and use the task to get administrator rights without a prompt. On a standard account the switch refuses: a task that runs as you could not give the service administrator rights. +*Settings → Service → Start as administrator without asking* stops the prompts. It is off until you turn it on, and Windows asks once then. The app sets up a scheduled task, `camless ()`, that runs `camless-gui.exe --start-service` with your full rights, and from then on starts the service through it, also at logon with *Start with Windows*. The task has no trigger of its own. You may run and delete it without administrator rights, so turning the switch off needs none. + +A task gives administrator rights to whatever it starts, so camless guards what that is: +- The switch works only for a camless in Program Files, where the setup puts it and only administrators write. A copy elsewhere, such as a build of your own, keeps asking through UAC. +- The task is written by a copy of the app that has administrator rights itself, `camless-gui.exe --set-up-task`, which the switch starts through UAC. It keeps the task's definition in its own folder until Windows has read it. +- The setup writes the task again after every install, for the camless it just installed. If that fails, it deletes the task, and the app asks through UAC again. + +On a standard account the switch refuses: a task that runs as you could not give the service administrator rights. ## Software from elsewhere @@ -56,7 +63,7 @@ When something this PC needs is missing, the app opens a dialog once each time i ## GPU fans `[devices] gpu`, off unless you turn it on, lets camless set the graphics card's fans. Experimental: nobody has run it on a card yet. Give them a curve on the GPU's temperature. -- On Windows, NVIDIA cards, through NVML (`nvml.dll`, which comes with the driver): `nvmlDeviceSetFanSpeed_v2` sets a fan's duty, within the card's `nvmlDeviceGetMinMaxFanSpeed`, and `nvmlDeviceSetDefaultFanSpeed_v2` gives it back to the card's curve. The rpm comes from `nvmlDeviceGetFanSpeedRPM`, on drivers that have it. Setting a fan needs administrator rights: without them, or on a card whose fans NVML does not set (`NVML_ERROR_NOT_SUPPORTED`, which no source rules out on GeForce cards), camless says so and leaves the fan out until the service starts again. Before it first sets a fan, camless leaves a file, `%APPDATA%\camless\taken-gpu-fans`: if camless crashes or is killed, the card keeps the last duty until a camless starts again, which gives every fan back to the card's curve, whatever the settings say by then. camless loads `nvml.dll` from System32, or from NVSMI on older drivers, by its full path, for the GPU's sensors too: a service that runs as administrator must not load one from a folder the user's programs can write to. AMD cards on Windows need AMD's ADLX, which camless does not drive yet. +- On Windows, NVIDIA cards, through NVML (`nvml.dll`, which comes with the driver): `nvmlDeviceSetFanSpeed_v2` sets a fan's duty, within the card's `nvmlDeviceGetMinMaxFanSpeed`, and `nvmlDeviceSetDefaultFanSpeed_v2` gives it back to the card's curve. The rpm comes from `nvmlDeviceGetFanSpeedRPM`, on drivers that have it. Setting a fan needs administrator rights: without them, or on a card whose fans NVML does not set (`NVML_ERROR_NOT_SUPPORTED`, which no source rules out on GeForce cards), camless says so and leaves the fan out until the service starts again. Before it first sets a fan, camless leaves a file, `taken-gpu-fans` in [the service's folder](#the-services-own-files): if camless crashes or is killed, the card keeps the last duty until a camless starts again, which gives every fan back to the card's curve, whatever the settings say by then. camless loads `nvml.dll` from System32, or from NVSMI on older drivers, by its full path, for the GPU's sensors too: a service that runs as administrator must not load one from a folder the user's programs can write to. AMD cards on Windows need AMD's ADLX, which camless does not drive yet. - On Linux, AMD cards, through the `amdgpu` driver's hwmon files, as the motherboard's headers: `pwm1_enable` 1 and `pwm1` for a duty, the mode it had to give it back. The same udev rule gives you those two files. Cards from the RX 7000 series on may not take a duty in `pwm1`: the kernel gives them a fan curve in `gpu_od` instead, which camless does not write. A card that refuses manual mode or the duty is left out once it refuses, until the service starts again. A crash is covered as on the motherboard. NVML needs root on Linux, which the service is not. - A card's fans are `gpu`, and a second card's `gpu#2`. camless gives a fan back when its curve is removed and when the service stops, the setting goes off, or another program that sets them starts: the motherboard's fan programs and MSI Afterburner. @@ -64,7 +71,7 @@ When something this PC needs is missing, the app opens a dialog once each time i The service records every sensor, and the speed and duty of every fan, while it runs: - the last hour at one reading a second, in memory; -- each minute's average and highest value, in `history/` next to `camless.toml`, one CSV file per UTC day. Files older than 30 days are deleted. A day takes about 300 KB with a Kraken and a Control Hub. +- each minute's average and highest value, in `history/` in [the service's folder](#the-services-own-files), one CSV file per UTC day. Files older than 30 days are deleted. A day takes about 300 KB with a Kraken and a Control Hub. *Monitoring → History* shows them for the last 10 minutes, hour, 24 hours, 7 days or 30 days, a chart for each kind: liquid temperature, CPU and GPU temperature, load, power, fan and pump speeds, and the frame rate while Games is on. Liquid has a chart of its own, scaled close around its readings, so a change of a degree shows; the line at 55 °C, where every fan goes to 100 %, shows once the readings come near it. Each series gives its reading now, its average and its highest over the range. Pointing at a chart shows the readings at that moment, and a line marks it in the others. Dragging across a chart zooms in: sideways on a stretch of time, for every chart, which loads again finer where the history has it; up or down on the values of that chart; far both ways on both. A double-click or *Reset zoom* zooms out. The button in a chart's corner makes it as wide as the page and taller, and the app remembers it. Over 24 hours and more, a point stands for several minutes: the line is their average, and a shade above it shows how high they went. `camless run --demo` keeps its simulated readings in memory only. @@ -107,9 +114,11 @@ The safeguards under [Fan control](#fan-control) still apply on top. The server To add it to Claude Code: ``` -claude mcp add camless -- C:\Users\\AppData\Local\Programs\camless\camless.exe mcp +claude mcp add camless -- "C:\Program Files\camless\camless.exe" mcp ``` +Until 0.6.0-beta.6 camless was in `%LOCALAPPDATA%\Programs\camless`. An assistant set up with that path needs the new one. + On Linux, the command is `~/.local/bin/camless mcp`. Or to Claude Desktop, in `claude_desktop_config.json`: @@ -118,7 +127,7 @@ Or to Claude Desktop, in `claude_desktop_config.json`: { "mcpServers": { "camless": { - "command": "C:\\Users\\\\AppData\\Local\\Programs\\camless\\camless.exe", + "command": "C:\\Program Files\\camless\\camless.exe", "args": ["mcp"] } } @@ -189,9 +198,17 @@ The fonts are in `gui/ui`: Archivo for text, Saira for digits, and one glyph fro ## Installs and updates -`camless-setup.exe` (Inno Setup, `installer/camless.iss`) installs both exes for the current user in `%LOCALAPPDATA%\Programs\camless`. Run over an installed camless, it closes the app, stops the service through `POST /v1/stop`, replaces both exes and opens the app again, which starts the service. +`camless-setup.exe` (Inno Setup, `installer/camless.iss`) installs both exes in `C:\Program Files\camless` and asks Windows for administrator rights to do it. The service runs as administrator, so its program must be where only administrators write: in a folder of yours, any program you run could replace it. Run over an installed camless, the setup closes the app, stops the service through `POST /v1/stop`, replaces both exes and opens the app again, without the setup's rights. The app starts the service. + +Until 0.6.0-beta.6 the setup needed no administrator rights and put camless in `%LOCALAPPDATA%\Programs\camless`. The setup moves such a copy: it removes the old exes, uninstaller, shortcuts and entry in Windows' list of apps, takes a PawnIO module along, and writes the task for *Start as administrator without asking* again. It runs nothing from the old folder, and it deletes there with your rights, not its own: the folder is yours, and a link in its place could lead anywhere. It leaves a folder that is a link alone. The app points *Start with Windows* at its new place when it starts. A `camless.toml` that you put beside the old exe stays there with its `profiles`, and camless goes back to the one in `%APPDATA%\camless`: move them there to keep those settings. This happens for the account that answers the UAC prompt. If you install with another account's administrator password, uninstall the old copy yourself in *Settings → Apps*. + +The app asks GitHub for the latest release once each time it starts. *Update* downloads `camless-setup.exe`, checks it against the release's SHA-256, quits the app and runs the setup, so the app and the service always update together. Uninstalling keeps `%APPDATA%\camless` and the history unless you choose to delete them. + +### The service's own files + +The service writes three things: the history, the game sessions (`history/sessions.jsonl`) and `taken-gpu-fans`. The history and the sessions are in the folder of `camless.toml`. `taken-gpu-fans` is in `%APPDATA%\camless` whatever config the service runs, so that the next camless finds it. There is one exception: the installed service on Windows, while it runs as administrator, keeps all three in `C:\Program Files\camless\data`. In a folder of yours, a program you run could put a link in place of `history`, and the service would write wherever the link leads, with administrator rights. -The app asks GitHub for the latest release once each time it starts. *Update* downloads `camless-setup.exe`, checks it against the release's SHA-256, quits the app and runs the setup, so the app and the service always update together. Uninstalling keeps `%APPDATA%\camless` unless you choose to delete it. +The first time it uses that folder, the service brings over the history beside `camless.toml`, all of it or none: a service that stops halfway starts again the next time. It takes day files and `sessions.jsonl` only, and of those only the lines that are history or sessions. The old files stay. A service that runs without administrator rights writes beside `camless.toml` as before, so the two do not see each other's days. *Settings → About → Update channel* picks what the app offers: - **Stable**, the default, offers releases. diff --git a/gui/Cargo.toml b/gui/Cargo.toml index 9412760..6c25858 100644 --- a/gui/Cargo.toml +++ b/gui/Cargo.toml @@ -32,6 +32,7 @@ windows-sys = { version = "0.61", features = [ "Win32_Security_Authorization", "Win32_Security_Cryptography", "Win32_System_Registry", + "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Shell", diff --git a/gui/src/main.rs b/gui/src/main.rs index 59fec62..51c245d 100644 --- a/gui/src/main.rs +++ b/gui/src/main.rs @@ -4,7 +4,8 @@ //! //! `camless-gui --serve 127.0.0.1: --config [--ui-dir ]` //! serves the same page to a browser instead, as a sandbox, to work on the UI. -//! `camless-gui --start-service` starts the service and exits; see [`task`]. +//! `camless-gui --start-service` starts the service and exits, and `--set-up-task` +//! sets up the task that runs it; see [`task`]. //! //! On Linux the window is GTK's and the page WebKitGTK's ([`app`]), the tray icon an //! AppIndicator ([`tray`]), and the service a systemd user service ([`service`]). @@ -41,6 +42,10 @@ fn main() -> anyhow::Result<()> { if args.iter().any(|a| a == task::START_SERVICE) { return client::start_daemon(&camless_core::config::default_path()); } + #[cfg(windows)] + if args.iter().any(|a| a == task::SET_UP) { + return task::set_up_elevated(); + } if let Some(listen) = value("--serve") { let config = value("--config") .map(PathBuf::from) diff --git a/gui/src/task.rs b/gui/src/task.rs index 60f7c40..0d68fa7 100644 --- a/gui/src/task.rs +++ b/gui/src/task.rs @@ -5,15 +5,24 @@ //! The task runs `camless-gui.exe --start-service`, which starts camless.exe next to //! it and exits: a task that ran camless.exe itself would open a console window. Its //! user may run, read and delete it, so the app reads it from its file, and turning -//! it off or uninstalling needs no administrator rights. +//! it off needs no administrator rights. +//! +//! A task hands administrator rights to whatever it starts, so it is only set up for +//! a camless in Program Files, where the setup puts it and only administrators write. +//! Setting it up takes a copy of the app with those rights, `camless-gui.exe +//! --set-up-task`, started through UAC: it writes the task's definition itself, in +//! its own folder, so no other program of the user's has a hand in what the task runs. use crate::service::{self, Elevate}; use anyhow::{anyhow, bail, Context, Result}; +use camless_core::config::is_inside; use std::path::{Path, PathBuf}; use std::sync::Mutex; /// Passed by the task: start the service and exit. pub const START_SERVICE: &str = "--start-service"; +/// Passed to the copy that runs as administrator: set the task up and exit. +pub const SET_UP: &str = "--set-up-task"; #[derive(Clone, Debug, Default)] pub struct State { @@ -48,12 +57,15 @@ pub fn spawn(on: bool) -> Result<()> { /// Whether the task is set up and starts the camless next to this app, not another copy. /// On a standard account it would start the service without administrator rights, so -/// there UAC asks as before. +/// there UAC asks as before, and so it does for a camless outside Program Files. pub fn ready() -> bool { if !administrator() { return false; } let (Ok(name), Ok(exe)) = (name(), std::env::current_exe()) else { return false }; + if !in_program_files(&exe) { + return false; + } let Ok(file) = std::fs::read(system32().join("Tasks").join(name)) else { return false }; command(&file).is_some_and(|c| c.to_lowercase() == exe.display().to_string().to_lowercase()) } @@ -68,18 +80,44 @@ fn set_up() -> Result<()> { bail!("this account is not an administrator, so the task could only start the service without administrator rights"); } let exe = std::env::current_exe()?; + if !in_program_files(&exe) { + bail!("{NOT_INSTALLED}"); + } + match service::run_elevated(&exe, SET_UP, true) { + Ok(Some(0)) => {} + Ok(_) => bail!("camless could not set the task up"), + Err(Elevate::Declined) => bail!("Windows did not give administrator rights, so nothing changed"), + Err(Elevate::Failed(e)) => return Err(e), + } + if !ready() { + bail!("Windows set the task up, but camless cannot read it, so it keeps asking"); + } + Ok(()) +} + +/// Why the task is refused for a camless outside Program Files. +const NOT_INSTALLED: &str = "this camless is not in Program Files, so other programs could replace it and get administrator rights through the task; install it with camless-setup.exe"; + +/// `--set-up-task`, with administrator rights: writes the task for this user and this +/// exe. The setup runs it too, after it moved camless, so the task follows. +pub fn set_up_elevated() -> Result<()> { + if !elevated_now() { + bail!("setting the task up needs administrator rights"); + } + let exe = std::env::current_exe()?; + if !in_program_files(&exe) { + bail!("{NOT_INSTALLED}"); + } let xml = definition(&user_sid()?, &exe); - let file = std::env::temp_dir().join(format!("camless-task-{}.xml", std::process::id())); + // Next to the exe, which only administrators write: a file in the user's temp + // folder could be swapped for another task before schtasks reads it. + let file = exe.with_file_name(format!("camless-task-{}.xml", std::process::id())); // schtasks reads UTF-16 with a byte order mark. let bytes: Vec = [0xFF, 0xFE].into_iter().chain(xml.encode_utf16().flat_map(u16::to_le_bytes)).collect(); std::fs::write(&file, bytes).context("writing the task for schtasks")?; - let created = elevated(&format!("/Create /TN \"{}\" /XML \"{}\" /F", name()?, file.display())); + let created = schtasks(&["/Create", "/TN", &name()?, "/XML", &file.display().to_string(), "/F"]); let _ = std::fs::remove_file(&file); - created?; - if !ready() { - bail!("Windows set the task up, but camless cannot read it, so it keeps asking"); - } - Ok(()) + created } fn remove() -> Result<()> { @@ -94,7 +132,7 @@ fn remove() -> Result<()> { } } -/// `camless ()`: camless installs for one user, so each has their own task. The +/// `camless ()`: the task runs as one user, so each has their own. The /// uninstaller deletes it by this name. fn name() -> Result { use windows_sys::Win32::System::WindowsProgramming::GetUserNameW; @@ -130,6 +168,47 @@ fn administrator() -> bool { } } +/// Whether this process has administrator rights now. +fn elevated_now() -> bool { + use std::ffi::c_void; + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + unsafe { + let mut token = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return false; + } + let (mut elevated, mut len) = (TOKEN_ELEVATION { TokenIsElevated: 0 }, 0); + let read = GetTokenInformation(token, TokenElevation, &mut elevated as *mut _ as *mut c_void, size_of::() as u32, &mut len) != 0; + CloseHandle(token); + read && elevated.TokenIsElevated != 0 + } +} + +/// Whether `exe` is in Program Files, which takes administrator rights to write. +/// Windows names the folder in a part of the registry that takes them too; a variable +/// such as `%ProgramFiles%` is whatever the user's programs set it to. +fn in_program_files(exe: &Path) -> bool { + program_files().is_some_and(|dir| is_inside(exe, &dir)) +} + +fn program_files() -> Option { + use windows_sys::Win32::Foundation::ERROR_SUCCESS; + use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ}; + let wide = |s: &str| s.encode_utf16().chain([0]).collect::>(); + let (key, value) = (wide(r"SOFTWARE\Microsoft\Windows\CurrentVersion"), wide("ProgramFilesDir")); + let mut buf = [0u16; 520]; + let mut len = size_of_val(&buf) as u32; + let r = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE, key.as_ptr(), value.as_ptr(), RRF_RT_REG_SZ, std::ptr::null_mut(), buf.as_mut_ptr().cast(), &mut len) }; + if r != ERROR_SUCCESS { + return None; + } + let text = String::from_utf16_lossy(&buf[..(len as usize / 2).min(buf.len())]); + let text = text.trim_end_matches('\0'); + (!text.is_empty()).then(|| PathBuf::from(text)) +} + /// The SID of the user this app runs as, such as `S-1-5-21-…-1001`. fn user_sid() -> Result { use std::ffi::c_void; @@ -219,9 +298,18 @@ fn unescape(s: &str) -> String { s.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'").replace("&", "&") } +/// Windows' System32, as Windows names it: this also runs as administrator, and a +/// variable such as `%SystemRoot%` is whatever the user's programs set it to. fn system32() -> PathBuf { - let root = std::env::var_os("SystemRoot").map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); - root.join("System32") + use std::os::windows::ffi::OsStringExt; + use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW; + let mut buf = [0u16; 260]; + let len = unsafe { GetSystemDirectoryW(buf.as_mut_ptr(), buf.len() as u32) } as usize; + if (1..buf.len()).contains(&len) { + PathBuf::from(std::ffi::OsString::from_wide(&buf[..len])) + } else { + PathBuf::from(r"C:\Windows\System32") + } } /// schtasks with this app's rights, without a window. @@ -240,7 +328,8 @@ fn schtasks(args: &[&str]) -> Result<()> { Ok(()) } -/// schtasks as administrator, through UAC; waits for it. +/// schtasks as administrator, through UAC; waits for it. Its parameters name the task +/// only, never a file. fn elevated(params: &str) -> Result<()> { match service::run_elevated(&system32().join("schtasks.exe"), params, true) { Ok(Some(0)) => Ok(()), @@ -269,6 +358,15 @@ mod tests { assert!(user_sid().unwrap().starts_with("S-1-5-"), "{}", user_sid().unwrap()); } + #[test] + fn windows_says_where_program_files_is() { + // And System32 is not in it. + let dir = program_files().expect("ProgramFilesDir"); + assert!(dir.is_absolute(), "{}", dir.display()); + assert!(!is_inside(&system32().join("schtasks.exe"), &dir)); + assert!(system32().is_absolute()); + } + #[test] fn a_file_without_a_command_runs_nothing() { assert_eq!(command(&[]), None); diff --git a/gui/src/tray.rs b/gui/src/tray.rs index 90b9e6e..47fb8bf 100644 --- a/gui/src/tray.rs +++ b/gui/src/tray.rs @@ -72,6 +72,7 @@ impl Tray { /// Must run on the thread of the event loop, once it runs. pub fn new() -> Result { let show = MenuItem::new("Open camless", true, None); + autostart::follow(); let logon = CheckMenuItem::new("Start with Windows", true, autostart::enabled(), None); let exit = MenuItem::new("Exit", true, None); let menu = Menu::new(); @@ -151,4 +152,38 @@ pub mod autostart { } Ok(()) } + + /// Points the entry at this app when the camless it names is gone: the setup once + /// put camless in the user's own folder and now moves it to Program Files. + pub fn follow() { + let (key, value) = (wide(KEY), wide(VALUE)); + let mut buf = [0u16; 1024]; + let mut len = size_of_val(&buf) as u32; + let r = unsafe { RegGetValueW(HKEY_CURRENT_USER, key.as_ptr(), value.as_ptr(), RRF_RT_REG_SZ, null_mut(), buf.as_mut_ptr().cast(), &mut len) }; + if r != ERROR_SUCCESS { + return; + } + let text = String::from_utf16_lossy(&buf[..(len as usize / 2).min(buf.len())]); + if program(&text).is_some_and(|exe| !std::path::Path::new(exe).exists()) { + let _ = set(true); + } + } + + /// The program an entry starts: what its first pair of quotes holds. + fn program(entry: &str) -> Option<&str> { + let rest = entry.trim_start().strip_prefix('"')?; + rest.split_once('"').map(|(exe, _)| exe).filter(|exe| !exe.is_empty()) + } + + #[cfg(test)] + mod tests { + #[test] + fn the_entry_names_its_program() { + let entry = "\"C:\\Users\\A B\\AppData\\Local\\Programs\\camless\\camless-gui.exe\" --tray\0"; + assert_eq!(super::program(entry), Some(r"C:\Users\A B\AppData\Local\Programs\camless\camless-gui.exe")); + // One written some other way is left alone. + assert_eq!(super::program(r"C:\camless-gui.exe --tray"), None); + assert_eq!(super::program("\"\""), None); + } + } } diff --git a/gui/ui/app.css b/gui/ui/app.css index bc8b889..01b7f2b 100644 --- a/gui/ui/app.css +++ b/gui/ui/app.css @@ -289,9 +289,6 @@ body.light { background: #f7f6fa; } .cam-thumb path { stroke: var(--tick-major); } .cam-thumb polyline { stroke: var(--ce-line); stroke-width: 1.5; stroke-linejoin: round; } .cam-row-line > .txt span { margin: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: none; } -.cam-risk { display: flex !important; gap: 6px; margin-top: 6px !important; color: var(--t2); } -.cam-risk svg.i { flex: none; width: 14px; height: 14px; margin-top: 2px; color: var(--amber); } -.cam-risk span { margin: 0 !important; } .cam-row > .txt { flex: 1; min-width: 0; } .cam-row > .txt > b { display: block; font-size: 13px; font-weight: 600; } .cam-row > .txt span b { font-weight: 600; color: var(--t2); } diff --git a/gui/ui/app.js b/gui/ui/app.js index e570aa5..b6b2a1c 100644 --- a/gui/ui/app.js +++ b/gui/ui/app.js @@ -3813,7 +3813,7 @@ const sv = S.server, v = esc(sv.update.latest); const ok = await confirmBox({ title: `Update to camless ${sv.update.latest}`, - text: `camless downloads ${v}, closes, installs the app and the service together, and opens again.${sv.admin_task || linux() ? '' : ' Windows then asks for administrator rights for the service, as at every start.'} For those few seconds, fans that camless sets run at the failsafe speed; curves stored on a cooler keep running.`, + text: `camless downloads ${v}, closes, installs the app and the service together, and opens again.${linux() ? '' : sv.admin_task ? ' Windows asks for administrator rights for the setup.' : ' Windows asks for administrator rights twice: for the setup, then for the service, as at every start.'} For those few seconds, fans that camless sets run at the failsafe speed; curves stored on a cooler keep running.`, ok: 'Update', }); if (ok) act('update/install', {}); @@ -3863,7 +3863,7 @@ let hint; if (sv.sandbox) hint = 'In this test copy the switch changes nothing in Windows.'; else if (sv.admin_task_busy) hint = 'Waiting for Windows…'; - else hint = `Windows asks once, then camless starts the service as administrator on its own.${I.warn}Any program you run could then get administrator rights through camless, without a prompt.`; + else hint = 'Windows asks once, then camless starts the service as administrator on its own.'; if (sv.admin_task_error && !sv.admin_task_busy) hint += `${esc(sv.admin_task_error)}`; r.hint(hint); }; diff --git a/installer/camless.iss b/installer/camless.iss index b5c570f..e58959c 100644 --- a/installer/camless.iss +++ b/installer/camless.iss @@ -1,7 +1,11 @@ -; Builds camless-setup.exe, which installs camless.exe and camless-gui.exe for the current user, -; without administrator rights. scripts\package.ps1 builds both exes and runs this with the version: +; Builds camless-setup.exe, which installs camless.exe and camless-gui.exe in Program Files. +; scripts\package.ps1 builds both exes and runs this with the version: ; ISCC /DAppVersion=0.5.0-beta.1 /DAppNumericVersion=0.5.0 installer\camless.iss ; +; The setup asks for administrator rights. The service runs with them, so camless must be where +; only administrators write: in a folder of the user's, any program they run could replace it. +; Until 0.6.0-beta.6 the setup put it in %LOCALAPPDATA%\Programs\camless; this one moves it. +; ; Running it over an installed camless updates it in place: it closes the app, stops the service ; through its loopback API, replaces both exes and opens the app again, which starts the service. ; /VERYSILENT does the same without a window. Settings and profiles in %APPDATA%\camless stay. @@ -27,11 +31,15 @@ AppPublisherURL=https://github.com/kleju13/camless AppSupportURL=https://github.com/kleju13/camless/issues AppUpdatesURL=https://github.com/kleju13/camless/releases VersionInfoVersion={#AppNumericVersion} -DefaultDirName={localappdata}\Programs\camless +DefaultDirName={autopf}\camless +; Always Program Files, also over a copy that /DIR once put elsewhere. +UsePreviousAppDir=no DisableDirPage=yes DisableProgramGroupPage=yes DisableReadyPage=yes -PrivilegesRequired=lowest +; The setup starts without them and asks Windows itself, so the app of an older camless, which +; starts it as a plain program, still updates. +PrivilegesRequired=admin ArchitecturesAllowed=x64compatible ArchitecturesInstallIn64BitMode=x64compatible MinVersion=10.0 @@ -55,18 +63,37 @@ Source: "..\target\release\camless-gui.exe"; DestDir: "{app}"; Flags: ignorevers [Icons] Name: "{autoprograms}\camless"; Filename: "{app}\camless-gui.exe"; Comment: "Fan, pump, lighting and LCD control for NZXT devices" -Name: "{autodesktop}\camless"; Filename: "{app}\camless-gui.exe"; Tasks: desktopicon +Name: "{autodesktop}\camless"; Filename: "{app}\camless-gui.exe"; Check: DesktopShortcut [Run] ; Not skipped when silent, so an update opens the app again, and the app starts the service. -Filename: "{app}\camless-gui.exe"; Description: "Open camless"; Flags: postinstall nowait +; The app runs as the user who started the setup, without the setup's administrator rights. +Filename: "{app}\camless-gui.exe"; Description: "Open camless"; Flags: postinstall nowait runasoriginaluser + +[UninstallDelete] +; The PawnIO modules the user put next to camless.exe. +Type: files; Name: "{app}\IntelMSR.bin" +Type: files; Name: "{app}\AMDFamily17.bin" [Code] const RunKey = 'Software\Microsoft\Windows\CurrentVersion\Run'; + { Where the setup listed camless for one user, until 0.6.0-beta.6. } + OldUninstallKey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall\{7D97C062-B088-4D5D-A5BE-24FFC0DC4483}_is1'; + +var + { The folder of a camless installed for one user, which this setup replaces, or empty. } + OldDir: String; + { That camless had a shortcut on the user's desktop. } + HadDesktopShortcut: Boolean; + +function DesktopShortcut: Boolean; +begin + Result := WizardIsTaskSelected('desktopicon') or HadDesktopShortcut; +end; { The service's API address: listen under [api] in camless.toml, which is next to the exe if there - is one, else in %APPDATA%\camless. } + is one, also the exe of a camless this setup replaces, else in %APPDATA%\camless. } function ApiAddress: String; var Lines: TArrayOfString; @@ -76,6 +103,8 @@ var begin Result := '127.0.0.1:30641'; Path := ExpandConstant('{app}\camless.toml'); + if not FileExists(Path) and (OldDir <> '') then + Path := OldDir + '\camless.toml'; if not FileExists(Path) then Path := ExpandConstant('{userappdata}\camless\camless.toml'); if not LoadStringsFromFile(Path, Lines) then @@ -148,13 +177,139 @@ begin Result := False; end; +function TaskName: String; +begin + Result := '"camless (' + GetUserNameString + ')"'; +end; + +{ Whether this user has the task the app sets up for Start as administrator without asking. } +function TaskExists: Boolean; +var + Code: Integer; +begin + Result := Exec(ExpandConstant('{sys}\schtasks.exe'), '/Query /TN ' + TaskName, '', SW_HIDE, ewWaitUntilTerminated, Code) and (Code = 0); +end; + +function RemoveTask: Boolean; +var + Code: Integer; +begin + Result := Exec(ExpandConstant('{sys}\schtasks.exe'), '/Delete /TN ' + TaskName + ' /F', '', SW_HIDE, ewWaitUntilTerminated, Code) and (Code = 0); +end; + +{ Whether the folder or file at Path is a link, such as a junction. } +function IsLink(const Path: String): Boolean; +var + Find: TFindRec; +begin + Result := FindFirst(Path, Find); + if not Result then + Exit; + Result := Find.Attributes and FILE_ATTRIBUTE_REPARSE_POINT <> 0; + FindClose(Find); +end; + +{ Until 0.6.0-beta.6 the setup installed camless for one user, in a folder of theirs. This finds + that copy, before the service is stopped and the new one's shortcuts are made. A folder that + is a link is left alone: it could lead to another program's folder. } +procedure FindOldInstall; +var + Programs: String; +begin + Programs := ExpandConstant('{localappdata}\Programs'); + OldDir := Programs + '\camless'; + if (CompareText(OldDir, WizardDirValue) = 0) or not FileExists(OldDir + '\camless-gui.exe') + or IsLink(Programs) or IsLink(OldDir) then + OldDir := '' + else + HadDesktopShortcut := FileExists(ExpandConstant('{userdesktop}\camless.lnk')); +end; + +function Quoted(const Path: String): String; +begin + Result := ' "' + Path + '"'; +end; + +{ Removes that copy once the new one is in place: its two exes, its uninstaller, its shortcuts, + a PawnIO module that the new copy has now, and its entry in Windows' list of apps. The folder + goes too if nothing else is left in it. Nothing from the folder is run, since this setup has + administrator rights and any program of the user's could have replaced what is there. For the + same reason the files are deleted with the user's rights, not the setup's: the folder could + become a link to another one between the look at it and the delete. The app repairs Start with + Windows by itself. } +procedure RemoveOldInstall; +var + Files: String; + Code: Integer; +begin + Files := Quoted(ExpandConstant('{userdesktop}\camless.lnk')) + Quoted(ExpandConstant('{userprograms}\camless.lnk')) + + Quoted(OldDir + '\camless.exe') + Quoted(OldDir + '\camless-gui.exe') + Quoted(OldDir + '\unins???.*'); + if FileExists(ExpandConstant('{app}\IntelMSR.bin')) then + Files := Files + Quoted(OldDir + '\IntelMSR.bin'); + if FileExists(ExpandConstant('{app}\AMDFamily17.bin')) then + Files := Files + Quoted(OldDir + '\AMDFamily17.bin'); + ExecAsOriginalUser(ExpandConstant('{cmd}'), '/C del /F /Q' + Files + ' & rd' + Quoted(OldDir), '', SW_HIDE, ewWaitUntilTerminated, Code); + RegDeleteKeyIncludingSubkeys(HKEY_CURRENT_USER, OldUninstallKey); +end; + +{ Copies a PawnIO module the user put next to the old camless.exe to the new one. Only a plain + file of a module's size: a link there could name a file the user may not read. } +procedure CopyModule(const Name: String); +var + Find: TFindRec; + Plain: Boolean; + Old, Target: String; +begin + Old := OldDir + '\' + Name; + Target := ExpandConstant('{app}\') + Name; + if not FindFirst(Old, Find) then + Exit; + Plain := (Find.Attributes and (FILE_ATTRIBUTE_DIRECTORY or FILE_ATTRIBUTE_REPARSE_POINT) = 0) + and (Find.SizeHigh = 0) and (Find.SizeLow < 1048576); + FindClose(Find); + if Plain and not FileExists(Target) then + CopyFile(Old, Target, True); +end; + function PrepareToInstall(var NeedsRestart: Boolean): String; begin Result := ''; + { First, for the address of a service that reads a camless.toml beside the old exe. } + FindOldInstall; if not StopCamless then Result := 'The camless service did not stop. Restart Windows, then run setup again.'; end; +{ The task names the exe it starts. The app writes it again for the camless just installed: one + left pointing at the old folder would start, as administrator, whatever is put there. So a + task that cannot be written again is deleted, and the app asks through UAC as before. } +procedure RenewTask; +var + Code: Integer; +begin + if not TaskExists then + Exit; + if Exec(ExpandConstant('{app}\camless-gui.exe'), '--set-up-task', '', SW_HIDE, ewWaitUntilTerminated, Code) and (Code = 0) then + Exit; + if RemoveTask then + Log('The task for Start as administrator without asking could not be written again, so it was deleted.') + else + MsgBox('camless could not renew or delete its scheduled task ' + TaskName + '. It may still start camless from its old folder. Delete it in Task Scheduler.', mbError, MB_OK); +end; + +procedure CurStepChanged(CurStep: TSetupStep); +begin + if CurStep <> ssPostInstall then + Exit; + RenewTask; + if OldDir <> '' then + begin + CopyModule('IntelMSR.bin'); + CopyModule('AMDFamily17.bin'); + RemoveOldInstall; + end; +end; + function InitializeUninstall: Boolean; begin Result := StopCamless; @@ -162,24 +317,14 @@ begin MsgBox('The camless service did not stop. Restart Windows, then uninstall again.', mbError, MB_OK); end; -{ Deletes the task the app sets up for Start as administrator without asking. Its user may delete - it; if that fails anyway, Windows is asked. A task left behind would run whatever exe is put in - the folder it points at, so a failure is reported. } +{ Deletes the task the app sets up for Start as administrator without asking. A task left behind + would start nothing, but a failure is reported all the same. } procedure DeleteTask; -var - Schtasks, Name: String; - Code: Integer; begin - Schtasks := ExpandConstant('{sys}\schtasks.exe'); - Name := '"camless (' + GetUserNameString + ')"'; - if not Exec(Schtasks, '/Query /TN ' + Name, '', SW_HIDE, ewWaitUntilTerminated, Code) or (Code <> 0) then - Exit; - if Exec(Schtasks, '/Delete /TN ' + Name + ' /F', '', SW_HIDE, ewWaitUntilTerminated, Code) and (Code = 0) then - Exit; - if ShellExec('runas', Schtasks, '/Delete /TN ' + Name + ' /F', '', SW_HIDE, ewWaitUntilTerminated, Code) and (Code = 0) then + if not TaskExists or RemoveTask then Exit; if not UninstallSilent then - MsgBox('camless could not delete its scheduled task ' + Name + '. Delete it in Task Scheduler.', mbError, MB_OK); + MsgBox('camless could not delete its scheduled task ' + TaskName + '. Delete it in Task Scheduler.', mbError, MB_OK); end; procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); @@ -189,11 +334,15 @@ begin { The app adds this value for Start with Windows. } RegDeleteValue(HKEY_CURRENT_USER, RunKey, 'camless'); DeleteTask; - if not UninstallSilent and (MsgBox('Also delete your camless settings and profiles?' + #13#10#13#10 - + ExpandConstant('{userappdata}\camless') + #13#10 + ExpandConstant('{localappdata}\camless'), + if not UninstallSilent and (MsgBox('Also delete your camless settings, profiles and history?' + #13#10#13#10 + + ExpandConstant('{userappdata}\camless') + #13#10 + ExpandConstant('{localappdata}\camless') + + #13#10 + ExpandConstant('{app}\data'), mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES) then begin DelTree(ExpandConstant('{userappdata}\camless'), True, True, True); DelTree(ExpandConstant('{localappdata}\camless'), True, True, True); + { The service's own folder for the history, while it runs as administrator. } + DelTree(ExpandConstant('{app}\data'), True, True, True); + RemoveDir(ExpandConstant('{app}')); end; end; diff --git a/scripts/install.ps1 b/scripts/install.ps1 index c1172de..a0c0e71 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -1,5 +1,6 @@ # Installs or updates camless from the latest release: downloads camless-setup.exe, checks its -# SHA-256 and runs it silently. No admin needed; the app asks for it when it starts the service. +# SHA-256 and runs it silently. The setup asks for administrator rights, and the app asks again +# when it starts the service. # irm https://raw.githubusercontent.com/kleju13/camless/main/scripts/install.ps1 | iex $ErrorActionPreference = 'Stop' # Windows PowerShell downloads many times slower while it draws a progress bar. @@ -23,7 +24,7 @@ $have = (Get-FileHash $setup -Algorithm SHA256).Hash if ($have -ne $want) { Remove-Item $setup; throw "download does not match its checksum ($have, expected $want)" } Unblock-File $setup -Write-Host 'Installing...' +Write-Host 'Installing: answer Yes when Windows asks for administrator rights.' # Not -Wait: that also waits for the app, which setup opens at the end and which keeps running. $p = Start-Process $setup '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART' -PassThru $null = $p.Handle # without it, Windows PowerShell loses the exit code @@ -31,5 +32,5 @@ $p.WaitForExit() if ($p.ExitCode -ne 0) { throw "setup failed with exit code $($p.ExitCode)" } Remove-Item $dir -Recurse -ErrorAction SilentlyContinue -Write-Host "Installed camless $($release.tag_name) in $env:LOCALAPPDATA\Programs\camless, with a Start menu entry." -Write-Host 'The app is opening: answer Yes when Windows asks for administrator rights, so CPU temperature works.' +Write-Host "Installed camless $($release.tag_name) in $env:ProgramFiles\camless, with a Start menu entry." +Write-Host 'The app is opening: answer Yes when Windows asks again, for the service, so CPU temperature works.' diff --git a/src/drivers/gpu.rs b/src/drivers/gpu.rs index 12783c7..d46afef 100644 --- a/src/drivers/gpu.rs +++ b/src/drivers/gpu.rs @@ -172,14 +172,23 @@ mod nvidia { /// There while camless may have left a fan at a duty: a camless that was killed /// or crashed has no Drop to give the fans back, and the card keeps a duty NVML /// set. The next one gives every fan back to the card first. + /// + /// It is in one place whatever config the service runs, so that the next camless + /// finds it: with the installed service's own files, and else in `%APPDATA%\camless`. fn marker() -> PathBuf { + crate::state::own().map_or_else(old_marker, |own| own.join("taken-gpu-fans")) + } + + /// Where a camless from before 0.6.0-beta.7 left it, and where one outside + /// Program Files still does. + fn old_marker() -> PathBuf { camless_core::config::app_config_dir().join("camless").join("taken-gpu-fans") } /// Gives every fan of every card back to its curve after a camless that did not, /// whatever the settings say now. pub fn hand_back_abandoned() { - if TAKEN.load(Ordering::SeqCst) > 0 || !marker().exists() { + if TAKEN.load(Ordering::SeqCst) > 0 || !(marker().exists() || old_marker().exists()) { return; } let Ok(api) = Api::open() else { return }; @@ -196,6 +205,7 @@ mod nvidia { } if all { let _ = std::fs::remove_file(marker()); + let _ = std::fs::remove_file(old_marker()); } } diff --git a/src/games.rs b/src/games.rs index debe894..6c225dd 100644 --- a/src/games.rs +++ b/src/games.rs @@ -290,7 +290,7 @@ impl Games { /// Sessions are kept in `dir`, or only in memory without one. Without /// administrator rights there are no frame rates. pub fn new(dir: Option<&Path>, elevated: bool, demo: bool) -> Games { - let file = dir.map(|d| d.join("sessions.jsonl")); + let file = dir.map(|d| d.join(FILE)); let log = file.as_deref().map(load).unwrap_or_default(); let (error, retry) = match (demo, elevated) { (true, _) => (None, Some(Instant::now())), @@ -522,6 +522,16 @@ fn unix_ms() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64) } +/// The sessions' file, in the history's folder. +pub const FILE: &str = "sessions.jsonl"; + +/// The lines of a sessions file that are sessions, written again. See +/// [`crate::state`] for what else a file can hold. +pub fn clean(text: &str) -> String { + let lines = text.lines().filter_map(|l| serde_json::from_str::(l).ok()).filter_map(|s| serde_json::to_string(&s).ok()); + lines.flat_map(|l| [l, "\n".to_string()]).collect() +} + fn load(file: &Path) -> Vec { let Ok(text) = std::fs::read_to_string(file) else { return Vec::new() }; // A line a crash cut short does not parse and is skipped. diff --git a/src/history.rs b/src/history.rs index 4d80bf8..210f488 100644 --- a/src/history.rs +++ b/src/history.rs @@ -355,6 +355,24 @@ fn day_file(day: i64) -> String { format!("{y:04}-{m:02}-{d:02}.csv") } +/// Whether `name` is a day file's, such as `2026-10-20.csv`. +pub fn is_day_file(name: &str) -> bool { + file_day(name).is_some() +} + +/// The lines of a day file that are this module's own: a header, or a time followed +/// by numbers. See [`crate::state`] for what else a file can hold. +pub fn clean(text: &str) -> String { + let own = |l: &&str| { + if let Some(names) = l.strip_prefix("#t") { + return (names.is_empty() || names.starts_with(',')) && !l.contains(char::is_control); + } + let mut fields = l.split(','); + fields.next().is_some_and(|t| t.parse::().is_ok()) && fields.all(|f| f.is_empty() || f.parse::().is_ok()) + }; + text.lines().filter(own).flat_map(|l| [l, "\n"]).collect() +} + /// The day a file is for, if its name is one of ours. fn file_day(name: &str) -> Option { let stem = name.strip_suffix(".csv")?; diff --git a/src/main.rs b/src/main.rs index e96f74d..cfccd41 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,7 @@ mod q565; mod report; mod requirements; mod sensors; +mod state; mod web; use anyhow::{bail, Context, Result}; @@ -470,7 +471,10 @@ fn run(path: PathBuf, verbose: bool, demo: bool, limit: Option) -> Res } let shared = Arc::new(Mutex::new(daemon::Snapshot::default())); // Simulated readings stay out of the files. - let history_dir = path.parent().filter(|_| !demo).map(|d| d.join("history")); + let history_dir = (!demo).then(|| state::init(&path).join("history")); + if !demo { + state::bring_history_over(&path); + } let games = games::Games::new(history_dir.as_deref(), web::is_elevated(), demo); let history = Arc::new(Mutex::new(history::History::new(history_dir))); // Two frames in flight at most; the API answers 429 beyond that. diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..1606bd7 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,148 @@ +//! Where the service keeps what it writes: the history, the game sessions and the +//! marker for the GPU fans it has taken. +//! +//! That is the config's folder, except for the installed service on Windows while it +//! runs as administrator: there it is `data` in camless's own folder in Program +//! Files, which only administrators write. In a folder of the user's, any program +//! they run could put a link in place of `history`, and the service would write, +//! with administrator rights, wherever the link leads. + +use crate::{games, history}; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +static DIR: OnceLock = OnceLock::new(); + +/// A file larger than this is not the service's own. +const LARGEST: u64 = 64 << 20; + +/// Settles the folder for the service that runs the config at `config`. Without a +/// call, [`dir`] goes by the default config. +pub fn init(config: &Path) -> &'static Path { + DIR.get_or_init(|| resolve(config)) +} + +pub fn dir() -> &'static Path { + init(&camless_core::config::default_path()) +} + +fn resolve(config: &Path) -> PathBuf { + let beside = config.parent().map(Path::to_path_buf).unwrap_or_default(); + own().map_or(beside, Path::to_path_buf) +} + +/// The installed service's folder for its files, while it runs as administrator. +pub fn own() -> Option<&'static Path> { + static OWN: OnceLock> = OnceLock::new(); + OWN.get_or_init(|| own_folder().map(|folder| folder.join("data"))).as_deref() +} + +/// The folder camless.exe is in, when that is in Program Files and the service has +/// administrator rights. Windows names Program Files in a part of the registry that +/// takes those rights to change; `%ProgramFiles%` is whatever the user's programs set. +#[cfg(windows)] +fn own_folder() -> Option { + if !crate::web::is_elevated() { + return None; + } + let exe = std::env::current_exe().ok()?; + let program_files = crate::sensors::reg_string(r"SOFTWARE\Microsoft\Windows\CurrentVersion", "ProgramFilesDir")?; + camless_core::config::is_inside(&exe, Path::new(&program_files)).then(|| exe.parent().map(Path::to_path_buf))? +} + +#[cfg(not(windows))] +fn own_folder() -> Option { + None +} + +/// Brings the history kept beside the config at `config` to [`dir`], once: what the +/// service wrote before it had a folder of its own, or while it ran without +/// administrator rights. The old files stay where they are. +pub fn bring_history_over(config: &Path) { + let Some(beside) = config.parent() else { return }; + if beside != dir() { + bring_over(&beside.join("history"), &dir().join("history")); + } +} + +/// Only the service's own files, and of each only the lines that are its own. `from` +/// is a folder of the user's, and this may run as administrator: a link there could +/// name a file the user may not read, and a copy of it would land where they may. +fn bring_over(from: &Path, to: &Path) { + if to.exists() { + return; + } + let Ok(entries) = std::fs::read_dir(from) else { return }; + // Filled beside `to` and renamed at the end: a camless that stops halfway leaves + // no `to`, and the next one starts again. + let part = to.with_extension("part"); + let _ = std::fs::remove_dir_all(&part); + if let Err(e) = std::fs::create_dir_all(&part) { + eprintln!("history: {} not made, so the old history stays in {}: {e}", part.display(), from.display()); + return; + } + let mut brought = 0; + for e in entries.flatten() { + let name = e.file_name(); + let Some(name) = name.to_str() else { continue }; + let clean: fn(&str) -> String = match name { + games::FILE => games::clean, + _ if history::is_day_file(name) => history::clean, + _ => continue, + }; + if !e.metadata().is_ok_and(|m| m.file_type().is_file() && m.len() <= LARGEST) { + continue; + } + let Ok(text) = std::fs::read_to_string(e.path()) else { continue }; + if std::fs::write(part.join(name), clean(&text)).is_ok() { + brought += 1; + } + } + if let Err(e) = std::fs::rename(&part, to) { + eprintln!("history: {} not made, so the old history stays in {}: {e}", to.display(), from.display()); + } else if brought > 0 { + eprintln!("history: {brought} files brought over from {} to {}", from.display(), to.display()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_the_services_own_lines_come_over() { + let root = std::env::temp_dir().join(format!("camless-state-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (from, to) = (root.join("old").join("history"), root.join("new").join("history")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::write(from.join("2026-10-20.csv"), "#t,cpu.temp\n1760918400,40,41.5\nroot:x:0:0:secret\n1760918460,,\n1760918520,4").unwrap(); + let session = r#"{"game":"Half-Life","exe":"hl.exe","start":1,"end":2,"played":1,"frames":0}"#; + std::fs::write(from.join(games::FILE), format!("{session}\nnot json\n")).unwrap(); + std::fs::write(from.join("notes.txt"), "mine").unwrap(); + std::fs::create_dir_all(from.join("2026-10-21.csv")).unwrap(); + // What a camless that stopped halfway left. + let part = root.join("new").join("history.part"); + std::fs::create_dir_all(&part).unwrap(); + std::fs::write(part.join("2026-10-19.csv"), "#t\n").unwrap(); + + bring_over(&from, &to); + assert!(!part.exists() && !to.join("2026-10-19.csv").exists()); + assert_eq!(std::fs::read_to_string(to.join("2026-10-20.csv")).unwrap(), "#t,cpu.temp\n1760918400,40,41.5\n1760918460,,\n1760918520,4\n"); + let sessions = std::fs::read_to_string(to.join(games::FILE)).unwrap(); + assert_eq!(sessions.lines().count(), 1); + assert!(sessions.contains("Half-Life") && !sessions.contains("not json"), "{sessions}"); + assert!(!to.join("notes.txt").exists() && !to.join("2026-10-21.csv").exists()); + // The old files stay, and a second run leaves what the service has written since. + assert!(from.join("2026-10-20.csv").exists()); + std::fs::write(to.join("2026-10-20.csv"), "#t\n").unwrap(); + bring_over(&from, &to); + assert_eq!(std::fs::read_to_string(to.join("2026-10-20.csv")).unwrap(), "#t\n"); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn the_folder_is_the_configs_without_an_install() { + // The tests' own exe is not in Program Files, whatever rights it runs with. + assert_eq!(resolve(Path::new("/etc/camless/camless.toml")), Path::new("/etc/camless")); + } +}