Files
hello-agent/vendor/rustdesk/libs/virtual_display/src/lib.rs
T
mike f8ead215d8
build-windows / build-hello-agent-x64 (push) Successful in 5m41s
Initial commit: hello-agent — headless RustDesk-protocol-compatible Windows agent
A single-binary, Flutter-free remote-support agent that speaks the stock
RustDesk wire protocol. Designed for one-line MDM deployment against a
self-hosted rustdesk-server: a supporter using the unmodified rustdesk.exe
client connects, the controlled-side user gets a native Win32 approval
prompt, click Yes / No.

CLI surface

    hello-agent.exe --install                # register + start service
    hello-agent.exe --uninstall              # stop, delete, clean up
    hello-agent.exe --config <BLOB>          # admin-UI deploy string
    hello-agent.exe --install --config <BLOB>   # MDM one-liner

--config accepts both forms emitted by the rustdesk-server admin UI: the
reversed-base64 deploy string and the host=,key=,api=,relay= filename
form. Decoded via the upstream custom_server module, persisted via
hbb_common::config::Config::set_option.

Architecture

    --service runs as a Session 0 LocalSystem service. It polls
    WTSGetActiveConsoleSessionId and (re)spawns hello-agent.exe --server
    into the active console session via librustdesk::platform::run_as_user,
    handling the Session 0 → user-session token impersonation.

    --server is the worker. It boots three concurrent components:
      1. cm_popup: an IPC listener on the rustdesk `_cm` named pipe
      2. librustdesk::start_server(true, false): the upstream protocol
         stack — rendezvous mediator, NAT punch, IPC server, screen
         capture, login validation, hbbs_http heartbeat / sysinfo sync
      3. (implicit) ApproveMode::Click is pinned in config, so every
         incoming connection routes through cm_popup

The popup mechanism reuses an existing upstream contract without any
patches to the protocol code: when a peer connects with no password,
Connection::start in the upstream code calls try_start_cm_ipc, which
ipc::connect-s the `_cm` pipe before falling back to spawning a Flutter
CM child. Since cm_popup is up first, step 1 succeeds; we read the
Data::Login{authorized:false} frame, show MessageBoxTimeoutW (Yes/No,
60s, top-most, system-modal), and reply Data::Authorize or Data::Close.

Source tree

    src/main.rs             CLI dispatcher + run_server() composition
    src/cli.rs              hand-rolled argv parser + unit tests
    src/service.rs          windows-service install/uninstall/dispatcher
    src/config_import.rs    --config blob decoding + persistence
    src/cm_popup.rs         _cm IPC listener + Win32 approval dialog

Vendoring

The upstream RustDesk crate is vendored under vendor/rustdesk/ — full
workspace including libs/{hbb_common, scrap, enigo, clipboard,
virtual_display, remote_printer}. This makes the build self-contained
(no submodules, no sibling-repo checkout in CI) and gives us freedom to
fork in a different direction later. Excluded from the vendor: .git,
target/, flutter/, appimage/, flatpak/, fastlane/, docs/, examples/,
ci/, build.py, Dockerfile, upstream README/CLAUDE/AGENTS/GEMINI.

One local divergence vs. upstream: vendor/rustdesk/src/lib.rs flips
`mod custom_server` → `pub mod custom_server` so config_import.rs can
call get_custom_server_from_string without going through the
ui_interface shim. Documented in README.md → "Re-syncing the vendored
copy".

CI

.gitea/workflows/build-windows.yml builds on a self-hosted Windows
runner with Rust 1.75, LLVM 15.0.6 (libclang for bindgen via libvpx-sys),
and a vcpkg cache. The vendored vcpkg.json drives x64-windows-static
deps. The workflow stages the resulting hello-agent.exe into
SignOutput\, reports authenticode signing status (warns on unsigned),
and uploads as artifact. ~15 min full build, faster on incremental.

Out of scope for this commit: Linux/macOS builds, code signing, MSI
packaging, coexistence with stock rustdesk on the same box (currently
shares the RustDesk APP_NAME and config dir).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 16:29:31 +02:00

197 lines
5.5 KiB
Rust

