mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
release: prepare GP Connect 3.5.0 with Windows support
This commit is contained in:
172 files changed
+9629
-1171
No files matched your search
@@ -17,10 +17,17 @@ use super::{
|
||||
command_traits::CommandExt,
|
||||
};
|
||||
|
||||
use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_crash_exit};
|
||||
use super::rendering_recovery::{
|
||||
AUTH_STDERR_PREFIX, GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible,
|
||||
is_crash_exit, is_gbm_diagnostic,
|
||||
};
|
||||
|
||||
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
|
||||
|
||||
#[cfg(windows)]
|
||||
/// The caller that receives foreground permission after browser authentication.
|
||||
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
|
||||
|
||||
pub struct SamlAuthLauncher<'a> {
|
||||
cancellation: CancellationToken,
|
||||
server: &'a str,
|
||||
@@ -49,6 +56,7 @@ pub struct SamlAuthLauncher<'a> {
|
||||
verbose: Option<&'a str>,
|
||||
log_format: LogFormat,
|
||||
dmabuf_disabled: bool,
|
||||
desktop_compatibility_graphics: bool,
|
||||
}
|
||||
|
||||
impl<'a> SamlAuthLauncher<'a> {
|
||||
@@ -81,9 +89,15 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
verbose: None,
|
||||
log_format: LogFormat::Text,
|
||||
dmabuf_disabled: false,
|
||||
desktop_compatibility_graphics: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn desktop_compatibility_graphics(mut self) -> Self {
|
||||
self.desktop_compatibility_graphics = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn dmabuf_disabled(mut self, disabled: bool) -> Self {
|
||||
self.dmabuf_disabled = disabled;
|
||||
self
|
||||
@@ -197,6 +211,8 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
/// argument that never gets appended.
|
||||
fn build_command(&self, program: &Path) -> Command {
|
||||
let mut auth_cmd = Command::new(program);
|
||||
#[cfg(windows)]
|
||||
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
|
||||
auth_cmd.arg(self.server);
|
||||
|
||||
if self.gateway {
|
||||
@@ -236,7 +252,7 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
{
|
||||
if self.browser.is_none() {
|
||||
if self.hidpi {
|
||||
auth_cmd.arg("--hidpi");
|
||||
}
|
||||
@@ -292,15 +308,34 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
if embedded && bundled && self.dmabuf_disabled {
|
||||
command.env("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||||
}
|
||||
let desktop_webview = embedded && bundled && self.desktop_compatibility_graphics;
|
||||
let can_use_shared_memory = desktop_webview && allows_shared_memory_override(&command, true);
|
||||
let use_shared_memory = can_use_shared_memory && crate::gui::compatibility_graphics_enabled();
|
||||
if use_shared_memory {
|
||||
command.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
let detect_gbm_failure = can_use_shared_memory && !use_shared_memory;
|
||||
let stdin = auth_stdin(self.browser);
|
||||
let cancellation = self.cancellation.clone();
|
||||
let output = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(feature = "logger")]
|
||||
let stderr = crate::logger::diagnostic_writer();
|
||||
#[cfg(not(feature = "logger"))]
|
||||
let stderr: Box<dyn std::io::Write + Send> = Box::new(std::io::stderr());
|
||||
let mut stderr = if desktop_webview {
|
||||
Box::new(std::io::LineWriter::new(AuthStderr(stderr)))
|
||||
} else {
|
||||
stderr
|
||||
};
|
||||
let gbm_failed = std::cell::Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Authentication cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -310,19 +345,31 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
command,
|
||||
&check,
|
||||
Some(MAX_AUTH_RESULT_BYTES),
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut std::io::stderr(),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(can_recover));
|
||||
},
|
||||
&mut stderr,
|
||||
stdin,
|
||||
)?;
|
||||
Ok::<_, std::io::Error>((output.output, diagnostic.matched()))
|
||||
);
|
||||
std::io::Write::flush(&mut stderr)?;
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let output = output?;
|
||||
Ok::<_, anyhow::Error>((output.output, diagnostic.matched()))
|
||||
})
|
||||
.await?;
|
||||
let (output, rendering_diagnostic) = match output {
|
||||
Ok(output) => output,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {
|
||||
Err(error)
|
||||
if error
|
||||
.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|error| error.kind() == std::io::ErrorKind::Interrupted) =>
|
||||
{
|
||||
return Err(crate::auth::AuthenticationCancelled.into());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
if self.cancellation.is_cancelled() {
|
||||
@@ -332,6 +379,26 @@ impl<'a> SamlAuthLauncher<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Attribute GBM failures to gpauth before forwarding them to the desktop supervisor.
|
||||
struct AuthStderr(Box<dyn std::io::Write + Send>);
|
||||
|
||||
impl std::io::Write for AuthStderr {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
for line in bytes.split_inclusive(|&byte| byte == b'\n') {
|
||||
if is_gbm_diagnostic(line) {
|
||||
self.0.write_all(&[AUTH_STDERR_PREFIX, line].concat())?;
|
||||
} else {
|
||||
self.0.write_all(line)?;
|
||||
}
|
||||
}
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.0.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// `gpauth --browser manual` reads the pasted `globalprotectcallback:` data from the user's terminal.
|
||||
fn auth_stdin(browser: Option<&str>) -> ChildInput<'static> {
|
||||
match browser {
|
||||
@@ -366,11 +433,14 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::os_profile::{ClientOs, OsProfileBuilder};
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::process::ExitStatusExt;
|
||||
|
||||
#[test]
|
||||
fn server_tls_result_survives_process_decoding_as_a_typed_error() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(),
|
||||
@@ -389,7 +459,6 @@ mod tests {
|
||||
#[test]
|
||||
fn client_certificate_required_result_survives_process_decoding() {
|
||||
use crate::error::{ServerTlsError, ServerTlsErrorKind};
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
let output = std::process::Output {
|
||||
status: std::process::ExitStatus::from_raw(0),
|
||||
stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(),
|
||||
@@ -409,6 +478,42 @@ mod tests {
|
||||
assert!(args.iter().any(|arg| arg == "--ignore-tls-errors"));
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn external_browser_receives_no_embedded_window_arguments() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.browser(Some("edge"))
|
||||
.clean(true)
|
||||
.hidpi(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--browser", "edge"]));
|
||||
for option in ["--clean", "--hidpi", "--window-title", "--window-theme"] {
|
||||
assert!(!args.iter().any(|arg| arg == option), "unexpected {option} in {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
#[test]
|
||||
fn embedded_window_receives_auth_preferences() {
|
||||
let args = child_args(
|
||||
SamlAuthLauncher::new("vpn.example.com")
|
||||
.clean(true)
|
||||
.window_title("GP Connect Login")
|
||||
.window_theme(AuthWindowTheme::Dark),
|
||||
);
|
||||
assert!(args.iter().any(|arg| arg == "--clean"));
|
||||
assert!(
|
||||
args
|
||||
.windows(2)
|
||||
.any(|pair| pair == ["--window-title", "GP Connect Login"])
|
||||
);
|
||||
assert!(args.windows(2).any(|pair| pair == ["--window-theme", "dark"]));
|
||||
assert!(!args.iter().any(|arg| arg == "--browser"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn os_profile_sets_os_from_profile() {
|
||||
let profile = OsProfileBuilder::new(ClientOs::Linux)
|
||||
@@ -451,6 +556,19 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn auth_child_receives_its_foreground_parent() {
|
||||
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
|
||||
let parent = command
|
||||
.as_std()
|
||||
.get_envs()
|
||||
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
|
||||
.and_then(|(_, value)| value)
|
||||
.expect("the authenticator must know its foreground recipient");
|
||||
assert_eq!(parent, std::process::id().to_string().as_str());
|
||||
}
|
||||
|
||||
/// gpauth writes to the same stderr as its parent, so a caller reading the
|
||||
/// parent's JSON would hit gpauth's text records mid-stream unless the format
|
||||
/// is passed down.
|
||||
@@ -513,11 +631,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
#[cfg(unix)]
|
||||
let status = std::process::ExitStatus::from_raw(71 << 8);
|
||||
#[cfg(windows)]
|
||||
let status = std::process::ExitStatus::from_raw(0xC0000005);
|
||||
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),
|
||||
status,
|
||||
stdout,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
@@ -530,7 +651,6 @@ mod tests {
|
||||
|
||||
#[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),
|
||||
@@ -544,6 +664,7 @@ mod tests {
|
||||
assert_eq!(error.to_string(), "Failed to parse auth data");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn custom_authenticator_crash_does_not_request_recovery() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -579,8 +700,11 @@ mod tests {
|
||||
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));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let alias = directory.path().join("auth-alias");
|
||||
std::os::unix::fs::symlink(&bundled, &alias).unwrap();
|
||||
assert!(is_bundled_authenticator(&alias, &bundled));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
use super::{
|
||||
command_runner::{ChildInput, run_observed},
|
||||
rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible_with_inheritance, is_crash_exit},
|
||||
rendering_recovery::{
|
||||
GbmBufferFailure, RenderingCrash, StderrDiagnostic, allows_shared_memory_override, eligible_with_inheritance,
|
||||
is_crash_exit,
|
||||
},
|
||||
};
|
||||
use crate::service::transport::SessionCredential;
|
||||
use anyhow::Context;
|
||||
use std::{
|
||||
cell::Cell,
|
||||
collections::HashMap,
|
||||
fs::OpenOptions,
|
||||
path::PathBuf,
|
||||
@@ -19,8 +23,10 @@ pub(super) async fn launch_desktop_child(
|
||||
envs: Option<&HashMap<String, String>>,
|
||||
credential: &SessionCredential,
|
||||
cancellation: &CancellationToken,
|
||||
detect_gbm_failure: bool,
|
||||
) -> anyhow::Result<ExitStatus> {
|
||||
let retry_eligible = eligible_with_inheritance(&command, envs.is_none());
|
||||
let detect_gbm_failure = detect_gbm_failure && allows_shared_memory_override(&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),
|
||||
@@ -38,12 +44,15 @@ pub(super) async fn launch_desktop_child(
|
||||
let cancellation = cancellation.clone();
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let gbm_failed = Cell::new(false);
|
||||
let check = || {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Desktop child launch cancelled",
|
||||
))
|
||||
} else if gbm_failed.get() {
|
||||
Err(std::io::Error::other(GbmBufferFailure))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
@@ -53,10 +62,17 @@ pub(super) async fn launch_desktop_child(
|
||||
command,
|
||||
&check,
|
||||
None,
|
||||
&mut |bytes| diagnostic.push(bytes),
|
||||
&mut |bytes| {
|
||||
diagnostic.push(bytes);
|
||||
gbm_failed.set(detect_gbm_failure && diagnostic.should_retry_gbm(retry_eligible));
|
||||
},
|
||||
&mut sink,
|
||||
ChildInput::Frame(&frame),
|
||||
)?;
|
||||
);
|
||||
if gbm_failed.get() && !cancellation.is_cancelled() {
|
||||
return Err(GbmBufferFailure.into());
|
||||
}
|
||||
let observed = observed?;
|
||||
let output = observed.output;
|
||||
if is_crash_exit(output.status) && retry_eligible && diagnostic.matched() {
|
||||
return Err(RenderingCrash { status: output.status }.into());
|
||||
|
||||
@@ -170,7 +170,11 @@ impl<'a> DesktopLauncher<'a> {
|
||||
}
|
||||
match outcome {
|
||||
Err(error) if recovery.recover(&error) => {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
if recovery.shared_memory() {
|
||||
warn!("{error}; restarting the desktop launch with compatibility graphics");
|
||||
} else {
|
||||
warn!("{error}; restarting the desktop launch with DMABUF disabled and opaque windows");
|
||||
}
|
||||
expecting_renewal = true;
|
||||
input.write_all(&[DESKTOP_RENDERING_RETRY]).await?;
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ impl<'a> GuiHelperLauncher<'a> {
|
||||
self.envs,
|
||||
self.credential,
|
||||
cancellation,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
|
||||
@@ -101,6 +101,12 @@ impl<'a> GuiLauncher<'a> {
|
||||
if let Some(envs) = &self.envs {
|
||||
cmd.env_clear().envs(envs);
|
||||
}
|
||||
if self.variant == crate::gui::GuiVariant::Tauri
|
||||
&& crate::gui::compatibility_graphics_enabled()
|
||||
&& super::rendering_recovery::allows_shared_memory_override(cmd.as_std(), self.envs.is_none())
|
||||
{
|
||||
cmd.env(crate::gui::FORCE_SHARED_MEMORY, "1");
|
||||
}
|
||||
cmd.arg("--service-credential-on-stdin");
|
||||
if self.minimized {
|
||||
cmd.arg("--minimized");
|
||||
@@ -112,6 +118,7 @@ impl<'a> GuiLauncher<'a> {
|
||||
self.envs.as_ref(),
|
||||
&self.credential,
|
||||
cancellation,
|
||||
self.variant == crate::gui::GuiVariant::Tauri,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -207,32 +214,45 @@ impl<'a> GuiLauncher<'a> {
|
||||
gui_switch::reply(&mut socket, Ok(GuiSwitchOutcome::DownloadRequired)).await?;
|
||||
return Ok(None);
|
||||
}
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let program = match program {
|
||||
Some(program) => program,
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(program, cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
return match outcome? {
|
||||
Ok(status) => Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
}
|
||||
use super::rendering_recovery::{GbmBufferFailure, RecoveryState};
|
||||
let mut recovery = RecoveryState::default();
|
||||
let mut program = program;
|
||||
let (mut child, start_result) = loop {
|
||||
service_input.write_all(&[DESKTOP_SWITCH_BEGIN]).await?;
|
||||
pending = true;
|
||||
let credential = super::desktop_launcher::read_credential(service_output).await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Service closed before issuing the switch credential"))?;
|
||||
anyhow::ensure!(credential.product_version() == self.version, "Service product version mismatch");
|
||||
let ready = gui_switch::SwitchListener::new()?;
|
||||
let mut envs = self.envs.clone().unwrap_or_else(|| std::env::vars().collect());
|
||||
envs.insert(gui_switch::READY_ENV.into(), ready.path().to_string_lossy().into_owned());
|
||||
let launcher = Self::new(self.version, Arc::new(credential), variant)
|
||||
.envs(envs)
|
||||
.minimized(false);
|
||||
let executable = match &program {
|
||||
Some(program) => program.clone(),
|
||||
None => launcher.resolve_program(cancellation, command.theme).await?,
|
||||
};
|
||||
let mut child = launcher.start_owned(executable.clone(), cancellation.child_token());
|
||||
let start_result = tokio::select! {
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(30), ready.ready()) => {
|
||||
result.map_err(|_| anyhow::anyhow!("The selected GUI did not finish starting" )).and_then(|result| result)
|
||||
},
|
||||
outcome = &mut child.task => {
|
||||
match outcome? {
|
||||
Ok(status) => return Err(anyhow::anyhow!("The selected GUI exited during startup: {status}")),
|
||||
Err(error) if error.is::<GbmBufferFailure>() && recovery.recover(&error) => {
|
||||
log::warn!("{error}; restarting the selected GUI with compatibility graphics");
|
||||
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
|
||||
pending = false;
|
||||
program = Some(executable);
|
||||
continue;
|
||||
}
|
||||
Err(error) => return Err(recovery.terminal(error)),
|
||||
}
|
||||
}
|
||||
};
|
||||
break (child, start_result);
|
||||
};
|
||||
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
|
||||
child.cancel.cancel();
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
#[cfg(unix)]
|
||||
mod command_runner;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_runner.rs"]
|
||||
mod command_runner;
|
||||
#[cfg(unix)]
|
||||
mod command_traits;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/command_traits.rs"]
|
||||
mod command_traits;
|
||||
#[cfg(unix)]
|
||||
mod desktop_child;
|
||||
#[cfg(unix)]
|
||||
mod desktop_session_env;
|
||||
#[cfg(unix)]
|
||||
pub(crate) mod gui_helper_launcher;
|
||||
|
||||
pub use command_traits::CommandExt;
|
||||
|
||||
pub mod auth_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod desktop_launcher;
|
||||
#[cfg(unix)]
|
||||
pub mod gui_launcher;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
pub mod gui_switch;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
mod nsh_runtime;
|
||||
#[cfg(unix)]
|
||||
pub mod users;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub mod collection;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/collection.rs"]
|
||||
pub mod collection;
|
||||
|
||||
pub mod rendering_recovery;
|
||||
#[cfg(windows)]
|
||||
#[path = "windows/user_process.rs"]
|
||||
pub mod user_process;
|
||||
@@ -1,6 +1,9 @@
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
const DMABUF: &str = "WEBKIT_DISABLE_DMABUF_RENDERER";
|
||||
pub const MAIN_WEBVIEW_INITIALIZED: &str = "GP Connect main webview initialized";
|
||||
const GBM_DIAGNOSTIC: &[u8] = b"Failed to create GBM buffer";
|
||||
pub(crate) const AUTH_STDERR_PREFIX: &[u8] = b"gpauth stderr: ";
|
||||
const DIAGNOSTIC: &[u8] = b"Error 71 (Protocol error) dispatching to Wayland display";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -16,20 +19,33 @@ pub struct RecoveryFailed(#[source] anyhow::Error);
|
||||
#[derive(Default)]
|
||||
pub struct RecoveryState {
|
||||
first_failure: Option<String>,
|
||||
shared_memory: bool,
|
||||
}
|
||||
|
||||
impl RecoveryState {
|
||||
pub fn dmabuf_disabled(&self) -> bool {
|
||||
self.first_failure.is_some()
|
||||
self.first_failure.is_some() && !self.shared_memory
|
||||
}
|
||||
|
||||
pub fn shared_memory(&self) -> bool {
|
||||
self.shared_memory
|
||||
}
|
||||
|
||||
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
|
||||
if self.first_failure.is_some() {
|
||||
return false;
|
||||
}
|
||||
let gbm_failure = error.downcast_ref::<GbmBufferFailure>().is_some();
|
||||
if !gbm_failure && error.downcast_ref::<RenderingCrash>().is_none() {
|
||||
return false;
|
||||
}
|
||||
if gbm_failure && let Err(error) = crate::gui::set_compatibility_graphics(true) {
|
||||
log::warn!("Could not save compatibility graphics setting: {error:#}");
|
||||
return false;
|
||||
}
|
||||
self.first_failure = Some(error.to_string());
|
||||
self.shared_memory = gbm_failure;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn terminal(&self, error: anyhow::Error) -> anyhow::Error {
|
||||
@@ -49,11 +65,17 @@ impl RecoveryState {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
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))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn is_crash_exit(status: ExitStatus) -> bool {
|
||||
status.code().is_some_and(|code| (code as u32) >= 0xC0000000)
|
||||
}
|
||||
|
||||
pub fn eligible(command: &Command) -> bool {
|
||||
eligible_with_inheritance(command, true)
|
||||
}
|
||||
@@ -64,6 +86,16 @@ pub(crate) fn eligible_with_inheritance(command: &Command, inherits: bool) -> bo
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn allows_shared_memory_override(command: &Command, inherits: bool) -> bool {
|
||||
crate::gui::COMPATIBILITY_GRAPHICS_SUPPORTED
|
||||
&& effective_env(command, DMABUF, inherits).is_none()
|
||||
&& effective_env(command, crate::gui::FORCE_SHARED_MEMORY, inherits).is_none()
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("WebKit failed to create a GBM buffer")]
|
||||
pub(crate) struct GbmBufferFailure;
|
||||
|
||||
fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ffi::OsString> {
|
||||
for (name, value) in command.get_envs() {
|
||||
if name == key {
|
||||
@@ -73,12 +105,21 @@ fn effective_env(command: &Command, key: &str, inherits: bool) -> Option<std::ff
|
||||
inherits.then(|| std::env::var_os(key)).flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn is_gbm_diagnostic(line: &[u8]) -> bool {
|
||||
!line.starts_with(AUTH_STDERR_PREFIX)
|
||||
&& line
|
||||
.windows(GBM_DIAGNOSTIC.len())
|
||||
.any(|message| message == GBM_DIAGNOSTIC)
|
||||
}
|
||||
|
||||
/// Observes diagnostic lines without retaining arbitrary application output.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StderrDiagnostic {
|
||||
line: Vec<u8>,
|
||||
overflow: bool,
|
||||
matched: bool,
|
||||
gbm_failed: bool,
|
||||
main_webview_initialized: bool,
|
||||
}
|
||||
|
||||
impl StderrDiagnostic {
|
||||
@@ -98,6 +139,14 @@ impl StderrDiagnostic {
|
||||
|
||||
fn check_line(&mut self) {
|
||||
let line = self.line.trim_ascii_end();
|
||||
if !self.overflow {
|
||||
if line == MAIN_WEBVIEW_INITIALIZED.as_bytes() {
|
||||
self.main_webview_initialized = true;
|
||||
}
|
||||
if !self.main_webview_initialized && is_gbm_diagnostic(line) {
|
||||
self.gbm_failed = true;
|
||||
}
|
||||
}
|
||||
let message = line.strip_suffix(b".").unwrap_or(line);
|
||||
if !self.overflow
|
||||
&& (line.starts_with(b"Gdk-Message:")
|
||||
@@ -111,6 +160,10 @@ impl StderrDiagnostic {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn should_retry_gbm(&self, can_retry_wayland: bool) -> bool {
|
||||
self.gbm_failed && !(can_retry_wayland && self.matched)
|
||||
}
|
||||
|
||||
pub(crate) fn matched(&mut self) -> bool {
|
||||
self.check_line();
|
||||
self.matched
|
||||
@@ -121,6 +174,43 @@ impl StderrDiagnostic {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn detects_gbm_failure_before_main_webview_initializes() {
|
||||
for line in [
|
||||
b"Failed to create GBM buffer of size 280x404: Invalid argument\n".as_slice(),
|
||||
b"(WebKitWebProcess:42): Warning: Failed to create GBM buffer\n",
|
||||
b"gpauth: Failed to create GBM buffer\n",
|
||||
] {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
for bytes in line.chunks(7) {
|
||||
observer.push(bytes);
|
||||
}
|
||||
assert!(observer.gbm_failed);
|
||||
assert!(!observer.matched());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_gbm_failure_after_startup_and_from_auth_stderr() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer
|
||||
.push(b"gpauth stderr: (WebKitWebProcess:42): Failed to create GBM buffer of size 900x648: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
observer.push(format!("{MAIN_WEBVIEW_INITIALIZED}\n").as_bytes());
|
||||
observer.push(b"Failed to create GBM buffer of size 840x640: Invalid argument\n");
|
||||
assert!(!observer.gbm_failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_wayland_retry_when_both_diagnostics_are_observed() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
observer.push(b"Failed to create GBM buffer of size 280x404: Invalid argument\n");
|
||||
observer.push(b"Gdk-Message: Error 71 (Protocol error) dispatching to Wayland display.\n");
|
||||
assert!(observer.matched());
|
||||
assert!(!observer.should_retry_gbm(true));
|
||||
assert!(observer.should_retry_gbm(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognizes_split_diagnostic_without_matching_quoted_warning() {
|
||||
let mut observer = StderrDiagnostic::default();
|
||||
@@ -192,6 +282,7 @@ mod tests {
|
||||
assert!(!eligible_with_inheritance(&command, false));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_is_once_and_preserves_cancellation_and_both_failures() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
@@ -213,6 +304,7 @@ mod tests {
|
||||
assert!(error.to_string().contains("71"));
|
||||
assert!(error.to_string().contains("second exit 72"));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn explicit_termination_is_not_a_rendering_crash() {
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Resolve system collectors from Windows' system directory, never the working directory.
|
||||
use super::command_runner::run_controlled;
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Output},
|
||||
};
|
||||
|
||||
pub struct CollectorCommands<'a> {
|
||||
control: &'a dyn CollectionControl,
|
||||
}
|
||||
impl<'a> CollectorCommands<'a> {
|
||||
pub fn new(control: &'a dyn CollectionControl) -> Self {
|
||||
Self { control }
|
||||
}
|
||||
pub fn resolve(&self, name: &str) -> Option<PathBuf> {
|
||||
let system = std::env::var_os("SystemRoot")?;
|
||||
let path = PathBuf::from(system).join("System32").join(name).with_extension("exe");
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
pub fn run(&self, name: &str, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
match self.resolve(name) {
|
||||
Some(path) => self.run_path(&path, args),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
pub fn run_executable(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.run_path(path, args)
|
||||
}
|
||||
pub fn run_path(&self, path: &Path, args: &[&str]) -> io::Result<Option<Output>> {
|
||||
self.control.check()?;
|
||||
let mut command = Command::new(path);
|
||||
command.args(args);
|
||||
match run_controlled(command, self.control, 256 * 1024) {
|
||||
Ok(output) => Ok(Some(output)),
|
||||
Err(error) if matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Controlled Windows child execution. Pipe polling keeps cancellation responsive.
|
||||
use crate::collection::CollectionControl;
|
||||
use std::{
|
||||
io::{self, Read, Write},
|
||||
os::windows::io::AsRawHandle,
|
||||
process::{Child, Command, Output, Stdio},
|
||||
thread,
|
||||
time::Duration,
|
||||
};
|
||||
use windows_sys::Win32::System::Pipes::PeekNamedPipe;
|
||||
|
||||
pub(crate) enum ChildInput<'a> {
|
||||
Null,
|
||||
Terminal,
|
||||
// Preserve the borrowed input type shared by callers without a Windows launcher.
|
||||
#[allow(dead_code)]
|
||||
Frame(&'a [u8]),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedOutput {
|
||||
pub output: Output,
|
||||
}
|
||||
|
||||
pub(crate) fn run_controlled(command: Command, control: &dyn CollectionControl, limit: usize) -> io::Result<Output> {
|
||||
run_observed(
|
||||
command,
|
||||
control,
|
||||
Some(limit),
|
||||
&mut |_| {},
|
||||
&mut io::sink(),
|
||||
ChildInput::Null,
|
||||
)
|
||||
.map(|observed| observed.output)
|
||||
}
|
||||
|
||||
pub(crate) fn run_observed(
|
||||
mut command: Command,
|
||||
control: &dyn CollectionControl,
|
||||
output_limit: Option<usize>,
|
||||
observer: &mut dyn FnMut(&[u8]),
|
||||
stderr_sink: &mut dyn Write,
|
||||
stdin: ChildInput<'_>,
|
||||
) -> io::Result<ObservedOutput> {
|
||||
control.check()?;
|
||||
// Windows desktop processes must not open a console for each helper.
|
||||
use std::os::windows::process::CommandExt;
|
||||
if !matches!(stdin, ChildInput::Terminal) {
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.stdout(if output_limit.is_some() {
|
||||
Stdio::piped()
|
||||
} else {
|
||||
Stdio::inherit()
|
||||
});
|
||||
command.stderr(Stdio::piped());
|
||||
command.stdin(match stdin {
|
||||
ChildInput::Terminal => Stdio::inherit(),
|
||||
ChildInput::Null => Stdio::null(),
|
||||
ChildInput::Frame(_) => Stdio::piped(),
|
||||
});
|
||||
let mut child = ControlledChild(command.spawn()?);
|
||||
let input = if let ChildInput::Frame(frame) = stdin {
|
||||
let mut pipe = child.0.stdin.take().expect("piped stdin");
|
||||
let frame = frame.to_vec();
|
||||
Some(thread::spawn(move || pipe.write_all(&frame)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut stdout = child.0.stdout.take();
|
||||
let mut stderr = child.0.stderr.take().expect("piped stderr");
|
||||
let mut output = Vec::new();
|
||||
let mut buffer = [0u8; 8192];
|
||||
loop {
|
||||
control.check()?;
|
||||
if let Some(pipe) = &mut stdout {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
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]);
|
||||
}
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
if let Some(status) = child.0.try_wait()? {
|
||||
// Drain the remaining buffered output after the process exits.
|
||||
if let Some(pipe) = &mut stdout {
|
||||
loop {
|
||||
let length = read_available(pipe, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
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]);
|
||||
}
|
||||
}
|
||||
loop {
|
||||
let length = read_available(&mut stderr, &mut buffer)?;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
observer(&buffer[..length]);
|
||||
stderr_sink.write_all(&buffer[..length])?;
|
||||
}
|
||||
if let Some(result) = input.and_then(|worker| worker.join().ok()) {
|
||||
result?;
|
||||
}
|
||||
return Ok(ObservedOutput {
|
||||
output: Output {
|
||||
status,
|
||||
stdout: output,
|
||||
stderr: Vec::new(),
|
||||
},
|
||||
});
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
fn read_available(pipe: &mut (impl Read + AsRawHandle), buffer: &mut [u8]) -> io::Result<usize> {
|
||||
let mut available = 0;
|
||||
let success = unsafe {
|
||||
PeekNamedPipe(
|
||||
pipe.as_raw_handle(),
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
&mut available,
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
if success == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(109) {
|
||||
return Ok(0);
|
||||
} // ERROR_BROKEN_PIPE
|
||||
return Err(error);
|
||||
}
|
||||
let length = buffer.len().min(available as usize);
|
||||
if length == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
pipe.read(&mut buffer[..length])
|
||||
}
|
||||
|
||||
struct ControlledChild(Child);
|
||||
impl Drop for ControlledChild {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn captures_output_and_rejects_excess_output() {
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo hello"]);
|
||||
let result = run_controlled(command, &|| Ok(()), 1024).unwrap();
|
||||
assert!(result.status.success());
|
||||
assert_eq!(String::from_utf8(result.stdout).unwrap().trim(), "hello");
|
||||
let mut command = Command::new("cmd.exe");
|
||||
command.args(["/D", "/C", "echo too much"]);
|
||||
assert_eq!(
|
||||
run_controlled(command, &|| Ok(()), 2).unwrap_err().kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn cancels_a_running_helper() {
|
||||
let start = std::time::Instant::now();
|
||||
let mut command = Command::new("powershell.exe");
|
||||
command.args(["-NoProfile", "-Command", "Start-Sleep -Seconds 30"]);
|
||||
let control = || {
|
||||
if start.elapsed() > Duration::from_millis(150) {
|
||||
Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
run_controlled(command, &control, 1024).unwrap_err().kind(),
|
||||
io::ErrorKind::Interrupted
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Windows authentication runs in the interactive user's GUI process.
|
||||
pub trait CommandExt {
|
||||
fn into_non_root(self) -> anyhow::Result<Command>;
|
||||
}
|
||||
|
||||
impl CommandExt for Command {
|
||||
fn into_non_root(self) -> anyhow::Result<Command> {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Launch a native worker with the admitted user's primary token and environment.
|
||||
use std::{
|
||||
ffi::{OsStr, c_void},
|
||||
io,
|
||||
os::windows::{
|
||||
ffi::OsStrExt,
|
||||
io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::Path,
|
||||
ptr,
|
||||
};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
|
||||
Globalization::{CSTR_EQUAL, CompareStringOrdinal},
|
||||
Security::{ImpersonateLoggedOnUser, RevertToSelf},
|
||||
System::{
|
||||
Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock},
|
||||
JobObjects::*,
|
||||
Threading::*,
|
||||
},
|
||||
};
|
||||
|
||||
pub struct UserProcess {
|
||||
process: OwnedHandle,
|
||||
job: Option<OwnedHandle>,
|
||||
pid: u32,
|
||||
}
|
||||
struct Environment(*mut c_void);
|
||||
impl Drop for Environment {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
DestroyEnvironmentBlock(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, message)
|
||||
}
|
||||
fn wide(value: &OsStr) -> io::Result<Vec<u16>> {
|
||||
let value: Vec<_> = value.encode_wide().collect();
|
||||
if value.contains(&0) {
|
||||
return Err(invalid("Windows process strings cannot contain NUL"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
fn quote(argument: &[u16], output: &mut Vec<u16>) {
|
||||
output.push(b'"' as u16);
|
||||
let mut backslashes = 0;
|
||||
for &character in argument {
|
||||
if character == b'\\' as u16 {
|
||||
backslashes += 1;
|
||||
continue;
|
||||
}
|
||||
let count = if character == b'"' as u16 {
|
||||
backslashes * 2 + 1
|
||||
} else {
|
||||
backslashes
|
||||
};
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, count));
|
||||
output.push(character);
|
||||
backslashes = 0;
|
||||
}
|
||||
output.extend(std::iter::repeat_n(b'\\' as u16, backslashes * 2));
|
||||
output.push(b'"' as u16);
|
||||
}
|
||||
fn command_line(program: &[u16], arguments: &[String]) -> io::Result<Vec<u16>> {
|
||||
let mut output = Vec::new();
|
||||
quote(program, &mut output);
|
||||
for argument in arguments {
|
||||
output.push(b' ' as u16);
|
||||
quote(&wide(OsStr::new(argument))?, &mut output);
|
||||
}
|
||||
output.push(0);
|
||||
if output.len() > 32767 {
|
||||
return Err(invalid("Windows worker command line is too long"));
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
fn key(entry: &[u16]) -> &[u16] {
|
||||
let end = entry
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(index, value)| *index != 0 && **value == b'=' as u16)
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(entry.len());
|
||||
&entry[..end]
|
||||
}
|
||||
fn compare(left: &[u16], right: &[u16]) -> std::cmp::Ordering {
|
||||
// Environment names follow Windows' ordinal, case-insensitive ordering.
|
||||
unsafe { CompareStringOrdinal(left.as_ptr(), left.len() as i32, right.as_ptr(), right.len() as i32, 1) }
|
||||
.cmp(&CSTR_EQUAL)
|
||||
}
|
||||
fn user_environment(token: BorrowedHandle<'_>, variables: &[(&str, &str)]) -> io::Result<Vec<u16>> {
|
||||
let mut pointer = ptr::null_mut();
|
||||
if unsafe { CreateEnvironmentBlock(&mut pointer, token.as_raw_handle(), 0) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let environment = Environment(pointer);
|
||||
let mut entries = Vec::new();
|
||||
unsafe {
|
||||
let mut current = environment.0.cast::<u16>();
|
||||
while *current != 0 {
|
||||
let mut length = 0;
|
||||
while *current.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
entries.push(std::slice::from_raw_parts(current, length).to_vec());
|
||||
current = current.add(length + 1);
|
||||
}
|
||||
}
|
||||
for (name, value) in variables {
|
||||
if name.is_empty() || name.contains('=') {
|
||||
return Err(invalid("Invalid worker environment name"));
|
||||
}
|
||||
let name = wide(OsStr::new(name))?;
|
||||
let value = wide(OsStr::new(value))?;
|
||||
entries.retain(|entry| compare(key(entry), &name) != std::cmp::Ordering::Equal);
|
||||
let mut entry = name;
|
||||
entry.push(b'=' as u16);
|
||||
entry.extend(value);
|
||||
entries.push(entry);
|
||||
}
|
||||
entries.sort_by(|left, right| compare(key(left), key(right)));
|
||||
let mut block = Vec::new();
|
||||
for entry in entries {
|
||||
block.extend(entry);
|
||||
block.push(0);
|
||||
}
|
||||
if block.is_empty() {
|
||||
block.push(0);
|
||||
}
|
||||
block.push(0);
|
||||
Ok(block)
|
||||
}
|
||||
impl UserProcess {
|
||||
/// No service handles or service environment are inherited. The user token
|
||||
/// determines the Windows session, including an existing interactive desktop.
|
||||
pub fn launch(
|
||||
token: BorrowedHandle<'_>,
|
||||
program: &Path,
|
||||
arguments: &[String],
|
||||
variables: &[(&str, &str)],
|
||||
) -> io::Result<Self> {
|
||||
if !program.is_absolute() {
|
||||
return Err(invalid("Windows worker executable must be absolute"));
|
||||
}
|
||||
let mut executable = wide(program.as_os_str())?;
|
||||
let mut command = command_line(&executable, arguments)?;
|
||||
executable.push(0);
|
||||
let mut environment = user_environment(token, variables)?;
|
||||
let directory = program.parent().ok_or_else(|| invalid("Worker directory is missing"))?;
|
||||
let mut directory = wide(directory.as_os_str())?;
|
||||
directory.push(0);
|
||||
let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
|
||||
if job.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let job = unsafe { OwnedHandle::from_raw_handle(job) };
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
std::mem::size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut desktop: Vec<u16> = "winsta0\\default".encode_utf16().chain(Some(0)).collect();
|
||||
let startup = STARTUPINFOW {
|
||||
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
|
||||
lpDesktop: desktop.as_mut_ptr(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut information = PROCESS_INFORMATION::default();
|
||||
// Read/execute the requested image as its user, as Unix exec-after-setuid
|
||||
// does. The service's filesystem access must not authorize a private image.
|
||||
if unsafe { ImpersonateLoggedOnUser(token.as_raw_handle()) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
struct Revert;
|
||||
impl Drop for Revert {
|
||||
fn drop(&mut self) {
|
||||
if unsafe { RevertToSelf() } == 0 {
|
||||
std::process::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
let revert = Revert;
|
||||
let created = unsafe {
|
||||
CreateProcessAsUserW(
|
||||
token.as_raw_handle(),
|
||||
executable.as_ptr(),
|
||||
command.as_mut_ptr(),
|
||||
ptr::null(),
|
||||
ptr::null(),
|
||||
0,
|
||||
CREATE_UNICODE_ENVIRONMENT | CREATE_SUSPENDED | CREATE_NO_WINDOW,
|
||||
environment.as_mut_ptr().cast(),
|
||||
directory.as_ptr(),
|
||||
&startup,
|
||||
&mut information,
|
||||
)
|
||||
};
|
||||
let error = (created == 0).then(io::Error::last_os_error);
|
||||
drop(revert);
|
||||
if let Some(error) = error {
|
||||
return Err(error);
|
||||
}
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(information.hProcess) };
|
||||
let thread = unsafe { OwnedHandle::from_raw_handle(information.hThread) };
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process.as_raw_handle()) } == 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
// The suspended child is not owned by the job on this failure path.
|
||||
unsafe {
|
||||
TerminateProcess(process.as_raw_handle(), 1);
|
||||
WaitForSingleObject(process.as_raw_handle(), 5000);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let child = Self {
|
||||
process,
|
||||
job: Some(job),
|
||||
pid: information.dwProcessId,
|
||||
};
|
||||
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
pub fn id(&self) -> u32 {
|
||||
self.pid
|
||||
}
|
||||
pub fn has_exited(&self) -> io::Result<bool> {
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 0) } {
|
||||
WAIT_OBJECT_0 => Ok(true),
|
||||
WAIT_TIMEOUT => Ok(false),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
pub fn stop(&mut self) -> io::Result<()> {
|
||||
if self.job.take().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match unsafe { WaitForSingleObject(self.process.as_raw_handle(), 5000) } {
|
||||
WAIT_OBJECT_0 => Ok(()),
|
||||
WAIT_TIMEOUT => Err(io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
"Windows worker did not terminate",
|
||||
)),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for UserProcess {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = self.stop() {
|
||||
log::warn!("Could not stop Windows worker: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows_sys::Win32::{Foundation::LocalFree, UI::Shell::CommandLineToArgvW};
|
||||
#[test]
|
||||
fn command_line_round_trips_through_windows_parser() {
|
||||
let program: Vec<u16> = r"C:\Program Files\GP Connect\gpgui-nsh.exe".encode_utf16().collect();
|
||||
let arguments = [
|
||||
"proxy-worker",
|
||||
"",
|
||||
"space value",
|
||||
"quoted\"value",
|
||||
"two\\\\\"quotes",
|
||||
"trailing\\",
|
||||
"雪",
|
||||
"&|<>",
|
||||
]
|
||||
.map(String::from);
|
||||
let command = command_line(&program, &arguments).unwrap();
|
||||
let mut count = 0;
|
||||
unsafe {
|
||||
let parsed = CommandLineToArgvW(command.as_ptr(), &mut count);
|
||||
assert!(!parsed.is_null());
|
||||
let result = std::slice::from_raw_parts(parsed, count as usize)
|
||||
.iter()
|
||||
.map(|&value| {
|
||||
let mut length = 0;
|
||||
while *value.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
String::from_utf16_lossy(std::slice::from_raw_parts(value, length))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
LocalFree(parsed.cast());
|
||||
assert_eq!(result[0], String::from_utf16_lossy(&program));
|
||||
assert_eq!(result[1..], arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user