Skip to content

Commit d765019

Browse files
committed
feat(remote): open a local WSL distribution as a remote workspace (Refs 1lck/Lithe-IDEA#2231)
remote.connect accepts wsl: { distribution, user? } instead of connection. Core then runs %SystemRoot%\System32\wsl.exe --distribution <d> [--user <u>] --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.
1 parent ae593eb commit d765019

17 files changed

Lines changed: 1248 additions & 128 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -802,9 +802,9 @@ or removing a command fails until the table changes in the same commit.
802802
| `git.authRespond` | Answer or cancel a live authentication challenge once |
803803
| `remote.probe` | Check that an SSH connection reaches a supported host |
804804
| `remote.authRespond` | Answer or cancel a prompt relayed by `remote.probe` or `remote.connect` once |
805-
| `remote.connect` | Open a connection, installing the shipped server when needed |
805+
| `remote.connect` | Open a connection over SSH or to a local WSL distribution, installing the shipped server when needed |
806806
| `remote.readDir` | List a directory over an open remote connection |
807-
| `remote.disconnect` | Close an open connection and its OpenSSH process tree |
807+
| `remote.disconnect` | Close an open connection and its OpenSSH or `wsl.exe` process tree |
808808
| `remote.closeAll` | Close every open connection; the host calls it at application exit |
809809
| `remote.readFile` | Read a file over an open remote connection |
810810
| `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.
827827
| `remote.effectiveSettings` | Tell what OpenSSH makes of a connection and where each value comes from |
828828
| `remote.sshConfigHosts` | List the Host aliases of the user's SSH configuration for an import |
829829
| `remote.mottyHosts` | List the SSH hosts saved in Motty for an import |
830+
| `remote.listWslDistributions` | List the WSL distributions installed on this Windows machine |
830831
| `git.historyRewritePreview` | Review undo, message edit, squash, or drop with complete messages, eligibility, and an immutable checkout expectation |
831832
| `git.remotes` | Return configured fetch remote names and URLs |
832833
| `git.tags` | Return tag names, tag object IDs, target IDs, dates, and annotations |
@@ -5903,6 +5904,19 @@ connection?, fields }`:
59035904
A relative directory is `invalid_request` and a damaged document
59045905
`parse_failed`. Nothing is written to Motty's files.
59055906

5907+
`remote.listWslDistributions` (no payload) returns `{ available,
5908+
distributions, diagnostics }`. On Windows Core runs `wsl.exe --list --quiet`
5909+
from `%SystemRoot%\System32` with `WSL_UTF8=1`, at most 15 seconds, and reads
5910+
its UTF-16 or UTF-8 output. `distributions` are the installed names in
5911+
`wsl.exe` order, at most 64, without Docker Desktop's `docker-desktop` and
5912+
`docker-desktop-data` and without names repeated in another case.
5913+
`available` is `false` on other systems, where nothing runs, and when
5914+
`wsl.exe` cannot start. When `wsl.exe` fails, for example because no
5915+
distribution is installed, `distributions` is empty and `diagnostics` holds
5916+
its redacted message for display; it is never logged. Cancellation and the
5917+
bound are `cancelled` and `timed_out`. Nothing is saved: the window lists
5918+
the distributions each time it opens.
5919+
59065920
#### Remote connections that stay open
59075921

59085922
`remote.connect` takes `{ connection, servers: [{ target, path, sha256 }],
@@ -5932,17 +5946,36 @@ host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName,
59325946
homeDirectory }` and is set only for `connected`. A host without a matching
59335947
build is `unsupportedPlatform` and nothing is uploaded.
59345948

5935-
A malformed connection, an unknown `target` or a `sha256` that is not 64
5936-
hexadecimal digits is `invalid_request`, before OpenSSH starts. A missing
5937-
`ssh` is `runtime_missing`. When the build for the host's platform cannot be
5949+
Instead of `connection`, the request may name a WSL distribution on this
5950+
Windows machine as `wsl: { distribution, user? }`, where `distribution` is a
5951+
name `remote.listWslDistributions` returned and `user` a Linux account (the
5952+
distribution's default user when absent). Core then runs
5953+
`wsl.exe --distribution <distribution> [--user <user>] --cd ~ --exec …` from
5954+
`%SystemRoot%\System32` in place of OpenSSH, keeping the Windows environment
5955+
`wsl.exe` needs and setting `WSL_UTF8=1`; the probe, the checked upload and
5956+
the stages are the same. Nothing is relayed through `remote.authRespond`,
5957+
because `wsl.exe` asks no questions. An unknown distribution is
5958+
`unreachable`; other failures are `failed` with `wsl.exe`'s message in
5959+
`diagnostics`, decoded from UTF-16 when it prints that. Trust decisions name
5960+
the distribution and the account (`{ wsl: { distribution, user } }` as the
5961+
first and only hop).
5962+
5963+
A request that names both `connection` and `wsl` is `invalid_request` with
5964+
`details` `{ field: "wsl", reason: "invalid" }`, and one that names neither
5965+
`{ field: "connection", reason: "required" }`. A malformed connection, a
5966+
distribution that is empty, longer than 64 bytes or not a WSL distribution
5967+
name, a user that is longer than 32 bytes or not a Linux login name, an
5968+
unknown `target` or a `sha256` that is not 64 hexadecimal digits is
5969+
`invalid_request`, before OpenSSH or `wsl.exe` starts. A missing `ssh` or
5970+
`wsl.exe` is `runtime_missing`. When the build for the host's platform cannot be
59385971
read or its SHA-256 differs, the attempt ends as `remote_server_invalid`
59395972
without sending anything; `details` says which of the two happened and, for a
59405973
mismatch, the SHA-256 Core computed, but never the path. Cancellation and the
59415974
five-minute bound are `cancelled` and `timed_out`.
59425975

59435976
Core keeps an open connection until `remote.disconnect` (`{ sessionId }`,
59445977
returning `{ closed }`) or until the host process exits; ending it terminates
5945-
the OpenSSH process tree. `remote.closeAll` (no payload, returning
5978+
the OpenSSH or `wsl.exe` process tree. `remote.closeAll` (no payload, returning
59465979
`{ closed }` with the number of connections) ends all of them; the host calls
59475980
it while quitting because exiting without it can leave the OpenSSH tree and
59485981
the remote server running. Requests over it take `sessionId`:

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1037,6 +1037,9 @@ pub enum RemoteCommand {
10371037
SshConfigHosts,
10381038
/// Lists the SSH hosts saved in Motty for an import (`remote.mottyHosts`).
10391039
MottyHosts,
1040+
/// Lists the WSL distributions installed on this Windows machine
1041+
/// (`remote.listWslDistributions`).
1042+
ListWslDistributions,
10401043
}
10411044

10421045
#[derive(Debug, Clone)]
@@ -1614,6 +1617,9 @@ impl CoreCommand {
16141617
"remote.effectiveSettings" => Some(Self::Remote(RemoteCommand::EffectiveSettings)),
16151618
"remote.sshConfigHosts" => Some(Self::Remote(RemoteCommand::SshConfigHosts)),
16161619
"remote.mottyHosts" => Some(Self::Remote(RemoteCommand::MottyHosts)),
1620+
"remote.listWslDistributions" => {
1621+
Some(Self::Remote(RemoteCommand::ListWslDistributions))
1622+
}
16171623
"git.historyRewritePreview" => Some(Self::Git(GitCommand::HistoryRewritePreview)),
16181624
"git.remotes" => Some(Self::Git(GitCommand::Remotes)),
16191625
"git.tags" => Some(Self::Git(GitCommand::Tags)),

‎rust/crates/core/src/runtime/dispatcher/remote.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,13 @@ pub(super) fn dispatch(command: RemoteCommand, id: Option<String>, payload: Valu
289289
id,
290290
json!({ "closed": lithe_workspace::sessions::close_all() }),
291291
),
292+
RemoteCommand::ListWslDistributions => match lithe_workspace::wsl::list() {
293+
Ok(listed) => CoreResponse::success(
294+
id,
295+
serde_json::to_value(listed).expect("WSL distributions should encode"),
296+
),
297+
Err(error) => CoreResponse::failure(id, error),
298+
},
292299
RemoteCommand::AuthRespond => {
293300
#[derive(serde::Deserialize)]
294301
#[serde(rename_all = "camelCase", deny_unknown_fields)]

‎rust/crates/core/src/tests/remote_sessions.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1306,7 +1306,31 @@ fn connection_window_helpers_answer_through_the_dispatcher() {
13061306
"a refused address is not echoed"
13071307
);
13081308

1309+
// Outside Windows there is no WSL, and nothing runs.
1310+
if !cfg!(windows) {
1311+
let distributions = call("remote.listWslDistributions", Value::Null);
1312+
assert_eq!(
1313+
distributions["data"],
1314+
json!({"available": false, "distributions": [], "diagnostics": ""}),
1315+
"{distributions}"
1316+
);
1317+
}
1318+
// A connection names SSH or WSL, not both, before anything starts.
1319+
let both = call(
1320+
"remote.connect",
1321+
json!({"connection": {"host": "devbox"}, "wsl": {"distribution": "Ubuntu"},
1322+
"servers": [], "serverVersion": "0.1.0"}),
1323+
);
1324+
assert_eq!(both["error"]["code"], "invalid_request", "{both}");
1325+
let details: Value = serde_json::from_str(both["error"]["details"].as_str().unwrap()).unwrap();
1326+
assert_eq!(details, json!({"field": "wsl", "reason": "invalid"}));
1327+
13091328
for (command, payload) in [
1329+
(
1330+
"remote.connect",
1331+
json!({"wsl": {"distribution": "Ubuntu", "program": "C:\\x.exe"},
1332+
"servers": [], "serverVersion": "0.1.0"}),
1333+
),
13101334
(
13111335
"remote.parseForwardAddress",
13121336
json!({"text": "3000", "extra": 1}),

‎rust/crates/diagnostics/src/catalog_generated.rs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,7 +1309,7 @@ pub static EVENTS: &[EventMetadata] = &[
13091309
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 },
13101310
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 },
13111311
FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None },
1312-
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 },
1312+
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 },
13131313
],
13141314
span: Some(SpanPhase::Failed),
13151315
rate: 60,
@@ -1328,7 +1328,7 @@ pub static EVENTS: &[EventMetadata] = &[
13281328
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 },
13291329
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 },
13301330
FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None },
1331-
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 },
1331+
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 },
13321332
],
13331333
span: Some(SpanPhase::Finished),
13341334
rate: 60,
@@ -1346,7 +1346,7 @@ pub static EVENTS: &[EventMetadata] = &[
13461346
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 },
13471347
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 },
13481348
FieldMetadata { name: "stage", field_type: FieldType::Token, required: false, description: "Connection step that failed: probe, artifact, deploy, handshake, authentication, network or connect", reason: None },
1349-
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 },
1349+
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 },
13501350
],
13511351
span: Some(SpanPhase::Started),
13521352
rate: 60,
@@ -1488,8 +1488,8 @@ pub static EVENTS: &[EventMetadata] = &[
14881488
level: LogLevel::Warn,
14891489
message: "Remote session cleanup failed",
14901490
fields: &[
1491-
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable native, thread, or remote category from ending an owned SSH connection", reason: None },
1492-
FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "SSH connection cleanup stage, e.g. shutdown, tree-kill, wait, or closer", reason: None },
1491+
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 },
1492+
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 },
14931493
],
14941494
span: None,
14951495
rate: 60,
@@ -1501,8 +1501,8 @@ pub static EVENTS: &[EventMetadata] = &[
15011501
level: LogLevel::Warn,
15021502
message: "Remote session diagnostic reader failed",
15031503
fields: &[
1504-
FieldMetadata { name: "error", field_type: FieldType::Error, required: true, description: "Stable I/O or thread category explaining incomplete SSH connection diagnostic evidence", reason: None },
1505-
FieldMetadata { name: "stage", field_type: FieldType::Token, required: true, description: "SSH diagnostic collection stage: reader join or stderr read", reason: None },
1504+
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 },
1505+
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 },
15061506
],
15071507
span: None,
15081508
rate: 60,

