Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion crates/openlogi-agent/src/autostart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
//! `config.toml` therefore takes effect the next time the GUI runs.
//! - **Linux** ([`linux`]): a systemd **user** unit, written/removed and
//! `systemctl --user` enabled/disabled. `Restart=on-failure` mirrors the
//! macOS service's `KeepAlive = {SuccessfulExit: false}` semantics.
//! macOS service's `KeepAlive = {SuccessfulExit: false}` semantics. Inside a
//! Flatpak, which can reach neither, the XDG Background portal's `autostart`
//! request instead — login launch only, as on Windows.
//! - **Windows** ([`windows`]): an `HKCU\…\Run` registry value — login launch
//! only, no crash respawn.
//!
Expand Down
32 changes: 27 additions & 5 deletions crates/openlogi-agent/src/autostart/linux.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
//! Linux systemd user-unit ownership and autostart reconciliation.
//!
//! Inside a Flatpak none of this applies: the sandbox has no `systemctl`, and
//! the host's systemd never reads the sandbox's `$XDG_DATA_HOME`. [`portal`]
//! takes over there, sharing only the enablement claim described below.
//!
//! When a packaged unit already launches this exact binary — installed by a
//! distribution package, `install.sh`, or an administrator — it is simply
//! enabled. Generating a second copy would duplicate its directives one tier
Expand Down Expand Up @@ -36,11 +40,17 @@ use std::path::{Path, PathBuf};

use tracing::{debug, info, warn};

mod portal;

