mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
Release 3.0.2
This commit is contained in:
54 files changed
+4007
-374
No files matched your search
@@ -12,7 +12,9 @@ use tokio_util::sync::CancellationToken;
|
||||
use crate::auth::AuthWindowTheme;
|
||||
use crate::{auth::SamlAuthResult, credential::Credential, log_format::LogFormat, os_profile::OsProfile};
|
||||
|
||||
use super::{command_runner::run_controlled, command_traits::CommandExt};
|
||||
use super::{command_runner::run_observed, command_traits::CommandExt};
|
||||
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
@@ -44,6 +46,7 @@ pub struct SamlAuthLauncher<'a> {
|
||||
browser_listen: Option<IpAddr>,
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -76,9 +79,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
browser_listen: None,
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn auth_executable(mut self, auth_executable: Option<&'a str>) -> Self {
|
||||
self.auth_executable = auth_executable;
|
||||
self
|
||||
@@ -282,8 +291,16 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
.unwrap_or_else(binary_paths::gpauth);
|
||||
let auth_cmd = self.build_command(&program);
|
||||
|
||||
let command = auth_cmd.into_non_root()?.into_std();
|
||||
let cancellation = self.cancellation;
|
||||
let mut command = auth_cmd.into_non_root()?.into_std();
|
||||
let embedded = cfg!(feature = "webview-auth") && self.browser.is_none();
|
||||
#[cfg(feature = "webview-auth")]
|
||||
let embedded = embedded && !self.default_browser;
|
||||
let bundled = is_bundled_authenticator(&program, &binary_paths::gpauth());
|
||||
let can_recover = embedded && bundled && eligible(&command);
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
@@ -295,10 +312,19 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
run_controlled(command, &check, MAX_AUTH_RESULT_BYTES)
|
||||
let mut diagnostic = StderrDiagnostic::default();
|
||||
let output = run_observed(
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut std::io::stderr(),
|
||||
None,
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let output = match output {
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
@@ -306,14 +332,33 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
|
||||
Credential::try_from(auth_result)
|
||||
if self.cancellation.is_cancelled() {
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
decode_auth_output(output, can_recover && rendering_diagnostic)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bundled_authenticator(program: &Path, bundled: &Path) -> bool {
|
||||
match (program.canonicalize(), bundled.canonicalize()) {
|
||||
(Ok(program), Ok(bundled)) => program == bundled,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_auth_output(output: std::process::Output, rendering_failure: bool) -> anyhow::Result<Credential> {
|
||||
if !output.status.success() {
|
||||
if rendering_failure && is_crash_exit(output.status) {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
}
|
||||
bail!("Authenticator exited unsuccessfully: {}", output.status);
|
||||
}
|
||||
let Ok(auth_result) = serde_json::from_slice::<SamlAuthResult>(&output.stdout) else {
|
||||
bail!("Failed to parse auth data")
|
||||
};
|
||||
Credential::try_from(auth_result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -404,4 +449,76 @@ mod tests {
|
||||
|
||||
assert_eq!(launcher.browser_listen, Some(listen_ip));
|
||||
}
|
||||
#[test]
|
||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] {
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(71 << 8),
|
||||
stdout,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_malformed_auth_output_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let error = decode_auth_output(
|
||||
std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: b"partial".to_vec(),
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_none());
|
||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let executable = directory.path().join("auth-fixture");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
"#!/bin/sh\nprintf 'Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display\\n' >&2\nexit 71\n",
|
||||
)
|
||||
.unwrap();
|
||||
// The launcher drops root privileges in CI; its child must be able to
|
||||
// traverse the fixture directory and execute this non-sensitive script.
|
||||
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let error = SamlAuthLauncher::new("fixture.invalid")
|
||||
.auth_executable(executable.to_str())
|
||||
.dmabuf_disabled(true)
|
||||
.launch()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.downcast_ref::<RenderingCrash>().is_none());
|
||||
assert!(
|
||||
error.to_string().starts_with("Authenticator exited unsuccessfully:"),
|
||||
"unexpected launch error: {error:#}"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn service_provided_bundled_path_is_not_a_custom_authenticator() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let bundled = directory.path().join("gpauth");
|
||||
let custom = directory.path().join("custom");
|
||||
std::fs::write(&bundled, "bundled").unwrap();
|
||||
std::fs::write(&custom, "custom").unwrap();
|
||||
assert!(is_bundled_authenticator(&bundled, &bundled));
|
||||
assert!(!is_bundled_authenticator(&custom, &bundled));
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
}
|
||||
@@ -179,7 +179,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn root_owned_sticky_directories_protect_collectors_without_trusting_writable_files() {
|
||||
// CI runs Rust tests as root; an unprivileged process cannot create these fixtures.
|
||||
// A focused privileged CI check runs this test; the ordinary suite cannot create root-owned fixtures.
|
||||
if uzers::get_effective_uid() != 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::{
|
||||
io::{self, Read},
|
||||
io::{self, Read, Write},
|
||||
os::unix::process::CommandExt,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use nix::{
|
||||
@@ -14,71 +14,280 @@ use nix::{
|
||||
|
||||
use super::collection::CollectionControl;
|
||||
|
||||
/// Execute an already configured command. Environment, identity and executable
|
||||
/// trust belong to its caller. This worker owns the process group until reaped;
|
||||
/// its asynchronous caller must cancel and await it instead of dropping it.
|
||||
/// Owns and reaps the command's process group. Its async caller must cancel and await this worker.
|
||||
pub(crate) fn run_controlled(
|
||||
mut command: Command,
|
||||
command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: usize,
|
||||
) -> io::Result<Output> {
|
||||
control.check()?;
|
||||
let child = command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.process_group(0)
|
||||
.spawn()?;
|
||||
let mut child = ControlledChild(child);
|
||||
let mut stdout = child.0.stdout.take().expect("controlled stdout was piped");
|
||||
let flags = fcntl(&stdout, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
run(command, control, Some(output_limit), None, None).map(|observed| observed.output)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedOutput {
|
||||
pub output: Output,
|
||||
pub input_error: Option<io::Error>,
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin_frame: Option<&[u8]>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
run(
|
||||
command,
|
||||
control,
|
||||
output_limit,
|
||||
Some((observer, stderr_sink)),
|
||||
stdin_frame,
|
||||
)
|
||||
}
|
||||
|
||||
fn nonblocking(fd: &impl std::os::fd::AsFd) -> io::Result<()> {
|
||||
let flags = fcntl(fd, FcntlArg::F_GETFL).map_err(io::Error::from)?;
|
||||
fcntl(
|
||||
&stdout,
|
||||
fd,
|
||||
FcntlArg::F_SETFL(OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
mut observation: Option<(&mut dyn FnMut(&[u8]), &mut dyn Write)>,
|
||||
stdin_frame: Option<&[u8]>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
command
|
||||
.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
})
|
||||
.process_group(0);
|
||||
command.stdin(if stdin_frame.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::null()
|
||||
});
|
||||
if observation.is_some() {
|
||||
command.stderr(Stdio::piped());
|
||||
}
|
||||
let mut child = ControlledChild {
|
||||
process: command.spawn()?,
|
||||
stopped: false,
|
||||
};
|
||||
let mut stdout = child.process.stdout.take();
|
||||
if let Some(pipe) = &stdout {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut stderr = if observation.is_some() {
|
||||
child.process.stderr.take()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(pipe) = &stderr {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut input = child.process.stdin.take();
|
||||
if let Some(pipe) = &input {
|
||||
nonblocking(pipe)?;
|
||||
}
|
||||
let mut input_offset = 0;
|
||||
let mut input_error = None;
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
let mut eof = false;
|
||||
let mut stdout_eof = stdout.is_none();
|
||||
let mut stderr_eof = stderr.is_none();
|
||||
let mut status = None;
|
||||
let mut exited_at = None;
|
||||
loop {
|
||||
control.check()?;
|
||||
if !eof {
|
||||
match stdout.read(&mut buffer) {
|
||||
Ok(0) => eof = true,
|
||||
let mut progressed = false;
|
||||
if let (Some(frame), Some(pipe)) = (stdin_frame, &mut input) {
|
||||
if input_offset < frame.len() && input_error.is_none() {
|
||||
match pipe.write(&frame[input_offset..]) {
|
||||
Ok(0) => input_error = Some(io::Error::new(io::ErrorKind::WriteZero, "Credential input pipe closed")),
|
||||
Ok(length) => {
|
||||
input_offset += length;
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => input_error = Some(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !stdout_eof {
|
||||
match stdout.as_mut().unwrap().read(&mut buffer) {
|
||||
Ok(0) => stdout_eof = true,
|
||||
Ok(length) => {
|
||||
if length > output_limit.saturating_sub(output.len()) {
|
||||
if length > output_limit.unwrap().saturating_sub(output.len()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Command output exceeds its limit",
|
||||
));
|
||||
}
|
||||
output.extend_from_slice(&buffer[..length]);
|
||||
continue;
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if status.is_none() {
|
||||
status = child.0.try_wait()?;
|
||||
if !stderr_eof {
|
||||
match stderr.as_mut().unwrap().read(&mut buffer) {
|
||||
Ok(0) => stderr_eof = true,
|
||||
Ok(length) => {
|
||||
let (observer, sink) = observation.as_mut().unwrap();
|
||||
observer(&buffer[..length]);
|
||||
sink.write_all(&buffer[..length])?;
|
||||
progressed = true;
|
||||
}
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
if eof && let Some(status) = status {
|
||||
return Ok(Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
});
|
||||
if status.is_none()
|
||||
&& let Some(exit_status) = child.process.try_wait()?
|
||||
{
|
||||
status = Some(exit_status);
|
||||
exited_at = Some(Instant::now());
|
||||
child.stop_helpers();
|
||||
}
|
||||
if let Some(status) = status {
|
||||
if (stdout_eof && stderr_eof) || exited_at.unwrap().elapsed() >= Duration::from_millis(250) {
|
||||
if stdin_frame.is_some_and(|frame| input_offset < frame.len()) && input_error.is_none() {
|
||||
input_error = Some(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"Child exited before receiving its credential",
|
||||
));
|
||||
}
|
||||
return Ok(ObservedOutput {
|
||||
output: Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
input_error,
|
||||
});
|
||||
}
|
||||
}
|
||||
if !progressed {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
struct ControlledChild {
|
||||
process: Child,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
impl ControlledChild {
|
||||
fn stop_helpers(&mut self) {
|
||||
if !self.stopped {
|
||||
let _ = killpg(Pid::from_raw(self.process.id() as i32), Signal::SIGKILL);
|
||||
self.stopped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
// Reap the direct child and stop helpers retaining stdout after it exits.
|
||||
let _ = killpg(Pid::from_raw(self.0.id() as i32), Signal::SIGKILL);
|
||||
let _ = self.0.wait();
|
||||
self.stop_helpers();
|
||||
let _ = self.process.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn drains_both_pipes_and_reaps_helpers_that_hold_them_open() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "printf auth; printf diagnostic >&2; sleep 30 & exit 1"]);
|
||||
let mut seen = Vec::new();
|
||||
let mut sink = Vec::new();
|
||||
let start = Instant::now();
|
||||
let output = run_observed(
|
||||
command,
|
||||
&|| Ok(()),
|
||||
Some(1024),
|
||||
&mut |bytes| seen.extend_from_slice(bytes),
|
||||
&mut sink,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!output.output.status.success());
|
||||
assert_eq!(output.output.stdout, b"auth");
|
||||
assert_eq!(seen, b"diagnostic");
|
||||
assert_eq!(sink, seen);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
#[test]
|
||||
fn continuous_stderr_does_not_starve_cancellation_or_stdout() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "printf auth; while :; do printf 'diagnostic\\n' >&2; done"]);
|
||||
let start = Instant::now();
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = run_observed(command, &control, Some(1024), &mut |_| {}, &mut io::sink(), None).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retains_broken_input_pipe_for_failed_child_without_a_diagnostic() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "exec 0<&-; exit 2"]);
|
||||
let observed = run_observed(
|
||||
command,
|
||||
&|| Ok(()),
|
||||
None,
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
Some(&vec![0; 128 * 1024]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(observed.output.status.code(), Some(2));
|
||||
assert!(observed.input_error.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_interrupts_a_blocked_credential_write() {
|
||||
let mut command = Command::new("sh");
|
||||
command.args(["-c", "sleep 30"]);
|
||||
let start = Instant::now();
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(100) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let error = run_observed(
|
||||
command,
|
||||
&control,
|
||||
None,
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
Some(&vec![0; 128 * 1024]),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use super::{
|
||||
command_runner::run_observed,
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
process::{Command, ExitStatus},
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Monitor a credential-bearing desktop child; the owner cancels and joins this attempt.
|
||||
pub(super) async fn launch_desktop_child(
|
||||
name: &'static str,
|
||||
command: Command,
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let log_file = match envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
};
|
||||
let mut sink: Box<dyn std::io::Write + Send> = match log_file {
|
||||
Some(path) => Box::new(
|
||||
OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?,
|
||||
),
|
||||
None => Box::new(std::io::stderr()),
|
||||
};
|
||||
let frame = credential.encode_frame()?;
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let mut diagnostic = StderrDiagnostic::default();
|
||||
let observed = run_observed(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut sink,
|
||||
Some(&frame),
|
||||
)?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
}
|
||||
if let Some(error) = observed.input_error {
|
||||
return Err(error.into());
|
||||
}
|
||||
anyhow::ensure!(output.status.success(), "{name} exited with {}", output.status);
|
||||
Ok(output.status)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
@@ -6,12 +6,16 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::RecoveryState;
|
||||
use crate::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
|
||||
use anyhow::{Context, ensure};
|
||||
use common::binary_paths;
|
||||
use log::warn;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
|
||||
process::Command,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{CommandExt, gui_launcher::GuiLauncher};
|
||||
@@ -64,34 +68,96 @@ impl<'a> DesktopLauncher<'a> {
|
||||
.context("Service credential pipe is unavailable")?;
|
||||
let mut received_credential = false;
|
||||
let mut cancelled = false;
|
||||
let result = tokio::select! {
|
||||
_ = crate::utils::shutdown_signal() => { cancelled = true; Ok(()) },
|
||||
result = async {
|
||||
let mut minimized = self.minimized;
|
||||
loop {
|
||||
let credential = read_credential(&mut output).await?;
|
||||
let Some(credential) = credential else { return Ok(()); };
|
||||
received_credential = true;
|
||||
ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||
if let Some(path) = &self.log_file {
|
||||
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||
}
|
||||
let launcher = GuiLauncher::new(self.version, Arc::new(credential)).envs(envs).minimized(minimized);
|
||||
let mut unexpected = [0];
|
||||
tokio::select! {
|
||||
result = launcher.launch() => { result?; }
|
||||
status = service.wait() => { anyhow::bail!("The privileged service exited while the GUI was running: {}", status?); }
|
||||
result = output.read(&mut unexpected) => {
|
||||
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||
anyhow::bail!("The privileged service closed its credential channel");
|
||||
let cancellation = CancellationToken::new();
|
||||
let mut recovery = RecoveryState::default();
|
||||
let result = {
|
||||
let operation = async {
|
||||
let mut minimized = self.minimized;
|
||||
let mut expecting_renewal = false;
|
||||
let mut program = None;
|
||||
loop {
|
||||
let credential = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => return Ok(()),
|
||||
result = read_credential(&mut output) => result?,
|
||||
};
|
||||
let Some(credential) = credential else {
|
||||
ensure!(
|
||||
!expecting_renewal,
|
||||
"Service closed before issuing the recovery credential"
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
expecting_renewal = false;
|
||||
received_credential = true;
|
||||
ensure!(
|
||||
credential.product_version() == self.version,
|
||||
"Service product version mismatch"
|
||||
);
|
||||
let mut envs: HashMap<String, String> = std::env::vars().collect();
|
||||
if recovery.dmabuf_disabled() {
|
||||
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), "1".into());
|
||||
}
|
||||
if let Some(path) = &self.log_file {
|
||||
envs.insert("GP_LOG_FILE".into(), path.clone());
|
||||
}
|
||||
let launcher = GuiLauncher::new(self.version, Arc::new(credential))
|
||||
.envs(envs)
|
||||
.minimized(minimized);
|
||||
let mut unexpected = [0];
|
||||
// Program resolution may launch the WebKit download helper. Keep it under
|
||||
// the same cancellation, service ownership and recovery budget as gpgui.
|
||||
let attempt = async {
|
||||
if program.is_none() {
|
||||
program = Some(launcher.resolve_program(&cancellation).await?);
|
||||
}
|
||||
launcher.launch_program(program.as_ref().unwrap(), &cancellation).await
|
||||
};
|
||||
tokio::pin!(attempt);
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => { let _ = attempt.await; return Ok(()); }
|
||||
result = &mut attempt => result,
|
||||
status = service.wait() => {
|
||||
cancellation.cancel(); let _ = attempt.await;
|
||||
anyhow::bail!("The privileged service exited while the GUI was running: {}", status?);
|
||||
}
|
||||
result = output.read(&mut unexpected) => {
|
||||
cancellation.cancel(); let _ = attempt.await;
|
||||
ensure!(result? == 0, "Unexpected service credential data while the GUI is running");
|
||||
anyhow::bail!("The privileged service closed its credential channel");
|
||||
}
|
||||
};
|
||||
if cancellation.is_cancelled() {
|
||||
return Ok(());
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
Ok(_) => {
|
||||
input.write_all(&[DESKTOP_GUI_EXITED]).await?;
|
||||
minimized = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
input.write_all(&[0]).await?;
|
||||
minimized = false;
|
||||
}
|
||||
} => result,
|
||||
};
|
||||
tokio::pin!(operation);
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = crate::utils::shutdown_signal() => {
|
||||
cancelled = true;
|
||||
cancellation.cancel();
|
||||
operation.await
|
||||
},
|
||||
result = &mut operation => result,
|
||||
};
|
||||
result
|
||||
};
|
||||
let result = recovery.finish(result);
|
||||
// EOF lets the service revoke the credential and disconnect the VPN gracefully.
|
||||
drop(input);
|
||||
if cancelled && !received_credential {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::{collections::HashMap, path::PathBuf, process::Stdio};
|
||||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::service::transport::SessionCredential;
|
||||
|
||||
@@ -34,7 +34,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<()> {
|
||||
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let mut cmd = Command::new(&self.program);
|
||||
|
||||
if let Some(envs) = self.envs {
|
||||
@@ -53,23 +53,110 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", self.program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
info!("gpgui-helper exited with: {}", exit_status);
|
||||
|
||||
super::desktop_child::launch_desktop_child(
|
||||
"gpgui-helper",
|
||||
cmd.into_std(),
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::process::rendering_recovery::RenderingCrash;
|
||||
use std::{fs, os::unix::fs::PermissionsExt};
|
||||
|
||||
fn fixture(dir: &tempfile::TempDir, credential: &SessionCredential, body: &str) -> PathBuf {
|
||||
let path = dir.path().join("helper");
|
||||
let length = credential.encode_frame().unwrap().len();
|
||||
fs::write(
|
||||
&path,
|
||||
format!("#!/bin/sh\ndd bs=1 count={length} of=/dev/null 2>/dev/null || exit 1\n{body}\n"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn propagates_helper_failure_and_preserves_stderr_in_desktop_log() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let path = fixture(&dir, &credential, "printf 'download failed\\n' >&2; exit 23");
|
||||
let log = dir.path().join("desktop.log");
|
||||
fs::write(&log, "").unwrap();
|
||||
let envs = HashMap::from([("GP_LOG_FILE".into(), log.to_str().unwrap().into())]);
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path,
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
|
||||
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
|
||||
assert!(error.to_string().contains("23"));
|
||||
assert_eq!(fs::read_to_string(log).unwrap(), "download failed\n");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recognizes_helper_rendering_crash_and_respects_explicit_override() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let path = fixture(
|
||||
&dir,
|
||||
&credential,
|
||||
"printf '(gpgui-helper:42): Gdk-Message: 12:00:00: Error 71 (Protocol error) dispatching to Wayland display\\n' >&2; exit 71",
|
||||
);
|
||||
let mut envs = HashMap::from([("WAYLAND_DISPLAY".into(), "wayland-0".into())]);
|
||||
for override_value in [None, Some(""), Some("0"), Some("1")] {
|
||||
if let Some(value) = override_value {
|
||||
envs.insert("WEBKIT_DISABLE_DMABUF_RENDERER".into(), value.into());
|
||||
}
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path.clone(),
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
|
||||
let eligible =
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")) && override_value.is_none();
|
||||
assert_eq!(error.downcast_ref::<RenderingCrash>().is_some(), eligible, "{error:#}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_joins_helper_before_returning() {
|
||||
let dir = tempfile::TempDir::new().unwrap();
|
||||
let credential = SessionCredential::generate(uuid::Uuid::new_v4(), "test").unwrap();
|
||||
let pid_file = dir.path().join("pid");
|
||||
let body = format!("echo $$ > '{}'; exec sleep 30", pid_file.display());
|
||||
let path = fixture(&dir, &credential, &body);
|
||||
let envs = HashMap::new();
|
||||
let launcher = GuiHelperLauncher {
|
||||
program: path,
|
||||
envs: Some(&envs),
|
||||
credential: &credential,
|
||||
gui_version: None,
|
||||
};
|
||||
let cancellation = CancellationToken::new();
|
||||
let attempt = launcher.launch(&cancellation);
|
||||
tokio::pin!(attempt);
|
||||
tokio::select! {
|
||||
result = &mut attempt => panic!("helper exited early: {result:?}"),
|
||||
_ = async { while !pid_file.exists() { tokio::time::sleep(std::time::Duration::from_millis(10)).await; } } => {}
|
||||
}
|
||||
cancellation.cancel();
|
||||
assert!(attempt.await.is_err());
|
||||
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
|
||||
assert_eq!(
|
||||
nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None),
|
||||
Err(nix::errno::Errno::ESRCH)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::{Path, PathBuf},
|
||||
process::{ExitStatus, Stdio},
|
||||
process::ExitStatus,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use anyhow::bail;
|
||||
use common::binary_paths;
|
||||
use log::info;
|
||||
use tokio::{io::AsyncWriteExt, process::Command};
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport::SessionCredential};
|
||||
|
||||
@@ -50,20 +50,26 @@ impl<'a> GuiLauncher<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn launch(&self) -> anyhow::Result<ExitStatus> {
|
||||
pub(crate) async fn resolve_program(&self, cancellation: &CancellationToken) -> anyhow::Result<PathBuf> {
|
||||
anyhow::ensure!(
|
||||
uzers::get_effective_uid() != 0,
|
||||
"The desktop GUI must not be launched by root"
|
||||
);
|
||||
if let Some(program) = self.find_compatible_program().await {
|
||||
return self.launch_program(&program).await;
|
||||
if let Some(program) = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
|
||||
result = self.find_compatible_program() => result,
|
||||
} {
|
||||
return Ok(program);
|
||||
}
|
||||
|
||||
self.download_program().await?;
|
||||
|
||||
self.download_program(cancellation).await?;
|
||||
let program = binary_paths::gpgui_update_target();
|
||||
self.check_version(&program).await?;
|
||||
self.launch_program(&program).await
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
|
||||
result = self.check_version(&program) => result?,
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
async fn find_compatible_program(&self) -> Option<PathBuf> {
|
||||
@@ -80,50 +86,28 @@ impl<'a> GuiLauncher<'a> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn launch_program(&self, program: &Path) -> anyhow::Result<ExitStatus> {
|
||||
pub(crate) async fn launch_program(
|
||||
&self,
|
||||
program: &Path,
|
||||
cancellation: &CancellationToken,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let mut cmd = Command::new(program);
|
||||
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
|
||||
let log_file = match &self.envs {
|
||||
Some(envs) => envs.get("GP_LOG_FILE").map(PathBuf::from),
|
||||
None => std::env::var_os("GP_LOG_FILE").map(PathBuf::from),
|
||||
};
|
||||
if let Some(path) = log_file {
|
||||
let file = OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.with_context(|| format!("Failed to open GUI log file: {}", path.display()))?;
|
||||
cmd.stderr(Stdio::from(file));
|
||||
}
|
||||
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
}
|
||||
|
||||
info!("Launching gpgui");
|
||||
let child = cmd.kill_on_drop(true).stdin(Stdio::piped()).spawn();
|
||||
let mut child = match child {
|
||||
Ok(child) => child,
|
||||
Err(err) => bail!("Failed to spawn {}: {}", program.display(), err),
|
||||
};
|
||||
|
||||
let Some(mut stdin) = child.stdin.take() else {
|
||||
bail!("Failed to open stdin");
|
||||
};
|
||||
|
||||
let frame = self.credential.encode_frame()?;
|
||||
stdin.write_all(&frame).await?;
|
||||
|
||||
let exit_status = child.wait().await?;
|
||||
drop(stdin);
|
||||
|
||||
Ok(exit_status)
|
||||
super::desktop_child::launch_desktop_child(
|
||||
"gpgui",
|
||||
cmd.into_std(),
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn check_version(&self, program: &Path) -> anyhow::Result<()> {
|
||||
@@ -132,7 +116,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
cmd.env_clear();
|
||||
cmd.envs(envs);
|
||||
}
|
||||
cmd.arg("--version");
|
||||
cmd.kill_on_drop(true).arg("--version");
|
||||
let output = cmd.output().await?;
|
||||
if !output.status.success() {
|
||||
bail!("Version command exited with {}", output.status);
|
||||
@@ -153,13 +137,13 @@ impl<'a> GuiLauncher<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn download_program(&self) -> anyhow::Result<()> {
|
||||
async fn download_program(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
|
||||
let gui_helper = GuiHelperLauncher::new(&self.credential);
|
||||
|
||||
gui_helper
|
||||
.envs(self.envs.as_ref())
|
||||
.gui_version(Some(self.version))
|
||||
.launch()
|
||||
.launch(cancellation)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -218,14 +202,74 @@ mod tests {
|
||||
.unwrap();
|
||||
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert!(launcher.launch_program(&program).await.unwrap().success());
|
||||
assert!(
|
||||
launcher
|
||||
.launch_program(&program, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(
|
||||
launcher
|
||||
.launch_program(&program, &CancellationToken::new())
|
||||
.await
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(log_file).unwrap(),
|
||||
"[gpservice] started\n[gpgui] initialized\n[gpgui] initialized\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_stops_a_hung_version_probe_before_other_candidates() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let pid_file = dir.path().join("version.pid");
|
||||
let next_marker = dir.path().join("next-probe");
|
||||
let first = dir.path().join("hung");
|
||||
let second = dir.path().join("next");
|
||||
fs::write(
|
||||
&first,
|
||||
format!("#!/bin/sh\necho $$ > '{}'; exec sleep 30\n", pid_file.display()),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
&second,
|
||||
format!(
|
||||
"#!/bin/sh\ntouch '{}'; echo 'gpgui test-version'\n",
|
||||
next_marker.display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
for path in [&first, &second] {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let launcher = launcher(VERSION, vec![first, second]);
|
||||
let cancellation = CancellationToken::new();
|
||||
let attempt = launcher.resolve_program(&cancellation);
|
||||
tokio::pin!(attempt);
|
||||
tokio::select! {
|
||||
result = &mut attempt => panic!("version probe exited early: {result:?}"),
|
||||
ready = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while !pid_file.exists() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
}) => ready.unwrap(),
|
||||
}
|
||||
cancellation.cancel();
|
||||
assert!(attempt.await.unwrap_err().to_string().contains("cancelled"));
|
||||
assert!(!next_marker.exists());
|
||||
let pid: i32 = fs::read_to_string(pid_file).unwrap().trim().parse().unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None).is_ok() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prefers_the_first_compatible_program() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod command_runner;
|
||||
mod command_traits;
|
||||
mod desktop_child;
|
||||
mod desktop_session_env;
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
@@ -11,3 +12,5 @@ pub mod gui_launcher;
|
||||
pub mod users;
|
||||
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
@@ -0,0 +1,189 @@
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("WebKit Wayland rendering process exited with {status}")]
|
||||
pub struct RenderingCrash {
|
||||
pub status: ExitStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("Rendering recovery failed: {0:#}. Collect diagnostics for a bug report")]
|
||||
pub struct RecoveryFailed(#[source] anyhow::Error);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RecoveryState {
|
||||
first_failure: Option<String>,
|
||||
}
|
||||
|
||||
impl RecoveryState {
|
||||
pub fn dmabuf_disabled(&self) -> bool {
|
||||
self.first_failure.is_some()
|
||||
}
|
||||
|
||||
pub fn recover(&mut self, error: &anyhow::Error) -> bool {
|
||||
if self.first_failure.is_none() && error.downcast_ref::<RenderingCrash>().is_some() {
|
||||
self.first_failure = Some(error.to_string());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
|
||||
if error.downcast_ref::<crate::auth::AuthenticationCancelled>().is_some()
|
||||
|| error.downcast_ref::<RecoveryFailed>().is_some()
|
||||
{
|
||||
return error;
|
||||
}
|
||||
match &self.first_failure {
|
||||
Some(first) => RecoveryFailed(error.context(format!("First attempt: {first}"))).into(),
|
||||
None => error,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish<T>(&self, result: anyhow::Result<T>) -> anyhow::Result<T> {
|
||||
result.map_err(|error| self.terminal(error))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
!status.success() && !matches!(status.signal(), Some(1 | 2 | 9 | 15))
|
||||
}
|
||||
|
||||
pub fn eligible(command: &Command) -> bool {
|
||||
eligible_with_inheritance(command, true)
|
||||
}
|
||||
|
||||
pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bool {
|
||||
cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))
|
||||
&& effective_env(command, "WAYLAND_DISPLAY", inherits).is_some_and(|value| !value.is_empty())
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
}
|
||||
|
||||
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
|
||||
for (name, value) in command.get_envs() {
|
||||
if name == key {
|
||||
return value.map(ToOwned::to_owned);
|
||||
}
|
||||
}
|
||||
inherits.then(|| std::env::var_os(key)).flatten()
|
||||
}
|
||||
|
||||
/// Observes diagnostic lines without retaining arbitrary application output.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StderrDiagnostic {
|
||||
line: Vec<u8>,
|
||||
overflow: bool,
|
||||
matched: bool,
|
||||
}
|
||||
|
||||
impl StderrDiagnostic {
|
||||
pub(crate) fn push(&mut self, bytes: &[u8]) {
|
||||
for &byte in bytes {
|
||||
if byte == b'\n' {
|
||||
self.check_line();
|
||||
self.line.clear();
|
||||
self.overflow = false;
|
||||
} else if self.line.len() < 1024 {
|
||||
self.line.push(byte);
|
||||
} else {
|
||||
self.overflow = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_line(&mut self) {
|
||||
let line = self.line.as_slice();
|
||||
if !self.overflow
|
||||
&& (line.starts_with(b"Gdk-Message:")
|
||||
|| line.starts_with(b"(gpgui:")
|
||||
|| line.starts_with(b"(gpauth:")
|
||||
|| line.starts_with(b"(gpgui-helper:"))
|
||||
&& line.windows(b"Gdk-Message:".len()).any(|part| part == b"Gdk-Message:")
|
||||
&& line.strip_suffix(b"\r").unwrap_or(line).ends_with(DIAGNOSTIC)
|
||||
{
|
||||
self.matched = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn matched(&mut self) -> bool {
|
||||
self.check_line();
|
||||
self.matched
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(b"warning: Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display\n");
|
||||
assert!(!observer.matched());
|
||||
observer.push(b"Gdk-Message: 12:00:00: Error 71 (Protocol error) dispat");
|
||||
observer.push(b"ching to Wayland display\n");
|
||||
assert!(observer.matched());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_lines_do_not_grow_or_match() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(&vec![b'x'; 100_000]);
|
||||
assert_eq!(observer.line.len(), 1024);
|
||||
observer.push(DIAGNOSTIC);
|
||||
assert!(!observer.matched());
|
||||
}
|
||||
#[test]
|
||||
fn respects_explicit_overrides_and_x11_environment() {
|
||||
let mut command = Command::new("fixture");
|
||||
command.env_clear().env("WAYLAND_DISPLAY", "wayland-0");
|
||||
let platform = cfg!(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"));
|
||||
assert_eq!(eligible_with_inheritance(&command, false), platform);
|
||||
for value in ["", "0", "1"] {
|
||||
command.env(DMABUF, value);
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
command
|
||||
.env_remove(DMABUF)
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env("DISPLAY", ":0");
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let mut recovery = RecoveryState::default();
|
||||
let first = RenderingCrash {
|
||||
status: ExitStatus::from_raw(71 << 8),
|
||||
}
|
||||
.into();
|
||||
assert!(recovery.recover(&first));
|
||||
assert!(!recovery.recover(&first));
|
||||
assert!(
|
||||
recovery
|
||||
.terminal(crate::auth::AuthenticationCancelled.into())
|
||||
.downcast_ref::<crate::auth::AuthenticationCancelled>()
|
||||
.is_some()
|
||||
);
|
||||
let error = recovery.terminal(anyhow::anyhow!("second exit 72"));
|
||||
assert!(error.downcast_ref::<RecoveryFailed>().is_some());
|
||||
assert!(error.to_string().contains("71"));
|
||||
assert!(error.to_string().contains("second exit 72"));
|
||||
}
|
||||
#[test]
|
||||
fn explicit_termination_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
for signal in [1, 2, 9, 15] {
|
||||
assert!(!is_crash_exit(ExitStatus::from_raw(signal)));
|
||||
}
|
||||
assert!(is_crash_exit(ExitStatus::from_raw(6)));
|
||||
assert!(is_crash_exit(ExitStatus::from_raw(71 << 8)));
|
||||
assert!(!is_crash_exit(ExitStatus::from_raw(0)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user