Split the apps and the SDK out of Fennec OS

The apps are developed apart from the OS now, each in its own repo under
gitea.bluefox.support/fennec:
- sdk: sf-app (the app contract: manifest, permissions, store rules,
  sandbox, launch; from sf-ipc), sf-ui, sf-pack, the app template, the
  developer guide. The OS depends on it by tag (v0.1.0).
- youtube, steam: store apps. netflex (native) replaces the Netflex web app.
- store: the Fennec catalog, the store source a new TV starts with.

This repo keeps the OS and its own apps (Settings, App Store, AirPlay,
Miracast). sf-ipc re-exports sf-app, so OS code is mostly unchanged.

- Store apps may register for DIAL (the `dial` permission); an official
  app with the same DIAL name wins.
- Built-in icon names are for official apps only.
- The image installs the catalog apps at build time (factory-store.toml,
  sf-update store in mkosi.postinst.chroot). Steam's system part stays in
  the image: 32-bit libraries, controller udev rules (from Valve's apt
  repo), Valve's key.
- Older TVs move over by themselves: sf-update adds the replacements to
  store.toml once, the old factory app stays until its replacement is
  installed, YouTube's and Steam's data folders move to the new ids, and
  the old sf-app-<id> packages are not installed any more.

Shell 0.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-10-25 17:58:21 +01:00
parent d7e9fe4568
commit deedf1416a
67 changed files with 393 additions and 13476 deletions

View File

@@ -1,283 +0,0 @@
//! 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/");
}
}

View File

@@ -1,12 +1,15 @@
//! Shared types for Fennec OS components (launcher, core daemon, remote daemon,
//! compositor).
//! compositor, updater).
//!
//! The app contract (manifests, permissions, sandbox, launching) lives in the
//! Fennec SDK (`sf-app`), so apps and their tools build without the OS. It is
//! re-exported here, so OS code keeps using `sf_ipc::manifest` and so on.
pub use sf_app::{launch, sandbox, settings};
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, Origin, Permission, load_apps};

View File

