Repository navigation
fix(agent): launch at login from the Flatpak through the Background portal #2734
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vintoware
wants to merge
3
commits into
AprilNEA:master
Choose a base branch
from
vintoware:fix/flatpak-autostart-portal
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| } | ||
| } | ||
|
|
||
| /// [`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"); | ||
|
vintoware marked this conversation as resolved.
Resolved
|
||
| } | ||
| } | ||
15 changes: 15 additions & 0 deletions
15
crates/openlogi-core/.ast-grep/rules/core-flatpak-sandbox-owner.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.