feat(linux): switch desktop interfaces and preserve selection on upgrade

This commit is contained in:
Kevin Yue committed 2026-11-01 23:35:55 +08:00
1 parent 0df25fbd28
commit e284840d89
17 files changed
+818 -58

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
//! Desktop GUI selection shared by launchers, installers and settings.
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::PathBuf;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "kebab-case")]
pub enum GuiVariant {
#[default]
Tauri,
Nsh,
}
impl GuiVariant {
pub fn binary_name(self) -> &'static str {
match self {
Self::Tauri => "gpgui",
Self::Nsh => "gpgui-nsh",
}
}
pub fn update_target(self) -> PathBuf {
let target = common::binary_paths::gpgui_update_target();
match self {
Self::Tauri => target,
Self::Nsh => target.with_file_name(self.binary_name()),
}
}
pub fn primary(self) -> PathBuf {
match self {
Self::Tauri => common::binary_paths::gpgui(),
Self::Nsh => common::binary_paths::gpgui().with_file_name(self.binary_name()),
}
}
}
#[cfg(target_os = "linux")]
fn preference_path() -> anyhow::Result<PathBuf> {
let dirs = directories::ProjectDirs::from("com.yuezk", "GlobalProtect-openconnect", "gpclient")
.ok_or_else(|| anyhow::anyhow!("Failed to locate GUI preference directory"))?;
Ok(dirs.config_dir().join("gui"))
}
pub fn preferred() -> anyhow::Result<GuiVariant> {
#[cfg(target_os = "linux")]
{
match std::fs::read_to_string(preference_path()?) {
Ok(value) => match value.trim() {
"gpgui" => Ok(GuiVariant::Tauri),
"gpgui-nsh" => Ok(GuiVariant::Nsh),
_ => anyhow::bail!("Invalid GUI preference"),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(GuiVariant::Tauri),
Err(error) => Err(error.into()),
}
}
#[cfg(not(target_os = "linux"))]
Ok(GuiVariant::Tauri)
}
#[cfg(target_os = "linux")]
pub fn save_preference(variant: GuiVariant) -> anyhow::Result<()> {
use std::io::Write;
let path = preference_path()?;
let directory = path.parent().unwrap();
std::fs::create_dir_all(directory)?;
let mut file = tempfile::NamedTempFile::new_in(directory)?;
writeln!(file, "{}", variant.binary_name())?;
file.persist(path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nsh_selection_keeps_both_launch_and_upgrade_paths_on_nsh() {
let variant = GuiVariant::Nsh;
assert_eq!(variant.primary().file_name().unwrap(), "gpgui-nsh");
assert_eq!(variant.update_target().file_name().unwrap(), "gpgui-nsh");
assert_eq!(
variant.update_target().parent(),
GuiVariant::Tauri.update_target().parent()
);
assert_eq!(serde_json::to_string(&variant).unwrap(), "\"nsh\"");
}
}
+2
View File
@@ -9,6 +9,8 @@ pub mod error;
pub mod gateway;
pub mod gp_params;
#[cfg(feature = "desktop")]
pub mod gui;
#[cfg(feature = "desktop")]
pub mod hip;
pub mod log_format;
pub mod os_profile;
+47 -22
View File
@@ -70,11 +70,12 @@ impl<'a> DesktopLauncher<'a> {
let mut cancelled = false;
let cancellation = CancellationToken::new();
let mut recovery = RecoveryState::default();
#[cfg(target_os = "linux")]
let switch_listener = super::gui_switch::SwitchListener::new()?;
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;
@@ -95,37 +96,59 @@ impl<'a> DesktopLauncher<'a> {
"Service product version mismatch"
);
let mut envs: HashMap<String, String> = std::env::vars().collect();
#[cfg(target_os = "linux")]
envs.insert(
super::gui_switch::SOCKET_ENV.into(),
switch_listener.path().to_string_lossy().into_owned(),
);
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))
let launcher = GuiLauncher::new(self.version, Arc::new(credential), crate::gui::preferred()?)
.envs(envs)
.minimized(minimized);
#[cfg(not(target_os = "linux"))]
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");
let outcome = {
let attempt = async {
let program = launcher.resolve_program(&cancellation).await?;
#[cfg(target_os = "linux")]
return launcher
.launch_with_switches(
&program,
&cancellation,
&switch_listener.listener,
&mut input,
&mut output,
)
.await;
#[cfg(not(target_os = "linux"))]
launcher.launch_program(&program, &cancellation).await
};
tokio::pin!(attempt);
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 = async {
#[cfg(not(target_os = "linux"))]
return output.read(&mut unexpected).await;
#[cfg(target_os = "linux")]
std::future::pending::<std::io::Result<usize>>().await
} => {
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() {
@@ -184,7 +207,9 @@ fn create_log_file(path: &Path) -> std::io::Result<File> {
OpenOptions::new().append(true).open(path)
}
async fn read_credential(reader: &mut (impl AsyncRead + Unpin)) -> anyhow::Result<Option<SessionCredential>> {
pub(super) async fn read_credential(
reader: &mut (impl AsyncRead + Unpin),
) -> anyhow::Result<Option<SessionCredential>> {
let mut header = [0; 2];
if reader.read(&mut header[..1]).await? == 0 {
return Ok(None);
@@ -12,6 +12,7 @@ pub struct GuiHelperLauncher<'a> {
envs: Option<&'a HashMap<String, String>>,
credential: &'a SessionCredential,
gui_version: Option<&'a str>,
variant: crate::gui::GuiVariant,
}
impl<'a> GuiHelperLauncher<'a> {
@@ -21,6 +22,7 @@ impl<'a> GuiHelperLauncher<'a> {
envs: None,
credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
}
}
@@ -34,6 +36,11 @@ impl<'a> GuiHelperLauncher<'a> {
self
}
pub fn variant(mut self, variant: crate::gui::GuiVariant) -> Self {
self.variant = variant;
self
}
pub async fn launch(&self, cancellation: &CancellationToken) -> anyhow::Result<()> {
let mut cmd = Command::new(&self.program);
@@ -43,6 +50,9 @@ impl<'a> GuiHelperLauncher<'a> {
}
cmd.arg("--service-credential-on-stdin");
if self.variant == crate::gui::GuiVariant::Nsh {
cmd.arg("--gui-variant").arg("nsh");
}
if let Some(gui_version) = self.gui_version {
cmd.arg("--gui-version").arg(gui_version);
@@ -96,6 +106,7 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
assert!(error.to_string().contains("gpgui-helper exited with"), "{error:#}");
@@ -122,6 +133,7 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
};
let error = launcher.launch(&CancellationToken::new()).await.unwrap_err();
let eligible =
@@ -143,6 +155,7 @@ mod tests {
envs: Some(&envs),
credential: &credential,
gui_version: None,
variant: crate::gui::GuiVariant::Tauri,
};
let cancellation = CancellationToken::new();
let attempt = launcher.launch(&cancellation);
+367 -5
View File
@@ -6,7 +6,6 @@ use std::{
};
use anyhow::bail;
use common::binary_paths;
use log::info;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
@@ -15,6 +14,7 @@ use crate::{process::gui_helper_launcher::GuiHelperLauncher, service::transport:
pub struct GuiLauncher<'a> {
version: &'a str,
variant: crate::gui::GuiVariant,
programs: Vec<PathBuf>,
credential: Arc<SessionCredential>,
minimized: bool,
@@ -22,9 +22,9 @@ pub struct GuiLauncher<'a> {
}
impl<'a> GuiLauncher<'a> {
pub fn new(version: &'a str, credential: Arc<SessionCredential>) -> Self {
let primary = binary_paths::gpgui();
let update_target = binary_paths::gpgui_update_target();
pub fn new(version: &'a str, credential: Arc<SessionCredential>, variant: crate::gui::GuiVariant) -> Self {
let primary = variant.primary();
let update_target = variant.update_target();
let programs = if primary == update_target {
vec![primary]
} else {
@@ -33,6 +33,7 @@ impl<'a> GuiLauncher<'a> {
Self {
version,
variant,
programs,
credential,
minimized: false,
@@ -63,7 +64,7 @@ impl<'a> GuiLauncher<'a> {
return Ok(program);
}
self.download_program(cancellation).await?;
let program = binary_paths::gpgui_update_target();
let program = self.variant.update_target();
tokio::select! {
biased;
_ = cancellation.cancelled() => anyhow::bail!("GUI resolution cancelled"),
@@ -143,9 +144,136 @@ impl<'a> GuiLauncher<'a> {
gui_helper
.envs(self.envs.as_ref())
.gui_version(Some(self.version))
.variant(self.variant)
.launch(cancellation)
.await
}
#[cfg(target_os = "linux")]
pub(crate) async fn launch_with_switches(
&self,
program: &Path,
cancellation: &CancellationToken,
listener: &tokio::net::UnixListener,
service_input: &mut (impl tokio::io::AsyncWrite + Unpin),
service_output: &mut (impl tokio::io::AsyncRead + Unpin),
) -> anyhow::Result<ExitStatus> {
use super::gui_switch;
use crate::service::transport::{DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut current = Some(self.start_owned(program.to_owned(), cancellation.child_token()));
let mut retired = Vec::new();
let mut unexpected = [0];
let result = async { loop {
tokio::select! {
biased;
outcome = &mut current.as_mut().unwrap().task => {
current.take();
break outcome?;
}
accepted = listener.accept() => {
let (mut socket, _) = accepted?;
let mut pending = false;
let replacement = async {
let variant = gui_switch::receive(&mut socket).await?;
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 = launcher.resolve_program(cancellation).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),
};
}
};
if let Err(error) = start_result.and_then(|()| crate::gui::save_preference(variant)) {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = gui_switch::reply(&mut socket, Ok(())).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error);
}
if let Err(error) = service_input.write_all(&[DESKTOP_SWITCH_COMMIT]).await {
child.cancel.cancel();
let _ = child.task.await;
return Err(error.into());
}
pending = false;
Ok(child)
}.await;
match replacement {
Ok(child) => retired.push(current.replace(child).unwrap()),
Err(error) => {
if pending {
service_input.write_all(&[DESKTOP_SWITCH_CANCEL]).await?;
}
let _ = gui_switch::reply(&mut socket, Err(format!("{error:#}"))).await;
}
}
}
result = service_output.read(&mut unexpected) => {
break match result {
Ok(0) => Err(anyhow::anyhow!("The privileged service closed its credential channel")),
Ok(_) => Err(anyhow::anyhow!("Unexpected service credential data while the GUI is running")),
Err(error) => Err(error.into()),
};
}
}
}}.await;
// Every GUI remains owned by this supervisor until it is reaped. The retiring
// GUI exits after the successful switch reply; cancellation also joins it.
if let Some(child) = current {
retired.push(child);
}
for child in &retired {
child.cancel.cancel();
}
for child in retired {
let _ = child.task.await;
}
result
}
#[cfg(target_os = "linux")]
fn start_owned(&self, program: PathBuf, cancel: CancellationToken) -> RunningGui {
let version = self.version.to_owned();
let variant = self.variant;
let credential = self.credential.clone();
let envs = self.envs.clone();
let minimized = self.minimized;
let task_cancel = cancel.clone();
let task = tokio::spawn(async move {
GuiLauncher::new(&version, credential, variant)
.envs(envs)
.minimized(minimized)
.launch_program(&program, &task_cancel)
.await
});
RunningGui { task, cancel }
}
}
#[cfg(target_os = "linux")]
struct RunningGui {
task: tokio::task::JoinHandle<anyhow::Result<ExitStatus>>,
cancel: CancellationToken,
}
#[cfg(test)]
@@ -174,6 +302,7 @@ mod tests {
fn launcher(version: &'static str, programs: Vec<PathBuf>) -> GuiLauncher<'static> {
GuiLauncher {
version,
variant: crate::gui::GuiVariant::Tauri,
programs,
credential: Arc::new(SessionCredential::generate(Uuid::new_v4(), version).unwrap()),
minimized: false,
@@ -298,4 +427,237 @@ mod tests {
assert_eq!(launcher.find_compatible_program().await, None);
}
#[tokio::test]
async fn nsh_version_mismatch_cannot_select_a_compatible_tauri_binary() {
let dir = TempDir::new().unwrap();
let _tauri = executable(&dir, "gpgui", "gpgui test-version", 0);
let nsh = executable(&dir, "gpgui-nsh", "gpgui-nsh old-version", 0);
let mut selected = launcher(VERSION, vec![nsh.clone()]);
selected.variant = crate::gui::GuiVariant::Nsh;
assert!(selected.find_compatible_program().await.is_none());
executable(&dir, "gpgui-nsh", "gpgui-nsh test-version", 0);
assert_eq!(selected.find_compatible_program().await, Some(nsh));
}
#[test]
#[cfg(target_os = "linux")]
fn supervisor_switch_success_and_failure_preserve_child_ownership() {
for scenario in ["success", "failure"] {
let directory = TempDir::new().unwrap();
let executable = std::env::current_exe().unwrap();
for name in ["gpgui", "gpgui-nsh"] {
let path = directory.path().join(name);
fs::write(&path, format!(
"#!/bin/sh\nif [ \"$1\" = --version ]; then echo '{name} {VERSION}'; exit 0; fi\nGP_SWITCH_GUI_VARIANT={name} exec '{}' --exact process::gui_launcher::tests::gui_process_fixture --ignored --nocapture\n",
executable.display()
)).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
let output = std::process::Command::new(&executable)
.args([
"--exact",
"process::gui_launcher::tests::supervisor_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_SCENARIO", scenario)
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", directory.path().join("gpgui"))
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
output.status.success(),
"{scenario}: {} {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
}
}
#[test]
#[cfg(target_os = "linux")]
fn selected_nsh_upgrade_downloads_nsh_without_probing_tauri() {
let directory = TempDir::new().unwrap();
let test_executable = std::env::current_exe().unwrap();
let tauri_marker = directory.path().join("tauri-probed");
let tauri = executable(&directory, "gpgui", "gpgui test-version", 0);
fs::write(
&tauri,
format!(
"#!/bin/sh\ntouch '{}'; echo 'gpgui {VERSION}'\n",
tauri_marker.display()
),
)
.unwrap();
executable(&directory, "gpgui-nsh", "gpgui-nsh old-version", 0);
let helper = directory.path().join("gpgui-helper");
fs::write(&helper, format!(
"#!/bin/sh\n[ \"$2\" = --gui-variant ] && [ \"$3\" = nsh ] || exit 21\nexec '{}' --exact process::gui_launcher::tests::upgrade_helper_fixture --ignored --nocapture\n",
test_executable.display()
)).unwrap();
fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap();
let result = std::process::Command::new(test_executable)
.args([
"--exact",
"process::gui_launcher::tests::upgrade_fixture",
"--ignored",
"--nocapture",
])
.env("GP_SWITCH_DIRECTORY", directory.path())
.env("GP_GUI_BINARY", &tauri)
.env("GP_GUI_HELPER_BINARY", helper)
.env("XDG_CONFIG_HOME", directory.path().join("config"))
.output()
.unwrap();
assert!(
result.status.success(),
"{} {}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
assert!(!tauri_marker.exists());
assert!(directory.path().join("nsh-updated").exists());
}
#[tokio::test]
#[ignore = "subprocess upgrade resolver fixture"]
#[cfg(target_os = "linux")]
async fn upgrade_fixture() {
crate::gui::save_preference(crate::gui::GuiVariant::Nsh).unwrap();
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap());
let selected = GuiLauncher::new(VERSION, credential, crate::gui::preferred().unwrap());
let program = selected.resolve_program(&CancellationToken::new()).await.unwrap();
assert_eq!(program.file_name().unwrap(), "gpgui-nsh");
}
#[test]
#[ignore = "subprocess download helper fixture"]
#[cfg(target_os = "linux")]
fn upgrade_helper_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
fs::write(
directory.join("gpgui-nsh"),
format!("#!/bin/sh\necho 'gpgui-nsh {VERSION}'\n"),
)
.unwrap();
fs::write(directory.join("nsh-updated"), "").unwrap();
}
#[test]
#[ignore = "subprocess GUI fixture"]
#[cfg(target_os = "linux")]
fn gui_process_fixture() {
use std::io::Read;
let mut input = std::io::stdin().lock();
let mut header = [0; 2];
input.read_exact(&mut header).unwrap();
let mut frame = zeroize::Zeroizing::new(vec![0; usize::from(u16::from_be_bytes(header))]);
input.read_exact(&mut frame).unwrap();
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let variant = std::env::var("GP_SWITCH_GUI_VARIANT").unwrap();
if variant == "gpgui-nsh" && std::env::var("GP_SWITCH_SCENARIO").unwrap() == "failure" {
panic!("fixture: native host failed to initialize");
}
super::super::gui_switch::notify_ready().unwrap();
fs::write(directory.join(format!("{variant}-started")), "").unwrap();
while !directory.join(format!("stop-{variant}")).exists() {
std::thread::sleep(std::time::Duration::from_millis(10));
}
fs::write(directory.join(format!("{variant}-exited")), "").unwrap();
}
#[tokio::test]
#[ignore = "subprocess supervisor fixture with isolated GUI paths and preferences"]
#[cfg(target_os = "linux")]
async fn supervisor_fixture() {
use crate::service::transport::{DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let directory = PathBuf::from(std::env::var_os("GP_SWITCH_DIRECTORY").unwrap());
let success = std::env::var("GP_SWITCH_SCENARIO").unwrap() == "success";
let listener = super::super::gui_switch::SwitchListener::new().unwrap();
let (mut service_input, mut control) = tokio::io::duplex(64);
let (mut service_output, mut credentials) = tokio::io::duplex(2048);
let service = tokio::spawn(async move {
loop {
let message = control.read_u8().await.unwrap();
match message {
DESKTOP_SWITCH_BEGIN => {
let credential = SessionCredential::generate(Uuid::new_v4(), VERSION).unwrap();
credentials
.write_all(&credential.encode_frame().unwrap())
.await
.unwrap();
}
DESKTOP_SWITCH_COMMIT | DESKTOP_SWITCH_CANCEL => {}
_ => panic!("unexpected fixture desktop control"),
}
}
});
let envs = std::env::vars().collect::<HashMap<_, _>>();
let launcher = launcher(VERSION, vec![]).envs(envs);
let cancel = CancellationToken::new();
let program = directory.join("gpgui");
let run = launcher.launch_with_switches(
&program,
&cancel,
&listener.listener,
&mut service_input,
&mut service_output,
);
tokio::pin!(run);
let checkpoint = async {
while !directory.join("gpgui-started").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
let result = super::super::gui_switch::request_at(&listener.path(), crate::gui::GuiVariant::Nsh).await;
anyhow::ensure!(result.is_ok() == success, "Unexpected switch result: {result:?}");
anyhow::ensure!(
!directory.join("gpgui-exited").exists(),
"Current GUI exited before acknowledgement"
);
if success {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Nsh,
"Successful switch did not save preference"
);
fs::write(directory.join("stop-gpgui"), "")?;
while !directory.join("gpgui-exited").exists() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
} else {
anyhow::ensure!(
crate::gui::preferred()? == crate::gui::GuiVariant::Tauri,
"Failed switch changed preference"
);
}
Ok::<_, anyhow::Error>(())
};
let checkpoint_result = tokio::select! {
result = &mut run => panic!("supervisor exited before the owned GUI: {result:?}"),
result = tokio::time::timeout(std::time::Duration::from_secs(10), checkpoint) => result.map_err(anyhow::Error::from).and_then(|result| result),
};
if let Err(error) = checkpoint_result {
cancel.cancel();
let _ = run.await;
panic!("{error:#}");
}
let stop = if success { "stop-gpgui-nsh" } else { "stop-gpgui" };
fs::write(directory.join(stop), "").unwrap();
assert!(
tokio::time::timeout(std::time::Duration::from_secs(5), run)
.await
.unwrap()
.unwrap()
.success()
);
service.abort();
}
}
+117
View File
@@ -0,0 +1,117 @@
//! Linux GUI switching through the user-owned desktop supervisor.
use anyhow::Context;
use std::os::unix::fs::PermissionsExt;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{UnixListener, UnixStream},
};
use crate::gui::GuiVariant;
pub(crate) const SOCKET_ENV: &str = "GP_DESKTOP_CONTROL_SOCKET";
pub(crate) const READY_ENV: &str = "GP_DESKTOP_READY_SOCKET";
/// Called after the replacement has initialized its native host.
pub fn notify_ready() -> anyhow::Result<()> {
use std::io::Write;
let Some(path) = std::env::var_os(READY_ENV) else {
return Ok(());
};
let mut socket = std::os::unix::net::UnixStream::connect(path).context("Could not notify the desktop supervisor")?;
socket.write_all(&[1])?;
Ok(())
}
pub async fn request(variant: GuiVariant) -> anyhow::Result<()> {
let path = std::env::var_os(SOCKET_ENV).context("GUI switching requires a desktop supervisor")?;
request_at(std::path::Path::new(&path), variant).await
}
pub(super) async fn request_at(path: &std::path::Path, variant: GuiVariant) -> anyhow::Result<()> {
let mut socket = UnixStream::connect(path)
.await
.context("Could not contact the desktop supervisor")?;
socket.write_all(&serde_json::to_vec(&variant)?).await?;
socket.shutdown().await?;
let mut reply = Vec::new();
socket.take(4096).read_to_end(&mut reply).await?;
let result: Result<(), String> = serde_json::from_slice(&reply).context("Invalid desktop supervisor response")?;
result.map_err(anyhow::Error::msg)
}
pub(crate) struct SwitchListener {
pub listener: UnixListener,
directory: tempfile::TempDir,
}
impl SwitchListener {
pub fn new() -> anyhow::Result<Self> {
let directory = tempfile::Builder::new().prefix("gp-desktop-").tempdir()?;
let path = directory.path().join("control");
let listener = UnixListener::bind(&path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
Ok(Self { listener, directory })
}
pub fn path(&self) -> std::path::PathBuf {
self.directory.path().join("control")
}
pub async fn ready(&self) -> anyhow::Result<()> {
let (mut socket, _) = self.listener.accept().await?;
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut byte = [0];
socket.read_exact(&mut byte).await?;
anyhow::ensure!(byte == [1], "Invalid GUI startup notification");
Ok(())
}
}
pub(crate) async fn receive(socket: &mut UnixStream) -> anyhow::Result<GuiVariant> {
anyhow::ensure!(
socket.peer_cred()?.uid() == uzers::get_effective_uid(),
"Desktop supervisor user mismatch"
);
let mut request = Vec::new();
tokio::time::timeout(
std::time::Duration::from_secs(5),
socket.take(128).read_to_end(&mut request),
)
.await??;
serde_json::from_slice(&request).context("Invalid GUI selection")
}
pub(crate) async fn reply(socket: &mut UnixStream, result: Result<(), String>) -> anyhow::Result<()> {
socket.write_all(&serde_json::to_vec(&result)?).await?;
socket.shutdown().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn private_switch_socket_preserves_selection_and_reports_failure() {
let control = SwitchListener::new().unwrap();
let path = control.path();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let client = tokio::spawn(async move {
let mut socket = UnixStream::connect(path).await.unwrap();
socket.write_all(b"\"nsh\"").await.unwrap();
socket.shutdown().await.unwrap();
let mut reply = Vec::new();
socket.read_to_end(&mut reply).await.unwrap();
serde_json::from_slice::<Result<(), String>>(&reply).unwrap()
});
let (mut socket, _) = control.listener.accept().await.unwrap();
assert_eq!(receive(&mut socket).await.unwrap(), GuiVariant::Nsh);
reply(&mut socket, Err("Selected GUI could not start".into()))
.await
.unwrap();
assert_eq!(client.await.unwrap().unwrap_err(), "Selected GUI could not start");
}
}
+2
View File
@@ -9,6 +9,8 @@ pub use command_traits::CommandExt;
pub mod auth_launcher;
pub mod desktop_launcher;
pub mod gui_launcher;
#[cfg(target_os = "linux")]
pub mod gui_switch;
pub mod users;
pub mod collection;
+2
View File
@@ -442,6 +442,8 @@ pub enum WsRequest {
pub struct UpdateGuiRequest {
pub path: String,
pub checksum: String,
#[serde(default)]
pub variant: crate::gui::GuiVariant,
}
#[cfg(test)]
@@ -21,3 +21,6 @@ pub const MAX_SERVICE_MESSAGE: usize = 256;
/// Private desktop control messages; never carry credentials.
pub const DESKTOP_GUI_EXITED: u8 = 0;
pub const DESKTOP_RENDERING_RETRY: u8 = 1;
pub const DESKTOP_SWITCH_BEGIN: u8 = 2;
pub const DESKTOP_SWITCH_COMMIT: u8 = 3;
pub const DESKTOP_SWITCH_CANCEL: u8 = 4;