diff --git a/Cargo.lock b/Cargo.lock index 1b67984ce..e606a98f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2451,11 +2451,11 @@ dependencies = [ "clap", "ironrdp-cfg", "ironrdp-client", - "ironrdp-core 0.2.1", "ironrdp-input", "ironrdp-pdu", "ironrdp-propertyset", "ironrdp-rdpfile", + "ironrdp-rpc", "ironrdp-tls", "libc", "now-client", @@ -2467,7 +2467,6 @@ dependencies = [ "tracing-subscriber", "uuid", "whoami", - "windows", ] [[package]] @@ -2896,6 +2895,22 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "ironrdp-rpc" +version = "0.1.0" +dependencies = [ + "anyhow", + "ironrdp-core 0.2.1", + "ironrdp-input", + "ironrdp-pdu", + "ironrdp-propertyset", + "libc", + "tokio", + "tracing", + "whoami", + "windows", +] + [[package]] name = "ironrdp-server" version = "0.13.0" @@ -3070,6 +3085,7 @@ dependencies = [ "clap", "inquire", "ironrdp", + "ironrdp-agent", "ironrdp-cfg", "ironrdp-propertyset", "ironrdp-rdpfile", diff --git a/README.md b/README.md index 544974f67..25d7f9841 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,8 @@ rendering. ironrdp-viewer --username --password ``` -Omitted credentials are prompted for interactively. You can also load a `.rdp` file: +Omitted connection values are prompted for interactively. You can also provide them through +`RDP_HOSTNAME`, `RDP_USERNAME`, and `RDP_PASSWORD`, or load a `.rdp` file: ```shell ironrdp-viewer --rdp-file ./my-server.rdp @@ -111,15 +112,23 @@ logging, and the full option list. ### `ironrdp-agent` -`ironrdp-agent` combines a long-lived RDP daemon with short-lived CLI invocations, which makes it -convenient for scripts and LLM-driven automation: +`ironrdp-agent` combines a long-lived local RPC backend with short-lived CLI invocations, which makes +it convenient for scripts and LLM-driven automation. The daemon backend remains the default; use +`--backend viewer` to drive a visible `ironrdp-viewer` window instead: ```shell ironrdp-agent daemon-start --overlay ./credentials.rdp # in one terminal ironrdp-agent connect --server --username # in another ironrdp-agent screenshot ./desktop.png +ironrdp-agent --backend viewer connect --server --username --password ``` +Normal operations automatically start and reuse the selected backend. The daemon and viewer use +distinct per-user endpoints by default; `--endpoint` overrides either one. Run +`ironrdp-agent --backend viewer stop` (or `stop` with the default backend) to terminate the selected +long-lived process. The viewer backend implements the same status, input, screenshot, and NOW +operations while rendering the shared session in its GUI. + `connect` fails with `missing required fields` unless credentials are available, so either preload them into the daemon with `daemon-start --overlay ` — which keeps secrets away from the IPC caller — or pass `--password` to `connect`. diff --git a/crates/ironrdp-agent/Cargo.toml b/crates/ironrdp-agent/Cargo.toml index bdfe6509e..0addee7f3 100644 --- a/crates/ironrdp-agent/Cargo.toml +++ b/crates/ironrdp-agent/Cargo.toml @@ -29,13 +29,13 @@ internal = [] ironrdp-client = { path = "../ironrdp-client", version = "0.1", features = ["rustls", "dvc-pipe-proxy"] } # Configuration model and codecs -ironrdp-core = { path = "../ironrdp-core", version = "0.2", features = ["alloc"] } ironrdp-pdu = { path = "../ironrdp-pdu", version = "0.9" } ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" } ironrdp-cfg = { path = "../ironrdp-cfg", version = "0.1" } ironrdp-rdpfile = { path = "../ironrdp-rdpfile", version = "0.1" } ironrdp-input = { path = "../ironrdp-input", version = "0.7" } ironrdp-tls = { path = "../ironrdp-tls", version = "0.2" } +ironrdp-rpc = { path = "../ironrdp-rpc", version = "0.1" } # Async runtime and IPC transport tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "macros", "io-util", "time", "signal"] } @@ -66,13 +66,5 @@ now-proto-pdu = { version = "0.4", features = ["std"] } [target.'cfg(unix)'.dependencies] libc = "0.2" -[target.'cfg(windows)'.dependencies] -windows = { version = "0.62", features = [ - "Win32_Foundation", - "Win32_Security", - "Win32_Security_Authorization", - "Win32_System_Threading", -] } - [lints] workspace = true diff --git a/crates/ironrdp-agent/README.md b/crates/ironrdp-agent/README.md index 76f0b5694..9f8d1006b 100644 --- a/crates/ironrdp-agent/README.md +++ b/crates/ironrdp-agent/README.md @@ -1,15 +1,24 @@ # IronRDP Agent -A CLI-driven, daemon-backed RDP client designed for programmatic (e.g. LLM) consumption. +A CLI-driven RDP client designed for programmatic (e.g. LLM) consumption. -The single `ironrdp-agent` binary bundles two roles: +The single `ironrdp-agent` binary provides a short-lived CLI and can drive either of two +long-lived local RPC backends: - **Daemon** (`ironrdp-agent daemon-start`): a long-lived, foreground process that owns the [`ironrdp-client`] engine and one RDP session. It stays alive across many CLI invocations and serves requests over a local IPC transport (a Unix domain socket on Unix, a named pipe on Windows). -- **CLI** (`ironrdp-agent …`): a short-lived invocation that opens the IPC endpoint, sends a - single request, prints the response, and exits. +- **Viewer** (`ironrdp-viewer --rpc`): the same RPC contract hosted by the visible + [`ironrdp-viewer`]. The viewer window and CLI share one RDP session, framebuffer, and input path. + +For normal CLI operations, the selected backend is started automatically when it is not already +running and remains available for later invocations. The daemon is the default; select the visible +viewer with `--backend viewer`. `--endpoint` overrides the selected backend's endpoint. Use +`stop` to terminate the selected backend. + +The CLI (`ironrdp-agent …`) is a short-lived invocation that opens the selected endpoint, sends +a single request, prints the response, and exits. Run `ironrdp-agent --help-agent` for a structured, machine-readable description of every operation. @@ -31,6 +40,13 @@ strictly-typed messages. `Request::Screenshot` returns the most recent frame as mouse cursor composited in — the agent enables software pointer rendering), which the CLI writes to disk. +Both backends implement the complete current RPC contract, including connection lifecycle, status, +property and log inspection, screenshots, mouse/keyboard/resize input, and NOW operations. The +default endpoints are `ironrdp-agent-.sock` (Unix) or `\\.\pipe\ironrdp-agent-` (Windows) +for the daemon, and the corresponding `ironrdp-viewer-.sock` or +`\\.\pipe\ironrdp-viewer-` endpoint for the viewer. A manually started viewer uses +`ironrdp-viewer --rpc --rpc-endpoint ` when a non-default endpoint is required. + ## Secrets The daemon never exposes secrets to the IPC reader. `ConfigBuilder::build` strips every diff --git a/crates/ironrdp-agent/src/cli.rs b/crates/ironrdp-agent/src/cli.rs index 2506a6ce6..7629c1fa7 100644 --- a/crates/ironrdp-agent/src/cli.rs +++ b/crates/ironrdp-agent/src/cli.rs @@ -15,9 +15,12 @@ use core::fmt; use core::str::FromStr; use std::io::Write as _; use std::path::{Path, PathBuf}; +use std::process::{Command as ProcessCommand, Stdio}; +use std::time::Instant; use anyhow::Context as _; use clap::{Args, CommandFactory as _, Parser, Subcommand, ValueEnum}; +use core::time::Duration as StdDuration; use ironrdp_cfg::{PropertySetExt as _, TargetAddr}; use ironrdp_input::MouseButton; use ironrdp_propertyset::{PropertySet, Value}; @@ -40,6 +43,10 @@ pub struct Cli { #[arg(long, global = true)] endpoint: Option, + /// Select the local RPC backend. The daemon remains the default. + #[arg(long, global = true, value_enum, default_value_t = Backend::Daemon)] + backend: Backend, + #[command(subcommand)] command: Option, } @@ -52,6 +59,8 @@ enum Command { Connect(ConnectArgs), /// Tear down the current RDP session (the daemon keeps running). Disconnect, + /// Stop the selected long-lived RPC backend. + Stop, /// Report the current session status. Status, /// Query the live session properties. @@ -246,6 +255,12 @@ enum OutputFormat { const MAX_JSON_STREAM_EVENTS: usize = 8 * 1024; const MAX_JSON_STREAM_OUTPUT: usize = 2 * 1024 * 1024; +#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] +pub enum Backend { + Daemon, + Viewer, +} + /// A daemon-provided error that must be rendered according to the selected NOW output format. #[derive(Debug)] struct NowRequestError(AgentError); @@ -414,7 +429,7 @@ pub async fn run(cli: Cli) -> anyhow::Result<()> { return Ok(()); } - let endpoint = endpoint_from_arg(cli.endpoint); + let endpoint = endpoint_from_arg(cli.endpoint, cli.backend); let Some(command) = cli.command else { let _ = Cli::command().print_help(); @@ -422,11 +437,19 @@ pub async fn run(cli: Cli) -> anyhow::Result<()> { return Ok(()); }; + if !matches!(&command, Command::DaemonStart(_) | Command::Stop) { + ensure_backend(&endpoint, cli.backend).await?; + } + let request = match command { Command::DaemonStart(args) => { + if cli.backend != Backend::Daemon { + anyhow::bail!("daemon-start requires --backend daemon"); + } let overlay = load_overlay(args.overlay.as_deref(), args.prop)?; return crate::daemon::run(endpoint, overlay).await; } + Command::Stop => Request::Shutdown, Command::Now(args) => { let format = args.format; let exit_code = match run_now(&endpoint, args).await { @@ -1119,19 +1142,72 @@ fn write_screenshot(width: u16, height: u16, png: &[u8], path: &Path) -> anyhow: Ok(()) } -#[cfg(unix)] -fn endpoint_from_arg(arg: Option) -> Endpoint { +fn endpoint_from_arg(arg: Option, backend: Backend) -> Endpoint { match arg { - Some(value) => Endpoint(PathBuf::from(value)), - None => transport::default_endpoint(), + Some(value) => transport::endpoint_from_string(value), + None => match backend { + Backend::Daemon => transport::default_endpoint_named("ironrdp-agent"), + Backend::Viewer => transport::default_endpoint_named("ironrdp-viewer"), + }, } } -#[cfg(windows)] -fn endpoint_from_arg(arg: Option) -> Endpoint { - match arg { - Some(value) => Endpoint(value), - None => transport::default_endpoint(), +async fn ensure_backend(endpoint: &Endpoint, backend: Backend) -> anyhow::Result<()> { + if transport::send_request(endpoint, &Request::Status).await.is_ok() { + return Ok(()); + } + + let mut child = spawn_backend(endpoint, backend)?; + let deadline = Instant::now() + StdDuration::from_secs(10); + + loop { + if transport::send_request(endpoint, &Request::Status).await.is_ok() { + return Ok(()); + } + + if let Some(status) = child.try_wait().context("check RPC backend process")? { + anyhow::bail!( + "{} backend exited before becoming ready with status {status}", + backend_name(backend) + ); + } + if Instant::now() >= deadline { + anyhow::bail!("timed out waiting for {} backend at {endpoint}", backend_name(backend)); + } + tokio::time::sleep(StdDuration::from_millis(50)).await; + } +} + +fn spawn_backend(endpoint: &Endpoint, backend: Backend) -> anyhow::Result { + let endpoint = endpoint.to_string(); + let mut command = match backend { + Backend::Daemon => { + let executable = std::env::current_exe().context("resolve ironrdp-agent executable")?; + let mut command = ProcessCommand::new(executable); + command.args(["--endpoint", &endpoint, "daemon-start"]); + command + } + Backend::Viewer => { + let mut executable = std::env::current_exe().context("resolve ironrdp-agent executable")?; + executable.set_file_name(format!("ironrdp-viewer{}", std::env::consts::EXE_SUFFIX)); + let mut command = ProcessCommand::new(executable); + command.args(["--rpc", "--rpc-endpoint", &endpoint]); + command + } + }; + + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .with_context(|| format!("start {} backend", backend_name(backend))) +} + +fn backend_name(backend: Backend) -> &'static str { + match backend { + Backend::Daemon => "daemon", + Backend::Viewer => "viewer", } } @@ -1203,7 +1279,21 @@ fn property_description(key: &str) -> Option<&'static str> { mod tests { use clap::Parser as _; - use super::{Cli, CommonExecutionArgs, NowExecutionKind, build_now_execution}; + use super::{Backend, Cli, CommonExecutionArgs, NowExecutionKind, build_now_execution, endpoint_from_arg}; + + #[test] + fn backend_endpoint_selection_is_distinct_and_overridable() { + let daemon = endpoint_from_arg(None, Backend::Daemon).to_string(); + let viewer = endpoint_from_arg(None, Backend::Viewer).to_string(); + + assert_ne!(daemon, viewer); + assert!(daemon.contains("ironrdp-agent")); + assert!(viewer.contains("ironrdp-viewer")); + assert_eq!( + endpoint_from_arg(Some("custom-rpc-endpoint".to_owned()), Backend::Viewer).to_string(), + "custom-rpc-endpoint" + ); + } #[test] fn shell_is_not_an_agent_command() { diff --git a/crates/ironrdp-agent/src/daemon.rs b/crates/ironrdp-agent/src/daemon.rs index cf972695c..8cbdf5c18 100644 --- a/crates/ironrdp-agent/src/daemon.rs +++ b/crates/ironrdp-agent/src/daemon.rs @@ -33,32 +33,21 @@ use crate::transport::{Endpoint, Listener, read_message, write_message}; /// (overlay wins), so any setting — credentials in particular — can be preconfigured without the /// caller ever supplying it. Pass an empty set when no overlay is desired. pub async fn run(endpoint: Endpoint, overlay: PropertySet) -> anyhow::Result<()> { - // On Unix a leftover socket file would make `bind` fail; clear it if no daemon is alive. - #[cfg(unix)] - if endpoint.0.exists() { - if crate::transport::connect(&endpoint).await.is_ok() { - anyhow::bail!("a daemon already appears to be running at {endpoint}"); - } - // No daemon answered, so the path is a stale socket we can reclaim. Guard against deleting - // an unrelated regular file (or following a symlink) when `--endpoint` points elsewhere: - // inspect the path itself and only remove genuine sockets. - use std::os::unix::fs::FileTypeExt as _; - let metadata = - std::fs::symlink_metadata(&endpoint.0).with_context(|| format!("stat IPC endpoint {endpoint}"))?; - if !metadata.file_type().is_socket() { - anyhow::bail!("refusing to remove {endpoint}: path exists and is not a socket"); - } - std::fs::remove_file(&endpoint.0).with_context(|| format!("remove stale socket {endpoint}"))?; - } - init_daemon_logging(); - let logs = LogBuffer::new(); + let daemon = Arc::new(Daemon::with_overlay(overlay)); + serve(endpoint, daemon).await +} +/// Serves `daemon` on `endpoint` until a [`Request::Shutdown`] is received. +/// +/// The caller owns the daemon so it can share the same session state with another frontend, such +/// as the viewer window. +pub async fn serve(endpoint: Endpoint, daemon: Arc) -> anyhow::Result<()> { + crate::transport::prepare_endpoint(&endpoint).await?; let mut listener = Listener::bind(&endpoint).with_context(|| format!("bind IPC endpoint {endpoint}"))?; - let daemon = Arc::new(Daemon::new(logs, overlay)); - info!(%endpoint, "Daemon listening"); + let mut shutdown = daemon.shutdown_receiver(); loop { tokio::select! { result = listener.accept() => { @@ -70,21 +59,29 @@ pub async fn run(endpoint: Endpoint, overlay: PropertySet) -> anyhow::Result<()> } }); } - _ = tokio::signal::ctrl_c() => { + result = tokio::signal::ctrl_c() => { + result.context("wait for shutdown signal")?; info!("Received shutdown signal, stopping"); break; } + result = shutdown.changed() => { + result.context("wait for RPC shutdown")?; + info!("Received RPC shutdown request, stopping"); + break; + } } } Ok(()) } -async fn handle_connection(mut stream: S, daemon: &Daemon) -> anyhow::Result<()> +/// Handles one framed RPC request and writes its response, including streamed NOW events. +pub async fn handle_connection(mut stream: S, daemon: &Daemon) -> anyhow::Result<()> where S: AsyncRead + AsyncWrite + Unpin, { let request: Request = read_message(&mut stream).await?; + let shutdown = matches!(&request, Request::Shutdown); trace!(?request, "Handling IPC request"); let response = daemon.handle(request).await; trace!(ok = response.response().is_ok(), "Replying to IPC request"); @@ -100,10 +97,13 @@ where } } } + if shutdown { + daemon.signal_shutdown(); + } Ok(()) } -enum DaemonResponse { +pub enum DaemonResponse { Single(Response), Stream(Response, OperationAttachment), } @@ -117,7 +117,7 @@ impl DaemonResponse { } /// The daemon's mutable state: the (single) current session, plus the shared log buffer. -struct Daemon { +pub struct Daemon { state: Mutex>, /// Serializes synchronous RDP session construction so concurrent IPC `connect` requests cannot /// both observe an empty session slot before either one installs its session. @@ -129,6 +129,9 @@ struct Daemon { /// Whether [`Self::overlay`] contributes any secret (password/token) value, i.e. whether the /// caller can omit credentials of its own. credentials_loaded: bool, + /// Notifies an optional GUI frontend whenever retained live state changes. + notification: Option>, + shutdown: tokio::sync::watch::Sender<()>, } /// Per-session state owned by the request handler. @@ -154,10 +157,11 @@ struct Live { /// A decoded frame retained for screenshots. `pixels` are `0x00RRGGBB` (`to_be_bytes()` yields /// `[0, R, G, B]`), row-major, `width * height` entries, with the remote cursor blended in. -struct Frame { - width: u16, - height: u16, - pixels: Vec, +#[derive(Clone)] +pub struct Frame { + pub width: u16, + pub height: u16, + pub pixels: Vec, } impl Daemon { @@ -165,22 +169,56 @@ impl Daemon { // Credentials are considered "loaded" when the overlay provides at least one secret value, // which is what frees the caller from supplying a password. let credentials_loaded = overlay.iter().any(|(key, _)| ironrdp_cfg::is_secret_key(key)); + let (shutdown, _) = tokio::sync::watch::channel(()); Self { state: Mutex::new(None), connect_lock: Mutex::new(()), logs, overlay, credentials_loaded, + notification: None, + shutdown, } } - async fn handle(&self, request: Request) -> DaemonResponse { + /// Creates a daemon with no preconfigured connection properties. + pub fn with_overlay(overlay: PropertySet) -> Self { + Self::new(LogBuffer::new(), overlay) + } + + /// Adds a notification channel for frontends that render the retained session state. + #[must_use] + pub fn with_notification(mut self, notification: mpsc::UnboundedSender<()>) -> Self { + self.notification = Some(notification); + self + } + + /// Returns a receiver that is notified when the server should stop. + pub fn shutdown_receiver(&self) -> tokio::sync::watch::Receiver<()> { + self.shutdown.subscribe() + } + + /// Returns the latest cursor-composited framebuffer, if one is available. + /// + /// # Panics + /// + /// Panics if the daemon or session state mutex is poisoned. + pub fn current_frame(&self) -> Option { + let guard = self.state.lock().expect("daemon state poisoned"); + guard + .as_ref() + .and_then(|session| session.live.lock().expect("session live state poisoned").frame.clone()) + } + + /// Handles one typed RPC request. + pub async fn handle(&self, request: Request) -> DaemonResponse { match request { Request::Connect { properties, log_directive, } => DaemonResponse::Single(self.connect(properties, log_directive)), Request::Disconnect => DaemonResponse::Single(self.disconnect()), + Request::Shutdown => DaemonResponse::Single(Self::shutdown()), Request::Status => DaemonResponse::Single(self.status()), Request::QueryProps { filter } => DaemonResponse::Single(self.query_props(filter.as_ref())), Request::QueryLogs { substring, last } => { @@ -370,7 +408,7 @@ impl Daemon { ); } - tokio::spawn(consume_output(output_rx, Arc::clone(&live))); + tokio::spawn(consume_output(output_rx, Arc::clone(&live), self.notification.clone())); info!(%destination, "Started RDP session"); @@ -386,7 +424,12 @@ impl Daemon { Response::ok() } - fn disconnect(&self) -> Response { + /// Requests the active RDP session to disconnect. + /// + /// # Panics + /// + /// Panics if the daemon or session state mutex is poisoned. + pub fn disconnect(&self) -> Response { let mut guard = self.state.lock().expect("daemon state poisoned"); match guard.as_mut() { None => { @@ -512,7 +555,12 @@ impl Daemon { } } - fn resize(&self, width: u16, height: u16) -> Response { + /// Sends a resize event to the active RDP session. + /// + /// # Panics + /// + /// Panics if the daemon state mutex is poisoned. + pub fn resize(&self, width: u16, height: u16) -> Response { if width == 0 || height == 0 { return Response::typed_error( crate::ipc::AgentErrorCategory::InvalidRequest, @@ -538,7 +586,12 @@ impl Daemon { } } - fn input(&self, operation: Operation) -> Response { + /// Sends an input operation to the active RDP session. + /// + /// # Panics + /// + /// Panics if the daemon state mutex is poisoned. + pub fn input(&self, operation: Operation) -> Response { let mut guard = self.state.lock().expect("daemon state poisoned"); let Some(session) = guard.as_mut() else { return Response::typed_error(crate::ipc::AgentErrorCategory::Unavailable, "no active session"); @@ -560,6 +613,14 @@ impl Daemon { Response::ok() } + fn shutdown() -> Response { + Response::ok() + } + + fn signal_shutdown(&self) { + let _ = self.shutdown.send(()); + } + fn operations(&self) -> Result { self.state .lock() @@ -697,7 +758,11 @@ impl Daemon { } /// Consumes the bounded output-event stream, keeping the live state current. -async fn consume_output(mut output_rx: mpsc::Receiver, live: Arc>) { +async fn consume_output( + mut output_rx: mpsc::Receiver, + live: Arc>, + notification: Option>, +) { while let Some(event) = output_rx.recv().await { let mut guard = live.lock().expect("session live state poisoned"); let previous = guard.state; @@ -745,6 +810,10 @@ async fn consume_output(mut output_rx: mpsc::Receiver, live: Arc // above; the remaining pointer events (default/hidden) carry no live state we track. _ => {} } + drop(guard); + if let Some(notification) = ¬ification { + let _ = notification.send(()); + } } // The engine thread has ended (channel closed). Resolve any transient state so a subsequent @@ -756,6 +825,10 @@ async fn consume_output(mut output_rx: mpsc::Receiver, live: Arc ) { guard.state = ConnState::Disconnected; } + drop(guard); + if let Some(notification) = ¬ification { + let _ = notification.send(()); + } } /// Encodes a retained framebuffer to PNG bytes. @@ -832,3 +905,37 @@ fn current_platform() -> MajorPlatformType { _ => MajorPlatformType::UNSPECIFIED, } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::{Daemon, handle_connection}; + use crate::ipc::{Payload, Request, Response}; + use crate::transport::{read_message, write_message}; + use ironrdp_propertyset::PropertySet; + + #[tokio::test] + async fn shutdown_reply_is_written_before_server_signal() { + let daemon = Arc::new(Daemon::with_overlay(PropertySet::new())); + let mut shutdown = daemon.shutdown_receiver(); + let (mut client, server) = tokio::io::duplex(4096); + let handler_daemon = Arc::clone(&daemon); + let handler = tokio::spawn(async move { handle_connection(server, handler_daemon.as_ref()).await }); + + write_message(&mut client, &Request::Shutdown) + .await + .expect("write shutdown request"); + let response: Response = read_message(&mut client).await.expect("read shutdown response"); + assert_eq!(response, Response::Ok(Payload::Empty)); + + tokio::time::timeout(core::time::Duration::from_secs(1), shutdown.changed()) + .await + .expect("shutdown signal timeout") + .expect("shutdown signal"); + handler + .await + .expect("join shutdown handler") + .expect("handle shutdown request"); + } +} diff --git a/crates/ironrdp-agent/src/help.rs b/crates/ironrdp-agent/src/help.rs index fda873f5a..c3b8cca96 100644 --- a/crates/ironrdp-agent/src/help.rs +++ b/crates/ironrdp-agent/src/help.rs @@ -3,20 +3,25 @@ /// Structured guide printed by `ironrdp-agent --help-agent`. pub(crate) const AGENT_GUIDE: &str = r#"# ironrdp-agent -A CLI-driven, daemon-backed RDP client. One binary plays two roles: +A CLI-driven RDP client. One binary provides a short-lived CLI for two local RPC backends: - DAEMON: `ironrdp-agent daemon-start` runs a long-lived foreground process that owns the RDP engine and one RDP session. Background it yourself (e.g. `ironrdp-agent daemon-start &`). -- CLI: every other subcommand opens the local IPC endpoint, sends one request, prints the - response, and exits. +- VIEWER: `ironrdp-viewer --rpc` runs the same RPC server alongside the visible viewer window. +- CLI: every operation opens the selected local IPC endpoint, sends one request, prints the response, + and exits. -The daemon stays alive across CLI invocations. One daemon serves one RDP session. +The daemon is the default backend. Normal operations automatically start the selected backend when +it is not already running, then reuse it across CLI invocations. One backend serves one RDP session. ## Endpoint -Unix: `$XDG_RUNTIME_DIR/ironrdp-agent-.sock` (falls back to `/tmp/ironrdp-agent-.sock`). -Windows: `\\.\pipe\ironrdp-agent-`. -Override with `--endpoint ` on any subcommand. +`--backend daemon` (the default): Unix `$XDG_RUNTIME_DIR/ironrdp-agent-.sock` (falls back to +`/tmp/ironrdp-agent-.sock`); Windows `\\.\pipe\ironrdp-agent-`. +`--backend viewer`: Unix `$XDG_RUNTIME_DIR/ironrdp-viewer-.sock` (falls back to +`/tmp/ironrdp-viewer-.sock`); Windows `\\.\pipe\ironrdp-viewer-`. +Override with `--endpoint ` on any agent subcommand. A manually started viewer accepts +`--rpc-endpoint `. ## Lifecycle @@ -30,6 +35,14 @@ Override with `--endpoint ` on any subcommand. file line (TYPE is `i` for integer or `s` for string), e.g. `--prop ironrdp_autologon:i:1`. Check `status` to see whether credentials are already loaded before supplying any yourself. +- `--backend viewer ` + Drive a visible `ironrdp-viewer` RPC host instead of the daemon. + The viewer is started automatically for normal operations and + remains available for later commands; the GUI and CLI share one + RDP session. +- `stop` + Stop the selected long-lived backend after replying. This does + not start a backend that is not already running. - `connect [--rdp-file F] [--prop KEY:TYPE:VALUE]... [--server H[:PORT]] [-u USER] [-p PASS] [-d DOMAIN] [--log-directive D]` Merge an optional .rdp file with CLI overrides into one config and open a session. Precedence (low to high): .rdp file -> `--prop` diff --git a/crates/ironrdp-agent/src/ipc.rs b/crates/ironrdp-agent/src/ipc.rs index 30e579a21..3f1fa4ffe 100644 --- a/crates/ironrdp-agent/src/ipc.rs +++ b/crates/ironrdp-agent/src/ipc.rs @@ -1,1737 +1,3 @@ -//! Strictly-typed IPC schema (V1) and its binary codec. -//! -//! # Framing -//! -//! Every message is sent length-delimited: a little-endian `u32` byte-count prefix followed by the -//! `Encode`d body. The framing is identical over Unix domain sockets and Windows named pipes (see -//! [`crate::transport`]). Both ends are the same binary at the same version, so there is no version -//! byte and no forward/backward-compatibility handling. -//! -//! # Schema -//! -//! Connection configuration travels as a binary-encoded [`PropertySet`] inside [`Request::Connect`]; -//! everything else is a strictly-typed message. See [`Request`]/[`Response`]. +//! Compatibility re-export for the shared local RPC schema. -use core::fmt; - -use ironrdp_core::{Decode, DecodeResult, Encode, EncodeResult, ReadCursor, WriteCursor, cast_length, ensure_size}; -use ironrdp_input::MouseButton; -use ironrdp_pdu::impl_pdu_pod; -use ironrdp_propertyset::PropertySet; - -use crate::wire::{ - bytes_size, opt_string_size, opt_u16_size, opt_u64_size, propertyset, read_bool, read_bytes, read_char, - read_mouse_button, read_opt_string, read_opt_u16, read_opt_u64, read_string, string_size, write_bool, write_bytes, - write_char, write_mouse_button, write_opt_string, write_opt_u16, write_opt_u64, write_string, -}; - -/// A request sent by the CLI to the daemon. -/// -/// `Connect` carries a binary-encoded [`PropertySet`] — never `argv` or CLI strings. Runtime -/// operations are strictly-typed. -#[derive(Clone, PartialEq, Eq)] -pub enum Request { - /// Start an RDP session from a fully-merged property bag. - /// - /// `log_directive`, when set, is a [`tracing`]-style filter directive applied to *this* - /// session's log capture (e.g. `ironrdp_connector=trace`), layered on top of the default - /// `DEBUG` level. It lets a caller raise verbosity up-front to troubleshoot a connection. - Connect { - properties: PropertySet, - log_directive: Option, - }, - /// Tear down the current RDP session (the daemon keeps running). - Disconnect, - /// Query the current session status. - Status, - /// Query the live session property bag, optionally filtered. - QueryProps { filter: Option }, - /// Return retained log lines, optionally filtered by substring and/or limited to the last `n`. - QueryLogs { - substring: Option, - last: Option, - }, - /// Capture the most recent frame (cursor composited in) as a PNG. - Screenshot, - /// Move the mouse pointer to an absolute position. - MouseMove { x: u16, y: u16 }, - /// Press or release a mouse button. - MouseButton { button: MouseButton, pressed: bool }, - /// Rotate the mouse wheel. - Wheel { delta: i16, horizontal: bool }, - // TODO: questioning whether we need a way to send multiple keys at once, e.g. a small mini - // format to express in a single command that keys A and B are pressed while key C is released. - // This could save LLM tokens by collapsing several round-trips into one request. - /// Press or release a key identified by its RDP scancode. - KeyScancode { scancode: u16, pressed: bool }, - /// Press or release a key identified by a Unicode character. - KeyUnicode { ch: char, pressed: bool }, - /// Resize the remote desktop. - Resize { width: u16, height: u16 }, - /// Query and negotiate the capabilities of the session's NOW endpoint. - NowCapabilities, - /// Submit an untracked generic NOW Run request. - NowRun { - /// Command line interpreted by the remote NOW agent. - command: String, - /// Optional remote working directory. - directory: Option, - }, - /// Submit a NOW operation that is tracked by the daemon unless `detached` is set. - NowExecute(NowExecutionRequest), - /// Request cancellation of the active tracked NOW operation. - NowCancel { operation_id: u64 }, - /// List daemon-retained NOW operations. - NowList, - /// Inspect a retained NOW operation. - NowStatus { operation_id: u64 }, - /// Replay retained operation events after `after_sequence` and then follow live output. - NowAttach { - operation_id: u64, - after_sequence: Option, - }, - /// Forward a bounded raw stdin chunk to a tracked operation. - NowStdin { - operation_id: u64, - data: Vec, - last: bool, - }, - /// Inspect the local NOW endpoint without exposing protocol internals. - NowDiagnostics, - // TODO: add clipboard support (CLIPRDR), e.g. requests to read the remote clipboard text and to - // set it, so an LLM can copy/paste to and from the session. -} - -// Manual `Debug` so the `Connect` payload's property *values* (which may include a password before -// it reaches `ConfigBuilder::build`) are never printed verbatim; only the keys are shown. -impl fmt::Debug for Request { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Connect { - properties, - log_directive, - } => f - .debug_struct("Connect") - .field("properties", &PropertyKeys(properties)) - .field("log_directive", log_directive) - .finish(), - Self::Disconnect => f.write_str("Disconnect"), - Self::Status => f.write_str("Status"), - Self::QueryProps { filter } => f.debug_struct("QueryProps").field("filter", filter).finish(), - Self::QueryLogs { substring, last } => f - .debug_struct("QueryLogs") - .field("substring", substring) - .field("last", last) - .finish(), - Self::Screenshot => f.write_str("Screenshot"), - Self::MouseMove { x, y } => f.debug_struct("MouseMove").field("x", x).field("y", y).finish(), - Self::MouseButton { button, pressed } => f - .debug_struct("MouseButton") - .field("button", button) - .field("pressed", pressed) - .finish(), - Self::Wheel { delta, horizontal } => f - .debug_struct("Wheel") - .field("delta", delta) - .field("horizontal", horizontal) - .finish(), - Self::KeyScancode { scancode, pressed } => f - .debug_struct("KeyScancode") - .field("scancode", scancode) - .field("pressed", pressed) - .finish(), - Self::KeyUnicode { ch, pressed } => f - .debug_struct("KeyUnicode") - .field("ch", ch) - .field("pressed", pressed) - .finish(), - Self::Resize { width, height } => f - .debug_struct("Resize") - .field("width", width) - .field("height", height) - .finish(), - Self::NowCapabilities => f.write_str("NowCapabilities"), - Self::NowRun { command, directory } => f - .debug_struct("NowRun") - .field("command_len", &command.len()) - .field("directory", directory) - .finish(), - Self::NowExecute(request) => f.debug_tuple("NowExecute").field(request).finish(), - Self::NowCancel { operation_id } => { - f.debug_struct("NowCancel").field("operation_id", operation_id).finish() - } - Self::NowList => f.write_str("NowList"), - Self::NowStatus { operation_id } => { - f.debug_struct("NowStatus").field("operation_id", operation_id).finish() - } - Self::NowAttach { - operation_id, - after_sequence, - } => f - .debug_struct("NowAttach") - .field("operation_id", operation_id) - .field("after_sequence", after_sequence) - .finish(), - Self::NowStdin { - operation_id, - data, - last, - } => f - .debug_struct("NowStdin") - .field("operation_id", operation_id) - .field("data_len", &data.len()) - .field("last", last) - .finish(), - Self::NowDiagnostics => f.write_str("NowDiagnostics"), - } - } -} - -/// A [`PropertySet`] whose `Debug` output lists only the keys, never the (possibly secret) values. -struct PropertyKeys<'a>(&'a PropertySet); - -impl fmt::Debug for PropertyKeys<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_set().entries(self.0.iter().map(|(key, _)| key)).finish() - } -} - -/// The daemon's reply to a [`Request`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Response { - /// Success, carrying an operation-specific [`Payload`]. - Ok(Payload), - /// Failure. The message is lowercase with no trailing punctuation. - Err(AgentError), -} - -impl Response { - /// A successful response with no payload. - pub fn ok() -> Self { - Self::Ok(Payload::Empty) - } - - /// A failure response. - pub fn error(message: impl Into) -> Self { - Self::Err(AgentError::internal(message)) - } - - /// A typed failure response. - pub fn typed_error(category: AgentErrorCategory, message: impl Into) -> Self { - Self::Err(AgentError { - category, - message: message.into(), - }) - } - - /// Whether this is a success response. - pub fn is_ok(&self) -> bool { - matches!(self, Self::Ok(_)) - } -} - -/// The success payload carried by [`Response::Ok`]. -#[derive(Clone, PartialEq, Eq)] -pub enum Payload { - /// No data. - Empty, - /// Current session status. - Status(StatusInfo), - /// A dump of the live property bag. - Properties(PropertyDump), - /// Retained log lines. - Logs(Vec), - /// The most recent frame encoded as a PNG (cursor included), with its dimensions. - Screenshot { width: u16, height: u16, png: Vec }, - /// Negotiated NOW capabilities. - NowCapabilities(NowCapabilities), - /// One durable NOW operation. - NowOperation(OperationInfo), - /// Retained NOW operations. - NowOperations(Vec), - /// A sequenced NOW operation event. Streaming requests receive one response per event. - NowEvent(OperationEvent), - /// Local NOW endpoint diagnostic state. - NowDiagnostics(NowDiagnostics), -} - -impl fmt::Debug for Payload { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Empty => f.write_str("Empty"), - Self::Status(status) => f.debug_tuple("Status").field(status).finish(), - Self::Properties(dump) => f.debug_tuple("Properties").field(dump).finish(), - Self::Logs(lines) => f.debug_tuple("Logs").field(lines).finish(), - // Print the PNG byte length rather than the (large, binary) blob. - Self::Screenshot { width, height, png } => f - .debug_struct("Screenshot") - .field("width", width) - .field("height", height) - .field("png_len", &png.len()) - .finish(), - Self::NowCapabilities(capabilities) => f.debug_tuple("NowCapabilities").field(capabilities).finish(), - Self::NowOperation(operation) => f.debug_tuple("NowOperation").field(operation).finish(), - Self::NowOperations(operations) => f.debug_tuple("NowOperations").field(operations).finish(), - Self::NowEvent(event) => f.debug_tuple("NowEvent").field(event).finish(), - Self::NowDiagnostics(diagnostics) => f.debug_tuple("NowDiagnostics").field(diagnostics).finish(), - } - } -} - -/// Machine-readable error category. The message is safe for display but must not include request -/// command text or stdin. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AgentErrorCategory { - /// The caller supplied an invalid request. - InvalidRequest, - /// No suitable connected RDP/NOW session exists. - Unavailable, - /// A tracked operation conflicts with another active tracked operation. - Conflict, - /// The local transport or NOW worker failed. - Transport, - /// The remote peer rejected or failed an operation. - Remote, - /// An internal daemon operation failed. - Internal, -} - -impl AgentErrorCategory { - /// Stable lowercase category used by structured CLI output. - pub const fn as_str(self) -> &'static str { - match self { - Self::InvalidRequest => "invalid_request", - Self::Unavailable => "unavailable", - Self::Conflict => "conflict", - Self::Transport => "transport", - Self::Remote => "remote", - Self::Internal => "internal", - } - } -} - -/// Typed IPC error response. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AgentError { - /// Error category for JSON/NDJSON clients. - pub category: AgentErrorCategory, - /// Display-safe lowercase error message. - pub message: String, -} - -impl AgentError { - /// Creates an internal error. - pub fn internal(message: impl Into) -> Self { - Self { - category: AgentErrorCategory::Internal, - message: message.into(), - } - } -} - -impl fmt::Display for AgentError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.message) - } -} - -impl core::error::Error for AgentError {} - -/// NOW execution style intentionally exposed by the agent. Shell is not an option. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NowExecutionKind { - /// Windows CreateProcess. - Process, - /// Windows Batch. - Batch, - /// Windows PowerShell. - PowerShell, - /// PowerShell 7. - Pwsh, -} - -/// Request for a supported NOW tracked or detached execution. -#[derive(Clone, PartialEq, Eq)] -pub struct NowExecutionRequest { - /// Exposed NOW execution style. - pub kind: NowExecutionKind, - /// Program path for Process, or script/command for the other styles. - pub command: String, - /// Process command-line parameters. - pub parameters: Option, - /// Optional remote working directory. - pub directory: Option, - /// Optional initial stdin. - pub stdin: Option>, - /// Optional command deadline in milliseconds. - pub timeout_ms: Option, - /// Ask the peer to detach. Detached commands have no retained output or result. - pub detached: bool, - /// Request PowerShell's `-NoProfile` mode. - pub no_profile: bool, - /// Request PowerShell's `-NonInteractive` mode. - pub non_interactive: bool, -} - -impl fmt::Debug for NowExecutionRequest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("NowExecutionRequest") - .field("kind", &self.kind) - .field("command_len", &self.command.len()) - .field("parameters_len", &self.parameters.as_ref().map(String::len)) - .field("directory", &self.directory) - .field("stdin_len", &self.stdin.as_ref().map(Vec::len)) - .field("timeout_ms", &self.timeout_ms) - .field("detached", &self.detached) - .field("no_profile", &self.no_profile) - .field("non_interactive", &self.non_interactive) - .finish() - } -} - -/// Durable operation state. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum OperationState { - /// The remote operation is active. - Running, - /// Cancellation has been sent and accepted or is awaiting a terminal result. - Cancelling, - /// The remote operation completed normally. - Completed, - /// The remote operation was cancelled. - Cancelled, - /// The operation failed locally or remotely. - Failed, - /// A detached operation was submitted and cannot report further state. - Detached, -} - -/// A stream associated with a raw output chunk. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NowStream { - /// Standard output. - Stdout, - /// Standard error. - Stderr, -} - -/// Daemon-retained metadata for one NOW operation. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct OperationInfo { - /// Daemon-generated operation identity. - pub id: u64, - /// Submitted NOW style. - pub kind: NowExecutionKind, - /// Current or terminal state. - pub state: OperationState, - /// Whether this was submitted detached. - pub detached: bool, - /// Remote exit code, including nonzero values. - pub exit_code: Option, - /// Typed terminal failure, when any. - pub error: Option, - /// Bytes of raw stdout/stderr currently retained for this operation. - pub retained_output_bytes: u64, - /// Sequence assigned to the next operation event. - pub next_sequence: u64, -} - -/// A replayable NOW operation event. -#[derive(Clone, PartialEq, Eq)] -pub struct OperationEvent { - /// Daemon-generated operation identity. - pub operation_id: u64, - /// Monotonically increasing sequence number scoped to the operation. - pub sequence: u64, - /// Event content. - pub kind: OperationEventKind, -} - -impl fmt::Debug for OperationEvent { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("OperationEvent") - .field("operation_id", &self.operation_id) - .field("sequence", &self.sequence) - .field("kind", &self.kind) - .finish() - } -} - -/// Content of a replayable NOW operation event. -#[derive(Clone, PartialEq, Eq)] -pub enum OperationEventKind { - /// The remote peer started the command. - Started, - /// A raw output chunk. - Output { - /// Output stream. - stream: NowStream, - /// Exact bytes received from NOW. - data: Vec, - /// Whether this is the final chunk on this stream. - last: bool, - }, - /// The remote peer accepted a cancellation request. - CancelAccepted, - /// The command completed with an exit code. - Completed { exit_code: u32 }, - /// The command was cancelled. - Cancelled, - /// The command terminated with a typed error. - Failed(AgentError), -} - -impl fmt::Debug for OperationEventKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Started => f.write_str("Started"), - Self::Output { stream, data, last } => f - .debug_struct("Output") - .field("stream", stream) - .field("data_len", &data.len()) - .field("last", last) - .finish(), - Self::CancelAccepted => f.write_str("CancelAccepted"), - Self::Completed { exit_code } => f.debug_struct("Completed").field("exit_code", exit_code).finish(), - Self::Cancelled => f.write_str("Cancelled"), - Self::Failed(error) => f.debug_tuple("Failed").field(error).finish(), - } - } -} - -/// Local NOW endpoint diagnostic snapshot. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct NowDiagnostics { - /// Whether the RDP session has allocated a NOW DVC endpoint. - pub endpoint_allocated: bool, - /// Whether a NOW client handle is currently cached. - pub connected: bool, - /// Current cached capabilities, if a connection has already been established. - pub capabilities: Option, -} - -/// Negotiated NOW capabilities exposed without leaking the NOW PDU types. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct NowCapabilities { - /// NOW protocol major version. - pub version_major: u16, - /// NOW protocol minor version. - pub version_minor: u16, - /// Negotiated heartbeat in milliseconds, if any. - pub heartbeat_ms: Option, - /// Generic Run support. - pub run: bool, - /// CreateProcess support. - pub process: bool, - /// Batch support. - pub batch: bool, - /// Windows PowerShell support. - pub powershell: bool, - /// PowerShell 7 support. - pub pwsh: bool, - /// Tracked I/O redirection support. - pub io_redirection: bool, - /// Unicode console support. - pub unicode_console: bool, -} - -/// Coarse connection state reported by [`Request::Status`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ConnState { - /// No session has been started. - NoSession, - /// A session was started and is connecting. - Connecting, - /// A session is active (at least one frame received). - Connected, - /// A graceful disconnect was requested; the engine thread is still shutting down. - Disconnecting, - /// A session terminated gracefully. - Disconnected, - /// A session failed. - Failed, -} - -impl ConnState { - fn tag(self) -> u8 { - match self { - Self::NoSession => 0, - Self::Connecting => 1, - Self::Connected => 2, - Self::Disconnected => 3, - Self::Failed => 4, - Self::Disconnecting => 5, - } - } - - fn from_tag(tag: u8) -> DecodeResult { - match tag { - 0 => Ok(Self::NoSession), - 1 => Ok(Self::Connecting), - 2 => Ok(Self::Connected), - 3 => Ok(Self::Disconnected), - 4 => Ok(Self::Failed), - 5 => Ok(Self::Disconnecting), - _ => Err(ironrdp_core::invalid_field_err!("connection state", "unknown tag")), - } - } -} - -/// Status snapshot returned by [`Request::Status`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct StatusInfo { - /// Coarse connection state. - pub state: ConnState, - /// RDP target (`host:port`), if a session exists. - pub destination: Option, - /// Most recent frame width, if any. - pub width: Option, - /// Most recent frame height, if any. - pub height: Option, - /// Human-readable detail, e.g. the failure reason. - pub message: Option, - /// `true` when the daemon was started with preloaded credentials (an operator-provided overlay). - /// - /// When set, a caller driving `connect` does not need to supply a password (or other secrets): - /// the daemon layers the overlay on top of the request before building the configuration. - pub credentials_loaded: bool, -} - -/// A bulk dump of live properties. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PropertyDump { - /// One entry per property, in key order. - pub entries: Vec, -} - -/// A single dumped property. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PropertyEntry { - /// Property key. - pub key: String, - /// Property value. - pub value: PropValue, -} - -/// A dumped property value. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PropValue { - /// Integer value. - Int(i64), - /// String value. - Str(String), -} - -/// A small key filter for [`Request::QueryProps`]. Matching is case-insensitive. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum KeyFilter { - /// Match keys containing this substring. - Substring(String), - /// Match keys starting with this prefix. - Prefix(String), -} - -impl KeyFilter { - /// Returns `true` when `key` matches this filter (case-insensitive). - pub fn matches(&self, key: &str) -> bool { - let key = key.to_ascii_lowercase(); - match self { - Self::Substring(needle) => key.contains(&needle.to_ascii_lowercase()), - Self::Prefix(prefix) => key.starts_with(&prefix.to_ascii_lowercase()), - } - } -} - -// ── KeyFilter codec ───────────────────────────────────────────────────────── - -impl Encode for KeyFilter { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Substring(value) => { - dst.write_u8(0); - write_string(dst, value) - } - Self::Prefix(value) => { - dst.write_u8(1); - write_string(dst, value) - } - } - } - - fn name(&self) -> &'static str { - "ironrdp_agent::KeyFilter" - } - - fn size(&self) -> usize { - let value = match self { - Self::Substring(value) | Self::Prefix(value) => value, - }; - 1 /* tag */ + string_size(value) - } -} - -impl Decode<'_> for KeyFilter { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(Self::Substring(read_string(src)?)), - 1 => Ok(Self::Prefix(read_string(src)?)), - _ => Err(ironrdp_core::invalid_field_err!("key filter", "unknown tag")), - } - } -} - -impl_pdu_pod!(KeyFilter); - -// ── PropValue / PropertyEntry / PropertyDump codec ────────────────────────── - -impl Encode for PropValue { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Int(value) => { - dst.write_u8(0); - dst.write_i64(*value); - } - Self::Str(value) => { - dst.write_u8(1); - write_string(dst, value)?; - } - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::PropValue" - } - - fn size(&self) -> usize { - 1 /* tag */ - + match self { - Self::Int(_) => 8, - Self::Str(value) => string_size(value), - } - } -} - -impl Decode<'_> for PropValue { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => { - ensure_size!(in: src, size: 8); - Ok(Self::Int(src.read_i64())) - } - 1 => Ok(Self::Str(read_string(src)?)), - _ => Err(ironrdp_core::invalid_field_err!("property value", "unknown tag")), - } - } -} - -impl_pdu_pod!(PropValue); - -impl Encode for PropertyEntry { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - write_string(dst, &self.key)?; - self.value.encode(dst) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::PropertyEntry" - } - - fn size(&self) -> usize { - string_size(&self.key) + self.value.size() - } -} - -impl Decode<'_> for PropertyEntry { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - let key = read_string(src)?; - let value = PropValue::decode(src)?; - Ok(Self { key, value }) - } -} - -impl_pdu_pod!(PropertyEntry); - -impl Encode for PropertyDump { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - let count: u32 = cast_length!("property count", self.entries.len())?; - dst.write_u32(count); - for entry in &self.entries { - entry.encode(dst)?; - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::PropertyDump" - } - - fn size(&self) -> usize { - 4 /* count */ + self.entries.iter().map(Encode::size).sum::() - } -} - -impl Decode<'_> for PropertyDump { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 4); - let count = src.read_u32(); - let mut entries = Vec::new(); - for _ in 0..count { - entries.push(PropertyEntry::decode(src)?); - } - Ok(Self { entries }) - } -} - -impl_pdu_pod!(PropertyDump); - -// ── StatusInfo codec ──────────────────────────────────────────────────────── - -impl Encode for StatusInfo { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - dst.write_u8(self.state.tag()); - write_opt_string(dst, self.destination.as_deref())?; - write_opt_u16(dst, self.width)?; - write_opt_u16(dst, self.height)?; - write_opt_string(dst, self.message.as_deref())?; - write_bool(dst, self.credentials_loaded) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::StatusInfo" - } - - fn size(&self) -> usize { - 1 /* state */ - + opt_string_size(self.destination.as_deref()) - + opt_u16_size(self.width) - + opt_u16_size(self.height) - + opt_string_size(self.message.as_deref()) - + 1 /* credentials_loaded */ - } -} - -impl Decode<'_> for StatusInfo { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - let state = ConnState::from_tag(src.read_u8())?; - let destination = read_opt_string(src)?; - let width = read_opt_u16(src)?; - let height = read_opt_u16(src)?; - let message = read_opt_string(src)?; - let credentials_loaded = read_bool(src)?; - Ok(Self { - state, - destination, - width, - height, - message, - credentials_loaded, - }) - } -} - -impl_pdu_pod!(StatusInfo); - -// ── Payload codec ─────────────────────────────────────────────────────────── - -impl Encode for Payload { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Empty => dst.write_u8(0), - Self::Status(status) => { - dst.write_u8(1); - status.encode(dst)?; - } - Self::Properties(dump) => { - dst.write_u8(2); - dump.encode(dst)?; - } - Self::Logs(lines) => { - dst.write_u8(3); - let count: u32 = cast_length!("log line count", lines.len())?; - dst.write_u32(count); - for line in lines { - write_string(dst, line)?; - } - } - Self::Screenshot { width, height, png } => { - dst.write_u8(4); - dst.write_u16(*width); - dst.write_u16(*height); - write_bytes(dst, png)?; - } - Self::NowCapabilities(capabilities) => { - dst.write_u8(5); - capabilities.encode(dst)?; - } - Self::NowOperation(operation) => { - dst.write_u8(6); - operation.encode(dst)?; - } - Self::NowOperations(operations) => { - dst.write_u8(7); - let count: u32 = cast_length!("operation count", operations.len())?; - dst.write_u32(count); - for operation in operations { - operation.encode(dst)?; - } - } - Self::NowEvent(event) => { - dst.write_u8(8); - event.encode(dst)?; - } - Self::NowDiagnostics(diagnostics) => { - dst.write_u8(9); - diagnostics.encode(dst)?; - } - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::Payload" - } - - fn size(&self) -> usize { - 1 /* tag */ - + match self { - Self::Empty => 0, - Self::Status(status) => status.size(), - Self::Properties(dump) => dump.size(), - Self::Logs(lines) => 4 + lines.iter().map(|line| string_size(line)).sum::(), - Self::Screenshot { png, .. } => 2 /* width */ + 2 /* height */ + bytes_size(png), - Self::NowCapabilities(capabilities) => capabilities.size(), - Self::NowOperation(operation) => operation.size(), - Self::NowOperations(operations) => 4 + operations.iter().map(Encode::size).sum::(), - Self::NowEvent(event) => event.size(), - Self::NowDiagnostics(diagnostics) => diagnostics.size(), - } - } -} - -impl Decode<'_> for Payload { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(Self::Empty), - 1 => Ok(Self::Status(StatusInfo::decode(src)?)), - 2 => Ok(Self::Properties(PropertyDump::decode(src)?)), - 3 => { - ensure_size!(in: src, size: 4); - let count = src.read_u32(); - let mut lines = Vec::new(); - for _ in 0..count { - lines.push(read_string(src)?); - } - Ok(Self::Logs(lines)) - } - 4 => { - ensure_size!(in: src, size: 4); - let width = src.read_u16(); - let height = src.read_u16(); - let png = read_bytes(src)?; - Ok(Self::Screenshot { width, height, png }) - } - 5 => Ok(Self::NowCapabilities(NowCapabilities::decode(src)?)), - 6 => Ok(Self::NowOperation(OperationInfo::decode(src)?)), - 7 => { - ensure_size!(in: src, size: 4); - let count = src.read_u32(); - let mut operations = Vec::new(); - for _ in 0..count { - operations.push(OperationInfo::decode(src)?); - } - Ok(Self::NowOperations(operations)) - } - 8 => Ok(Self::NowEvent(OperationEvent::decode(src)?)), - 9 => Ok(Self::NowDiagnostics(NowDiagnostics::decode(src)?)), - _ => Err(ironrdp_core::invalid_field_err!("payload", "unknown tag")), - } - } -} - -impl_pdu_pod!(Payload); - -// ── Response codec ────────────────────────────────────────────────────────── - -impl Encode for Response { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Ok(payload) => { - dst.write_u8(0); - payload.encode(dst) - } - Self::Err(message) => { - dst.write_u8(1); - message.encode(dst) - } - } - } - - fn name(&self) -> &'static str { - "ironrdp_agent::Response" - } - - fn size(&self) -> usize { - 1 /* tag */ - + match self { - Self::Ok(payload) => payload.size(), - Self::Err(error) => error.size(), - } - } -} - -impl Decode<'_> for Response { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(Self::Ok(Payload::decode(src)?)), - 1 => Ok(Self::Err(AgentError::decode(src)?)), - _ => Err(ironrdp_core::invalid_field_err!("response", "unknown tag")), - } - } -} - -impl_pdu_pod!(Response); - -// ── Request codec ─────────────────────────────────────────────────────────── - -impl Encode for Request { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Connect { - properties, - log_directive, - } => { - dst.write_u8(0); - propertyset::write(properties, dst)?; - write_opt_string(dst, log_directive.as_deref())?; - } - Self::Disconnect => dst.write_u8(1), - Self::Status => dst.write_u8(2), - Self::QueryProps { filter } => { - dst.write_u8(3); - match filter { - Some(filter) => { - dst.write_u8(1); - filter.encode(dst)?; - } - None => dst.write_u8(0), - } - } - Self::QueryLogs { substring, last } => { - dst.write_u8(4); - write_opt_string(dst, substring.as_deref())?; - match last { - Some(last) => { - dst.write_u8(1); - dst.write_u32(*last); - } - None => dst.write_u8(0), - } - } - Self::Screenshot => dst.write_u8(5), - Self::MouseMove { x, y } => { - dst.write_u8(6); - dst.write_u16(*x); - dst.write_u16(*y); - } - Self::MouseButton { button, pressed } => { - dst.write_u8(7); - write_mouse_button(dst, *button)?; - write_bool(dst, *pressed)?; - } - Self::Wheel { delta, horizontal } => { - dst.write_u8(8); - dst.write_i16(*delta); - write_bool(dst, *horizontal)?; - } - Self::KeyScancode { scancode, pressed } => { - dst.write_u8(9); - dst.write_u16(*scancode); - write_bool(dst, *pressed)?; - } - Self::KeyUnicode { ch, pressed } => { - dst.write_u8(10); - write_char(dst, *ch)?; - write_bool(dst, *pressed)?; - } - Self::Resize { width, height } => { - dst.write_u8(11); - dst.write_u16(*width); - dst.write_u16(*height); - } - Self::NowCapabilities => dst.write_u8(12), - Self::NowRun { command, directory } => { - dst.write_u8(13); - write_string(dst, command)?; - write_opt_string(dst, directory.as_deref())?; - } - Self::NowExecute(request) => { - dst.write_u8(14); - request.encode(dst)?; - } - Self::NowCancel { operation_id } => { - dst.write_u8(15); - dst.write_u64(*operation_id); - } - Self::NowList => dst.write_u8(16), - Self::NowStatus { operation_id } => { - dst.write_u8(17); - dst.write_u64(*operation_id); - } - Self::NowAttach { - operation_id, - after_sequence, - } => { - dst.write_u8(18); - dst.write_u64(*operation_id); - write_opt_u64(dst, *after_sequence)?; - } - Self::NowStdin { - operation_id, - data, - last, - } => { - dst.write_u8(19); - dst.write_u64(*operation_id); - write_bytes(dst, data)?; - write_bool(dst, *last)?; - } - Self::NowDiagnostics => dst.write_u8(20), - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::Request" - } - - fn size(&self) -> usize { - 1 /* tag */ - + match self { - Self::Connect { properties, log_directive } => { - propertyset::size(properties) + opt_string_size(log_directive.as_deref()) - } - Self::Disconnect - | Self::Status - | Self::Screenshot - | Self::NowCapabilities - | Self::NowList - | Self::NowDiagnostics => 0, - Self::QueryProps { filter } => 1 /* presence */ + filter.as_ref().map_or(0, Encode::size), - Self::QueryLogs { substring, last } => { - opt_string_size(substring.as_deref()) + 1 /* presence */ + last.map_or(0, |_| 4) - } - Self::MouseMove { .. } => 2 /* x */ + 2 /* y */, - Self::MouseButton { .. } => 1 /* button */ + 1 /* pressed */, - Self::Wheel { .. } => 2 /* delta */ + 1 /* horizontal */, - Self::KeyScancode { .. } => 2 /* scancode */ + 1 /* pressed */, - Self::KeyUnicode { .. } => 4 /* ch */ + 1 /* pressed */, - Self::Resize { .. } => 2 /* width */ + 2 /* height */, - Self::NowRun { command, directory } => string_size(command) + opt_string_size(directory.as_deref()), - Self::NowExecute(request) => request.size(), - Self::NowCancel { .. } | Self::NowStatus { .. } => 8, - Self::NowAttach { after_sequence, .. } => 8 /* operation_id */ + opt_u64_size(*after_sequence), - Self::NowStdin { data, .. } => 8 /* operation_id */ + bytes_size(data) + 1 /* last */, - } - } -} - -impl Decode<'_> for Request { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => { - let mut properties = PropertySet::new(); - propertyset::read(&mut properties, src)?; - let log_directive = read_opt_string(src)?; - Ok(Self::Connect { - properties, - log_directive, - }) - } - 1 => Ok(Self::Disconnect), - 2 => Ok(Self::Status), - 3 => { - ensure_size!(in: src, size: 1); - let filter = match src.read_u8() { - 0 => None, - 1 => Some(KeyFilter::decode(src)?), - _ => return Err(ironrdp_core::invalid_field_err!("dump filter", "invalid presence flag")), - }; - Ok(Self::QueryProps { filter }) - } - 4 => { - let substring = read_opt_string(src)?; - ensure_size!(in: src, size: 1); - let last = match src.read_u8() { - 0 => None, - 1 => { - ensure_size!(in: src, size: 4); - Some(src.read_u32()) - } - _ => return Err(ironrdp_core::invalid_field_err!("query last", "invalid presence flag")), - }; - Ok(Self::QueryLogs { substring, last }) - } - 5 => Ok(Self::Screenshot), - 6 => { - ensure_size!(in: src, size: 4); - let x = src.read_u16(); - let y = src.read_u16(); - Ok(Self::MouseMove { x, y }) - } - 7 => { - let button = read_mouse_button(src)?; - let pressed = read_bool(src)?; - Ok(Self::MouseButton { button, pressed }) - } - 8 => { - ensure_size!(in: src, size: 2); - let delta = src.read_i16(); - let horizontal = read_bool(src)?; - Ok(Self::Wheel { delta, horizontal }) - } - 9 => { - ensure_size!(in: src, size: 2); - let scancode = src.read_u16(); - let pressed = read_bool(src)?; - Ok(Self::KeyScancode { scancode, pressed }) - } - 10 => { - let ch = read_char(src)?; - let pressed = read_bool(src)?; - Ok(Self::KeyUnicode { ch, pressed }) - } - 11 => { - ensure_size!(in: src, size: 4); - let width = src.read_u16(); - let height = src.read_u16(); - Ok(Self::Resize { width, height }) - } - 12 => Ok(Self::NowCapabilities), - 13 => Ok(Self::NowRun { - command: read_string(src)?, - directory: read_opt_string(src)?, - }), - 14 => Ok(Self::NowExecute(NowExecutionRequest::decode(src)?)), - 15 => { - ensure_size!(in: src, size: 8); - Ok(Self::NowCancel { - operation_id: src.read_u64(), - }) - } - 16 => Ok(Self::NowList), - 17 => { - ensure_size!(in: src, size: 8); - Ok(Self::NowStatus { - operation_id: src.read_u64(), - }) - } - 18 => { - ensure_size!(in: src, size: 8); - let operation_id = src.read_u64(); - let after_sequence = read_opt_u64(src)?; - Ok(Self::NowAttach { - operation_id, - after_sequence, - }) - } - 19 => { - ensure_size!(in: src, size: 8); - let operation_id = src.read_u64(); - let data = read_bytes(src)?; - let last = read_bool(src)?; - Ok(Self::NowStdin { - operation_id, - data, - last, - }) - } - 20 => Ok(Self::NowDiagnostics), - _ => Err(ironrdp_core::invalid_field_err!("request", "unknown tag")), - } - } -} - -impl_pdu_pod!(Request); - -// ── NOW IPC codec ────────────────────────────────────────────────────────── - -fn write_error_category(dst: &mut WriteCursor<'_>, category: AgentErrorCategory) { - dst.write_u8(match category { - AgentErrorCategory::InvalidRequest => 0, - AgentErrorCategory::Unavailable => 1, - AgentErrorCategory::Conflict => 2, - AgentErrorCategory::Transport => 3, - AgentErrorCategory::Remote => 4, - AgentErrorCategory::Internal => 5, - }); -} - -fn read_error_category(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(AgentErrorCategory::InvalidRequest), - 1 => Ok(AgentErrorCategory::Unavailable), - 2 => Ok(AgentErrorCategory::Conflict), - 3 => Ok(AgentErrorCategory::Transport), - 4 => Ok(AgentErrorCategory::Remote), - 5 => Ok(AgentErrorCategory::Internal), - _ => Err(ironrdp_core::invalid_field_err!("agent error category", "unknown tag")), - } -} - -impl Encode for AgentError { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - write_error_category(dst, self.category); - write_string(dst, &self.message) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::AgentError" - } - - fn size(&self) -> usize { - 1 /* category */ + string_size(&self.message) - } -} - -impl Decode<'_> for AgentError { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - Ok(Self { - category: read_error_category(src)?, - message: read_string(src)?, - }) - } -} - -impl_pdu_pod!(AgentError); - -fn write_execution_kind(dst: &mut WriteCursor<'_>, kind: NowExecutionKind) { - dst.write_u8(match kind { - NowExecutionKind::Process => 0, - NowExecutionKind::Batch => 1, - NowExecutionKind::PowerShell => 2, - NowExecutionKind::Pwsh => 3, - }); -} - -fn read_execution_kind(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(NowExecutionKind::Process), - 1 => Ok(NowExecutionKind::Batch), - 2 => Ok(NowExecutionKind::PowerShell), - 3 => Ok(NowExecutionKind::Pwsh), - _ => Err(ironrdp_core::invalid_field_err!("NOW execution kind", "unknown tag")), - } -} - -impl Encode for NowExecutionRequest { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - write_execution_kind(dst, self.kind); - write_string(dst, &self.command)?; - write_opt_string(dst, self.parameters.as_deref())?; - write_opt_string(dst, self.directory.as_deref())?; - match &self.stdin { - Some(data) => { - dst.write_u8(1); - write_bytes(dst, data)?; - } - None => dst.write_u8(0), - } - write_opt_u64(dst, self.timeout_ms)?; - write_bool(dst, self.detached)?; - write_bool(dst, self.no_profile)?; - write_bool(dst, self.non_interactive) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::NowExecutionRequest" - } - - fn size(&self) -> usize { - 1 /* kind */ - + string_size(&self.command) - + opt_string_size(self.parameters.as_deref()) - + opt_string_size(self.directory.as_deref()) - + 1 /* stdin presence */ - + self.stdin.as_ref().map_or(0, |data| bytes_size(data)) - + opt_u64_size(self.timeout_ms) - + 1 /* detached */ - + 1 /* no_profile */ - + 1 /* non_interactive */ - } -} - -impl Decode<'_> for NowExecutionRequest { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - let kind = read_execution_kind(src)?; - let command = read_string(src)?; - let parameters = read_opt_string(src)?; - let directory = read_opt_string(src)?; - ensure_size!(in: src, size: 1); - let stdin = match src.read_u8() { - 0 => None, - 1 => Some(read_bytes(src)?), - _ => return Err(ironrdp_core::invalid_field_err!("NOW stdin", "invalid presence flag")), - }; - Ok(Self { - kind, - command, - parameters, - directory, - stdin, - timeout_ms: read_opt_u64(src)?, - detached: read_bool(src)?, - no_profile: read_bool(src)?, - non_interactive: read_bool(src)?, - }) - } -} - -impl_pdu_pod!(NowExecutionRequest); - -fn write_operation_state(dst: &mut WriteCursor<'_>, state: OperationState) { - dst.write_u8(match state { - OperationState::Running => 0, - OperationState::Cancelling => 1, - OperationState::Completed => 2, - OperationState::Cancelled => 3, - OperationState::Failed => 4, - OperationState::Detached => 5, - }); -} - -fn read_operation_state(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(OperationState::Running), - 1 => Ok(OperationState::Cancelling), - 2 => Ok(OperationState::Completed), - 3 => Ok(OperationState::Cancelled), - 4 => Ok(OperationState::Failed), - 5 => Ok(OperationState::Detached), - _ => Err(ironrdp_core::invalid_field_err!("operation state", "unknown tag")), - } -} - -impl Encode for OperationInfo { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - dst.write_u64(self.id); - write_execution_kind(dst, self.kind); - write_operation_state(dst, self.state); - write_bool(dst, self.detached)?; - match self.exit_code { - Some(exit_code) => { - dst.write_u8(1); - dst.write_u32(exit_code); - } - None => dst.write_u8(0), - } - match &self.error { - Some(error) => { - dst.write_u8(1); - error.encode(dst)?; - } - None => dst.write_u8(0), - } - dst.write_u64(self.retained_output_bytes); - dst.write_u64(self.next_sequence); - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::OperationInfo" - } - - fn size(&self) -> usize { - 8 /* id */ - + 1 /* kind */ - + 1 /* state */ - + 1 /* detached */ - + 1 /* exit-code presence */ - + self.exit_code.map_or(0, |_| 4) - + 1 /* error presence */ - + self.error.as_ref().map_or(0, Encode::size) - + 8 /* retained_output_bytes */ - + 8 /* next_sequence */ - } -} - -impl Decode<'_> for OperationInfo { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 8); - let id = src.read_u64(); - let kind = read_execution_kind(src)?; - let state = read_operation_state(src)?; - let detached = read_bool(src)?; - ensure_size!(in: src, size: 1); - let exit_code = match src.read_u8() { - 0 => None, - 1 => { - ensure_size!(in: src, size: 4); - Some(src.read_u32()) - } - _ => return Err(ironrdp_core::invalid_field_err!("exit code", "invalid presence flag")), - }; - ensure_size!(in: src, size: 1); - let error = match src.read_u8() { - 0 => None, - 1 => Some(AgentError::decode(src)?), - _ => { - return Err(ironrdp_core::invalid_field_err!( - "operation error", - "invalid presence flag" - )); - } - }; - ensure_size!(in: src, size: 16); - Ok(Self { - id, - kind, - state, - detached, - exit_code, - error, - retained_output_bytes: src.read_u64(), - next_sequence: src.read_u64(), - }) - } -} - -impl_pdu_pod!(OperationInfo); - -fn write_stream(dst: &mut WriteCursor<'_>, stream: NowStream) { - dst.write_u8(match stream { - NowStream::Stdout => 0, - NowStream::Stderr => 1, - }); -} - -fn read_stream(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(NowStream::Stdout), - 1 => Ok(NowStream::Stderr), - _ => Err(ironrdp_core::invalid_field_err!("NOW output stream", "unknown tag")), - } -} - -impl Encode for OperationEventKind { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - match self { - Self::Started => dst.write_u8(0), - Self::Output { stream, data, last } => { - dst.write_u8(1); - write_stream(dst, *stream); - write_bytes(dst, data)?; - write_bool(dst, *last)?; - } - Self::CancelAccepted => dst.write_u8(2), - Self::Completed { exit_code } => { - dst.write_u8(3); - dst.write_u32(*exit_code); - } - Self::Cancelled => dst.write_u8(4), - Self::Failed(error) => { - dst.write_u8(5); - error.encode(dst)?; - } - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::OperationEventKind" - } - - fn size(&self) -> usize { - 1 /* tag */ - + match self { - Self::Started | Self::CancelAccepted | Self::Cancelled => 0, - Self::Output { data, .. } => 1 /* stream */ + bytes_size(data) + 1 /* last */, - Self::Completed { .. } => 4, - Self::Failed(error) => error.size(), - } - } -} - -impl Decode<'_> for OperationEventKind { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 1); - match src.read_u8() { - 0 => Ok(Self::Started), - 1 => Ok(Self::Output { - stream: read_stream(src)?, - data: read_bytes(src)?, - last: read_bool(src)?, - }), - 2 => Ok(Self::CancelAccepted), - 3 => { - ensure_size!(in: src, size: 4); - Ok(Self::Completed { - exit_code: src.read_u32(), - }) - } - 4 => Ok(Self::Cancelled), - 5 => Ok(Self::Failed(AgentError::decode(src)?)), - _ => Err(ironrdp_core::invalid_field_err!("operation event", "unknown tag")), - } - } -} - -impl_pdu_pod!(OperationEventKind); - -impl Encode for OperationEvent { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - dst.write_u64(self.operation_id); - dst.write_u64(self.sequence); - self.kind.encode(dst) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::OperationEvent" - } - - fn size(&self) -> usize { - 8 /* operation_id */ + 8 /* sequence */ + self.kind.size() - } -} - -impl Decode<'_> for OperationEvent { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 16); - Ok(Self { - operation_id: src.read_u64(), - sequence: src.read_u64(), - kind: OperationEventKind::decode(src)?, - }) - } -} - -impl_pdu_pod!(OperationEvent); - -impl Encode for NowCapabilities { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - dst.write_u16(self.version_major); - dst.write_u16(self.version_minor); - write_opt_u64(dst, self.heartbeat_ms)?; - for value in [ - self.run, - self.process, - self.batch, - self.powershell, - self.pwsh, - self.io_redirection, - self.unicode_console, - ] { - write_bool(dst, value)?; - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::NowCapabilities" - } - - fn size(&self) -> usize { - 2 /* version major */ - + 2 /* version minor */ - + opt_u64_size(self.heartbeat_ms) - + 7 /* feature flags */ - } -} - -impl Decode<'_> for NowCapabilities { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - ensure_size!(in: src, size: 4); - let version_major = src.read_u16(); - let version_minor = src.read_u16(); - Ok(Self { - version_major, - version_minor, - heartbeat_ms: read_opt_u64(src)?, - run: read_bool(src)?, - process: read_bool(src)?, - batch: read_bool(src)?, - powershell: read_bool(src)?, - pwsh: read_bool(src)?, - io_redirection: read_bool(src)?, - unicode_console: read_bool(src)?, - }) - } -} - -impl_pdu_pod!(NowCapabilities); - -impl Encode for NowDiagnostics { - fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { - ensure_size!(in: dst, size: self.size()); - write_bool(dst, self.endpoint_allocated)?; - write_bool(dst, self.connected)?; - match &self.capabilities { - Some(capabilities) => { - dst.write_u8(1); - capabilities.encode(dst)?; - } - None => dst.write_u8(0), - } - Ok(()) - } - - fn name(&self) -> &'static str { - "ironrdp_agent::NowDiagnostics" - } - - fn size(&self) -> usize { - 1 /* endpoint_allocated */ - + 1 /* connected */ - + 1 /* capabilities presence */ - + self.capabilities.as_ref().map_or(0, Encode::size) - } -} - -impl Decode<'_> for NowDiagnostics { - fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { - let endpoint_allocated = read_bool(src)?; - let connected = read_bool(src)?; - ensure_size!(in: src, size: 1); - let capabilities = match src.read_u8() { - 0 => None, - 1 => Some(NowCapabilities::decode(src)?), - _ => { - return Err(ironrdp_core::invalid_field_err!( - "NOW capabilities", - "invalid presence flag" - )); - } - }; - Ok(Self { - endpoint_allocated, - connected, - capabilities, - }) - } -} - -impl_pdu_pod!(NowDiagnostics); +pub use ironrdp_rpc::ipc::*; diff --git a/crates/ironrdp-agent/src/lib.rs b/crates/ironrdp-agent/src/lib.rs index d93ba422a..b45923219 100644 --- a/crates/ironrdp-agent/src/lib.rs +++ b/crates/ironrdp-agent/src/lib.rs @@ -24,6 +24,4 @@ pub(crate) mod logbuf; // so they can be unit tested from the workspace test suite. #[cfg(feature = "internal")] #[doc(hidden)] -pub mod wire; -#[cfg(not(feature = "internal"))] -pub(crate) mod wire; +pub use ironrdp_rpc::wire; diff --git a/crates/ironrdp-agent/src/transport.rs b/crates/ironrdp-agent/src/transport.rs index 595072fc3..fe8a0a00e 100644 --- a/crates/ironrdp-agent/src/transport.rs +++ b/crates/ironrdp-agent/src/transport.rs @@ -1,496 +1,3 @@ -//! Local IPC transport and message framing. -//! -//! The daemon and CLI talk over a platform-native local transport: -//! -//! - **Unix**: a [`tokio::net::UnixListener`]/[`tokio::net::UnixStream`] at -//! `$XDG_RUNTIME_DIR/ironrdp-agent-.sock`, falling back to `/tmp/ironrdp-agent-.sock` -//! when `XDG_RUNTIME_DIR` is unset. -//! - **Windows**: a named pipe at `\\.\pipe\ironrdp-agent-`, restricted to the current user. -//! -//! Framing is identical on both: a little-endian `u32` byte-count prefix followed by the `Encode`d -//! message body. +//! Compatibility re-export for the shared local RPC transport. -use anyhow::{Context as _, bail}; -use ironrdp_core::{DecodeOwned, Encode}; -use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; - -use crate::ipc::{Request, Response}; - -/// Upper bound on a single framed message, guarding against absurd length prefixes. -const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024; - -/// Writes `message` to `stream`, length-delimited. -pub(crate) async fn write_message(stream: &mut S, message: &M) -> anyhow::Result<()> -where - S: AsyncWrite + Unpin, - M: Encode, -{ - let body = ironrdp_core::encode_vec(message).map_err(|e| anyhow::anyhow!("encode {}: {e}", message.name()))?; - let len = u32::try_from(body.len()).context("message too large to frame")?; - stream - .write_all(&len.to_le_bytes()) - .await - .context("write frame length")?; - stream.write_all(&body).await.context("write frame body")?; - stream.flush().await.context("flush frame")?; - Ok(()) -} - -/// Reads a single length-delimited message from `stream`. -pub(crate) async fn read_message(stream: &mut S) -> anyhow::Result -where - S: AsyncRead + Unpin, - M: DecodeOwned, -{ - let mut len_buf = [0u8; 4]; - stream.read_exact(&mut len_buf).await.context("read frame length")?; - let len = usize::try_from(u32::from_le_bytes(len_buf)).expect("u32 fits in usize on supported platforms"); - if MAX_MESSAGE_LEN < len { - bail!("frame length {len} exceeds the {MAX_MESSAGE_LEN}-byte limit"); - } - let mut body = vec![0u8; len]; - stream.read_exact(&mut body).await.context("read frame body")?; - ironrdp_core::decode_owned(&body).map_err(|e| anyhow::anyhow!("decode: {e}")) -} - -/// Opens the endpoint, sends one `request`, and returns the daemon's `Response`. -pub async fn send_request(endpoint: &Endpoint, request: &Request) -> anyhow::Result { - let mut stream = open_stream(endpoint, request).await?; - read_message(&mut stream).await -} - -/// Opens an IPC connection, sends `request`, and leaves the stream available for streamed replies. -pub async fn open_stream(endpoint: &Endpoint, request: &Request) -> anyhow::Result { - let mut stream = connect(endpoint) - .await - .with_context(|| format!("connect to daemon at {endpoint}"))?; - write_message(&mut stream, request).await?; - Ok(stream) -} - -#[cfg(unix)] -mod imp { - use std::io; - use std::path::PathBuf; - - use tokio::net::{UnixListener, UnixStream}; - - /// A resolved IPC endpoint (a Unix domain socket path). - #[derive(Debug, Clone)] - pub struct Endpoint(pub PathBuf); - - impl core::fmt::Display for Endpoint { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.0.display()) - } - } - - /// Returns the default per-user endpoint. - pub fn default_endpoint() -> Endpoint { - // SAFETY: `getuid` has no preconditions and is always safe to call. - let uid = unsafe { libc::getuid() }; - let dir = std::env::var_os("XDG_RUNTIME_DIR") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from("/tmp")); - Endpoint(dir.join(format!("ironrdp-agent-{uid}.sock"))) - } - - /// Connects to a listening daemon. - pub async fn connect(endpoint: &Endpoint) -> io::Result { - UnixStream::connect(&endpoint.0).await - } - - /// A bound listener that accepts client connections. - pub struct Listener { - inner: UnixListener, - path: PathBuf, - } - - impl Listener { - /// Binds the listener at `endpoint`. - pub fn bind(endpoint: &Endpoint) -> io::Result { - let inner = UnixListener::bind(&endpoint.0)?; - // Restrict the socket to the owner. The fallback directory is world-writable `/tmp`, so - // without this any local user could connect and drive the session (input, screenshots, - // logs). Fail loudly rather than serve on a world-accessible endpoint. - use std::os::unix::fs::PermissionsExt as _; - std::fs::set_permissions(&endpoint.0, std::fs::Permissions::from_mode(0o600))?; - Ok(Self { - inner, - path: endpoint.0.clone(), - }) - } - - /// Accepts the next client connection. - pub async fn accept(&mut self) -> io::Result { - let (stream, _addr) = self.inner.accept().await?; - Ok(stream) - } - } - - impl Drop for Listener { - fn drop(&mut self) { - // Best-effort removal of the socket file on shutdown (named pipes need no cleanup). - let _ = std::fs::remove_file(&self.path); - } - } -} - -#[cfg(windows)] -mod imp { - use std::io; - - use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions}; - use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree}; - use windows::Win32::Security::Authorization::{ - ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, - }; - use windows::Win32::Security::{ - GetTokenInformation, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, - }; - use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; - use windows::core::{PCWSTR, PWSTR}; - - /// A resolved IPC endpoint (a named pipe path). - #[derive(Debug, Clone)] - pub struct Endpoint(pub String); - - impl core::fmt::Display for Endpoint { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", self.0) - } - } - - /// Returns the default per-user endpoint. - pub fn default_endpoint() -> Endpoint { - let user = whoami::username().unwrap_or_else(|_| "user".to_owned()); - Endpoint(format!(r"\\.\pipe\ironrdp-agent-{user}")) - } - - /// Connects to a listening daemon. - pub async fn connect(endpoint: &Endpoint) -> io::Result { - ClientOptions::new().open(&endpoint.0) - } - - /// Owns a process token handle and closes it on drop. - struct OwnedTokenHandle(HANDLE); - - impl Drop for OwnedTokenHandle { - fn drop(&mut self) { - // SAFETY: `self.0` is a real token handle from `OpenProcessToken`, owned exclusively by us. - if let Err(e) = unsafe { CloseHandle(self.0) } { - tracing::warn!(error = %e, "Failed to close process token handle"); - } - } - } - - /// Owns a self-relative security descriptor allocated by - /// `ConvertStringSecurityDescriptorToSecurityDescriptorW` and frees it with `LocalFree` on drop. - struct OwnedSecurityDescriptor(PSECURITY_DESCRIPTOR); - - impl OwnedSecurityDescriptor { - /// Builds a security descriptor granting access only to the current user. - /// - /// The descriptor is a protected DACL (no inherited ACEs) with a single allow-ACE granting - /// `GENERIC_ALL` to the user identified by the current process token. This mirrors the Unix - /// listener's `0o600` owner-only stance: only the user running the daemon may connect to the - /// named pipe. On shared Windows hosts the pipe namespace is otherwise reachable by every - /// local user, so this is the last line of defense against a different local user driving the - /// session (input, screenshots, logs, NOW execution). - fn for_current_user() -> io::Result { - let buffer = current_user_token_buffer()?; - let sid = sid_from_token_buffer(&buffer); - - let mut sid_wide = PWSTR(core::ptr::null_mut()); - // SAFETY: `sid` is a valid SID from the token; `sid_wide` is a valid out-pointer. - unsafe { ConvertSidToStringSidW(sid, core::ptr::addr_of_mut!(sid_wide)) } - .map_err(|e| io::Error::other(format!("convert sid to string: {e}")))?; - // SAFETY: `sid_wide` points to a null-terminated UTF-16 string allocated by the call above. - let sid_text = - unsafe { sid_wide.to_string() }.map_err(|e| io::Error::other(format!("decode sid string: {e}")))?; - // SAFETY: `sid_wide` was `LocalAlloc`'d by `ConvertSidToStringSidW` and is no longer needed. - let _ = unsafe { LocalFree(Some(HLOCAL(sid_wide.as_ptr().cast::()))) }; - - // Build the SDDL: a protected DACL granting GENERIC_ALL to the current user only. - let sddl_string = format!("D:P(A;;GA;;;{sid_text})"); - let mut sddl_utf16: Vec = sddl_string.encode_utf16().collect(); - sddl_utf16.push(0u16); - let sddl_ptr = PCWSTR::from_raw(sddl_utf16.as_ptr()); - - let mut security_descriptor = PSECURITY_DESCRIPTOR(core::ptr::null_mut()); - // SAFETY: `sddl_ptr` is a valid null-terminated SDDL string; `SDDL_REVISION_1` is the only - // supported revision; `security_descriptor` is a valid out-pointer. The returned SD is - // `LocalAlloc`'d and owned by us. - unsafe { - ConvertStringSecurityDescriptorToSecurityDescriptorW( - sddl_ptr, - SDDL_REVISION_1, - core::ptr::addr_of_mut!(security_descriptor), - None, - ) - } - .map_err(|e| io::Error::other(format!("convert sddl to security descriptor: {e}")))?; - - Ok(Self(security_descriptor)) - } - - /// Returns the raw security-descriptor pointer for use as `lpSecurityDescriptor`. - fn as_ptr(&self) -> *mut core::ffi::c_void { - self.0.0 - } - } - - impl Drop for OwnedSecurityDescriptor { - fn drop(&mut self) { - // SAFETY: `self.0` is a self-relative SD allocated by - // `ConvertStringSecurityDescriptorToSecurityDescriptorW` (via `LocalAlloc`) and owned - // exclusively by this guard. - let _ = unsafe { LocalFree(Some(HLOCAL(self.0.0))) }; - } - } - - /// Returns the buffer holding the `TOKEN_USER` of the current process token. - /// - /// The user SID is referenced by `TOKEN_USER.User.Sid` and lives inside this buffer, so keep the - /// buffer alive while using the SID pointer. - fn current_user_token_buffer() -> io::Result> { - // SAFETY: `GetCurrentProcess` has no preconditions and returns a pseudo-handle that must - // not be closed. - let process = unsafe { GetCurrentProcess() }; - - let mut token = HANDLE::default(); - // SAFETY: `process` is the valid current-process pseudo-handle; `token` is a valid out-pointer. - unsafe { OpenProcessToken(process, TOKEN_QUERY, core::ptr::addr_of_mut!(token)) } - .map_err(|e| io::Error::other(format!("open process token: {e}")))?; - let token_guard = OwnedTokenHandle(token); - let token = token_guard.0; - - // First query the required buffer size; the call fails with `ERROR_INSUFFICIENT_BUFFER`. - let mut len = 0u32; - // SAFETY: `token` is a valid token handle; a null buffer with zero length is the documented - // way to retrieve the required size; `len` is a valid out-pointer. - let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, core::ptr::addr_of_mut!(len)) }; - - let mut buffer = vec![0u8; usize::try_from(len).expect("token information length fits in usize")]; - // SAFETY: `token` is valid; `buffer` has `len` bytes as required; `len` is a valid out-pointer. - unsafe { - GetTokenInformation( - token, - TokenUser, - Some(buffer.as_mut_ptr().cast::()), - len, - core::ptr::addr_of_mut!(len), - ) - } - .map_err(|e| io::Error::other(format!("query token user: {e}")))?; - - Ok(buffer) - } - - /// Returns the user SID referenced by a token buffer from [`current_user_token_buffer`]. - fn sid_from_token_buffer(buffer: &[u8]) -> PSID { - // The buffer is byte-aligned, so read the `TOKEN_USER` header unaligned; the SID it references - // lives further inside the buffer and stays valid as long as the buffer does. - // SAFETY: `GetTokenInformation` wrote a valid `TOKEN_USER` at the start of `buffer`. - let token_user = unsafe { core::ptr::read_unaligned(buffer.as_ptr().cast::()) }; - token_user.User.Sid - } - - /// Creates one named-pipe server instance with `security` applied as its security descriptor. - /// - /// `CreateNamedPipeW` copies the security descriptor before returning, so `security` may be - /// reused across instances and need only outlive this synchronous call. `first` sets - /// `FILE_FLAG_FIRST_PIPE_INSTANCE`, which is only valid for the first instance of a pipe name. - fn create_server_instance( - name: &str, - first: bool, - security: &OwnedSecurityDescriptor, - ) -> io::Result { - let mut options = ServerOptions::new(); - if first { - options.first_pipe_instance(true); - } - - let mut attributes = SECURITY_ATTRIBUTES { - nLength: u32::try_from(size_of::()).expect("security_attributes struct fits in u32"), - lpSecurityDescriptor: security.as_ptr(), - ..Default::default() - }; - - let raw = core::ptr::addr_of_mut!(attributes).cast::(); - // SAFETY: `attributes` lives for the duration of this synchronous call; `CreateNamedPipeW` - // copies the security descriptor before returning, so dropping `attributes` afterwards is safe. - unsafe { options.create_with_security_attributes_raw(name, raw) } - } - - /// A named-pipe listener. - /// - /// It always keeps one ready (unconnected) server instance alive, which is both what serves the - /// next connection and what upholds the `first_pipe_instance` exclusivity (a pipe with no live - /// instance would let a second daemon claim the name). Every instance is created with a security - /// descriptor that restricts access to the current user, mirroring the Unix listener's `0o600`. - pub struct Listener { - name: String, - ready: NamedPipeServer, - security: OwnedSecurityDescriptor, - } - - impl Listener { - /// Creates the first pipe instance, claiming the name exclusively. - /// - /// `first_pipe_instance(true)` makes this fail with `ERROR_ACCESS_DENIED` if another daemon - /// already owns the pipe, so two daemons cannot coexist on the same endpoint. - pub fn bind(endpoint: &Endpoint) -> io::Result { - let security = OwnedSecurityDescriptor::for_current_user()?; - let ready = create_server_instance(&endpoint.0, true, &security)?; - Ok(Self { - name: endpoint.0.clone(), - ready, - security, - }) - } - - /// Waits for the next client to connect to the ready instance, then mints a replacement. - pub async fn accept(&mut self) -> io::Result { - // Connect by reference so a cancelled future leaves `ready` intact (and the pipe alive). - self.ready.connect().await?; - // Mint the next listening instance before returning so the pipe is never instance-less. - // Subsequent instances must omit `first_pipe_instance`, which is only valid on the first. - let next = create_server_instance(&self.name, false, &self.security)?; - Ok(core::mem::replace(&mut self.ready, next)) - } - } - - #[cfg(test)] - mod tests { - use super::*; - use windows::Win32::Foundation::ERROR_SUCCESS; - use windows::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT}; - use windows::Win32::Security::{ - ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, AclSizeInformation, DACL_SECURITY_INFORMATION, EqualSid, - GetAce, GetAclInformation, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, SE_DACL_PROTECTED, - }; - - /// The pipe created by the listener must actually carry the restrictive DACL, not just a - /// non-null descriptor. This catches three regressions a non-null check would miss: the SDDL - /// granting `Everyone`, the protected-DACL flag (`P`) being dropped, and `create_server_instance` - /// failing to apply the descriptor. It queries the live pipe's DACL and asserts it is - /// protected and contains exactly one allow-ACE granting `GENERIC_ALL` to the current user SID. - #[tokio::test] - async fn pipe_dacl_grants_generic_all_only_to_current_user() { - // Expected SID = current process user. - let expected_buffer = current_user_token_buffer().expect("get current user token"); - let expected_sid = sid_from_token_buffer(&expected_buffer); - - // Build the descriptor and a real server instance with a unique name. - let security = OwnedSecurityDescriptor::for_current_user().expect("build security descriptor"); - let name = format!("\\\\.\\pipe\\ironrdp-agent-acl-test-{}", std::process::id()); - let mut name_utf16: Vec = name.encode_utf16().collect(); - name_utf16.push(0u16); - let _server = create_server_instance(&name, true, &security).expect("create pipe instance"); - - // Query the pipe's actual DACL. - let mut sd = PSECURITY_DESCRIPTOR(core::ptr::null_mut()); - let mut dacl: *mut ACL = core::ptr::null_mut(); - // SAFETY: `name_utf16` is a valid null-terminated pipe path; we request only the DACL; the - // out-pointers are valid. The returned SD is `LocalAlloc`'d and owned by us until freed below. - let result = unsafe { - GetNamedSecurityInfoW( - PCWSTR::from_raw(name_utf16.as_ptr()), - SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, - None, - None, - Some(core::ptr::addr_of_mut!(dacl)), - None, - core::ptr::addr_of_mut!(sd), - ) - }; - assert_eq!(result, ERROR_SUCCESS, "GetNamedSecurityInfoW should succeed"); - - // `GetNamedSecurityInfoW` `LocalAlloc`'s the descriptor; reuse the production RAII guard so it - // is freed on drop at the end of the test even if an assertion below panics. - let _sd_guard = OwnedSecurityDescriptor(sd); - - // The DACL must be protected (no inherited ACEs from the pipe namespace). - let mut control: u16 = 0; - let mut revision: u32 = 0; - // SAFETY: `sd` is a valid self-relative SD returned by `GetNamedSecurityInfoW`. - unsafe { - GetSecurityDescriptorControl(sd, core::ptr::addr_of_mut!(control), core::ptr::addr_of_mut!(revision)) - } - .expect("get security descriptor control"); - assert!( - (control & SE_DACL_PROTECTED.0) != 0, - "DACL must be protected so inherited ACEs cannot widen access" - ); - - // Exactly one ACE must be present. - let mut dacl_present = windows::core::BOOL::default(); - let mut dacl_ptr: *mut ACL = core::ptr::null_mut(); - let mut defaulted = windows::core::BOOL::default(); - // SAFETY: `sd` is a valid SD; the out-pointers are valid. - unsafe { - GetSecurityDescriptorDacl( - sd, - core::ptr::addr_of_mut!(dacl_present), - core::ptr::addr_of_mut!(dacl_ptr), - core::ptr::addr_of_mut!(defaulted), - ) - } - .expect("get dacl"); - assert!(dacl_present.as_bool(), "DACL must be present"); - assert!(!dacl_ptr.is_null(), "DACL pointer must not be null"); - - let mut size_info = ACL_SIZE_INFORMATION::default(); - // SAFETY: `dacl_ptr` is a valid ACL; `size_info` is a valid out-buffer of the right size. - unsafe { - GetAclInformation( - dacl_ptr.cast_const(), - core::ptr::addr_of_mut!(size_info).cast::(), - u32::try_from(size_of::()).expect("acl size information fits in u32"), - AclSizeInformation, - ) - } - .expect("get acl information"); - assert_eq!(size_info.AceCount, 1, "DACL must contain exactly one ACE"); - - // The single ACE must be an allow-ACE granting GENERIC_ALL to the current user SID. - let mut ace_ptr: *mut core::ffi::c_void = core::ptr::null_mut(); - // SAFETY: `dacl_ptr` is valid and holds one ACE (verified above); `ace_ptr` is a valid out-pointer. - unsafe { GetAce(dacl_ptr.cast_const(), 0, core::ptr::addr_of_mut!(ace_ptr)) }.expect("get ace"); - assert!(!ace_ptr.is_null(), "ACE pointer must not be null"); - - // SAFETY: ACE 0 is an `ACCESS_ALLOWED_ACE` (SDDL "A;;" = allow) placed at DWORD alignment by - // the ACL; `read_unaligned` avoids any alignment assumption. - let ace: ACCESS_ALLOWED_ACE = unsafe { core::ptr::read_unaligned(ace_ptr.cast::()) }; - assert_eq!( - ace.Header.AceType, 0u8, /* ACCESS_ALLOWED_ACE_TYPE */ - "ACE must be an allow ACE" - ); - // `GENERIC_ALL` (0x10000000) in the SDDL is mapped by the kernel to the file-object-specific - // `FILE_ALL_ACCESS` (0x001F01FF) when the descriptor is stored on a named pipe, so compare - // against the mapped value rather than the generic bit. - assert_eq!( - ace.Mask, 0x001F01FFu32, /* FILE_ALL_ACCESS */ - "ACE must grant full access (GENERIC_ALL mapped to the pipe object)" - ); - - // The SID starts at `SidStart` and extends past the struct into the ACL buffer, so point into - // the in-place ACE rather than the local copy. - // SAFETY: `ace_ptr` is a non-null pointer to a valid `ACCESS_ALLOWED_ACE`; `SidStart` is the - // first DWORD of the variable-length SID that follows the fixed ACE header. - let ace_sid = PSID(unsafe { ace_ptr.byte_add(core::mem::offset_of!(ACCESS_ALLOWED_ACE, SidStart)) }); - // SAFETY: both `ace_sid` and `expected_sid` are valid SIDs from the token / ACL. - let sids_equal = unsafe { EqualSid(ace_sid, expected_sid) }.is_ok(); - assert!(sids_equal, "ACE SID must equal the current user SID"); - } - } -} - -pub use imp::{Endpoint, Listener, connect, default_endpoint}; - -#[cfg(unix)] -pub type ClientStream = tokio::net::UnixStream; -#[cfg(windows)] -pub type ClientStream = tokio::net::windows::named_pipe::NamedPipeClient; +pub use ironrdp_rpc::transport::*; diff --git a/crates/ironrdp-agent/tests/ipc.rs b/crates/ironrdp-agent/tests/ipc.rs index ad6457407..be0c262ae 100644 --- a/crates/ironrdp-agent/tests/ipc.rs +++ b/crates/ironrdp-agent/tests/ipc.rs @@ -69,8 +69,25 @@ fn daemon_reports_no_active_session() { assert!(stdout.contains("state: NoSession"), "{stdout}"); }); - let _ = daemon.kill(); - let _ = daemon.wait(); + let stop = agent(&endpoint, &["stop"]); + if result.is_ok() { + assert!(stop.status.success(), "{}", String::from_utf8_lossy(&stop.stderr)); + + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if daemon.try_wait().expect("check daemon exit").is_some() { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + } + if daemon.try_wait().expect("check daemon exit").is_none() { + let _ = daemon.kill(); + let _ = daemon.wait(); + if result.is_ok() { + panic!("daemon did not stop"); + } + } if let Err(error) = result { std::panic::resume_unwind(error); diff --git a/crates/ironrdp-rpc/Cargo.toml b/crates/ironrdp-rpc/Cargo.toml new file mode 100644 index 000000000..a2945ffac --- /dev/null +++ b/crates/ironrdp-rpc/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "ironrdp-rpc" +version = "0.1.0" +readme = "README.md" +description = "Shared local RPC protocol and transport for IronRDP clients" +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +authors.workspace = true +keywords.workspace = true +categories.workspace = true + +[dependencies] +ironrdp-core = { path = "../ironrdp-core", version = "0.2", features = ["alloc"] } +ironrdp-input = { path = "../ironrdp-input", version = "0.7" } +ironrdp-pdu = { path = "../ironrdp-pdu", version = "0.9" } +ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" } +tokio = { version = "1", features = ["net", "io-util"] } +anyhow = "1" +tracing = "0.1" + +[features] +internal = [] + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +whoami = "2.1" +windows = { version = "0.62", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_System_Threading", +] } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt"] } + +[lints] +workspace = true diff --git a/crates/ironrdp-rpc/README.md b/crates/ironrdp-rpc/README.md new file mode 100644 index 000000000..812ab8f5f --- /dev/null +++ b/crates/ironrdp-rpc/README.md @@ -0,0 +1,9 @@ +# IronRDP RPC + +Shared local RPC protocol and transport used by `ironrdp-agent` and +`ironrdp-viewer`. + +The crate provides the typed request/response schema, binary codecs, framed +messages, Unix-domain-socket transport, and Windows named-pipe transport. +It is an internal workspace crate; both endpoints must use compatible +versions of the protocol. diff --git a/crates/ironrdp-rpc/src/ipc.rs b/crates/ironrdp-rpc/src/ipc.rs new file mode 100644 index 000000000..71d39b594 --- /dev/null +++ b/crates/ironrdp-rpc/src/ipc.rs @@ -0,0 +1,1743 @@ +//! Strictly-typed local RPC schema (V1) and its binary codec. +//! +//! # Framing +//! +//! Every message is sent length-delimited: a little-endian `u32` byte-count prefix followed by the +//! `Encode`d body. The framing is identical over Unix domain sockets and Windows named pipes (see +//! [`crate::transport`]). Both ends are the same binary at the same version, so there is no version +//! byte and no forward/backward-compatibility handling. +//! +//! # Schema +//! +//! Connection configuration travels as a binary-encoded [`PropertySet`] inside [`Request::Connect`]; +//! everything else is a strictly-typed message. See [`Request`]/[`Response`]. + +use core::fmt; + +use ironrdp_core::{Decode, DecodeResult, Encode, EncodeResult, ReadCursor, WriteCursor, cast_length, ensure_size}; +use ironrdp_input::MouseButton; +use ironrdp_pdu::impl_pdu_pod; +use ironrdp_propertyset::PropertySet; + +use crate::wire::{ + bytes_size, opt_string_size, opt_u16_size, opt_u64_size, propertyset, read_bool, read_bytes, read_char, + read_mouse_button, read_opt_string, read_opt_u16, read_opt_u64, read_string, string_size, write_bool, write_bytes, + write_char, write_mouse_button, write_opt_string, write_opt_u16, write_opt_u64, write_string, +}; + +/// A request sent by the CLI to the daemon. +/// +/// `Connect` carries a binary-encoded [`PropertySet`] — never `argv` or CLI strings. Runtime +/// operations are strictly-typed. +#[derive(Clone, PartialEq, Eq)] +pub enum Request { + /// Start an RDP session from a fully-merged property bag. + /// + /// `log_directive`, when set, is a [`tracing`]-style filter directive applied to *this* + /// session's log capture (e.g. `ironrdp_connector=trace`), layered on top of the default + /// `DEBUG` level. It lets a caller raise verbosity up-front to troubleshoot a connection. + Connect { + properties: PropertySet, + log_directive: Option, + }, + /// Tear down the current RDP session (the daemon keeps running). + Disconnect, + /// Stop the long-lived RPC server after replying. + Shutdown, + /// Query the current session status. + Status, + /// Query the live session property bag, optionally filtered. + QueryProps { filter: Option }, + /// Return retained log lines, optionally filtered by substring and/or limited to the last `n`. + QueryLogs { + substring: Option, + last: Option, + }, + /// Capture the most recent frame (cursor composited in) as a PNG. + Screenshot, + /// Move the mouse pointer to an absolute position. + MouseMove { x: u16, y: u16 }, + /// Press or release a mouse button. + MouseButton { button: MouseButton, pressed: bool }, + /// Rotate the mouse wheel. + Wheel { delta: i16, horizontal: bool }, + // TODO: questioning whether we need a way to send multiple keys at once, e.g. a small mini + // format to express in a single command that keys A and B are pressed while key C is released. + // This could save LLM tokens by collapsing several round-trips into one request. + /// Press or release a key identified by its RDP scancode. + KeyScancode { scancode: u16, pressed: bool }, + /// Press or release a key identified by a Unicode character. + KeyUnicode { ch: char, pressed: bool }, + /// Resize the remote desktop. + Resize { width: u16, height: u16 }, + /// Query and negotiate the capabilities of the session's NOW endpoint. + NowCapabilities, + /// Submit an untracked generic NOW Run request. + NowRun { + /// Command line interpreted by the remote NOW agent. + command: String, + /// Optional remote working directory. + directory: Option, + }, + /// Submit a NOW operation that is tracked by the daemon unless `detached` is set. + NowExecute(NowExecutionRequest), + /// Request cancellation of the active tracked NOW operation. + NowCancel { operation_id: u64 }, + /// List daemon-retained NOW operations. + NowList, + /// Inspect a retained NOW operation. + NowStatus { operation_id: u64 }, + /// Replay retained operation events after `after_sequence` and then follow live output. + NowAttach { + operation_id: u64, + after_sequence: Option, + }, + /// Forward a bounded raw stdin chunk to a tracked operation. + NowStdin { + operation_id: u64, + data: Vec, + last: bool, + }, + /// Inspect the local NOW endpoint without exposing protocol internals. + NowDiagnostics, + // TODO: add clipboard support (CLIPRDR), e.g. requests to read the remote clipboard text and to + // set it, so an LLM can copy/paste to and from the session. +} + +// Manual `Debug` so the `Connect` payload's property *values* (which may include a password before +// it reaches `ConfigBuilder::build`) are never printed verbatim; only the keys are shown. +impl fmt::Debug for Request { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Connect { + properties, + log_directive, + } => f + .debug_struct("Connect") + .field("properties", &PropertyKeys(properties)) + .field("log_directive", log_directive) + .finish(), + Self::Disconnect => f.write_str("Disconnect"), + Self::Shutdown => f.write_str("Shutdown"), + Self::Status => f.write_str("Status"), + Self::QueryProps { filter } => f.debug_struct("QueryProps").field("filter", filter).finish(), + Self::QueryLogs { substring, last } => f + .debug_struct("QueryLogs") + .field("substring", substring) + .field("last", last) + .finish(), + Self::Screenshot => f.write_str("Screenshot"), + Self::MouseMove { x, y } => f.debug_struct("MouseMove").field("x", x).field("y", y).finish(), + Self::MouseButton { button, pressed } => f + .debug_struct("MouseButton") + .field("button", button) + .field("pressed", pressed) + .finish(), + Self::Wheel { delta, horizontal } => f + .debug_struct("Wheel") + .field("delta", delta) + .field("horizontal", horizontal) + .finish(), + Self::KeyScancode { scancode, pressed } => f + .debug_struct("KeyScancode") + .field("scancode", scancode) + .field("pressed", pressed) + .finish(), + Self::KeyUnicode { ch, pressed } => f + .debug_struct("KeyUnicode") + .field("ch", ch) + .field("pressed", pressed) + .finish(), + Self::Resize { width, height } => f + .debug_struct("Resize") + .field("width", width) + .field("height", height) + .finish(), + Self::NowCapabilities => f.write_str("NowCapabilities"), + Self::NowRun { command, directory } => f + .debug_struct("NowRun") + .field("command_len", &command.len()) + .field("directory", directory) + .finish(), + Self::NowExecute(request) => f.debug_tuple("NowExecute").field(request).finish(), + Self::NowCancel { operation_id } => { + f.debug_struct("NowCancel").field("operation_id", operation_id).finish() + } + Self::NowList => f.write_str("NowList"), + Self::NowStatus { operation_id } => { + f.debug_struct("NowStatus").field("operation_id", operation_id).finish() + } + Self::NowAttach { + operation_id, + after_sequence, + } => f + .debug_struct("NowAttach") + .field("operation_id", operation_id) + .field("after_sequence", after_sequence) + .finish(), + Self::NowStdin { + operation_id, + data, + last, + } => f + .debug_struct("NowStdin") + .field("operation_id", operation_id) + .field("data_len", &data.len()) + .field("last", last) + .finish(), + Self::NowDiagnostics => f.write_str("NowDiagnostics"), + } + } +} + +/// A [`PropertySet`] whose `Debug` output lists only the keys, never the (possibly secret) values. +struct PropertyKeys<'a>(&'a PropertySet); + +impl fmt::Debug for PropertyKeys<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self.0.iter().map(|(key, _)| key)).finish() + } +} + +/// The daemon's reply to a [`Request`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Response { + /// Success, carrying an operation-specific [`Payload`]. + Ok(Payload), + /// Failure. The message is lowercase with no trailing punctuation. + Err(AgentError), +} + +impl Response { + /// A successful response with no payload. + pub fn ok() -> Self { + Self::Ok(Payload::Empty) + } + + /// A failure response. + pub fn error(message: impl Into) -> Self { + Self::Err(AgentError::internal(message)) + } + + /// A typed failure response. + pub fn typed_error(category: AgentErrorCategory, message: impl Into) -> Self { + Self::Err(AgentError { + category, + message: message.into(), + }) + } + + /// Whether this is a success response. + pub fn is_ok(&self) -> bool { + matches!(self, Self::Ok(_)) + } +} + +/// The success payload carried by [`Response::Ok`]. +#[derive(Clone, PartialEq, Eq)] +pub enum Payload { + /// No data. + Empty, + /// Current session status. + Status(StatusInfo), + /// A dump of the live property bag. + Properties(PropertyDump), + /// Retained log lines. + Logs(Vec), + /// The most recent frame encoded as a PNG (cursor included), with its dimensions. + Screenshot { width: u16, height: u16, png: Vec }, + /// Negotiated NOW capabilities. + NowCapabilities(NowCapabilities), + /// One durable NOW operation. + NowOperation(OperationInfo), + /// Retained NOW operations. + NowOperations(Vec), + /// A sequenced NOW operation event. Streaming requests receive one response per event. + NowEvent(OperationEvent), + /// Local NOW endpoint diagnostic state. + NowDiagnostics(NowDiagnostics), +} + +impl fmt::Debug for Payload { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Empty => f.write_str("Empty"), + Self::Status(status) => f.debug_tuple("Status").field(status).finish(), + Self::Properties(dump) => f.debug_tuple("Properties").field(dump).finish(), + Self::Logs(lines) => f.debug_tuple("Logs").field(lines).finish(), + // Print the PNG byte length rather than the (large, binary) blob. + Self::Screenshot { width, height, png } => f + .debug_struct("Screenshot") + .field("width", width) + .field("height", height) + .field("png_len", &png.len()) + .finish(), + Self::NowCapabilities(capabilities) => f.debug_tuple("NowCapabilities").field(capabilities).finish(), + Self::NowOperation(operation) => f.debug_tuple("NowOperation").field(operation).finish(), + Self::NowOperations(operations) => f.debug_tuple("NowOperations").field(operations).finish(), + Self::NowEvent(event) => f.debug_tuple("NowEvent").field(event).finish(), + Self::NowDiagnostics(diagnostics) => f.debug_tuple("NowDiagnostics").field(diagnostics).finish(), + } + } +} + +/// Machine-readable error category. The message is safe for display but must not include request +/// command text or stdin. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AgentErrorCategory { + /// The caller supplied an invalid request. + InvalidRequest, + /// No suitable connected RDP/NOW session exists. + Unavailable, + /// A tracked operation conflicts with another active tracked operation. + Conflict, + /// The local transport or NOW worker failed. + Transport, + /// The remote peer rejected or failed an operation. + Remote, + /// An internal daemon operation failed. + Internal, +} + +impl AgentErrorCategory { + /// Stable lowercase category used by structured CLI output. + pub const fn as_str(self) -> &'static str { + match self { + Self::InvalidRequest => "invalid_request", + Self::Unavailable => "unavailable", + Self::Conflict => "conflict", + Self::Transport => "transport", + Self::Remote => "remote", + Self::Internal => "internal", + } + } +} + +/// Typed IPC error response. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentError { + /// Error category for JSON/NDJSON clients. + pub category: AgentErrorCategory, + /// Display-safe lowercase error message. + pub message: String, +} + +impl AgentError { + /// Creates an internal error. + pub fn internal(message: impl Into) -> Self { + Self { + category: AgentErrorCategory::Internal, + message: message.into(), + } + } +} + +impl fmt::Display for AgentError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl core::error::Error for AgentError {} + +/// NOW execution style intentionally exposed by the agent. Shell is not an option. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NowExecutionKind { + /// Windows CreateProcess. + Process, + /// Windows Batch. + Batch, + /// Windows PowerShell. + PowerShell, + /// PowerShell 7. + Pwsh, +} + +/// Request for a supported NOW tracked or detached execution. +#[derive(Clone, PartialEq, Eq)] +pub struct NowExecutionRequest { + /// Exposed NOW execution style. + pub kind: NowExecutionKind, + /// Program path for Process, or script/command for the other styles. + pub command: String, + /// Process command-line parameters. + pub parameters: Option, + /// Optional remote working directory. + pub directory: Option, + /// Optional initial stdin. + pub stdin: Option>, + /// Optional command deadline in milliseconds. + pub timeout_ms: Option, + /// Ask the peer to detach. Detached commands have no retained output or result. + pub detached: bool, + /// Request PowerShell's `-NoProfile` mode. + pub no_profile: bool, + /// Request PowerShell's `-NonInteractive` mode. + pub non_interactive: bool, +} + +impl fmt::Debug for NowExecutionRequest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NowExecutionRequest") + .field("kind", &self.kind) + .field("command_len", &self.command.len()) + .field("parameters_len", &self.parameters.as_ref().map(String::len)) + .field("directory", &self.directory) + .field("stdin_len", &self.stdin.as_ref().map(Vec::len)) + .field("timeout_ms", &self.timeout_ms) + .field("detached", &self.detached) + .field("no_profile", &self.no_profile) + .field("non_interactive", &self.non_interactive) + .finish() + } +} + +/// Durable operation state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OperationState { + /// The remote operation is active. + Running, + /// Cancellation has been sent and accepted or is awaiting a terminal result. + Cancelling, + /// The remote operation completed normally. + Completed, + /// The remote operation was cancelled. + Cancelled, + /// The operation failed locally or remotely. + Failed, + /// A detached operation was submitted and cannot report further state. + Detached, +} + +/// A stream associated with a raw output chunk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NowStream { + /// Standard output. + Stdout, + /// Standard error. + Stderr, +} + +/// Daemon-retained metadata for one NOW operation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OperationInfo { + /// Daemon-generated operation identity. + pub id: u64, + /// Submitted NOW style. + pub kind: NowExecutionKind, + /// Current or terminal state. + pub state: OperationState, + /// Whether this was submitted detached. + pub detached: bool, + /// Remote exit code, including nonzero values. + pub exit_code: Option, + /// Typed terminal failure, when any. + pub error: Option, + /// Bytes of raw stdout/stderr currently retained for this operation. + pub retained_output_bytes: u64, + /// Sequence assigned to the next operation event. + pub next_sequence: u64, +} + +/// A replayable NOW operation event. +#[derive(Clone, PartialEq, Eq)] +pub struct OperationEvent { + /// Daemon-generated operation identity. + pub operation_id: u64, + /// Monotonically increasing sequence number scoped to the operation. + pub sequence: u64, + /// Event content. + pub kind: OperationEventKind, +} + +impl fmt::Debug for OperationEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OperationEvent") + .field("operation_id", &self.operation_id) + .field("sequence", &self.sequence) + .field("kind", &self.kind) + .finish() + } +} + +/// Content of a replayable NOW operation event. +#[derive(Clone, PartialEq, Eq)] +pub enum OperationEventKind { + /// The remote peer started the command. + Started, + /// A raw output chunk. + Output { + /// Output stream. + stream: NowStream, + /// Exact bytes received from NOW. + data: Vec, + /// Whether this is the final chunk on this stream. + last: bool, + }, + /// The remote peer accepted a cancellation request. + CancelAccepted, + /// The command completed with an exit code. + Completed { exit_code: u32 }, + /// The command was cancelled. + Cancelled, + /// The command terminated with a typed error. + Failed(AgentError), +} + +impl fmt::Debug for OperationEventKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Started => f.write_str("Started"), + Self::Output { stream, data, last } => f + .debug_struct("Output") + .field("stream", stream) + .field("data_len", &data.len()) + .field("last", last) + .finish(), + Self::CancelAccepted => f.write_str("CancelAccepted"), + Self::Completed { exit_code } => f.debug_struct("Completed").field("exit_code", exit_code).finish(), + Self::Cancelled => f.write_str("Cancelled"), + Self::Failed(error) => f.debug_tuple("Failed").field(error).finish(), + } + } +} + +/// Local NOW endpoint diagnostic snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NowDiagnostics { + /// Whether the RDP session has allocated a NOW DVC endpoint. + pub endpoint_allocated: bool, + /// Whether a NOW client handle is currently cached. + pub connected: bool, + /// Current cached capabilities, if a connection has already been established. + pub capabilities: Option, +} + +/// Negotiated NOW capabilities exposed without leaking the NOW PDU types. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NowCapabilities { + /// NOW protocol major version. + pub version_major: u16, + /// NOW protocol minor version. + pub version_minor: u16, + /// Negotiated heartbeat in milliseconds, if any. + pub heartbeat_ms: Option, + /// Generic Run support. + pub run: bool, + /// CreateProcess support. + pub process: bool, + /// Batch support. + pub batch: bool, + /// Windows PowerShell support. + pub powershell: bool, + /// PowerShell 7 support. + pub pwsh: bool, + /// Tracked I/O redirection support. + pub io_redirection: bool, + /// Unicode console support. + pub unicode_console: bool, +} + +/// Coarse connection state reported by [`Request::Status`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConnState { + /// No session has been started. + NoSession, + /// A session was started and is connecting. + Connecting, + /// A session is active (at least one frame received). + Connected, + /// A graceful disconnect was requested; the engine thread is still shutting down. + Disconnecting, + /// A session terminated gracefully. + Disconnected, + /// A session failed. + Failed, +} + +impl ConnState { + fn tag(self) -> u8 { + match self { + Self::NoSession => 0, + Self::Connecting => 1, + Self::Connected => 2, + Self::Disconnected => 3, + Self::Failed => 4, + Self::Disconnecting => 5, + } + } + + fn from_tag(tag: u8) -> DecodeResult { + match tag { + 0 => Ok(Self::NoSession), + 1 => Ok(Self::Connecting), + 2 => Ok(Self::Connected), + 3 => Ok(Self::Disconnected), + 4 => Ok(Self::Failed), + 5 => Ok(Self::Disconnecting), + _ => Err(ironrdp_core::invalid_field_err!("connection state", "unknown tag")), + } + } +} + +/// Status snapshot returned by [`Request::Status`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StatusInfo { + /// Coarse connection state. + pub state: ConnState, + /// RDP target (`host:port`), if a session exists. + pub destination: Option, + /// Most recent frame width, if any. + pub width: Option, + /// Most recent frame height, if any. + pub height: Option, + /// Human-readable detail, e.g. the failure reason. + pub message: Option, + /// `true` when the daemon was started with preloaded credentials (an operator-provided overlay). + /// + /// When set, a caller driving `connect` does not need to supply a password (or other secrets): + /// the daemon layers the overlay on top of the request before building the configuration. + pub credentials_loaded: bool, +} + +/// A bulk dump of live properties. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PropertyDump { + /// One entry per property, in key order. + pub entries: Vec, +} + +/// A single dumped property. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PropertyEntry { + /// Property key. + pub key: String, + /// Property value. + pub value: PropValue, +} + +/// A dumped property value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PropValue { + /// Integer value. + Int(i64), + /// String value. + Str(String), +} + +/// A small key filter for [`Request::QueryProps`]. Matching is case-insensitive. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyFilter { + /// Match keys containing this substring. + Substring(String), + /// Match keys starting with this prefix. + Prefix(String), +} + +impl KeyFilter { + /// Returns `true` when `key` matches this filter (case-insensitive). + pub fn matches(&self, key: &str) -> bool { + let key = key.to_ascii_lowercase(); + match self { + Self::Substring(needle) => key.contains(&needle.to_ascii_lowercase()), + Self::Prefix(prefix) => key.starts_with(&prefix.to_ascii_lowercase()), + } + } +} + +// ── KeyFilter codec ───────────────────────────────────────────────────────── + +impl Encode for KeyFilter { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Substring(value) => { + dst.write_u8(0); + write_string(dst, value) + } + Self::Prefix(value) => { + dst.write_u8(1); + write_string(dst, value) + } + } + } + + fn name(&self) -> &'static str { + "ironrdp_agent::KeyFilter" + } + + fn size(&self) -> usize { + let value = match self { + Self::Substring(value) | Self::Prefix(value) => value, + }; + 1 /* tag */ + string_size(value) + } +} + +impl Decode<'_> for KeyFilter { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(Self::Substring(read_string(src)?)), + 1 => Ok(Self::Prefix(read_string(src)?)), + _ => Err(ironrdp_core::invalid_field_err!("key filter", "unknown tag")), + } + } +} + +impl_pdu_pod!(KeyFilter); + +// ── PropValue / PropertyEntry / PropertyDump codec ────────────────────────── + +impl Encode for PropValue { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Int(value) => { + dst.write_u8(0); + dst.write_i64(*value); + } + Self::Str(value) => { + dst.write_u8(1); + write_string(dst, value)?; + } + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::PropValue" + } + + fn size(&self) -> usize { + 1 /* tag */ + + match self { + Self::Int(_) => 8, + Self::Str(value) => string_size(value), + } + } +} + +impl Decode<'_> for PropValue { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => { + ensure_size!(in: src, size: 8); + Ok(Self::Int(src.read_i64())) + } + 1 => Ok(Self::Str(read_string(src)?)), + _ => Err(ironrdp_core::invalid_field_err!("property value", "unknown tag")), + } + } +} + +impl_pdu_pod!(PropValue); + +impl Encode for PropertyEntry { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + write_string(dst, &self.key)?; + self.value.encode(dst) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::PropertyEntry" + } + + fn size(&self) -> usize { + string_size(&self.key) + self.value.size() + } +} + +impl Decode<'_> for PropertyEntry { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + let key = read_string(src)?; + let value = PropValue::decode(src)?; + Ok(Self { key, value }) + } +} + +impl_pdu_pod!(PropertyEntry); + +impl Encode for PropertyDump { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + let count: u32 = cast_length!("property count", self.entries.len())?; + dst.write_u32(count); + for entry in &self.entries { + entry.encode(dst)?; + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::PropertyDump" + } + + fn size(&self) -> usize { + 4 /* count */ + self.entries.iter().map(Encode::size).sum::() + } +} + +impl Decode<'_> for PropertyDump { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 4); + let count = src.read_u32(); + let mut entries = Vec::new(); + for _ in 0..count { + entries.push(PropertyEntry::decode(src)?); + } + Ok(Self { entries }) + } +} + +impl_pdu_pod!(PropertyDump); + +// ── StatusInfo codec ──────────────────────────────────────────────────────── + +impl Encode for StatusInfo { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + dst.write_u8(self.state.tag()); + write_opt_string(dst, self.destination.as_deref())?; + write_opt_u16(dst, self.width)?; + write_opt_u16(dst, self.height)?; + write_opt_string(dst, self.message.as_deref())?; + write_bool(dst, self.credentials_loaded) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::StatusInfo" + } + + fn size(&self) -> usize { + 1 /* state */ + + opt_string_size(self.destination.as_deref()) + + opt_u16_size(self.width) + + opt_u16_size(self.height) + + opt_string_size(self.message.as_deref()) + + 1 /* credentials_loaded */ + } +} + +impl Decode<'_> for StatusInfo { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + let state = ConnState::from_tag(src.read_u8())?; + let destination = read_opt_string(src)?; + let width = read_opt_u16(src)?; + let height = read_opt_u16(src)?; + let message = read_opt_string(src)?; + let credentials_loaded = read_bool(src)?; + Ok(Self { + state, + destination, + width, + height, + message, + credentials_loaded, + }) + } +} + +impl_pdu_pod!(StatusInfo); + +// ── Payload codec ─────────────────────────────────────────────────────────── + +impl Encode for Payload { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Empty => dst.write_u8(0), + Self::Status(status) => { + dst.write_u8(1); + status.encode(dst)?; + } + Self::Properties(dump) => { + dst.write_u8(2); + dump.encode(dst)?; + } + Self::Logs(lines) => { + dst.write_u8(3); + let count: u32 = cast_length!("log line count", lines.len())?; + dst.write_u32(count); + for line in lines { + write_string(dst, line)?; + } + } + Self::Screenshot { width, height, png } => { + dst.write_u8(4); + dst.write_u16(*width); + dst.write_u16(*height); + write_bytes(dst, png)?; + } + Self::NowCapabilities(capabilities) => { + dst.write_u8(5); + capabilities.encode(dst)?; + } + Self::NowOperation(operation) => { + dst.write_u8(6); + operation.encode(dst)?; + } + Self::NowOperations(operations) => { + dst.write_u8(7); + let count: u32 = cast_length!("operation count", operations.len())?; + dst.write_u32(count); + for operation in operations { + operation.encode(dst)?; + } + } + Self::NowEvent(event) => { + dst.write_u8(8); + event.encode(dst)?; + } + Self::NowDiagnostics(diagnostics) => { + dst.write_u8(9); + diagnostics.encode(dst)?; + } + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::Payload" + } + + fn size(&self) -> usize { + 1 /* tag */ + + match self { + Self::Empty => 0, + Self::Status(status) => status.size(), + Self::Properties(dump) => dump.size(), + Self::Logs(lines) => 4 + lines.iter().map(|line| string_size(line)).sum::(), + Self::Screenshot { png, .. } => 2 /* width */ + 2 /* height */ + bytes_size(png), + Self::NowCapabilities(capabilities) => capabilities.size(), + Self::NowOperation(operation) => operation.size(), + Self::NowOperations(operations) => 4 + operations.iter().map(Encode::size).sum::(), + Self::NowEvent(event) => event.size(), + Self::NowDiagnostics(diagnostics) => diagnostics.size(), + } + } +} + +impl Decode<'_> for Payload { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(Self::Empty), + 1 => Ok(Self::Status(StatusInfo::decode(src)?)), + 2 => Ok(Self::Properties(PropertyDump::decode(src)?)), + 3 => { + ensure_size!(in: src, size: 4); + let count = src.read_u32(); + let mut lines = Vec::new(); + for _ in 0..count { + lines.push(read_string(src)?); + } + Ok(Self::Logs(lines)) + } + 4 => { + ensure_size!(in: src, size: 4); + let width = src.read_u16(); + let height = src.read_u16(); + let png = read_bytes(src)?; + Ok(Self::Screenshot { width, height, png }) + } + 5 => Ok(Self::NowCapabilities(NowCapabilities::decode(src)?)), + 6 => Ok(Self::NowOperation(OperationInfo::decode(src)?)), + 7 => { + ensure_size!(in: src, size: 4); + let count = src.read_u32(); + let mut operations = Vec::new(); + for _ in 0..count { + operations.push(OperationInfo::decode(src)?); + } + Ok(Self::NowOperations(operations)) + } + 8 => Ok(Self::NowEvent(OperationEvent::decode(src)?)), + 9 => Ok(Self::NowDiagnostics(NowDiagnostics::decode(src)?)), + _ => Err(ironrdp_core::invalid_field_err!("payload", "unknown tag")), + } + } +} + +impl_pdu_pod!(Payload); + +// ── Response codec ────────────────────────────────────────────────────────── + +impl Encode for Response { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Ok(payload) => { + dst.write_u8(0); + payload.encode(dst) + } + Self::Err(message) => { + dst.write_u8(1); + message.encode(dst) + } + } + } + + fn name(&self) -> &'static str { + "ironrdp_agent::Response" + } + + fn size(&self) -> usize { + 1 /* tag */ + + match self { + Self::Ok(payload) => payload.size(), + Self::Err(error) => error.size(), + } + } +} + +impl Decode<'_> for Response { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(Self::Ok(Payload::decode(src)?)), + 1 => Ok(Self::Err(AgentError::decode(src)?)), + _ => Err(ironrdp_core::invalid_field_err!("response", "unknown tag")), + } + } +} + +impl_pdu_pod!(Response); + +// ── Request codec ─────────────────────────────────────────────────────────── + +impl Encode for Request { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Connect { + properties, + log_directive, + } => { + dst.write_u8(0); + propertyset::write(properties, dst)?; + write_opt_string(dst, log_directive.as_deref())?; + } + Self::Disconnect => dst.write_u8(1), + Self::Shutdown => dst.write_u8(21), + Self::Status => dst.write_u8(2), + Self::QueryProps { filter } => { + dst.write_u8(3); + match filter { + Some(filter) => { + dst.write_u8(1); + filter.encode(dst)?; + } + None => dst.write_u8(0), + } + } + Self::QueryLogs { substring, last } => { + dst.write_u8(4); + write_opt_string(dst, substring.as_deref())?; + match last { + Some(last) => { + dst.write_u8(1); + dst.write_u32(*last); + } + None => dst.write_u8(0), + } + } + Self::Screenshot => dst.write_u8(5), + Self::MouseMove { x, y } => { + dst.write_u8(6); + dst.write_u16(*x); + dst.write_u16(*y); + } + Self::MouseButton { button, pressed } => { + dst.write_u8(7); + write_mouse_button(dst, *button)?; + write_bool(dst, *pressed)?; + } + Self::Wheel { delta, horizontal } => { + dst.write_u8(8); + dst.write_i16(*delta); + write_bool(dst, *horizontal)?; + } + Self::KeyScancode { scancode, pressed } => { + dst.write_u8(9); + dst.write_u16(*scancode); + write_bool(dst, *pressed)?; + } + Self::KeyUnicode { ch, pressed } => { + dst.write_u8(10); + write_char(dst, *ch)?; + write_bool(dst, *pressed)?; + } + Self::Resize { width, height } => { + dst.write_u8(11); + dst.write_u16(*width); + dst.write_u16(*height); + } + Self::NowCapabilities => dst.write_u8(12), + Self::NowRun { command, directory } => { + dst.write_u8(13); + write_string(dst, command)?; + write_opt_string(dst, directory.as_deref())?; + } + Self::NowExecute(request) => { + dst.write_u8(14); + request.encode(dst)?; + } + Self::NowCancel { operation_id } => { + dst.write_u8(15); + dst.write_u64(*operation_id); + } + Self::NowList => dst.write_u8(16), + Self::NowStatus { operation_id } => { + dst.write_u8(17); + dst.write_u64(*operation_id); + } + Self::NowAttach { + operation_id, + after_sequence, + } => { + dst.write_u8(18); + dst.write_u64(*operation_id); + write_opt_u64(dst, *after_sequence)?; + } + Self::NowStdin { + operation_id, + data, + last, + } => { + dst.write_u8(19); + dst.write_u64(*operation_id); + write_bytes(dst, data)?; + write_bool(dst, *last)?; + } + Self::NowDiagnostics => dst.write_u8(20), + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::Request" + } + + fn size(&self) -> usize { + 1 /* tag */ + + match self { + Self::Connect { properties, log_directive } => { + propertyset::size(properties) + opt_string_size(log_directive.as_deref()) + } + Self::Disconnect + | Self::Shutdown + | Self::Status + | Self::Screenshot + | Self::NowCapabilities + | Self::NowList + | Self::NowDiagnostics => 0, + Self::QueryProps { filter } => 1 /* presence */ + filter.as_ref().map_or(0, Encode::size), + Self::QueryLogs { substring, last } => { + opt_string_size(substring.as_deref()) + 1 /* presence */ + last.map_or(0, |_| 4) + } + Self::MouseMove { .. } => 2 /* x */ + 2 /* y */, + Self::MouseButton { .. } => 1 /* button */ + 1 /* pressed */, + Self::Wheel { .. } => 2 /* delta */ + 1 /* horizontal */, + Self::KeyScancode { .. } => 2 /* scancode */ + 1 /* pressed */, + Self::KeyUnicode { .. } => 4 /* ch */ + 1 /* pressed */, + Self::Resize { .. } => 2 /* width */ + 2 /* height */, + Self::NowRun { command, directory } => string_size(command) + opt_string_size(directory.as_deref()), + Self::NowExecute(request) => request.size(), + Self::NowCancel { .. } | Self::NowStatus { .. } => 8, + Self::NowAttach { after_sequence, .. } => 8 /* operation_id */ + opt_u64_size(*after_sequence), + Self::NowStdin { data, .. } => 8 /* operation_id */ + bytes_size(data) + 1 /* last */, + } + } +} + +impl Decode<'_> for Request { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => { + let mut properties = PropertySet::new(); + propertyset::read(&mut properties, src)?; + let log_directive = read_opt_string(src)?; + Ok(Self::Connect { + properties, + log_directive, + }) + } + 1 => Ok(Self::Disconnect), + 2 => Ok(Self::Status), + 3 => { + ensure_size!(in: src, size: 1); + let filter = match src.read_u8() { + 0 => None, + 1 => Some(KeyFilter::decode(src)?), + _ => return Err(ironrdp_core::invalid_field_err!("dump filter", "invalid presence flag")), + }; + Ok(Self::QueryProps { filter }) + } + 4 => { + let substring = read_opt_string(src)?; + ensure_size!(in: src, size: 1); + let last = match src.read_u8() { + 0 => None, + 1 => { + ensure_size!(in: src, size: 4); + Some(src.read_u32()) + } + _ => return Err(ironrdp_core::invalid_field_err!("query last", "invalid presence flag")), + }; + Ok(Self::QueryLogs { substring, last }) + } + 5 => Ok(Self::Screenshot), + 6 => { + ensure_size!(in: src, size: 4); + let x = src.read_u16(); + let y = src.read_u16(); + Ok(Self::MouseMove { x, y }) + } + 7 => { + let button = read_mouse_button(src)?; + let pressed = read_bool(src)?; + Ok(Self::MouseButton { button, pressed }) + } + 8 => { + ensure_size!(in: src, size: 2); + let delta = src.read_i16(); + let horizontal = read_bool(src)?; + Ok(Self::Wheel { delta, horizontal }) + } + 9 => { + ensure_size!(in: src, size: 2); + let scancode = src.read_u16(); + let pressed = read_bool(src)?; + Ok(Self::KeyScancode { scancode, pressed }) + } + 10 => { + let ch = read_char(src)?; + let pressed = read_bool(src)?; + Ok(Self::KeyUnicode { ch, pressed }) + } + 11 => { + ensure_size!(in: src, size: 4); + let width = src.read_u16(); + let height = src.read_u16(); + Ok(Self::Resize { width, height }) + } + 12 => Ok(Self::NowCapabilities), + 13 => Ok(Self::NowRun { + command: read_string(src)?, + directory: read_opt_string(src)?, + }), + 14 => Ok(Self::NowExecute(NowExecutionRequest::decode(src)?)), + 15 => { + ensure_size!(in: src, size: 8); + Ok(Self::NowCancel { + operation_id: src.read_u64(), + }) + } + 16 => Ok(Self::NowList), + 17 => { + ensure_size!(in: src, size: 8); + Ok(Self::NowStatus { + operation_id: src.read_u64(), + }) + } + 18 => { + ensure_size!(in: src, size: 8); + let operation_id = src.read_u64(); + let after_sequence = read_opt_u64(src)?; + Ok(Self::NowAttach { + operation_id, + after_sequence, + }) + } + 19 => { + ensure_size!(in: src, size: 8); + let operation_id = src.read_u64(); + let data = read_bytes(src)?; + let last = read_bool(src)?; + Ok(Self::NowStdin { + operation_id, + data, + last, + }) + } + 20 => Ok(Self::NowDiagnostics), + 21 => Ok(Self::Shutdown), + _ => Err(ironrdp_core::invalid_field_err!("request", "unknown tag")), + } + } +} + +impl_pdu_pod!(Request); + +// ── NOW IPC codec ────────────────────────────────────────────────────────── + +fn write_error_category(dst: &mut WriteCursor<'_>, category: AgentErrorCategory) { + dst.write_u8(match category { + AgentErrorCategory::InvalidRequest => 0, + AgentErrorCategory::Unavailable => 1, + AgentErrorCategory::Conflict => 2, + AgentErrorCategory::Transport => 3, + AgentErrorCategory::Remote => 4, + AgentErrorCategory::Internal => 5, + }); +} + +fn read_error_category(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(AgentErrorCategory::InvalidRequest), + 1 => Ok(AgentErrorCategory::Unavailable), + 2 => Ok(AgentErrorCategory::Conflict), + 3 => Ok(AgentErrorCategory::Transport), + 4 => Ok(AgentErrorCategory::Remote), + 5 => Ok(AgentErrorCategory::Internal), + _ => Err(ironrdp_core::invalid_field_err!("agent error category", "unknown tag")), + } +} + +impl Encode for AgentError { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + write_error_category(dst, self.category); + write_string(dst, &self.message) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::AgentError" + } + + fn size(&self) -> usize { + 1 /* category */ + string_size(&self.message) + } +} + +impl Decode<'_> for AgentError { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + Ok(Self { + category: read_error_category(src)?, + message: read_string(src)?, + }) + } +} + +impl_pdu_pod!(AgentError); + +fn write_execution_kind(dst: &mut WriteCursor<'_>, kind: NowExecutionKind) { + dst.write_u8(match kind { + NowExecutionKind::Process => 0, + NowExecutionKind::Batch => 1, + NowExecutionKind::PowerShell => 2, + NowExecutionKind::Pwsh => 3, + }); +} + +fn read_execution_kind(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(NowExecutionKind::Process), + 1 => Ok(NowExecutionKind::Batch), + 2 => Ok(NowExecutionKind::PowerShell), + 3 => Ok(NowExecutionKind::Pwsh), + _ => Err(ironrdp_core::invalid_field_err!("NOW execution kind", "unknown tag")), + } +} + +impl Encode for NowExecutionRequest { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + write_execution_kind(dst, self.kind); + write_string(dst, &self.command)?; + write_opt_string(dst, self.parameters.as_deref())?; + write_opt_string(dst, self.directory.as_deref())?; + match &self.stdin { + Some(data) => { + dst.write_u8(1); + write_bytes(dst, data)?; + } + None => dst.write_u8(0), + } + write_opt_u64(dst, self.timeout_ms)?; + write_bool(dst, self.detached)?; + write_bool(dst, self.no_profile)?; + write_bool(dst, self.non_interactive) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::NowExecutionRequest" + } + + fn size(&self) -> usize { + 1 /* kind */ + + string_size(&self.command) + + opt_string_size(self.parameters.as_deref()) + + opt_string_size(self.directory.as_deref()) + + 1 /* stdin presence */ + + self.stdin.as_ref().map_or(0, |data| bytes_size(data)) + + opt_u64_size(self.timeout_ms) + + 1 /* detached */ + + 1 /* no_profile */ + + 1 /* non_interactive */ + } +} + +impl Decode<'_> for NowExecutionRequest { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + let kind = read_execution_kind(src)?; + let command = read_string(src)?; + let parameters = read_opt_string(src)?; + let directory = read_opt_string(src)?; + ensure_size!(in: src, size: 1); + let stdin = match src.read_u8() { + 0 => None, + 1 => Some(read_bytes(src)?), + _ => return Err(ironrdp_core::invalid_field_err!("NOW stdin", "invalid presence flag")), + }; + Ok(Self { + kind, + command, + parameters, + directory, + stdin, + timeout_ms: read_opt_u64(src)?, + detached: read_bool(src)?, + no_profile: read_bool(src)?, + non_interactive: read_bool(src)?, + }) + } +} + +impl_pdu_pod!(NowExecutionRequest); + +fn write_operation_state(dst: &mut WriteCursor<'_>, state: OperationState) { + dst.write_u8(match state { + OperationState::Running => 0, + OperationState::Cancelling => 1, + OperationState::Completed => 2, + OperationState::Cancelled => 3, + OperationState::Failed => 4, + OperationState::Detached => 5, + }); +} + +fn read_operation_state(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(OperationState::Running), + 1 => Ok(OperationState::Cancelling), + 2 => Ok(OperationState::Completed), + 3 => Ok(OperationState::Cancelled), + 4 => Ok(OperationState::Failed), + 5 => Ok(OperationState::Detached), + _ => Err(ironrdp_core::invalid_field_err!("operation state", "unknown tag")), + } +} + +impl Encode for OperationInfo { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + dst.write_u64(self.id); + write_execution_kind(dst, self.kind); + write_operation_state(dst, self.state); + write_bool(dst, self.detached)?; + match self.exit_code { + Some(exit_code) => { + dst.write_u8(1); + dst.write_u32(exit_code); + } + None => dst.write_u8(0), + } + match &self.error { + Some(error) => { + dst.write_u8(1); + error.encode(dst)?; + } + None => dst.write_u8(0), + } + dst.write_u64(self.retained_output_bytes); + dst.write_u64(self.next_sequence); + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::OperationInfo" + } + + fn size(&self) -> usize { + 8 /* id */ + + 1 /* kind */ + + 1 /* state */ + + 1 /* detached */ + + 1 /* exit-code presence */ + + self.exit_code.map_or(0, |_| 4) + + 1 /* error presence */ + + self.error.as_ref().map_or(0, Encode::size) + + 8 /* retained_output_bytes */ + + 8 /* next_sequence */ + } +} + +impl Decode<'_> for OperationInfo { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 8); + let id = src.read_u64(); + let kind = read_execution_kind(src)?; + let state = read_operation_state(src)?; + let detached = read_bool(src)?; + ensure_size!(in: src, size: 1); + let exit_code = match src.read_u8() { + 0 => None, + 1 => { + ensure_size!(in: src, size: 4); + Some(src.read_u32()) + } + _ => return Err(ironrdp_core::invalid_field_err!("exit code", "invalid presence flag")), + }; + ensure_size!(in: src, size: 1); + let error = match src.read_u8() { + 0 => None, + 1 => Some(AgentError::decode(src)?), + _ => { + return Err(ironrdp_core::invalid_field_err!( + "operation error", + "invalid presence flag" + )); + } + }; + ensure_size!(in: src, size: 16); + Ok(Self { + id, + kind, + state, + detached, + exit_code, + error, + retained_output_bytes: src.read_u64(), + next_sequence: src.read_u64(), + }) + } +} + +impl_pdu_pod!(OperationInfo); + +fn write_stream(dst: &mut WriteCursor<'_>, stream: NowStream) { + dst.write_u8(match stream { + NowStream::Stdout => 0, + NowStream::Stderr => 1, + }); +} + +fn read_stream(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(NowStream::Stdout), + 1 => Ok(NowStream::Stderr), + _ => Err(ironrdp_core::invalid_field_err!("NOW output stream", "unknown tag")), + } +} + +impl Encode for OperationEventKind { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + match self { + Self::Started => dst.write_u8(0), + Self::Output { stream, data, last } => { + dst.write_u8(1); + write_stream(dst, *stream); + write_bytes(dst, data)?; + write_bool(dst, *last)?; + } + Self::CancelAccepted => dst.write_u8(2), + Self::Completed { exit_code } => { + dst.write_u8(3); + dst.write_u32(*exit_code); + } + Self::Cancelled => dst.write_u8(4), + Self::Failed(error) => { + dst.write_u8(5); + error.encode(dst)?; + } + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::OperationEventKind" + } + + fn size(&self) -> usize { + 1 /* tag */ + + match self { + Self::Started | Self::CancelAccepted | Self::Cancelled => 0, + Self::Output { data, .. } => 1 /* stream */ + bytes_size(data) + 1 /* last */, + Self::Completed { .. } => 4, + Self::Failed(error) => error.size(), + } + } +} + +impl Decode<'_> for OperationEventKind { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 1); + match src.read_u8() { + 0 => Ok(Self::Started), + 1 => Ok(Self::Output { + stream: read_stream(src)?, + data: read_bytes(src)?, + last: read_bool(src)?, + }), + 2 => Ok(Self::CancelAccepted), + 3 => { + ensure_size!(in: src, size: 4); + Ok(Self::Completed { + exit_code: src.read_u32(), + }) + } + 4 => Ok(Self::Cancelled), + 5 => Ok(Self::Failed(AgentError::decode(src)?)), + _ => Err(ironrdp_core::invalid_field_err!("operation event", "unknown tag")), + } + } +} + +impl_pdu_pod!(OperationEventKind); + +impl Encode for OperationEvent { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + dst.write_u64(self.operation_id); + dst.write_u64(self.sequence); + self.kind.encode(dst) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::OperationEvent" + } + + fn size(&self) -> usize { + 8 /* operation_id */ + 8 /* sequence */ + self.kind.size() + } +} + +impl Decode<'_> for OperationEvent { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 16); + Ok(Self { + operation_id: src.read_u64(), + sequence: src.read_u64(), + kind: OperationEventKind::decode(src)?, + }) + } +} + +impl_pdu_pod!(OperationEvent); + +impl Encode for NowCapabilities { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + dst.write_u16(self.version_major); + dst.write_u16(self.version_minor); + write_opt_u64(dst, self.heartbeat_ms)?; + for value in [ + self.run, + self.process, + self.batch, + self.powershell, + self.pwsh, + self.io_redirection, + self.unicode_console, + ] { + write_bool(dst, value)?; + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::NowCapabilities" + } + + fn size(&self) -> usize { + 2 /* version major */ + + 2 /* version minor */ + + opt_u64_size(self.heartbeat_ms) + + 7 /* feature flags */ + } +} + +impl Decode<'_> for NowCapabilities { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + ensure_size!(in: src, size: 4); + let version_major = src.read_u16(); + let version_minor = src.read_u16(); + Ok(Self { + version_major, + version_minor, + heartbeat_ms: read_opt_u64(src)?, + run: read_bool(src)?, + process: read_bool(src)?, + batch: read_bool(src)?, + powershell: read_bool(src)?, + pwsh: read_bool(src)?, + io_redirection: read_bool(src)?, + unicode_console: read_bool(src)?, + }) + } +} + +impl_pdu_pod!(NowCapabilities); + +impl Encode for NowDiagnostics { + fn encode(&self, dst: &mut WriteCursor<'_>) -> EncodeResult<()> { + ensure_size!(in: dst, size: self.size()); + write_bool(dst, self.endpoint_allocated)?; + write_bool(dst, self.connected)?; + match &self.capabilities { + Some(capabilities) => { + dst.write_u8(1); + capabilities.encode(dst)?; + } + None => dst.write_u8(0), + } + Ok(()) + } + + fn name(&self) -> &'static str { + "ironrdp_agent::NowDiagnostics" + } + + fn size(&self) -> usize { + 1 /* endpoint_allocated */ + + 1 /* connected */ + + 1 /* capabilities presence */ + + self.capabilities.as_ref().map_or(0, Encode::size) + } +} + +impl Decode<'_> for NowDiagnostics { + fn decode(src: &mut ReadCursor<'_>) -> DecodeResult { + let endpoint_allocated = read_bool(src)?; + let connected = read_bool(src)?; + ensure_size!(in: src, size: 1); + let capabilities = match src.read_u8() { + 0 => None, + 1 => Some(NowCapabilities::decode(src)?), + _ => { + return Err(ironrdp_core::invalid_field_err!( + "NOW capabilities", + "invalid presence flag" + )); + } + }; + Ok(Self { + endpoint_allocated, + connected, + capabilities, + }) + } +} + +impl_pdu_pod!(NowDiagnostics); diff --git a/crates/ironrdp-rpc/src/lib.rs b/crates/ironrdp-rpc/src/lib.rs new file mode 100644 index 000000000..584baae44 --- /dev/null +++ b/crates/ironrdp-rpc/src/lib.rs @@ -0,0 +1,5 @@ +//! Shared local RPC protocol and transport used by the agent and viewer. + +pub mod ipc; +pub mod transport; +pub mod wire; diff --git a/crates/ironrdp-rpc/src/transport.rs b/crates/ironrdp-rpc/src/transport.rs new file mode 100644 index 000000000..ffa5a96cf --- /dev/null +++ b/crates/ironrdp-rpc/src/transport.rs @@ -0,0 +1,541 @@ +//! Local IPC transport and message framing. +//! +//! RPC peers talk over a platform-native local transport: +//! +//! - **Unix**: a [`tokio::net::UnixListener`]/[`tokio::net::UnixStream`] at a named +//! `$XDG_RUNTIME_DIR/-.sock`, falling back to `/tmp` when `XDG_RUNTIME_DIR` is unset. +//! - **Windows**: a named pipe at `\\.\pipe\-`, restricted to the current user. +//! +//! Framing is identical on both: a little-endian `u32` byte-count prefix followed by the `Encode`d +//! message body. + +use anyhow::{Context as _, bail}; +use ironrdp_core::{DecodeOwned, Encode}; +use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; + +use crate::ipc::{Request, Response}; + +/// Upper bound on a single framed message, guarding against absurd length prefixes. +const MAX_MESSAGE_LEN: usize = 16 * 1024 * 1024; + +/// Writes `message` to `stream`, length-delimited. +pub async fn write_message(stream: &mut S, message: &M) -> anyhow::Result<()> +where + S: AsyncWrite + Unpin, + M: Encode, +{ + let body = ironrdp_core::encode_vec(message).map_err(|e| anyhow::anyhow!("encode {}: {e}", message.name()))?; + let len = u32::try_from(body.len()).context("message too large to frame")?; + stream + .write_all(&len.to_le_bytes()) + .await + .context("write frame length")?; + stream.write_all(&body).await.context("write frame body")?; + stream.flush().await.context("flush frame")?; + Ok(()) +} + +/// Reads a single length-delimited message from `stream`. +pub async fn read_message(stream: &mut S) -> anyhow::Result +where + S: AsyncRead + Unpin, + M: DecodeOwned, +{ + let mut len_buf = [0u8; 4]; + stream.read_exact(&mut len_buf).await.context("read frame length")?; + let len = usize::try_from(u32::from_le_bytes(len_buf)).context("frame length does not fit this platform")?; + if MAX_MESSAGE_LEN < len { + bail!("frame length {len} exceeds the {MAX_MESSAGE_LEN}-byte limit"); + } + let mut body = vec![0u8; len]; + stream.read_exact(&mut body).await.context("read frame body")?; + ironrdp_core::decode_owned(&body).map_err(|e| anyhow::anyhow!("decode: {e}")) +} + +/// Opens the endpoint, sends one `request`, and returns the daemon's `Response`. +pub async fn send_request(endpoint: &Endpoint, request: &Request) -> anyhow::Result { + let mut stream = open_stream(endpoint, request).await?; + read_message(&mut stream).await +} + +/// Opens an IPC connection, sends `request`, and leaves the stream available for streamed replies. +pub async fn open_stream(endpoint: &Endpoint, request: &Request) -> anyhow::Result { + let mut stream = connect(endpoint) + .await + .with_context(|| format!("connect to RPC server at {endpoint}"))?; + write_message(&mut stream, request).await?; + Ok(stream) +} + +#[cfg(unix)] +mod imp { + use anyhow::{Context as _, bail}; + use std::io; + use std::path::PathBuf; + + use tokio::net::{UnixListener, UnixStream}; + + /// A resolved IPC endpoint (a Unix domain socket path). + #[derive(Debug, Clone)] + pub struct Endpoint(pub PathBuf); + + impl core::fmt::Display for Endpoint { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.0.display()) + } + } + + /// Returns the default agent endpoint. + pub fn default_endpoint() -> Endpoint { + default_endpoint_named("ironrdp-agent") + } + + /// Returns a named per-user endpoint. + pub fn default_endpoint_named(name: &str) -> Endpoint { + // SAFETY: `getuid` has no preconditions and is always safe to call. + let uid = unsafe { libc::getuid() }; + let dir = std::env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/tmp")); + Endpoint(dir.join(format!("{name}-{uid}.sock"))) + } + + pub fn endpoint_from_string(value: String) -> Endpoint { + Endpoint(PathBuf::from(value)) + } + + pub async fn prepare_endpoint(endpoint: &Endpoint) -> anyhow::Result<()> { + if !endpoint.0.exists() { + return Ok(()); + } + + if super::connect(endpoint).await.is_ok() { + bail!("an RPC server already appears to be running at {endpoint}"); + } + + // No server answered, so the path may be a stale socket. Guard against deleting an + // unrelated regular file (or following a symlink) when an explicit endpoint is used. + use std::os::unix::fs::FileTypeExt as _; + let metadata = + std::fs::symlink_metadata(&endpoint.0).with_context(|| format!("stat IPC endpoint {endpoint}"))?; + if !metadata.file_type().is_socket() { + bail!("refusing to remove {endpoint}: path exists and is not a socket"); + } + std::fs::remove_file(&endpoint.0).with_context(|| format!("remove stale socket {endpoint}"))?; + Ok(()) + } + + /// Connects to a listening daemon. + pub async fn connect(endpoint: &Endpoint) -> io::Result { + UnixStream::connect(&endpoint.0).await + } + + /// A bound listener that accepts client connections. + pub struct Listener { + inner: UnixListener, + path: PathBuf, + } + + impl Listener { + /// Binds the listener at `endpoint`. + pub fn bind(endpoint: &Endpoint) -> io::Result { + let inner = UnixListener::bind(&endpoint.0)?; + // Restrict the socket to the owner. The fallback directory is world-writable `/tmp`, so + // without this any local user could connect and drive the session (input, screenshots, + // logs). Fail loudly rather than serve on a world-accessible endpoint. + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(&endpoint.0, std::fs::Permissions::from_mode(0o600))?; + Ok(Self { + inner, + path: endpoint.0.clone(), + }) + } + + /// Accepts the next client connection. + pub async fn accept(&mut self) -> io::Result { + let (stream, _addr) = self.inner.accept().await?; + Ok(stream) + } + } + + impl Drop for Listener { + fn drop(&mut self) { + // Best-effort removal of the socket file on shutdown (named pipes need no cleanup). + let _ = std::fs::remove_file(&self.path); + } + } +} + +#[cfg(windows)] +mod imp { + use std::io; + + use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer, ServerOptions}; + use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree}; + use windows::Win32::Security::Authorization::{ + ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, + }; + use windows::Win32::Security::{ + GetTokenInformation, PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER, TokenUser, + }; + use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + use windows::core::{PCWSTR, PWSTR}; + + /// A resolved IPC endpoint (a named pipe path). + #[derive(Debug, Clone)] + pub struct Endpoint(pub String); + + impl core::fmt::Display for Endpoint { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.0) + } + } + + /// Returns the default agent endpoint. + pub fn default_endpoint() -> Endpoint { + default_endpoint_named("ironrdp-agent") + } + + /// Returns a named per-user endpoint. + pub fn default_endpoint_named(name: &str) -> Endpoint { + let user = whoami::username().unwrap_or_else(|_| "user".to_owned()); + Endpoint(format!(r"\\.\pipe\{name}-{user}")) + } + + pub fn endpoint_from_string(value: String) -> Endpoint { + Endpoint(value) + } + + pub async fn prepare_endpoint(_endpoint: &Endpoint) -> anyhow::Result<()> { + Ok(()) + } + + /// Connects to a listening daemon. + pub async fn connect(endpoint: &Endpoint) -> io::Result { + ClientOptions::new().open(&endpoint.0) + } + + /// Owns a process token handle and closes it on drop. + struct OwnedTokenHandle(HANDLE); + + impl Drop for OwnedTokenHandle { + fn drop(&mut self) { + // SAFETY: `self.0` is a real token handle from `OpenProcessToken`, owned exclusively by us. + if let Err(e) = unsafe { CloseHandle(self.0) } { + tracing::warn!(error = %e, "Failed to close process token handle"); + } + } + } + + /// Owns a self-relative security descriptor allocated by + /// `ConvertStringSecurityDescriptorToSecurityDescriptorW` and frees it with `LocalFree` on drop. + struct OwnedSecurityDescriptor(PSECURITY_DESCRIPTOR); + + impl OwnedSecurityDescriptor { + /// Builds a security descriptor granting access only to the current user. + /// + /// The descriptor is a protected DACL (no inherited ACEs) with a single allow-ACE granting + /// `GENERIC_ALL` to the user identified by the current process token. This mirrors the Unix + /// listener's `0o600` owner-only stance: only the user running the daemon may connect to the + /// named pipe. On shared Windows hosts the pipe namespace is otherwise reachable by every + /// local user, so this is the last line of defense against a different local user driving the + /// session (input, screenshots, logs, NOW execution). + fn for_current_user() -> io::Result { + let buffer = current_user_token_buffer()?; + let sid = sid_from_token_buffer(&buffer); + + let mut sid_wide = PWSTR(core::ptr::null_mut()); + // SAFETY: `sid` is a valid SID from the token; `sid_wide` is a valid out-pointer. + unsafe { ConvertSidToStringSidW(sid, core::ptr::addr_of_mut!(sid_wide)) } + .map_err(|e| io::Error::other(format!("convert sid to string: {e}")))?; + // SAFETY: `sid_wide` points to a null-terminated UTF-16 string allocated by the call above. + let sid_text = + unsafe { sid_wide.to_string() }.map_err(|e| io::Error::other(format!("decode sid string: {e}")))?; + // SAFETY: `sid_wide` was `LocalAlloc`'d by `ConvertSidToStringSidW` and is no longer needed. + let _ = unsafe { LocalFree(Some(HLOCAL(sid_wide.as_ptr().cast::()))) }; + + // Build the SDDL: a protected DACL granting GENERIC_ALL to the current user only. + let sddl_string = format!("D:P(A;;GA;;;{sid_text})"); + let mut sddl_utf16: Vec = sddl_string.encode_utf16().collect(); + sddl_utf16.push(0u16); + let sddl_ptr = PCWSTR::from_raw(sddl_utf16.as_ptr()); + + let mut security_descriptor = PSECURITY_DESCRIPTOR(core::ptr::null_mut()); + // SAFETY: `sddl_ptr` is a valid null-terminated SDDL string; `SDDL_REVISION_1` is the only + // supported revision; `security_descriptor` is a valid out-pointer. The returned SD is + // `LocalAlloc`'d and owned by us. + unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + sddl_ptr, + SDDL_REVISION_1, + core::ptr::addr_of_mut!(security_descriptor), + None, + ) + } + .map_err(|e| io::Error::other(format!("convert sddl to security descriptor: {e}")))?; + + Ok(Self(security_descriptor)) + } + + /// Returns the raw security-descriptor pointer for use as `lpSecurityDescriptor`. + fn as_ptr(&self) -> *mut core::ffi::c_void { + self.0.0 + } + } + + impl Drop for OwnedSecurityDescriptor { + fn drop(&mut self) { + // SAFETY: `self.0` is a self-relative SD allocated by + // `ConvertStringSecurityDescriptorToSecurityDescriptorW` (via `LocalAlloc`) and owned + // exclusively by this guard. + let _ = unsafe { LocalFree(Some(HLOCAL(self.0.0))) }; + } + } + + /// Returns the buffer holding the `TOKEN_USER` of the current process token. + /// + /// The user SID is referenced by `TOKEN_USER.User.Sid` and lives inside this buffer, so keep the + /// buffer alive while using the SID pointer. + fn current_user_token_buffer() -> io::Result> { + // SAFETY: `GetCurrentProcess` has no preconditions and returns a pseudo-handle that must + // not be closed. + let process = unsafe { GetCurrentProcess() }; + + let mut token = HANDLE::default(); + // SAFETY: `process` is the valid current-process pseudo-handle; `token` is a valid out-pointer. + unsafe { OpenProcessToken(process, TOKEN_QUERY, core::ptr::addr_of_mut!(token)) } + .map_err(|e| io::Error::other(format!("open process token: {e}")))?; + let token_guard = OwnedTokenHandle(token); + let token = token_guard.0; + + // First query the required buffer size; the call fails with `ERROR_INSUFFICIENT_BUFFER`. + let mut len = 0u32; + // SAFETY: `token` is a valid token handle; a null buffer with zero length is the documented + // way to retrieve the required size; `len` is a valid out-pointer. + let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, core::ptr::addr_of_mut!(len)) }; + + let mut buffer = vec![0u8; usize::try_from(len).expect("token information length fits in usize")]; + // SAFETY: `token` is valid; `buffer` has `len` bytes as required; `len` is a valid out-pointer. + unsafe { + GetTokenInformation( + token, + TokenUser, + Some(buffer.as_mut_ptr().cast::()), + len, + core::ptr::addr_of_mut!(len), + ) + } + .map_err(|e| io::Error::other(format!("query token user: {e}")))?; + + Ok(buffer) + } + + /// Returns the user SID referenced by a token buffer from [`current_user_token_buffer`]. + fn sid_from_token_buffer(buffer: &[u8]) -> PSID { + // The buffer is byte-aligned, so read the `TOKEN_USER` header unaligned; the SID it references + // lives further inside the buffer and stays valid as long as the buffer does. + // SAFETY: `GetTokenInformation` wrote a valid `TOKEN_USER` at the start of `buffer`. + let token_user = unsafe { core::ptr::read_unaligned(buffer.as_ptr().cast::()) }; + token_user.User.Sid + } + + /// Creates one named-pipe server instance with `security` applied as its security descriptor. + /// + /// `CreateNamedPipeW` copies the security descriptor before returning, so `security` may be + /// reused across instances and need only outlive this synchronous call. `first` sets + /// `FILE_FLAG_FIRST_PIPE_INSTANCE`, which is only valid for the first instance of a pipe name. + fn create_server_instance( + name: &str, + first: bool, + security: &OwnedSecurityDescriptor, + ) -> io::Result { + let mut options = ServerOptions::new(); + if first { + options.first_pipe_instance(true); + } + + let mut attributes = SECURITY_ATTRIBUTES { + nLength: u32::try_from(size_of::()).expect("security_attributes struct fits in u32"), + lpSecurityDescriptor: security.as_ptr(), + ..Default::default() + }; + + let raw = core::ptr::addr_of_mut!(attributes).cast::(); + // SAFETY: `attributes` lives for the duration of this synchronous call; `CreateNamedPipeW` + // copies the security descriptor before returning, so dropping `attributes` afterwards is safe. + unsafe { options.create_with_security_attributes_raw(name, raw) } + } + + /// A named-pipe listener. + /// + /// It always keeps one ready (unconnected) server instance alive, which is both what serves the + /// next connection and what upholds the `first_pipe_instance` exclusivity (a pipe with no live + /// instance would let a second daemon claim the name). Every instance is created with a security + /// descriptor that restricts access to the current user, mirroring the Unix listener's `0o600`. + pub struct Listener { + name: String, + ready: NamedPipeServer, + security: OwnedSecurityDescriptor, + } + + impl Listener { + /// Creates the first pipe instance, claiming the name exclusively. + /// + /// `first_pipe_instance(true)` makes this fail with `ERROR_ACCESS_DENIED` if another daemon + /// already owns the pipe, so two daemons cannot coexist on the same endpoint. + pub fn bind(endpoint: &Endpoint) -> io::Result { + let security = OwnedSecurityDescriptor::for_current_user()?; + let ready = create_server_instance(&endpoint.0, true, &security)?; + Ok(Self { + name: endpoint.0.clone(), + ready, + security, + }) + } + + /// Waits for the next client to connect to the ready instance, then mints a replacement. + pub async fn accept(&mut self) -> io::Result { + // Connect by reference so a cancelled future leaves `ready` intact (and the pipe alive). + self.ready.connect().await?; + // Mint the next listening instance before returning so the pipe is never instance-less. + // Subsequent instances must omit `first_pipe_instance`, which is only valid on the first. + let next = create_server_instance(&self.name, false, &self.security)?; + Ok(core::mem::replace(&mut self.ready, next)) + } + } + + #[cfg(test)] + mod tests { + use super::*; + use windows::Win32::Foundation::ERROR_SUCCESS; + use windows::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT}; + use windows::Win32::Security::{ + ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION, AclSizeInformation, DACL_SECURITY_INFORMATION, EqualSid, + GetAce, GetAclInformation, GetSecurityDescriptorControl, GetSecurityDescriptorDacl, SE_DACL_PROTECTED, + }; + + /// The pipe created by the listener must actually carry the restrictive DACL, not just a + /// non-null descriptor. This catches three regressions a non-null check would miss: the SDDL + /// granting `Everyone`, the protected-DACL flag (`P`) being dropped, and `create_server_instance` + /// failing to apply the descriptor. It queries the live pipe's DACL and asserts it is + /// protected and contains exactly one allow-ACE granting `GENERIC_ALL` to the current user SID. + #[tokio::test] + async fn pipe_dacl_grants_generic_all_only_to_current_user() { + // Expected SID = current process user. + let expected_buffer = current_user_token_buffer().expect("get current user token"); + let expected_sid = sid_from_token_buffer(&expected_buffer); + + // Build the descriptor and a real server instance with a unique name. + let security = OwnedSecurityDescriptor::for_current_user().expect("build security descriptor"); + let name = format!("\\\\.\\pipe\\ironrdp-agent-acl-test-{}", std::process::id()); + let mut name_utf16: Vec = name.encode_utf16().collect(); + name_utf16.push(0u16); + let _server = create_server_instance(&name, true, &security).expect("create pipe instance"); + + // Query the pipe's actual DACL. + let mut sd = PSECURITY_DESCRIPTOR(core::ptr::null_mut()); + let mut dacl: *mut ACL = core::ptr::null_mut(); + // SAFETY: `name_utf16` is a valid null-terminated pipe path; we request only the DACL; the + // out-pointers are valid. The returned SD is `LocalAlloc`'d and owned by us until freed below. + let result = unsafe { + GetNamedSecurityInfoW( + PCWSTR::from_raw(name_utf16.as_ptr()), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + None, + None, + Some(core::ptr::addr_of_mut!(dacl)), + None, + core::ptr::addr_of_mut!(sd), + ) + }; + assert_eq!(result, ERROR_SUCCESS, "GetNamedSecurityInfoW should succeed"); + + // `GetNamedSecurityInfoW` `LocalAlloc`'s the descriptor; reuse the production RAII guard so it + // is freed on drop at the end of the test even if an assertion below panics. + let _sd_guard = OwnedSecurityDescriptor(sd); + + // The DACL must be protected (no inherited ACEs from the pipe namespace). + let mut control: u16 = 0; + let mut revision: u32 = 0; + // SAFETY: `sd` is a valid self-relative SD returned by `GetNamedSecurityInfoW`. + unsafe { + GetSecurityDescriptorControl(sd, core::ptr::addr_of_mut!(control), core::ptr::addr_of_mut!(revision)) + } + .expect("get security descriptor control"); + assert!( + (control & SE_DACL_PROTECTED.0) != 0, + "DACL must be protected so inherited ACEs cannot widen access" + ); + + // Exactly one ACE must be present. + let mut dacl_present = windows::core::BOOL::default(); + let mut dacl_ptr: *mut ACL = core::ptr::null_mut(); + let mut defaulted = windows::core::BOOL::default(); + // SAFETY: `sd` is a valid SD; the out-pointers are valid. + unsafe { + GetSecurityDescriptorDacl( + sd, + core::ptr::addr_of_mut!(dacl_present), + core::ptr::addr_of_mut!(dacl_ptr), + core::ptr::addr_of_mut!(defaulted), + ) + } + .expect("get dacl"); + assert!(dacl_present.as_bool(), "DACL must be present"); + assert!(!dacl_ptr.is_null(), "DACL pointer must not be null"); + + let mut size_info = ACL_SIZE_INFORMATION::default(); + // SAFETY: `dacl_ptr` is a valid ACL; `size_info` is a valid out-buffer of the right size. + unsafe { + GetAclInformation( + dacl_ptr.cast_const(), + core::ptr::addr_of_mut!(size_info).cast::(), + u32::try_from(size_of::()).expect("acl size information fits in u32"), + AclSizeInformation, + ) + } + .expect("get acl information"); + assert_eq!(size_info.AceCount, 1, "DACL must contain exactly one ACE"); + + // The single ACE must be an allow-ACE granting GENERIC_ALL to the current user SID. + let mut ace_ptr: *mut core::ffi::c_void = core::ptr::null_mut(); + // SAFETY: `dacl_ptr` is valid and holds one ACE (verified above); `ace_ptr` is a valid out-pointer. + unsafe { GetAce(dacl_ptr.cast_const(), 0, core::ptr::addr_of_mut!(ace_ptr)) }.expect("get ace"); + assert!(!ace_ptr.is_null(), "ACE pointer must not be null"); + + // SAFETY: ACE 0 is an `ACCESS_ALLOWED_ACE` (SDDL "A;;" = allow) placed at DWORD alignment by + // the ACL; `read_unaligned` avoids any alignment assumption. + let ace: ACCESS_ALLOWED_ACE = unsafe { core::ptr::read_unaligned(ace_ptr.cast::()) }; + assert_eq!( + ace.Header.AceType, 0u8, /* ACCESS_ALLOWED_ACE_TYPE */ + "ACE must be an allow ACE" + ); + // `GENERIC_ALL` (0x10000000) in the SDDL is mapped by the kernel to the file-object-specific + // `FILE_ALL_ACCESS` (0x001F01FF) when the descriptor is stored on a named pipe, so compare + // against the mapped value rather than the generic bit. + assert_eq!( + ace.Mask, 0x001F01FFu32, /* FILE_ALL_ACCESS */ + "ACE must grant full access (GENERIC_ALL mapped to the pipe object)" + ); + + // The SID starts at `SidStart` and extends past the struct into the ACL buffer, so point into + // the in-place ACE rather than the local copy. + // SAFETY: `ace_ptr` is a non-null pointer to a valid `ACCESS_ALLOWED_ACE`; `SidStart` is the + // first DWORD of the variable-length SID that follows the fixed ACE header. + let ace_sid = PSID(unsafe { ace_ptr.byte_add(core::mem::offset_of!(ACCESS_ALLOWED_ACE, SidStart)) }); + // SAFETY: both `ace_sid` and `expected_sid` are valid SIDs from the token / ACL. + let sids_equal = unsafe { EqualSid(ace_sid, expected_sid) }.is_ok(); + assert!(sids_equal, "ACE SID must equal the current user SID"); + } + } +} + +pub use imp::{ + Endpoint, Listener, connect, default_endpoint, default_endpoint_named, endpoint_from_string, prepare_endpoint, +}; + +#[cfg(unix)] +pub type ClientStream = tokio::net::UnixStream; +#[cfg(windows)] +pub type ClientStream = tokio::net::windows::named_pipe::NamedPipeClient; diff --git a/crates/ironrdp-agent/src/wire/mod.rs b/crates/ironrdp-rpc/src/wire/mod.rs similarity index 98% rename from crates/ironrdp-agent/src/wire/mod.rs rename to crates/ironrdp-rpc/src/wire/mod.rs index e7a7b2d35..7c29d785d 100644 --- a/crates/ironrdp-agent/src/wire/mod.rs +++ b/crates/ironrdp-rpc/src/wire/mod.rs @@ -1,4 +1,4 @@ -//! Binary wire primitives shared by the IPC message codecs. +//! Binary wire primitives shared by the local RPC message codecs. //! //! Everything is little-endian and cursor-based so it composes directly with [`ironrdp_core`]'s //! `Encode`/`Decode`/`DecodeOwned` traits. Strings (and string-shaped payloads) are length-delimited diff --git a/crates/ironrdp-agent/src/wire/propertyset.rs b/crates/ironrdp-rpc/src/wire/propertyset.rs similarity index 97% rename from crates/ironrdp-agent/src/wire/propertyset.rs rename to crates/ironrdp-rpc/src/wire/propertyset.rs index 25f984deb..5d1c17665 100644 --- a/crates/ironrdp-agent/src/wire/propertyset.rs +++ b/crates/ironrdp-rpc/src/wire/propertyset.rs @@ -1,4 +1,4 @@ -//! Binary wire codec for [`PropertySet`]. +//! Binary wire codec for [`PropertySet`] used by the local RPC protocol. //! //! This mirrors the shape of [`ironrdp_rdpfile::load`]/[`ironrdp_rdpfile::write`] but is binary and //! cursor-based so it composes with [`ironrdp_core`]'s `Encode`/`DecodeOwned` traits. diff --git a/crates/ironrdp-testsuite-extra/tests/agent.rs b/crates/ironrdp-testsuite-extra/tests/agent.rs index b13223f9b..f7836d6a6 100644 --- a/crates/ironrdp-testsuite-extra/tests/agent.rs +++ b/crates/ironrdp-testsuite-extra/tests/agent.rs @@ -113,6 +113,7 @@ fn request_variants_round_trip() { last: true, }, Request::NowDiagnostics, + Request::Shutdown, ]; for request in &requests { diff --git a/crates/ironrdp-viewer/Cargo.toml b/crates/ironrdp-viewer/Cargo.toml index 96dc099e2..611607e03 100644 --- a/crates/ironrdp-viewer/Cargo.toml +++ b/crates/ironrdp-viewer/Cargo.toml @@ -28,6 +28,7 @@ qoi = ["ironrdp/qoi"] qoiz = ["ironrdp/qoiz"] [dependencies] +ironrdp-agent = { path = "../ironrdp-agent", version = "0.1" } ironrdp = { path = "../ironrdp", version = "0.17", features = ["connector", "cliprdr", "input", "pdu", "client", "client-all"] } ironrdp-cfg = { path = "../ironrdp-cfg", version = "0.1" } ironrdp-propertyset = { path = "../ironrdp-propertyset", version = "0.1" } @@ -38,7 +39,7 @@ winit = { version = "0.30", features = ["rwh_06"] } softbuffer = "0.4" # CLI -clap = { version = "4.6", features = ["derive", "cargo"] } +clap = { version = "4.6", features = ["derive", "cargo", "env"] } inquire = "0.9" proc-exit = "2" diff --git a/crates/ironrdp-viewer/README.md b/crates/ironrdp-viewer/README.md index 2361ec078..8868e3eac 100644 --- a/crates/ironrdp-viewer/README.md +++ b/crates/ironrdp-viewer/README.md @@ -18,6 +18,28 @@ download and verification instructions. ironrdp-viewer --username --password ``` +You can provide the hostname and credentials through environment variables instead: + +```shell +RDP_HOSTNAME= RDP_USERNAME= RDP_PASSWORD= ironrdp-viewer +``` + +## Agent RPC host + +The viewer can host the same local RPC protocol used by `ironrdp-agent`, while keeping its visible +window: + +```shell +ironrdp-viewer --rpc +ironrdp-agent --backend viewer connect --server --username --password +``` + +The agent automatically starts and reuses a viewer RPC host for normal operations. Its default +viewer endpoint is `ironrdp-viewer-.sock` on Unix or `\\.\pipe\ironrdp-viewer-` on +Windows. Override it with `--endpoint` on the agent or `--rpc-endpoint` on the viewer, and stop the +selected host with `ironrdp-agent --backend viewer stop`. The GUI and RPC client share one RDP +session, including its framebuffer and input. + ## `.rdp` file support You can load a `.rdp` file with `--rdp-file `. @@ -50,8 +72,9 @@ Currently supported properties: Property precedence is: 1. CLI options -2. `.rdp` file values -3. Defaults and interactive prompts +2. Environment variables +3. `.rdp` file values +4. Defaults and interactive prompts Unknown or unsupported `.rdp` properties are ignored and do not cause parsing failures. Parse issues are reported to stderr. diff --git a/crates/ironrdp-viewer/src/app.rs b/crates/ironrdp-viewer/src/app.rs index 735105879..04034fdff 100644 --- a/crates/ironrdp-viewer/src/app.rs +++ b/crates/ironrdp-viewer/src/app.rs @@ -7,6 +7,7 @@ use std::time::Instant; use anyhow::Context as _; use ironrdp::client::rdp::{RdpInputEvent, RdpInputSender, RdpOutputEvent}; +use ironrdp_agent::daemon::Daemon; use raw_window_handle::{DisplayHandle, HasDisplayHandle as _}; use smallvec::SmallVec; use tracing::{debug, error, info, trace, warn}; @@ -19,8 +20,25 @@ use winit::window::{CursorIcon, CustomCursor, Window, WindowAttributes}; type WindowSurface = (Arc, softbuffer::Surface, Arc>); +/// Events delivered from the RDP engine and the viewer-hosted RPC server to the window. +pub enum ViewerEvent { + Output(RdpOutputEvent), + Frame { + buffer: Vec, + width: NonZeroU32, + height: NonZeroU32, + }, + Shutdown, +} + +/// Where local window input is sent. +pub enum InputTarget { + Direct(RdpInputSender), + Rpc(Arc), +} + pub struct App { - input_event_sender: RdpInputSender, + input_target: InputTarget, context: softbuffer::Context>, initial_window_size: PhysicalSize, window: Option, @@ -33,9 +51,21 @@ pub struct App { impl App { pub fn new( - event_loop: &EventLoop, + event_loop: &EventLoop, input_event_sender: &RdpInputSender, initial_window_size: PhysicalSize, + ) -> anyhow::Result { + Self::new_with_input_target( + event_loop, + InputTarget::Direct(input_event_sender.clone()), + initial_window_size, + ) + } + + pub fn new_with_input_target( + event_loop: &EventLoop, + input_target: InputTarget, + initial_window_size: PhysicalSize, ) -> anyhow::Result { // SAFETY: We drop the softbuffer context right before the event loop is stopped, thus making this safe. // FIXME: This is not a sufficient proof and the API is actually unsound as-is. @@ -49,7 +79,7 @@ impl App { let input_database = ironrdp::input::Database::new(); Ok(Self { - input_event_sender: input_event_sender.clone(), + input_target, context, initial_window_size, window: None, @@ -74,27 +104,51 @@ impl App { let width = u16::try_from(size.width).expect("reasonable width"); let height = u16::try_from(size.height).expect("reasonable height"); - match self.input_event_sender.try_send(RdpInputEvent::Resize { - width, - height, - scale_factor, - // TODO: it should be possible to get the physical size here, however winit doesn't make it straightforward. - // FreeRDP does it based on DPI reading grabbed via [`SDL_GetDisplayDPI`](https://wiki.libsdl.org/SDL2/SDL_GetDisplayDPI): - // https://github.com/FreeRDP/FreeRDP/blob/ba8cf8cf2158018fb7abbedb51ab245f369be813/client/SDL/sdl_monitor.cpp#L250-L262 - // See also: https://github.com/rust-windowing/winit/issues/826 - physical_size: None, - }) { - Ok(()) => self.last_size = None, - Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => { - self.resize_timeout = Some(Instant::now() + Duration::from_millis(10)); - } - Err(_) => { - self.last_size = None; - warn!("Unable to enqueue resize event because the RDP session is closed"); + match &self.input_target { + InputTarget::Direct(input_event_sender) => match input_event_sender.try_send(RdpInputEvent::Resize { + width, + height, + scale_factor, + // TODO: it should be possible to get the physical size here, however winit doesn't make it straightforward. + // FreeRDP does it based on DPI reading grabbed via [`SDL_GetDisplayDPI`](https://wiki.libsdl.org/SDL2/SDL_GetDisplayDPI): + // https://github.com/FreeRDP/FreeRDP/blob/ba8cf8cf2158018fb7abbedb51ab245f369be813/client/SDL/sdl_monitor.cpp#L250-L262 + // See also: https://github.com/rust-windowing/winit/issues/826 + physical_size: None, + }) { + Ok(()) => self.last_size = None, + Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => { + self.resize_timeout = Some(Instant::now() + Duration::from_millis(10)); + } + Err(_) => { + self.last_size = None; + warn!("Unable to enqueue resize event because the RDP session is closed"); + } + }, + InputTarget::Rpc(daemon) => { + if daemon.resize(width, height).is_ok() { + self.last_size = None; + } else { + self.last_size = None; + warn!("Unable to resize the RPC-backed RDP session"); + } } } } + fn update_frame(&mut self, buffer: Vec, width: NonZeroU32, height: NonZeroU32) { + let Some((window, surface)) = self.window.as_mut() else { + return; + }; + trace!(?width, ?height, "Received RPC-backed image"); + self.buffer_size = ( + u16::try_from(width.get()).expect("frame width fits in u16"), + u16::try_from(height.get()).expect("frame height fits in u16"), + ); + self.buffer = buffer; + surface.resize(width, height).expect("surface resize"); + window.request_redraw(); + } + fn draw(&mut self) { if self.buffer.is_empty() { return; @@ -108,7 +162,7 @@ impl App { } } -impl ApplicationHandler for App { +impl ApplicationHandler for App { fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { if let Some(timeout) = self.resize_timeout { if let Some(timeout) = timeout.checked_duration_since(Instant::now()) { @@ -157,9 +211,12 @@ impl ApplicationHandler for App { self.last_size = Some(size); self.resize_timeout = Some(Instant::now() + Duration::from_secs(1)); } - WindowEvent::CloseRequested => { - self.input_event_sender.request_graceful_close(); - } + WindowEvent::CloseRequested => match &self.input_target { + InputTarget::Direct(input_event_sender) => input_event_sender.request_graceful_close(), + InputTarget::Rpc(daemon) => { + let _ = daemon.disconnect(); + } + }, WindowEvent::DroppedFile(_) => { // TODO(#110): File upload } @@ -198,7 +255,7 @@ impl ApplicationHandler for App { }; apply_and_send_fast_path_events( - &self.input_event_sender, + &self.input_target, &mut self.input_database, core::iter::once(operation), ); @@ -235,7 +292,7 @@ impl ApplicationHandler for App { add_operation(modifiers.state().alt_key(), ALT_LEFT); add_operation(modifiers.state().super_key(), LOGO_LEFT); - apply_and_send_fast_path_events(&self.input_event_sender, &mut self.input_database, operations); + apply_and_send_fast_path_events(&self.input_target, &mut self.input_database, operations); } WindowEvent::CursorMoved { position, .. } => { let win_size = window.inner_size(); @@ -246,7 +303,7 @@ impl ApplicationHandler for App { let operation = ironrdp::input::Operation::MouseMove(ironrdp::input::MousePosition { x, y }); apply_and_send_fast_path_events( - &self.input_event_sender, + &self.input_target, &mut self.input_database, core::iter::once(operation), ); @@ -299,7 +356,7 @@ impl ApplicationHandler for App { } }; - apply_and_send_fast_path_events(&self.input_event_sender, &mut self.input_database, operations); + apply_and_send_fast_path_events(&self.input_target, &mut self.input_database, operations); } WindowEvent::MouseInput { state, button, .. } => { let mouse_button = match button { @@ -323,7 +380,7 @@ impl ApplicationHandler for App { }; apply_and_send_fast_path_events( - &self.input_event_sender, + &self.input_target, &mut self.input_database, core::iter::once(operation), ); @@ -355,7 +412,16 @@ impl ApplicationHandler for App { } } - fn user_event(&mut self, event_loop: &ActiveEventLoop, event: RdpOutputEvent) { + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: ViewerEvent) { + let ViewerEvent::Output(event) = event else { + match event { + ViewerEvent::Frame { buffer, width, height } => self.update_frame(buffer, width, height), + ViewerEvent::Shutdown => event_loop.exit(), + ViewerEvent::Output(_) => unreachable!(), + } + return; + }; + let Some((window, surface)) = self.window.as_mut() else { return; }; @@ -435,15 +501,24 @@ impl ApplicationHandler for App { } fn apply_and_send_fast_path_events( - input_event_sender: &RdpInputSender, + input_target: &InputTarget, input_database: &mut ironrdp::input::Database, operations: impl IntoIterator, ) { - let Ok(permit) = input_event_sender.try_reserve() else { - return; - }; - let input_events = input_database.apply(operations); - if !input_events.is_empty() { - permit.send(RdpInputEvent::FastPath(input_events)); + match input_target { + InputTarget::Direct(input_event_sender) => { + let Ok(permit) = input_event_sender.try_reserve() else { + return; + }; + let input_events = input_database.apply(operations); + if !input_events.is_empty() { + permit.send(RdpInputEvent::FastPath(input_events)); + } + } + InputTarget::Rpc(daemon) => { + for operation in operations { + let _ = daemon.input(operation); + } + } } } diff --git a/crates/ironrdp-viewer/src/cli.rs b/crates/ironrdp-viewer/src/cli.rs index c03a4a0e3..2602d1156 100644 --- a/crates/ironrdp-viewer/src/cli.rs +++ b/crates/ironrdp-viewer/src/cli.rs @@ -62,6 +62,14 @@ struct Args { #[clap(short, long, value_parser)] log_file: Option, + /// Run as a visible GUI host for the ironrdp-agent RPC protocol. + #[clap(long)] + rpc: bool, + + /// Override the viewer RPC endpoint (defaults to the per-user viewer endpoint). + #[clap(long, requires = "rpc")] + rpc_endpoint: Option, + #[clap(long, value_parser)] gw_endpoint: Option, #[clap(long, value_parser)] @@ -70,6 +78,7 @@ struct Args { gw_pass: Option, /// An address on which the client will connect. + #[clap(env = "RDP_HOSTNAME")] destination: Option, /// Path to a .rdp file to read the configuration from. @@ -77,7 +86,7 @@ struct Args { rdp_file: Option, /// A target RDP server user name - #[clap(short, long)] + #[clap(short, long, env = "RDP_USERNAME")] username: Option, /// An optional target RDP server domain name @@ -85,7 +94,7 @@ struct Args { domain: Option, /// A target RDP server user password - #[clap(short, long)] + #[clap(short, long, env = "RDP_PASSWORD")] password: Option, /// Proxy URL to connect to for the RDCleanPath @@ -225,6 +234,8 @@ pub struct ViewerConfig { // CLI-only settings that are not representable as `.rdp` file properties. log_file: Option, dump_rdp: Option, + rpc: bool, + rpc_endpoint: Option, } impl ViewerConfig { @@ -255,6 +266,19 @@ impl ViewerConfig { let log_file = args.log_file.clone(); let dump_rdp = args.dump_rdp.clone(); + if args.rpc { + if args.rdp_file.is_some() || dump_rdp.is_some() { + anyhow::bail!("--rpc cannot be combined with --rdp-file or --dump-rdp"); + } + return Ok(Self { + builder: ConfigBuilder::new(), + log_file, + dump_rdp: None, + rpc: true, + rpc_endpoint: args.rpc_endpoint, + }); + } + // The library overlays everything expressible as a `.rdp` property: destination, credentials, // transport, channels, desktop size, audio, DVC proxies, etc. let builder = ConfigBuilder::from_property_set(&properties)?; @@ -270,6 +294,8 @@ impl ViewerConfig { builder, log_file, dump_rdp, + rpc: false, + rpc_endpoint: None, }) } @@ -290,6 +316,14 @@ impl ViewerConfig { pub fn dump_rdp(&self) -> Option<&std::path::Path> { self.dump_rdp.as_deref() } + + pub fn rpc_mode(&self) -> bool { + self.rpc + } + + pub fn rpc_endpoint(&self) -> Option<&str> { + self.rpc_endpoint.as_deref() + } } /// Apply CLI overrides on top of a builder that already reflects the `.rdp` file. Every flag that is diff --git a/crates/ironrdp-viewer/src/main.rs b/crates/ironrdp-viewer/src/main.rs index 797d327a1..1280564f7 100644 --- a/crates/ironrdp-viewer/src/main.rs +++ b/crates/ironrdp-viewer/src/main.rs @@ -1,8 +1,14 @@ #![allow(unused_crate_dependencies)] // false positives because there is both a library and a binary +use core::num::NonZeroU32; +use std::sync::Arc; + use anyhow::Context as _; use ironrdp::client::rdp::{RdpClient, RdpOutputEvent}; -use ironrdp_viewer::app::App; +use ironrdp_agent::daemon::Daemon; +use ironrdp_agent::transport; +use ironrdp_propertyset::PropertySet; +use ironrdp_viewer::app::{App, InputTarget, ViewerEvent}; use ironrdp_viewer::cli::ViewerConfig; use tokio::runtime; use tokio::sync::mpsc; @@ -15,6 +21,10 @@ fn main() -> anyhow::Result<()> { setup_logging(cli.log_file()).context("unable to initialize logging")?; + if cli.rpc_mode() { + return run_rpc(cli).context("RPC server"); + } + let dump_rdp = cli.dump_rdp().map(ToOwned::to_owned); let config = cli.into_config().context("configuration")?; @@ -26,7 +36,7 @@ fn main() -> anyhow::Result<()> { } debug!("Initialize App"); - let event_loop = EventLoop::::with_user_event().build()?; + let event_loop = EventLoop::::with_user_event().build()?; let event_loop_proxy = event_loop.create_proxy(); let (output_event_sender, mut output_event_receiver) = mpsc::channel::(64); let initial_window_size = PhysicalSize::new( @@ -51,7 +61,7 @@ fn main() -> anyhow::Result<()> { // `tokio::sync::mpsc` channel. Bridging onto the GUI event loop is the binary's job. rt.spawn(async move { while let Some(event) = output_event_receiver.recv().await { - if event_loop_proxy.send_event(event).is_err() { + if event_loop_proxy.send_event(ViewerEvent::Output(event)).is_err() { // The event loop is gone; nothing left to forward. break; } @@ -69,6 +79,75 @@ fn main() -> anyhow::Result<()> { Ok(()) } +fn run_rpc(cli: ViewerConfig) -> anyhow::Result<()> { + let endpoint = cli + .rpc_endpoint() + .map(|value| transport::endpoint_from_string(value.to_owned())) + .unwrap_or_else(|| transport::default_endpoint_named("ironrdp-viewer")); + + debug!(%endpoint, "Initialize viewer RPC server"); + let event_loop = EventLoop::::with_user_event().build()?; + let event_loop_proxy = event_loop.create_proxy(); + let (notification_sender, mut notification_receiver) = mpsc::unbounded_channel(); + let daemon = Arc::new(Daemon::with_overlay(PropertySet::new()).with_notification(notification_sender)); + + let runtime = runtime::Builder::new_multi_thread() + .enable_all() + .build() + .context("unable to create tokio runtime")?; + + let frame_daemon = Arc::clone(&daemon); + let frame_proxy = event_loop_proxy.clone(); + runtime.spawn(async move { + while notification_receiver.recv().await.is_some() { + let Some(frame) = frame_daemon.current_frame() else { + continue; + }; + let (Some(width), Some(height)) = ( + NonZeroU32::new(u32::from(frame.width)), + NonZeroU32::new(u32::from(frame.height)), + ) else { + continue; + }; + if frame_proxy + .send_event(ViewerEvent::Frame { + buffer: frame.pixels, + width, + height, + }) + .is_err() + { + break; + } + } + }); + + let server_daemon = Arc::clone(&daemon); + let server_proxy = event_loop_proxy; + std::thread::Builder::new() + .name("ironrdp-viewer-rpc".to_owned()) + .spawn(move || { + let server_runtime = runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("unable to create viewer RPC runtime"); + server_runtime.block_on(async move { + if let Err(error) = ironrdp_agent::daemon::serve(endpoint, server_daemon).await { + tracing::error!(error = format!("{error:#}"), "Viewer RPC server stopped with an error"); + } + let _ = server_proxy.send_event(ViewerEvent::Shutdown); + }); + }) + .context("unable to spawn viewer RPC server")?; + + let mut app = App::new_with_input_target(&event_loop, InputTarget::Rpc(daemon), PhysicalSize::new(1024, 768)) + .context("unable to initialize App")?; + + debug!("Run viewer RPC App"); + event_loop.run_app(&mut app)?; + Ok(()) +} + fn setup_logging(log_file: Option<&str>) -> anyhow::Result<()> { use std::fs::OpenOptions;