foghorn/leghorn
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-10-23 20:02:15 +02:00
..
src fmt 2026-10-23 20:02:15 +02:00
tests fmt 2026-10-23 20:02:15 +02:00
Cargo.toml Leghorn: require https, make the fallback gateway optional, add forget and wake holds. 2026-10-09 08:35:54 +02:00
LICENSE Leghorn + foghorn-common: MPL license. 2026-10-08 08:56:26 +02:00
README.md Deslop, son. I said, deslop. Boy don't listen. 2026-10-18 21:20:29 +02:00

Leghorn

"That's a push, son. A push. Ya got your message whether ya asked for it or not."

— Foghorn Leghorn, probably

UnifiedPush for Sailfish OS applications written in Rust. It implements the connector side of the protocol and handles the SailJail and D-Bus requirements described in docs/connectors.md. Any UnifiedPush distributor works; on Sailfish that usually means Foghorn.

[dependencies]
leghorn = { git = "https://git.agnos.is/projectmoon/foghorn.git" }

Leghorn uses zbus with its tokio feature and runs its own tokio runtime, so the app does not need one. The unifiedpush crate is incompatible with this configuration: its D-Bus handlers panic when zbus uses the tokio feature.

Usage

Define a configuration and a push handler, then add #[leghorn::main] to the application's main function:

use leghorn::Event;

const PUSH: leghorn::Config = leghorn::Config::new("org.example", "MyApp");

#[leghorn::main(config = PUSH, push = on_push)]
fn main() {
    // normal GUI startup
}

async fn on_push(event: Event) -> anyhow::Result<()> {
    match event {
        Event::NewEndpoint(endpoint) => { /* register it with the app's server */ }
        Event::Message(payload) => { /* store it, show a notification */ }
        Event::Raw(payload) => { /* a push that was not encrypted for you */ }
        Event::Unregistered => { /* fall back to polling */ }
        Event::Failed(error) => { /* report an enable() or disable() error */ }
    }
    Ok(())
}

When the user turns push on or off, call leghorn::enable() or leghorn::disable() from anywhere in the app. Both functions return immediately. The push handler receives the resulting events, including any errors as Event::Failed.

Config::new takes the desktop file's OrganizationName and ApplicationName. SailJail only persists ~/.local/share/<org>/<app>/, and Leghorn keeps its state there in leghorn.json. The connector name defaults to org.unifiedpush.Connector.<app>, and Config::connector_name overrides it. Config::description sets the name the distributor shows for the app, which otherwise is ApplicationName. wake_env sets the environment variable used to identify a push launch; the default is LEGHORN_PUSH_WAKE. wake_timeout sets how long a process started by a push waits for its first event. The default is 25 seconds.

Application startup

#[leghorn::main] first applies the D-Bus workaround Sailfish releases before 5.1 need, then checks for the LEGHORN_PUSH_WAKE variable. When a push started the process, it runs the push handler and exits without running the rest of main, so no window opens. Otherwise it starts Leghorn on a background thread with the same handler and then runs main as normal. While the app is open it owns the connector name, so pushes go to it rather than starting a second copy. If push is enabled, Leghorn renews the registration with the existing token on every launch. If the app is launched while another instance is handling a push, GUI startup waits for that instance to finish.

Use an init function for setup required by both normal and push launches, such as logging. It runs before the wake check: #[leghorn::main(config = PUSH, push = on_push, init = setup_logging)]. It must not start threads. Without the macro, leghorn::run(&PUSH, on_push, || gui()) at the top of main does the same thing, after any such setup.

Handling events

The handler receives every event, whether the app is open or was started by the push. It runs on Leghorn's thread. Dispatch UI updates to the Qt thread using the application's threading mechanism.

Handle NewEndpoint by registering the endpoint with the application's server. It arrives after the first enable, and again whenever the distributor rotates the endpoint. Its Display form is url|p256dh|auth, with the keys base64url-encoded; send all three, since Web Push bodies must be encrypted. A woken process may not be in a state to finish that registration. Returning Err does not cause Leghorn to redeliver NewEndpoint, so save the endpoint and retry from the app if the server call fails.

Payloads arrive decrypted as Message. If decryption with the app's keys fails, the handler receives the original payload as Raw. Return Err from a Message and the distributor delivers it again later. The handler timeout is 7 seconds, leaving one second before Foghorn's 8-second D-Bus call timeout.

Failed reports errors from background operations such as leghorn::enable() and leghorn::disable(). With one distributor installed, enable uses it. With several, the handler gets Error::ChooseDistributor with their names: show them to the user, call leghorn::select with the choice, then enable again. $UNIFIEDPUSH_DISTRIBUTOR picks one without asking. A second application instance receives Error::AlreadyRunning through the same handler.

