From d765019c81abbf7e9d09bf490c0e0ddf15afccd2 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 23:05:22 +0800 Subject: [PATCH] feat(remote): open a local WSL distribution as a remote workspace (Refs 1lck/Lithe-IDEA#2231) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit remote.connect accepts wsl: { distribution, user? } instead of connection. Core then runs %SystemRoot%\System32\wsl.exe --distribution [--user ] --cd ~ --exec … in place of OpenSSH; the probe, the checked upload, the stages and the session are the same as over SSH. - Transport: the WSL hop validates the user as a Linux login name (at most 32 bytes), is allowed as the first hop only, keeps the Windows environment wsl.exe needs and sets WSL_UTF8=1. Identity is wsl:[user@]distribution. - Trust: decisions name the distribution and the account as the first and only hop; WSL after SSH, WSL after WSL and unknown fields are refused. - Connection: WSL starts no AskPass session. A wsl.exe that exits before the server starts is classified from its stable error codes (WSL_E_DISTRO_NOT_FOUND is unreachable), with its UTF-16 or UTF-8 message decoded for diagnostics; a silent exit names wsl.exe and the status. A request naming both connection and wsl, or neither, is invalid_request with the field, before anything starts. - remote.listWslDistributions (no payload) runs wsl.exe --list --quiet with a 15 s bound and returns { available, distributions, diagnostics }: at most 64 names in wsl.exe order, without Docker Desktop's engine distributions and case-insensitive repeats. Other systems answer unavailable without running anything. - Logging: the connection kind wsl, and the cleanup and diagnostics stage descriptions cover wsl.exe; catalog regenerated. - Contract: remote.connect's wsl field, its refusals, and the new command. Tests use a stand-in wsl.exe to run the whole connection, check the arguments and environment it receives, the UTF-16 failure path and the listing. --- rust/contracts/rust-core-api.md | 45 ++- rust/crates/core/src/protocol/command.rs | 6 + .../core/src/runtime/dispatcher/remote.rs | 7 + rust/crates/core/src/tests/remote_sessions.rs | 24 ++ .../diagnostics/src/catalog_generated.rs | 14 +- .../remote/src/client/connection_log.rs | 3 + rust/crates/remote/src/client/connections.rs | 2 +- rust/crates/remote/src/client/mod.rs | 12 +- rust/crates/remote/src/client/transport.rs | 269 +++++++++++++++++- rust/crates/remote/src/client/trust.rs | 103 ++++++- rust/crates/remote/src/client/wsl.rs | 256 +++++++++++++++++ rust/crates/workspace/src/lib.rs | 16 +- rust/crates/workspace/src/probe.rs | 37 ++- rust/crates/workspace/src/probe/tests.rs | 132 +++++++++ rust/crates/workspace/src/sessions.rs | 258 ++++++++++++----- rust/crates/workspace/src/wsl.rs | 182 ++++++++++++ rust/logging/events/remote.json | 10 +- 17 files changed, 1248 insertions(+), 128 deletions(-) create mode 100644 rust/crates/remote/src/client/wsl.rs create mode 100644 rust/crates/workspace/src/wsl.rs diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index ea1032e6..ec26804b 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -802,9 +802,9 @@ or removing a command fails until the table changes in the same commit. | `git.authRespond` | Answer or cancel a live authentication challenge once | | `remote.probe` | Check that an SSH connection reaches a supported host | | `remote.authRespond` | Answer or cancel a prompt relayed by `remote.probe` or `remote.connect` once | -| `remote.connect` | Open a connection, installing the shipped server when needed | +| `remote.connect` | Open a connection over SSH or to a local WSL distribution, installing the shipped server when needed | | `remote.readDir` | List a directory over an open remote connection | -| `remote.disconnect` | Close an open connection and its OpenSSH process tree | +| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree | | `remote.closeAll` | Close every open connection; the host calls it at application exit | | `remote.readFile` | Read a file over an open remote connection | | `remote.writeFile` | Save a file over an open remote connection | @@ -827,6 +827,7 @@ or removing a command fails until the table changes in the same commit. | `remote.effectiveSettings` | Tell what OpenSSH makes of a connection and where each value comes from | | `remote.sshConfigHosts` | List the Host aliases of the user's SSH configuration for an import | | `remote.mottyHosts` | List the SSH hosts saved in Motty for an import | +| `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine | | `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation | | `git.remotes` | Return configured fetch remote names and URLs | | `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations | @@ -5903,6 +5904,19 @@ connection?, fields }`: A relative directory is `invalid_request` and a damaged document `parse_failed`. Nothing is written to Motty's files. +`remote.listWslDistributions` (no payload) returns `{ available, +distributions, diagnostics }`. On Windows Core runs `wsl.exe --list --quiet` +from `%SystemRoot%\System32` with `WSL_UTF8=1`, at most 15 seconds, and reads +its UTF-16 or UTF-8 output. `distributions` are the installed names in +`wsl.exe` order, at most 64, without Docker Desktop's `docker-desktop` and +`docker-desktop-data` and without names repeated in another case. +`available` is `false` on other systems, where nothing runs, and when +`wsl.exe` cannot start. When `wsl.exe` fails, for example because no +distribution is installed, `distributions` is empty and `diagnostics` holds +its redacted message for display; it is never logged. Cancellation and the +bound are `cancelled` and `timed_out`. Nothing is saved: the window lists +the distributions each time it opens. + #### Remote connections that stay open `remote.connect` takes `{ connection, servers: [{ target, path, sha256 }], @@ -5932,9 +5946,28 @@ host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName, homeDirectory }` and is set only for `connected`. A host without a matching build is `unsupportedPlatform` and nothing is uploaded. -A malformed connection, an unknown `target` or a `sha256` that is not 64 -hexadecimal digits is `invalid_request`, before OpenSSH starts. A missing -`ssh` is `runtime_missing`. When the build for the host's platform cannot be +Instead of `connection`, the request may name a WSL distribution on this +Windows machine as `wsl: { distribution, user? }`, where `distribution` is a +name `remote.listWslDistributions` returned and `user` a Linux account (the +distribution's default user when absent). Core then runs +`wsl.exe --distribution [--user ] --cd ~ --exec …` from +`%SystemRoot%\System32` in place of OpenSSH, keeping the Windows environment +`wsl.exe` needs and setting `WSL_UTF8=1`; the probe, the checked upload and +the stages are the same. Nothing is relayed through `remote.authRespond`, +because `wsl.exe` asks no questions. An unknown distribution is +`unreachable`; other failures are `failed` with `wsl.exe`'s message in +`diagnostics`, decoded from UTF-16 when it prints that. Trust decisions name +the distribution and the account (`{ wsl: { distribution, user } }` as the +first and only hop). + +A request that names both `connection` and `wsl` is `invalid_request` with +`details` `{ field: "wsl", reason: "invalid" }`, and one that names neither +`{ field: "connection", reason: "required" }`. A malformed connection, a +distribution that is empty, longer than 64 bytes or not a WSL distribution +name, a user that is longer than 32 bytes or not a Linux login name, an +unknown `target` or a `sha256` that is not 64 hexadecimal digits is +`invalid_request`, before OpenSSH or `wsl.exe` starts. A missing `ssh` or +`wsl.exe` is `runtime_missing`. When the build for the host's platform cannot be read or its SHA-256 differs, the attempt ends as `remote_server_invalid` without sending anything; `details` says which of the two happened and, for a mismatch, the SHA-256 Core computed, but never the path. Cancellation and the @@ -5942,7 +5975,7 @@ five-minute bound are `cancelled` and `timed_out`. Core keeps an open connection until `remote.disconnect` (`{ sessionId }`, returning `{ closed }`) or until the host process exits; ending it terminates -the OpenSSH process tree. `remote.closeAll` (no payload, returning +the OpenSSH or `wsl.exe` process tree. `remote.closeAll` (no payload, returning `{ closed }` with the number of connections) ends all of them; the host calls it while quitting because exiting without it can leave the OpenSSH tree and the remote server running. Requests over it take `sessionId`: diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 708b1e92..a2a2142c 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -1037,6 +1037,9 @@ pub enum RemoteCommand { SshConfigHosts, /// Lists the SSH hosts saved in Motty for an import (`remote.mottyHosts`). MottyHosts, + /// Lists the WSL distributions installed on this Windows machine + /// (`remote.listWslDistributions`). + ListWslDistributions, } #[derive(Debug, Clone)] @@ -1614,6 +1617,9 @@ impl CoreCommand { "remote.effectiveSettings" => Some(Self::Remote(RemoteCommand::EffectiveSettings)), "remote.sshConfigHosts" => Some(Self::Remote(RemoteCommand::SshConfigHosts)), "remote.mottyHosts" => Some(Self::Remote(RemoteCommand::MottyHosts)), + "remote.listWslDistributions" => { + Some(Self::Remote(RemoteCommand::ListWslDistributions)) + } "git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)), "git.remotes" => Some(Self::Git(GitCommand::Remotes)), "git.tags" => Some(Self::Git(GitCommand::Tags)), diff --git a/rust/crates/core/src/runtime/dispatcher/remote.rs b/rust/crates/core/src/runtime/dispatcher/remote.rs index 8bdf8e22..e333cc21 100644 --- a/rust/crates/core/src/runtime/dispatcher/remote.rs +++ b/rust/crates/core/src/runtime/dispatcher/remote.rs @@ -289,6 +289,13 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option, payload: Valu id, json!({ "closed": lithe_workspace::sessions::close_all() }), ), + RemoteCommand::ListWslDistributions => match lithe_workspace::wsl::list() { + Ok(listed) => CoreResponse::success( + id, + serde_json::to_value(listed).expect("WSL distributions should encode"), + ), + Err(error) => CoreResponse::failure(id, error), + }, RemoteCommand::AuthRespond => { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 1caebca8..89fa9313 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -1306,7 +1306,31 @@ fn connection_window_helpers_answer_through_the_dispatcher() { "a refused address is not echoed" ); + // Outside Windows there is no WSL, and nothing runs. + if !cfg!(windows) { + let distributions = call("remote.listWslDistributions", Value::Null); + assert_eq!( + distributions["data"], + json!({"available": false, "distributions": [], "diagnostics": ""}), + "{distributions}" + ); + } + // A connection names SSH or WSL, not both, before anything starts. + let both = call( + "remote.connect", + json!({"connection": {"host": "devbox"}, "wsl": {"distribution": "Ubuntu"}, + "servers": [], "serverVersion": "0.1.0"}), + ); + assert_eq!(both["error"]["code"], "invalid_request", "{both}"); + let details: Value = serde_json::from_str(both["error"]["details"].as_str().unwrap()).unwrap(); + assert_eq!(details, json!({"field": "wsl", "reason": "invalid"})); + for (command, payload) in [ + ( + "remote.connect", + json!({"wsl": {"distribution": "Ubuntu", "program": "C:\\x.exe"}, + "servers": [], "serverVersion": "0.1.0"}), + ), ( "remote.parseForwardAddress", json!({"text": "3000", "extra": 1}), diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index aca8183d..a4edf634 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -1309,7 +1309,7 @@ pub static EVENTS: &[EventMetadata] = &[ FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, - FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Failed), rate: 60, @@ -1328,7 +1328,7 @@ pub static EVENTS: &[EventMetadata] = &[ FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, - FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Finished), rate: 60, @@ -1346,7 +1346,7 @@ pub static EVENTS: &[EventMetadata] = &[ FieldMetadata { name: "resumed", field_type: FieldType::Bool, required: false, description: "Whether this connection reattached to an existing persistent session, i.e. a reconnect", reason: None }, FieldMetadata { name: "server_version", field_type: FieldType::Version, required: false, description: "Version the remote server reported in server.hello once the handshake succeeded", reason: None }, FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None }, - FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, + FieldMetadata { name: "transport", field_type: FieldType::Token, required: true, description: "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)", reason: None }, ], span: Some(SpanPhase::Started), rate: 60, @@ -1488,8 +1488,8 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Warn, message: "Remote session cleanup failed", fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable native, thread, or remote category from ending an owned SSH connection", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "SSH connection cleanup stage, e.g. shutdown, tree-kill, wait, or closer", reason: None }, + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable native, thread, or remote category from ending an owned ssh or wsl.exe connection", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, tree-kill, wait, or closer", reason: None }, ], span: None, rate: 60, @@ -1501,8 +1501,8 @@ pub static EVENTS: &[EventMetadata] = &[ level: LogLevel::Warn, message: "Remote session diagnostic reader failed", fields: &[ - FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable I/O or thread category explaining incomplete SSH connection diagnostic evidence", reason: None }, - FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "SSH diagnostic collection stage: reader join or stderr read", reason: None }, + FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable I/O or thread category explaining incomplete ssh or wsl.exe diagnostic evidence", reason: None }, + FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "Diagnostic collection stage of the ssh or wsl.exe process: reader join or stderr read", reason: None }, ], span: None, rate: 60, diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index ae1ec729..df544c3e 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -69,6 +69,8 @@ const RELEASED: u8 = 3; pub enum ConnectionKind { /// An SSH connection owned by the caller. Ssh, + /// A WSL distribution started through `wsl.exe`, owned by the caller. + Wsl, /// A transport chain [`crate::client::RemoteSession::connect`] spawns. Command, /// Streams the caller supplies to @@ -80,6 +82,7 @@ impl ConnectionKind { fn as_str(self) -> &'static str { match self { Self::Ssh => "ssh", + Self::Wsl => "wsl", Self::Command => "command", Self::Streams => "streams", } diff --git a/rust/crates/remote/src/client/connections.rs b/rust/crates/remote/src/client/connections.rs index 84de0175..fdb8344d 100644 --- a/rust/crates/remote/src/client/connections.rs +++ b/rust/crates/remote/src/client/connections.rs @@ -204,7 +204,7 @@ pub enum Reason { } impl ConnectionError { - fn at(field: &'static str, reason: Reason) -> Self { + pub(crate) fn at(field: &'static str, reason: Reason) -> Self { Self { field, reason } } } diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 81c0e6d3..5358afbb 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -2,8 +2,10 @@ //! //! - [`connections`] keeps the SSH connections the user saved and turns each //! into an SSH hop with allowlisted options only. -//! - [`transport`] turns a chain of hops (SSH, container exec) into the local -//! command line that runs a program at the end of the chain. +//! - [`transport`] turns a chain of hops (SSH, WSL, container exec) into the +//! local command line that runs a program at the end of the chain. +//! - [`wsl`] turns a WSL distribution into the first hop and lists the +//! installed distributions. //! - [`bootstrap`] probes the platform at the end of the chain and describes //! the local server builds that can run there. //! - [`launch`] probes, installs and starts the server over one connection, @@ -50,6 +52,7 @@ pub mod session; pub mod ssh_config; pub mod transport; pub mod trust; +pub mod wsl; pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; @@ -58,4 +61,7 @@ pub use forward::PortForward; pub use forward_address::{AddressError, ForwardAddress}; pub use forward_set::{ForwardError, ForwardInfo, ForwardSet, ForwardSpec, TargetField}; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; -pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError}; +pub use transport::{ + ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError, WslHop, +}; +pub use wsl::WslConnection; diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index f58f20f4..f39b8355 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -2,10 +2,16 @@ //! //! A chain is an ordered list of hops from the local machine to the place //! where the workspace lives: `[]` is the local machine, `[ssh devbox]` a -//! remote host, `[ssh devbox, docker api]` a container on that host. A chain -//! builds the local command line that runs a program at its end with -//! standard streams connected end to end, and decides which inherited -//! environment variables that local command keeps. +//! remote host, `[ssh devbox, docker api]` a container on that host, and +//! `[wsl Ubuntu]` a distribution of the Windows Subsystem for Linux on the +//! local Windows machine. A chain builds the local command line that runs a +//! program at its end with standard streams connected end to end, and +//! decides which inherited environment variables that local command keeps. +//! +//! A WSL hop runs `wsl.exe --exec`, which hands its arguments to the +//! distribution without a shell, so they need no quoting beyond the Windows +//! command line's, which the standard library applies. Only the local +//! machine runs `wsl.exe`, so a WSL hop must come first. //! //! An SSH hop passes its remote command to the remote user's login shell as //! one string. That shell may be sh, bash, zsh, fish or csh, which disagree on @@ -157,6 +163,64 @@ pub enum Hop { Ssh(SshHop), /// An `exec` into a running container. Container(ContainerHop), + /// A distribution of the Windows Subsystem for Linux; only as the first hop. + Wsl(WslHop), +} + +/// Longest WSL distribution name, in bytes. `wsl.exe --import` accepts +/// shorter names; the bound only refuses garbage. +pub(crate) const MAX_WSL_DISTRIBUTION_BYTES: usize = 64; + +/// Distribution of the Windows Subsystem for Linux, started through +/// `wsl.exe --distribution`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct WslHop { + /// `wsl.exe`, resolved by [`WslHop::new`] from the Windows system + /// directory so that a program of that name on `PATH` cannot stand in. + pub program: String, + /// Distribution name as `wsl.exe --list` prints it, for example `Ubuntu-24.04`. + pub distribution: String, + /// Linux account passed as `--user`; the distribution's default user when absent. + pub user: Option, +} + +impl WslHop { + /// A hop into `distribution` as its default user, through the system's `wsl.exe`. + pub fn new(distribution: impl Into) -> Self { + Self { + program: wsl_program(), + distribution: distribution.into(), + user: None, + } + } +} + +/// `%SystemRoot%\System32\wsl.exe`, or `wsl.exe` when the variable is unset, +/// which only happens outside Windows. +pub fn wsl_program() -> String { + match std::env::var_os("SystemRoot") { + Some(root) => std::path::Path::new(&root) + .join("System32") + .join("wsl.exe") + .to_string_lossy() + .into_owned(), + None => "wsl.exe".into(), + } +} + +/// Longest Linux account name, in bytes, as `useradd` accepts it. +pub(crate) const MAX_WSL_USER_BYTES: usize = 32; + +/// A WSL distribution name: ASCII letters, digits, `.`, `_` and `-`, starting +/// with a letter or digit, which is what `wsl.exe --import` accepts. +pub(crate) fn is_wsl_distribution(name: &str) -> bool { + name.len() <= MAX_WSL_DISTRIBUTION_BYTES && is_plain_name(name) +} + +/// A Linux account name `wsl.exe --user` can take: the login names +/// [`is_ssh_user`] accepts, at most [`MAX_WSL_USER_BYTES`] long. +pub(crate) fn is_wsl_user(user: &str) -> bool { + user.len() <= MAX_WSL_USER_BYTES && is_ssh_user(user) } /// Connection through the system OpenSSH client. Host aliases, jump hosts, @@ -295,11 +359,22 @@ impl TransportChain { /// Local command line that runs `argv` at the end of the chain. pub fn command(&self, argv: &[String]) -> Result, TransportError> { + if self + .hops + .iter() + .skip(1) + .any(|hop| matches!(hop, Hop::Wsl(_))) + { + return Err(TransportError::InvalidHop { + reason: "a WSL hop must be the first hop".into(), + }); + } let mut current: Vec = argv.iter().cloned().map(Word::Raw).collect(); for hop in self.hops.iter().rev() { current = match hop { Hop::Ssh(hop) => ssh_command(hop, ¤t)?, Hop::Container(hop) => container_command(hop, current)?, + Hop::Wsl(hop) => wsl_command(hop, current)?, }; } Ok(current.into_iter().map(Word::into_string).collect()) @@ -311,17 +386,31 @@ impl TransportChain { /// A chain that starts with an SSH hop keeps only the variables ssh /// itself needs, and no locale, proxy or tool variable that a `SendEnv` /// pattern could pass on. Local and container chains keep everything: a container engine only - /// passes the variables a hop names with `-e`. The call also drops the - /// variables already set on `command`, so callers set their own, such as - /// an AskPass helper's, afterwards. + /// passes the variables a hop names with `-e`. A chain that starts with a + /// WSL hop keeps everything too, since `wsl.exe` only passes the + /// variables `WSLENV` names, and sets `WSL_UTF8=1` so that `wsl.exe` + /// prints its own messages in UTF-8 rather than UTF-16. The call also + /// drops the variables already set on `command`, so callers set their + /// own, such as an AskPass helper's, afterwards. pub fn restrict_environment(&self, command: &mut Command) { - if matches!(self.hops.first(), Some(Hop::Ssh(_))) { - command - .env_clear() - .envs(kept_ssh_variables(std::env::vars_os(), cfg!(windows))); + match self.hops.first() { + Some(Hop::Ssh(_)) => { + command + .env_clear() + .envs(kept_ssh_variables(std::env::vars_os(), cfg!(windows))); + } + Some(Hop::Wsl(_)) => { + command.env("WSL_UTF8", "1"); + } + Some(Hop::Container(_)) | None => {} } } + /// Whether the chain starts with an SSH hop, whose prompts need AskPass. + pub fn starts_with_ssh(&self) -> bool { + matches!(self.hops.first(), Some(Hop::Ssh(_))) + } + /// Stable identity of the chain, for example `ssh:devbox/docker:api`. /// Recent-project lists and per-host storage key on it, so it ignores /// settings such as keep-alive options that do not change the target. @@ -337,6 +426,10 @@ impl TransportChain { None => format!("ssh:{}", hop.destination), }, Hop::Container(hop) => format!("{}:{}", hop.engine.name(), hop.container), + Hop::Wsl(hop) => match &hop.user { + Some(user) => format!("wsl:{user}@{}", hop.distribution), + None => format!("wsl:{}", hop.distribution), + }, }) .collect::>() .join("/") @@ -497,6 +590,44 @@ fn container_command(hop: &ContainerHop, inner: Vec) -> Result, Ok(words) } +fn wsl_command(hop: &WslHop, inner: Vec) -> Result, TransportError> { + if !is_wsl_distribution(&hop.distribution) { + return Err(TransportError::InvalidHop { + reason: format!("invalid WSL distribution {:?}", hop.distribution), + }); + } + let mut command = vec![ + hop.program.clone(), + "--distribution".into(), + hop.distribution.clone(), + ]; + if let Some(user) = &hop.user { + if !is_wsl_user(user) { + return Err(TransportError::InvalidHop { + reason: format!("invalid WSL user {user:?}"), + }); + } + command.push("--user".into()); + command.push(user.clone()); + } + // Without `--cd`, the distribution starts in the Windows working + // directory under /mnt, a slow network mount the server does not need. + command.extend(["--cd".into(), "~".into(), "--exec".into()]); + // Windows passes a command line, not an argument vector; a NUL cannot + // be part of it. + if let Some(Word::Raw(argument) | Word::Generated(argument)) = inner + .iter() + .find(|word| matches!(word, Word::Raw(text) | Word::Generated(text) if text.contains('\0'))) + { + return Err(TransportError::UnsafeArgument { + argument: argument.clone(), + }); + } + let mut words: Vec = command.into_iter().map(Word::Raw).collect(); + words.extend(inner); + Ok(words) +} + fn validate_ssh_destination(destination: &str) -> Result<(), TransportError> { if destination.is_empty() || destination.starts_with('-') @@ -1061,5 +1192,121 @@ mod tests { container(), ssh() ]))); + let wsl = TransportChain::new(vec![Hop::Wsl(WslHop::new("Ubuntu"))]); + assert!(keeps_caller_variable(wsl.clone())); + let mut command = Command::new("true"); + wsl.restrict_environment(&mut command); + assert!(command + .get_envs() + .any(|(name, value)| name == "WSL_UTF8" && value == Some("1".as_ref()))); + } + + fn wsl(distribution: &str, user: Option<&str>) -> TransportChain { + let mut hop = WslHop { + program: "wsl.exe".into(), + ..WslHop::new(distribution) + }; + hop.user = user.map(Into::into); + TransportChain::new(vec![Hop::Wsl(hop)]) + } + + #[test] + fn wsl_hop_passes_arguments_without_a_shell_from_the_home_directory() { + // `--exec` runs no shell, so characters unsafe for shells pass as they are. + assert_eq!( + wsl("Ubuntu-24.04", None) + .command(&strings(&["sh", "-c", "echo \"$HOME\" it's", "x y"])) + .unwrap(), + strings(&[ + "wsl.exe", + "--distribution", + "Ubuntu-24.04", + "--cd", + "~", + "--exec", + "sh", + "-c", + "echo \"$HOME\" it's", + "x y", + ]) + ); + assert_eq!( + wsl("Debian", Some("dev")) + .command(&strings(&["true"])) + .unwrap(), + strings(&[ + "wsl.exe", + "--distribution", + "Debian", + "--user", + "dev", + "--cd", + "~", + "--exec", + "true", + ]) + ); + assert_eq!(wsl("Ubuntu", None).identity(), "wsl:Ubuntu"); + assert_eq!(wsl("Ubuntu", Some("dev")).identity(), "wsl:dev@Ubuntu"); + assert!(!wsl("Ubuntu", None).starts_with_ssh()); + } + + #[test] + fn wsl_hops_refuse_malformed_names_nul_and_a_place_after_the_first_hop() { + let long = "a".repeat(MAX_WSL_DISTRIBUTION_BYTES + 1); + for distribution in ["", "-d", "Ubuntu 24.04", "Ubuntu/x", long.as_str()] { + assert!( + matches!( + wsl(distribution, None).command(&strings(&["true"])), + Err(TransportError::InvalidHop { .. }) + ), + "{distribution:?}" + ); + } + let long_user = "u".repeat(MAX_WSL_USER_BYTES + 1); + for user in ["", "-u", "root;id", long_user.as_str()] { + assert!( + matches!( + wsl("Ubuntu", Some(user)).command(&strings(&["true"])), + Err(TransportError::InvalidHop { .. }) + ), + "{user:?}" + ); + } + assert_eq!( + wsl("Ubuntu", None).command(&strings(&["echo", "a\0b"])), + Err(TransportError::UnsafeArgument { + argument: "a\0b".into() + }) + ); + let behind_ssh = TransportChain::new(vec![ + Hop::Ssh(SshHop::new("devbox")), + Hop::Wsl(WslHop::new("Ubuntu")), + ]); + assert!(matches!( + behind_ssh.command(&strings(&["true"])), + Err(TransportError::InvalidHop { .. }) + )); + // A container inside the distribution is reached through it. + let container = TransportChain::new(vec![ + wsl("Ubuntu", None).hops.remove(0), + Hop::Container(ContainerHop::new(ContainerEngine::Docker, "api")), + ]); + assert_eq!( + container.command(&strings(&["true"])).unwrap()[6..], + strings(&["docker", "exec", "-i", "api", "true"]) + ); + } + + #[test] + fn the_system_wsl_program_comes_from_the_windows_directory() { + let program = wsl_program(); + match std::env::var_os("SystemRoot") { + Some(root) => assert_eq!( + std::path::PathBuf::from(&program), + std::path::Path::new(&root).join("System32").join("wsl.exe") + ), + None => assert_eq!(program, "wsl.exe"), + } } } diff --git a/rust/crates/remote/src/client/trust.rs b/rust/crates/remote/src/client/trust.rs index 3e48d5cc..f119c1df 100644 --- a/rust/crates/remote/src/client/trust.rs +++ b/rust/crates/remote/src/client/trust.rs @@ -20,7 +20,7 @@ //! did not resolve. The platform adapter reads the document and publishes //! edits atomically. -use crate::client::transport::{Hop, TransportChain}; +use crate::client::transport::{is_wsl_distribution, is_wsl_user, Hop, TransportChain}; use serde::{Deserialize, Serialize}; use std::fmt; @@ -76,6 +76,8 @@ pub enum TargetHop { Ssh(SshTarget), /// An `exec` into a container. Container(ContainerTarget), + /// A distribution of the Windows Subsystem for Linux. + Wsl(WslTarget), } /// SSH hop fields that choose the host, the account and the route. @@ -113,6 +115,19 @@ pub struct ContainerTarget { pub user: Option, } +/// WSL hop fields that choose the distribution and the account. The program +/// is always the system's `wsl.exe`, so it is not part of the key. +#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WslTarget { + /// Distribution name as `wsl.exe --list` prints it. + pub distribution: String, + /// Linux account passed as `--user`; absent for the distribution's + /// default user. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user: Option, +} + impl Target { /// The target of a session opened through `chain` to a server running as /// the numeric account `user_id`. @@ -142,6 +157,10 @@ impl Target { container: hop.container.clone(), user: hop.user.clone(), }), + Hop::Wsl(hop) => TargetHop::Wsl(WslTarget { + distribution: hop.distribution.clone(), + user: hop.user.clone(), + }), }) .collect(); Self { hops, user_id } @@ -149,7 +168,8 @@ impl Target { /// Refuses targets no transport chain produces: too many hops, empty, /// oversized or control characters in a field, a destination ssh would - /// read as an option, or an unknown engine. + /// read as an option, an unknown engine, or a WSL hop that is not first + /// or names a distribution or user `wsl.exe` would not be given. fn validate(&self) -> Result<(), TrustError> { let field = |value: &str| { !value.is_empty() @@ -158,7 +178,7 @@ impl Target { }; let optional = |value: &Option| value.as_deref().is_none_or(field); let valid = self.hops.len() <= MAX_HOPS - && self.hops.iter().all(|hop| match hop { + && self.hops.iter().enumerate().all(|(index, hop)| match hop { TargetHop::Ssh(hop) => { field(&hop.destination) && !hop.destination.starts_with('-') @@ -172,6 +192,11 @@ impl Target { && field(&hop.container) && optional(&hop.user) } + TargetHop::Wsl(hop) => { + index == 0 + && is_wsl_distribution(&hop.distribution) + && hop.user.as_deref().is_none_or(is_wsl_user) + } }); if valid { Ok(()) @@ -593,7 +618,7 @@ fn remove(list: &mut Vec, path: &str) { #[cfg(test)] mod tests { use super::*; - use crate::client::transport::{ContainerEngine, ContainerHop, SshHop}; + use crate::client::transport::{ContainerEngine, ContainerHop, SshHop, WslHop}; use serde_json::json; fn ssh(destination: &str) -> SshHop { @@ -714,6 +739,76 @@ mod tests { assert_eq!(target(vec![Hop::Ssh(keep_alive)], Some(1000)), devbox()); } + #[test] + fn wsl_targets_name_the_distribution_and_account_and_come_first_only() { + let wsl = |distribution: &str, user: Option<&str>| { + let mut hop = WslHop::new(distribution); + hop.program = r"C:\Windows\System32\wsl.exe".into(); + hop.user = user.map(Into::into); + Hop::Wsl(hop) + }; + let ubuntu = target(vec![wsl("Ubuntu", Some("dev"))], Some(1000)); + assert_eq!( + serde_json::to_value(&ubuntu).unwrap(), + json!({"hops": [{"wsl": {"distribution": "Ubuntu", "user": "dev"}}], "userId": 1000}) + ); + let mut decisions = Decisions::parse(None).unwrap(); + trust(&mut decisions, &ubuntu, "/home/dev/app", false); + let reparsed = Decisions::parse(Some(&decisions.text().unwrap())).unwrap(); + assert_eq!( + state(&reparsed, &ubuntu, "/home/dev/app"), + TrustState::Trusted + ); + // The program path is where wsl.exe lives, not where the hop ends. + let mut moved = WslHop::new("Ubuntu"); + moved.user = Some("dev".into()); + assert_eq!(target(vec![Hop::Wsl(moved)], Some(1000)), ubuntu); + for other in [ + target(vec![wsl("Ubuntu", None)], Some(1000)), + target(vec![wsl("Ubuntu", Some("root"))], Some(1000)), + target(vec![wsl("Debian", Some("dev"))], Some(1000)), + target(vec![Hop::Ssh(ssh("dev@Ubuntu"))], Some(1000)), + target( + vec![ + wsl("Ubuntu", Some("dev")), + Hop::Container(ContainerHop::new(ContainerEngine::Docker, "api")), + ], + Some(1000), + ), + ] { + assert_ne!(other, ubuntu); + assert_eq!( + state(&reparsed, &other, "/home/dev/app"), + TrustState::Unknown, + "{other:?}" + ); + } + + let entry = |hops: serde_json::Value| { + json!({"version": 1, "targets": [{"target": {"hops": hops}, "trustedWorkspaces": ["/a"]}]}) + .to_string() + }; + for hops in [ + json!([{"ssh": {"destination": "box"}}, {"wsl": {"distribution": "Ubuntu"}}]), + json!([{"wsl": {"distribution": "Ubuntu"}}, {"wsl": {"distribution": "Debian"}}]), + json!([{"wsl": {"distribution": "-d"}}]), + json!([{"wsl": {"distribution": "Ubuntu", "user": "root;id"}}]), + ] { + assert_eq!( + Decisions::parse(Some(&entry(hops.clone()))), + Err(TrustError::at("target")), + "{hops}" + ); + } + // Unknown fields are refused while reading, like any other. + assert_eq!( + Decisions::parse(Some(&entry(json!([ + {"wsl": {"distribution": "Ubuntu", "program": "wsl.exe"}} + ])))), + Err(TrustError::at("document")) + ); + } + #[test] fn a_trusted_location_covers_its_own_target_only_and_never_the_host_root() { let mut decisions = Decisions::parse(None).unwrap(); diff --git a/rust/crates/remote/src/client/wsl.rs b/rust/crates/remote/src/client/wsl.rs new file mode 100644 index 00000000..31c7acd4 --- /dev/null +++ b/rust/crates/remote/src/client/wsl.rs @@ -0,0 +1,256 @@ +//! Distributions of the Windows Subsystem for Linux as remote workspaces. +//! +//! A distribution on the local Windows machine is reached through +//! `wsl.exe` instead of OpenSSH. [`WslConnection`] names the distribution +//! and, optionally, the Linux account, and becomes the first hop of a +//! transport chain; the server is then probed, installed and started inside +//! the distribution exactly as on an SSH host. Nothing is saved: the +//! connection window lists the installed distributions each time it opens, +//! with [`list_command`] and [`parse_distributions`]. +//! +//! `wsl.exe --list` prints UTF-16LE unless `WSL_UTF8=1` is set, and releases +//! before WSL 0.64 ignore that variable, so the parser reads both encodings. +//! +//! Note: .agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md + +use crate::client::connections::{ConnectionError, Reason}; +use crate::client::transport::{ + is_wsl_distribution, is_wsl_user, wsl_program, WslHop, MAX_WSL_DISTRIBUTION_BYTES, + MAX_WSL_USER_BYTES, +}; +use serde::{Deserialize, Serialize}; + +/// Distributions one listing returns at most; later ones are dropped. +pub const MAX_DISTRIBUTIONS: usize = 64; + +/// Bytes of `wsl.exe --list` output read at most; the rest is ignored. +pub const MAX_LIST_BYTES: usize = 64 * 1024; + +/// Distributions Docker Desktop registers for its own engine. They hold no +/// user workspace, and `docker-desktop-data` has no shell at all, so +/// listings leave them out, as Visual Studio Code does. +const ENGINE_DISTRIBUTIONS: [&str; 2] = ["docker-desktop", "docker-desktop-data"]; + +/// `remote.connect`'s `wsl` field: the distribution to open and the account. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct WslConnection { + /// Distribution name as `wsl.exe --list` prints it, for example `Ubuntu-24.04`. + pub distribution: String, + /// Linux account passed as `--user`; the distribution's default user when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub user: Option, +} + +impl WslConnection { + /// The hop into the distribution through the system's `wsl.exe`. Both + /// fields are trimmed and an empty `user` means the default user. + /// + /// Refused, with the field and the reason, when the distribution is + /// empty, longer than 64 bytes or not a name `wsl.exe --import` accepts, + /// or the user is longer than 32 bytes or not a Linux login name. + pub fn hop(&self) -> Result { + let distribution = self.distribution.trim(); + if distribution.is_empty() { + return Err(ConnectionError::at("distribution", Reason::Required)); + } + if distribution.len() > MAX_WSL_DISTRIBUTION_BYTES { + return Err(ConnectionError::at("distribution", Reason::TooLong)); + } + if !is_wsl_distribution(distribution) { + return Err(ConnectionError::at("distribution", Reason::Invalid)); + } + let user = self + .user + .as_deref() + .map(str::trim) + .filter(|user| !user.is_empty()); + if let Some(user) = user { + if user.len() > MAX_WSL_USER_BYTES { + return Err(ConnectionError::at("user", Reason::TooLong)); + } + if !is_wsl_user(user) { + return Err(ConnectionError::at("user", Reason::Invalid)); + } + } + let mut hop = WslHop::new(distribution); + hop.user = user.map(Into::into); + Ok(hop) + } +} + +/// Local command line that prints the installed distributions, one name per +/// line (`wsl.exe --list --quiet`). +pub fn list_command() -> Vec { + vec![wsl_program(), "--list".into(), "--quiet".into()] +} + +/// The distribution names in the output of [`list_command`], in the order +/// `wsl.exe` printed them. +/// +/// Reads UTF-16LE, with or without a byte order mark, and UTF-8. Leaves out +/// Docker Desktop's engine distributions, repeated names (WSL compares names +/// without regard to case), and lines that are not distribution names, such +/// as the message `wsl.exe` prints when none is installed. At most +/// [`MAX_LIST_BYTES`] of output and [`MAX_DISTRIBUTIONS`] names are read. +pub fn parse_distributions(output: &[u8]) -> Vec { + let output = &output[..output.len().min(MAX_LIST_BYTES)]; + let text = output_text(output); + let mut names: Vec = Vec::new(); + for line in text.lines() { + let name = line.trim_matches(|character: char| { + character.is_whitespace() || character == '\0' || character == '\u{feff}' + }); + let known = |known: &str| known.eq_ignore_ascii_case(name); + if !is_wsl_distribution(name) + || ENGINE_DISTRIBUTIONS.iter().any(|engine| known(engine)) + || names.iter().any(|seen| known(seen)) + { + continue; + } + names.push(name.into()); + if names.len() == MAX_DISTRIBUTIONS { + break; + } + } + names +} + +/// What `wsl.exe` itself printed, as text: UTF-16LE when it starts with that +/// byte order mark or its second byte is NUL, which no UTF-8 text has, and +/// UTF-8 otherwise. Malformed sequences become replacement characters, which +/// no distribution name has. +pub fn output_text(output: &[u8]) -> String { + let utf16 = match output { + [0xff, 0xfe, rest @ ..] => Some(rest), + [_, 0, ..] => Some(output), + _ => None, + }; + match utf16 { + Some(bytes) => char::decode_utf16( + bytes + .as_chunks::<2>() + .0 + .iter() + .map(|pair| u16::from_le_bytes(*pair)), + ) + .map(|unit| unit.unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect(), + None => String::from_utf8_lossy(output).into_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn utf16(text: &str, bom: bool) -> Vec { + let mut bytes = if bom { vec![0xff, 0xfe] } else { Vec::new() }; + bytes.extend(text.encode_utf16().flat_map(u16::to_le_bytes)); + bytes + } + + #[test] + fn listings_read_utf16_with_or_without_a_byte_order_mark_and_utf8() { + let listing = "Ubuntu-24.04\r\nDebian\r\n"; + let expected = vec!["Ubuntu-24.04".to_owned(), "Debian".to_owned()]; + assert_eq!(parse_distributions(&utf16(listing, false)), expected); + assert_eq!(parse_distributions(&utf16(listing, true)), expected); + assert_eq!(parse_distributions(listing.as_bytes()), expected); + // WSL_UTF8 output may still end each line with a NUL. + assert_eq!( + parse_distributions(b"Ubuntu-24.04\0\r\n\r\nDebian\n"), + expected + ); + assert!(parse_distributions(b"").is_empty()); + assert!(parse_distributions(&[0xff, 0xfe]).is_empty()); + // Messages decode the same way, so diagnostics stay readable. + let message = "There is no distribution with the supplied name.\r\n"; + assert_eq!(output_text(&utf16(message, false)), message); + assert_eq!(output_text(message.as_bytes()), message); + assert_eq!(output_text(b"x"), "x"); + } + + #[test] + fn listings_leave_out_engine_distributions_repeats_and_messages() { + let listing = "docker-desktop\r\nUbuntu\r\nDOCKER-DESKTOP-DATA\r\nubuntu\r\n\ + Windows Subsystem for Linux has no installed distributions.\r\n\ + https://aka.ms/wslstore\r\n-d\r\nAlpine\r\n"; + assert_eq!( + parse_distributions(&utf16(listing, false)), + vec!["Ubuntu".to_owned(), "Alpine".to_owned()] + ); + let many: String = (0..MAX_DISTRIBUTIONS + 5) + .map(|index| format!("Distro{index}\n")) + .collect(); + let names = parse_distributions(many.as_bytes()); + assert_eq!(names.len(), MAX_DISTRIBUTIONS); + assert_eq!(names[0], "Distro0"); + // Output past the bound is not read. + let mut long = "a".repeat(MAX_LIST_BYTES).into_bytes(); + long.extend(b"\nLate\n"); + assert!(parse_distributions(&long).is_empty()); + } + + #[test] + fn connections_become_a_hop_after_trimming_and_refuse_malformed_fields() { + let connection = |distribution: &str, user: Option<&str>| WslConnection { + distribution: distribution.into(), + user: user.map(Into::into), + }; + let hop = connection(" Ubuntu-24.04 ", Some(" dev ")).hop().unwrap(); + assert_eq!(hop.distribution, "Ubuntu-24.04"); + assert_eq!(hop.user.as_deref(), Some("dev")); + assert_eq!(hop.program, wsl_program()); + assert_eq!(connection("Debian", Some(" ")).hop().unwrap().user, None); + + let long_distribution = "d".repeat(MAX_WSL_DISTRIBUTION_BYTES + 1); + let long_user = "u".repeat(MAX_WSL_USER_BYTES + 1); + for (refused, field, reason) in [ + (connection(" ", None), "distribution", Reason::Required), + ( + connection(&long_distribution, None), + "distribution", + Reason::TooLong, + ), + (connection("-d", None), "distribution", Reason::Invalid), + ( + connection("Ubuntu 24", None), + "distribution", + Reason::Invalid, + ), + ( + connection("Ubuntu", Some(&long_user)), + "user", + Reason::TooLong, + ), + (connection("Ubuntu", Some("-u")), "user", Reason::Invalid), + (connection("Ubuntu", Some("a b")), "user", Reason::Invalid), + ] { + assert_eq!( + refused.hop(), + Err(ConnectionError::at(field, reason)), + "{refused:?}" + ); + } + } + + #[test] + fn requests_name_only_the_distribution_and_the_user() { + let parsed: WslConnection = + serde_json::from_value(serde_json::json!({"distribution": "Ubuntu"})).unwrap(); + assert_eq!(parsed.user, None); + assert!(serde_json::from_value::( + serde_json::json!({"distribution": "Ubuntu", "program": "C:\\evil.exe"}) + ) + .is_err()); + } + + #[test] + fn the_listing_runs_the_system_wsl_program_quietly() { + assert_eq!( + list_command(), + vec![wsl_program(), "--list".into(), "--quiet".into()] + ); + } +} diff --git a/rust/crates/workspace/src/lib.rs b/rust/crates/workspace/src/lib.rs index 0e59d2fa..77d36b48 100644 --- a/rust/crates/workspace/src/lib.rs +++ b/rust/crates/workspace/src/lib.rs @@ -10,13 +10,14 @@ //! The session side owns the long-lived connections: [`connections`] keeps //! the SSH connections the user saved, [`ssh_configuration`] tells what //! OpenSSH makes of them and lists the hosts of the user's SSH configuration, -//! [`motty`] lists the hosts saved in Motty for an import, [`probe`] checks -//! that a saved SSH connection reaches a usable host, [`sessions`] opens and -//! keeps the connections, [`host`] forwards finite requests and owned -//! streaming resources (processes, terminals, watches), [`forwards`] keeps the -//! port forwards of -//! the ports page, [`upload`] streams a verified file to the host, and -//! [`trust`] keys remote workspace trust by what the connection resolves. +//! [`motty`] lists the hosts saved in Motty for an import, [`wsl`] lists the +//! WSL distributions of this Windows machine, [`probe`] checks that a saved +//! SSH connection reaches a usable host, [`sessions`] opens and keeps the +//! connections (over OpenSSH or `wsl.exe`), [`host`] forwards finite requests +//! and owned streaming resources (processes, terminals, watches), +//! [`forwards`] keeps the port forwards of the ports page, [`upload`] streams +//! a verified file to the host, and [`trust`] keys remote workspace trust by +//! what the connection resolves. //! Domain semantics stay in their engines (Git, build, language servers); //! this crate only supplies the IO boundary. @@ -33,6 +34,7 @@ pub mod ssh_configuration; pub mod test_support; pub mod trust; pub mod upload; +pub mod wsl; pub use scope::{ current, enter, identity_key, is_remote, local_path, remote_path, Host, Scope, Workspace, diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index 46385dcf..8b85d26a 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -260,20 +260,39 @@ pub(crate) fn classify(exit: Option, stdout: &[u8], stderr: &[u8]) - } else { ProbeStatus::Failed }; - let diagnostics = if diagnostics.is_empty() { - // Some failures, such as a remote shell that exits early, print - // nothing; the exit status is then the only clue. - match exit.and_then(|exit| exit.code()) { - Some(code) => format!("ssh exited with status {code}"), - None => "ssh was terminated by a signal".into(), - } + ProbeResult { + status, + host: None, + diagnostics: or_exit_status(diagnostics, "ssh", exit), + } +} + +/// Interprets a `wsl.exe` that exited before the server started. `wsl.exe` +/// names its failures with stable error codes, such as +/// `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`, and may print them in UTF-16. +pub(crate) fn classify_wsl(exit: Option, stderr: &[u8]) -> ProbeResult { + let text = lithe_remote::client::wsl::output_text(stderr); + let status = if text.contains("WSL_E_DISTRO_NOT_FOUND") { + ProbeStatus::Unreachable } else { - diagnostics + ProbeStatus::Failed }; ProbeResult { status, host: None, - diagnostics, + diagnostics: or_exit_status(diagnostics(&text), "wsl.exe", exit), + } +} + +/// `diagnostics`, or the exit status of `program` when it printed nothing: +/// some failures, such as a remote shell that exits early, are silent. +fn or_exit_status(diagnostics: String, program: &str, exit: Option) -> String { + if !diagnostics.is_empty() { + return diagnostics; + } + match exit.and_then(|exit| exit.code()) { + Some(code) => format!("{program} exited with status {code}"), + None => format!("{program} was terminated by a signal"), } } diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 518bd198..79557617 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -338,6 +338,138 @@ fn the_ssh_client_starts_with_only_the_variables_it_needs() { } } +#[cfg(unix)] +fn wsl_request(wsl: serde_json::Value) -> sessions::ConnectRequest { + serde_json::from_value(json!({ + "wsl": wsl, + "servers": [], + "serverVersion": "0.1.0", + })) + .unwrap() +} + +/// Stand-in for `wsl.exe`: writes its arguments and variables next to +/// itself, then runs what follows `--exec` with the local shell. +#[cfg(unix)] +const FAKE_WSL: &str = "printf '%s\\n' \"$@\" > \"$0.arguments\"\n\ + env > \"$0.environment\"\n\ + while [ \"$#\" -gt 0 ]; do case \"$1\" in --exec) shift; break;; *) shift;; esac; done\n\ + exec \"$@\""; + +// A WSL distribution is reached through `wsl.exe` instead of OpenSSH: the +// server is probed inside the distribution like on an SSH host, `wsl.exe` +// keeps the Windows environment it needs, and nothing asks through AskPass. +#[cfg(unix)] +#[test] +fn connecting_to_a_wsl_distribution_runs_the_launch_through_wsl() { + let wsl = FakeSsh::new("remote-connect-wsl", FAKE_WSL); + let request = wsl_request(json!({ "distribution": " Ubuntu-24.04 ", "user": "dev" })); + let result = sessions::connect_with(request, Some(wsl.path())).unwrap(); + let value = serde_json::to_value(result).unwrap(); + assert_eq!(value["status"], "unsupportedPlatform"); + assert_eq!(value["host"]["system"], local_uname("-s")); + let arguments = std::fs::read_to_string(wsl.program.with_extension("arguments")).unwrap(); + let arguments: Vec<&str> = arguments.lines().collect(); + assert_eq!( + arguments[..7], + [ + "--distribution", + "Ubuntu-24.04", + "--user", + "dev", + "--cd", + "~", + "--exec" + ] + ); + let seen = environment_seen_by(&wsl); + let names = seen.keys().collect::>(); + assert_eq!( + seen.get("WSL_UTF8").map(String::as_str), + Some("1"), + "{names:?}" + ); + assert!(seen.contains_key("CARGO_PKG_NAME"), "{names:?}"); + assert!(!seen.contains_key("SSH_ASKPASS_REQUIRE"), "{names:?}"); +} + +// `wsl.exe` prints its failures in UTF-16 with a stable error code; an +// unknown distribution reads like an unknown host name. +#[cfg(unix)] +#[test] +fn an_unknown_wsl_distribution_is_unreachable_with_readable_diagnostics() { + let message = "There is no distribution with the supplied name.\r\n\ + Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n"; + let escaped: String = message + .encode_utf16() + .flat_map(u16::to_le_bytes) + .map(|byte| format!("\\{byte:03o}")) + .collect(); + let wsl = FakeSsh::new( + "remote-connect-wsl-missing", + &format!("printf '{escaped}' >&2\nexit 1"), + ); + let request = wsl_request(json!({ "distribution": "Missing" })); + let result = sessions::connect_with(request, Some(wsl.path())).unwrap(); + let value = serde_json::to_value(result).unwrap(); + assert_eq!(value["status"], "unreachable"); + assert_eq!(value["session"], serde_json::Value::Null); + assert_eq!( + value["diagnostics"], + "There is no distribution with the supplied name.\r\n\ + Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND" + ); + // A silent failure still says which program gave up. + let silent = FakeSsh::new("remote-connect-wsl-silent", "exit 3"); + let request = wsl_request(json!({ "distribution": "Ubuntu" })); + let value = serde_json::to_value(sessions::connect_with(request, Some(silent.path())).unwrap()) + .unwrap(); + assert_eq!(value["status"], "failed"); + assert_eq!(value["diagnostics"], "wsl.exe exited with status 3"); +} + +// A connection names exactly one way to reach the host, and a malformed WSL +// field is refused before anything runs, naming the field. +#[cfg(unix)] +#[test] +fn connections_name_exactly_one_client() { + let wsl = FakeSsh::new("remote-connect-wsl-refused", "touch \"$0.ran\""); + let refused = |request: serde_json::Value| { + let request: sessions::ConnectRequest = serde_json::from_value(request).unwrap(); + let error = sessions::connect_with(request, Some(wsl.path())).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest), "{error:?}"); + serde_json::from_str::(error.details.as_deref().unwrap()).unwrap() + }; + assert_eq!( + refused(json!({ "servers": [], "serverVersion": "0.1.0" })), + json!({ "field": "connection", "reason": "required" }) + ); + assert_eq!( + refused(json!({ + "connection": { "host": "devbox" }, + "wsl": { "distribution": "Ubuntu" }, + "servers": [], + "serverVersion": "0.1.0", + })), + json!({ "field": "wsl", "reason": "invalid" }) + ); + assert_eq!( + refused( + json!({ "wsl": { "distribution": "-d" }, "servers": [], "serverVersion": "0.1.0" }) + ), + json!({ "field": "distribution", "reason": "invalid" }) + ); + assert_eq!( + refused(json!({ + "wsl": { "distribution": "Ubuntu", "user": "root;id" }, + "servers": [], + "serverVersion": "0.1.0", + })), + json!({ "field": "user", "reason": "invalid" }) + ); + assert!(!wsl.program.with_extension("ran").exists()); +} + // The connection log keeps one category per failed status, so a log line // tells authentication, host key and network failures apart. #[test] diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 52b2f81c..e3febe8b 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -1,22 +1,26 @@ //! Long-lived remote connections. //! -//! `remote.connect` starts one OpenSSH process that probes the host, installs -//! the server when needed and starts it (see `lithe_remote::client::launch`), -//! so the user authenticates once. The connection then stays open in this -//! registry until `remote.disconnect`; requests such as `remote.readDir` use -//! it by id. OpenSSH runs in its own process tree, which closing a connection -//! ends, together with the connection's port forwards. - -use crate::probe::{classify, diagnostics, relay_challenge, ssh_hop, ProbeStatus, ProbedHost}; +//! `remote.connect` starts one client process, OpenSSH for a host or +//! `wsl.exe` for a WSL distribution on this machine, that probes the host, +//! installs the server when needed and starts it (see +//! `lithe_remote::client::launch`), so the user authenticates once. The +//! connection then stays open in this registry until `remote.disconnect`; +//! requests such as `remote.readDir` use it by id. The client runs in its own +//! process tree, which closing a connection ends, together with the +//! connection's port forwards. + +use crate::probe::{ + classify, classify_wsl, diagnostics, relay_challenge, ssh_hop, ProbeStatus, ProbedHost, +}; use lithe_git_host::ProcessTree; use lithe_protocol::{CoreError, ErrorCode}; -use lithe_remote::client::connections::SshConnection; +use lithe_remote::client::connections::{ConnectionError, Reason, SshConnection}; use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, Stage}; use lithe_remote::client::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ - ArtifactError, ConnectionKind, ConnectionLog, ForwardSet, Hop, RemoteSession, ServerArtifact, - ServerTarget, TransportChain, + wsl, ArtifactError, ConnectionKind, ConnectionLog, ForwardSet, Hop, RemoteSession, + ServerArtifact, ServerTarget, TransportChain, WslConnection, }; use lithe_remote::protocol::methods; use lithe_request_context::events as execution_events; @@ -44,10 +48,10 @@ const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30); /// Deadline for one request over an open connection. const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); -/// Time OpenSSH gets to exit and print its reason after the stream ended. +/// Time the client gets to exit and print its reason after the stream ended. const EXIT_GRACE: Duration = Duration::from_secs(2); -/// Bytes of OpenSSH's standard error kept while a connection is open. +/// Bytes of the client's standard error kept while a connection is open. const STDERR_TAIL_BYTES: usize = 8 * 1024; /// A server build shipped with the host. @@ -63,12 +67,17 @@ struct ServerInput { sha256: String, } -/// `remote.connect`: the connection, the server builds Core may install, -/// and where to install them. +/// `remote.connect`: the host, the server builds Core may install, and where +/// to install them. Exactly one of `connection` and `wsl` names the host. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ConnectRequest { - connection: SshConnection, + /// A host reached through OpenSSH. + #[serde(default)] + connection: Option, + /// A WSL distribution on this machine, reached through `wsl.exe`. + #[serde(default)] + wsl: Option, servers: Vec, server_version: String, /// Install root on the remote; `None` is `$HOME/.lithe-server`. @@ -117,7 +126,8 @@ pub struct Connection { /// Owns the native transport independently of the framed workspace session. pub(crate) enum ConnectionTransport { - Ssh { + /// The client process, OpenSSH or `wsl.exe`, and its process tree. + Process { child: Mutex, tree: ProcessTree, }, @@ -162,7 +172,7 @@ impl Connection { } } match &self.transport { - ConnectionTransport::Ssh { child, tree } => { + ConnectionTransport::Process { child, tree } => { let mut child = child .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -191,7 +201,7 @@ impl Connection { } } -/// Records one failed SSH transport cleanup step. The caller keeps its own +/// Records one failed client process cleanup step. The caller keeps its own /// result; WARN reports a process that may outlive the session. fn record_cleanup_io(stage: &str, error: &std::io::Error) { lithe_diagnostics::core_events::recovery_failed( @@ -202,7 +212,7 @@ fn record_cleanup_io(stage: &str, error: &std::io::Error) { ); } -/// Kills the SSH process tree and reaps its root, recording each failed step. +/// Kills the client's process tree and reaps its root, recording each failed step. fn reap(tree: &ProcessTree, child: &mut Child) { if let Err(error) = tree.kill() { record_cleanup_io("tree-kill", &error); @@ -271,18 +281,112 @@ pub fn connect(request: ConnectRequest) -> Result { connect_with(request, None) } -/// `ssh_program` replaces the `ssh` found on `PATH`; tests use a stand-in. +/// The local program that reaches the host. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Client { + /// OpenSSH, which asks its questions through AskPass. + Ssh, + /// `wsl.exe`, which starts a local distribution and asks nothing. + Wsl, +} + +impl Client { + /// The client `request` names. A request that names both or neither is + /// refused by [`first_hop`]; it counts as SSH until then. + fn of(request: &ConnectRequest) -> Self { + if request.wsl.is_some() && request.connection.is_none() { + Self::Wsl + } else { + Self::Ssh + } + } + + fn log_kind(self) -> ConnectionKind { + match self { + Self::Ssh => ConnectionKind::Ssh, + Self::Wsl => ConnectionKind::Wsl, + } + } + + fn invalid(self) -> &'static str { + match self { + Self::Ssh => "Invalid SSH connection", + Self::Wsl => "Invalid WSL connection", + } + } + + fn start_failed(self) -> &'static str { + match self { + Self::Ssh => "Could not start the SSH client", + Self::Wsl => "Could not start wsl.exe", + } + } + + fn supervise_failed(self) -> &'static str { + match self { + Self::Ssh => "Could not supervise the SSH client", + Self::Wsl => "Could not supervise wsl.exe", + } + } + + fn timed_out(self) -> &'static str { + match self { + Self::Ssh => "The SSH connection did not finish in time", + Self::Wsl => "The WSL distribution did not finish starting in time", + } + } + + /// The client's standard error as text; `wsl.exe` may print UTF-16. + fn text(self, stderr: &[u8]) -> String { + match self { + Self::Ssh => String::from_utf8_lossy(stderr).into_owned(), + Self::Wsl => wsl::output_text(stderr), + } + } +} + +/// The hop that starts the chain, with `program` in place of the system +/// client when set. Exactly one of `connection` and `wsl` must be set. +fn first_hop(request: &ConnectRequest, program: Option<&str>) -> Result { + let refused = + |field, reason| crate::connections::invalid_request(ConnectionError { field, reason }); + match (&request.connection, &request.wsl) { + (Some(connection), None) => { + let mut hop = ssh_hop(connection)?; + if let Some(program) = program { + hop.program = program.into(); + } + Ok(Hop::Ssh(hop)) + } + (None, Some(distribution)) => { + let mut hop = distribution + .hop() + .map_err(crate::connections::invalid_request)?; + if let Some(program) = program { + hop.program = program.into(); + } + Ok(Hop::Wsl(hop)) + } + (None, None) => Err(refused("connection", Reason::Required)), + (Some(_), Some(_)) => Err(refused("wsl", Reason::Invalid)), + } +} + +/// `program` replaces the system client (`ssh` on `PATH`, or `wsl.exe`); +/// tests use a stand-in. /// /// The attempt is recorded in a [`ConnectionLog`]. The launch and the /// handshake record the failures they see themselves; this records what only -/// the SSH process shows (authentication, host key, network), cancellation -/// and local errors, as stable categories without diagnostics or host names. +/// the client process shows (authentication, host key, network), +/// cancellation and local errors, as stable categories without diagnostics +/// or host names. pub(crate) fn connect_with( request: ConnectRequest, - ssh_program: Option<&str>, + program: Option<&str>, ) -> Result { - let log = ConnectionLog::begin(ConnectionKind::Ssh); - let result = connect_logged(request, ssh_program, &log); + let client = Client::of(&request); + let log = ConnectionLog::begin(client.log_kind()); + let result = connect_logged(request, client, program, &log); match &result { Ok(result) => { if let Some((stage, code)) = failure_of(result.status) { @@ -313,7 +417,8 @@ pub(crate) fn failure_of(status: ProbeStatus) -> Option<(&'static str, &'static fn connect_logged( request: ConnectRequest, - ssh_program: Option<&str>, + client: Client, + program: Option<&str>, log: &ConnectionLog, ) -> Result { // Only the build for the host's platform is read and checked, once the @@ -341,23 +446,17 @@ fn connect_logged( let rejected_in_launch = Arc::clone(&rejected); let _connecting = ConnectingGuard::enter(); - let mut hop = ssh_hop(&request.connection)?; - if let Some(program) = ssh_program { - hop.program = program.into(); - } - let chain = TransportChain::new(vec![Hop::Ssh(hop)]); + let chain = TransportChain::new(vec![first_hop(&request, program)?]); let argv = chain .command(&launch_command( request.install_root.as_deref(), &["--stdio"], )) .map_err(|error| { - CoreError::new(ErrorCode::InvalidRequest, "Invalid SSH connection") + CoreError::new(ErrorCode::InvalidRequest, client.invalid()) .with_details(error.to_string()) })?; - let (program, arguments) = argv - .split_first() - .expect("an SSH hop always produces a command"); + let (program, arguments) = argv.split_first().expect("a hop always produces a command"); let mut process = Command::new(program); process .args(arguments) @@ -366,31 +465,37 @@ fn connect_logged( .stderr(Stdio::piped()); // Before the AskPass variables, which must reach ssh. chain.restrict_environment(&mut process); - let mut authentication = lithe_git_host::authentication::Session::new().map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not prepare SSH authentication", - ) - .with_details(error.to_string()) - })?; - authentication.configure(&mut process).map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not configure SSH authentication", - ) - .with_details(error.to_string()) - })?; + // OpenSSH asks for passwords, passphrases and host keys through AskPass; + // `wsl.exe` starts a local distribution as a local user and asks nothing. + let mut authentication = match client { + Client::Ssh => { + let authentication = + lithe_git_host::authentication::Session::new().map_err(|error| { + CoreError::new( + ErrorCode::ProcessStartFailed, + "Could not prepare SSH authentication", + ) + .with_details(error.to_string()) + })?; + authentication.configure(&mut process).map_err(|error| { + CoreError::new( + ErrorCode::ProcessStartFailed, + "Could not configure SSH authentication", + ) + .with_details(error.to_string()) + })?; + Some(authentication) + } + Client::Wsl => None, + }; ProcessTree::prepare(&mut process); let mut child = process.spawn().map_err(|error| { - CoreError::new(ErrorCode::RuntimeMissing, "Could not start the SSH client") + CoreError::new(ErrorCode::RuntimeMissing, client.start_failed()) .with_details(error.to_string()) })?; let tree = ProcessTree::adopt(&mut child).map_err(|error| { - CoreError::new( - ErrorCode::ProcessStartFailed, - "Could not supervise the SSH client", - ) - .with_details(error.to_string()) + CoreError::new(ErrorCode::ProcessStartFailed, client.supervise_failed()) + .with_details(error.to_string()) })?; let stderr_tail = Arc::new(Mutex::new(VecDeque::new())); let stderr_reader = Mutex::new( @@ -459,25 +564,24 @@ fn connect_logged( } if Instant::now() >= deadline { return abandon( - CoreError::new( - ErrorCode::TimedOut, - "The SSH connection did not finish in time", - ), + CoreError::new(ErrorCode::TimedOut, client.timed_out()), &mut child, ); } relay_stages(&stages); - match authentication.poll() { - Ok(challenges) => challenges.into_iter().for_each(relay_challenge), - Err(error) => { - return abandon( - CoreError::new( - ErrorCode::ProcessFailed, - "SSH authentication transport failed", + if let Some(authentication) = authentication.as_mut() { + match authentication.poll() { + Ok(challenges) => challenges.into_iter().for_each(relay_challenge), + Err(error) => { + return abandon( + CoreError::new( + ErrorCode::ProcessFailed, + "SSH authentication transport failed", + ) + .with_details(error.to_string()), + &mut child, ) - .with_details(error.to_string()), - &mut child, - ) + } } } match launched.recv_timeout(POLL_INTERVAL) { @@ -533,10 +637,14 @@ fn connect_logged( let launched = match result { Ok(launched) => launched, Err(LaunchError::NoShell) => { - // OpenSSH prints why it gave up only as it exits. + // The client prints why it gave up only as it exits. let status = wait_for_exit(&mut child, EXIT_GRACE); reap(&tree, &mut child); - let probe = classify(status, &[], &tail(&stderr_tail)); + let stderr = tail(&stderr_tail); + let probe = match client { + Client::Ssh => classify(status, &[], &stderr), + Client::Wsl => classify_wsl(status, &stderr), + }; return Ok(failed(probe.status, None, probe.diagnostics)); } Err(LaunchError::NoArtifact(report)) => { @@ -568,7 +676,7 @@ fn connect_logged( } Err(error) => { reap(&tree, &mut child); - let stderr = diagnostics(&String::from_utf8_lossy(&tail(&stderr_tail))); + let stderr = diagnostics(&client.text(&tail(&stderr_tail))); return Ok(failed( ProbeStatus::Failed, None, @@ -595,7 +703,7 @@ fn connect_logged( // Grace expiry is advisory: the following checked kill/wait owns the final cleanup result. wait_for_exit(&mut child, EXIT_GRACE); reap(&tree, &mut child); - let stderr = diagnostics(&String::from_utf8_lossy(&tail(&stderr_tail))); + let stderr = diagnostics(&client.text(&tail(&stderr_tail))); return Ok(failed( ProbeStatus::Failed, Some(host), @@ -616,7 +724,7 @@ fn connect_logged( Arc::new(Connection::new( session, Target::new(&chain, capabilities.user_id), - ConnectionTransport::Ssh { + ConnectionTransport::Process { child: Mutex::new(child), tree, }, diff --git a/rust/crates/workspace/src/wsl.rs b/rust/crates/workspace/src/wsl.rs new file mode 100644 index 00000000..dedb012f --- /dev/null +++ b/rust/crates/workspace/src/wsl.rs @@ -0,0 +1,182 @@ +//! `remote.listWslDistributions`: the WSL distributions installed on this +//! Windows machine, for the connection window. +//! +//! The list is read from `wsl.exe --list --quiet` each time the window asks; +//! nothing is saved. Other systems have no WSL and answer without running +//! anything. Connecting to a distribution is `remote.connect` with `wsl`. + +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_remote::client::wsl; +use serde::Serialize; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// How long `wsl.exe --list` may take. The first call after boot starts the +/// WSL service, which takes a few seconds. +const LIST_TIMEOUT: Duration = Duration::from_secs(15); + +/// `remote.listWslDistributions` result. +#[derive(Debug, Default, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Distributions { + /// `wsl.exe` ran. `false` on other systems and when it could not start. + pub available: bool, + /// Installed distributions in `wsl.exe` order, without Docker Desktop's + /// engine distributions. + pub distributions: Vec, + /// What `wsl.exe` printed when it failed, such as the message that WSL + /// is not installed, redacted; empty otherwise. Shown, never logged. + pub diagnostics: String, +} + +/// The distributions installed on this machine. +pub fn list() -> Result { + list_with(None) +} + +/// `program` replaces the system `wsl.exe`, also on systems without WSL; +/// tests use a stand-in. +pub(crate) fn list_with(program: Option<&str>) -> Result { + if program.is_none() && !cfg!(windows) { + return Ok(Distributions::default()); + } + let argv = wsl::list_command(); + let (system, arguments) = argv + .split_first() + .expect("the listing always names wsl.exe"); + let mut process = Command::new(program.unwrap_or(system)); + // `wsl.exe` needs the Windows environment, as for a connection. + process.args(arguments).env("WSL_UTF8", "1"); + let deadline = Instant::now() + LIST_TIMEOUT; + let mut stop = None; + let outcome = lithe_git_host::run( + &mut process, + None, + || { + if let Err(error) = lithe_protocol::cancellation::check() { + stop = Some(error); + } else if Instant::now() >= deadline { + stop = Some(CoreError::new( + ErrorCode::TimedOut, + "wsl.exe did not list the distributions in time", + )); + } + stop.is_some() + }, + || {}, + |_, _| {}, + ); + if let Some(error) = stop { + return Err(error); + } + match outcome.failure { + None => {} + // No `wsl.exe`: WSL is not part of this Windows. + Some(lithe_git_host::Failure::Start(_)) => return Ok(Distributions::default()), + Some(failure) => { + return Err(CoreError::new(ErrorCode::ProcessFailed, "wsl.exe failed") + .with_details(format!("{failure:?}"))) + } + } + if outcome.status.is_some_and(|status| status.success()) { + return Ok(Distributions { + available: true, + distributions: wsl::parse_distributions(&outcome.stdout), + diagnostics: String::new(), + }); + } + // `wsl.exe` prints its messages to standard output, for example when no + // distribution is installed, and some to standard error. + let mut printed = wsl::output_text(&outcome.stdout); + printed.push('\n'); + printed.push_str(&wsl::output_text(&outcome.stderr)); + Ok(Distributions { + available: true, + distributions: Vec::new(), + diagnostics: crate::probe::diagnostics(&printed), + }) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + struct FakeWsl { + root: PathBuf, + program: String, + } + + impl FakeWsl { + fn new(label: &str, body: &str) -> Self { + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "lithe-wsl-list-{label}-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let program = root.join("wsl"); + std::fs::write(&program, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap(); + Self { + root, + program: program.to_string_lossy().into_owned(), + } + } + } + + impl Drop for FakeWsl { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } + } + + #[test] + fn listings_run_wsl_quietly_and_read_its_utf16_output() { + // "Ubuntu\r\ndocker-desktop\r\n" in UTF-16LE with a byte order mark. + let fake = FakeWsl::new( + "utf16", + r#"printf '%s\n' "$@" "$WSL_UTF8" > "$0.arguments" +printf '\377\376U\000b\000u\000n\000t\000u\000\r\000\n\000d\000o\000c\000k\000e\000r\000-\000d\000e\000s\000k\000t\000o\000p\000\r\000\n\000'"#, + ); + let listed = list_with(Some(&fake.program)).unwrap(); + assert_eq!( + listed, + Distributions { + available: true, + distributions: vec!["Ubuntu".into()], + diagnostics: String::new(), + } + ); + let arguments = std::fs::read_to_string(format!("{}.arguments", fake.program)).unwrap(); + assert_eq!(arguments, "--list\n--quiet\n1\n"); + } + + #[test] + fn failed_listings_are_available_with_the_message_and_no_names() { + let fake = FakeWsl::new( + "none", + "printf 'Windows Subsystem for Linux has no installed distributions.\\r\\n'\nexit 1", + ); + let listed = list_with(Some(&fake.program)).unwrap(); + assert!(listed.available); + assert!(listed.distributions.is_empty()); + assert_eq!( + listed.diagnostics, + "Windows Subsystem for Linux has no installed distributions." + ); + } + + #[test] + fn a_missing_wsl_and_other_systems_are_unavailable() { + let fake = FakeWsl::new("missing", "exit 0"); + let missing = fake.root.join("absent").to_string_lossy().into_owned(); + assert_eq!(list_with(Some(&missing)).unwrap(), Distributions::default()); + // Without an override nothing runs outside Windows. + assert_eq!(list().unwrap(), Distributions::default()); + } +} diff --git a/rust/logging/events/remote.json b/rust/logging/events/remote.json index ec426efb..04ad8c28 100644 --- a/rust/logging/events/remote.json +++ b/rust/logging/events/remote.json @@ -61,12 +61,12 @@ "stage": { "type": "token", "required": true, - "description": "SSH connection cleanup stage, e.g. shutdown, tree-kill, wait, or closer" + "description": "Connection cleanup stage of the owned ssh or wsl.exe process, e.g. shutdown, tree-kill, wait, or closer" }, "error": { "type": "error", "required": true, - "description": "Stable native, thread, or remote category from ending an owned SSH connection" + "description": "Stable native, thread, or remote category from ending an owned ssh or wsl.exe connection" } }, "rate": 60, @@ -81,12 +81,12 @@ "stage": { "type": "token", "required": true, - "description": "SSH diagnostic collection stage: reader join or stderr read" + "description": "Diagnostic collection stage of the ssh or wsl.exe process: reader join or stderr read" }, "error": { "type": "error", "required": true, - "description": "Stable I/O or thread category explaining incomplete SSH connection diagnostic evidence" + "description": "Stable I/O or thread category explaining incomplete ssh or wsl.exe diagnostic evidence" } }, "rate": 60, @@ -176,7 +176,7 @@ "transport": { "type": "token", "required": true, - "description": "How the client reached the server: ssh, command (any spawned transport chain) or streams (caller-supplied pipes)" + "description": "How the client reached the server: ssh, wsl (a local WSL distribution through wsl.exe), command (any spawned transport chain) or streams (caller-supplied pipes)" }, "outcome": { "type": "token",