use hbb_common::{anyhow, dlopen::symbor::Library, log, ResultType};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
};
const LIB_NAME_VIRTUAL_DISPLAY: &str = "dylib_virtual_display";
pub type DWORD = ::std::os::raw::c_ulong;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _MonitorMode {
pub width: DWORD,
pub height: DWORD,
pub sync: DWORD,
}
pub type MonitorMode = _MonitorMode;
pub type PMonitorMode = *mut MonitorMode;
pub type GetDriverInstallPath = fn() -> &'static str;
pub type IsDeviceCreated = fn() -> bool;
pub type CloseDevice = fn();
pub type DownLoadDriver = fn() -> ResultType<()>;
pub type CreateDevice = fn() -> ResultType<()>;
pub type InstallUpdateDriver = fn(&mut bool) -> ResultType<()>;
pub type UninstallDriver = fn(&mut bool) -> ResultType<()>;
pub type PlugInMonitor = fn(u32, u32, u32) -> ResultType<()>;
pub type PlugOutMonitor = fn(u32) -> ResultType<()>;
pub type UpdateMonitorModes = fn(u32, u32, PMonitorMode) -> ResultType<()>;
macro_rules! make_lib_wrapper {
($($field:ident : $tp:ty),+) => {
struct LibWrapper {
_lib: Option<Library>,
$($field: Option<$tp>),+
}
impl LibWrapper {
fn new() -> Self {
let lib = match Library::open(get_lib_name()) {
Ok(lib) => Some(lib),
Err(e) => {
log::warn!("Failed to load library {}, {}", LIB_NAME_VIRTUAL_DISPLAY, e);
None
}
};
$(let $field = if let Some(lib) = &lib {
match unsafe { lib.symbol::<$tp>(stringify!($field)) } {
Ok(m) => {
Some(*m)
},
Err(e) => {
log::warn!("Failed to load func {}, {}", stringify!($field), e);
None
}
}
} else {
None
};)+
Self {
_lib: lib,
$( $field ),+
}
}
}
impl Default for LibWrapper {
fn default() -> Self {
Self::new()
}
}
}
}
make_lib_wrapper!(
get_driver_install_path: GetDriverInstallPath,
is_device_created: IsDeviceCreated,
close_device: CloseDevice,
download_driver: DownLoadDriver,
create_device: CreateDevice,
install_update_driver: InstallUpdateDriver,
uninstall_driver: UninstallDriver,
plug_in_monitor: PlugInMonitor,
plug_out_monitor: PlugOutMonitor,
update_monitor_modes: UpdateMonitorModes
);
lazy_static::lazy_static! {
static ref LIB_WRAPPER: Arc<Mutex<LibWrapper>> = Default::default();
static ref MONITOR_INDICES: Mutex<HashSet<u32>> = Mutex::new(HashSet::new());
}
#[cfg(target_os = "windows")]
fn get_lib_name() -> String {
format!("{}.dll", LIB_NAME_VIRTUAL_DISPLAY)
}
#[cfg(target_os = "linux")]
fn get_lib_name() -> String {
format!("lib{}.so", LIB_NAME_VIRTUAL_DISPLAY)
}
#[cfg(target_os = "macos")]
fn get_lib_name() -> String {
format!("lib{}.dylib", LIB_NAME_VIRTUAL_DISPLAY)
}
#[cfg(windows)]
pub fn get_driver_install_path() -> Option<&'static str> {
Some(LIB_WRAPPER.lock().unwrap().get_driver_install_path?())
}
pub fn is_device_created() -> bool {
LIB_WRAPPER
.lock()
.unwrap()
.is_device_created
.map(|f| f())
.unwrap_or(false)
}
pub fn close_device() {
let _r = LIB_WRAPPER.lock().unwrap().close_device.map(|f| f());
}
pub fn download_driver() -> ResultType<()> {
LIB_WRAPPER
.lock()
.unwrap()
.download_driver
.ok_or(anyhow::Error::msg("download_driver method not found"))?()
}
pub fn create_device() -> ResultType<()> {
LIB_WRAPPER
.lock()
.unwrap()
.create_device
.ok_or(anyhow::Error::msg("create_device method not found"))?()
}
pub fn install_update_driver(reboot_required: &mut bool) -> ResultType<()> {
LIB_WRAPPER
.lock()
.unwrap()
.install_update_driver
.ok_or(anyhow::Error::msg("install_update_driver method not found"))?(reboot_required)
}
pub fn uninstall_driver(reboot_required: &mut bool) -> ResultType<()> {
LIB_WRAPPER
.lock()
.unwrap()
.uninstall_driver
.ok_or(anyhow::Error::msg("uninstall_driver method not found"))?(reboot_required)
}
#[cfg(windows)]
pub fn plug_in_monitor(monitor_index: u32) -> ResultType<()> {
let mut lock = MONITOR_INDICES.lock().unwrap();
if lock.contains(&monitor_index) {
return Ok(());
}
let f = LIB_WRAPPER
.lock()
.unwrap()
.plug_in_monitor
.ok_or(anyhow::Error::msg("plug_in_monitor method not found"))?;
f(monitor_index, 0, 20)?;
lock.insert(monitor_index);
Ok(())
}
#[cfg(windows)]
pub fn plug_out_monitor(monitor_index: u32) -> ResultType<()> {
let f = LIB_WRAPPER
.lock()
.unwrap()
.plug_out_monitor
.ok_or(anyhow::Error::msg("plug_out_monitor method not found"))?;
f(monitor_index)?;
MONITOR_INDICES.lock().unwrap().remove(&monitor_index);
Ok(())
}
#[cfg(windows)]
pub fn update_monitor_modes(monitor_index: u32, modes: &[MonitorMode]) -> ResultType<()> {
let f = LIB_WRAPPER
.lock()
.unwrap()
.update_monitor_modes
.ok_or(anyhow::Error::msg("update_monitor_modes method not found"))?;
f(monitor_index, modes.len() as _, modes.as_ptr() as _)
}