leghorn::endpoint() returns the saved endpoint while push is enabled, and leghorn::distributor() the distributor in use. disable unregisters and forgets the token and keys, so the old endpoint stops working. forget also deletes leghorn.json. forget_stored does that without a running connector. leghorn::enabled reads the saved state without creating files or claiming the name, so an app can skip starting Leghorn while push is off.

Endpoints must be https. Others are refused with Error::InsecureEndpoint, sent as a Failed event.

Using your own runtime

An app that wants to drive Leghorn from its own tokio runtime can skip the macro and call start instead. Use either the macro or start. Calling both attempts to claim the connector name twice and returns Error::AlreadyRunning. The app then has to do what the macro would, in the same order:

use std::sync::Arc;

use leghorn::{Error, Event, Leghorn};
use tokio::runtime::{Handle, Runtime};

const PUSH: leghorn::Config = leghorn::Config::new("org.example", "MyApp");

fn main() -> anyhow::Result<()> {
    leghorn::prelude();
    setup_logging();

    if leghorn::is_wake(&PUSH) {
        leghorn::run_wake(&PUSH, on_push);
        return Ok(());
    }

    let runtime = Runtime::new()?;
    let push = Arc::new(runtime.block_on(leghorn::start(&PUSH, on_push))?);
    run_gui(runtime.handle(), push);
    Ok(())
}

async fn on_push(event: Event) -> anyhow::Result<()> {
    match event {
        Event::NewEndpoint(endpoint) => send_to_server(&endpoint.to_string()).await?,
        Event::Message(payload) => show_notification(&payload),
        _ => {}
    }
    Ok(())
}

// Wired to the push switch in the settings page.
fn on_push_switch(runtime: &Handle, push: Arc<Leghorn>, on: bool) {
    runtime.spawn(async move {
        if let Err(error) = set_push(&push, on).await {
            show_error(&error);
        }
    });
}

async fn set_push(push: &Leghorn, on: bool) -> leghorn::Result<()> {
    if !on {
        return push.disable().await;
    }
    match push.enable().await {
        Err(Error::ChooseDistributor(names)) => {
            push.select(&ask_user(names).await).await?;
            push.enable().await.map(drop)
        }
        result => result.map(drop),
    }
}

prelude has to run before any thread starts, which rules out #[tokio::main]: its runtime is already up by the time main's body runs. run_wake builds its own runtime and blocks until the pushes are handled, so it also has to be called outside one. leghorn::wake does the same inside the caller's runtime. A Hold keeps the process running and retains the connector's D-Bus name after the handler returns, e.g. while fetching the message, for up to a minute.

Keep the Leghorn that start returns for as long as the app runs; dropping it releases the connector name. enable waits up to 20 seconds for the endpoint and returns it. Operation errors are returned directly as Results instead of being sent to the handler as Failed events. The handler still gets NewEndpoint for the same endpoint. Register with the server from the handler, which also sees later rotations and woken processes; the return value is only useful for the UI. distributors lists the installed distributors, including ones that are not running, and select picks one. endpoint and distributor on the Leghorn read the saved state, like the free functions of the same name.

Matrix

A homeserver can't push to an endpoint directly. It sends to a Matrix push gateway, which forwards to the endpoint. With the matrix feature, Leghorn uses the same gateway discovery process as Element: it checks whether the endpoint's push server provides a Matrix gateway (ntfy, for example, has one built in), and otherwise uses matrix.gateway.unifiedpush.org. Config::matrix_gateway sets a different fallback (https only). Config::matrix_without_fallback removes it, and gateway is None when the push server has none. Config::matrix_device sets a fixed device name and language instead of the hostname and $LANG. Endpoint::matrix_support reports whether the push service provides a Matrix gateway: Yes, No, or Unknown while discovery is incomplete.

leghorn = { git = "https://git.agnos.is/projectmoon/foghorn.git", features = ["matrix"] }
use anyhow::Context;
use leghorn::{matrix::Notification, Event};
use matrix_sdk::ruma::api::client::push::PusherIds;

const PUSH: leghorn::Config = leghorn::Config::new("org.example", "Chatty")
    .matrix("org.example.chatty");

async fn on_push(event: Event) -> anyhow::Result<()> {
    match event {
        Event::NewEndpoint(endpoint) => {
            let pusher = endpoint.matrix.context("no pusher")?;
            client().pusher().set(pusher.convert()?).await?;
            if let Some(old) = pusher.replaces {
                client().pusher().delete(PusherIds::new(old, pusher.app_id)).await?;
            }
        }
        Event::Message(payload) => {
            let note = Notification::from_slice(&payload)?;
            /* fetch note.event_id in note.room_id and show it */
        }
        Event::Unregistered => {
            if let Some(pusher) = leghorn::matrix::last_pusher(&PUSH) {
                client().pusher().delete(pusher.convert()?).await?;
            }
        }
        _ => {}
    }
    Ok(())
}