/// Reconcile the agent's autostart state with `enabled`.
///
/// Idempotent; failures are logged, not propagated — startup must not abort
/// because an autostart directory is read-only or systemd is unavailable.
pub(super) fn reconcile(enabled: bool) {
if openlogi_core::sandbox::is_flatpak() {
portal::reconcile(enabled);
return;
}
if let Err(e) = apply(enabled) {
warn!(error = %e, enabled, "agent systemd unit reconcile failed");
}
Expand Down Expand Up @@ -220,6 +230,12 @@ fn enablement_marker_path() -> io::Result<PathBuf> {
}

/// Enable the unit and record that this app is the one that did.
fn enable_unit() {
claim_enablement(|| run_systemctl(&["enable", UNIT_NAME]));
}

/// Run `enable`, the step that turns autostart on, under this app's claim on
/// the enablement.
///
/// The claim is recorded *before* enabling. An enablement this app cannot
/// record is one a later reconcile could never withdraw, leaving autostart
Expand All @@ -232,11 +248,11 @@ fn enablement_marker_path() -> io::Result<PathBuf> {
/// Claiming an enablement the user made by hand is deliberate: reaching the
/// toggle at all is an explicit request for this app to manage autostart, and
/// the setting has to mean what it says when it is switched back off.
fn enable_unit() {
fn claim_enablement(enable: impl FnOnce() -> bool) {
let Ok(marker) = enablement_marker_path() else {
return;
};
enable_unit_with(&marker, || run_systemctl(&["enable", UNIT_NAME]));
enable_unit_with(&marker, enable);
}

/// The ordering and rollback rules of [`enable_unit`], over an injectable
Expand Down Expand Up @@ -296,21 +312,27 @@ fn record_enablement_at(path: &Path) -> io::Result<bool> {
}
}

/// Withdraw the enablement only when this app recorded making it.
/// Disable the unit, if this app is the one that enabled it.
fn disable_unit_if_ours() {
withdraw_enablement(|| run_systemctl(&["disable", UNIT_NAME]));
}

/// Run `disable`, the step that turns autostart off, only when this app
/// recorded making the enablement.
///
/// A missing marker means the enablement came from somewhere else — the
/// install instructions, another tool, the user — and is not ours to remove.
/// Losing the marker therefore fails safe: autostart keeps working, and the
/// user can still turn it off the way they turned it on.
fn disable_unit_if_ours() {
fn withdraw_enablement(disable: impl FnOnce() -> bool) {
let Ok(marker) = enablement_marker_path() else {
return;
};
if !marker.exists() {
debug!("autostart enablement was not made by OpenLogi; leaving it alone");
return;
}
if !run_systemctl(&["disable", UNIT_NAME]) {
if !disable() {
// Keep the marker so the next reconcile retries rather than stranding
// an enablement this app is still responsible for.
return;
Expand Down
230 changes: 230 additions & 0 deletions crates/openlogi-agent/src/autostart/linux/portal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
//! Autostart from inside a Flatpak, through the XDG Background portal.
//!
//! The systemd arm cannot work in the sandbox: there is no `systemctl` to
//! enable a unit with, and the unit it writes lands in the sandbox's
//! `$XDG_DATA_HOME` (`~/.var/app/<id>/data`), which the host's systemd never
//! reads. The portal is the sandbox's own route instead. `RequestBackground`
//! with `autostart` set has the host write `~/.config/autostart/<id>.desktop`,
//! which launches `commandline` inside this app's sandbox at login; with
//! `autostart` cleared, it removes that file again. It is login launch only,
//! with no crash respawn — the same as on Windows.
//!
//! Enablement goes through the claim the systemd arm keeps, so a disabled
//! setting reaches the portal only to withdraw an autostart this app asked
//! for. That keeps more than tidiness: a desktop may ask the user whether the
//! app may run in the background the first time it requests anything, and a
//! user who never turned the setting on must not be asked.
//!
//! Only the request is awaited, not the user's answer. Reconcile runs at agent
//! startup and inside the `reload_config` RPC, and neither may wait on a
//! person; the answer is logged when it arrives. A refusal is the portal's to
//! remember, so asking again later does not ask the user again.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;

use tracing::{debug, info, warn};
use zbus::blocking::Connection;
use zbus::proxy;
use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Value};

/// Shown by desktops that ask the user before granting the request.
const REASON: &str =
"Start the OpenLogi agent at login so your device settings apply without opening the app.";

#[proxy(
interface = "org.freedesktop.portal.Background",
default_service = "org.freedesktop.portal.Desktop",
default_path = "/org/freedesktop/portal/desktop",
gen_blocking = true
)]
trait Background {
fn request_background(
&self,
parent_window: &str,
options: HashMap<&str, Value<'_>>,
) -> zbus::Result<OwnedObjectPath>;
}

#[proxy(
interface = "org.freedesktop.portal.Request",
default_service = "org.freedesktop.portal.Desktop",
gen_blocking = true
)]
trait Request {
#[zbus(signal)]
fn response(&self, response: u32, results: HashMap<String, OwnedValue>) -> zbus::Result<()>;
}

/// Reconcile the portal autostart with `enabled`.
pub(super) fn reconcile(enabled: bool) {
if enabled {
let exe = match std::env::current_exe() {
Ok(exe) => exe,
Err(error) => {
warn!(%error, "cannot resolve the agent executable; leaving autostart unchanged");
return;
}
};
super::claim_enablement(|| request_once(Some(&exe)));
} else {
super::withdraw_enablement(|| request_once(None));
Comment thread
vintoware marked this conversation as resolved.
Resolved
}
}

/// [`request`], skipped when this process last asked for the same state.
///
/// Every settings save reloads the config and reconciles again. The first
/// request may still have a dialog in front of the user, and repeating it
/// would stack a second one behind it. A new process asks again, which is what
/// restores an autostart file the user deleted by hand.
fn request_once(autostart: Option<&Path>) -> bool {
static LAST: Mutex<Option<bool>> = Mutex::new(None);
let mut last = LAST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let wanted = autostart.is_some();
if *last == Some(wanted) {
debug!(
autostart = wanted,
"Background portal already asked this session"
);
return true;
}
let sent = request(autostart);
if sent {
*last = Some(wanted);
}
sent
}

/// Ask the portal to launch `autostart` at login, or with `None` to stop.
///
/// `true` once the portal has accepted the request; its outcome is logged
/// from a helper thread when the portal answers.
fn request(autostart: Option<&Path>) -> bool {
match send(autostart) {
Ok(()) => true,
Err(error) => {
warn!(%error, autostart = autostart.is_some(), "Background portal request failed");
false
}
}
}

fn send(autostart: Option<&Path>) -> zbus::Result<()> {
let connection = Connection::session()?;
let token = handle_token();
let handle = request_path(&connection, &token)?;
// Subscribe before asking, or a portal that answers at once (no dialog)
// could send the response before anything is listening for it.
let mut responses = RequestProxyBlocking::builder(&connection)
.path(handle)?
.build()?
.receive_response()?;

let mut options = HashMap::from([
("handle_token", Value::from(token.as_str())),
("reason", Value::from(REASON)),
("autostart", Value::from(autostart.is_some())),
]);
if let Some(exe) = autostart {
options.insert(
"commandline",
Value::from(vec![exe.to_string_lossy().into_owned()]),
);
}
BackgroundProxyBlocking::new(&connection)?.request_background("", options)?;
debug!(
autostart = autostart.is_some(),
"Background portal request sent"
);

// The portal cancels a request whose sender leaves the bus, so the
// connection stays open, held by the iterator, until the answer arrives.
let wanted = autostart.is_some();
let spawned = thread::Builder::new()
.name("openlogi-autostart-portal".into())
.spawn(move || {
let Some(signal) = responses.next() else {
debug!("Background portal response stream ended without an answer");
return;
};
match signal.args() {
Ok(args) => log_response(wanted, *args.response(), args.results()),
Err(error) => warn!(%error, "unreadable Background portal response"),
}
});
if let Err(error) = spawned {
// The request is out already; only its answer goes unlogged.
warn!(%error, "could not wait for the Background portal response");
}
Ok(())
}

/// A token unique within this connection, as the portal's `handle_token`
/// requires: object-path-element characters only.
fn handle_token() -> String {
static NEXT: AtomicU32 = AtomicU32::new(0);
format!(
"openlogi_autostart_{}_{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
)
}

/// The object path the portal will give the request with `token`, known in
/// advance so the response can be subscribed to before the call is made.
fn request_path(connection: &Connection, token: &str) -> zbus::Result<ObjectPath<'static>> {
let unique = connection
.unique_name()
.ok_or_else(|| zbus::Error::Failure("session bus connection has no unique name".into()))?;
let sender = sender_path_element(unique.as_str());
Ok(ObjectPath::try_from(format!(
"/org/freedesktop/portal/desktop/request/{sender}/{token}"
))?)
}

