使用 logind D-Bus 监听锁屏变化,减少进程轮询和审计噪声 (#218)

* fix: monitor logind lock state over D-Bus instead of spawning loginctl

* docs: add redacted lock-monitor audit evidence and validation

* fix: retain logind subscription without a graphical session
This commit is contained in:
阿夜 authored and GitHub committed 2026-11-12 17:14:51 +08:00
1 parent 890c46e280
commit 50a7447b7b
6 files changed
+628 -20

No files matched your search

Generated
+341 -1
View File
@@ -172,6 +172,29 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "async-broadcast"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
dependencies = [
"event-listener",
"event-listener-strategy",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-recursion"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "async-trait"
version = "0.1.92"
@@ -640,6 +663,33 @@ dependencies = [
"zeroize",
]
[[package]]
name = "endi"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enumflags2"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
dependencies = [
"enumflags2_derive",
"serde",
]
[[package]]
name = "enumflags2_derive"
version = "0.7.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "env_filter"
version = "2.0.0"
@@ -663,6 +713,12 @@ dependencies = [
"log",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "errno"
version = "0.3.14"
@@ -673,6 +729,32 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "event-listener"
version = "5.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
dependencies = [
"parking",
"pin-project-lite",
]
[[package]]
name = "event-listener-strategy"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
dependencies = [
"event-listener",
"pin-project-lite",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
@@ -797,6 +879,19 @@ version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
[[package]]
name = "futures-lite"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"parking",
"pin-project-lite",
]
[[package]]
name = "futures-macro"
version = "0.3.34"
@@ -912,6 +1007,12 @@ dependencies = [
"subtle",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hermit-abi"
version = "0.5.3"
@@ -1145,6 +1246,16 @@ dependencies = [
"icu_properties",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "inout"
version = "0.1.4"
@@ -1326,6 +1437,15 @@ dependencies = [
"autocfg",
]
[[package]]
name = "memoffset"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1372,7 +1492,7 @@ dependencies = [
"bitflags 1.3.2",
"cfg-if",
"libc",
"memoffset",
"memoffset 0.7.1",
"pin-utils",
]
@@ -1475,6 +1595,16 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "ordered-stream"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
dependencies = [
"futures-core",
"pin-project-lite",
]
[[package]]
name = "owned_ttf_parser"
version = "0.25.1"
@@ -1508,6 +1638,12 @@ dependencies = [
"sha2",
]
[[package]]
name = "parking"
version = "2.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -1663,6 +1799,15 @@ dependencies = [
"elliptic-curve",
]
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
dependencies = [
"toml_edit",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -2229,6 +2374,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_repr"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -2463,6 +2619,19 @@ dependencies = [
"syn 3.0.9",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -2563,6 +2732,7 @@ dependencies = [
"signal-hook-registry",
"socket2 0.6.5",
"tokio-macros",
"tracing",
"windows-sys 0.61.2",
]
@@ -2616,6 +2786,36 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.25.19+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"
dependencies = [
"indexmap",
"toml_datetime",
"toml_parser",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [
"winnow",
]
[[package]]
name = "tower"
version = "0.5.3"
@@ -2668,9 +2868,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"pin-project-lite",
"tracing-attributes",
"tracing-core",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
@@ -2738,6 +2950,17 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "uds_windows"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset 0.9.1",
"tempfile",
"windows-sys 0.61.2",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -2834,6 +3057,7 @@ dependencies = [
"tokio-tungstenite",
"webrtc",
"x11rb",
"zbus",
]
[[package]]
@@ -2844,6 +3068,7 @@ checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"getrandom 0.4.3",
"js-sys",
"serde_core",
"wasm-bindgen",
]
@@ -3291,6 +3516,15 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
dependencies = [
"memchr",
]
[[package]]
name = "writeable"
version = "0.6.4"
@@ -3378,6 +3612,71 @@ dependencies = [
"synstructure 0.14.0",
]
[[package]]
name = "zbus"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
dependencies = [
"async-broadcast",
"async-recursion",
"async-trait",
"enumflags2",
"event-listener",
"futures-core",
"futures-lite",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"tokio",
"tracing",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow",
"zbus_macros",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus_macros"
version = "5.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
"zbus_names",
"zvariant",
"zvariant_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"
dependencies = [
"serde",
"winnow",
"zvariant",
]
[[package]]
name = "zcheapstr"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
dependencies = [
"serde",
]
[[package]]
name = "zerocopy"
version = "0.8.62"
@@ -3483,3 +3782,44 @@ name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zvariant"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"
dependencies = [
"endi",
"enumflags2",
"serde",
"winnow",
"zcheapstr",
"zvariant_derive",
"zvariant_utils",
]
[[package]]
name = "zvariant_derive"
version = "5.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"
dependencies = [
"proc-macro-crate",
"proc-macro2",
"quote",
"syn 3.0.9",
"zvariant_utils",
]
[[package]]
name = "zvariant_utils"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"winnow",
]
+1
View File
@@ -38,6 +38,7 @@ inproc-av = ["dep:x11rb"]
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = { version = "0.23", features = ["rustls-tls-webpki-roots"] }
futures-util = "0.3"
zbus = { version = "5", default-features = false, features = ["tokio"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "rustls-tls-native-roots"] }
+2
View File
@@ -128,6 +128,8 @@ The host also accepts a desktop connection while GNOME is locked with no Portal
Existing screen-off and lock settings remain unchanged. Only capture recovery in an unlocked session temporarily holds a GNOME idle inhibitor; the first frame, lock, disconnect or initialization failure releases it. An idle viewer still allows the normal screen-off and lock timeout, and manual lock remains effective. Desktop input is blocked and real video is hidden while locked or when lock state is unknown. Independent terminal, file-transfer and port-mapping peers do not wait for video initialization and survive desktop reconnection. Automated protocol and lifecycle regression tests cover this path; auto unlock and capture recovery after a cold locked connection are verified on GNOME hardware with the official Mac and iPhone 4.42.0 viewers, while screen-off and the other scenarios still need acceptance testing. Waking a fully suspended or hibernating machine is outside this CONTROL path.
Lock monitoring reads logind `LockedHint` over the system D-Bus and subscribes to changes instead of spawning `loginctl` every second. Without a graphical session it stays subscribed with unknown state, so login signals trigger a fresh read. It reconciles the session over D-Bus every 30 seconds; if D-Bus fails, it retries with a bounded `loginctl` fallback every 30 seconds, resolving the executable path once. Notifications may be delayed during fallback; unreadable state remains unknown. The locker must still report its state to logind. Suspend, locking and remote connection policies are unchanged.
Locked black video requires FFmpeg's libx264/libx265 encoder for the negotiated H.264/H.265 codec; hardware encoding support alone does not satisfy this dependency. Encoder failures are logged explicitly. Synthetic video does not change capture permissions or advertised monitor dimensions. It pauses on unlock or unknown lock state, ends when capture is ready/rejected or the connection closes, and then hands the same video track to real capture. See [#29](../../issues/29) and [#34](../../pull/34) for the controlled experiment and validation scope.
The native Wayland backend needs `wlr-output-power-management` from the compositor to wake a turned-off screen; without it only wake is unavailable — capture and encoding are unaffected. Display-wake failures at video startup or during streaming are logged and retried at the next interval without ending the video stream; capture, encoder and send errors retain their existing handling.
+2
View File
@@ -114,6 +114,8 @@ GNOME Portal 的控制通道不再等待授权窗口或第一帧画面:先通
无需修改现有熄屏和锁屏设置。主机仅在会话已解锁的采集恢复期间临时申请 GNOME 的 idle 抑制,拿到首帧后立即释放;锁屏、断开或初始化失败也会释放。远控窗口空闲时仍按原策略熄屏和锁屏,手动锁屏也继续生效。锁屏及锁状态未知时停止桌面输入并隐藏真实画面;独立终端、文件传输和端口映射连接不依赖画面初始化,也不会因桌面重连被关闭。这一恢复路径已覆盖自动化协议与生命周期回归测试,锁屏冷连接后的自动解锁与采集恢复已用官方 Mac 和 iPhone 4.42.0 客户端在 GNOME 实机验证,熄屏等其余场景仍待验收;不支持从整机挂起或休眠状态通过现有控制通道唤醒。
锁屏状态优先通过系统 D-Bus 读取 logind 的 `LockedHint` 并监听变化,正常监测不按秒启动 `loginctl`。尚无图形会话时保持未知并继续监听,登录后由信号触发重新读取。每 30 秒通过 D-Bus 校验会话;D-Bus 异常时每 30 秒重试并使用带超时的 `loginctl` 回退查询,命令路径只解析一次。回退期间状态通知可能延迟;无法读取时保持未知。锁屏程序仍需正确上报 logind 状态,这不改变睡眠、锁屏或远程连接策略。
锁屏黑帧使用 FFmpeg 的 libx264/libx265 编码器(按已协商的 H.264/H.265 选择),硬件编码器可用并不代表这些软件编码器已安装。编码失败会明确记录日志。黑帧不改变采集权限或上报的真实屏幕尺寸;解锁或锁状态未知时暂停,采集就绪、拒绝或连接关闭时结束,再由真实视频接续同一条视频轨。对照实验与验证范围见 [#29](../../issues/29)、[#34](../../pull/34)。
原生 Wayland 后端需要合成器提供 `wlr-output-power-management` 才能唤醒已关闭的屏幕;缺少该协议不影响采集和编码。视频启动及运行期间,屏幕保活失败仅记录警告并在下轮重试,不终止视频;实际采集、编码或发送错误仍按原逻辑处理。
+74 -19
View File
@@ -11,11 +11,15 @@
//! (`loginctl unlock-session`, allowed for the session owner), which avoids remote keystrokes
//! and gives an exact wrong-password result. The password is never logged or stored.
use std::process::Command;
use std::process::{Command, Stdio};
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
use tokio::sync::watch;
mod logind;
/// Official UnlockResult cases (LockScreenManager).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnlockResult { Success, WrongPassword, NoLoggedInUser, NoPermission, Failed }
@@ -29,10 +33,44 @@ extern "C" {
fn uu_pam_check(service: *const libc::c_char, user: *const libc::c_char, password: *const libc::c_char) -> libc::c_int;
}
// Resolve once: execvp's unsuccessful PATH candidates are also recorded by auditd.
fn loginctl_path() -> Option<&'static Path> {
static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
PATH.get_or_init(|| {
std::env::var_os("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
.map(|dir| dir.join("loginctl"))
.find(|path| path.is_file() && std::ffi::CString::new(path.as_os_str().as_encoded_bytes())
.map(|p| unsafe { libc::access(p.as_ptr(), libc::X_OK) == 0 }).unwrap_or(false))
.and_then(|path| std::fs::canonicalize(path).ok())
}).as_deref()
}
#[cfg(test)]
static COMMAND_STARTS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
fn bounded_command(path: &Path, args: &[&str], timeout: Duration) -> Option<String> {
use std::io::Read;
#[cfg(test)]
COMMAND_STARTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let mut child = Command::new(path).args(args).stdin(Stdio::null()).stdout(Stdio::piped())
.stderr(Stdio::null()).spawn().ok()?;
let deadline = std::time::Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(status)) => {
if !status.success() { return None; }
let mut text = String::new();
child.stdout.take()?.take(4096).read_to_string(&mut text).ok()?;
return Some(text.trim().to_owned());
}
Ok(None) if std::time::Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)),
_ => { let _ = child.kill(); let _ = child.wait(); return None; }
}
}
}
fn loginctl(args: &[&str]) -> Option<String> {
let out = Command::new("loginctl").args(args).output().ok()?;
if !out.status.success() { return None; }
Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty())
bounded_command(loginctl_path()?, args, Duration::from_secs(3)).filter(|s| !s.is_empty())
}
/// The logind session that owns this user's graphical display.
@@ -44,7 +82,7 @@ fn display_session() -> Option<String> {
pub fn locked_now() -> Option<bool> { display_session().as_deref().and_then(session_locked) }
fn session_locked(session: &str) -> Option<bool> {
loginctl(&["show-session", session, "-p", "LockedHint", "--value"]).map(|v| v == "yes")
loginctl(&["show-session", session, "-p", "LockedHint", "--value"]).and_then(|v| match v.as_str() { "yes" => Some(true), "no" => Some(false), _ => None })
}
fn user_name() -> Option<String> {
@@ -78,30 +116,28 @@ pub fn supported() -> bool {
*SUPPORTED.get_or_init(|| pam_available() && display_session().is_some())
}
/// Current lock state (None = unknown), refreshed every second by one background thread.
/// Current lock state (None = unknown), shared by all desktop connections.
pub fn watch_locked() -> watch::Receiver<Option<bool>> {
static STATE: OnceLock<watch::Sender<Option<bool>>> = OnceLock::new();
STATE.get_or_init(|| {
let (tx, _) = watch::channel(None);
let sender = tx.clone();
std::thread::Builder::new().name("uu-lock-state".into()).spawn(move || {
let mut session = None;
loop {
if session.is_none() { session = display_session(); }
let locked = session.as_deref().and_then(session_locked);
if locked.is_none() { session = None; } // session ended or changed: look it up again
sender.send_if_modified(|current| if *current != locked {
log::info!("Desktop lock state: {}", match locked { Some(true) => "locked", Some(false) => "unlocked", None => "unknown" });
if locked == Some(true) { log::info!("Desktop is locked; capture continues while the compositor supplies frames"); }
*current = locked; true
} else { false });
std::thread::sleep(Duration::from_secs(1));
}
tokio::runtime::Builder::new_current_thread().enable_all().build()
.expect("lock monitor runtime").block_on(logind::monitor(sender));
}).expect("spawn lock state thread");
tx
}).subscribe()
}
fn publish_lock_state(sender: &watch::Sender<Option<bool>>, locked: Option<bool>) {
sender.send_if_modified(|current| if *current != locked {
log::info!("Desktop lock state: {}", match locked { Some(true) => "locked", Some(false) => "unlocked", None => "unknown" });
if locked == Some(true) { log::info!("Desktop is locked; capture continues while the compositor supplies frames"); }
*current = locked; true
} else { false });
}
/// Verifies the session user's password and unlocks the display session. Blocking (PAM may
/// delay a failure by seconds); call from spawn_blocking. Consumes and wipes the password.
pub fn unlock(password: String) -> UnlockResult {
@@ -117,7 +153,7 @@ fn unlock_with(password: &str) -> UnlockResult {
let Some(user) = user_name() else { return UnlockResult::NoLoggedInUser };
if password.is_empty() || password.contains('\0') { return UnlockResult::WrongPassword; }
match pam_check(&user, password) { 0 => {}, 1 => return UnlockResult::WrongPassword, _ => return UnlockResult::Failed }
if Command::new("loginctl").args(["unlock-session", &session]).status().map(|s| !s.success()).unwrap_or(true) {
if loginctl_path().and_then(|path| bounded_command(path, &["unlock-session", &session], Duration::from_secs(3))).is_none() {
return UnlockResult::NoPermission;
}
if let Err(error) = crate::capture::keep_display_awake() {
@@ -204,6 +240,25 @@ pub fn password_from_args(args: &[u8]) -> Option<String> {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_state_is_preserved_and_repeated_states_do_not_notify() {
let (tx, mut rx) = watch::channel(Some(true));
publish_lock_state(&tx, None);
assert_eq!(*rx.borrow_and_update(), None);
publish_lock_state(&tx, None);
assert!(!rx.has_changed().unwrap());
publish_lock_state(&tx, Some(false));
assert!(rx.has_changed().unwrap());
assert_eq!(*rx.borrow_and_update(), Some(false));
}
#[test]
fn hung_fallback_is_killed_and_reaped() {
let start = std::time::Instant::now();
assert_eq!(bounded_command(Path::new("/bin/sleep"), &["10"], Duration::from_millis(30)), None);
assert!(start.elapsed() < Duration::from_secs(2));
}
#[test]
fn password_comes_from_the_official_key_field() {
assert_eq!(password_from_args(br#"{"key":"p@ss word"}"#).as_deref(), Some("p@ss word"));
+208
View File
@@ -0,0 +1,208 @@
//! logind signals replace per-second process spawning; loginctl is a bounded fallback.
use super::{publish_lock_state, Duration};
use futures_util::StreamExt;
use tokio::sync::watch;
use zbus::{Connection, MatchRule, MessageStream, Proxy, proxy::CacheProperties};
const SERVICE: &str = "org.freedesktop.login1";
const ROOT: &str = "/org/freedesktop/login1";
const CALL_TIMEOUT: Duration = Duration::from_secs(5);
const RETRY: Duration = Duration::from_secs(30);
async fn locked(connection: &Connection) -> zbus::Result<Option<bool>> {
let path = format!("{ROOT}/user/_{}", unsafe { libc::getuid() });
let user = zbus::proxy::Builder::<Proxy<'_>>::new(connection).destination(SERVICE)?
.path(path)?.interface("org.freedesktop.login1.User")?
.cache_properties(CacheProperties::No).build().await?;
// No cached property reads: signals, including invalidations, trigger a fresh snapshot.
let display: (String, zbus::zvariant::OwnedObjectPath) = user.get_property("Display").await?;
if display.0.is_empty() { return Ok(None); }
let session = zbus::proxy::Builder::<Proxy<'_>>::new(connection).destination(SERVICE)?
.path(display.1)?.interface("org.freedesktop.login1.Session")?
.cache_properties(CacheProperties::No).build().await?;
session.get_property("LockedHint").await.map(Some)
}
async fn snapshot(connection: &Connection) -> zbus::Result<Option<bool>> {
tokio::time::timeout(CALL_TIMEOUT, locked(connection)).await
.map_err(|_| zbus::Error::Failure("lock query timed out".into()))?
}
async fn monitor_connection(connection: &Connection, sender: &watch::Sender<Option<bool>>) -> zbus::Result<()> {
// Subscribe before reading: any change during the first snapshot stays queued.
// Watch all logind signals so User.Display, SessionNew/Removed and invalidated
// properties also re-resolve the graphical session instead of trusting a stale path.
let rule = MatchRule::builder().msg_type(zbus::message::Type::Signal)
.sender(SERVICE)?.path_namespace(ROOT)?.build();
let mut signals = tokio::time::timeout(CALL_TIMEOUT, MessageStream::for_match_rule(rule, connection, Some(64))).await
.map_err(|_| zbus::Error::Failure("lock subscription timed out".into()))??;
publish_lock_state(sender, snapshot(connection).await?);
let mut reconcile = tokio::time::interval(RETRY);
reconcile.tick().await;
loop {
tokio::select! {
event = signals.next() => { event.ok_or_else(|| zbus::Error::Failure("system bus closed".into()))??; },
_ = reconcile.tick() => {},
}
publish_lock_state(sender, snapshot(connection).await?);
}
}
pub(super) async fn monitor(sender: watch::Sender<Option<bool>>) {
let mut degraded = false;
loop {
let result = tokio::time::timeout(CALL_TIMEOUT, async { zbus::connection::Builder::system()?.method_timeout(CALL_TIMEOUT).build().await }).await;
if let Ok(Ok(connection)) = result {
if !degraded { log::debug!("Desktop lock monitor: logind D-Bus"); }
// Recovery is announced only after a valid snapshot, via the state channel.
let _ = monitor_connection(&connection, &sender).await;
}
publish_lock_state(&sender, None);
if !degraded { log::warn!("Desktop lock monitor unavailable; retrying D-Bus with bounded loginctl fallback every 30s"); }
degraded = true;
let fallback = tokio::task::spawn_blocking(super::locked_now).await.ok().flatten();
publish_lock_state(&sender, fallback);
tokio::time::sleep(RETRY).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use zbus::zvariant::{OwnedObjectPath, Value};
struct User(Arc<Mutex<String>>);
#[zbus::interface(name = "org.freedesktop.login1.User")]
impl User {
#[zbus(property)]
fn display(&self) -> (String, OwnedObjectPath) {
let id = self.0.lock().unwrap().clone();
let path = if id.is_empty() { "/".into() } else { format!("{ROOT}/session/{id}") };
(id, OwnedObjectPath::try_from(path).unwrap())
}
}
struct Session { locked: Arc<AtomicBool>, valid: Arc<AtomicBool> }
#[zbus::interface(name = "org.freedesktop.login1.Session")]
impl Session {
#[zbus(property)]
fn locked_hint(&self) -> zbus::fdo::Result<bool> {
if !self.valid.load(Ordering::SeqCst) { return Err(zbus::fdo::Error::Failed("unavailable".into())); }
Ok(self.locked.load(Ordering::SeqCst))
}
}
async fn expect(rx: &mut watch::Receiver<Option<bool>>, value: Option<bool>) {
tokio::time::timeout(Duration::from_secs(3), async {
loop {
let current = *rx.borrow_and_update();
if current == value { return; }
rx.changed().await.unwrap();
}
}).await.expect("lock state update");
}
async fn invalidated(server: &Connection, path: &str, interface: &str, property: &str) {
// An invalidation has no replacement value: the client must re-read it.
let changed = std::collections::HashMap::<&str, Value<'_>>::new();
server.emit_signal(None::<&str>, path, "org.freedesktop.DBus.Properties", "PropertiesChanged",
&(interface, changed, vec![property])).await.unwrap();
}
#[tokio::test]
#[ignore = "isolated D-Bus integration; requires dbus-daemon, never changes the real desktop"]
async fn private_bus_tracks_initial_state_invalidation_session_change_and_failure() {
use tokio::io::{AsyncBufReadExt, BufReader};
let mut daemon = tokio::process::Command::new("dbus-daemon")
.args(["--session", "--nofork", "--print-address=1"])
.stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null())
.kill_on_drop(true).spawn().unwrap();
let mut address = String::new();
tokio::time::timeout(Duration::from_secs(3), BufReader::new(daemon.stdout.take().unwrap()).read_line(&mut address)).await.unwrap().unwrap();
let address = address.trim();
let display = Arc::new(Mutex::new(String::new()));
let locked = Arc::new(AtomicBool::new(true));
let valid = Arc::new(AtomicBool::new(true));
let user_path = format!("{ROOT}/user/_{}", unsafe { libc::getuid() });
let server = zbus::connection::Builder::address(address).unwrap().name(SERVICE).unwrap()
.serve_at(user_path.clone(), User(display.clone())).unwrap()
.serve_at(format!("{ROOT}/session/a"), Session { locked: locked.clone(), valid: valid.clone() }).unwrap()
.serve_at(format!("{ROOT}/session/b"), Session { locked: Arc::new(AtomicBool::new(true)), valid: valid.clone() }).unwrap()
.build().await.unwrap();
let client = zbus::connection::Builder::address(address).unwrap().build().await.unwrap();
let (tx, mut rx) = watch::channel(Some(false));
let monitor = tokio::spawn(async move {
let result = monitor_connection(&client, &tx).await;
publish_lock_state(&tx, None);
result
});
expect(&mut rx, None).await;
assert!(!monitor.is_finished(), "no graphical session must keep the D-Bus subscription alive");
*display.lock().unwrap() = "a".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await; // login is observed without waiting for the retry timer
locked.store(false, Ordering::SeqCst);
invalidated(&server, &format!("{ROOT}/session/a"), "org.freedesktop.login1.Session", "LockedHint").await;
expect(&mut rx, Some(false)).await;
*display.lock().unwrap() = "b".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await;
display.lock().unwrap().clear();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, None).await;
assert!(!monitor.is_finished(), "logout must keep the D-Bus subscription alive");
*display.lock().unwrap() = "b".into();
invalidated(&server, &user_path, "org.freedesktop.login1.User", "Display").await;
expect(&mut rx, Some(true)).await;
valid.store(false, Ordering::SeqCst);
invalidated(&server, &format!("{ROOT}/session/b"), "org.freedesktop.login1.Session", "LockedHint").await;
expect(&mut rx, None).await; // failure must not become unlocked
assert!(monitor.await.unwrap().is_err());
// A fresh connection must recover after a service/property failure.
valid.store(true, Ordering::SeqCst);
let client = zbus::connection::Builder::address(address).unwrap().build().await.unwrap();
let close = client.clone();
let (tx, mut rx) = watch::channel(None);
let monitor = tokio::spawn(async move {
let result = monitor_connection(&client, &tx).await;
publish_lock_state(&tx, None);
result
});
expect(&mut rx, Some(true)).await;
close.close().await.unwrap();
expect(&mut rx, None).await;
assert!(monitor.await.unwrap().is_err());
daemon.kill().await.unwrap();
daemon.wait().await.unwrap();
}
#[tokio::test]
#[ignore = "manual acceptance: observes a real lock/unlock for up to three minutes"]
async fn live_lock_unlock_signals() {
let before = super::super::COMMAND_STARTS.load(Ordering::SeqCst);
let mut rx = super::super::watch_locked();
let start = std::time::Instant::now();
tokio::time::timeout(Duration::from_secs(180), async {
let mut saw_lock = false;
loop {
let state = *rx.borrow_and_update();
println!("live lock state: {state:?}; elapsed_ms={}", start.elapsed().as_millis());
if state == Some(true) { saw_lock = true; }
if saw_lock && state == Some(false) { break; }
rx.changed().await.unwrap();
}
}).await.expect("please lock and unlock the desktop during this probe");
let started = super::super::COMMAND_STARTS.load(Ordering::SeqCst) - before;
println!("lock monitor command starts: {started}");
assert_eq!(started, 0, "healthy D-Bus monitoring should not spawn loginctl");
}
#[tokio::test]
#[ignore = "read-only live logind probe; requires an active graphical logind session"]
async fn live_logind_snapshot_matches_loginctl_without_changing_lock_state() {
let connection = Connection::system().await.unwrap();
let dbus = snapshot(&connection).await.unwrap();
let command = tokio::task::spawn_blocking(super::super::locked_now).await.unwrap();
assert_eq!(dbus, command);
}
}