‎rust/crates/remote/src/client/connection_log.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ const RELEASED: u8 = 3;
6969
pub enum ConnectionKind {
7070
/// An SSH connection owned by the caller.
7171
Ssh,
72+
/// A WSL distribution started through `wsl.exe`, owned by the caller.
73+
Wsl,
7274
/// A transport chain [`crate::client::RemoteSession::connect`] spawns.
7375
Command,
7476
/// Streams the caller supplies to
@@ -80,6 +82,7 @@ impl ConnectionKind {
8082
fn as_str(self) -> &'static str {
8183
match self {
8284
Self::Ssh => "ssh",
85+
Self::Wsl => "wsl",
8386
Self::Command => "command",
8487
Self::Streams => "streams",
8588
}

‎rust/crates/remote/src/client/connections.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ pub enum Reason {
204204
}
205205

206206
impl ConnectionError {
207-
fn at(field: &'static str, reason: Reason) -> Self {
207+
pub(crate) fn at(field: &'static str, reason: Reason) -> Self {
208208
Self { field, reason }
209209
}
210210
}

‎rust/crates/remote/src/client/mod.rs‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
//!
33
//! - [`connections`] keeps the SSH connections the user saved and turns each
44
//! into an SSH hop with allowlisted options only.
5-
//! - [`transport`] turns a chain of hops (SSH, container exec) into the local
6-
//! command line that runs a program at the end of the chain.
5+
//! - [`transport`] turns a chain of hops (SSH, WSL, container exec) into the
6+
//! local command line that runs a program at the end of the chain.
7+
//! - [`wsl`] turns a WSL distribution into the first hop and lists the
8+
//! installed distributions.
79
//! - [`bootstrap`] probes the platform at the end of the chain and describes
810
//! the local server builds that can run there.
911
//! - [`launch`] probes, installs and starts the server over one connection,
@@ -50,6 +52,7 @@ pub mod session;
5052
pub mod ssh_config;
5153
pub mod transport;
5254
pub mod trust;
55+
pub mod wsl;
5356

5457
pub use api::{SpawnSpec, TerminalSpec, WriteOptions};
5558
pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget};
@@ -58,4 +61,7 @@ pub use forward::PortForward;
5861
pub use forward_address::{AddressError, ForwardAddress};
5962
pub use forward_set::{ForwardError, ForwardInfo, ForwardSet, ForwardSpec, TargetField};
6063
pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode};
61-
pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError};
64+
pub use transport::{
65+
ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError, WslHop,
66+
};
67+
pub use wsl::WslConnection;

0 commit comments

Comments
 (0)