For Matrix, register the pusher from NewEndpoint with the homeserver instead of registering the endpoint directly. convert turns it into any type that deserializes from the Matrix pusher JSON, such as ruma's Pusher, or PusherIds for matrix-sdk. to_json gives the body for /_matrix/client/v3/pushers/set for apps that make the request themselves. Pushers ask for event_id_only, so the notification carries only IDs and the unread count. When the distributor moves the endpoint, replaces holds the old pushkey to delete.

Gateways send pushes unencrypted, and with matrix set these arrive as Message rather than Raw. A Notification without an event_id only updates the unread count. The gateway check happens before the handler sees NewEndpoint. It makes up to 3 attempts at the push server, taking at most 4 of the handler's 7 seconds.

If the push server doesn't answer, the pusher keeps the gateway it had for that server. For a new pusher, Leghorn uses the configured fallback gateway and sets provisional. If fallback is disabled, the pusher has no gateway. Leghorn logs a warning and retries gateway discovery in the background for about two hours and on each application launch. If the server has a gateway, the handler gets another NewEndpoint with the same pushkey. Register the updated pusher with the homeserver to switch to the discovered gateway.

Packaging

The desktop file needs X-DBusActivatable=true, an ExecDBus identical to Exec (minus %u), and UnifiedPush in Permissions:

[Desktop Entry]
Type=Application
Name=My App
Exec=myapp
X-DBusActivatable=true

[X-Sailjail]
OrganizationName=org.example
ApplicationName=MyApp
ExecDBus=myapp
Permissions=Internet;UnifiedPush

Package a D-Bus activation file for the connector name so a push can start the app when it is closed:

[D-BUS Service]
Name=org.unifiedpush.Connector.MyApp
Exec=/usr/bin/env LEGHORN_PUSH_WAKE=1 /usr/bin/sailjail -p myapp.desktop -- /usr/bin/myapp

Install it from the RPM spec, and list it under %files:

install -Dm 644 rpm/%{name}.push.service \
    %{buildroot}%{_datadir}/dbus-1/services/org.unifiedpush.Connector.MyApp.service

With leghorn-build as a build dependency, a build.rs can generate that file and check the desktop file, failing the build if Exec and ExecDBus differ, a key is missing, or the names don't match the Config. leghorn::Config is leghorn_build::Config, so one PUSH definition can serve both:

leghorn_build::check_desktop_file("rpm/myapp.desktop", &PUSH)?;
leghorn_build::write_service_file("rpm/myapp.push.service", &PUSH, "myapp.desktop", "/usr/bin/myapp")?;

leghorn-build has no dependencies, so the build script stays small. An app that calls Config::matrix turns on leghorn-build's matrix feature there too.

If Config::connector_name is set to the application's own OrganizationName.ApplicationName, omit X-DBusActivatable and ExecDBus. Otherwise SailJail generates a second activation file for the same name, without the wake variable. foghorn-test-connector is set up this way.

After changing Permissions, Exec or ExecDBus on a device, launch the app by hand once. SailJail requires renewed consent, which the user must grant during an interactive launch.

Testing

toot, in this repository, sends a push to an app that has push enabled. It reads the endpoint from the app's leghorn.json over ssh:

cargo run -p toot                          # the first device in `sfdk device list`
cargo run -p toot -- -d phone 'hello'      # any ssh destination
cargo run -p toot -- -a MyApp              # when several apps have push enabled

TOOT_DEVICE sets the default device. The push goes through the real push service, so this tests the whole path, including a closed app being woken.

Connector responsibilities

Leghorn handles the following requirements from docs/connectors.md:

  • setting FLATPAK_ID before any thread starts on Sailfish 5.0, so zbus gets past SailJail's D-Bus proxy
  • the wake branch, taken before any GUI code runs
  • claiming the name and exporting the connector object before registering
  • writing the token and keys to the per-app directory before Register, and never losing them when the distributor is off the bus
  • an endpoint that arrives before the Register reply
  • finding distributors that are installed but not running
  • Web Push decryption, without the ece-native panic on 32-bit devices
  • replying to a message only after the handler has it
  • a lock that keeps the GUI and a push copy from running side by side

License

MPL-2.0, as are leghorn-macros and foghorn-common. See LICENSE. The rest of Foghorn is AGPL-3.0-or-later.