Add Store support and unsigned app releases
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-ipc"
|
||||
description = "Shared types for SmartFox: app manifests, settings and IPC messages"
|
||||
description = "Shared types for Fennec OS: app manifests, settings and IPC messages"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
283
crates/sf-ipc/src/launch.rs
Normal file
283
crates/sf-ipc/src/launch.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! How apps are started: the command line for a web app (Chromium in kiosk or
|
||||
//! app mode with its own profile) or an exec app. Shared by the launcher
|
||||
//! (local testing on a desktop) and sf-core (the TV).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::{AppKind, AppManifest, Settings, paths, sandbox};
|
||||
|
||||
/// Environment variable carrying the app id into the app's processes. The
|
||||
/// compositor reads it from `/proc/<pid>/environ` to tell windows apart.
|
||||
pub const APP_ENV: &str = "SMARTFOX_APP";
|
||||
|
||||
pub struct Browser {
|
||||
pub exe: PathBuf,
|
||||
/// Full version, used to build a realistic user agent.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub fn find_browser() -> Option<Browser> {
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BROWSER") {
|
||||
candidates.push(p.into());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
||||
if let Some(b) = std::env::var_os(base) {
|
||||
let b = PathBuf::from(b);
|
||||
candidates.push(b.join(r"Google\Chrome\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Chromium\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] {
|
||||
for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] {
|
||||
candidates.push(Path::new(dir).join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
let exe = candidates.into_iter().find(|p| p.is_file())?;
|
||||
let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into());
|
||||
Some(Browser { exe, version })
|
||||
}
|
||||
|
||||
fn browser_version(exe: &Path) -> Option<String> {
|
||||
// Windows installs keep a folder named after the version next to the exe.
|
||||
if cfg!(windows) {
|
||||
let dir = exe.parent()?;
|
||||
let mut versions: Vec<String> = std::fs::read_dir(dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::<u32>().is_ok()))
|
||||
.collect();
|
||||
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
|
||||
return versions.pop();
|
||||
}
|
||||
let out = Command::new(exe).arg("--version").output().ok()?;
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn default_user_agent(version: &str) -> String {
|
||||
let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" };
|
||||
let major = version.split('.').next().unwrap_or("141");
|
||||
format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
|
||||
}
|
||||
|
||||
pub struct LaunchOptions<'a> {
|
||||
/// Per-app browser profiles live in `<data_dir>/profiles/<id>`.
|
||||
pub data_dir: &'a Path,
|
||||
pub fullscreen: bool,
|
||||
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
|
||||
pub bounds: Option<(i32, i32, u32, u32)>,
|
||||
/// Extra query string for the start URL (DIAL launch parameters).
|
||||
pub query: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// A program with its arguments and environment, before it is (maybe) put
|
||||
/// into the sandbox.
|
||||
struct Inner {
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps
|
||||
/// never run without it. Official apps run unsandboxed when bwrap is missing
|
||||
/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off`
|
||||
/// (debugging), with a warning.
|
||||
fn sandbox_for(app: &AppManifest) -> Result<Option<PathBuf>> {
|
||||
if app.origin == crate::Origin::Store {
|
||||
anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)");
|
||||
return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some);
|
||||
}
|
||||
if !cfg!(target_os = "linux") || !app.sandboxed() {
|
||||
return Ok(None);
|
||||
}
|
||||
if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") {
|
||||
log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id);
|
||||
return Ok(None);
|
||||
}
|
||||
let bwrap = sandbox::bwrap_path();
|
||||
if bwrap.is_none() {
|
||||
log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id);
|
||||
}
|
||||
Ok(bwrap)
|
||||
}
|
||||
|
||||
/// The command that starts `app`. Not spawned yet, so callers can wrap it
|
||||
/// (sf-core runs it inside a systemd scope).
|
||||
pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Command> {
|
||||
let bwrap = sandbox_for(app)?;
|
||||
// Where the app's files are, as the app sees them.
|
||||
let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() };
|
||||
let data = paths::app_data_dir(&app.id);
|
||||
let inner = match app.kind {
|
||||
AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?,
|
||||
AppKind::Exec => {
|
||||
let line = app.resolved_exec(&root);
|
||||
let (prog, args) = line.split_first().context("empty exec command")?;
|
||||
Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() }
|
||||
}
|
||||
AppKind::Builtin => bail!("built-in app has no process"),
|
||||
};
|
||||
let mut env = inner.env;
|
||||
env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v))));
|
||||
|
||||
let mut cmd = match bwrap {
|
||||
Some(bwrap) => {
|
||||
std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?;
|
||||
// Store apps sit behind symlinks (store/apps/<id> -> ../store-<id>/current).
|
||||
let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone());
|
||||
let permissions = app.permissions();
|
||||
let spec = sandbox::Spec {
|
||||
app_id: &app.id,
|
||||
app_dir: &app_dir,
|
||||
data_dir: &data,
|
||||
extra_rw: Vec::new(),
|
||||
permissions: &permissions,
|
||||
env,
|
||||
program: inner.program,
|
||||
args: inner.args,
|
||||
};
|
||||
let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current());
|
||||
log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::<Vec<_>>());
|
||||
cmd
|
||||
}
|
||||
None => {
|
||||
let mut cmd = Command::new(&inner.program);
|
||||
cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir);
|
||||
cmd
|
||||
}
|
||||
};
|
||||
cmd.env(APP_ENV, &app.id);
|
||||
// Own process group, so stopping the app also ends its helper processes.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
/// Adds `query` to `url`, before any `#fragment`.
|
||||
pub fn with_query(url: &str, query: Option<&str>) -> String {
|
||||
let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else {
|
||||
return url.to_string();
|
||||
};
|
||||
let (base, frag) = match url.find('#') {
|
||||
Some(i) => (&url[..i], &url[i..]),
|
||||
None => (url, ""),
|
||||
};
|
||||
let sep = if base.contains('?') { '&' } else { '?' };
|
||||
format!("{base}{sep}{q}{frag}")
|
||||
}
|
||||
|
||||
/// First-run preferences for an app profile: no translate prompt, Hungarian
|
||||
/// content language. Existing profiles are left alone.
|
||||
fn seed_profile(profile: &Path) -> Result<()> {
|
||||
let prefs = profile.join("Default").join("Preferences");
|
||||
if prefs.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(prefs.parent().unwrap())?;
|
||||
std::fs::write(
|
||||
&prefs,
|
||||
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The browser command for a web app. `sandbox_home`: the app's data folder
|
||||
/// when it runs sandboxed; its Chromium profile then lives in there.
|
||||
fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result<Inner> {
|
||||
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
|
||||
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
|
||||
if url.starts_with('/') {
|
||||
bail!("URL is not set (check settings: {url})");
|
||||
}
|
||||
let url = with_query(&url, opts.query);
|
||||
let old_profile = opts.data_dir.join("profiles").join(&app.id);
|
||||
let profile = match sandbox_home {
|
||||
Some(home) => {
|
||||
let profile = home.join("chromium");
|
||||
// Profiles from before the sandbox (logins, settings) move along.
|
||||
if old_profile.is_dir() && !profile.exists() {
|
||||
std::fs::create_dir_all(home)?;
|
||||
if let Err(e) = std::fs::rename(&old_profile, &profile) {
|
||||
log::warn!("{}: moving the browser profile: {e}", app.id);
|
||||
}
|
||||
}
|
||||
profile
|
||||
}
|
||||
None => old_profile,
|
||||
};
|
||||
seed_profile(&profile)?;
|
||||
|
||||
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
|
||||
(Some(ua), _) => ua.clone(),
|
||||
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
|
||||
(None, None) => default_user_agent(&browser.version),
|
||||
};
|
||||
|
||||
let mut args: Vec<String> = vec![
|
||||
format!("--user-data-dir={}", profile.display()),
|
||||
format!("--user-agent={ua}"),
|
||||
"--no-first-run".into(),
|
||||
"--no-default-browser-check".into(),
|
||||
"--disable-session-crashed-bubble".into(),
|
||||
"--hide-crash-restore-bubble".into(),
|
||||
"--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(),
|
||||
"--lang=hu".into(),
|
||||
"--accept-lang=hu-HU,hu,en".into(),
|
||||
// Dark first paint instead of a white flash before the page draws.
|
||||
"--force-dark-mode".into(),
|
||||
"--autoplay-policy=no-user-gesture-required".into(),
|
||||
"--overscroll-history-navigation=0".into(),
|
||||
];
|
||||
if opts.fullscreen {
|
||||
args.extend(["--kiosk".into(), url]);
|
||||
} else {
|
||||
args.push(format!("--app={url}"));
|
||||
match opts.bounds {
|
||||
Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]),
|
||||
None => args.push("--window-size=1600,900".into()),
|
||||
}
|
||||
}
|
||||
let mut env = Vec::new();
|
||||
if cfg!(target_os = "linux") {
|
||||
// Chromium on Linux picks its UI language from the environment, not --lang.
|
||||
env.push(("LANGUAGE".to_string(), "hu".to_string()));
|
||||
args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into());
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
args.push("--ozone-platform=wayland".into());
|
||||
}
|
||||
}
|
||||
for ext in &app.web.extensions {
|
||||
args.push(format!("--load-extension={}", root.join(ext).display()));
|
||||
}
|
||||
Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adds_query() {
|
||||
assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2");
|
||||
assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f");
|
||||
assert_eq!(with_query("https://x/", None), "https://x/");
|
||||
assert_eq!(with_query("https://x/", Some("")), "https://x/");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Shared types for SmartFox components (launcher, core daemon, remote daemon).
|
||||
//! Shared types for Fennec OS components (launcher, core daemon, remote daemon,
|
||||
//! compositor).
|
||||
|
||||
pub mod launch;
|
||||
pub mod manifest;
|
||||
pub mod message;
|
||||
pub mod paths;
|
||||
pub mod sandbox;
|
||||
pub mod settings;
|
||||
pub mod store;
|
||||
|
||||
pub use manifest::{AppKind, AppManifest, load_apps};
|
||||
pub use manifest::{AppKind, AppManifest, Origin, Permission, load_apps};
|
||||
pub use message::{CoreEvent, LauncherRequest};
|
||||
pub use settings::Settings;
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
//! App manifests: one `app.toml` per folder under the apps directory.
|
||||
//!
|
||||
//! Apps come from two places:
|
||||
//! - factory apps (the image) and official packages (`sf-app-<id>`, signed
|
||||
//! with the Fennec OS key);
|
||||
//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos,
|
||||
//! published in their own repo (docs/store.md). These always run sandboxed and
|
||||
//! can never replace an official app.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -18,6 +26,101 @@ pub enum AppKind {
|
||||
Builtin,
|
||||
}
|
||||
|
||||
/// Where an app was loaded from.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Origin {
|
||||
/// The image or an official package.
|
||||
#[default]
|
||||
Official,
|
||||
/// A store package from a third-party repo: always sandboxed.
|
||||
Store,
|
||||
}
|
||||
|
||||
/// What a sandboxed app may reach besides its own files and the screen
|
||||
/// (the Wayland socket). Shown to the user before installing.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Permission {
|
||||
/// Internet and the local network.
|
||||
Network,
|
||||
/// Hardware graphics and video decoding (/dev/dri).
|
||||
Gpu,
|
||||
/// Sound output (PipeWire / PulseAudio socket).
|
||||
Audio,
|
||||
/// Game controllers: /dev/input, /dev/hidraw*, /dev/uinput.
|
||||
Gamepad,
|
||||
/// The user's D-Bus session bus (unfiltered).
|
||||
DbusSession,
|
||||
/// The system D-Bus (unfiltered).
|
||||
DbusSystem,
|
||||
/// Every device in /dev.
|
||||
Devices,
|
||||
}
|
||||
|
||||
impl Permission {
|
||||
pub const ALL: [Permission; 7] = [
|
||||
Permission::Network,
|
||||
Permission::Gpu,
|
||||
Permission::Audio,
|
||||
Permission::Gamepad,
|
||||
Permission::DbusSession,
|
||||
Permission::DbusSystem,
|
||||
Permission::Devices,
|
||||
];
|
||||
|
||||
/// Name used in app.toml and store.toml.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Network => "network",
|
||||
Permission::Gpu => "gpu",
|
||||
Permission::Audio => "audio",
|
||||
Permission::Gamepad => "gamepad",
|
||||
Permission::DbusSession => "dbus-session",
|
||||
Permission::DbusSystem => "dbus-system",
|
||||
Permission::Devices => "devices",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(key: &str) -> Option<Permission> {
|
||||
Permission::ALL.into_iter().find(|p| p.key() == key)
|
||||
}
|
||||
|
||||
/// Hungarian label for the store screen.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Network => "Internet és helyi hálózat",
|
||||
Permission::Gpu => "Grafikus gyorsítás",
|
||||
Permission::Audio => "Hang",
|
||||
Permission::Gamepad => "Játékvezérlők",
|
||||
Permission::DbusSession => "Munkamenet D-Bus",
|
||||
Permission::DbusSystem => "Rendszer D-Bus",
|
||||
Permission::Devices => "Minden eszköz (/dev)",
|
||||
}
|
||||
}
|
||||
|
||||
/// Worth a warning: the app can reach far outside its sandbox.
|
||||
pub fn risky(self) -> bool {
|
||||
matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SandboxOptions {
|
||||
/// Run in a bubblewrap sandbox. Only official apps may turn it off
|
||||
/// (system receivers like AirPlay); store apps are always sandboxed.
|
||||
/// Unset: on, except for official background services.
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
}
|
||||
|
||||
impl Default for SandboxOptions {
|
||||
fn default() -> Self {
|
||||
SandboxOptions { enabled: None, permissions: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AppManifest {
|
||||
pub id: String,
|
||||
@@ -59,9 +162,26 @@ pub struct AppManifest {
|
||||
/// launcher tile only opens the details sheet.
|
||||
#[serde(default)]
|
||||
pub service: bool,
|
||||
#[serde(default)]
|
||||
pub sandbox: SandboxOptions,
|
||||
/// Extra environment for the app's process.
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Legacy store manifest field. Older signed releases may still contain it.
|
||||
#[serde(default)]
|
||||
pub public_key: Option<String>,
|
||||
/// Store apps: source code / home page, shown on the store screen.
|
||||
#[serde(default)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Folder the manifest was loaded from (not serialized).
|
||||
#[serde(skip)]
|
||||
pub dir: PathBuf,
|
||||
#[serde(skip)]
|
||||
pub origin: Origin,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
@@ -96,6 +216,79 @@ impl AppManifest {
|
||||
pub fn resolved_url(&self, settings: &Settings) -> Option<String> {
|
||||
self.url.as_ref().map(|u| settings.expand(u))
|
||||
}
|
||||
|
||||
/// The command line with `${app}` replaced by `app_root` (where the app's
|
||||
/// files are: its folder, or /app inside the sandbox). A relative program
|
||||
/// path with a slash (`bin/hello`) is inside the app folder too; a bare
|
||||
/// name (`uxplay`) is looked up in PATH.
|
||||
pub fn resolved_exec(&self, app_root: &Path) -> Vec<String> {
|
||||
let root = app_root.to_string_lossy();
|
||||
let mut line: Vec<String> = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect();
|
||||
if let Some(first) = line.first_mut() {
|
||||
if first.contains('/') && !first.starts_with('/') {
|
||||
*first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./"));
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// What the app may reach from its sandbox. Web apps always get what a
|
||||
/// browser needs.
|
||||
pub fn permissions(&self) -> Vec<Permission> {
|
||||
let mut p = self.sandbox.permissions.clone();
|
||||
if self.kind == AppKind::Web {
|
||||
p.extend([Permission::Network, Permission::Gpu, Permission::Audio]);
|
||||
}
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
}
|
||||
|
||||
/// Store apps always run sandboxed; official ones unless they opt out.
|
||||
pub fn sandboxed(&self) -> bool {
|
||||
self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service)
|
||||
}
|
||||
|
||||
/// An image file shipped with the app (`icon = "icon.png"`), if `icon`
|
||||
/// isn't one of the launcher's built-in icon names.
|
||||
pub fn icon_file(&self) -> Option<PathBuf> {
|
||||
let lower = self.icon.to_ascii_lowercase();
|
||||
if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) {
|
||||
return None;
|
||||
}
|
||||
if self.icon.contains("..") || Path::new(&self.icon).is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let path = self.dir.join(&self.icon);
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
|
||||
/// Rules a store app must follow (checked by sf-update before installing
|
||||
/// and by the launcher when loading).
|
||||
pub fn check_store_rules(&self) -> Result<()> {
|
||||
anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id);
|
||||
anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in");
|
||||
anyhow::ensure!(!self.service, "store apps can't be background services");
|
||||
anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL");
|
||||
anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox");
|
||||
match self.kind {
|
||||
AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"),
|
||||
AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"),
|
||||
AppKind::Builtin => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Store app ids are reverse domain names with at least one dot
|
||||
/// (`io.github.user.app`). Official app ids never have a dot, so a store app
|
||||
/// can't take the place of one.
|
||||
pub fn is_store_id(id: &str) -> bool {
|
||||
let parts: Vec<&str> = id.split('.').collect();
|
||||
id.len() <= 128
|
||||
&& parts.len() >= 2
|
||||
&& parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
&& parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
|
||||
@@ -128,6 +321,12 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
}
|
||||
found = true;
|
||||
for app in load_apps(dir)? {
|
||||
// Official ids have no dot; a store app here (developed inside
|
||||
// the apps folder) belongs to the store, not the factory set.
|
||||
if is_store_id(&app.id) {
|
||||
log::info!("skipping {}: a store app id in an official apps folder", app.id);
|
||||
continue;
|
||||
}
|
||||
match apps.iter_mut().find(|a| a.id == app.id) {
|
||||
Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app,
|
||||
Some(_) => {}
|
||||
@@ -140,16 +339,37 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
/// Official apps from `dirs` (see `load_apps_from`), plus store apps from
|
||||
/// `store`. A store app is skipped if it breaks the store rules or has the id
|
||||
/// of an official app.
|
||||
pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
|
||||
let mut apps = load_apps_from(dirs)?;
|
||||
if let Some(store) = store.filter(|d| d.is_dir()) {
|
||||
for mut app in load_apps(store)? {
|
||||
app.origin = Origin::Store;
|
||||
if let Err(e) = app.check_store_rules() {
|
||||
log::warn!("skipping store app {}: {e:#}", app.dir.display());
|
||||
} else if apps.iter().any(|a| a.id == app.id) {
|
||||
log::warn!("skipping store app {}: an app with this id is already installed", app.id);
|
||||
} else {
|
||||
apps.push(app);
|
||||
}
|
||||
}
|
||||
sort_apps(&mut apps);
|
||||
}
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn sort_apps(apps: &mut [AppManifest]) {
|
||||
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)));
|
||||
}
|
||||
|
||||
/// Compares dotted numeric versions ("1.10.0" > "1.9.2"); anything that
|
||||
/// isn't a number compares as 0.
|
||||
/// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts
|
||||
/// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0.
|
||||
pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
(0..3).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
(0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
fn load_one(path: &Path) -> Result<AppManifest> {
|
||||
@@ -174,7 +394,7 @@ mod tests {
|
||||
accent = "#E50914"
|
||||
palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
|
||||
[web]
|
||||
user_agent_suffix = "SMART-TV SmartFox/0.1"
|
||||
user_agent_suffix = "SMART-TV FennecOS/0.1"
|
||||
"##,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -191,5 +411,49 @@ mod tests {
|
||||
assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater);
|
||||
assert_eq!(version_cmp("0.2", "0.2.0"), Equal);
|
||||
assert_eq!(version_cmp("0.1.9", "0.2.0"), Less);
|
||||
assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater);
|
||||
assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_ids() {
|
||||
assert!(is_store_id("io.github.user.app"));
|
||||
assert!(is_store_id("org.example.My_App-2"));
|
||||
assert!(!is_store_id("youtube"));
|
||||
assert!(!is_store_id("IO.github.x"));
|
||||
assert!(!is_store_id("io..x"));
|
||||
assert!(!is_store_id("io.x/../y"));
|
||||
assert!(!is_store_id(".io.x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_and_permissions() {
|
||||
let app: AppManifest = toml::from_str(
|
||||
r#"
|
||||
id = "io.github.fox.hello"
|
||||
name = "Hello"
|
||||
kind = "exec"
|
||||
exec = ["bin/hello", "--data", "${app}/share"]
|
||||
[sandbox]
|
||||
permissions = ["network", "gamepad"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]);
|
||||
assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]);
|
||||
assert!(app.sandboxed());
|
||||
app.check_store_rules().unwrap();
|
||||
|
||||
let mut bad = app.clone();
|
||||
bad.sandbox.enabled = Some(false);
|
||||
assert!(bad.check_store_rules().is_err());
|
||||
bad = app.clone();
|
||||
bad.id = "youtube".into();
|
||||
assert!(bad.check_store_rules().is_err());
|
||||
|
||||
let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap();
|
||||
assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]);
|
||||
let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap();
|
||||
assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,82 @@
|
||||
//! Messages between the launcher and the core daemon (newline-delimited JSON
|
||||
//! over a unix socket). The core daemon itself comes in phase 3.
|
||||
//! Messages between the launcher and the core daemon: newline-delimited JSON
|
||||
//! over the core socket (`paths::core_socket`).
|
||||
//!
|
||||
//! The launcher sends `LauncherRequest`s; the core sends `CoreEvent`s to
|
||||
//! every connected client (and `Hello` right after connecting).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum LauncherRequest {
|
||||
Launch { app_id: String },
|
||||
/// Bring the launcher back to the front (freezes the foreground app).
|
||||
/// Start the app, or bring it back if it waits in the background.
|
||||
Launch {
|
||||
app_id: String,
|
||||
/// Extra query string for the start URL (DIAL uses this).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
query: Option<String>,
|
||||
},
|
||||
/// Show the launcher. The foreground app is frozen in the background if
|
||||
/// the compositor can switch windows, otherwise it is closed.
|
||||
GoHome,
|
||||
SetSetting { key: String, value: String },
|
||||
/// Close the app.
|
||||
Stop { app_id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum CoreEvent {
|
||||
AppStarted { app_id: String },
|
||||
/// First message on every connection.
|
||||
Hello {
|
||||
/// True if apps are kept (frozen) in the background on Home.
|
||||
switching: bool,
|
||||
/// The app in the foreground, if any.
|
||||
#[serde(default)]
|
||||
foreground: Option<String>,
|
||||
},
|
||||
/// An app came to the front: newly started or thawed.
|
||||
AppStarted {
|
||||
app_id: String,
|
||||
/// Started from a phone (DIAL), not from the launcher.
|
||||
#[serde(default)]
|
||||
cast: bool,
|
||||
},
|
||||
/// The app's process ended.
|
||||
AppStopped { app_id: String },
|
||||
/// Something connected over DIAL/AirPlay/Miracast.
|
||||
CastConnected { app_id: String, device: String },
|
||||
/// The cast session ended.
|
||||
CastEnded { app_id: String },
|
||||
Toast { text: String },
|
||||
}
|
||||
|
||||
impl LauncherRequest {
|
||||
pub fn to_line(&self) -> String {
|
||||
let mut s = serde_json::to_string(self).unwrap_or_default();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
impl CoreEvent {
|
||||
pub fn to_line(&self) -> String {
|
||||
let mut s = serde_json::to_string(self).unwrap_or_default();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
let r = LauncherRequest::Launch { app_id: "youtube".into(), query: None };
|
||||
assert_eq!(r.to_line(), "{\"type\":\"launch\",\"app_id\":\"youtube\"}\n");
|
||||
let back: LauncherRequest = serde_json::from_str(r.to_line().trim()).unwrap();
|
||||
assert_eq!(back, r);
|
||||
let e: CoreEvent = serde_json::from_str(r#"{"type":"app_started","app_id":"netflex"}"#).unwrap();
|
||||
assert_eq!(e, CoreEvent::AppStarted { app_id: "netflex".into(), cast: false });
|
||||
}
|
||||
}
|
||||
|
||||
78
crates/sf-ipc/src/paths.rs
Normal file
78
crates/sf-ipc/src/paths.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Where the Fennec OS sockets and files live.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `$XDG_RUNTIME_DIR`, or the temp dir.
|
||||
pub fn runtime_dir() -> PathBuf {
|
||||
std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
fn from_env(var: &str, default: &str) -> PathBuf {
|
||||
match std::env::var_os(var) {
|
||||
Some(p) => p.into(),
|
||||
None => runtime_dir().join(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Launcher command socket (`home`, `remote <state>`, `power`, `wake`).
|
||||
pub fn launcher_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_SOCKET", "smartfox.sock")
|
||||
}
|
||||
|
||||
/// sf-core: app lifecycle (JSON lines, see `message`).
|
||||
pub fn core_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_CORE_SOCKET", "smartfox-core.sock")
|
||||
}
|
||||
|
||||
/// sf-compositor control socket (`focus launcher`, `focus <app-id>`).
|
||||
pub fn wm_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock")
|
||||
}
|
||||
|
||||
/// The settings file: `$SMARTFOX_SETTINGS`, else `<config>/smartfox/settings.toml`.
|
||||
pub fn settings_file() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") {
|
||||
return p.into();
|
||||
}
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("settings.toml")
|
||||
}
|
||||
|
||||
/// An app's private data folder; its `$HOME` inside the sandbox:
|
||||
/// `$XDG_DATA_HOME/smartfox/apps/<id>` (default `~/.local/share/...`).
|
||||
pub fn app_data_dir(id: &str) -> PathBuf {
|
||||
let base = std::env::var_os("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
|
||||
.or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("apps").join(id)
|
||||
}
|
||||
|
||||
/// Installed store apps (`/var/lib/sf-pkg/store/apps/<id>`), written by sf-update.
|
||||
pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps";
|
||||
|
||||
/// Looks for an `apps` folder next to the binary or above the cwd (dev
|
||||
/// checkout), else the installed one.
|
||||
pub fn apps_dir() -> PathBuf {
|
||||
let mut starts = vec![];
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
starts.push(cwd);
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
starts.extend(exe.parent().map(Path::to_path_buf));
|
||||
}
|
||||
for start in starts {
|
||||
for dir in start.ancestors() {
|
||||
let candidate = dir.join("apps");
|
||||
if candidate.join("netflex").is_dir() {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
PathBuf::from("/usr/share/smartfox/apps")
|
||||
}
|
||||
350
crates/sf-ipc/src/sandbox.rs
Normal file
350
crates/sf-ipc/src/sandbox.rs
Normal file
@@ -0,0 +1,350 @@
|
||||
//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container,
|
||||
//! the same building block Flatpak uses.
|
||||
//!
|
||||
//! Inside the sandbox an app sees:
|
||||
//! - the system read-only (`/usr`, `/etc`), no other user's or app's files;
|
||||
//! - its own files read-only at `/app`;
|
||||
//! - its own data folder as `$HOME` (on the host:
|
||||
//! `~/.local/share/smartfox/apps/<id>`), the only writable place that lasts;
|
||||
//! - the Wayland socket (it can show a window), nothing else from
|
||||
//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets);
|
||||
//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces;
|
||||
//! - and only what its permissions allow (`Permission`): network, GPU,
|
||||
//! sound, game controllers, D-Bus, devices.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
/// Where the app's own files are inside the sandbox.
|
||||
pub const APP_DIR: &str = "/app";
|
||||
|
||||
/// Environment variables passed through from the session when set.
|
||||
const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"];
|
||||
|
||||
/// What a host path is, for building the mount list (a function so tests
|
||||
/// can fake the file system).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
Missing,
|
||||
Dir,
|
||||
Other,
|
||||
Symlink(PathBuf),
|
||||
/// There, but we may not read it (bwrap's `--*-bind-try` fails on that).
|
||||
Denied,
|
||||
}
|
||||
|
||||
pub fn probe(path: &Path) -> Entry {
|
||||
if let Err(e) = std::fs::metadata(path) {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
return Entry::Denied;
|
||||
}
|
||||
}
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Err(_) => Entry::Missing,
|
||||
Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing),
|
||||
Ok(m) if m.is_dir() => Entry::Dir,
|
||||
Ok(_) => Entry::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The session the app is started from.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Host {
|
||||
pub uid: u32,
|
||||
pub user: String,
|
||||
pub home: PathBuf,
|
||||
pub runtime_dir: PathBuf,
|
||||
pub wayland_display: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
/// Allowed variables from the session (`PASS_ENV`).
|
||||
pub env: Vec<(String, String)>,
|
||||
/// /dev/hidraw* (controllers that talk raw HID, like DualSense).
|
||||
pub hidraw: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn current() -> Host {
|
||||
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
|
||||
let hidraw = std::fs::read_dir("/dev")
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect())
|
||||
.unwrap_or_default();
|
||||
Host {
|
||||
uid: current_uid(),
|
||||
user: var("USER").unwrap_or_else(|| "tv".into()),
|
||||
home,
|
||||
runtime_dir: crate::paths::runtime_dir(),
|
||||
wayland_display: var("WAYLAND_DISPLAY"),
|
||||
hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()),
|
||||
env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(),
|
||||
hidraw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn current_uid() -> u32 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// The owner of our own /proc entry is our uid (no libc needed).
|
||||
std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn current_uid() -> u32 {
|
||||
1000
|
||||
}
|
||||
|
||||
/// One sandboxed process.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Spec<'a> {
|
||||
pub app_id: &'a str,
|
||||
/// The app's files (host path), read-only at `/app`.
|
||||
pub app_dir: &'a Path,
|
||||
/// The app's private data (host path), mounted as `$HOME`.
|
||||
pub data_dir: &'a Path,
|
||||
/// More writable folders, at the same path inside (a browser profile).
|
||||
pub extra_rw: Vec<PathBuf>,
|
||||
pub permissions: &'a [Permission],
|
||||
/// Extra environment for the app.
|
||||
pub env: Vec<(String, String)>,
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn bwrap_path() -> Option<PathBuf> {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BWRAP") {
|
||||
return Some(p.into());
|
||||
}
|
||||
["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The bwrap command for `spec`.
|
||||
pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command {
|
||||
let mut cmd = Command::new(bwrap);
|
||||
cmd.args(args(spec, host, &probe));
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The bwrap arguments. Mount order matters: later mounts go on top.
|
||||
pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec<String> {
|
||||
let has = |p: Permission| spec.permissions.contains(&p);
|
||||
let mut a: Vec<String> = Vec::new();
|
||||
let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
|
||||
|
||||
push(&["--die-with-parent", "--unshare-all"]);
|
||||
if has(Permission::Network) {
|
||||
push(&["--share-net"]);
|
||||
}
|
||||
if host.uid == 0 {
|
||||
// Unprivileged bwrap drops every capability by itself; as root
|
||||
// (development) do it explicitly.
|
||||
push(&["--cap-drop", "ALL"]);
|
||||
}
|
||||
if let Some(h) = &host.hostname {
|
||||
push(&["--hostname", h]);
|
||||
}
|
||||
|
||||
// The system, read-only. /bin, /lib... are symlinks into /usr on Debian.
|
||||
push(&["--ro-bind", "/usr", "/usr"]);
|
||||
for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] {
|
||||
match fs(Path::new(top)) {
|
||||
Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]),
|
||||
Entry::Dir => push(&["--ro-bind", top, top]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]);
|
||||
|
||||
// Devices.
|
||||
if has(Permission::Devices) {
|
||||
push(&["--dev-bind", "/dev", "/dev"]);
|
||||
} else {
|
||||
push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]);
|
||||
if has(Permission::Gpu) {
|
||||
push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]);
|
||||
}
|
||||
if has(Permission::Gamepad) {
|
||||
push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]);
|
||||
for h in &host.hidraw {
|
||||
let h = h.to_string_lossy();
|
||||
push(&["--dev-bind-try", &h, &h]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
push(&["--ro-bind", "/sys", "/sys"]);
|
||||
}
|
||||
|
||||
// Fresh writable scratch space.
|
||||
push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]);
|
||||
push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]);
|
||||
if has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
// Hotplug of controllers (SDL, Steam) goes through udev.
|
||||
push(&["--ro-bind-try", "/run/udev", "/run/udev"]);
|
||||
}
|
||||
if has(Permission::Network) {
|
||||
// /etc/resolv.conf points at systemd-resolved's stub file on the TV;
|
||||
// elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at.
|
||||
push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]);
|
||||
if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) {
|
||||
let target = Path::new("/etc").join(t);
|
||||
let target = target.to_string_lossy();
|
||||
if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") {
|
||||
push(&["--ro-bind-try", &target, &target]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::DbusSystem) {
|
||||
push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]);
|
||||
}
|
||||
|
||||
// The session's runtime dir: only the sockets the app may use.
|
||||
let rt = host.runtime_dir.to_string_lossy().to_string();
|
||||
push(&["--perms", "0700", "--dir", &rt]);
|
||||
let mut socket = |name: &str| {
|
||||
let p = format!("{rt}/{name}");
|
||||
if fs(Path::new(&p)) != Entry::Denied {
|
||||
push(&["--ro-bind-try", &p, &p]);
|
||||
}
|
||||
};
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
socket(wl);
|
||||
}
|
||||
if has(Permission::Audio) {
|
||||
socket("pipewire-0");
|
||||
socket("pulse/native");
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
socket("bus");
|
||||
}
|
||||
|
||||
// $HOME is the app's own data folder (at the real home path, so programs
|
||||
// that remember absolute paths keep working).
|
||||
let home = host.home.to_string_lossy().to_string();
|
||||
if let Entry::Symlink(t) = fs(Path::new("/home")) {
|
||||
push(&["--symlink", &t.to_string_lossy(), "/home"]);
|
||||
}
|
||||
push(&["--bind", &spec.data_dir.to_string_lossy(), &home]);
|
||||
for p in &spec.extra_rw {
|
||||
let p = p.to_string_lossy();
|
||||
push(&["--bind", &p, &p]);
|
||||
}
|
||||
push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]);
|
||||
|
||||
// A clean environment.
|
||||
push(&["--clearenv"]);
|
||||
let mut env: Vec<(String, String)> = vec![
|
||||
("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), host.user.clone()),
|
||||
("LOGNAME".into(), host.user.clone()),
|
||||
("SHELL".into(), "/bin/sh".into()),
|
||||
("XDG_RUNTIME_DIR".into(), rt.clone()),
|
||||
("XDG_SESSION_TYPE".into(), "wayland".into()),
|
||||
("SMARTFOX_APP".into(), spec.app_id.into()),
|
||||
("SMARTFOX_APP_DIR".into(), APP_DIR.into()),
|
||||
];
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
env.push(("WAYLAND_DISPLAY".into(), wl.clone()));
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus")));
|
||||
}
|
||||
env.extend(host.env.iter().cloned());
|
||||
env.extend(spec.env.iter().cloned());
|
||||
for (k, v) in env {
|
||||
push(&["--setenv", &k, &v]);
|
||||
}
|
||||
|
||||
push(&["--", &spec.program]);
|
||||
a.extend(spec.args.iter().cloned());
|
||||
a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn host() -> Host {
|
||||
Host {
|
||||
uid: 1000,
|
||||
user: "tv".into(),
|
||||
home: "/var/home/tv".into(),
|
||||
runtime_dir: "/run/user/1000".into(),
|
||||
wayland_display: Some("wayland-1".into()),
|
||||
hostname: Some("smartfox".into()),
|
||||
env: vec![("LANG".into(), "C.UTF-8".into())],
|
||||
hidraw: vec!["/dev/hidraw0".into()],
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_fs(p: &Path) -> Entry {
|
||||
match p.to_str().unwrap() {
|
||||
"/bin" => Entry::Symlink("usr/bin".into()),
|
||||
"/lib" => Entry::Symlink("usr/lib".into()),
|
||||
"/lib64" => Entry::Symlink("usr/lib64".into()),
|
||||
"/home" => Entry::Symlink("var/home".into()),
|
||||
_ => Entry::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_seq(args: &[String], seq: &[&str]) -> bool {
|
||||
args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_sandbox() {
|
||||
let spec = Spec {
|
||||
app_id: "io.github.fox.hello",
|
||||
app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"),
|
||||
data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"),
|
||||
extra_rw: vec![],
|
||||
permissions: &[],
|
||||
env: vec![("FOO".into(), "bar".into())],
|
||||
program: "/app/bin/hello".into(),
|
||||
args: vec!["--x".into()],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(has_seq(&a, &["--unshare-all"]));
|
||||
assert!(!a.contains(&"--share-net".to_string()));
|
||||
assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys"));
|
||||
assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus")));
|
||||
assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"]));
|
||||
assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"]));
|
||||
assert!(has_seq(&a, &["--setenv", "FOO", "bar"]));
|
||||
assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"]));
|
||||
assert_eq!(a.last().unwrap(), "--x");
|
||||
// /run must be fresh before the runtime dir and sockets go in.
|
||||
let run = a.iter().position(|s| s == "/run").unwrap();
|
||||
let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap();
|
||||
assert!(run < sock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_open_doors() {
|
||||
let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession];
|
||||
let spec = Spec {
|
||||
app_id: "steam",
|
||||
app_dir: Path::new("/usr/share/smartfox/apps/steam"),
|
||||
data_dir: Path::new("/d"),
|
||||
extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()],
|
||||
permissions: &perms,
|
||||
env: vec![],
|
||||
program: "/app/x".into(),
|
||||
args: vec![],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(a.contains(&"--share-net".to_string()));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"]));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"]));
|
||||
assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"]));
|
||||
}
|
||||
}
|
||||
180
crates/sf-ipc/src/store.rs
Normal file
180
crates/sf-ipc/src/store.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
//! The app store's files, shared by the launcher and sf-update (docs/store.md).
|
||||
//!
|
||||
//! /var/lib/smartfox/store.toml what the user wants: sources, apps and
|
||||
//! the permissions they approved (the
|
||||
//! launcher writes it, user tv)
|
||||
//! /var/lib/sf-pkg/store/catalog.json what the sources offer, and why an
|
||||
//! update is held back (sf-update, root)
|
||||
//! /var/lib/sf-pkg/store/apps/<id> installed store apps (sf-update)
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
pub const WANTED_FILE: &str = "/var/lib/smartfox/store.toml";
|
||||
pub const CATALOG_FILE: &str = "/var/lib/sf-pkg/store/catalog.json";
|
||||
/// Package (folder) name of a store app in /var/lib/sf-pkg.
|
||||
pub const PACKAGE_PREFIX: &str = "store-";
|
||||
/// The file a catalog repo keeps on its default branch.
|
||||
pub const INDEX_FILE: &str = "smartfox-store.toml";
|
||||
/// Largest store.toml sf-update reads.
|
||||
pub const MAX_WANTED: u64 = 256 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Wanted {
|
||||
/// Repos the user added: app repos and catalogs.
|
||||
#[serde(default)]
|
||||
pub sources: Vec<String>,
|
||||
/// Installed (or to be installed) apps by id.
|
||||
#[serde(default)]
|
||||
pub apps: BTreeMap<String, WantedApp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct WantedApp {
|
||||
/// The repo the app comes from (canonical https URL).
|
||||
pub source: String,
|
||||
/// Permissions the user approved; an update that asks for more waits
|
||||
/// for a new approval.
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
pub fn parse(text: &str) -> Result<Wanted> {
|
||||
toml::from_str(text).context("store.toml")
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Wanted> {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => Wanted::parse(&text),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Wanted::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes atomically (the updater may read it at any time).
|
||||
pub fn save(&self, path: &Path) -> Result<()> {
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, toml::to_string_pretty(self)?).with_context(|| format!("writing {}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `smartfox-store.toml` in a catalog repo.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct Index {
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// App repo addresses.
|
||||
#[serde(default)]
|
||||
pub apps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Catalog {
|
||||
/// Unix time of the last refresh (0: never).
|
||||
#[serde(default)]
|
||||
pub updated_at: u64,
|
||||
#[serde(default)]
|
||||
pub sources: Vec<SourceInfo>,
|
||||
#[serde(default)]
|
||||
pub apps: Vec<CatalogApp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SourceInfo {
|
||||
/// As in store.toml.
|
||||
pub url: String,
|
||||
/// "app" or "catalog"
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
/// Apps found in it.
|
||||
#[serde(default)]
|
||||
pub apps: usize,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct CatalogApp {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub category: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub homepage: String,
|
||||
#[serde(default)]
|
||||
pub license: String,
|
||||
#[serde(default)]
|
||||
pub accent: String,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
/// The app's repo (canonical https URL).
|
||||
pub source: String,
|
||||
/// The catalog it was listed in, if any.
|
||||
#[serde(default)]
|
||||
pub catalog: Option<String>,
|
||||
pub package_url: String,
|
||||
/// Installed version, if any.
|
||||
#[serde(default)]
|
||||
pub installed: Option<String>,
|
||||
/// Why the newest version isn't installed: "permissions" (asks for more
|
||||
/// than approved).
|
||||
#[serde(default)]
|
||||
pub blocked: Option<String>,
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
pub fn load(path: &Path) -> Option<Catalog> {
|
||||
serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
|
||||
}
|
||||
|
||||
pub fn app(&self, id: &str) -> Option<&CatalogApp> {
|
||||
self.apps.iter().find(|a| a.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Permissions in `want` that `approved` doesn't have.
|
||||
pub fn missing_permissions(want: &[Permission], approved: &[Permission]) -> Vec<Permission> {
|
||||
want.iter().filter(|p| !approved.contains(p)).copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wanted_round_trip() {
|
||||
let w = Wanted::parse(
|
||||
r#"
|
||||
sources = ["https://github.com/fox/store"]
|
||||
[apps."io.github.fox.hello"]
|
||||
source = "https://github.com/fox/hello"
|
||||
permissions = ["network", "audio"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(w.apps["io.github.fox.hello"].permissions, [Permission::Network, Permission::Audio]);
|
||||
let again = Wanted::parse(&toml::to_string_pretty(&w).unwrap()).unwrap();
|
||||
assert_eq!(w, again);
|
||||
assert!(Wanted::parse("[apps.x]\nsource = 'a'\npermissions = ['root']\n").is_err());
|
||||
assert_eq!(missing_permissions(&[Permission::Network, Permission::Gpu], &[Permission::Network]), [Permission::Gpu]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user