Skip to content

Commit eeebb58

Browse files
authored
fix(remote): WSL 连接失败读 wsl.exe 的标准输出,找不到发行版报 unreachable,中文消息也能识别 (Refs 1lck/Lithe-IDEA#2231) (#169)
wsl.exe 把自己的失败写在标准输出上,标准错误为空(发行版启动后才会在标准错误加一行)。 探测读到流结束时 LaunchError::NoShell 丢掉了这些内容,classify_wsl 只看标准错误, 所以未安装的发行版报 failed,诊断只剩退出码。 - LaunchError::NoShell 带上流结束前读到的行(output),日志分类和错误文字不含它们 - wsl::failure_text 先读标准输出、再读标准错误;classify_wsl 用它分类和生成诊断 - wsl::output_text 识别以非 ASCII 字符开头的 UTF-16LE(如中文消息) - 假 wsl.exe 的测试改为写标准输出,补中文、UTF-8 和找不到用户的情况 - 契约写明诊断来自哪个流
1 parent 18feb4a commit eeebb58

7 files changed

Lines changed: 152 additions & 39 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6154,8 +6154,10 @@ distribution's default user when absent). Core then runs
61546154
`wsl.exe` needs and setting `WSL_UTF8=1`; the probe, the checked upload and
61556155
the stages are the same. Nothing is relayed through `remote.authRespond`,
61566156
because `wsl.exe` asks no questions. An unknown distribution is
6157-
`unreachable`; other failures are `failed` with `wsl.exe`'s message in
6158-
`diagnostics`, decoded from UTF-16 when it prints that. Trust decisions name
6157+
`unreachable`; other failures, such as an unknown user, are `failed` with
6158+
`wsl.exe`'s message in `diagnostics`: what it printed on standard output,
6159+
where it reports its own failures, then standard error, decoded from UTF-16
6160+
when it prints that. Trust decisions name
61596161
the distribution and the account (`{ wsl: { distribution, user } }` as the
61606162
first and only hop).
61616163

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ impl ConnectionLog {
203203
/// probe is left to the caller, which knows from the SSH process whether
204204
/// authentication, the host key or the network failed.
205205
pub(crate) fn launch_failed(&self, stage: &'static str, error: &LaunchError) {
206-
if stage == "probe" && matches!(error, LaunchError::NoShell) {
206+
if stage == "probe" && matches!(error, LaunchError::NoShell { .. }) {
207207
return;
208208
}
209209
let domain = match error {

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

Lines changed: 44 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,14 @@ impl Verification {
250250
pub enum LaunchError {
251251
/// The stream ended before the shell answered, usually because the
252252
/// connection or authentication failed.
253-
NoShell,
253+
NoShell {
254+
/// The lines the stream carried before it ended, each with its
255+
/// newline (a last line without one gains it), at most the probe's
256+
/// bound on output before the server; empty when it ended after the
257+
/// probe. `wsl.exe` prints its own failures there, not on standard
258+
/// error.
259+
output: Vec<u8>,
260+
},
254261
/// The caller has no artifact for the reported platform.
255262
NoArtifact(Box<ProbeReport>),
256263
/// An install directory on the host is not private to the remote user,
@@ -273,7 +280,7 @@ pub enum LaunchError {
273280
impl fmt::Display for LaunchError {
274281
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
275282
match self {
276-
Self::NoShell => formatter.write_str("the remote shell did not start"),
283+
Self::NoShell { .. } => formatter.write_str("the remote shell did not start"),
277284
Self::NoArtifact(report) => write!(
278285
formatter,
279286
"no remote server is available for {} {}",
@@ -312,7 +319,7 @@ impl LaunchError {
312319
/// Stable category for logs. It never contains remote output or paths.
313320
pub fn failure_category(&self) -> String {
314321
match self {
315-
Self::NoShell => "no-shell".into(),
322+
Self::NoShell { .. } => "no-shell".into(),
316323
Self::NoArtifact(_) => "no-artifact".into(),
317324
Self::UnsafeInstall { reason, .. } => format!("unsafe-{}", reason.as_str()),
318325
Self::InstallFailed(step) => format!("install-{}", step.as_str()),
@@ -373,8 +380,13 @@ fn probe(
373380
) -> Result<ProbeReport, LaunchError> {
374381
let mut probe_output = Vec::new();
375382
loop {
376-
let line = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))?
377-
.ok_or(LaunchError::NoShell)?;
383+
// `read_line` drops only the newline, so the lines and their
384+
// newlines are the bytes as they arrived, UTF-16 included.
385+
let Some(line) = read_line(output, NOISE_LIMIT.saturating_sub(probe_output.len()))? else {
386+
return Err(LaunchError::NoShell {
387+
output: probe_output,
388+
});
389+
};
378390
if probe_output.is_empty() {
379391
stage(Stage::Authenticated);
380392
}
@@ -384,7 +396,7 @@ fn probe(
384396
break;
385397
}
386398
}
387-
parse_probe(&probe_output).ok_or(LaunchError::NoShell)
399+
parse_probe(&probe_output).ok_or(LaunchError::NoShell { output: Vec::new() })
388400
}
389401

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

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

@@ -585,6 +598,30 @@ mod tests {
585598
}
586599
}
587600

601+
// `wsl.exe` prints why it gave up on the stream the probe reads, in
602+
// UTF-16 unless `WSL_UTF8` is set; the failure keeps those lines so the
603+
// caller can read them, and its text shows none. Splitting UTF-16 at its
604+
// newline bytes loses nothing: only the last line gains a newline byte,
605+
// which completes no code unit.
606+
#[test]
607+
fn a_stream_that_ends_before_the_probe_keeps_what_it_carried() {
608+
let text =
609+
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
610+
let message: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
611+
let error = probe(&mut message.as_slice(), &mut |_| {}).unwrap_err();
612+
let LaunchError::NoShell { output } = &error else {
613+
panic!("{error:?}");
614+
};
615+
assert_eq!(output[..message.len()], message[..]);
616+
assert_eq!(crate::client::wsl::output_text(output), text);
617+
let error = probe(&mut text.as_bytes(), &mut |_| {}).unwrap_err();
618+
assert!(matches!(&error, LaunchError::NoShell { output } if output == text.as_bytes()));
619+
assert_eq!(error.to_string(), "the remote shell did not start");
620+
assert_eq!(error.failure_category(), "no-shell");
621+
let error = probe(&mut io::empty(), &mut |_| {}).unwrap_err();
622+
assert!(matches!(error, LaunchError::NoShell { output } if output.is_empty()));
623+
}
624+
588625
// Categories reach the log, so none carries remote output or a path.
589626
#[test]
590627
fn failure_categories_carry_no_remote_text() {

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

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,13 +117,20 @@ pub fn parse_distributions(output: &[u8]) -> Vec<String> {
117117
}
118118

119119
/// What `wsl.exe` itself printed, as text: UTF-16LE when it starts with that
120-
/// byte order mark or its second byte is NUL, which no UTF-8 text has, and
121-
/// UTF-8 otherwise. Malformed sequences become replacement characters, which
122-
/// no distribution name has.
120+
/// byte order mark or its second byte is NUL, which no UTF-8 text has, or
121+
/// when it is not UTF-8 and has a NUL at an odd offset, as UTF-16LE text
122+
/// that opens with a character outside ASCII, such as a message in Chinese,
123+
/// has at its line ends; UTF-8 otherwise. Malformed sequences become
124+
/// replacement characters, which no distribution name has.
123125
pub fn output_text(output: &[u8]) -> String {
124126
let utf16 = match output {
125127
[0xff, 0xfe, rest @ ..] => Some(rest),
126128
[_, 0, ..] => Some(output),
129+
_ if std::str::from_utf8(output).is_err()
130+
&& output.iter().skip(1).step_by(2).any(|byte| *byte == 0) =>
131+
{
132+
Some(output)
133+
}
127134
_ => None,
128135
};
129136
match utf16 {
@@ -140,6 +147,21 @@ pub fn output_text(output: &[u8]) -> String {
140147
}
141148
}
142149

150+
/// What `wsl.exe` printed when it gave up before its command started, as
151+
/// text. It reports its own failures, with a stable error code such as
152+
/// `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`, on standard output; a distribution
153+
/// that started may add a line on standard error. Standard output comes
154+
/// first, each part read as [`output_text`] reads it and blank parts left
155+
/// out.
156+
pub fn failure_text(stdout: &[u8], stderr: &[u8]) -> String {
157+
[stdout, stderr]
158+
.iter()
159+
.map(|part| output_text(part).trim().to_owned())
160+
.filter(|part| !part.is_empty())
161+
.collect::<Vec<_>>()
162+
.join("\n")
163+
}
164+
143165
#[cfg(test)]
144166
mod tests {
145167
use super::*;
@@ -169,6 +191,34 @@ mod tests {
169191
assert_eq!(output_text(&utf16(message, false)), message);
170192
assert_eq!(output_text(message.as_bytes()), message);
171193
assert_eq!(output_text(b"x"), "x");
194+
// A message in Chinese opens with a character whose second byte is
195+
// not NUL; its line ends and error code still are.
196+
let chinese =
197+
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
198+
assert_eq!(output_text(&utf16(chinese, false)), chinese);
199+
assert_eq!(output_text(chinese.as_bytes()), chinese);
200+
// UTF-8 with a stray NUL stays UTF-8.
201+
assert_eq!(output_text(b"Alpine1\0\r\n"), "Alpine1\0\r\n");
202+
}
203+
204+
// Real `wsl.exe` prints its failure on standard output; the line on
205+
// standard error comes from the distribution it started.
206+
#[test]
207+
fn failures_read_standard_output_then_standard_error() {
208+
let message = "User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\r\n";
209+
let relay =
210+
b"<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(dev) failed 17\n";
211+
assert_eq!(
212+
failure_text(&utf16(message, false), relay),
213+
"User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\n\
214+
<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(dev) failed 17"
215+
);
216+
assert_eq!(failure_text(message.as_bytes(), b""), message.trim());
217+
assert_eq!(
218+
failure_text(b"\r\n", relay),
219+
String::from_utf8_lossy(relay).trim()
220+
);
221+
assert_eq!(failure_text(b"", b""), "");
172222
}
173223

174224
#[test]

‎rust/crates/workspace/src/probe.rs‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -270,11 +270,13 @@ pub(crate) fn classify(exit: Option<ExitStatus>, stdout: &[u8], stderr: &[u8]) -
270270
}
271271
}
272272

273-
/// Interprets a `wsl.exe` that exited before the server started. `wsl.exe`
274-
/// names its failures with stable error codes, such as
275-
/// `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`, and may print them in UTF-16.
276-
pub(crate) fn classify_wsl(exit: Option<ExitStatus>, stderr: &[u8]) -> ProbeResult {
277-
let text = lithe_remote::client::wsl::output_text(stderr);
273+
/// Interprets a `wsl.exe` that exited before the server started, from what
274+
/// it printed on standard output and standard error (see
275+
/// [`lithe_remote::client::wsl::failure_text`]). A distribution that is not
276+
/// installed is `Wsl/Service/WSL_E_DISTRO_NOT_FOUND`; other failures, such
277+
/// as an unknown user, keep `wsl.exe`'s message in the diagnostics.
278+
pub(crate) fn classify_wsl(exit: Option<ExitStatus>, stdout: &[u8], stderr: &[u8]) -> ProbeResult {
279+
let text = lithe_remote::client::wsl::failure_text(stdout, stderr);
278280
let status = if text.contains("WSL_E_DISTRO_NOT_FOUND") {
279281
ProbeStatus::Unreachable
280282
} else {

‎rust/crates/workspace/src/probe/tests.rs‎

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -393,32 +393,54 @@ fn connecting_to_a_wsl_distribution_runs_the_launch_through_wsl() {
393393
assert!(!seen.contains_key("SSH_ASKPASS_REQUIRE"), "{names:?}");
394394
}
395395

396-
// `wsl.exe` prints its failures in UTF-16 with a stable error code; an
397-
// unknown distribution reads like an unknown host name.
396+
// `wsl.exe` prints its failures on standard output, in UTF-16 unless
397+
// `WSL_UTF8` is set, with a stable error code; an unknown distribution
398+
// reads like an unknown host name, whatever language the message is in.
398399
#[cfg(unix)]
399400
#[test]
400401
fn an_unknown_wsl_distribution_is_unreachable_with_readable_diagnostics() {
401-
let message = "There is no distribution with the supplied name.\r\n\
402+
let octal = |bytes: Vec<u8>| -> String {
403+
bytes
404+
.into_iter()
405+
.map(|byte| format!("\\{byte:03o}"))
406+
.collect()
407+
};
408+
let utf16 = |text: &str| octal(text.encode_utf16().flat_map(u16::to_le_bytes).collect());
409+
let english = "There is no distribution with the supplied name.\r\n\
402410
Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
403-
let escaped: String = message
404-
.encode_utf16()
405-
.flat_map(u16::to_le_bytes)
406-
.map(|byte| format!("\\{byte:03o}"))
407-
.collect();
411+
let chinese =
412+
"不存在具有所提供名称的分发。\r\n错误代码: Wsl/Service/WSL_E_DISTRO_NOT_FOUND\r\n";
413+
for (name, printed, message) in [
414+
("remote-connect-wsl-missing", utf16(english), english),
415+
("remote-connect-wsl-missing-zh", utf16(chinese), chinese),
416+
(
417+
"remote-connect-wsl-missing-utf8",
418+
octal(chinese.into()),
419+
chinese,
420+
),
421+
] {
422+
let wsl = FakeSsh::new(name, &format!("printf '{printed}'\nexit 1"));
423+
let request = wsl_request(json!({ "distribution": "Missing" }));
424+
let result = sessions::connect_with(request, Some(wsl.path())).unwrap();
425+
let value = serde_json::to_value(result).unwrap();
426+
assert_eq!(value["status"], "unreachable", "{name}");
427+
assert_eq!(value["session"], serde_json::Value::Null, "{name}");
428+
assert_eq!(value["diagnostics"], message.trim(), "{name}");
429+
}
430+
// An unknown user is another failure: `wsl.exe` names it on standard
431+
// output and the distribution adds why on standard error.
432+
let message = "User not found.\r\nError code: Wsl/WSL_E_USER_NOT_FOUND\r\n";
433+
let relay = "<3>WSL (342 - Relay) ERROR: CreateProcessParseCommon:1067: getpwnam(nobody-here) failed 17";
408434
let wsl = FakeSsh::new(
409-
"remote-connect-wsl-missing",
410-
&format!("printf '{escaped}' >&2\nexit 1"),
435+
"remote-connect-wsl-no-user",
436+
&format!("printf '{}'\necho '{relay}' >&2\nexit 1", utf16(message)),
411437
);
412-
let request = wsl_request(json!({ "distribution": "Missing" }));
413-
let result = sessions::connect_with(request, Some(wsl.path())).unwrap();
414-
let value = serde_json::to_value(result).unwrap();
415-
assert_eq!(value["status"], "unreachable");
438+
let request = wsl_request(json!({ "distribution": "Ubuntu", "user": "nobody-here" }));
439+
let value =
440+
serde_json::to_value(sessions::connect_with(request, Some(wsl.path())).unwrap()).unwrap();
441+
assert_eq!(value["status"], "failed");
416442
assert_eq!(value["session"], serde_json::Value::Null);
417-
assert_eq!(
418-
value["diagnostics"],
419-
"There is no distribution with the supplied name.\r\n\
420-
Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND"
421-
);
443+
assert_eq!(value["diagnostics"], format!("{}\n{relay}", message.trim()));
422444
// A silent failure still says which program gave up.
423445
let silent = FakeSsh::new("remote-connect-wsl-silent", "exit 3");
424446
let request = wsl_request(json!({ "distribution": "Ubuntu" }));

‎rust/crates/workspace/src/sessions.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -908,7 +908,7 @@ fn connect_logged(
908908
};
909909
let launched = match result {
910910
Ok(launched) => launched,
911-
Err(LaunchError::NoShell) => {
911+
Err(LaunchError::NoShell { output }) => {
912912
// The client prints why it gave up only as it exits.
913913
let status = wait_for_exit(&mut child, EXIT_GRACE);
914914
reap(&tree, &mut child);
@@ -917,7 +917,7 @@ fn connect_logged(
917917
(Client::Container, Some(container)) => {
918918
classify_container(status, &stderr, container.engine)
919919
}
920-
(Client::Wsl, _) => classify_wsl(status, &stderr),
920+
(Client::Wsl, _) => classify_wsl(status, &output, &stderr),
921921
_ => classify(status, &[], &stderr),
922922
};
923923
// The engine on the host printed why it gave up, after the SSH

0 commit comments

Comments
 (0)