/// A unique bus name as the portal spells it in a request path: `:1.42`
/// becomes `1_42`.
fn sender_path_element(unique: &str) -> String {
unique.trim_start_matches(':').replace('.', "_")
}

fn log_response(wanted: bool, response: u32, results: &HashMap<String, OwnedValue>) {
let granted = |key: &str| {
results
.get(key)
.and_then(|value| bool::try_from(value).ok())
};
match response {
0 => info!(
requested = wanted,
autostart = ?granted("autostart"),
background = ?granted("background"),
"Background portal answered",
),
1 => warn!(
requested = wanted,
"the user declined the Background portal request"
),
_ => warn!(
requested = wanted,
response, "the Background portal request did not complete"
),
}
}

#[cfg(test)]
mod tests {
use super::sender_path_element;

#[test]
fn sender_path_element_matches_the_portal_spelling() {
assert_eq!(sender_path_element(":1.42"), "1_42");
assert_eq!(sender_path_element(":1.1024"), "1_1024");
Comment thread
vintoware marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Owner: openlogi_core::sandbox — whether this process runs inside a Flatpak.
id: core-flatpak-sandbox-owner
language: rust
severity: error
message: Whether this process runs inside a Flatpak is openlogi_core::sandbox::is_flatpak's to answer; call it instead of probing /.flatpak-info here.
note: |
The udev remedy and the agent's autostart both branch on the sandbox. See
"Single source of truth" in AGENTS.md.
files:
- crates/**/*.rs
- xtask/**/*.rs
ignores:
- crates/openlogi-core/**
rule:
pattern: '"/.flatpak-info"'
15 changes: 9 additions & 6 deletions crates/openlogi-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
//! `hidpp`, `async-hid`, or any platform-specific event/window API; those live
//! in sibling crates.
//!
//! The exceptions are feature-gated: reading and writing that config file
//! (`fs`) and locale negotiation (`locale`), which reads the host's language
//! preference, both on by default; and, off by default, the dedicated tokio
//! worker thread the host crates run async work on (`worker`) and the `tracing`
//! filter every process installs (`logging`). Without them this crate touches
//! no host at all, which is what the `wasm (portable crates)` CI job checks.
//! The exceptions are feature-gated: reading and writing that config file and
//! probing the sandbox this process runs in (`fs`), and locale negotiation
//! (`locale`), which reads the host's language preference, both on by default;
//! and, off by default, the dedicated tokio worker thread the host crates run
//! async work on (`worker`) and the `tracing` filter every process installs
//! (`logging`). Without them this crate touches no host at all, which is what
//! the `wasm (portable crates)` CI job checks.

#![deny(missing_docs)]

Expand All @@ -32,6 +33,8 @@ pub mod locale;
pub mod logging;
#[cfg(feature = "fs")]
pub mod paths;
#[cfg(feature = "fs")]
pub mod sandbox;
pub mod scroll;
#[cfg(feature = "fs")]
pub mod single_instance;
Expand Down
18 changes: 18 additions & 0 deletions crates/openlogi-core/src/sandbox.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//! Whether this process runs inside an application sandbox.
//!
//! Several Linux integrations take a different route from inside a Flatpak:
//! the sandbox has no host `/etc`, no `pkexec`, no `systemctl`, and its
//! `$XDG_*_HOME` point into `~/.var/app/<id>/`, which the host never reads.
//! The check is answered here once so every such integration asks the same
//! question the same way.

use std::path::Path;

/// Whether this process runs inside a Flatpak sandbox.
///
/// `flatpak run` mounts `/.flatpak-info` into every sandbox it creates, and
/// nothing else does, which makes it the documented test.
#[must_use]
pub fn is_flatpak() -> bool {
Path::new("/.flatpak-info").exists()
}
Loading