@@ -1,459 +1,110 @@
//! 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.
//! App manifests: the Fennec SDK's `sf_app::manifest`, plus what only the OS
//! decides: which factory apps became store apps, and how a TV moves over.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use anyhow::Result;
use crate::settings::Settings;
pub use sf_app::manifest::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppKind {
/// Runs in the shared Chromium web runtime.
Web,
/// Any executable: AppImage, Rust binary, script.
Exec,
/// Built into the launcher (e.g. settings screen).
Builtin,
/// The Fennec catalog: the store source with the Bluefox apps.
pub const FENNEC_CATALOG: &str = "https://gitea.bluefox.support/fennec/store";
/// A factory app that became a store app (its own repo, Fennec catalog).
pub struct Retired {
/// The old official id (`apps/<id>`, `sf-app-<id>`).
pub id: &'static str,
/// The store app that replaces it.
pub replacement: &'static str,
/// Its repo (canonical https URL, as in store.toml).
pub source: &'static str,
/// What it asks for; the old app had the same, so it is approved.
pub permissions: &'static [Permission],
/// The old app's data folder (logins, Chromium profile) moves over.
pub move_data: bool,
}
/// 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,
pub const RETIRED: &[Retired] = &[
Retired {
// The Netflex web app; the native app keeps its own login.
id: "netflex",
replacement: "support.bluefox.netflex",
source: "https://gitea.bluefox.support/fennec/netflex",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio],
move_data: false,
},
Retired {
id: "youtube",
replacement: "support.bluefox.youtube",
source: "https://gitea.bluefox.support/fennec/youtube",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Dial],
move_data: true,
},
Retired {
id: "steam",
replacement: "support.bluefox.steam",
source: "https://gitea.bluefox.support/fennec/steam",
permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession],
move_data: true,
},
];
pub fn retired(id: &str) -> Option<&'static Retired> {
RETIRED.iter().find(|r| r.id == id)
}
/// 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,
pub fn is_retired(id: &str) -> bool {
retired(id).is_some()
}
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,
pub name: String,
pub kind: AppKind,
/// Package version (semver). Published as `sf-app-<id>` when it changes;
/// the newer of a factory and an installed copy wins.
#[serde(default = "default_version")]
pub version: String,
/// Short label above the title in the hero ("Saját app", "Castolás"...).
#[serde(default)]
pub category: String,
#[serde(default)]
pub description: String,
/// Web apps: start URL. May contain `${settings.<key>}` placeholders.
#[serde(default)]
pub url: Option<String>,
/// Exec apps: command line.
#[serde(default)]
pub exec: Option<Vec<String>>,
/// Built-in icon name used by the launcher.
#[serde(default)]
pub icon: String,
/// Accent color (hex), used for focus glow and buttons.
#[serde(default = "default_accent")]
pub accent: String,
/// Three colors for the animated hero backdrop: highlight, mid, deep.
#[serde(default)]
pub palette: Vec<String>,
/// Sort order on the home row.
#[serde(default)]
pub order: i32,
#[serde(default)]
pub web: WebOptions,
#[serde(default)]
pub dial: Option<DialOptions>,
/// Background receiver (AirPlay, Miracast): sf-core keeps it running all
/// the time and it shows its own window when something connects. The
/// 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)]
pub struct WebOptions {
/// Full user agent override.
#[serde(default)]
pub user_agent: Option<String>,
/// Appended to the default user agent.
#[serde(default)]
pub user_agent_suffix: Option<String>,
/// Unpacked extensions to load (paths relative to the app folder).
#[serde(default)]
pub extensions: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialOptions {
/// DIAL application name, e.g. "YouTube".
pub name: String,
}
fn default_version() -> String {
"0.0.0".into()
}
fn default_accent() -> String {
"#ffffff".into()
}
impl AppManifest {
/// Start URL with `${settings.key}` placeholders filled in.
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.
pub fn load_apps(dir: &Path) -> Result<Vec<AppManifest>> {
let mut apps = Vec::new();
let entries = std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?;
for entry in entries.flatten() {
let path = entry.path().join("app.toml");
if !path.is_file() {
continue;
}
match load_one(&path) {
Ok(app) => apps.push(app),
Err(e) => log::warn!("skipping {}: {e:#}", path.display()),
}
}
sort_apps(&mut apps);
Ok(apps)
}
/// Loads apps from several folders (factory apps, then installed packages).
/// Missing folders are skipped; of two apps with the same id the higher
/// `version` wins, on a tie the later folder.
pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
let mut apps: Vec<AppManifest> = Vec::new();
let mut found = false;
for dir in dirs {
if !dir.is_dir() {
continue;
}
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(_) => {}
None => apps.push(app),
}
}
}
anyhow::ensure!(found, "none of the app folders exist: {dirs:?}");
sort_apps(&mut apps);
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.
/// `sf_app::manifest::load_all`, where a retired official app (the old
/// factory copy in an older image, or its `sf-app-<id>` package) stays only
/// until its store replacement is installed: the TV never loses the 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);
let apps = sf_app::manifest::load_all(dirs, store)?;
let replaced = |id: &str| retired(id).is_some_and(|r| apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement));
let keep: Vec<bool> = apps.iter().map(|a| a.origin == Origin::Store || !replaced(&a.id)).collect();
Ok(apps.into_iter().zip(keep).filter_map(|(a, k)| k.then_some(a)).collect())
}
/// Moves the data folder of a retired app to its replacement, once the
/// replacement is installed and has no data yet (runs as the TV user).
pub fn migrate_data(apps: &[AppManifest]) {
for r in RETIRED.iter().filter(|r| r.move_data) {
if !apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement) {
continue;
}
let (old, new) = (sf_app::paths::app_data_dir(r.id), sf_app::paths::app_data_dir(r.replacement));
if old.is_dir() && std::fs::symlink_metadata(&new).is_err() {
match std::fs::rename(&old, &new) {
Ok(()) => log::info!("moved the data of {} to {}", r.id, r.replacement),
Err(e) => log::warn!("moving {} to {}: {e}", old.display(), new.display()),
}
}
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"), 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(4).map(|p| p.parse().unwrap_or(0)).collect() };
let (a, b) = (parts(a), parts(b));
(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> {
let text = std::fs::read_to_string(path)?;
let mut app: AppManifest = toml::from_str(&text)?;
app.dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
Ok(app)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_web_manifest() {
let app: AppManifest = toml::from_str(
r##"
id = "netflex"
name = "Netflex"
kind = "web"
url = "${settings.netflex_server}/"
accent = "#E50914"
palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
[web]
user_agent_suffix = "SMART-TV FennecOS/0.1"
"##,
)
.unwrap();
assert_eq!(app.kind, AppKind::Web);
let mut s = Settings::default();
s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into());
assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/");
assert_eq!(app.version, "0.0.0");
fn write(dir: &Path, id: &str, body: &str) {
std::fs::create_dir_all(dir.join(id)).unwrap();
std::fs::write(dir.join(id).join("app.toml"), format!("id = \"{id}\"\nname = \"{id}\"\n{body}")).unwrap();
}
#[test]
fn compares_versions() {
use std::cmp::Ordering::*;
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"]);
fn retired_app_stays_until_replaced() {
let base = std::env::temp_dir().join(format!("sf-ipc-retired-{}", std::process::id()));
let (factory, store) = (base.join("factory"), base.join("store"));
write(&factory, "youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n");
write(&factory, "settings", "kind = \"builtin\"\n");
let ids = |apps: Vec<AppManifest>| apps.into_iter().map(|a| a.id).collect::<Vec<_>>();
assert_eq!(ids(load_all(&[factory.clone()], Some(&store)).unwrap()), ["settings", "youtube"]);
write(&store, "support.bluefox.youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n");
let mut got = ids(load_all(&[factory.clone()], Some(&store)).unwrap());
got.sort();
assert_eq!(got, ["settings", "support.bluefox.youtube"]);
std::fs::remove_dir_all(&base).unwrap();
}
}

View File

@@ -1,11 +1,9 @@
//! Where the Fennec OS sockets and files live.
//! Where the Fennec OS sockets and files live. The app paths (data folder,
//! settings file) come from the Fennec SDK (`sf_app::paths`).
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)
}
pub use sf_app::paths::{app_data_dir, runtime_dir, settings_file};
fn from_env(var: &str, default: &str) -> PathBuf {
match std::env::var_os(var) {
@@ -29,30 +27,6 @@ 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";
@@ -69,7 +43,7 @@ pub fn apps_dir() -> PathBuf {
for start in starts {
for dir in start.ancestors() {
let candidate = dir.join("apps");
if candidate.join("netflex").is_dir() {
if candidate.join("settings").join("app.toml").is_file() {
return candidate;
}
}

View File

@@ -1,350 +0,0 @@
//! 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"]));
}
}

View File

@@ -1,57 +0,0 @@
//! Flat key/value settings stored in `settings.toml`.
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::Result;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Settings {
#[serde(flatten)]
pub values: BTreeMap<String, String>,
}
impl Settings {
/// Missing file means default settings.
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
Ok(toml::from_str(&std::fs::read_to_string(path)?)?)
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(path, toml::to_string_pretty(self)?)?;
Ok(())
}
pub fn get(&self, key: &str) -> Option<&str> {
self.values.get(key).map(String::as_str)
}
/// Replaces `${settings.key}` with the value (or an empty string).
pub fn expand(&self, input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(start) = rest.find("${settings.") {
out.push_str(&rest[..start]);
let after = &rest[start + "${settings.".len()..];
match after.find('}') {
Some(end) => {
out.push_str(self.get(&after[..end]).unwrap_or(""));
rest = &after[end + 1..];
}
None => {
out.push_str(&rest[start..]);
rest = "";
}
}
}
out.push_str(rest);
out
}
}