Skip to content

An open-source remote desktop application designed for self-hosting, as an alternative to TeamViewer.

Fix/privacy mode2 initialization (#17090)

fufesou0d1cc898288d
diff --git a/libs/scrap/src/common/dxgi.rs b/libs/scrap/src/common/dxgi.rs
index 3cf816eb4..eabfc0690 100644
--- a/libs/scrap/src/common/dxgi.rs
+++ b/libs/scrap/src/common/dxgi.rs
@@ -38,6 +38,14 @@ impl Capturer {
pub fn height(&self) -> usize {
self.height
}
+
+ /// Check DXGI access without reading pixels; an unchanged desktop may return WouldBlock.
+ pub fn probe_frame(&mut self) -> io::Result<()> {
+ match self.inner.probe_frame() {
+ Err(ref error) if error.kind() == TimedOut => Err(WouldBlock.into()),
+ result => result,
+ }
+ }
}
impl TraitCapturer for Capturer {
diff --git a/libs/scrap/src/dxgi/mod.rs b/libs/scrap/src/dxgi/mod.rs
index 20c994eb9..b9afb41bc 100644
--- a/libs/scrap/src/dxgi/mod.rs
+++ b/libs/scrap/src/dxgi/mod.rs
@@ -437,6 +437,24 @@ impl Capturer {
self.output_texture = texture;
}
+ /// Probe duplication access without copying or mapping desktop pixels.
+ pub fn probe_frame(&mut self) -> io::Result<()> {
+ const NO_WAIT: UINT = 0;
+ if self.is_gdi() || self.duplication.is_null() {
+ return Err(io::ErrorKind::AddrNotAvailable.into());
+ }
+ // Release just before acquiring again to avoid redundant DXGI copies between polls.
+ self.release_frame()?;
+ let mut info = mem::MaybeUninit::<DXGI_OUTDUPL_FRAME_INFO>::uninit();
+ let mut frame = ptr::null_mut();
+ wrap_hresult(unsafe {
+ (*self.duplication.0).AcquireNextFrame(NO_WAIT, info.as_mut_ptr(), &mut frame)
+ })?;
+ self.frame_state = FrameState::Acquired;
+ drop(ComPtr(frame));
+ Ok(())
+ }
+
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
if self.duplication.0.is_null() {
return Err(io::ErrorKind::AddrNotAvailable.into());
diff --git a/src/privacy_mode.rs b/src/privacy_mode.rs
index 5757dee44..2daf63f5a 100644
--- a/src/privacy_mode.rs
+++ b/src/privacy_mode.rs
@@ -29,7 +29,7 @@ pub mod macos;
#[cfg(windows)]
mod win_virtual_display;
#[cfg(windows)]
-pub use win_virtual_display::restore_reg_connectivity;
+pub use win_virtual_display::{check_privacy_mode, restore_reg_connectivity};
pub const INVALID_PRIVACY_MODE_CONN_ID: i32 = 0;
pub const OCCUPIED: &'static str = "Privacy occupied by another one.";
@@ -63,6 +63,14 @@ pub trait PrivacyMode: Sync + Send {
fn get_impl_key(&self) -> &str;
+ #[cfg(windows)]
+ fn add_prepared_virtual_display(&mut self, _index: u32) -> ResultType<()> {
+ bail!(
+ "Prepared virtual displays are unsupported for {}",
+ self.get_impl_key()
+ );
+ }
+
#[inline]
fn check_on_conn_id(&self, conn_id: i32) -> ResultType<bool> {
let pre_conn_id = self.pre_conn_id();
@@ -213,11 +221,66 @@ fn get_supported_impl(impl_key: &str) -> String {
cur_impl
}
-pub async fn turn_on_privacy(impl_key: &str, conn_id: i32) -> Option<ResultType<bool>> {
+#[cfg(windows)]
+pub fn prepare_virtual_display(
+ impl_key: &str,
+ conn_id: i32,
+) -> ResultType<Option<oneshot::Receiver<ResultType<Option<u32>>>>> {
+ const LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
+ if get_supported_impl(impl_key) != PRIVACY_MODE_IMPL_WIN_VIRTUAL_DISPLAY
+ || !crate::virtual_display_manager::is_amyuni_idd()
+ || !crate::virtual_display_manager::is_virtual_display_supported()
+ || get_privacy_mode_conn_id()
+ .is_some_and(|owner| owner != INVALID_PRIVACY_MODE_CONN_ID && owner != conn_id)
+ {
+ return Ok(None);
+ }
+ let (tx, rx) = oneshot::channel();
+ std::thread::Builder::new()
+ .name("privacy-prepare".to_owned())
+ .spawn(move || {
+ let result =
+ crate::virtual_display_manager::amyuni_idd::prepare_privacy_monitor(|| {
+ tx.is_closed()
+ });
+ if let Err(Err(error)) = tx.send(result) {
+ hbb_common::throttled_log!(
+ LOG_INTERVAL,
+ debug,
+ "Privacy mode preparation ended after cancellation: {}",
+ error
+ );
+ }
+ })?;
+ Ok(Some(rx))
+}
+
+pub async fn turn_on_privacy(
+ impl_key: &str,
+ conn_id: i32,
+ #[cfg(windows)] prepared_display: Option<u32>,
+) -> Option<ResultType<bool>> {
+ #[cfg(windows)]
+ if get_supported_impl(impl_key) == PRIVACY_MODE_IMPL_WIN_VIRTUAL_DISPLAY
+ && crate::virtual_display_manager::is_amyuni_idd()
+ {
+ return turn_on_privacy_async(impl_key.to_string(), conn_id, prepared_display).await;
+ }
if is_async_privacy_mode() {
- turn_on_privacy_async(impl_key.to_string(), conn_id).await
+ turn_on_privacy_async(
+ impl_key.to_string(),
+ conn_id,
+ #[cfg(windows)]
+ prepared_display,
+ )
+ .await
} else {
- turn_on_privacy_sync(impl_key, conn_id)
+ turn_on_privacy_sync(
+ impl_key,
+ conn_id,
+ #[cfg(windows)]
+ prepared_display,
+ )
}
}
@@ -231,10 +294,19 @@ fn is_async_privacy_mode() -> bool {
}
#[inline]
-async fn turn_on_privacy_async(impl_key: String, conn_id: i32) -> Option<ResultType<bool>> {
+async fn turn_on_privacy_async(
+ impl_key: String,
+ conn_id: i32,
+ #[cfg(windows)] prepared_display: Option<u32>,
+) -> Option<ResultType<bool>> {
let (tx, rx) = oneshot::channel();
std::thread::spawn(move || {
- let res = turn_on_privacy_sync(&impl_key, conn_id);
+ let res = turn_on_privacy_sync(
+ &impl_key,
+ conn_id,
+ #[cfg(windows)]
+ prepared_display,
+ );
let _ = tx.send(res);
});
// Wait at most 7.5 seconds for the result.
@@ -249,7 +321,11 @@ async fn turn_on_privacy_async(impl_key: String, conn_id: i32) -> Option<ResultT
}
}
-fn turn_on_privacy_sync(impl_key: &str, conn_id: i32) -> Option<ResultType<bool>> {
+fn turn_on_privacy_sync(
+ impl_key: &str,
+ conn_id: i32,
+ #[cfg(windows)] prepared_display: Option<u32>,
+) -> Option<ResultType<bool>> {
// Check if privacy mode is already on or occupied by another one
let mut privacy_mode_lock = PRIVACY_MODE.lock().unwrap();
@@ -290,8 +366,16 @@ fn turn_on_privacy_sync(impl_key: &str, conn_id: i32) -> Option<ResultType<bool>
}
}
+ let privacy_mode = privacy_mode_lock.as_mut()?;
+ #[cfg(windows)]
+ if let Some(index) = prepared_display {
+ if let Err(error) = privacy_mode.add_prepared_virtual_display(index) {
+ return Some(Err(error));
+ }
+ }
+
// turn on privacy mode
- Some(privacy_mode_lock.as_mut()?.turn_on_privacy(conn_id))
+ Some(privacy_mode.turn_on_privacy(conn_id))
}
#[cfg(not(target_os = "ios"))]
diff --git a/src/privacy_mode/win_virtual_display.rs b/src/privacy_mode/win_virtual_display.rs
index f521cbacb..532a7a4e7 100644
--- a/src/privacy_mode/win_virtual_display.rs
+++ b/src/privacy_mode/win_virtual_display.rs
@@ -1,6 +1,8 @@
use super::{PrivacyMode, PrivacyModeState, INVALID_PRIVACY_MODE_CONN_ID, NO_PHYSICAL_DISPLAYS};
use crate::{platform::windows::reg_display_settings, virtual_display_manager};
-use hbb_common::{allow_err, bail, config::Config, log, ResultType};
+use hbb_common::{
+ allow_err, bail, config::Config, log, tokio::sync::mpsc::UnboundedSender, ResultType,
+};
use std::{
io::Error,
ops::{Deref, DerefMut},
@@ -30,6 +32,104 @@ use winapi::{
pub(super) const PRIVACY_MODE_IMPL: &str = super::PRIVACY_MODE_IMPL_WIN_VIRTUAL_DISPLAY;
const CONFIG_KEY_REG_RECOVERY: &str = "reg_recovery";
+const STATE_CHECK_LOG_INTERVAL: Duration = Duration::from_secs(60);
+
+fn check_active_displays(displays: impl Iterator<Item = DISPLAY_DEVICEW>) -> ResultType<()> {
+ let device_string: Vec<u16> = virtual_display_manager::get_cur_device_string()
+ .encode_utf16()
+ .collect();
+ let mut has_virtual_display = false;
+ for display in displays {
+ // Inactive outputs are not part of the desktop. Mirror drivers expose
+ // invisible pseudo-monitors, not active physical screens.
+ if display.StateFlags & DISPLAY_DEVICE_ACTIVE == 0
+ || display.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER != 0
+ {
+ continue;
+ }
+ if !display.DeviceString.starts_with(&device_string) {
+ bail!("Physical display is still active.");
+ }
+ has_virtual_display = true;
+ }
+ if !has_virtual_display {
+ bail!("No active virtual displays.");
+ }
+ Ok(())
+}
+
+fn check_current_displays() -> ResultType<()> {
+ check_active_displays((0..).map_while(|index| {
+ let mut display: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() };
+ display.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as _;
+ let result = unsafe { EnumDisplayDevicesW(std::ptr::null(), index, &mut display, 0) };
+ (result != FALSE).then_some(display)
+ }))
+}
+
+fn notify_privacy_mode_exit<'a>(
+ connections: impl IntoIterator<Item = (i32, &'a UnboundedSender<crate::ipc::Data>)>,
+ owner_id: i32,
+) -> ResultType<()> {
+ let Some((_, sender)) = connections
+ .into_iter()
+ .find(|(conn_id, _)| *conn_id == owner_id)
+ else {
+ bail!("Privacy mode owner connection {} is unavailable.", owner_id);
+ };
+ sender.send(crate::ipc::Data::PrivacyModeState((
+ owner_id,
+ PrivacyModeState::OffUnknown,
+ PRIVACY_MODE_IMPL.to_owned(),
+ )))?;
+ Ok(())
+}
+
+pub fn check_privacy_mode() {
+ // Retry next tick while another thread activates or restores privacy mode.
+ let mut privacy_mode = match super::PRIVACY_MODE.try_lock() {
+ Ok(privacy_mode) => privacy_mode,
+ Err(std::sync::TryLockError::WouldBlock) => return,
+ Err(error) => {
+ hbb_common::throttled_log!(
+ STATE_CHECK_LOG_INTERVAL,
+ error,
+ "Cannot check privacy mode: {}",
+ error
+ );
+ return;
+ }
+ };
+ let Some(privacy_mode) = privacy_mode.as_mut() else {
+ return;
+ };
+ let conn_id = privacy_mode.pre_conn_id();
+ if conn_id == INVALID_PRIVACY_MODE_CONN_ID || privacy_mode.get_impl_key() != PRIVACY_MODE_IMPL {
+ return;
+ }
+ let Err(error) = check_current_displays() else {
+ return;
+ };
+
+ let cleanup = privacy_mode.turn_off_privacy(conn_id, None);
+ // The connection manager may be absent; notify the owner through its server channel.
+ let notification = {
+ let connections = crate::server::AUTHED_CONNS.lock().unwrap();
+ notify_privacy_mode_exit(
+ connections.iter().map(|conn| (conn.conn_id, &conn.sender)),
+ conn_id,
+ )
+ };
+ hbb_common::throttled_log!(
+ STATE_CHECK_LOG_INTERVAL,
+ error,
+ "Privacy mode is no longer active: {}; conn_id: {}; cleanup: {:?}; notification: {:?}",
+ error,
+ conn_id,
+ cleanup,
+ notification
+ );
+}
struct Display {
dm: DEVMODEW,
@@ -444,6 +544,12 @@ impl PrivacyModeImpl {
}
impl PrivacyMode for PrivacyModeImpl {
+ fn add_prepared_virtual_display(&mut self, index: u32) -> ResultType<()> {
+ // Preparation created this monitor before ensure_virtual_display could record it.
+ self.virtual_displays_added.push(index);
+ Ok(())
+ }
+
fn is_async_privacy_mode(&self) -> bool {
virtual_display_manager::is_amyuni_idd()
}
@@ -506,6 +612,8 @@ impl PrivacyMode for PrivacyModeImpl {
reset_config_reg_connectivity();
};
+ check_current_displays()?;
+
// OpenInputDesktop and block the others' input ?
guard.conn_id = conn_id;
guard.succeeded = true;
@@ -584,3 +692,64 @@ pub fn restore_reg_connectivity(plug_out_monitors: bool, force: bool) {
}
reset_config_reg_connectivity();
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use hbb_common::tokio::sync::mpsc::{error::TryRecvError, unbounded_channel};
+
+ #[test]
+ fn privacy_mode_checks_active_displays() {
+ let virtual_name = virtual_display_manager::get_cur_device_string();
+ let active = DISPLAY_DEVICE_ACTIVE;
+ let mirror = active | DISPLAY_DEVICE_MIRRORING_DRIVER;
+ for (devices, expected) in [
+ (
+ vec![(virtual_name, active), ("Physical display\0", active)],
+ false,
+ ),
+ (
+ vec![
+ (virtual_name, active),
+ ("Physical display\0", 0),
+ ("Mirror display\0", mirror),
+ ],
+ true,
+ ),
+ (vec![(virtual_name, 0)], false),
+ ] {
+ let displays = devices.into_iter().map(|(name, flags)| {
+ let mut display: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() };
+ display.StateFlags = flags;
+ for (target, value) in display.DeviceString.iter_mut().zip(name.encode_utf16()) {
+ *target = value;
+ }
+ display
+ });
+ assert_eq!(check_active_displays(displays).is_ok(), expected);
+ }
+ }
+
+ #[test]
+ fn privacy_mode_exit_uses_owner_channel_without_cm() {
+ const OWNER_CONN_ID: i32 = 1;
+ const OTHER_CONN_ID: i32 = 2;
+ let (owner_sender, mut owner_receiver) = unbounded_channel();
+ let (other_sender, mut other_receiver) = unbounded_channel();
+ let connections = [
+ (OWNER_CONN_ID, &owner_sender),
+ (OTHER_CONN_ID, &other_sender),
+ ];
+
+ assert!(notify_privacy_mode_exit([], OWNER_CONN_ID).is_err());
+ notify_privacy_mode_exit(connections, OWNER_CONN_ID).unwrap();
+ assert!(matches!(
+ owner_receiver.try_recv().unwrap(),
+ crate::ipc::Data::PrivacyModeState((OWNER_CONN_ID, PrivacyModeState::OffUnknown, impl_key))
+ if impl_key == PRIVACY_MODE_IMPL
+ ));
+ assert_eq!(other_receiver.try_recv().err(), Some(TryRecvError::Empty));
+ drop(owner_receiver);
+ assert!(notify_privacy_mode_exit(connections, OWNER_CONN_ID).is_err());
+ }
+}
diff --git a/src/server/connection.rs b/src/server/connection.rs
index 1fbee2439..6773a1953 100644
--- a/src/server/connection.rs
+++ b/src/server/connection.rs
@@ -385,6 +385,12 @@ pub struct Connection {
recording: bool,
block_input: bool,
privacy_mode: bool,
+ // Dropping the receiver cancels the pending activation.
+ #[cfg(windows)]
+ privacy_preparation: Option<(
+ String,
+ hbb_common::tokio::sync::oneshot::Receiver<ResultType<Option<u32>>>,
+ )>,
control_permissions: Option<ControlPermissions>,
last_test_delay: Option<Instant>,
network_delay: u32,
@@ -600,6 +606,8 @@ impl Connection {
recording: Self::permission(keys::OPTION_ENABLE_RECORD_SESSION, &control_permissions),
block_input: Self::permission(keys::OPTION_ENABLE_BLOCK_INPUT, &control_permissions),
privacy_mode: Self::permission(keys::OPTION_ENABLE_PRIVACY_MODE, &control_permissions),
+ #[cfg(windows)]
+ privacy_preparation: None,
control_permissions,
last_test_delay: None,
network_delay: 0,
@@ -875,6 +883,10 @@ impl Connection {
conn.block_input = enabled;
conn.send_permission(Permission::BlockInput, enabled).await;
} else if &name == "privacy_mode" {
+ #[cfg(windows)]
+ if !enabled {
+ conn.privacy_preparation = None;
+ }
// Keep permission state and runtime state consistent:
// when revoking the permission, try to leave privacy mode first.
// Otherwise we could end up in an inconsistent state where
@@ -947,6 +959,8 @@ impl Connection {
}
}
ipc::Data::PrivacyModeState((_, state, impl_key)) => {
+ #[cfg(windows)]
+ conn.privacy_preparation.take();
let msg_out = match state {
privacy_mode::PrivacyModeState::OffSucceeded => {
crate::common::make_privacy_mode_msg(
@@ -1163,6 +1177,16 @@ impl Connection {
conn.on_close("privacy mode", false).await;
break;
}
+ #[cfg(windows)]
+ ipc::Data::PrivacyModeState((_, privacy_mode::PrivacyModeState::OffUnknown, impl_key)) => {
+ if privacy_mode::get_cur_impl_key().as_deref() == Some(impl_key.as_str()) {
+ conn.privacy_preparation = None;
+ conn.send(crate::common::make_privacy_mode_msg(
+ back_notification::PrivacyModeState::PrvOffUnknown,
+ impl_key,
+ )).await;
+ }
+ }
#[cfg(all(target_os = "windows", feature = "flutter"))]
ipc::Data::PrinterData(data) => {
if Self::permission(keys::OPTION_ENABLE_REMOTE_PRINTER, &conn.control_permissions) {
@@ -1177,6 +1201,11 @@ impl Connection {
_ = second_timer.tick() => {
#[cfg(windows)]
conn.portable_check();
+ #[cfg(windows)]
+ if let Some((impl_key, _)) = conn.privacy_preparation.as_ref() {
+ let impl_key = impl_key.clone();
+ conn.turn_on_privacy(impl_key).await;
+ }
raii::AuthedConnID::check_wake_lock_on_setting_changed();
if let Some((instant, minute)) = conn.auto_disconnect_timer.as_ref() {
if instant.elapsed().as_secs() > minute * 60 {
@@ -5183,8 +5212,40 @@ impl Connection {
}
}
+ // Return while pending instead of awaiting here: the connection must keep
+ // processing remote input and video while its timer polls for completion.
+ #[cfg(windows)]
+ fn poll_privacy_preparation(
+ &mut self,
+ impl_key: &str,
+ ) -> ResultType<std::task::Poll<Option<u32>>> {
+ use hbb_common::tokio::sync::oneshot::error::TryRecvError;
+ use std::task::Poll;
+ if matches!(&self.privacy_preparation, Some((key, _)) if key != impl_key) {
+ self.privacy_preparation = None;
+ }
+ if let Some((_, receiver)) = self.privacy_preparation.as_mut() {
+ let result = match receiver.try_recv() {
+ Ok(result) => result,
+ Err(TryRecvError::Empty) => return Ok(Poll::Pending),
+ Err(error) => Err(error.into()),
+ };
+ self.privacy_preparation = None;
+ return result.map(Poll::Ready);
+ }
+ self.privacy_preparation = privacy_mode::prepare_virtual_display(impl_key, self.inner.id)?
+ .map(|receiver| (impl_key.to_owned(), receiver));
+ Ok(if self.privacy_preparation.is_some() {
+ Poll::Pending
+ } else {
+ Poll::Ready(None)
+ })
+ }
+
async fn turn_on_privacy(&mut self, impl_key: String) {
if !self.is_authed_remote_conn() || !self.privacy_mode {
+ #[cfg(windows)]
+ self.privacy_preparation.take();
let msg_out = crate::common::make_privacy_mode_msg(
back_notification::PrivacyModeState::PrvOnFailedDenied,
impl_key,
@@ -5193,6 +5254,28 @@ impl Connection {
return;
}
+ #[cfg(windows)]
+ let prepared_display = match self.poll_privacy_preparation(&impl_key) {
+ Ok(std::task::Poll::Pending) => return,
+ Ok(std::task::Poll::Ready(display)) => display,
+ Err(error) => {
+ const LOG_INTERVAL: Duration = Duration::from_secs(1);
+ hbb_common::throttled_log!(
+ LOG_INTERVAL,
+ error,
+ "Failed to prepare privacy mode: {}",
+ error
+ );
+ self.send(crate::common::make_privacy_mode_msg_with_details(
+ back_notification::PrivacyModeState::PrvOnFailed,
+ error.to_string(),
+ impl_key,
+ ))
+ .await;
+ return;
+ }
+ };
+
let msg_out = if !privacy_mode::is_privacy_mode_supported() {
crate::common::make_privacy_mode_msg_with_details(
back_notification::PrivacyModeState::PrvNotSupported,
@@ -5215,7 +5298,13 @@ impl Connection {
}
}
- let turn_on_res = privacy_mode::turn_on_privacy(&impl_key, self.inner.id).await;
+ let turn_on_res = privacy_mode::turn_on_privacy(
+ &impl_key,
+ self.inner.id,
+ #[cfg(windows)]
+ prepared_display,
+ )
+ .await;
match turn_on_res {
Some(Ok(res)) => {
if res {
@@ -5274,6 +5363,17 @@ impl Connection {
}
async fn turn_off_privacy(&mut self, impl_key: String) {
+ #[cfg(windows)]
+ if self.privacy_preparation.take().is_some() && !privacy_mode::is_in_privacy_mode() {
+ // The worker cleans up preparation. Restoring an inactive Mode 2 here
+ // would unplug all virtual displays and race that cleanup.
+ self.send(crate::common::make_privacy_mode_msg(
+ back_notification::PrivacyModeState::PrvOffSucceeded,
+ impl_key,
+ ))
+ .await;
+ return;
+ }
let msg_out = if !privacy_mode::is_privacy_mode_supported() {
crate::common::make_privacy_mode_msg_with_details(
back_notification::PrivacyModeState::PrvNotSupported,
@@ -5324,6 +5424,8 @@ impl Connection {
return;
}
self.closed = true;
+ #[cfg(windows)]
+ self.privacy_preparation.take();
// If voice A,B -> C, and A,B has voice call
// B disconnects, C will reset the voice call input.
//
diff --git a/src/server/display_service.rs b/src/server/display_service.rs
index 111c746e2..fc8ed83d8 100644
--- a/src/server/display_service.rs
+++ b/src/server/display_service.rs
@@ -716,6 +716,9 @@ fn run(sp: EmptyExtraFieldService) -> ResultType<()> {
Ok(())
})?;
+ #[cfg(windows)]
+ crate::privacy_mode::check_privacy_mode();
+
if let Some(msg_out) = check_get_displays_changed_msg() {
sp.send(msg_out);
log::info!("Displays changed");
diff --git a/src/virtual_display_manager.rs b/src/virtual_display_manager.rs
index c7bbd518f..2e7dccd2d 100644
--- a/src/virtual_display_manager.rs
+++ b/src/virtual_display_manager.rs
@@ -406,6 +406,16 @@ pub mod amyuni_idd {
const HARDWARE_ID: &str = "usbmmidd";
const PLUG_MONITOR_IO_CONTROL_CDOE: u32 = 2307084;
const INSTALLER_EXE_FILE: &str = "deviceinstaller64.exe";
+ const DIAGNOSTIC_LOG_INTERVAL: Duration = Duration::from_secs(1);
+ const PRIVACY_INITIALIZATION_TIMEOUT: Duration = Duration::from_secs(20);
+ // First-install traces show resets after PnP is idle and the monitor is visible.
+ // This quiet interval is an empirical margin, not an initialization-complete signal.
+ const PRIVACY_DISPLAY_STABLE_FOR: Duration = Duration::from_secs(5);
+ const PRIVACY_INITIALIZATION_POLL: Duration = Duration::from_millis(300);
+ const PRIVACY_MONITOR_TIMEOUT: Duration = Duration::from_secs(6);
+ const PRIVACY_MONITOR_INDEX: u32 = 0;
+ // Accessed under PREPARATION_LOCK; failed first-install work must survive retries.
+ static PRIVACY_INITIALIZATION_PENDING: atomic::AtomicBool = atomic::AtomicBool::new(false);
lazy_static::lazy_static! {
static ref LOCK: Arc<Mutex<()>> = Default::default();
@@ -486,7 +496,8 @@ pub mod amyuni_idd {
// If the driver is installed by "deviceinstaller64.exe", the driver will be installed asynchronously.
// The caller must wait some time before using the driver.
- fn check_install_driver(is_async: &mut bool) -> ResultType<()> {
+ // Returns whether this call started driver installation.
+ fn check_install_driver(is_async: &mut bool) -> ResultType<bool> {
let _l = LOCK.lock().unwrap();
let drivers = windows::get_display_drivers();
if drivers
@@ -494,7 +505,7 @@ pub mod amyuni_idd {
.any(|(s, c)| s == super::AMYUNI_IDD_DEVICE_STRING && *c == 0)
{
*is_async = false;
- return Ok(());
+ return Ok(false);
}
if let Ok(Some(work_dir)) = get_deviceinstaller64_work_dir() {
@@ -502,7 +513,7 @@ pub mod amyuni_idd {
log::info!("Installing driver by deviceinstaller64.exe");
install_if_x86_on_x64(&work_dir, "install usbmmidd.inf usbmmidd")?;
*is_async = true;
- return Ok(());
+ return Ok(true);
}
}
@@ -521,7 +532,7 @@ pub mod amyuni_idd {
let _ =
unsafe { win_device::install_driver(&inf_path, HARDWARE_ID, &mut reboot_required)? };
*is_async = false;
- Ok(())
+ Ok(true)
}
pub fn reset_all() -> ResultType<()> {
@@ -659,6 +670,207 @@ pub mod amyuni_idd {
plug_in_monitor_(true, is_async, None)
}
+ fn privacy_initialization_capturer(reason: &str) -> ResultType<scrap::Capturer> {
+ use scrap::TraitCapturer;
+
+ let started = Instant::now();
+ // DXGI allows one duplication per output per process. The video service
+ // may already own the physical output; observe the monitor we just created.
+ let display = scrap::Display::all()?
+ .into_iter()
+ .find(|display| is_my_display(&display.name()))
+ .ok_or_else(|| {
+ hbb_common::anyhow::anyhow!("No active Amyuni display during initialization.")
+ })?;
+ let display_name = display.name();
+ let capturer = scrap::Capturer::new(display)?;
+ hbb_common::throttled_log!(
+ DIAGNOSTIC_LOG_INTERVAL,
+ info,
+ "First-use DXGI probe created: display={}, reason={}, elapsed={:?}, gdi={}, pixel_readback=false",
+ display_name,
+ reason,
+ started.elapsed(),
+ capturer.is_gdi()
+ );
+ Ok(capturer)
+ }
+
+ // Observe independently: session capture may fall back to GDI during initialization.
+ fn wait_for_privacy_display_stability() -> ResultType<()> {
+ use scrap::TraitCapturer;
+ use std::io::ErrorKind;
+
+ let started = Instant::now();
+ let mut capturer = privacy_initialization_capturer("initial");
+ let mut stable_since = Instant::now();
+ while started.elapsed() < PRIVACY_INITIALIZATION_TIMEOUT {
+ let capture = match capturer.as_mut() {
+ Ok(capture) if !capture.is_gdi() => capture,
+ _ => {
+ hbb_common::throttled_log!(
+ DIAGNOSTIC_LOG_INTERVAL, warn,
+ "Cannot observe DXGI initialization (GDI or error: {:?}); retrying within {:?} first-install wait",
+ capturer.as_ref().err(), PRIVACY_INITIALIZATION_TIMEOUT
+ );
+ drop(capturer);
+ std::thread::sleep(PRIVACY_INITIALIZATION_POLL);
+ capturer = privacy_initialization_capturer("retry");
+ stable_since = Instant::now();
+ continue;
+ }
+ };
+ // A static desktop can time out without losing the duplication interface.
+ match capture.probe_frame() {
+ Ok(()) => {}
+ Err(error) if error.kind() == ErrorKind::WouldBlock => {}
+ Err(error) if error.kind() == ErrorKind::ConnectionReset => {
+ drop(capturer);
+ capturer = privacy_initialization_capturer("access_lost");
+ stable_since = Instant::now();
+ }
+ Err(error) => {
+ capturer = Err(error.into());
+ continue;
+ }
+ }
+ if stable_since.elapsed() >= PRIVACY_DISPLAY_STABLE_FOR {
+ hbb_common::throttled_log!(
+ DIAGNOSTIC_LOG_INTERVAL,
+ info,
+ "First-use display capture stable for {:?} after {:?}",
+ PRIVACY_DISPLAY_STABLE_FOR,
+ started.elapsed()
+ );
+ return Ok(());
+ }
+ std::thread::sleep(PRIVACY_INITIALIZATION_POLL);
+ }
+ privacy_display_stability_timeout(&capturer)
+ }
+
+ fn privacy_display_stability_timeout(capturer: &ResultType<scrap::Capturer>) -> ResultType<()> {
+ use scrap::TraitCapturer;
+
+ if matches!(capturer, Ok(capture) if !capture.is_gdi()) {
+ bail!("Timed out waiting for display initialization to stabilize.");
+ }
+ // GDI cannot establish readiness; retain the full-wait fallback only at the deadline.
+ hbb_common::throttled_log!(
+ DIAGNOSTIC_LOG_INTERVAL, warn,
+ "Cannot observe DXGI initialization (GDI or error: {:?}); proceeding after {:?} first-install wait",
+ capturer.as_ref().err(), PRIVACY_INITIALIZATION_TIMEOUT
+ );
+ Ok(())
+ }
+
+ fn finish_privacy_initialization() -> ResultType<()> {
+ if PRIVACY_INITIALIZATION_PENDING.load(atomic::Ordering::Relaxed) {
+ wait_for_privacy_display_stability()?;
+ // The full-wait fallback can finish after reset_all removed the output.
+ if get_monitor_count() == 0 {
+ bail!("No active virtual displays after privacy mode preparation.");
+ }
+ PRIVACY_INITIALIZATION_PENDING.store(false, atomic::Ordering::Relaxed);
+ }
+ Ok(())
+ }
+
+ fn lock_privacy_preparation<'a>(
+ lock: &'a Mutex<()>,
+ cancelled: impl Fn() -> bool,
+ ) -> ResultType<std::sync::MutexGuard<'a, ()>> {
+ // A cancelled first-install worker still finishes initialization. Let retries
+ // wait for it, but release cancelled waiters without waiting for the lock.
+ loop {
+ if cancelled() {
+ bail!("Privacy mode preparation cancelled.");
+ }
+ match lock.try_lock() {
+ Ok(preparation) => return Ok(preparation),
+ Err(std::sync::TryLockError::WouldBlock) => {
+ std::thread::sleep(PRIVACY_INITIALIZATION_POLL);
+ }
+ Err(error) => bail!("Privacy mode preparation is unavailable: {}", error),
+ }
+ }
+ }
+
+ fn cleanup_prepared_monitor() -> ResultType<()> {
+ let monitor_count = get_monitor_count();
+ if monitor_count == 0 {
+ // The driver can create an inactive monitor that enumeration misses.
+ // Undo its request directly; normal unplug may reject a physical-only layout.
+ plug_monitor_(false, None)?;
+ return Ok(());
+ }
+ // Keep single-monitor safety checks here because plug_out_monitor
+ // discards driver errors in its bulk-removal loop.
+ if VIRTUAL_DISPLAY_COUNT.load(atomic::Ordering::Relaxed) == 0 {
+ bail!("The virtual display is managed by other processes.");
+ }
+ match windows::get_device_names(None).len() {
+ 0 => return Ok(()),
+ 1 => bail!("This only virtual display cannot be plugged out."),
+ _ => {}
+ }
+ // Keep preparation serialized until removal is visible to the next attempt.
+ plug_monitor_(false, Some(PRIVACY_MONITOR_TIMEOUT))?;
+ if get_monitor_count() >= monitor_count {
+ bail!("Virtual display count did not decrease after preparation cleanup.");
+ }
+ Ok(())
+ }
+
+ pub fn prepare_privacy_monitor(cancelled: impl Fn() -> bool) -> ResultType<Option<u32>> {
+ static PREPARATION_LOCK: Mutex<()> = Mutex::new(());
+ let _preparation = lock_privacy_preparation(&PREPARATION_LOCK, &cancelled)?;
+ if cancelled() {
+ bail!("Privacy mode preparation cancelled.");
+ }
+ if get_monitor_count() > 0 {
+ finish_privacy_initialization()?;
+ return Ok(None);
+ }
+ if windows::get_device_names(None).is_empty() {
+ bail!(crate::privacy_mode::NO_PHYSICAL_DISPLAYS);
+ }
+ let mut is_async = false;
+ if check_install_driver(&mut is_async)? {
+ PRIVACY_INITIALIZATION_PENDING.store(true, atomic::Ordering::Relaxed);
+ }
+ if get_monitor_count() == VIRTUAL_DISPLAY_MAX_COUNT {
+ bail!("There are already {VIRTUAL_DISPLAY_MAX_COUNT} monitors plugged in.");
+ }
+ plug_in_monitor_(true, is_async, Some(PRIVACY_MONITOR_TIMEOUT))?;
+ // Complete observation even if cancelled, so a retry can reuse the result.
+ if let Err(error) = finish_privacy_initialization() {
+ let cleanup = cleanup_prepared_monitor();
+ hbb_common::throttled_log!(
+ DIAGNOSTIC_LOG_INTERVAL,
+ error,
+ "First-use display initialization failed: {}; cleanup: {:?}",
+ error,
+ cleanup
+ );
+ return Err(error);
+ }
+ if cancelled() {
+ cleanup_prepared_monitor()?;
+ bail!("Privacy mode preparation cancelled.");
+ }
+ if get_monitor_count() == 0 {
+ if let Err(error) = cleanup_prepared_monitor() {
+ bail!(
+ "No active virtual displays; preparation cleanup failed: {}",
+ error
+ );
+ }
+ bail!("No active virtual displays after privacy mode preparation.");
+ }
+ Ok(Some(PRIVACY_MONITOR_INDEX))
+ }
+
// `index` the display index to plug out. -1 means plug out all.
// `force_all` is used to forcibly plug out all virtual displays.
// `force_one` is used to forcibly plug out one virtual display managed by other processes
@@ -736,6 +948,48 @@ pub mod amyuni_idd {
.iter()
.any(|s| windows::is_device_name(s, name))
}
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+ use std::sync::mpsc::{channel, RecvTimeoutError};
+
+ #[test]
+ fn privacy_preparation_waits_and_can_be_cancelled() {
+ const PENDING_CHECK: Duration = Duration::from_millis(100);
+ const COMPLETION_TIMEOUT: Duration = Duration::from_secs(2);
+ for cancel in [false, true] {
+ let lock = Mutex::new(());
+ let mut held = Some(lock.lock().unwrap());
+ let cancelled = atomic::AtomicBool::new(false);
+ let (sender, receiver) = channel();
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ let result = lock_privacy_preparation(&lock, || {
+ cancelled.load(atomic::Ordering::Relaxed)
+ })
+ .map(|_| ());
+ sender.send(result).unwrap();
+ });
+ assert!(matches!(
+ receiver.recv_timeout(PENDING_CHECK),
+ Err(RecvTimeoutError::Timeout)
+ ));
+ if cancel {
+ cancelled.store(true, atomic::Ordering::Relaxed);
+ } else {
+ drop(held.take());
+ }
+ let result = receiver.recv_timeout(COMPLETION_TIMEOUT).unwrap();
+ if cancel {
+ assert!(result.unwrap_err().to_string().contains("cancelled"));
+ } else {
+ result.unwrap();
+ }
+ });
+ }
+ }
+ }
}
mod windows {