Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6154,8 +6154,10 @@ distribution's default user when absent). Core then runs
`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
`unreachable`; other failures, such as an unknown user, are `failed` with
`wsl.exe`'s message in `diagnostics`: what it printed on standard output,
where it reports its own failures, then standard error, 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).

Expand Down
2 changes: 1 addition & 1 deletion rust/crates/remote/src/client/connection_log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ impl ConnectionLog {
/// probe is left to the caller, which knows from the SSH process whether
/// authentication, the host key or the network failed.
pub(crate) fn launch_failed(&self, stage: &'static str, error: &LaunchError) {
if stage == "probe" && matches!(error, LaunchError::NoShell) {
if stage == "probe" && matches!(error, LaunchError::NoShell { .. }) {
return;
}
let domain = match error {
Expand Down
51 changes: 44 additions & 7 deletions rust/crates/remote/src/client/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,14 @@ impl Verification {
pub enum LaunchError {
/// The stream ended before the shell answered, usually because the
/// connection or authentication failed.
NoShell,
NoShell {
/// The lines the stream carried before it ended, each with its
/// newline (a last line without one gains it), at most the probe's
/// bound on output before the server; empty when it ended after the
/// probe. `wsl.exe` prints its own failures there, not on standard
/// error.
output: Vec<u8>,
},
/// The caller has no artifact for the reported platform.
NoArtifact(Box<ProbeReport>),
/// An install directory on the host is not private to the remote user,
Expand All @@ -273,7 +280,7 @@ pub enum LaunchError {
impl fmt::Display for LaunchError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoShell => formatter.write_str("the remote shell did not start"),
Self::NoShell { .. } => formatter.write_str("the remote shell did not start"),
Self::NoArtifact(report) => write!(
formatter,
"no remote server is available for {} {}",
Expand Down Expand Up @@ -312,7 +319,7 @@ impl LaunchError {
/// Stable category for logs. It never contains remote output or paths.
pub fn failure_category(&self) -> String {
match self {
Self::NoShell => "no-shell".into(),
Self::NoShell { .. } => "no-shell".into(),
Self::NoArtifact(_) => "no-artifact".into(),
Self::UnsafeInstall { reason, .. } => format!("unsafe-{}", reason.as_str()),
Self::InstallFailed(step) => format!("install-{}", step.as_str()),
Expand Down Expand Up @@ -373,8 +380,13 @@ fn probe(
) -> Result<ProbeReport, LaunchError> {
let mut probe_output = Vec::new();
loop {
let line = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))?
.ok_or(LaunchError::NoShell)?;
// `read_line` drops only the newline, so the lines and their
// newlines are the bytes as they arrived, UTF-16 included.
let Some(line) = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))? else {
return Err(LaunchError::NoShell {
output: probe_output,
});
};
if probe_output.is_empty() {
stage(Stage::Authenticated);
}
Expand All @@ -384,7 +396,7 @@ fn probe(
break;
}
}
parse_probe(&probe_output).ok_or(LaunchError::NoShell)
parse_probe(&probe_output).ok_or(LaunchError::NoShell { output: Vec::new() })
}

/// Checks the version, the only field the caller chose freely, and returns
Expand Down Expand Up @@ -453,7 +465,8 @@ fn deploy(

/// Reads one answer line of the script.
fn answer(output: &mut impl Read) -> Result<String, LaunchError> {
let line = read_line(output, NOISE_LIMIT)?.ok_or(LaunchError::NoShell)?;
let line =
read_line(output, NOISE_LIMIT)?.ok_or(LaunchError::NoShell { output: Vec::new() })?;
Ok(String::from_utf8_lossy(&line).trim_end().to_owned())
}

Expand Down Expand Up @@ -585,6 +598,30 @@ mod tests {
}
}

// `wsl.exe` prints why it gave up on the stream the probe reads, in
// UTF-16 unless `WSL_UTF8` is set; the failure keeps those lines so the
// caller can read them, and its text shows none. Splitting UTF-16 at its
// newline bytes loses nothing: only the last line gains a newline byte,
// which completes no code unit.
#[test]
fn a_stream_that_ends_before_the_probe_keeps_what_it_carried() {
let text =
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
let message: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
let error = probe(&mut message.as_slice(), &mut |_| {}).unwrap_err();
let LaunchError::NoShell { output } = &error else {
panic!("{error:?}");
};
assert_eq!(output[..message.len()], message[..]);
assert_eq!(crate::client::wsl::output_text(output), text);
let error = probe(&mut text.as_bytes(), &mut |_| {}).unwrap_err();
assert!(matches!(&error, LaunchError::NoShell { output } if output == text.as_bytes()));
assert_eq!(error.to_string(), "the remote shell did not start");
assert_eq!(error.failure_category(), "no-shell");
let error = probe(&mut io::empty(), &mut |_| {}).unwrap_err();
assert!(matches!(error, LaunchError::NoShell { output } if output.is_empty()));
}

// Categories reach the log, so none carries remote output or a path.
#[test]
fn failure_categories_carry_no_remote_text() {
Expand Down
56 changes: 53 additions & 3 deletions rust/crates/remote/src/client/wsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,20 @@ pub fn parse_distributions(output: &[u8]) -> Vec<String> {
}

/// 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.
/// byte order mark or its second byte is NUL, which no UTF-8 text has, or
/// when it is not UTF-8 and has a NUL at an odd offset, as UTF-16LE text
/// that opens with a character outside ASCII, such as a message in Chinese,
/// has at its line ends; 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),
_ if std::str::from_utf8(output).is_err()
&& output.iter().skip(1).step_by(2).any(|byte| *byte == 0) =>
{
Some(output)
}
_ => None,
};
match utf16 {
Expand All @@ -140,6 +147,21 @@ pub fn output_text(output: &[u8]) -> String {
}
}

/// What `wsl.exe` printed when it gave up before its command started, as
/// text. It reports its own failures, with a stable error code such as
/// `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`, on standard output; a distribution
/// that started may add a line on standard error. Standard output comes
/// first, each part read as [`output_text`] reads it and blank parts left
/// out.
pub fn failure_text(stdout: &[u8], stderr: &[u8]) -> String {
[stdout, stderr]
.iter()
.map(|part| output_text(part).trim().to_owned())
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join("\n")
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -169,6 +191,34 @@ mod tests {
assert_eq!(output_text(&utf16(message, false)), message);
assert_eq!(output_text(message.as_bytes()), message);
assert_eq!(output_text(b"x"), "x");
// A message in Chinese opens with a character whose second byte is
// not NUL; its line ends and error code still are.
let chinese =
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
assert_eq!(output_text(&utf16(chinese, false)), chinese);
assert_eq!(output_text(chinese.as_bytes()), chinese);
// UTF-8 with a stray NUL stays UTF-8.
assert_eq!(output_text(b"Alpine1\0\r\n"), "Alpine1\0\r\n");
}

// Real `wsl.exe` prints its failure on standard output; the line on
// standard error comes from the distribution it started.
#[test]
fn failures_read_standard_output_then_standard_error() {
let message = "User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\r\n";
let relay =
b"<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(dev) failed 17\n";
assert_eq!(
failure_text(&utf16(message, false), relay),
"User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\n\
<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(dev) failed 17"
);
assert_eq!(failure_text(message.as_bytes(), b""), message.trim());
assert_eq!(
failure_text(b"\r\n", relay),
String::from_utf8_lossy(relay).trim()
);
assert_eq!(failure_text(b"", b""), "");
}

#[test]
Expand Down
12 changes: 7 additions & 5 deletions rust/crates/workspace/src/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,11 +270,13 @@ pub(crate) fn classify(exit: Option<ExitStatus>, stdout: &[u8], stderr: &[u8]) -
}
}

/// 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<ExitStatus>, stderr: &[u8]) -> ProbeResult {
let text = lithe_remote::client::wsl::output_text(stderr);
/// Interprets a `wsl.exe` that exited before the server started, from what
/// it printed on standard output and standard error (see
/// [`lithe_remote::client::wsl::failure_text`]). A distribution that is not
/// installed is `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`; other failures, such
/// as an unknown user, keep `wsl.exe`'s message in the diagnostics.
pub(crate) fn classify_wsl(exit: Option<ExitStatus>, stdout: &[u8], stderr: &[u8]) -> ProbeResult {
let text = lithe_remote::client::wsl::failure_text(stdout, stderr);
let status = if text.contains("WSL_E_DISTRO_NOT_FOUND") {
ProbeStatus::Unreachable
} else {
Expand Down
60 changes: 41 additions & 19 deletions rust/crates/workspace/src/probe/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,32 +393,54 @@ fn connecting_to_a_wsl_distribution_runs_the_launch_through_wsl() {
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.
// `wsl.exe` prints its failures on standard output, in UTF-16 unless
// `WSL_UTF8` is set, with a stable error code; an unknown distribution
// reads like an unknown host name, whatever language the message is in.
#[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\
let octal = |bytes: Vec<u8>| -> String {
bytes
.into_iter()
.map(|byte| format!("\\{byte:03o}"))
.collect()
};
let utf16 = |text: &str| octal(text.encode_utf16().flat_map(u16::to_le_bytes).collect());
let english = "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 chinese =
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
for (name, printed, message) in [
("remote-connect-wsl-missing", utf16(english), english),
("remote-connect-wsl-missing-zh", utf16(chinese), chinese),
(
"remote-connect-wsl-missing-utf8",
octal(chinese.into()),
chinese,
),
] {
let wsl = FakeSsh::new(name, &format!("printf '{printed}'\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", "{name}");
assert_eq!(value["session"], serde_json::Value::Null, "{name}");
assert_eq!(value["diagnostics"], message.trim(), "{name}");
}
// An unknown user is another failure: `wsl.exe` names it on standard
// output and the distribution adds why on standard error.
let message = "User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\r\n";
let relay = "<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(nobody-here) failed 17";
let wsl = FakeSsh::new(
"remote-connect-wsl-missing",
&format!("printf '{escaped}' >&2\nexit 1"),
"remote-connect-wsl-no-user",
&format!("printf '{}'\necho '{relay}' >&2\nexit 1", utf16(message)),
);
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");
let request = wsl_request(json!({ "distribution": "Ubuntu", "user": "nobody-here" }));
let value =
serde_json::to_value(sessions::connect_with(request, Some(wsl.path())).unwrap()).unwrap();
assert_eq!(value["status"], "failed");
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"
);
assert_eq!(value["diagnostics"], format!("{}\n{relay}", message.trim()));
// 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" }));
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/workspace/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@ fn connect_logged(
};
let launched = match result {
Ok(launched) => launched,
Err(LaunchError::NoShell) => {
Err(LaunchError::NoShell { output }) => {
// The client prints why it gave up only as it exits.
let status = wait_for_exit(&mut child, EXIT_GRACE);
reap(&tree, &mut child);
Expand All @@ -917,7 +917,7 @@ fn connect_logged(
(Client::Container, Some(container)) => {
classify_container(status, &stderr, container.engine)
}
(Client::Wsl, _) => classify_wsl(status, &stderr),
(Client::Wsl, _) => classify_wsl(status, &output, &stderr),
_ => classify(status, &[], &stderr),
};
// The engine on the host printed why it gave up, after the SSH
Expand Down
Loading