mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat(linux): switch desktop interfaces and preserve selection on upgrade
This commit is contained in:
17 files changed
+818
-58
No files matched your search
Generated
+1
@@ -2059,6 +2059,7 @@ dependencies = [
|
||||
"clap",
|
||||
"clap-verbosity-flag",
|
||||
"common",
|
||||
"directories",
|
||||
"dns-lookup",
|
||||
"env_logger",
|
||||
"getrandom 0.4.3",
|
||||
|
||||
@@ -11,19 +11,27 @@ pub struct App {
|
||||
credential: Arc<SessionCredential>,
|
||||
credential_lease: watch::Receiver<bool>,
|
||||
gui_version: String,
|
||||
variant: gpapi::gui::GuiVariant,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(credential: Arc<SessionCredential>, credential_lease: watch::Receiver<bool>, gui_version: &str) -> Self {
|
||||
pub fn new(
|
||||
credential: Arc<SessionCredential>,
|
||||
credential_lease: watch::Receiver<bool>,
|
||||
gui_version: &str,
|
||||
variant: gpapi::gui::GuiVariant,
|
||||
) -> Self {
|
||||
Self {
|
||||
credential,
|
||||
credential_lease,
|
||||
gui_version: gui_version.to_string(),
|
||||
variant,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&self) -> anyhow::Result<()> {
|
||||
let gui_version = self.gui_version.clone();
|
||||
let variant = self.variant;
|
||||
let credential = Arc::clone(&self.credential);
|
||||
let credential_lease = self.credential_lease.clone();
|
||||
|
||||
@@ -34,7 +42,7 @@ impl App {
|
||||
|
||||
let notifier = ProgressNotifier::new(win.clone());
|
||||
let installer = Installer::new(credential, credential_lease.clone());
|
||||
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer));
|
||||
let updater = Arc::new(GuiUpdater::new(gui_version, notifier, installer, variant));
|
||||
|
||||
let app_handle = app.handle().clone();
|
||||
let mut app_credential_lease = credential_lease;
|
||||
|
||||
@@ -29,6 +29,8 @@ struct Cli {
|
||||
|
||||
#[arg(long, default_value = env!("CARGO_PKG_VERSION"), help = "The version of the GUI")]
|
||||
gui_version: String,
|
||||
#[arg(long, default_value = "tauri", value_parser = ["tauri", "nsh"])]
|
||||
gui_variant: String,
|
||||
|
||||
#[command(flatten)]
|
||||
verbose: InfoLevelVerbosity,
|
||||
@@ -38,7 +40,16 @@ impl Cli {
|
||||
fn run(&self) -> anyhow::Result<()> {
|
||||
let credential = self.read_credential()?;
|
||||
let credential_lease = monitor_credential_lease().context("Failed to monitor service credential lifetime")?;
|
||||
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version);
|
||||
let variant = if self.gui_variant == "nsh" {
|
||||
gpapi::gui::GuiVariant::Nsh
|
||||
} else {
|
||||
gpapi::gui::GuiVariant::Tauri
|
||||
};
|
||||
anyhow::ensure!(
|
||||
variant != gpapi::gui::GuiVariant::Nsh || cfg!(target_os = "linux"),
|
||||
"Native Shell is available only on Linux"
|
||||
);
|
||||
let app = App::new(Arc::new(credential), credential_lease, &self.gui_version, variant);
|
||||
|
||||
env_utils::patch_gui_runtime_env(false);
|
||||
|
||||
|
||||
@@ -41,10 +41,20 @@ const GUI_LIBC_SUFFIX: &str = "-musl";
|
||||
#[cfg(not(target_env = "musl"))]
|
||||
const GUI_LIBC_SUFFIX: &str = "";
|
||||
|
||||
fn gui_asset_name() -> Option<String> {
|
||||
fn gui_asset_name(variant: gpapi::gui::GuiVariant) -> Option<String> {
|
||||
if variant == gpapi::gui::GuiVariant::Nsh {
|
||||
return nsh_asset_name_for(std::env::consts::OS, std::env::consts::ARCH);
|
||||
}
|
||||
gui_asset_name_for(std::env::consts::OS, std::env::consts::ARCH, GUI_LIBC_SUFFIX)
|
||||
}
|
||||
|
||||
fn nsh_asset_name_for(os: &str, arch: &str) -> Option<String> {
|
||||
match (os, arch) {
|
||||
("linux", "x86_64" | "aarch64") => Some(format!("gpgui-nsh_{arch}.bin.tar.xz")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn gui_asset_name_for(os: &str, arch: &str, libc_suffix: &str) -> Option<String> {
|
||||
let name = match (os, arch) {
|
||||
("linux", "x86_64" | "aarch64") => format!("gpgui_{arch}{libc_suffix}.bin.tar.xz"),
|
||||
@@ -97,10 +107,11 @@ impl Installer {
|
||||
Self { command_tx }
|
||||
}
|
||||
|
||||
async fn install(&self, path: &str, checksum: &str) -> anyhow::Result<()> {
|
||||
async fn install(&self, path: &str, checksum: &str, variant: gpapi::gui::GuiVariant) -> anyhow::Result<()> {
|
||||
let request = UpdateGuiRequest {
|
||||
path: path.to_string(),
|
||||
checksum: checksum.to_string(),
|
||||
variant,
|
||||
};
|
||||
let (reply, result) = oneshot::channel();
|
||||
self
|
||||
@@ -363,6 +374,7 @@ async fn receive_binary(socket: &mut Socket) -> anyhow::Result<Vec<u8>> {
|
||||
|
||||
pub struct GuiUpdater {
|
||||
version: String,
|
||||
variant: gpapi::gui::GuiVariant,
|
||||
notifier: Arc<ProgressNotifier>,
|
||||
installer: Installer,
|
||||
in_progress: RwLock<bool>,
|
||||
@@ -370,9 +382,15 @@ pub struct GuiUpdater {
|
||||
}
|
||||
|
||||
impl GuiUpdater {
|
||||
pub fn new(version: String, notifier: ProgressNotifier, installer: Installer) -> Self {
|
||||
pub fn new(
|
||||
version: String,
|
||||
notifier: ProgressNotifier,
|
||||
installer: Installer,
|
||||
variant: gpapi::gui::GuiVariant,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
variant,
|
||||
notifier: Arc::new(notifier),
|
||||
installer,
|
||||
in_progress: Default::default(),
|
||||
@@ -381,7 +399,7 @@ impl GuiUpdater {
|
||||
}
|
||||
|
||||
pub async fn update(&self) {
|
||||
let Some(asset_name) = gui_asset_name() else {
|
||||
let Some(asset_name) = gui_asset_name(self.variant) else {
|
||||
info!("GUI updates are not supported on this platform.");
|
||||
return;
|
||||
};
|
||||
@@ -438,7 +456,7 @@ impl GuiUpdater {
|
||||
|
||||
info!("Checksum success");
|
||||
|
||||
if let Err(err) = self.installer.install(&file_path, &checksum).await {
|
||||
if let Err(err) = self.installer.install(&file_path, &checksum, self.variant).await {
|
||||
warn!("Install error: {}", err);
|
||||
self.notify_error();
|
||||
} else {
|
||||
@@ -488,13 +506,10 @@ impl GuiUpdater {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use gpapi::{
|
||||
os_profile::HostIdentity,
|
||||
service::{
|
||||
transport::{ClientPrelude, NoiseResponder},
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
},
|
||||
use gpapi::service::{
|
||||
transport::{ClientPrelude, NoiseResponder},
|
||||
vpn_env::{HostInfo, VpnEnv},
|
||||
vpn_state::VpnState,
|
||||
};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::accept_async;
|
||||
@@ -522,6 +537,21 @@ mod tests {
|
||||
assert_eq!(gui_asset_name_for("macos", "aarch64", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsh_assets_are_linux_only_and_use_the_nsh_binary_archive() {
|
||||
assert_eq!(
|
||||
nsh_asset_name_for("linux", "x86_64"),
|
||||
Some("gpgui-nsh_x86_64.bin.tar.xz".into())
|
||||
);
|
||||
assert_eq!(
|
||||
nsh_asset_name_for("linux", "aarch64"),
|
||||
Some("gpgui-nsh_aarch64.bin.tar.xz".into())
|
||||
);
|
||||
for os in ["freebsd", "openbsd", "macos"] {
|
||||
assert_eq!(nsh_asset_name_for(os, "x86_64"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pending_install_reconnects_with_a_fresh_handshake() {
|
||||
let credential = Arc::new(SessionCredential::generate(Uuid::new_v4(), env!("CARGO_PKG_VERSION")).unwrap());
|
||||
@@ -532,6 +562,7 @@ mod tests {
|
||||
request: UpdateGuiRequest {
|
||||
path: "/tmp/gpgui-update".to_owned(),
|
||||
checksum: "checksum".to_owned(),
|
||||
variant: gpapi::gui::GuiVariant::Tauri,
|
||||
},
|
||||
reply: reply_tx,
|
||||
})
|
||||
|
||||
@@ -17,7 +17,9 @@ use tokio::io::unix::AsyncFd;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::session_registry::SessionRegistry;
|
||||
use gpapi::service::transport::{DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY};
|
||||
use gpapi::service::transport::{
|
||||
DESKTOP_GUI_EXITED, DESKTOP_RENDERING_RETRY, DESKTOP_SWITCH_BEGIN, DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_COMMIT,
|
||||
};
|
||||
|
||||
/// Private parent/service pipes; credentials never pass through argv, environment or files.
|
||||
pub(crate) struct DesktopClient {
|
||||
@@ -62,15 +64,38 @@ impl DesktopClient {
|
||||
let mut rendering_renewed = false;
|
||||
loop {
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
|
||||
let session_id = credential.session_id();
|
||||
let mut session_id = credential.session_id();
|
||||
let mut pending = None;
|
||||
let result = tokio::select! {
|
||||
_ = cancel.cancelled() => Ok(None),
|
||||
result = async {
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
self.gui_exited().await
|
||||
loop {
|
||||
match self.gui_exited().await? {
|
||||
Some(DESKTOP_SWITCH_BEGIN) => {
|
||||
ensure!(pending.is_none(), "A GUI switch is already pending");
|
||||
let credential = registry.issue(env!("CARGO_PKG_VERSION"), Some(uid))?;
|
||||
pending = Some(credential.session_id());
|
||||
self.write_frame(&credential.encode_frame()?).await?;
|
||||
}
|
||||
Some(DESKTOP_SWITCH_COMMIT) => {
|
||||
let replacement = pending.take().context("No GUI switch is pending")?;
|
||||
registry.revoke(session_id);
|
||||
session_id = replacement;
|
||||
}
|
||||
Some(DESKTOP_SWITCH_CANCEL) => {
|
||||
let replacement = pending.take().context("No GUI switch is pending")?;
|
||||
registry.revoke(replacement);
|
||||
}
|
||||
message => break Ok(message),
|
||||
}
|
||||
}
|
||||
} => result,
|
||||
};
|
||||
registry.revoke(session_id);
|
||||
if let Some(session_id) = pending {
|
||||
registry.revoke(session_id);
|
||||
}
|
||||
let requested = restart.swap(false, Ordering::SeqCst);
|
||||
match result? {
|
||||
None => return Ok(()),
|
||||
@@ -253,6 +278,39 @@ mod tests {
|
||||
assert!(registry.last_successful_hip_report(issued.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switch_cancel_preserves_current_session_and_commit_replaces_it() {
|
||||
let (channel, control, reader) = pipes();
|
||||
let registry = Arc::new(SessionRegistry::for_tests(uuid::Uuid::new_v4()));
|
||||
let task = tokio::spawn(channel.serve(
|
||||
registry.clone(),
|
||||
1000,
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
CancellationToken::new(),
|
||||
));
|
||||
let (reader, first) = credential(reader).await;
|
||||
write(&control, &[DESKTOP_SWITCH_BEGIN]).unwrap();
|
||||
let (reader, cancelled) = credential(reader).await;
|
||||
assert_ne!(first.session_id(), cancelled.session_id());
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_ok());
|
||||
write(&control, &[DESKTOP_SWITCH_CANCEL, DESKTOP_SWITCH_BEGIN]).unwrap();
|
||||
let (reader, replacement) = credential(reader).await;
|
||||
assert!(registry.last_successful_hip_report(cancelled.session_id()).is_err());
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_ok());
|
||||
write(&control, &[DESKTOP_SWITCH_COMMIT, DESKTOP_SWITCH_BEGIN]).unwrap();
|
||||
let (_, pending) = credential(reader).await;
|
||||
assert!(registry.last_successful_hip_report(first.session_id()).is_err());
|
||||
assert!(registry.last_successful_hip_report(replacement.session_id()).is_ok());
|
||||
drop(control);
|
||||
tokio::time::timeout(Duration::from_secs(1), task)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(registry.last_successful_hip_report(replacement.session_id()).is_err());
|
||||
assert!(registry.last_successful_hip_report(pending.session_id()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn desktop_channel_rejects_invalid_control_messages_and_revokes() {
|
||||
let (channel, control, reader) = pipes();
|
||||
|
||||
@@ -6,7 +6,6 @@ use std::{
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
};
|
||||
|
||||
use common::binary_paths;
|
||||
use gpapi::{
|
||||
service::{
|
||||
request::{UpdateGuiRequest, UpdateLogLevelRequest, WsRequest},
|
||||
@@ -299,10 +298,17 @@ impl RequestDispatcher {
|
||||
}
|
||||
|
||||
async fn update_gui(&self, request: UpdateGuiRequest) -> ServiceResult {
|
||||
if request.variant == gpapi::gui::GuiVariant::Nsh && !cfg!(target_os = "linux") {
|
||||
return ServiceResult::rejected(
|
||||
ServiceErrorCode::InvalidRequest,
|
||||
"Native Shell is available only on Linux",
|
||||
);
|
||||
}
|
||||
let _install = self.install_lock.lock().await;
|
||||
let path = request.path;
|
||||
let checksum = request.checksum;
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui(&path, &checksum)).await;
|
||||
let target = request.variant.update_target();
|
||||
let installed = tokio::task::spawn_blocking(move || install_gui_at(Path::new(&path), &checksum, &target)).await;
|
||||
match installed {
|
||||
Ok(Ok(())) => ServiceResult::Accepted,
|
||||
Ok(Err(GuiInstallError::Checksum(err))) => {
|
||||
@@ -327,10 +333,6 @@ enum GuiInstallError {
|
||||
Install(anyhow::Error),
|
||||
}
|
||||
|
||||
fn install_gui(src: &str, checksum: &str) -> Result<(), GuiInstallError> {
|
||||
install_gui_at(Path::new(src), checksum, &binary_paths::gpgui_update_target())
|
||||
}
|
||||
|
||||
fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiInstallError> {
|
||||
let Some(dir) = target.parent() else {
|
||||
return Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
@@ -350,7 +352,8 @@ fn install_gui_at(src: &Path, checksum: &str, target: &Path) -> Result<(), GuiIn
|
||||
))
|
||||
.take(MAX_GUI_ARCHIVE_CONTENT_SIZE);
|
||||
let mut archive = Archive::new(tar);
|
||||
let file = extract_gui_binary(&mut archive, dir)?;
|
||||
let binary_name = target.file_name().and_then(|name| name.to_str()).unwrap_or("gpgui");
|
||||
let file = extract_gui_binary(&mut archive, dir, binary_name)?;
|
||||
file
|
||||
.as_file()
|
||||
.set_permissions(Permissions::from_mode(0o755))
|
||||
@@ -398,14 +401,18 @@ fn stage_gui_archive(src: &Path, dir: &Path) -> Result<NamedTempFile, GuiInstall
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<NamedTempFile, GuiInstallError> {
|
||||
fn extract_gui_binary<R: Read>(
|
||||
archive: &mut Archive<R>,
|
||||
dir: &Path,
|
||||
binary_name: &str,
|
||||
) -> Result<NamedTempFile, GuiInstallError> {
|
||||
for entry in archive.entries().map_err(|err| GuiInstallError::Install(err.into()))? {
|
||||
let mut entry = entry.map_err(|err| GuiInstallError::Install(err.into()))?;
|
||||
let is_gui = entry
|
||||
.path()
|
||||
.map_err(|err| GuiInstallError::Install(err.into()))?
|
||||
.file_name()
|
||||
.is_some_and(|name| name == "gpgui");
|
||||
.is_some_and(|name| name == binary_name);
|
||||
if is_gui && entry.header().entry_type().is_file() {
|
||||
let declared_size = entry.size();
|
||||
if declared_size == 0 || declared_size > MAX_GUI_BINARY_SIZE {
|
||||
@@ -425,7 +432,7 @@ fn extract_gui_binary<R: Read>(archive: &mut Archive<R>, dir: &Path) -> Result<N
|
||||
}
|
||||
}
|
||||
Err(GuiInstallError::Install(anyhow::anyhow!(
|
||||
"GUI update archive does not contain a non-empty regular gpgui file"
|
||||
"GUI update archive does not contain a non-empty regular {binary_name} file"
|
||||
)))
|
||||
}
|
||||
|
||||
@@ -475,7 +482,7 @@ mod tests {
|
||||
for (entry_type, contents) in [(EntryType::Directory, &[][..]), (EntryType::Regular, &[][..])] {
|
||||
let data = archive_with_entry(entry_type, contents);
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -484,7 +491,7 @@ mod tests {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let data = archive_with_entry(EntryType::Regular, b"gui binary");
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
let extracted = extract_gui_binary(&mut archive, output.path()).unwrap();
|
||||
let extracted = extract_gui_binary(&mut archive, output.path(), "gpgui").unwrap();
|
||||
let contents = std::fs::read(extracted.path()).unwrap();
|
||||
assert_eq!(contents, b"gui binary");
|
||||
}
|
||||
@@ -515,7 +522,7 @@ mod tests {
|
||||
data.resize(512 * 3, 0);
|
||||
|
||||
let mut archive = Archive::new(Cursor::new(data));
|
||||
assert!(extract_gui_binary(&mut archive, output.path()).is_err());
|
||||
assert!(extract_gui_binary(&mut archive, output.path(), "gpgui").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -531,6 +538,33 @@ mod tests {
|
||||
assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o755);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_nsh_beside_tauri_without_replacing_it() {
|
||||
let output = tempfile::tempdir().unwrap();
|
||||
let tauri = output.path().join("gpgui");
|
||||
std::fs::write(&tauri, b"tauri").unwrap();
|
||||
let mut encoder = XzEncoder::new(Vec::new(), 1);
|
||||
{
|
||||
let mut archive = Builder::new(&mut encoder);
|
||||
let mut header = Header::new_gnu();
|
||||
header.set_size(3);
|
||||
header.set_mode(0o755);
|
||||
header.set_cksum();
|
||||
archive
|
||||
.append_data(&mut header, "gpgui-nsh_3.2.0/gpgui-nsh", &b"nsh"[..])
|
||||
.unwrap();
|
||||
archive.finish().unwrap();
|
||||
}
|
||||
let mut archive = NamedTempFile::new().unwrap();
|
||||
archive.write_all(&encoder.finish().unwrap()).unwrap();
|
||||
archive.flush().unwrap();
|
||||
let checksum = gpapi::utils::checksum::file_sha256(archive.path()).unwrap();
|
||||
let nsh = output.path().join("gpgui-nsh");
|
||||
install_gui_at(archive.path(), &checksum, &nsh).unwrap();
|
||||
assert_eq!(std::fs::read(nsh).unwrap(), b"nsh");
|
||||
assert_eq!(std::fs::read(tauri).unwrap(), b"tauri");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checksum_failure_preserves_the_existing_gui() {
|
||||
let archive = compressed_gui_archive(b"replacement");
|
||||
|
||||
@@ -763,6 +763,7 @@ mod tests {
|
||||
request: WsRequest::UpdateGui(UpdateGuiRequest {
|
||||
path: update_file.path().to_string_lossy().into_owned(),
|
||||
checksum: "invalid".to_owned(),
|
||||
variant: gpapi::gui::GuiVariant::Tauri,
|
||||
}),
|
||||
};
|
||||
socket
|
||||
|
||||
@@ -8,6 +8,7 @@ license = "MIT"
|
||||
[dependencies]
|
||||
nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true }
|
||||
common = { path = "../common" }
|
||||
directories.workspace = true
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
dns-lookup = { workspace = true, optional = true }
|
||||
|
||||
@@ -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\"");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
Reference in new issue
Block a user