9 Commits

Author SHA1 Message Date
nevaforget ca934b8c36 feat: add MOONLOCK_DEBUG env var for debug-level logging (v0.6.1)
Align with moongreet/moonset logging pattern — set MOONLOCK_DEBUG to
enable debug-level journal output for troubleshooting.
2026-03-28 22:57:02 +01:00
nevaforget d11b6e634e fix: audit fixes — D-Bus sender validation, fp lifecycle, multi-monitor caching (v0.6.0)
Close the only exploitable auth bypass: validate VerifyStatus signal sender
against fprintd's unique bus name. Fix fingerprint D-Bus lifecycle so devices
are properly released on verify-match and async restarts check the running
flag between awaits.

Security: num_msg guard in PAM callback, symlink rejection for background_path,
peek icon disabled, TOML parse errors logged, panic hook before logging.

Performance: blur and avatar textures cached across monitors, release profile
with LTO/strip.
2026-03-28 22:47:09 +01:00
nevaforget 4026f6dafa fix: audit fixes — double-unlock guard, PAM OOM code, GPU blur, async fp stop (v0.5.1)
Security: prevent double unlock() when PAM and fingerprint succeed
simultaneously (ext-session-lock protocol error). Fix PAM callback
returning PAM_AUTH_ERR instead of PAM_BUF_ERR on calloc OOM.

Performance: replace CPU-side Gaussian blur (image crate) with GPU blur
via GskBlurNode + GskRenderer::render_texture(). Eliminates 500ms-2s
main-thread blocking on cold cache for 4K wallpapers. Remove image and
dirs dependencies (~15 transitive crates). Make fingerprint stop()
fire-and-forget async to avoid 6s UI block after successful auth.
2026-03-28 22:06:38 +01:00
nevaforget 48706e5a29 perf: cache blurred wallpaper to disk to avoid re-blur on startup
First launch with blur blurs and saves to ~/.cache/moonlock/.
Subsequent starts load the cached PNG directly. Cache invalidates
when wallpaper path, size, mtime, or sigma changes.
Adds dirs crate for cache directory resolution.
2026-03-28 21:23:43 +01:00
nevaforget de9a3e9e6a feat: add optional background blur, align to shared texture pattern
Gaussian blur applied at texture load time when `background_blur` is
set in moonlock.toml. Refactored wallpaper loading from per-window
Picture::for_filename() to shared gdk::Texture pattern (matching
moonset/moongreet), avoiding redundant JPEG decoding on multi-monitor.
2026-03-28 14:53:27 +01:00
nevaforget 09e0d47a38 fix: audit fixes — async restart_verify, locale caching, panic safety (v0.5.0)
- restart_verify() now async via spawn_future_local (was blocking main thread)
- stop() uses 3s timeout instead of unbounded
- load_strings() caches locale detection in OnceLock (was reading /etc/locale.conf on every call)
- child_get() replaced with child_value().get() for graceful D-Bus type mismatch handling
- Eliminate redundant password clone in auth path (direct move into spawn_blocking)
- Add on_exhausted callback: hides fp_label after MAX_FP_ATTEMPTS
- Set running=false before on_success callback (prevent double-unlock)
- Add 4 unit tests for on_verify_status state machine
- Document GLib-GString/CString zeroize limitation in CLAUDE.md
2026-03-28 10:16:06 +01:00
nevaforget 13b329cd98 perf: async fprintd initialization for instant window display
Move all fprintd D-Bus calls (init, availability check, claim, verify)
from synchronous to async using gio futures. Windows now appear
immediately without waiting for D-Bus — fingerprint label fades in
once fprintd is ready. Single shared FingerprintListener across all
monitors instead of one per monitor.
2026-03-28 09:57:56 +01:00
nevaforget 58c076198f feat: switch logging to systemd journal (v0.4.2)
Replace env_logger + /var/cache/moonlock file logging with
systemd-journal-logger. Logs are now reliably accessible via
journalctl --user -u moonlock, fixing invisible errors in the
systemd user service context.

