Files
hello-agent/src/main.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

214 lines
9.4 KiB
Rust

// hello-agent: a headless RustDesk-protocol-compatible support agent.
//
// One binary, two run modes: a console / installer entry point that handles
// --install / --uninstall / --config, and a "--service" entry registered with
// the Windows SCM that spawns the actual worker into the active console
// session as "--server".
//
// The protocol stack (rendezvous, NAT punch, screen capture, input, login
// flow) is reused unchanged from `librustdesk`. This crate is just the
// thin shell that gives us a different CLI surface, our own service install
// path, and a native approval popup in place of the Flutter CM.
//
// We override `hbb_common`'s default `APP_NAME` ("RustDesk") with our own
// product name as the very first thing every process does. APP_NAME is read
// lazily from a `RwLock<String>` whenever any path is computed (config dir,
// log dir, named-pipe namespace, …), so setting it before any of those
// initializers fire is enough to redirect all hbb_common state under
// `%APPDATA%\HelloAgent\` and the matching LocalService path. Identical
// to the `read_custom_client` write path the upstream Flutter build uses
// for OEM rebrands.
#![cfg_attr(not(target_os = "windows"), allow(dead_code, unused_imports))]
mod cli;
mod config_import;
#[cfg(target_os = "windows")]
mod cm_popup;
#[cfg(target_os = "windows")]
mod service;
#[cfg(target_os = "windows")]
mod unattended_password;
use cli::{Action, ParsedArgs};
/// Product name used to namespace all on-disk state and the IPC pipe path.
/// Written into `hbb_common::config::APP_NAME` at the top of `main` so
/// every subsequent path computation (config dir, log dir, named pipe)
/// targets `%APPDATA%\HelloAgent\` rather than the upstream default of
/// `%APPDATA%\RustDesk\`. Must be set before any code touches a path —
/// `hbb_common` initializes path globals lazily on first read.
pub const APP_NAME: &str = "HelloAgent";
/// Set up logging. We delegate to `hbb_common::init_log`, which:
/// * In **debug** builds: installs `env_logger` writing to stderr.
/// * In **release** builds: installs `flexi_logger` writing to a rolling
/// file under `<config_dir>/log/<mode>/` — the SYSTEM service log ends
/// up at `%SystemRoot%\ServiceProfiles\LocalService\AppData\Roaming\HelloAgent\log\<mode>\`
/// and the user-mode log at `%APPDATA%\HelloAgent\log\<mode>\`.
///
/// The `mode` label segregates per-run-mode log files so service worker
/// chatter doesn't tangle with --install diagnostics. `init_log` is
/// `Once`-guarded internally so calling it twice is harmless.
fn init_logging(mode: &str) {
let _ = hbb_common::init_log(false, mode);
}
fn main() {
// MUST be the very first line. See the doc-comment on `APP_NAME` —
// anything that lazily reads a config / log / pipe path before this
// runs would cache `"RustDesk"` in `hbb_common`'s path globals and
// we'd never recover.
*hbb_common::config::APP_NAME.write().unwrap() = APP_NAME.to_owned();
// Identify ourselves to the rustdesk-server's /api/sysinfo endpoint
// so the admin Devices page can show "HelloAgent 0.1.0" instead of
// the embedded rustdesk core version. These RwLocks are read once
// per sysinfo upload by hbbs_http::sync; setting them here (before
// start_server) ensures the very first upload carries the identity.
*hbb_common::config::AGENT_NAME.write().unwrap() = APP_NAME.to_owned();
*hbb_common::config::AGENT_VERSION.write().unwrap() = env!("CARGO_PKG_VERSION").to_owned();
let parsed = match ParsedArgs::from_argv(std::env::args().skip(1)) {
Ok(p) => p,
Err(e) => {
eprintln!("hello-agent: {e}");
eprintln!();
cli::print_usage();
std::process::exit(2);
}
};
// Initialize logging *after* arg parsing so the per-mode log file path
// is deterministic. `init_log` is Once-guarded internally.
let mode = match parsed.action {
Action::Install => "install",
Action::Uninstall => "uninstall",
Action::Service => "service",
Action::Server => "server",
Action::Cm => "cm",
Action::ConfigOnly | Action::None => "hello-agent",
};
init_logging(mode);
// --config is allowed to combine with --install (one-line MDM deploy)
// but on its own is a separate operation. Apply it first so --install
// sees the populated config.
if let Some(blob) = parsed.config_blob.as_deref() {
if let Err(e) = config_import::apply(blob) {
eprintln!("hello-agent: --config failed: {e:#}");
std::process::exit(2);
}
}
// Bake in fallback rendezvous defaults. Idempotent — if --config above
// (or a prior install) already set custom-rendezvous-server, this is a
// no-op. Without this, a bare `hello-agent.exe --install` would land
// at an unconfigured agent that can't reach any server.
config_import::apply_defaults_if_empty();
match parsed.action {
Action::Install => {
#[cfg(target_os = "windows")]
{
if let Err(e) = service::install() {
eprintln!("hello-agent: install failed: {e:#}");
std::process::exit(1);
}
println!("hello-agent: installed and started.");
}
#[cfg(not(target_os = "windows"))]
{
eprintln!("hello-agent: --install is Windows-only for now.");
std::process::exit(1);
}
}
Action::Uninstall => {
#[cfg(target_os = "windows")]
{
if let Err(e) = service::uninstall() {
eprintln!("hello-agent: uninstall failed: {e:#}");
std::process::exit(1);
}
println!("hello-agent: uninstalled.");
}
#[cfg(not(target_os = "windows"))]
{
eprintln!("hello-agent: --uninstall is Windows-only for now.");
std::process::exit(1);
}
}
Action::Service => {
#[cfg(target_os = "windows")]
{
if let Err(e) = service::run_as_service() {
eprintln!("hello-agent: service dispatcher failed: {e:#}");
std::process::exit(1);
}
}
#[cfg(not(target_os = "windows"))]
{
eprintln!("hello-agent: --service is Windows-only.");
std::process::exit(1);
}
}
Action::Server => run_server(),
Action::Cm => {
// Spawned by the SYSTEM-token --server worker (via librustdesk's
// run_as_user) when the rustdesk core wants a CM. Runs as the
// logged-in user, binds the `_cm` IPC pipe, services one Login
// request with a MessageBoxW, replies, exits.
#[cfg(target_os = "windows")]
cm_popup::run_blocking();
}
Action::ConfigOnly => {
// --config without --install or --service: just persist and exit.
}
Action::None => {
// No flags: dev mode. Run as a foreground server so the operator
// can watch logs. Production deployments use --install + --service.
run_server();
}
}
}
fn run_server() {
// Clear any stale `approve-mode = click` left by older hello-agent
// versions. ApproveMode comes from `password_security::approve_mode`:
// "password" → password only, "click" → popup only, anything else →
// both (try password first, fall back to popup). We want both so
// that (a) attended sessions still go through the cm_popup approval,
// and (b) unattended sessions can authenticate with the per-boot
// password we report to the admin UI. Setting to "" is idempotent
// and overrides any leftover "click" value on disk.
hbb_common::config::Config::set_option("approve-mode".into(), "".into());
// Pre-spawn the --cm child *on the user's interactive desktop* before
// start_server boots. librustdesk's start_ipc has its own
// run_as_user(["--cm"]) fallback, but it goes through C-side
// LaunchProcessWin with show=FALSE → lpDesktop=NULL → child inherits
// the parent's desktop, which (because we were spawned by the Session-0
// service) is the invisible Session 0 service desktop. Our spawn
// helper sets lpDesktop = winsta0\\default explicitly, putting the
// popup on the user's screen. Once our --cm is bound to `_cm`,
// start_ipc's first ipc::connect("_cm") succeeds and rustdesk's
// built-in fallback never fires.
//
// We target *our own* session (whichever the supervisor placed us in
// — physical console, RDP, multi-user) rather than the physical
// console specifically. WTSGetActiveConsoleSessionId would point at
// the empty / lock-screen console session in RDP-only scenarios.
#[cfg(target_os = "windows")]
match service::spawn_cm_in_my_session() {
Ok(pid) => log::info!("spawned --cm child pid={pid} on winsta0\\default"),
Err(e) => log::warn!(
"could not pre-spawn --cm child ({e:#}); rustdesk's start_ipc fallback may be invisible"
),
}
// `start_server` is `#[tokio::main]` and runs forever. (is_server=true,
// no_server=false). It boots the default IPC server, input service,
// rendezvous mediator, and heartbeat sync.
librustdesk::start_server(true, false);
}