Compare commits

...
3 Commits
Author SHA1 Message Date
VallierDevandClaude Opus 5.5 5f28047a34 release: v0.2.59
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 13:15:56 +08:00
Mr. Error 661263fe37 fix(portal): capture the lock screen on locked cold connections (#229)
* fix(portal): capture the lock screen on locked cold connections

KWin keeps the Portal screencast alive while the session is locked, but maintain() refused to open a session until unlock, so a cold connection only received synthetic black frames. Allow capture during lock on KDE and keep the black-frame fallback for compositors that close the session. A consent failure behind the lock screen and auto privacy now wait for the local unlock.

* docs: document the KDE lock-screen capture default

Cover the new default, the UU_LOCKED_CAPTURE opt-out and the desktop-detection fallback in both READMEs, as requested in #229.
2026-11-14 14:14:42 +09:00
ff2bd9c582 build: copy engine plugins to the profile dir under Cargo's newer build-dir layout (#226)
Rust 1.100 CI places OUT_DIR one level deeper, so ancestors().nth(3) no longer
reached target/<profile> and the release feature-set checks lost libuu-wayland.so.

Co-authored-by: VallierDev <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-13 13:40:01 +09:00
9 changed files with 269 additions and 35 deletions

No files matched your search

Generated
+1 -1
View File
@@ -3027,7 +3027,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]] [[package]]
name = "uu-remote-linux" name = "uu-remote-linux"
version = "0.2.58" version = "0.2.59"
dependencies = [ dependencies = [
"ab_glyph", "ab_glyph",
"async-trait", "async-trait",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "uu-remote-linux" name = "uu-remote-linux"
version = "0.2.58" version = "0.2.59"
edition = "2021" edition = "2021"
default-run = "uuremote-server" default-run = "uuremote-server"
authors = ["uu-remote-linux contributors"] authors = ["uu-remote-linux contributors"]
+3 -1
View File
@@ -126,7 +126,9 @@ GNOME Portal CONTROL no longer waits for a consent dialog or the first video fra
The host also accepts a desktop connection while GNOME is locked with no Portal session yet (a cold connection): it reports lock state and accepts auto unlock, then restores picture, input and clipboard after unlock. While Portal is pending, the host sends generated black video once per second on the negotiated track by default, allowing the official iPhone viewer to enter its auto-unlock flow without extra configuration. Verified on Ubuntu GNOME Wayland with the official Mac viewer; iPhone 4.42.0 with H.265 completed a same-executable control experiment: black video ON succeeded, OFF failed, and ON succeeded again ([#29](../../issues/29)). **Limitation**: this is synthetic black video, not the GNOME lock screen, and it does not enable native mouse/keyboard input while locked. Enable 「自动解锁被控端」 in the UU client under 控制中心 → 安全 and enter the password. Without saved Portal permission, local consent is still required after unlock before the real desktop can appear. The host also accepts a desktop connection while GNOME is locked with no Portal session yet (a cold connection): it reports lock state and accepts auto unlock, then restores picture, input and clipboard after unlock. While Portal is pending, the host sends generated black video once per second on the negotiated track by default, allowing the official iPhone viewer to enter its auto-unlock flow without extra configuration. Verified on Ubuntu GNOME Wayland with the official Mac viewer; iPhone 4.42.0 with H.265 completed a same-executable control experiment: black video ON succeeded, OFF failed, and ON succeeded again ([#29](../../issues/29)). **Limitation**: this is synthetic black video, not the GNOME lock screen, and it does not enable native mouse/keyboard input while locked. Enable 「自动解锁被控端」 in the UU client under 控制中心 → 安全 and enter the password. Without saved Portal permission, local consent is still required after unlock before the real desktop can appear.
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. On KDE Plasma (KWin), the Portal screencast stays alive after the session locks. The host now opens capture while locked by default, so a cold connection shows the real lock screen and the password can be entered with the remote keyboard instead of receiving black video ([#227](../../issues/227), [#229](../../pull/229)). Set `UU_LOCKED_CAPTURE=0` to disable this and return to the black-video and auto-unlock path. Detection requires `XDG_CURRENT_DESKTOP` or `XDG_SESSION_DESKTOP` in the systemd user environment. Without either the host falls back to black video, and `UU_LOCKED_CAPTURE=1` forces the new behavior. Portal pointer input remains blocked while locked, and the keyboard uses uinput and can enter the password. This does not apply to GNOME: Mutter closes the Portal session on lock, so the black-video and auto-unlock behavior above is unchanged.
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. Portal input is blocked while locked. KDE keeps sending the real lock screen, while GNOME hides real video and uses black video. 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. 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.
+3 -1
View File
@@ -112,7 +112,9 @@ GNOME Portal 的控制通道不再等待授权窗口或第一帧画面:先通
桌面锁屏且尚未建立 Portal 时(冷连接),主机也会建立控制通道:上报锁屏状态并接受自动解锁,解锁后再恢复画面、键鼠和剪贴板。Portal 等待就绪期间,主机默认通过已协商的视频轨每秒发送一帧生成的纯黑画面,让官方 iPhone 客户端进入自动解锁流程,无需额外配置。Ubuntu GNOME Wayland 上已用官方 Mac 客户端验证;iPhone 4.42.0 的 H.265 冷连接完成了同一实验二进制「开启黑帧成功 → 关闭失败 → 再开成功」对照([#29](../../issues/29))。**局限**:黑帧不是真实 GNOME 锁屏画面,也不支持在锁屏界面操作原生键鼠;需要在 UU 客户端 控制中心 → 安全 → 自动解锁被控端 中启用自动解锁并输入密码。若本机没有已保存的 Portal 授权,解锁后仍需本机确认授权才能显示真实桌面。 桌面锁屏且尚未建立 Portal 时(冷连接),主机也会建立控制通道:上报锁屏状态并接受自动解锁,解锁后再恢复画面、键鼠和剪贴板。Portal 等待就绪期间,主机默认通过已协商的视频轨每秒发送一帧生成的纯黑画面,让官方 iPhone 客户端进入自动解锁流程,无需额外配置。Ubuntu GNOME Wayland 上已用官方 Mac 客户端验证;iPhone 4.42.0 的 H.265 冷连接完成了同一实验二进制「开启黑帧成功 → 关闭失败 → 再开成功」对照([#29](../../issues/29))。**局限**:黑帧不是真实 GNOME 锁屏画面,也不支持在锁屏界面操作原生键鼠;需要在 UU 客户端 控制中心 → 安全 → 自动解锁被控端 中启用自动解锁并输入密码。若本机没有已保存的 Portal 授权,解锁后仍需本机确认授权才能显示真实桌面。
无需修改现有熄屏和锁屏设置。主机仅在会话已解锁的采集恢复期间临时申请 GNOME 的 idle 抑制,拿到首帧后立即释放;锁屏、断开或初始化失败也会释放。远控窗口空闲时仍按原策略熄屏和锁屏,手动锁屏也继续生效。锁屏及锁状态未知时停止桌面输入并隐藏真实画面;独立终端、文件传输和端口映射连接不依赖画面初始化,也不会因桌面重连被关闭。这一恢复路径已覆盖自动化协议与生命周期回归测试,锁屏冷连接后的自动解锁与采集恢复已用官方 Mac 和 iPhone 4.42.0 客户端在 GNOME 实机验证,熄屏等其余场景仍待验收;不支持从整机挂起或休眠状态通过现有控制通道唤醒。 KDE Plasma(KWin)的 Portal 采集在锁屏后仍会继续。主机默认在锁屏时也打开采集,冷连接可以直接看到真实锁屏界面,并用远程键盘输入密码,不再只发黑帧([#227](../../issues/227)、[#229](../../pull/229))。`UU_LOCKED_CAPTURE=0` 关闭这一行为,回到黑帧和自动解锁的路径。KDE 判断依赖 systemd 用户环境里的 `XDG_CURRENT_DESKTOP` 或 `XDG_SESSION_DESKTOP`,两者都没有时回落到黑帧行为,可以手动设 `UU_LOCKED_CAPTURE=1` 开启。锁屏时 Portal 指针输入仍会被拦截,键盘通过 uinput 注入,可以输入密码。GNOME 不适用这一段,Mutter 在锁屏时关闭 Portal 会话,仍走上面的黑帧和自动解锁。
无需修改现有熄屏和锁屏设置。主机仅在会话已解锁的采集恢复期间临时申请 GNOME 的 idle 抑制,拿到首帧后立即释放;锁屏、断开或初始化失败也会释放。远控窗口空闲时仍按原策略熄屏和锁屏,手动锁屏也继续生效。锁屏时停止 Portal 输入。KDE 下继续传输真实锁屏画面,GNOME 下隐藏真实画面并发黑帧。独立终端、文件传输和端口映射连接不依赖画面初始化,也不会因桌面重连被关闭。这一恢复路径已覆盖自动化协议与生命周期回归测试,锁屏冷连接后的自动解锁与采集恢复已用官方 Mac 和 iPhone 4.42.0 客户端在 GNOME 实机验证,熄屏等其余场景仍待验收;不支持从整机挂起或休眠状态通过现有控制通道唤醒。
锁屏状态优先通过系统 D-Bus 读取 logind 的 `LockedHint` 并监听变化,正常监测不按秒启动 `loginctl`。尚无图形会话时保持未知并继续监听,登录后由信号触发重新读取。每 30 秒通过 D-Bus 校验会话;D-Bus 异常时每 30 秒重试并使用带超时的 `loginctl` 回退查询,命令路径只解析一次。回退期间状态通知可能延迟;无法读取时保持未知。锁屏程序仍需正确上报 logind 状态,这不改变睡眠、锁屏或远程连接策略。 锁屏状态优先通过系统 D-Bus 读取 logind 的 `LockedHint` 并监听变化,正常监测不按秒启动 `loginctl`。尚无图形会话时保持未知并继续监听,登录后由信号触发重新读取。每 30 秒通过 D-Bus 校验会话;D-Bus 异常时每 30 秒重试并使用带超时的 `loginctl` 回退查询,命令路径只解析一次。回退期间状态通知可能延迟;无法读取时保持未知。锁屏程序仍需正确上报 logind 状态,这不改变睡眠、锁屏或远程连接策略。
+7 -2
View File
@@ -173,6 +173,11 @@ fn shared_engine(name: &str, sources: &[&str], includes: &[&std::path::Path], cf
command.args(cflags.split_whitespace()).args(sources).args(libs.split_whitespace()).arg("-lpthread"); command.args(cflags.split_whitespace()).args(sources).args(libs.split_whitespace()).arg("-lpthread");
let status = command.status().expect("C compiler for the engine plugin"); let status = command.status().expect("C compiler for the engine plugin");
assert!(status.success(), "building {name} failed"); assert!(status.success(), "building {name} failed");
// OUT_DIR = target/<profile>/build/<package>-<hash>/out // OUT_DIR = target/<profile>/build/<package>-<hash>/out, or target/<profile>/build/<package>/<hash>/out with
if let Some(profile) = out.ancestors().nth(3) { std::fs::copy(&library, profile.join(name)).expect("copy engine plugin"); } // the newer Cargo build-dir layout (Rust 1.100 CI): the profile dir is the parent of the `build` component.
let profile = out.ancestors().find(|dir| dir.file_name().is_some_and(|n| n == "build")).and_then(|dir| dir.parent());
match profile {
Some(profile) => { std::fs::copy(&library, profile.join(name)).expect("copy engine plugin"); }
None => println!("cargo:warning={name} built in {} but no target/<profile> dir found to copy it to", out.display()),
}
} }
+15
View File
@@ -0,0 +1,15 @@
修复版:KDE 锁屏冷连接显示真实锁屏界面、适配 Cargo 新 build-dir 布局。/ Fix release: real lock screen on KDE locked cold connections, Cargo build-dir layout fix.
### 修复 / Fixed
- **KDE 锁屏冷连接(#227、#229)**:KDE Plasma(KWin)锁屏后 Portal 采集仍可用,主机默认在锁屏时也打开采集,冷连接直接看到真实锁屏界面并可用远程键盘输入密码,不再停在「正在传输画面」;`UU_LOCKED_CAPTURE=0` 关闭,`UU_LOCKED_CAPTURE=1` 在无法识别桌面时强制开启。GNOME 行为不变。/ On KDE Plasma the host now keeps Portal capture open while locked, so a cold connection shows the real lock screen; `UU_LOCKED_CAPTURE=0` disables it. GNOME is unchanged.
- **源码构建(#226)**:适配 Cargo 新的 build-dir 布局,引擎插件复制到 profile 目录。/ Engine plugins are copied to the profile directory under Cargo's newer build-dir layout.
感谢 @RiverOnVenus 的贡献。/ Thanks to @RiverOnVenus.
### 验证范围 / Validation
单元测试与 CI;#229 由贡献者在 Plasma 6.8.2 + 官方 Windows 控制端实测锁屏冷连接与远程键盘解锁。维护方未做 KDE 实机验收。
### 下载 / Download
`uu-remote-linux_0.2.59_<amd64|arm64>.deb`,或 `uu-remote-linux-v0.2.59-<x86_64|aarch64>-linux.tar.gz`(解压后运行 `./install.sh`),或 `docker pull ghcr.io/vallierdev/uu-remote-linux:v0.2.59`(x86_64)。
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
+199 -25
View File
@@ -1,6 +1,6 @@
//! Portal availability is independent of the authenticated CONTROL transport. //! Portal availability is independent of the authenticated CONTROL transport.
use std::future::Future; use std::future::Future;
use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; use std::sync::{Arc, OnceLock, atomic::{AtomicBool, Ordering}};
use std::time::Instant; use std::time::Instant;
use tokio::sync::{watch, Mutex}; use tokio::sync::{watch, Mutex};
use crate::{capture::ScreenCapture, input::DesktopInputSession}; use crate::{capture::ScreenCapture, input::DesktopInputSession};
@@ -29,6 +29,7 @@ pub struct PortalDesktop {
state: watch::Sender<State>, state: watch::Sender<State>,
opening: Arc<Mutex<()>>, opening: Arc<Mutex<()>>,
locked: watch::Receiver<Option<bool>>, locked: watch::Receiver<Option<bool>>,
capture_while_locked: bool,
} }
struct CancelOnDrop(Arc<AtomicBool>); struct CancelOnDrop(Arc<AtomicBool>);
@@ -71,6 +72,7 @@ enum AttemptOutcome {
Ready(Arc<ScreenCapture>), Ready(Arc<ScreenCapture>),
Retry(String), Retry(String),
Terminal(String), Terminal(String),
Deferred,
Cancelled, Cancelled,
} }
@@ -85,14 +87,52 @@ fn classify(result: Result<Arc<ScreenCapture>, PortalError>) -> AttemptOutcome {
} }
} }
/// A consent dialog opened behind the lock screen cannot be approved, so its denied/timed-out
/// error must not end this connection's supervisor: ask again after the local unlock.
fn defer_consent(error: &PortalError, state: Option<bool>) -> bool {
state == Some(true) && matches!(error.code, 4 | 5)
}
/// True when this iteration sees a lock state it has not attempted under yet. Waking and resetting
/// the retry delay must happen once per transition, not once per 200 ms poll: a locked state would
/// otherwise re-run wake, inhibitor and publish on every tick and defeat the 5 s retry backoff.
fn fresh_state(previous: Option<Option<bool>>, state: Option<bool>) -> bool {
previous != Some(state)
}
fn should_prepare_power(healthy: bool, force_wake: bool) -> bool { fn should_prepare_power(healthy: bool, force_wake: bool) -> bool {
!healthy || force_wake !healthy || force_wake
} }
/// KWin keeps the Portal screencast, including the lock screen, alive while the session is
/// locked, so a cold connection can show the real lock screen. Mutter closes the session on
/// lock, so other desktops keep the existing black-frame path. `UU_LOCKED_CAPTURE=0` opts out.
fn capture_while_locked() -> bool {
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| {
match std::env::var("UU_LOCKED_CAPTURE").ok().filter(|value| !value.is_empty()) {
Some(value) => !matches!(value.to_ascii_lowercase().as_str(), "0" | "off" | "false" | "no"),
None => ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP"].iter().any(|key|
std::env::var(key).is_ok_and(|desktop| desktop.split(':')
.any(|part| part.eq_ignore_ascii_case("KDE")))),
}
})
}
/// Capture may start and continue in this lock state. An unknown state keeps the old wait on
/// desktops whose compositor closes the session on lock.
fn attempt_allowed(state: Option<bool>, capture_while_locked: bool) -> bool {
match state {
Some(false) => true,
Some(true) | None => capture_while_locked,
}
}
fn prepare_attempt<W, I>( fn prepare_attempt<W, I>(
cancelled: &AtomicBool, cancelled: &AtomicBool,
owner: &DesktopInputSession, owner: &DesktopInputSession,
locked: &watch::Receiver<Option<bool>>, locked: &watch::Receiver<Option<bool>>,
allow_locked: bool,
wake: W, wake: W,
inhibit: I, inhibit: I,
) -> Option<AttemptPrep> ) -> Option<AttemptPrep>
@@ -102,7 +142,7 @@ where
{ {
let current = || !cancelled.load(Ordering::Acquire) let current = || !cancelled.load(Ordering::Acquire)
&& owner.is_current() && owner.is_current()
&& *locked.borrow() == Some(false); && attempt_allowed(*locked.borrow(), allow_locked);
if !current() { return None; } if !current() { return None; }
let wake = wake(); let wake = wake();
if !current() { return None; } if !current() { return None; }
@@ -114,7 +154,8 @@ where
impl PortalDesktop { impl PortalDesktop {
pub fn new(screen: Arc<ScreenCapture>) -> Self { pub fn new(screen: Arc<ScreenCapture>) -> Self {
Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0, Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0,
opening: Arc::new(Mutex::new(())), locked: crate::session_lock::watch_locked() } opening: Arc::new(Mutex::new(())), locked: crate::session_lock::watch_locked(),
capture_while_locked: capture_while_locked() }
} }
pub fn begin(&self) { pub fn begin(&self) {
// GNOME closes the Portal session on lock; a cached screen with a dead session // GNOME closes the Portal session on lock; a cached screen with a dead session
@@ -133,10 +174,21 @@ impl PortalDesktop {
} }
pub fn subscribe(&self) -> watch::Receiver<State> { self.state.subscribe() } pub fn subscribe(&self) -> watch::Receiver<State> { self.state.subscribe() }
pub fn lock_state(&self) -> watch::Receiver<Option<bool>> { self.locked.clone() } pub fn lock_state(&self) -> watch::Receiver<Option<bool>> { self.locked.clone() }
/// Whether capture may run in this lock state for this desktop. Shares the rule used by
/// maintain(), so capture-setting requests do not stall behind a lock the compositor does
/// not honor.
pub fn capture_allowed(&self, locked: Option<bool>) -> bool {
attempt_allowed(locked, self.capture_while_locked)
}
#[cfg(test)] #[cfg(test)]
pub fn with_lock_state(screen: Arc<ScreenCapture>, locked: watch::Receiver<Option<bool>>) -> Self { pub fn with_lock_state(screen: Arc<ScreenCapture>, locked: watch::Receiver<Option<bool>>) -> Self {
Self::with_lock_state_and_capture(screen, locked, false)
}
#[cfg(test)]
pub fn with_lock_state_and_capture(screen: Arc<ScreenCapture>, locked: watch::Receiver<Option<bool>>,
capture_while_locked: bool) -> Self {
Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0, Self { state: watch::channel(State { waiting: screen.init_error.is_some(), screen }).0,
opening: Arc::new(Mutex::new(())), locked } opening: Arc::new(Mutex::new(())), locked, capture_while_locked }
} }
#[cfg(test)] #[cfg(test)]
pub fn publish_test_screen(&self, screen: Arc<ScreenCapture>) { pub fn publish_test_screen(&self, screen: Arc<ScreenCapture>) {
@@ -204,22 +256,27 @@ impl PortalDesktop {
let inhibit = Arc::new(inhibit); let inhibit = Arc::new(inhibit);
let open = Arc::new(open); let open = Arc::new(open);
let mut locked = self.locked.clone(); let mut locked = self.locked.clone();
let mut previous = None; let allow_locked = self.capture_while_locked;
let mut previous: Option<Option<bool>> = None;
let mut defer_until_unlock = false;
let mut retry_at = Instant::now(); let mut retry_at = Instant::now();
loop { loop {
if !owner.is_current() { return Ok(()); } if !owner.is_current() { return Ok(()); }
let state = *locked.borrow_and_update(); let state = *locked.borrow_and_update();
if state != Some(false) { if state == Some(false) { defer_until_unlock = false; }
if previous == Some(false) { self.pause(&owner); } if state != Some(false) && previous == Some(Some(false)) { self.pause(&owner); }
} else { if state == Some(true) && previous != Some(Some(true)) && allow_locked {
// A fresh unlocked transition gets an immediate wake/recovery attempt. log::info!("Desktop is locked; opening Portal capture for the lock screen");
let force_wake = previous != Some(false); }
if attempt_allowed(state, allow_locked) && !defer_until_unlock {
// A fresh transition into an attempted state gets an immediate wake/recovery attempt.
let force_wake = fresh_state(previous, state);
if force_wake { retry_at = Instant::now(); } if force_wake { retry_at = Instant::now(); }
let mut attempt_locked = locked.clone(); let mut attempt_locked = locked.clone();
let outcome = tokio::select! { let outcome = tokio::select! {
biased; biased;
_ = wait_for_lock(&mut locked) => AttemptOutcome::Cancelled, _ = wait_for_lock(&mut locked, allow_locked) => AttemptOutcome::Cancelled,
outcome = self.portal_attempt(&owner, &mut attempt_locked, retry_at, force_wake, wake.clone(), inhibit.clone(), open.clone()) => outcome, outcome = self.portal_attempt(&owner, &mut attempt_locked, allow_locked, retry_at, force_wake, wake.clone(), inhibit.clone(), open.clone()) => outcome,
}; };
match outcome { match outcome {
AttemptOutcome::Ready(screen) => self.publish(&owner, screen), AttemptOutcome::Ready(screen) => self.publish(&owner, screen),
@@ -228,11 +285,12 @@ impl PortalDesktop {
log::warn!("Portal desktop recovery deferred: {error}"); log::warn!("Portal desktop recovery deferred: {error}");
retry_at = Instant::now() + std::time::Duration::from_secs(5); retry_at = Instant::now() + std::time::Duration::from_secs(5);
} }
AttemptOutcome::Deferred => { defer_until_unlock = true; }
AttemptOutcome::Cancelled => {} AttemptOutcome::Cancelled => {}
} }
if *locked.borrow_and_update() != Some(false) { self.pause(&owner); } if !attempt_allowed(*locked.borrow_and_update(), allow_locked) { self.pause(&owner); }
} }
previous = *locked.borrow_and_update(); previous = Some(*locked.borrow_and_update());
tokio::select! { tokio::select! {
_ = locked.changed() => {}, _ = locked.changed() => {},
_ = tokio::time::sleep(std::time::Duration::from_millis(200)) => {}, _ = tokio::time::sleep(std::time::Duration::from_millis(200)) => {},
@@ -241,20 +299,20 @@ impl PortalDesktop {
} }
async fn portal_attempt<W, I, O>(&self, owner: &Arc<DesktopInputSession>, async fn portal_attempt<W, I, O>(&self, owner: &Arc<DesktopInputSession>,
locked: &mut watch::Receiver<Option<bool>>, retry_at: Instant, force_wake: bool, locked: &mut watch::Receiver<Option<bool>>, allow_locked: bool, retry_at: Instant, force_wake: bool,
wake: Arc<W>, inhibit: Arc<I>, open: Arc<O>) -> AttemptOutcome wake: Arc<W>, inhibit: Arc<I>, open: Arc<O>) -> AttemptOutcome
where where
W: Fn() -> Result<(), String> + Send + Sync + 'static, W: Fn() -> Result<(), String> + Send + Sync + 'static,
I: Fn() -> IdleGuard + Send + Sync + 'static, I: Fn() -> IdleGuard + Send + Sync + 'static,
O: Fn(Arc<ScreenCapture>, Arc<AtomicBool>) -> Result<Arc<ScreenCapture>, PortalError> + Send + Sync + 'static, O: Fn(Arc<ScreenCapture>, Arc<AtomicBool>) -> Result<Arc<ScreenCapture>, PortalError> + Send + Sync + 'static,
{ {
if !owner.is_current() || *locked.borrow() != Some(false) || Instant::now() < retry_at { if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) || Instant::now() < retry_at {
return AttemptOutcome::Cancelled; return AttemptOutcome::Cancelled;
} }
let gate = self.opening.clone().lock_owned().await; let gate = self.opening.clone().lock_owned().await;
// The state can change while this attempt waits for an earlier worker // The state can change while this attempt waits for an earlier worker
// to finish rotating the Portal permission token. // to finish rotating the Portal permission token.
if !owner.is_current() || *locked.borrow() != Some(false) { if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
return AttemptOutcome::Cancelled; return AttemptOutcome::Cancelled;
} }
let screen = self.snapshot().screen; let screen = self.snapshot().screen;
@@ -271,6 +329,7 @@ impl PortalDesktop {
&prep_cancel, &prep_cancel,
&prep_owner, &prep_owner,
&prep_locked, &prep_locked,
allow_locked,
|| (*wake)(), || (*wake)(),
|| (*inhibit)(), || (*inhibit)(),
)).await { )).await {
@@ -282,7 +341,7 @@ impl PortalDesktop {
// Held by the cancellable async helper, not the blocking worker, so a // Held by the cancellable async helper, not the blocking worker, so a
// lock transition releases it while worker cleanup may still be running. // lock transition releases it while worker cleanup may still be running.
let _inhibitor = prep.inhibitor; let _inhibitor = prep.inhibitor;
if !owner.is_current() || *locked.borrow() != Some(false) { if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
return AttemptOutcome::Cancelled; return AttemptOutcome::Cancelled;
} }
// A new controller can arrive while the cached Portal handle is alive // A new controller can arrive while the cached Portal handle is alive
@@ -298,19 +357,25 @@ impl PortalDesktop {
} }
open(screen, worker_cancel) open(screen, worker_cancel)
}).await; }).await;
if !owner.is_current() || *locked.borrow() != Some(false) { if !owner.is_current() || !attempt_allowed(*locked.borrow(), allow_locked) {
return AttemptOutcome::Cancelled; return AttemptOutcome::Cancelled;
} }
match result { match result {
Ok(Err(error)) if defer_consent(&error, *locked.borrow()) => {
// The consent dialog opened behind the lock screen cannot be approved here.
// Keep this connection alive and ask again after the local unlock.
log::info!("Portal consent is behind the lock screen; waiting for the local unlock");
AttemptOutcome::Deferred
}
Ok(result) => classify(result), Ok(result) => classify(result),
Err(_) => AttemptOutcome::Terminal("Portal initialization worker failed".into()), Err(_) => AttemptOutcome::Terminal("Portal initialization worker failed".into()),
} }
} }
} }
async fn wait_for_lock(locked: &mut watch::Receiver<Option<bool>>) { async fn wait_for_lock(locked: &mut watch::Receiver<Option<bool>>, allow_locked: bool) {
while locked.changed().await.is_ok() { while locked.changed().await.is_ok() {
if *locked.borrow_and_update() != Some(false) { return; } if !attempt_allowed(*locked.borrow_and_update(), allow_locked) { return; }
} }
} }
@@ -441,19 +506,19 @@ mod tests {
let wakes = AtomicUsize::new(0); let wakes = AtomicUsize::new(0);
let inhibitors = AtomicUsize::new(0); let inhibitors = AtomicUsize::new(0);
let cancelled = AtomicBool::new(true); let cancelled = AtomicBool::new(true);
assert!(prepare_attempt(&cancelled, &owner, &locked, assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) }, || { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none()); || { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
assert_eq!(wakes.load(Ordering::Relaxed), 0); assert_eq!(wakes.load(Ordering::Relaxed), 0);
cancelled.store(false, Ordering::Release); cancelled.store(false, Ordering::Release);
lock.send(Some(true)).unwrap(); lock.send(Some(true)).unwrap();
assert!(prepare_attempt(&cancelled, &owner, &locked, assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) }, || { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none()); || { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
assert_eq!(wakes.load(Ordering::Relaxed), 0); assert_eq!(wakes.load(Ordering::Relaxed), 0);
lock.send(Some(false)).unwrap(); lock.send(Some(false)).unwrap();
let locked_during_wake = lock.clone(); let locked_during_wake = lock.clone();
assert!(prepare_attempt(&cancelled, &owner, &locked, assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|| { || {
wakes.fetch_add(1, Ordering::Relaxed); wakes.fetch_add(1, Ordering::Relaxed);
locked_during_wake.send(Some(true)).unwrap(); locked_during_wake.send(Some(true)).unwrap();
@@ -464,7 +529,7 @@ mod tests {
assert_eq!(inhibitors.load(Ordering::Relaxed), 0); assert_eq!(inhibitors.load(Ordering::Relaxed), 0);
lock.send(Some(false)).unwrap(); lock.send(Some(false)).unwrap();
let replacement = input.desktop_session(); let replacement = input.desktop_session();
assert!(prepare_attempt(&cancelled, &owner, &locked, assert!(prepare_attempt(&cancelled, &owner, &locked, false,
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) }, || { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|| { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none()); || { inhibitors.fetch_add(1, Ordering::Relaxed); IdleGuard::default() }).is_none());
assert_eq!(wakes.load(Ordering::Relaxed), 1); assert_eq!(wakes.load(Ordering::Relaxed), 1);
@@ -479,6 +544,115 @@ mod tests {
drop(guard); drop(guard);
assert!(flag.load(Ordering::Acquire)); assert!(flag.load(Ordering::Acquire));
} }
#[test]
fn locked_capture_gate_follows_the_compositor_rule() {
assert!(attempt_allowed(Some(false), false));
assert!(!attempt_allowed(Some(true), false));
assert!(!attempt_allowed(None, false));
assert!(attempt_allowed(Some(true), true));
assert!(attempt_allowed(None, true));
}
#[test]
fn wake_and_retry_reset_once_per_lock_transition() {
assert!(fresh_state(None, Some(true)));
assert!(!fresh_state(Some(Some(true)), Some(true)));
assert!(fresh_state(Some(Some(true)), Some(false)));
assert!(!fresh_state(Some(Some(false)), Some(false)));
assert!(fresh_state(Some(Some(true)), None));
assert!(!fresh_state(Some(None), None));
}
#[test]
fn consent_failures_are_deferred_only_while_locked() {
for code in [4, 5] {
assert!(defer_consent(&PortalError { code }, Some(true)));
assert!(!defer_consent(&PortalError { code }, Some(false)));
assert!(!defer_consent(&PortalError { code }, None));
}
assert!(!defer_consent(&PortalError { code: 8 }, Some(true)));
assert!(!defer_consent(&PortalError { code: 13 }, Some(true)));
}
#[tokio::test]
async fn wait_for_lock_ends_on_a_lock_the_compositor_does_not_honor() {
use std::time::Duration;
let (lock, mut locked) = watch::channel(Some(false));
let mut task = tokio::spawn(async move { wait_for_lock(&mut locked, false).await; });
lock.send(Some(true)).unwrap();
tokio::time::timeout(Duration::from_secs(1), &mut task).await
.expect("lock must end the wait").unwrap();
}
#[tokio::test]
async fn wait_for_lock_ignores_lock_changes_when_capture_is_allowed() {
use std::time::Duration;
let (lock, mut locked) = watch::channel(Some(false));
let mut task = tokio::spawn(async move { wait_for_lock(&mut locked, true).await; });
lock.send(Some(true)).unwrap();
assert!(tokio::time::timeout(Duration::from_millis(100), &mut task).await.is_err(),
"lock cancelled an allowed wait");
lock.send(None).unwrap();
assert!(tokio::time::timeout(Duration::from_millis(100), &mut task).await.is_err(),
"unknown lock cancelled an allowed wait");
task.abort();
let _ = task.await;
}
#[test]
fn locked_attempt_is_allowed_when_the_compositor_keeps_the_stream() {
let input = Arc::new(crate::input::InputInjector::without_desktop());
let owner = input.desktop_session();
let (lock, locked) = watch::channel(Some(true));
let cancelled = AtomicBool::new(false);
let wakes = AtomicUsize::new(0);
assert!(prepare_attempt(&cancelled, &owner, &locked, true,
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|| IdleGuard::default()).is_some());
lock.send(None).unwrap();
assert!(prepare_attempt(&cancelled, &owner, &locked, true,
|| { wakes.fetch_add(1, Ordering::Relaxed); Ok(()) },
|| IdleGuard::default()).is_some());
assert_eq!(wakes.load(Ordering::Relaxed), 2);
}
#[tokio::test]
async fn locked_capture_keeps_the_attempt_running() {
use std::time::Duration;
let (lock, locked) = watch::channel(Some(false));
let host = Arc::new(PortalDesktop::with_lock_state_and_capture(
Arc::new(ScreenCapture::unavailable("pending".into())), locked, true));
let input = Arc::new(crate::input::InputInjector::without_desktop());
let owner = input.desktop_session();
let releases = Arc::new(AtomicUsize::new(0));
let worker_release = Arc::new(AtomicBool::new(false));
let (started, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
let task = tokio::spawn({
let host = host.clone();
let owner = owner.clone();
let releases = releases.clone();
let worker_release = worker_release.clone();
async move {
host.maintain_with(owner,
|| Ok(()),
move || IdleGuard(Some(Inhibitor::Fake(DropSignal(releases.clone())))),
move |screen, cancel| {
let _ = started.send(());
while !worker_release.load(Ordering::Acquire) && !cancel.load(Ordering::Acquire) {
std::thread::sleep(Duration::from_millis(1));
}
if cancel.load(Ordering::Acquire) { return Err(PortalError { code: 13 }); }
Ok(screen)
}).await
}
});
started_rx.recv().await.unwrap();
lock.send(Some(true)).unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
assert_eq!(releases.load(Ordering::Relaxed), 0, "lock released a compositor-backed attempt");
worker_release.store(true, Ordering::Release);
let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
while host.snapshot().waiting {
assert!(tokio::time::Instant::now() < deadline, "locked attempt did not publish");
tokio::task::yield_now().await;
}
task.abort();
let _ = task.await;
}
#[tokio::test] #[tokio::test]
async fn lock_transition_cancels_blocked_attempt_and_releases_inhibitor() { async fn lock_transition_cancels_blocked_attempt_and_releases_inhibitor() {
let (lock, locked) = watch::channel(Some(false)); let (lock, locked) = watch::channel(Some(false));
+39 -3
View File
@@ -12,7 +12,7 @@ mod record;
mod tool; mod tool;
pub use mode::Mode; pub use mode::Mode;
use std::sync::{atomic::{AtomicBool, Ordering}, Mutex}; use std::sync::{atomic::{AtomicBool, AtomicU64, Ordering}, Mutex};
struct Active { mode: Mode, record: Option<record::Record> } struct Active { mode: Mode, record: Option<record::Record> }
struct State { sessions: usize, active: Option<Active> } struct State { sessions: usize, active: Option<Active> }
@@ -25,6 +25,9 @@ static POINTER: Mutex<Option<[f64; 4]>> = Mutex::new(None);
/// ends. An auto-enable never overrides it, including an RPC that arrives after the connection /// ends. An auto-enable never overrides it, including an RPC that arrives after the connection
/// opens but before `session_started` bumps the counter. /// opens but before `session_started` bumps the counter.
static VIEWER_OVERRIDE: AtomicBool = AtomicBool::new(false); static VIEWER_OVERRIDE: AtomicBool = AtomicBool::new(false);
/// Bumped when a new first desktop session spawns its auto-enable thread. A reconnect that beats
/// the 500 ms poll would otherwise leave the old waiter running for up to five minutes.
static AUTO_GENERATION: AtomicU64 = AtomicU64::new(0);
/// iOS viewers encode "screen off" as `enable=0, type=3`, and Windows viewers carry every request /// iOS viewers encode "screen off" as `enable=0, type=3`, and Windows viewers carry every request
/// in `type` with `enable=0`; see `protocol::Request::normalize_ios_screen_off` and /// in `type` with `enable=0`; see `protocol::Request::normalize_ios_screen_off` and
/// `protocol::Request::normalize_windows`. /// `protocol::Request::normalize_windows`.
@@ -182,10 +185,42 @@ fn auto_set(mode: Mode) -> Result<bool, String> {
if result.is_err() { if let Err(e) = leave(&mut state) { log::warn!("Privacy rollback failed: {e}"); } } if result.is_err() { if let Err(e) = leave(&mut state) { log::warn!("Privacy rollback failed: {e}"); } }
result.map(|_| true) result.map(|_| true)
} }
/// The watch is authoritative while it has a value. A None (the logind monitor lost the session)
/// must not fail open: ask logind directly before covering a possibly locked desktop.
fn currently_locked() -> bool {
let locked = crate::session_lock::watch_locked();
let state = *locked.borrow();
match state {
Some(state) => state,
None => crate::session_lock::locked_now() == Some(true),
}
}
/// The capture session and the viewer's CONTROL state need a moment after the peer connects; /// The capture session and the viewer's CONTROL state need a moment after the peer connects;
/// retry while the portal session is still missing, and let the viewer's RPC 7 win if it arrives. /// retry while the portal session is still missing, and let the viewer's RPC 7 win if it arrives.
fn auto_enable(mode: Mode) { fn auto_enable(mode: Mode, generation: u64) {
// A locked desktop is already covered. Switching the share to the virtual output would hide
// the lock screen the viewer needs to unlock, so wait for the local unlock first. Bounded:
// a viewer that never unlocks, or leaves, must not hold this thread forever.
let current = || AUTO_GENERATION.load(Ordering::Acquire) == generation;
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
while currently_locked() {
if !current() { return; }
if VIEWER_OVERRIDE.load(Ordering::Relaxed) {
log::info!("Privacy auto: skipped, the viewer already chose a mode");
return;
}
if STATE.try_lock().is_ok_and(|state| state.sessions == 0) {
log::info!("Privacy auto: skipped, the desktop session ended");
return;
}
if std::time::Instant::now() >= deadline {
log::info!("Privacy auto: desktop stayed locked; not covering it");
return;
}
std::thread::sleep(std::time::Duration::from_millis(500));
}
for attempt in 1..=5 { for attempt in 1..=5 {
if !current() { return; }
if VIEWER_OVERRIDE.load(Ordering::Relaxed) { if VIEWER_OVERRIDE.load(Ordering::Relaxed) {
log::info!("Privacy auto: skipped, the viewer already chose a mode"); log::info!("Privacy auto: skipped, the viewer already chose a mode");
return; return;
@@ -215,9 +250,10 @@ pub fn session_started() {
let first = STATE.lock().ok().is_some_and(|mut s| { s.sessions += 1; s.sessions == 1 }); let first = STATE.lock().ok().is_some_and(|mut s| { s.sessions += 1; s.sessions == 1 });
let Some(mode) = auto else { return }; let Some(mode) = auto else { return };
if !first { return; } if !first { return; }
let generation = AUTO_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
std::thread::spawn(move || { std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(1500)); std::thread::sleep(std::time::Duration::from_millis(1500));
auto_enable(mode); auto_enable(mode, generation);
}); });
} }
pub fn session_ended() { pub fn session_ended() {
+1 -1
View File
@@ -712,7 +712,7 @@ impl WebRtcSession {
} }
let live = state.screen.init_error.is_none() let live = state.screen.init_error.is_none()
&& (cfg!(test) || state.screen.portal.as_ref().is_some_and(|portal| portal.is_alive())) && (cfg!(test) || state.screen.portal.as_ref().is_some_and(|portal| portal.is_alive()))
&& *manager.lock_state().borrow() == Some(false); && manager.capture_allowed(*manager.lock_state().borrow());
if live { break Some(state.screen); } if live { break Some(state.screen); }
tokio::time::sleep(std::time::Duration::from_millis(100)).await; tokio::time::sleep(std::time::Duration::from_millis(100)).await;
if channel.upgrade().is_none_or(|channel| channel.ready_state() != webrtc::data_channel::data_channel_state::RTCDataChannelState::Open) { return; } if channel.upgrade().is_none_or(|channel| channel.ready_state() != webrtc::data_channel::data_channel_state::RTCDataChannelState::Open) { return; }