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
7 changes: 7 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# The workflows pin each action to a commit; this proposes the newer ones, once a month.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
18 changes: 12 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,27 @@ on:
branches: [main]
pull_request:

# Actions are pinned to a commit, not a tag that can be moved: a build here becomes the setup people
# install. .github/dependabot.yml proposes the newer commits.
permissions:
contents: read

jobs:
test:
runs-on: windows-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# Restores the compiled dependencies from the last run on main. Only main saves, so pull requests
# read that cache but don't fill the repository's 10 GB with their own.
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo test --workspace --release
- run: cargo test --workspace --release --locked
- run: choco install innosetup --no-progress -y
- run: ./scripts/package.ps1
- uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: camless-setup
path: dist/*
Expand All @@ -33,14 +37,16 @@ jobs:
linux:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libudev-dev
- run: cargo test --workspace --release
- run: cargo test --workspace --release --locked
- run: sh scripts/package-linux.sh
- uses: actions/upload-artifact@v7
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: camless-linux
path: dist/camless-linux-x86_64.tar.gz*
27 changes: 18 additions & 9 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,32 @@ jobs:
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v7
- run: cargo test --workspace --release
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- run: cargo test --workspace --release --locked
- run: choco install innosetup --no-progress -y
- run: ./scripts/package.ps1 -Tag "${{ github.ref_name }}"
- uses: actions/upload-artifact@v7
# The tag through the environment: written into the script, its name would run as part of it.
- run: ./scripts/package.ps1 -Tag "$env:TAG"
env:
TAG: ${{ github.ref_name }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: windows
path: dist/camless-setup.exe*

linux:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libwebkit2gtk-4.1-dev libgtk-3-dev libudev-dev
- run: cargo test --workspace --release
- run: sh scripts/package-linux.sh "${{ github.ref_name }}"
- uses: actions/upload-artifact@v7
- run: cargo test --workspace --release --locked
- run: sh scripts/package-linux.sh "$TAG"
env:
TAG: ${{ github.ref_name }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: linux
path: dist/camless-linux-x86_64.tar.gz*
Expand All @@ -45,7 +54,7 @@ jobs:
permissions:
contents: write
steps:
- uses: actions/download-artifact@v8
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
path: dist
merge-multiple: true
Expand Down
16 changes: 8 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,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. 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, `%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 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.

Expand Down Expand Up @@ -159,7 +159,11 @@ Each call returns a promise that resolves once camless has taken the message, or
| `POST /v1/stop` | stops the service the way Ctrl+C does: host-driven fans to `failsafe_duty` or their fixed duty, the LCD back to its own screen; `Content-Type: application/json` only, so web pages cannot send it |
| `POST /v1/lcd/frame` | one frame for the LCD in `frames` mode at its size (640×640 on the Kraken Elite), raw RGBA or RGB565 big-endian, `Content-Type: application/octet-stream`; 202, 409 without such an LCD, 429 when two frames are already waiting |

It listens on `127.0.0.1:30641` by default and binds to loopback only. It rejects foreign `Host` headers, so web pages cannot reach it through DNS rebinding.
It listens on `127.0.0.1:30641` by default and binds to loopback only. Web pages are kept out:
- A foreign `Host` header gets 421, so a page cannot reach it through DNS rebinding.
- A request a browser sends for a page elsewhere gets 403: one with an `Origin` other than the API's own address, or with `Sec-Fetch-Site` other than `same-origin` or `none`. Programs send neither header, and an address typed into a browser comes with `Sec-Fetch-Site: none`; a link to the API on a web page gets the 403.

It has no password. Any program on this PC can read it, send frames and stop the service, and so can another user signed in to the same PC.

## The app's look

Expand Down
2 changes: 1 addition & 1 deletion scripts/package-linux.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ if [ -n "$tag" ] && [ "$tag" != "v$version" ]; then
exit 1
fi

cargo build --release --workspace --manifest-path "$root/Cargo.toml"
cargo build --release --workspace --locked --manifest-path "$root/Cargo.toml"
target=${CARGO_TARGET_DIR:-$root/target}/release

name=camless-linux-x86_64.tar.gz
Expand Down
2 changes: 1 addition & 1 deletion scripts/package.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ $version = $versions[0]
if (@($versions | Select-Object -Unique).Count -ne 1) { throw "the crates are at different versions: $($versions -join ', ')" }
if ($Tag -and $Tag -ne "v$version") { throw "tag $Tag does not match version $version in Cargo.toml" }

cargo build --release --workspace --manifest-path (Join-Path $root 'Cargo.toml')
cargo build --release --workspace --locked --manifest-path (Join-Path $root 'Cargo.toml')
if ($LASTEXITCODE -ne 0) { throw 'cargo build failed' }

$iscc = (Get-Command iscc -ErrorAction SilentlyContinue).Source
Expand Down
49 changes: 48 additions & 1 deletion src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ fn handle(
if !header(&req, "Host").is_some_and(|h| hosts.iter().any(|ok| ok.eq_ignore_ascii_case(h))) {
return Ok(req.respond(Response::empty(421))?);
}
// Nor does a page on the web get to ask at all: a browser says where a request
// comes from, and programs on this PC say nothing.
if from_another_site(header(&req, "Origin"), header(&req, "Sec-Fetch-Site"), hosts) {
// Someone who followed a link here reads this in their browser.
let msg = "camless's local API does not answer web pages. To see this address, type it into the address bar.";
return Ok(req.respond(Response::from_string(msg).with_status_code(403))?);
}
let snapshot = || shared.lock().unwrap_or_else(|e| e.into_inner()).clone();
let url = req.url().to_string();
let (path, query) = url.split_once('?').unwrap_or((&url, ""));
Expand Down Expand Up @@ -128,6 +135,16 @@ fn handle(
}
}

/// Whether a browser sent this for a page that is not the API's own: one with an
/// `Origin` other than the API's address, or one the browser marks as coming from
/// another site or another port (`Sec-Fetch-Site`). Such a page could not read the
/// answer, and the two POSTs already turn it away by content type; this keeps it from
/// every path, the ones added later too. A request with neither header is a program's.
fn from_another_site(origin: Option<&str>, fetch_site: Option<&str>, hosts: &[String]) -> bool {
let own = |o: &str| o.strip_prefix("http://").is_some_and(|h| hosts.iter().any(|ok| ok.eq_ignore_ascii_case(h)));
origin.is_some_and(|o| !own(o.trim())) || fetch_site.is_some_and(|s| !matches!(s.trim(), "same-origin" | "none"))
}

/// The body of `GET path` from the service at `addr`, for commands that ask the
/// running service, the way the app asks it.
pub fn get(addr: &str, path: &str) -> Result<String> {
Expand All @@ -146,12 +163,19 @@ pub fn get(addr: &str, path: &str) -> Result<String> {
Ok(body.to_string())
}

/// The largest time or span a history query may name, in seconds.
const MAX_SECS: i64 = 99_999_999_999;

/// The window a history query asks for, as (from, to, ids): the last `span` seconds,
/// 600 by default, or `from` to `to` (Unix seconds, `to` now by default). `ids` is a
/// comma-separated list of series.
fn history_query(query: &str, now: i64) -> std::result::Result<(i64, i64, Option<Vec<String>>), String> {
let (mut span, mut from, mut to, mut ids) = (600, None, now, None);
let secs = |k: &str, v: &str| v.parse::<i64>().map_err(|_| format!("{k} {v:?} is not a number of seconds"));
// Times since 1970 and spans, so never negative, and no further than the year
// 5138: the arithmetic on them then stays far from the ends of an i64.
let secs = |k: &str, v: &str| {
v.parse::<i64>().ok().filter(|n| (0..=MAX_SECS).contains(n)).ok_or_else(|| format!("{k} {v:?} is not a number of seconds"))
};
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
match k {
Expand Down Expand Up @@ -260,5 +284,28 @@ mod tests {
assert_eq!(history_query("from=1799999000", now), Ok((1_799_999_000, now, None)));
assert!(history_query("from=1700003600&to=1700000000", now).is_err());
assert_eq!(percent_decode("a%2"), "a%2");
// Nothing that would overflow further on.
for query in ["from=-9223372036854775808&to=-9223372036854775807", "to=-1", "span=-5", "from=100000000000", "span=9223372036854775807"] {
assert!(history_query(query, now).is_err(), "{query}");
}
}

#[test]
fn pages_on_the_web_are_turned_away() {
let hosts = ["127.0.0.1:30641".to_string(), "localhost:30641".to_string(), "[::1]:30641".to_string()];
let other = |origin, site| from_another_site(origin, site, &hosts);
// Programs: the app, curl, a script that posts frames.
assert!(!other(None, None));
// A page the API itself would serve, and an address typed into the browser.
assert!(!other(Some("http://127.0.0.1:30641"), Some("same-origin")));
assert!(!other(Some("http://LOCALHOST:30641"), None));
assert!(!other(None, Some("none")));
// Pages elsewhere, with or without CORS, and ones on another port of this PC.
assert!(other(Some("https://example.com"), Some("cross-site")));
assert!(other(None, Some("cross-site")));
assert!(other(None, Some("same-site")));
assert!(other(Some("http://localhost:8080"), None));
assert!(other(Some("https://127.0.0.1:30641"), None));
assert!(other(Some("null"), None));
}
}
16 changes: 2 additions & 14 deletions src/drivers/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,23 +110,11 @@ mod nvidia {
speed: u32,
}

/// Where the driver puts `nvml.dll`: System32 since 2019, NVSMI before. A full
/// path, so no `nvml.dll` beside camless loads instead.
fn library() -> Result<Library> {
let system = std::env::var_os("SystemRoot").map(|r| PathBuf::from(r).join("System32").join("nvml.dll"));
let nvsmi = std::env::var_os("ProgramFiles").map(|p| PathBuf::from(p).join("NVIDIA Corporation").join("NVSMI").join("nvml.dll"));
for path in [system, nvsmi].into_iter().flatten().filter(|p| p.exists()) {
if let Ok(lib) = unsafe { Library::new(&path) } {
return Ok(lib);
}
}
bail!("nvml.dll not found: no NVIDIA driver")
}

impl Api {
fn open() -> Result<Api> {
unsafe {
let lib = library()?;
// By its full path, so no `nvml.dll` beside camless loads instead.
let lib = crate::sensors::nvml_library()?;
let init: unsafe extern "C" fn() -> i32 = *lib.get(b"nvmlInit_v2\0")?;
// Every function first, so a missing one returns before NVML starts.
let api = Api {
Expand Down
6 changes: 3 additions & 3 deletions src/sensors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! and FanControl already install, and through hwmon and RAPL on Linux; CPU load and
//! memory from the system. [`os`] holds what differs.

use anyhow::{bail, Context, Result};
use anyhow::{bail, Result};
use camless_core::status::{PowerSource, Sensor, Unit};
use libloading::Library;
use serde::Serialize;
Expand All @@ -17,7 +17,7 @@ mod os;
#[path = "sensors/windows.rs"]
mod os;
#[cfg(windows)]
pub use os::{cpu_maker, pawnio_module_file, reg_dword, reg_string, PAWNIO_LIB};
pub use os::{cpu_maker, nvml as nvml_library, pawnio_module_file, reg_dword, reg_string, PAWNIO_LIB};
pub use os::{cpu_name, NO_CPU_TEMP};

/// Where camless reads the signed PawnIO module from: the config's path, or the
Expand Down Expand Up @@ -262,7 +262,7 @@ fn nvml_ok(code: i32, what: &str) -> Result<()> {
impl Nvml {
fn open() -> Result<Nvml> {
unsafe {
let lib = Library::new(os::NVML).with_context(|| format!("{} not found", os::NVML))?;
let lib = os::nvml()?;
let init: unsafe extern "C" fn() -> i32 = *lib.get(b"nvmlInit_v2\0")?;
nvml_ok(init(), "nvmlInit")?;
let by_index: unsafe extern "C" fn(u32, *mut NvmlDevice) -> i32 =
Expand Down
6 changes: 6 additions & 0 deletions src/sensors/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ use std::time::Instant;
/// The library NVIDIA's driver installs.
pub const NVML: &str = "libnvidia-ml.so.1";

/// By its name, which the dynamic linker finds in the system's library folders; the
/// service runs as the user here, so there is nobody's rights to borrow.
pub fn nvml() -> Result<libloading::Library> {
unsafe { libloading::Library::new(NVML) }.with_context(|| format!("{NVML} not found"))
}

pub const NO_CPU_TEMP: &str = "no CPU temperature (no k10temp, zenpower or coretemp sensor)";

const HWMON: &str = "/sys/class/hwmon";
Expand Down
Loading