diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index b28ab211..29e1c9c2 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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). diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index 453f7cd0..52a5174a 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -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 { diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 05041a87..301eb43b 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -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, + }, /// The caller has no artifact for the reported platform. NoArtifact(Box), /// An install directory on the host is not private to the remote user, @@ -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 {} {}", @@ -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()), @@ -373,8 +380,13 @@ fn probe( ) -> Result { 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); } @@ -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 @@ -453,7 +465,8 @@ fn deploy( /// Reads one answer line of the script. fn answer(output: &mut impl Read) -> Result { - 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()) } @@ -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 = 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() { diff --git a/rust/crates/remote/src/client/wsl.rs b/rust/crates/remote/src/client/wsl.rs index 31c7acd4..71b68b05 100644 --- a/rust/crates/remote/src/client/wsl.rs +++ b/rust/crates/remote/src/client/wsl.rs @@ -117,13 +117,20 @@ pub fn parse_distributions(output: &[u8]) -> Vec { } /// 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 { @@ -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::>() + .join("\n") +} + #[cfg(test)] mod tests { use super::*; @@ -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] diff --git a/rust/crates/workspace/src/probe.rs b/rust/crates/workspace/src/probe.rs index 8e37f1d1..2f1dd756 100644 --- a/rust/crates/workspace/src/probe.rs +++ b/rust/crates/workspace/src/probe.rs @@ -270,11 +270,13 @@ pub(crate) fn classify(exit: Option, 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, 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, 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 { diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index e47d1934..5b631b7a 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -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| -> 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" })); diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 7cf763c3..75cbf583 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -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); @@ -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