- Cargo.toml: env_logger → systemd-journal-logger 2.2
- main.rs: setup_logging() uses JournalLog
- PKGBUILD: add systemd-libs dependency
- power.rs: include unstaged systemctl fixes (ABOUTME, --no-ask-password, output())
2026-03-28 01:11:48 +01:00
nevaforget 78bcf90492 fix: use systemctl instead of loginctl for reboot/poweroff
loginctl has no reboot/poweroff subcommands — these are systemctl
commands. The error was silently swallowed because stderr wasn't
captured and logs went to a non-existent directory.
2026-03-28 00:53:14 +01:00
13 changed files with 633 additions and 431 deletions
+11 -9
View File
@@ -38,22 +38,24 @@ LD_PRELOAD=/usr/lib/libgtk4-layer-shell.so ./target/release/moonlock
## Architektur
- `auth.rs` — PAM-Authentifizierung via Raw FFI (unsafe extern "C" conv callback, msg_style-aware, Zeroizing<Vec<u8>>)
- `fingerprint.rs` — fprintd D-Bus Listener (Rc<RefCell<FingerprintListener>>, self-wiring g-signal via connect_local)
- `fingerprint.rs` — fprintd D-Bus Listener, async init/claim/verify via gio futures, sender-validated signal handler, cleanup_dbus() für sauberen D-Bus-Lifecycle, running_flag für Race-Safety in async restarts, on_exhausted callback after MAX_FP_ATTEMPTS
- `users.rs` — Aktuellen User via nix getuid, Avatar-Loading mit Symlink-Rejection
- `power.rs` — Reboot/Shutdown via /usr/bin/loginctl
- `i18n.rs` — Locale-Erkennung und String-Tabellen (DE/EN), faillock_warning mit konfigurierbarem max_attempts
- `config.rs` — TOML-Config (background_path, fingerprint_enabled als Option<bool>) + Wallpaper-Fallback
- `lockscreen.rs` — GTK4 UI, PAM-Auth via gio::spawn_blocking, Fingerprint-Indikator, Zeroizing<String> für Passwort, Power-Confirm
- `main.rs` — Entry Point, Panic-Hook, Root-Check, ext-session-lock-v1 (Pflicht in Release), Multi-Monitor
- `power.rs` — Reboot/Shutdown via /usr/bin/systemctl
- `i18n.rs` — Locale-Erkennung (OnceLock-cached) und String-Tabellen (DE/EN), faillock_warning mit konfigurierbarem max_attempts
- `config.rs` — TOML-Config (background_path, background_blur, fingerprint_enabled als Option<bool>) + Wallpaper-Fallback + Symlink-Rejection für background_path + Parse-Error-Logging
- `lockscreen.rs` — GTK4 UI via LockscreenHandles, PAM-Auth via gio::spawn_blocking, FP-Label/Start separat verdrahtet, Zeroizing<String> für Passwort, Power-Confirm, GPU-Blur via GskBlurNode, Blur/Avatar-Cache für Multi-Monitor
- `main.rs` — Entry Point, Panic-Hook (vor Logging), Root-Check, ext-session-lock-v1 (Pflicht in Release), Multi-Monitor mit shared Blur/Avatar-Caches, systemd-Journal-Logging, Debug-Level per `MOONLOCK_DEBUG` Env-Var, async fprintd-Init nach window.present()
## Sicherheit
- ext-session-lock-v1 garantiert: Compositor sperrt alle Surfaces bei lock()
- Release-Build: Ohne ext-session-lock-v1 wird `exit(1)` aufgerufen — kein Fenster-Fallback
- Panic-Hook: Bei Crash wird geloggt, aber NIEMALS unlock() aufgerufen — Screen bleibt schwarz
- PAM-Callback: msg_style-aware (Passwort nur bei PAM_PROMPT_ECHO_OFF), strdup-OOM-sicher
- Passwort: Zeroizing<String> ab GTK-Entry-Extraktion, Zeroizing<Vec<u8>> im PAM-FFI-Layer
- Panic-Hook: Bei Crash wird geloggt, aber NIEMALS unlock() aufgerufen — Screen bleibt schwarz. Hook wird vor Logging installiert.
- PAM-Callback: msg_style-aware (Passwort nur bei PAM_PROMPT_ECHO_OFF), strdup-OOM-sicher, num_msg-Guard gegen negative Werte
- fprintd: D-Bus Signal-Sender wird gegen fprintd's unique bus name validiert (Anti-Spoofing)
- Passwort: Zeroizing<String> ab GTK-Entry-Extraktion, Zeroizing<Vec<u8>> im PAM-FFI-Layer (bekannte Einschränkung: GLib-GString und CString werden nicht gezeroized — inhärente GTK/libc-Limitierung)
- Root-Check: Exit mit Fehler wenn als root gestartet
- Faillock: UI-Warnung nach 3 Fehlversuchen, aber PAM entscheidet über Lockout (Entry bleibt aktiv)
- Kein Schließen per Escape/Alt-F4 — nur durch erfolgreiche PAM-Auth oder Fingerprint
- Kein Peek-Icon am Passwortfeld (Shoulder-Surfing-Schutz)
- GResource-Bundle: CSS/Assets in der Binary kompiliert
Generated
+13 -176
View File
@@ -2,65 +2,6 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "anyhow"
version = "1.0.102"
@@ -124,35 +65,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "env_filter"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"jiff",
"log",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -610,42 +522,12 @@ dependencies = [
"serde_core",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jiff"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359"
dependencies = [
"jiff-static",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
]
[[package]]
name = "jiff-static"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "khronos_api"
version = "3.1.0"
@@ -693,20 +575,21 @@ dependencies = [
[[package]]
name = "moonlock"
version = "0.4.0"
version = "0.6.0"
dependencies = [
"env_logger",
"gdk-pixbuf",
"gdk4",
"gio",
"glib",
"glib-build-tools",
"graphene-rs",
"gtk4",
"gtk4-session-lock",
"libc",
"log",
"nix",
"serde",
"systemd-journal-logger",
"tempfile",
"toml 0.8.23",
"zeroize",
@@ -730,12 +613,6 @@ version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "pango"
version = "0.22.0"
@@ -772,21 +649,6 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "portable-atomic"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]]
name = "portable-atomic-util"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091397be61a01d4be58e7841595bd4bfedb15f1cd54977d79b8271e94ed799a3"
dependencies = [
"portable-atomic",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
@@ -830,35 +692,6 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -984,6 +817,16 @@ dependencies = [
"version-compare",
]
[[package]]
name = "systemd-journal-logger"
version = "2.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7266304d24ca5a4b230545fc558c80e18bd3e1d2eb1be149b6bcd04398d3e79c"
dependencies = [
"log",
"rustix",
]
[[package]]
name = "target-lexicon"
version = "0.13.3"
@@ -1116,12 +959,6 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "version-compare"
version = "0.2.1"
+8 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "moonlock"
version = "0.4.1"
version = "0.6.1"
edition = "2024"
description = "A secure Wayland lockscreen with GTK4, PAM and fingerprint support"
license = "MIT"
@@ -14,14 +14,20 @@ gdk-pixbuf = "0.22"
gio = "0.22"
toml = "0.8"
serde = { version = "1", features = ["derive"] }
graphene-rs = { version = "0.22", package = "graphene-rs" }
nix = { version = "0.29", features = ["user"] }
zeroize = { version = "1", features = ["derive"] }
libc = "0.2"
log = "0.4"
env_logger = "0.11"
systemd-journal-logger = "2.2"
[dev-dependencies]
tempfile = "3"
[build-dependencies]
glib-build-tools = "0.22"
[profile.release]
lto = "thin"
codegen-units = 1
strip = true
+31
View File
@@ -0,0 +1,31 @@
# Decisions
Architectural and design decisions for Moonlock, in reverse chronological order.
## 2026-03-28 Audit-driven security and lifecycle fixes (v0.6.0)
- **Who**: Nyx, Dom
- **Why**: Triple audit (quality, performance, security) revealed a critical D-Bus signal spoofing vector, fingerprint lifecycle bugs, and multi-monitor performance issues.
- **Tradeoffs**: `cleanup_dbus()` extraction adds a method but clarifies the stop/match ownership; `running_flag: Rc<Cell<bool>>` adds a field but prevents race between async restart and stop; sender validation adds a check per signal but closes the only known auth bypass.
- **How**: (1) Validate D-Bus VerifyStatus sender against fprintd's unique bus name. (2) Extract `cleanup_dbus()` from `stop()`, call it on verify-match. (3) `Rc<Cell<bool>>` running flag checked after await in `restart_verify_async`. (4) Consistent 3s D-Bus timeouts. (5) Panic hook before logging. (6) Blur and avatar caches shared across monitors. (7) Peek icon disabled. (8) Symlink rejection for background_path. (9) TOML parse errors logged.
## 2026-03-28 GPU blur via GskBlurNode replaces CPU blur
- **Who**: Nyx, Dom
- **Why**: CPU-side Gaussian blur (`image` crate) blocked the GTK main thread for 500ms2s on 4K wallpapers at cold cache. Disk cache mitigated repeat starts but added ~100 lines of complexity.
- **Tradeoffs**: GPU blur quality is slightly different (box-blur approximation vs true Gaussian), acceptable for wallpaper. Removes `image` and `dirs` dependencies entirely. No disk cache needed.
- **How**: `Snapshot::push_blur()` + `GskRenderer::render_texture()` on `connect_realize`. Blur happens once on the GPU when the widget gets its renderer, producing a concrete `gdk::Texture`. Zero startup latency.
## 2026-03-28 Optional background blur via `image` crate (superseded)
- **Who**: Nyx, Dom
- **Why**: Consistent with moonset/moongreet — blurred wallpaper as lockscreen background is a common UX pattern
- **Tradeoffs**: Adds `image` crate dependency (~15 transitive crates); CPU-side Gaussian blur at load time adds startup latency proportional to image size and sigma. Acceptable because blur runs once and the texture is shared across monitors.
- **How**: `load_background_texture(bg_path, blur_radius)` loads texture, optionally applies `imageops::blur()`, returns `gdk::Texture`. Config option `background_blur: Option<f32>` in TOML.
## 2026-03-28 Shared wallpaper texture pattern (aligned with moonset/moongreet)
- **Who**: Nyx, Dom
- **Why**: Previously loaded wallpaper per-window via `Picture::for_filename()`. Multi-monitor setups decoded the JPEG redundantly. Blur feature requires texture pixel access anyway.
- **Tradeoffs**: Slightly more code in main.rs (texture loaded before window creation), but avoids redundant decoding and enables the blur feature.
- **How**: `load_background_texture()` in lockscreen.rs decodes once, `create_background_picture()` wraps shared `gdk::Texture` in `gtk::Picture`. Same pattern as moonset/moongreet.
+2 -2
View File
@@ -7,8 +7,8 @@ Part of the Moonarch ecosystem.
- **ext-session-lock-v1** — Protocol-guaranteed screen locking (compositor keeps screen locked on crash)
- **PAM authentication** — Uses system PAM stack (`/etc/pam.d/moonlock`)
- **Fingerprint unlock** — fprintd D-Bus integration (optional)
- **Multi-monitor** — Lockscreen on every monitor
- **Fingerprint unlock** — fprintd D-Bus integration, async init (optional, window appears instantly)
- **Multi-monitor** — Lockscreen on every monitor, single shared fingerprint listener
- **i18n** — German and English (auto-detected)
- **Faillock warning** — UI counter + system pam_faillock
- **Panic safety** — Panic hook logs but never unlocks
+2 -1
View File
@@ -4,7 +4,7 @@
# Maintainer: Dominik Kressler
pkgname=moonlock-git
pkgver=0.4.0.r0.g0000000
pkgver=0.4.1.r1.g78bcf90
pkgrel=1
pkgdesc="A secure Wayland lockscreen with GTK4, PAM and fingerprint support"
arch=('x86_64')
@@ -15,6 +15,7 @@ depends=(
'gtk4-layer-shell'
'gtk-session-lock'
'pam'
'systemd-libs'
)
makedepends=(
'git'
+7 -2
View File
@@ -8,6 +8,7 @@ use zeroize::Zeroizing;
// PAM return codes
const PAM_SUCCESS: i32 = 0;
const PAM_BUF_ERR: i32 = 5;
const PAM_AUTH_ERR: i32 = 7;
// PAM message styles
const PAM_PROMPT_ECHO_OFF: libc::c_int = 1;
@@ -70,10 +71,14 @@ unsafe extern "C" fn pam_conv_callback(
appdata_ptr: *mut libc::c_void,
) -> libc::c_int {
unsafe {
if num_msg <= 0 {
return PAM_AUTH_ERR;
}
// Safety: appdata_ptr was set to a valid *const CString in authenticate()
let password = appdata_ptr as *const CString;
if password.is_null() {
return 7; // PAM_AUTH_ERR
return PAM_AUTH_ERR;
}
// Safety: calloc returns zeroed memory for num_msg PamResponse structs.
@@ -84,7 +89,7 @@ unsafe extern "C" fn pam_conv_callback(
) as *mut PamResponse;
if resp_array.is_null() {
return 7; // PAM_AUTH_ERR
return PAM_BUF_ERR;
}
for i in 0..num_msg as isize {
+44 -7
View File
@@ -21,6 +21,7 @@ fn default_config_paths() -> Vec<PathBuf> {
#[derive(Debug, Clone, Default, Deserialize)]
struct RawConfig {
pub background_path: Option<String>,
pub background_blur: Option<f32>,
pub fingerprint_enabled: Option<bool>,
}
@@ -28,6 +29,7 @@ struct RawConfig {
#[derive(Debug, Clone)]
pub struct Config {
pub background_path: Option<String>,
pub background_blur: Option<f32>,
pub fingerprint_enabled: bool,
}
@@ -35,6 +37,7 @@ impl Default for Config {
fn default() -> Self {
Config {
background_path: None,
background_blur: None,
fingerprint_enabled: true,
}
}
@@ -46,9 +49,15 @@ pub fn load_config(config_paths: Option<&[PathBuf]>) -> Config {
let mut merged = Config::default();
for path in paths {
if let Ok(content) = fs::read_to_string(path) {
if let Ok(parsed) = toml::from_str::<RawConfig>(&content) {
if parsed.background_path.is_some() { merged.background_path = parsed.background_path; }
if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; }
match toml::from_str::<RawConfig>(&content) {
Ok(parsed) => {
if parsed.background_path.is_some() { merged.background_path = parsed.background_path; }
if parsed.background_blur.is_some() { merged.background_blur = parsed.background_blur; }
if let Some(fp) = parsed.fingerprint_enabled { merged.fingerprint_enabled = fp; }
}
Err(e) => {
log::warn!("Failed to parse {}: {e}", path.display());
}
}
}
}
@@ -62,7 +71,7 @@ pub fn resolve_background_path(config: &Config) -> PathBuf {
pub fn resolve_background_path_with(config: &Config, moonarch_wallpaper: &Path) -> PathBuf {
if let Some(ref bg) = config.background_path {
let path = PathBuf::from(bg);
if path.is_file() { return path; }
if path.is_file() && !path.is_symlink() { return path; }
}
if moonarch_wallpaper.is_file() { return moonarch_wallpaper.to_path_buf(); }
PathBuf::from(format!("{GRESOURCE_PREFIX}/wallpaper.jpg"))
@@ -72,7 +81,7 @@ pub fn resolve_background_path_with(config: &Config, moonarch_wallpaper: &Path)
mod tests {
use super::*;
#[test] fn default_config() { let c = Config::default(); assert!(c.background_path.is_none()); assert!(c.fingerprint_enabled); }
#[test] fn default_config() { let c = Config::default(); assert!(c.background_path.is_none()); assert!(c.background_blur.is_none()); assert!(c.fingerprint_enabled); }
#[test] fn load_default_fingerprint_true() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml");
@@ -83,15 +92,23 @@ mod tests {
#[test] fn load_background() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml");
fs::write(&conf, "background_path = \"/custom/bg.jpg\"\nfingerprint_enabled = false\n").unwrap();
fs::write(&conf, "background_path = \"/custom/bg.jpg\"\nbackground_blur = 15.0\nfingerprint_enabled = false\n").unwrap();
let c = load_config(Some(&[conf]));
assert_eq!(c.background_path.as_deref(), Some("/custom/bg.jpg"));
assert_eq!(c.background_blur, Some(15.0));
assert!(!c.fingerprint_enabled);
}
#[test] fn load_blur_optional() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml");
fs::write(&conf, "background_path = \"/bg.jpg\"\n").unwrap();
let c = load_config(Some(&[conf]));
assert!(c.background_blur.is_none());
}
#[test] fn resolve_config_path() {
let dir = tempfile::tempdir().unwrap();
let wp = dir.path().join("bg.jpg"); fs::write(&wp, "fake").unwrap();
let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), fingerprint_enabled: true };
let c = Config { background_path: Some(wp.to_str().unwrap().to_string()), ..Config::default() };
assert_eq!(resolve_background_path_with(&c, Path::new("/nonexistent")), wp);
}
#[test] fn empty_user_config_preserves_system_fingerprint() {
@@ -108,4 +125,24 @@ mod tests {
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
assert!(r.to_str().unwrap().contains("moonlock"));
}
#[test] fn toml_parse_error_returns_default() {
let dir = tempfile::tempdir().unwrap();
let conf = dir.path().join("moonlock.toml");
fs::write(&conf, "this is not valid toml {{{{").unwrap();
let c = load_config(Some(&[conf]));
assert!(c.fingerprint_enabled);
assert!(c.background_path.is_none());
}
#[cfg(unix)]
#[test] fn symlink_rejected_for_background() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("bg.jpg");
let link = dir.path().join("link.jpg");
fs::write(&real, "fake").unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();
let c = Config { background_path: Some(link.to_str().unwrap().to_string()), ..Config::default() };
// Symlink should be rejected — falls through to moonarch wallpaper or gresource
let r = resolve_background_path_with(&c, Path::new("/nonexistent"));
assert_ne!(r, link);
}
}
+186 -100
View File
@@ -3,7 +3,7 @@
use gio::prelude::*;
use gtk4::gio;
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const FPRINTD_BUS_NAME: &str = "net.reactivated.Fprint";
@@ -12,6 +12,7 @@ const FPRINTD_MANAGER_IFACE: &str = "net.reactivated.Fprint.Manager";
const FPRINTD_DEVICE_IFACE: &str = "net.reactivated.Fprint.Device";
const MAX_FP_ATTEMPTS: u32 = 10;
const DBUS_TIMEOUT_MS: i32 = 3000;
/// Retry-able statuses — finger not read properly, try again.
const RETRY_STATUSES: &[&str] = &[
@@ -26,38 +27,42 @@ pub struct FingerprintListener {
device_proxy: Option<gio::DBusProxy>,
signal_id: Option<glib::SignalHandlerId>,
running: bool,
/// Shared flag for async tasks to detect stop() between awaits.
running_flag: Rc<Cell<bool>>,
failed_attempts: u32,
on_success: Option<Box<dyn Fn() + 'static>>,
on_failure: Option<Box<dyn Fn() + 'static>>,
on_exhausted: Option<Box<dyn Fn() + 'static>>,
}
impl FingerprintListener {
/// Create a new FingerprintListener.
/// Connects to fprintd synchronously — call before creating GTK windows.
/// Create a lightweight FingerprintListener without any D-Bus calls.
/// Call `init_async().await` afterwards to connect to fprintd.
pub fn new() -> Self {
let mut listener = FingerprintListener {
FingerprintListener {
device_proxy: None,
signal_id: None,
running: false,
running_flag: Rc::new(Cell::new(false)),
failed_attempts: 0,
on_success: None,
on_failure: None,
};
listener.init_device();
listener
on_exhausted: None,
}
}
/// Connect to fprintd and get the default device.
fn init_device(&mut self) {
let manager = match gio::DBusProxy::for_bus_sync(
/// Connect to fprintd and get the default device asynchronously.
pub async fn init_async(&mut self) {
let manager = match gio::DBusProxy::for_bus_future(
gio::BusType::System,
gio::DBusProxyFlags::NONE,
None,
FPRINTD_BUS_NAME,
FPRINTD_MANAGER_PATH,
FPRINTD_MANAGER_IFACE,
gio::Cancellable::NONE,
) {
)
.await
{
Ok(m) => m,
Err(e) => {
log::debug!("fprintd manager not available: {e}");
@@ -66,13 +71,10 @@ impl FingerprintListener {
};
// Call GetDefaultDevice
let result = match manager.call_sync(
"GetDefaultDevice",
None,
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
) {
let result = match manager
.call_future("GetDefaultDevice", None, gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await
{
Ok(r) => r,
Err(e) => {
log::debug!("fprintd GetDefaultDevice failed: {e}");
@@ -81,20 +83,27 @@ impl FingerprintListener {
};
// Extract device path from variant tuple
let device_path: String = result.child_get::<String>(0);
let device_path = match result.child_value(0).get::<String>() {
Some(p) => p,
None => {
log::debug!("fprintd: unexpected GetDefaultDevice response type");
return;
}
};
if device_path.is_empty() {
return;
}
match gio::DBusProxy::for_bus_sync(
match gio::DBusProxy::for_bus_future(
gio::BusType::System,
gio::DBusProxyFlags::NONE,
None,
FPRINTD_BUS_NAME,
&device_path,
FPRINTD_DEVICE_IFACE,
gio::Cancellable::NONE,
) {
)
.await
{
Ok(proxy) => {
self.device_proxy = Some(proxy);
}
@@ -104,41 +113,46 @@ impl FingerprintListener {
}
}
/// Check if fprintd is available and the user has enrolled fingerprints.
pub fn is_available(&self, username: &str) -> bool {
/// Check if fprintd is available and the user has enrolled fingerprints (async).
pub async fn is_available_async(&self, username: &str) -> bool {
let proxy = match &self.device_proxy {
Some(p) => p,
None => return false,
};
let args = glib::Variant::from((&username,));
match proxy.call_sync(
"ListEnrolledFingers",
Some(&args),
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
) {
match proxy
.call_future("ListEnrolledFingers", Some(&args), gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await
{
Ok(result) => {
// Result is a tuple of (array of strings)
let fingers: Vec<String> = result.child_get::<Vec<String>>(0);
!fingers.is_empty()
match result.child_value(0).get::<Vec<String>>() {
Some(fingers) => !fingers.is_empty(),
None => {
log::debug!("fprintd: unexpected ListEnrolledFingers response type");
false
}
}
}
Err(_) => false,
}
}
/// Start listening for fingerprint verification.
/// Claims the device and starts verification using async D-Bus calls.
/// Connects the D-Bus g-signal handler internally. The `listener` parameter
/// must be the same `Rc<RefCell<FingerprintListener>>` that owns `self`.
pub fn start<F, G>(
pub async fn start_async<F, G, H>(
listener: &Rc<RefCell<FingerprintListener>>,
username: &str,
on_success: F,
on_failure: G,
on_exhausted: H,
) where
F: Fn() + 'static,
G: Fn() + 'static,
H: Fn() + 'static,
{
let proxy = {
let inner = listener.borrow();
@@ -152,45 +166,50 @@ impl FingerprintListener {
let mut inner = listener.borrow_mut();
inner.on_success = Some(Box::new(on_success));
inner.on_failure = Some(Box::new(on_failure));
inner.on_exhausted = Some(Box::new(on_exhausted));
}
// Claim the device
let args = glib::Variant::from((&username,));
if let Err(e) = proxy.call_sync(
"Claim",
Some(&args),
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
) {
if let Err(e) = proxy
.call_future("Claim", Some(&args), gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await
{
log::error!("Failed to claim fingerprint device: {e}");
return;
}
// Start verification
let start_args = glib::Variant::from((&"any",));
if let Err(e) = proxy.call_sync(
"VerifyStart",
Some(&start_args),
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
) {
if let Err(e) = proxy
.call_future("VerifyStart", Some(&start_args), gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await
{
log::error!("Failed to start fingerprint verification: {e}");
let _ = proxy.call_sync(
"Release",
None,
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
);
let _ = proxy
.call_future("Release", None, gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await;
return;
}
// Capture the unique bus name of fprintd for sender validation.
// D-Bus signals carry the sender's unique name (e.g. ":1.42"), not the
// well-known name. We validate this to prevent signal spoofing.
let expected_sender = proxy.name_owner();
// Connect the g-signal handler on the proxy to dispatch VerifyStatus
let listener_weak = Rc::downgrade(listener);
let signal_id = proxy.connect_local("g-signal", false, move |values| {
// g-signal arguments: (proxy, sender_name, signal_name, parameters)
let sender: String = match values[1].get() {
Ok(s) => s,
Err(_) => return None,
};
if expected_sender.as_ref().map(|s| s.as_str()) != Some(sender.as_str()) {
log::warn!("Ignoring D-Bus signal from unexpected sender: {sender}");
return None;
}
let signal_name: String = match values[2].get() {
Ok(v) => v,
Err(_) => return None,
@@ -223,6 +242,7 @@ impl FingerprintListener {
let mut inner = listener.borrow_mut();
inner.signal_id = Some(signal_id);
inner.running = true;
inner.running_flag.set(true);
}
/// Process a VerifyStatus signal from fprintd.
@@ -232,6 +252,7 @@ impl FingerprintListener {
}
if status == "verify-match" {
self.cleanup_dbus();
if let Some(ref cb) = self.on_success {
cb();
}
@@ -240,23 +261,26 @@ impl FingerprintListener {
if RETRY_STATUSES.contains(&status) {
if done {
self.restart_verify();
self.restart_verify_async();
}
return;
}
if status == "verify-no-match" {
self.failed_attempts += 1;
if let Some(ref cb) = self.on_failure {
cb();
}
if self.failed_attempts >= MAX_FP_ATTEMPTS {
log::warn!("Fingerprint max attempts ({MAX_FP_ATTEMPTS}) reached, stopping");
if let Some(ref cb) = self.on_exhausted {
cb();
}
self.stop();
return;
}
if let Some(ref cb) = self.on_failure {
cb();
}
if done {
self.restart_verify();
self.restart_verify_async();
}
return;
}
@@ -264,58 +288,62 @@ impl FingerprintListener {
log::debug!("Unhandled fprintd status: {status}");
}
/// Restart fingerprint verification after a completed attempt.
fn restart_verify(&self) {
/// Restart fingerprint verification asynchronously after a completed attempt.
/// Checks running_flag after VerifyStop to avoid restarting on a released device.
fn restart_verify_async(&self) {
if let Some(ref proxy) = self.device_proxy {
// VerifyStop before VerifyStart to avoid D-Bus errors
let _ = proxy.call_sync(
"VerifyStop",
None,
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
);
let args = glib::Variant::from((&"any",));
if let Err(e) = proxy.call_sync(
"VerifyStart",
Some(&args),
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
) {
log::error!("Failed to restart fingerprint verification: {e}");
}
let proxy = proxy.clone();
let running = self.running_flag.clone();
glib::spawn_future_local(async move {
// VerifyStop before VerifyStart to avoid D-Bus errors
let _ = proxy
.call_future("VerifyStop", None, gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await;
if !running.get() {
return;
}
let args = glib::Variant::from((&"any",));
if let Err(e) = proxy
.call_future("VerifyStart", Some(&args), gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await
{
log::error!("Failed to restart fingerprint verification: {e}");
}
});
}
}
/// Stop listening and release the device.
pub fn stop(&mut self) {
if !self.running {
return;
}
/// Disconnect the signal handler and send VerifyStop + Release to fprintd.
/// Signal disconnect is synchronous to prevent further callbacks.
/// D-Bus cleanup is fire-and-forget to avoid blocking the UI.
fn cleanup_dbus(&mut self) {
self.running = false;
self.running_flag.set(false);
if let Some(ref proxy) = self.device_proxy {
if let Some(id) = self.signal_id.take() {
proxy.disconnect(id);
}
let _ = proxy.call_sync(
"VerifyStop",
None,
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
);
let _ = proxy.call_sync(
"Release",
None,
gio::DBusCallFlags::NONE,
-1,
gio::Cancellable::NONE,
);
let proxy = proxy.clone();
glib::spawn_future_local(async move {
let _ = proxy
.call_future("VerifyStop", None, gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await;
let _ = proxy
.call_future("Release", None, gio::DBusCallFlags::NONE, DBUS_TIMEOUT_MS)
.await;
});
}
}
/// Stop listening and release the device. Idempotent — safe to call multiple times.
pub fn stop(&mut self) {
if !self.running {
return;
}
self.cleanup_dbus();
}
}
#[cfg(test)]
@@ -334,4 +362,62 @@ mod tests {
fn max_attempts_constant() {
assert_eq!(MAX_FP_ATTEMPTS, 10);
}
#[test]
fn verify_match_sets_running_false_and_calls_success() {
let called = Rc::new(Cell::new(false));
let called_clone = called.clone();
let mut listener = FingerprintListener::new();
listener.running = true;
listener.running_flag.set(true);
listener.on_success = Some(Box::new(move || { called_clone.set(true); }));
listener.on_verify_status("verify-match", false);
assert!(called.get());
assert!(!listener.running);
assert!(!listener.running_flag.get());
}
#[test]
fn verify_no_match_calls_failure_and_stays_running() {
let called = Rc::new(Cell::new(false));
let called_clone = called.clone();
let mut listener = FingerprintListener::new();
listener.running = true;
listener.on_failure = Some(Box::new(move || { called_clone.set(true); }));
listener.on_verify_status("verify-no-match", false);
assert!(called.get());
assert!(listener.running);
assert_eq!(listener.failed_attempts, 1);
}
#[test]
fn max_attempts_stops_listener_and_calls_exhausted() {
let exhausted = Rc::new(Cell::new(false));
let exhausted_clone = exhausted.clone();
let mut listener = FingerprintListener::new();
listener.running = true;
listener.on_failure = Some(Box::new(|| {}));
listener.on_exhausted = Some(Box::new(move || { exhausted_clone.set(true); }));
for _ in 0..MAX_FP_ATTEMPTS {
listener.on_verify_status("verify-no-match", true);
}
assert!(!listener.running);
assert!(exhausted.get());
assert_eq!(listener.failed_attempts, MAX_FP_ATTEMPTS);
}
#[test]
fn not_running_ignores_signals() {
let called = Rc::new(Cell::new(false));
let called_clone = called.clone();
let mut listener = FingerprintListener::new();
listener.running = false;
listener.on_success = Some(Box::new(move || { called_clone.set(true); }));
listener.on_verify_status("verify-match", false);
assert!(!called.get());
}
}
+9 -2
View File
@@ -4,9 +4,13 @@
use std::env;
use std::fs;
use std::path::Path;
use std::sync::OnceLock;
const DEFAULT_LOCALE_CONF: &str = "/etc/locale.conf";
/// Cached locale prefix — detected once, reused for all subsequent calls.
static CACHED_LOCALE: OnceLock<String> = OnceLock::new();
#[derive(Debug, Clone)]
pub struct Strings {
pub password_placeholder: &'static str,
@@ -86,8 +90,11 @@ pub fn detect_locale() -> String {
}
pub fn load_strings(locale: Option<&str>) -> &'static Strings {
let locale = match locale { Some(l) => l.to_string(), None => detect_locale() };
match locale.as_str() { "de" => &STRINGS_DE, _ => &STRINGS_EN }
let locale = match locale {
Some(l) => l,
None => CACHED_LOCALE.get_or_init(detect_locale),
};
match locale { "de" => &STRINGS_DE, _ => &STRINGS_EN }
}
pub fn faillock_warning(attempt_count: u32, max_attempts: u32, strings: &Strings) -> Option<String> {
+219 -90
View File
@@ -4,6 +4,7 @@
use gdk4 as gdk;
use gdk_pixbuf::Pixbuf;
use glib::clone;
use graphene_rs as graphene;
use gtk4::prelude::*;
use gtk4::{self as gtk, gio};
use std::cell::RefCell;
@@ -19,23 +20,37 @@ use crate::i18n::{faillock_warning, load_strings, Strings};
use crate::power::{self, PowerError};
use crate::users;
/// Handles returned from create_lockscreen_window for post-creation wiring.
pub struct LockscreenHandles {
pub window: gtk::ApplicationWindow,
pub fp_label: gtk::Label,
pub password_entry: gtk::PasswordEntry,
pub unlock_callback: Rc<dyn Fn()>,
pub username: String,
state: Rc<RefCell<LockscreenState>>,
}
const AVATAR_SIZE: i32 = 128;
const FAILLOCK_MAX_ATTEMPTS: u32 = 3;
/// Shared mutable state for the lockscreen.
struct LockscreenState {
failed_attempts: u32,
fp_listener: FingerprintListener,
fp_listener_rc: Option<Rc<RefCell<FingerprintListener>>>,
}
/// Create a lockscreen window for a single monitor.
/// Fingerprint is not initialized here — use `wire_fingerprint()` after async init.
/// The `blur_cache` and `avatar_cache` are shared across monitors for multi-monitor
/// setups, avoiding redundant GPU renders and SVG rasterizations.
pub fn create_lockscreen_window(
bg_path: &Path,
bg_texture: &gdk::Texture,
config: &Config,
app: &gtk::Application,
unlock_callback: Rc<dyn Fn()>,
) -> gtk::ApplicationWindow {
blur_cache: &Rc<RefCell<Option<gdk::Texture>>>,
avatar_cache: &Rc<RefCell<Option<gdk::Texture>>>,
) -> LockscreenHandles {
let window = gtk::ApplicationWindow::builder()
.application(app)
.build();
@@ -46,17 +61,24 @@ pub fn create_lockscreen_window(
Some(u) => u,
None => {
log::error!("Failed to get current user");
return window;
let fp_label = gtk::Label::new(None);
fp_label.set_visible(false);
return LockscreenHandles {
window,
fp_label,
password_entry: gtk::PasswordEntry::new(),
unlock_callback,
username: String::new(),
state: Rc::new(RefCell::new(LockscreenState {
failed_attempts: 0,
fp_listener_rc: None,
})),
};
}
};
let fp_listener = FingerprintListener::new();
let fp_available = config.fingerprint_enabled
&& fp_listener.is_available(&user.username);
let state = Rc::new(RefCell::new(LockscreenState {
failed_attempts: 0,
fp_listener,
fp_listener_rc: None,
}));
@@ -65,7 +87,7 @@ pub fn create_lockscreen_window(
window.set_child(Some(&overlay));
// Background wallpaper
let background = create_background_picture(bg_path);
let background = create_background_picture(bg_texture, config.background_blur, blur_cache);
overlay.set_child(Some(&background));
// Centered vertical box
@@ -91,12 +113,17 @@ pub fn create_lockscreen_window(
avatar_frame.append(&avatar_image);
login_box.append(&avatar_frame);
// Load avatar
let avatar_path = users::get_avatar_path(&user.home, &user.username);
if let Some(path) = avatar_path {
set_avatar_from_file(&avatar_image, &path);
// Load avatar — use shared cache to avoid redundant loading on multi-monitor setups.
// The cache is populated by the first monitor and reused by subsequent ones.
if let Some(ref cached) = *avatar_cache.borrow() {
avatar_image.set_paintable(Some(cached));
} else {
set_default_avatar(&avatar_image, &window);
let avatar_path = users::get_avatar_path(&user.home, &user.username);
if let Some(path) = avatar_path {
set_avatar_from_file(&avatar_image, &path, avatar_cache);
} else {
set_default_avatar(&avatar_image, &window, avatar_cache);
}
}
// Username label
@@ -107,7 +134,7 @@ pub fn create_lockscreen_window(
// Password entry
let password_entry = gtk::PasswordEntry::builder()
.placeholder_text(strings.password_placeholder)
.show_peek_icon(true)
.show_peek_icon(false)
.hexpand(true)
.build();
password_entry.add_css_class("password-entry");
@@ -119,15 +146,10 @@ pub fn create_lockscreen_window(
error_label.set_visible(false);
login_box.append(&error_label);
// Fingerprint label
// Fingerprint label — hidden until async fprintd init completes
let fp_label = gtk::Label::new(None);
fp_label.add_css_class("fingerprint-label");
if fp_available {
fp_label.set_text(strings.fingerprint_prompt);
fp_label.set_visible(true);
} else {
fp_label.set_visible(false);
}
fp_label.set_visible(false);
login_box.append(&fp_label);
// Confirm box area (for power confirm)
@@ -227,9 +249,8 @@ pub fn create_lockscreen_window(
password_entry,
async move {
let user = username.clone();
let pass = Zeroizing::new((*password).clone());
let result = gio::spawn_blocking(move || {
auth::authenticate(&user, &pass)
auth::authenticate(&user, &password)
}).await;
match result {
@@ -293,61 +314,6 @@ pub fn create_lockscreen_window(
));
window.add_controller(key_controller);
// Start fingerprint listener
if fp_available {
let unlock_cb_fp = unlock_callback.clone();
let fp_label_success = fp_label.clone();
let fp_label_fail = fp_label.clone();
let on_success = move || {
let label = fp_label_success.clone();
let cb = unlock_cb_fp.clone();
glib::idle_add_local_once(move || {
label.set_text(load_strings(None).fingerprint_success);
label.add_css_class("success");
cb();
});
};
let on_failure = move || {
let label = fp_label_fail.clone();
glib::idle_add_local_once(clone!(
#[weak]
label,
move || {
let strings = load_strings(None);
label.set_text(strings.fingerprint_failed);
label.add_css_class("failed");
// Reset after 2 seconds
glib::timeout_add_local_once(
std::time::Duration::from_secs(2),
clone!(
#[weak]
label,
move || {
label.set_text(load_strings(None).fingerprint_prompt);
label.remove_css_class("success");
label.remove_css_class("failed");
}
),
);
}
));
};
// Extract the fp_listener into its own Rc<RefCell<>> for signal self-wiring
let fp_rc = {
let mut s = state.borrow_mut();
let listener = std::mem::replace(&mut s.fp_listener, FingerprintListener::new());
Rc::new(RefCell::new(listener))
};
FingerprintListener::start(&fp_rc, &user.username, on_success, on_failure);
// Store back the Rc reference for stop() on unlock
state.borrow_mut().fp_listener_rc = Some(fp_rc);
}
// Fade-in on map
window.connect_map(|w| {
glib::idle_add_local_once(clone!(
@@ -370,28 +336,185 @@ pub fn create_lockscreen_window(
}
));
window
LockscreenHandles {
window,
fp_label,
password_entry: password_entry.clone(),
unlock_callback,
username: user.username,
state: state.clone(),
}
}
/// Show the fingerprint label and store the listener reference for stop-on-unlock.
/// Does NOT start verification — call `start_fingerprint()` on one monitor for that.
pub fn show_fingerprint_label(
handles: &LockscreenHandles,
fp_rc: &Rc<RefCell<FingerprintListener>>,
) {
let strings = load_strings(None);
handles.fp_label.set_text(strings.fingerprint_prompt);
handles.fp_label.set_visible(true);
// Store the Rc reference for stop() on unlock
handles.state.borrow_mut().fp_listener_rc = Some(fp_rc.clone());
}
/// Start fingerprint verification on a single monitor's handles.
/// Wires up on_success/on_failure callbacks and calls start_async.
pub fn start_fingerprint(
handles: &LockscreenHandles,
fp_rc: &Rc<RefCell<FingerprintListener>>,
) {
let fp_label_success = handles.fp_label.clone();
let fp_label_fail = handles.fp_label.clone();
let unlock_cb_fp = handles.unlock_callback.clone();
let fp_rc_success = fp_rc.clone();
let on_success = move || {
let label = fp_label_success.clone();
let cb = unlock_cb_fp.clone();
let fp = fp_rc_success.clone();
glib::idle_add_local_once(move || {
let strings = load_strings(None);
label.set_text(strings.fingerprint_success);
label.add_css_class("success");
// stop() is idempotent — cleanup_dbus() already ran inside on_verify_status,
// but this mirrors the PAM success path for defense-in-depth.
fp.borrow_mut().stop();
cb();
});
};
let on_failure = move || {
let label = fp_label_fail.clone();
glib::idle_add_local_once(clone!(
#[weak]
label,
move || {
let strings = load_strings(None);
label.set_text(strings.fingerprint_failed);
label.add_css_class("failed");
// Reset after 2 seconds
glib::timeout_add_local_once(
std::time::Duration::from_secs(2),
clone!(
#[weak]
label,
move || {
label.set_text(load_strings(None).fingerprint_prompt);
label.remove_css_class("success");
label.remove_css_class("failed");
}
),
);
}
));
};
let fp_label_exhausted = handles.fp_label.clone();
let on_exhausted = move || {
let label = fp_label_exhausted.clone();
glib::idle_add_local_once(move || {
label.set_visible(false);
});
};
let username = handles.username.clone();
let fp_rc_clone = fp_rc.clone();
glib::spawn_future_local(async move {
FingerprintListener::start_async(
&fp_rc_clone, &username, on_success, on_failure, on_exhausted,
).await;
});
}
/// Load the wallpaper as a texture once, for sharing across all windows.
/// Blur is applied at render time via GPU (GskBlurNode), not here.
pub fn load_background_texture(bg_path: &Path) -> gdk::Texture {
let fallback = "/dev/moonarch/moonlock/wallpaper.jpg";
if bg_path.starts_with("/dev/moonarch/moonlock") {
let resource_path = bg_path.to_str().unwrap_or(fallback);
gdk::Texture::from_resource(resource_path)
} else {
let file = gio::File::for_path(bg_path);
gdk::Texture::from_file(&file).unwrap_or_else(|_| {
gdk::Texture::from_resource(fallback)
})
}
}
/// Create a Picture widget for the wallpaper background.
fn create_background_picture(bg_path: &Path) -> gtk::Picture {
let background = if bg_path.starts_with("/dev/moonarch/moonlock") {
gtk::Picture::for_resource(bg_path.to_str().unwrap_or(""))
} else {
gtk::Picture::for_filename(bg_path.to_str().unwrap_or(""))
};
/// When `blur_radius` is `Some(sigma)` with sigma > 0, blur is applied via GPU
/// (GskBlurNode). The blur is rendered to a concrete texture on `realize` (when
/// the GPU renderer is available), avoiding lazy-render artifacts.
/// The `blur_cache` is shared across monitors — the first to realize renders the
/// blur, subsequent monitors reuse the cached texture.
fn create_background_picture(
texture: &gdk::Texture,
blur_radius: Option<f32>,
blur_cache: &Rc<RefCell<Option<gdk::Texture>>>,
) -> gtk::Picture {
let background = gtk::Picture::for_paintable(texture);
background.set_content_fit(gtk::ContentFit::Cover);
background.set_hexpand(true);
background.set_vexpand(true);
if let Some(sigma) = blur_radius {
if sigma > 0.0 {
let texture = texture.clone();
let cache = blur_cache.clone();
background.connect_realize(move |picture| {
if let Some(ref cached) = *cache.borrow() {
picture.set_paintable(Some(cached));
return;
}
if let Some(blurred) = render_blurred_texture(picture, &texture, sigma) {
picture.set_paintable(Some(&blurred));
*cache.borrow_mut() = Some(blurred);
}
});
}
}
background
}
/// Load an image file and set it as the avatar.
fn set_avatar_from_file(image: &gtk::Image, path: &Path) {
/// Render a blurred texture using the widget's GPU renderer.
/// Returns None if the renderer is not available.
fn render_blurred_texture(
widget: &impl IsA<gtk::Widget>,
texture: &gdk::Texture,
sigma: f32,
) -> Option<gdk::Texture> {
let native = widget.native()?;
let renderer = native.renderer()?;
let snapshot = gtk::Snapshot::new();
let bounds = graphene::Rect::new(
0.0,
0.0,
texture.width() as f32,
texture.height() as f32,
);
snapshot.push_blur(sigma as f64);
snapshot.append_texture(texture, &bounds);
snapshot.pop();
let node = snapshot.to_node()?;
Some(renderer.render_texture(&node, None))
}
/// Load an image file and set it as the avatar. Stores the texture in the cache.
fn set_avatar_from_file(
image: &gtk::Image,
path: &Path,
cache: &Rc<RefCell<Option<gdk::Texture>>>,
) {
match Pixbuf::from_file_at_scale(path.to_str().unwrap_or(""), AVATAR_SIZE, AVATAR_SIZE, true) {
Ok(pixbuf) => {
let texture = gdk::Texture::for_pixbuf(&pixbuf);
image.set_paintable(Some(&texture));
*cache.borrow_mut() = Some(texture);
}
Err(_) => {
image.set_icon_name(Some("avatar-default-symbolic"));
@@ -400,7 +523,12 @@ fn set_avatar_from_file(image: &gtk::Image, path: &Path) {
}
/// Load the default avatar SVG from GResources, tinted with the foreground color.
fn set_default_avatar(image: &gtk::Image, window: &gtk::ApplicationWindow) {
/// Stores the texture in the cache for reuse on additional monitors.
fn set_default_avatar(
image: &gtk::Image,
window: &gtk::ApplicationWindow,
cache: &Rc<RefCell<Option<gdk::Texture>>>,
) {
let resource_path = users::get_default_avatar_path();
if let Ok(bytes) =
gio::resources_lookup_data(&resource_path, gio::ResourceLookupFlags::NONE)
@@ -422,6 +550,7 @@ fn set_default_avatar(image: &gtk::Image, window: &gtk::ApplicationWindow) {
if let Some(pixbuf) = loader.pixbuf() {
let texture = gdk::Texture::for_pixbuf(&pixbuf);
image.set_paintable(Some(&texture));
*cache.borrow_mut() = Some(texture);
return;
}
}
+95 -30
View File
@@ -13,9 +13,11 @@ use gdk4 as gdk;
use gtk4::prelude::*;
use gtk4::{self as gtk, gio};
use gtk4_session_lock;
use std::path::PathBuf;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use crate::fingerprint::FingerprintListener;
fn load_css(display: &gdk::Display) {
let css_provider = gtk::CssProvider::new();
css_provider.load_from_resource("/dev/moonarch/moonlock/style.css");
@@ -39,14 +41,15 @@ fn activate(app: &gtk::Application) {
let config = config::load_config(None);
let bg_path = config::resolve_background_path(&config);
let bg_texture = lockscreen::load_background_texture(&bg_path);
if gtk4_session_lock::is_supported() {
activate_with_session_lock(app, &display, &bg_path, &config);
activate_with_session_lock(app, &display, &bg_texture, &config);
} else {
#[cfg(debug_assertions)]
{
log::warn!("ext-session-lock-v1 not supported — running in development mode");
activate_without_lock(app, &bg_path, &config);
activate_without_lock(app, &bg_texture, &config);
}
#[cfg(not(debug_assertions))]
{
@@ -59,7 +62,7 @@ fn activate(app: &gtk::Application) {
fn activate_with_session_lock(
app: &gtk::Application,
display: &gdk::Display,
bg_path: &PathBuf,
bg_texture: &gdk::Texture,
config: &config::Config,
) {
let lock = gtk4_session_lock::Instance::new();
@@ -67,41 +70,95 @@ fn activate_with_session_lock(
let monitors = display.monitors();
// Shared unlock callback — unlocks session and quits
// Shared unlock callback — unlocks session and quits.
// Guard prevents double-unlock if PAM and fingerprint succeed simultaneously.
let lock_clone = lock.clone();
let app_clone = app.clone();
let already_unlocked = Rc::new(Cell::new(false));
let au = already_unlocked.clone();
let unlock_callback: Rc<dyn Fn()> = Rc::new(move || {
if au.get() {
log::debug!("Unlock already triggered, ignoring duplicate");
return;
}
au.set(true);
lock_clone.unlock();
app_clone.quit();
});
// Shared caches for multi-monitor — first monitor renders, rest reuse
let blur_cache: Rc<RefCell<Option<gdk::Texture>>> = Rc::new(RefCell::new(None));
let avatar_cache: Rc<RefCell<Option<gdk::Texture>>> = Rc::new(RefCell::new(None));
// Create all monitor windows immediately — no D-Bus calls here
let mut all_handles = Vec::new();
let mut created_any = false;
for i in 0..monitors.n_items() {
if let Some(monitor) = monitors
.item(i)
.and_then(|obj| obj.downcast::<gdk::Monitor>().ok())
{
let window = lockscreen::create_lockscreen_window(
bg_path,
let handles = lockscreen::create_lockscreen_window(
bg_texture,
config,
app,
unlock_callback.clone(),
&blur_cache,
&avatar_cache,
);
lock.assign_window_to_monitor(&window, &monitor);
window.present();
lock.assign_window_to_monitor(&handles.window, &monitor);
handles.window.present();
all_handles.push(handles);
created_any = true;
}
}
if !created_any {
log::error!("No lockscreen windows created — screen stays locked (compositor policy)");
return;
}
// Async fprintd initialization — runs after windows are visible
if config.fingerprint_enabled {
init_fingerprint_async(all_handles);
}
}
/// Initialize fprintd asynchronously after windows are visible.
/// Uses a single FingerprintListener shared across all monitors —
/// only the first monitor's handles get the fingerprint UI wired up.
fn init_fingerprint_async(all_handles: Vec<lockscreen::LockscreenHandles>) {
glib::spawn_future_local(async move {
let mut listener = FingerprintListener::new();
listener.init_async().await;
// Use the first monitor's username to check enrollment
let username = &all_handles[0].username;
if username.is_empty() {
return;
}
if !listener.is_available_async(username).await {
log::debug!("fprintd not available or no enrolled fingers");
return;
}
let fp_rc = Rc::new(RefCell::new(listener));
// Show fingerprint label on all monitors
for handles in &all_handles {
lockscreen::show_fingerprint_label(handles, &fp_rc);
}
// Start verification listener on the first monitor only
lockscreen::start_fingerprint(&all_handles[0], &fp_rc);
});
}
#[cfg(debug_assertions)]
fn activate_without_lock(
app: &gtk::Application,
bg_path: &PathBuf,
bg_texture: &gdk::Texture,
config: &config::Config,
) {
let app_clone = app.clone();
@@ -109,33 +166,42 @@ fn activate_without_lock(
app_clone.quit();
});
let window = lockscreen::create_lockscreen_window(
bg_path,
let blur_cache = Rc::new(RefCell::new(None));
let avatar_cache = Rc::new(RefCell::new(None));
let handles = lockscreen::create_lockscreen_window(
bg_texture,
config,
app,
unlock_callback,
&blur_cache,
&avatar_cache,
);
window.set_default_size(800, 600);
window.present();
handles.window.set_default_size(800, 600);
handles.window.present();
// Async fprintd initialization for development mode
if config.fingerprint_enabled {
init_fingerprint_async(vec![handles]);
}
}
fn setup_logging() {
let mut builder = env_logger::Builder::from_default_env();
builder.filter_level(log::LevelFilter::Info);
let log_dir = PathBuf::from("/var/cache/moonlock");
if log_dir.is_dir() {
let log_file = log_dir.join("moonlock.log");
if let Ok(file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&log_file)
{
builder.target(env_logger::Target::Pipe(Box::new(file)));
match systemd_journal_logger::JournalLog::new() {
Ok(logger) => {
if let Err(e) = logger.install() {
eprintln!("Failed to install journal logger: {e}");
}
}
Err(e) => {
eprintln!("Failed to create journal logger: {e}");
}
}
builder.init();
let level = if std::env::var("MOONLOCK_DEBUG").is_ok() {
log::LevelFilter::Debug
} else {
log::LevelFilter::Info
};
log::set_max_level(level);
}
fn install_panic_hook() {
@@ -150,6 +216,7 @@ fn install_panic_hook() {
}
fn main() {
install_panic_hook();
setup_logging();
// Root check — moonlock should not run as root
@@ -157,8 +224,6 @@ fn main() {
log::error!("Moonlock should not run as root");
std::process::exit(1);
}
install_panic_hook();
log::info!("Moonlock starting");
// Register compiled GResources
+6 -10
View File
@@ -1,4 +1,4 @@
// ABOUTME: Power actions — reboot and shutdown via loginctl.
// ABOUTME: Power actions — reboot and shutdown via systemctl.
// ABOUTME: Wrappers around system commands for the lockscreen UI.
use std::fmt;
@@ -7,14 +7,12 @@ use std::process::Command;
#[derive(Debug)]
pub enum PowerError {
CommandFailed { action: &'static str, message: String },
Timeout { action: &'static str },
}
impl fmt::Display for PowerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PowerError::CommandFailed { action, message } => write!(f, "{action} failed: {message}"),
PowerError::Timeout { action } => write!(f, "{action} timed out"),
}
}
}
@@ -22,11 +20,10 @@ impl fmt::Display for PowerError {
impl std::error::Error for PowerError {}
fn run_command(action: &'static str, program: &str, args: &[&str]) -> Result<(), PowerError> {
let child = Command::new(program)
let output = Command::new(program)
.args(args)
.spawn()
.map_err(|e| PowerError::CommandFailed { action, message: e.to_string() })?;
let output = child.wait_with_output()
.stderr(std::process::Stdio::piped())
.output()
.map_err(|e| PowerError::CommandFailed { action, message: e.to_string() })?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -37,15 +34,14 @@ fn run_command(action: &'static str, program: &str, args: &[&str]) -> Result<(),
Ok(())
}
pub fn reboot() -> Result<(), PowerError> { run_command("reboot", "/usr/bin/loginctl", &["reboot"]) }
pub fn shutdown() -> Result<(), PowerError> { run_command("shutdown", "/usr/bin/loginctl", &["poweroff"]) }
pub fn reboot() -> Result<(), PowerError> { run_command("reboot", "/usr/bin/systemctl", &["--no-ask-password", "reboot"]) }
pub fn shutdown() -> Result<(), PowerError> { run_command("shutdown", "/usr/bin/systemctl", &["--no-ask-password", "poweroff"]) }
#[cfg(test)]
mod tests {
use super::*;
#[test] fn power_error_display() { assert_eq!(PowerError::CommandFailed { action: "reboot", message: "fail".into() }.to_string(), "reboot failed: fail"); }
#[test] fn timeout_display() { assert_eq!(PowerError::Timeout { action: "shutdown" }.to_string(), "shutdown timed out"); }
#[test] fn missing_binary() { assert!(run_command("test", "nonexistent-xyz", &[]).is_err()); }
#[test] fn nonzero_exit() { assert!(run_command("test", "false", &[]).is_err()); }
#[test] fn success() { assert!(run_command("test", "true", &[]).is_ok()); }