diff --git a/.gitea/workflows/packages.yml b/.gitea/workflows/packages.yml new file mode 100644 index 0000000..2d8d62d --- /dev/null +++ b/.gitea/workflows/packages.yml @@ -0,0 +1,65 @@ +# Builds, signs and publishes the SmartFox packages (shell + apps) to the +# Gitea generic package registry. A package is only built when its version +# isn't published yet: bump the version to release (docs/updates.md). +# +# Runner hygiene (shared host, little disk): runs in the runner image that is +# already on the host (no image pull), uses no `uses:` actions (no action +# cache), and deletes everything it made at the end. +name: packages + +on: + push: + branches: [main] + paths: + - "crates/**" + - "apps/**" + - "Cargo.toml" + - "Cargo.lock" + - "tools/pkg/**" + - "tools/siri-remote/fastpair.py" + - ".gitea/workflows/packages.yml" + workflow_dispatch: + +jobs: + packages: + runs-on: build + container: + image: docker.gitea.com/runner-images:ubuntu-latest + env: + CARGO_HOME: /tmp/sf-build/cargo + RUSTUP_HOME: /tmp/sf-build/rustup + CARGO_TARGET_DIR: /tmp/sf-build/target + CARGO_INCREMENTAL: "0" + SF_OUT: /tmp/sf-build/out + steps: + - name: Checkout + run: | + mkdir -p /tmp/sf-build + host="${GITHUB_SERVER_URL#https://}" + git clone --depth 1 --branch "${GITHUB_REF_NAME}" \ + "https://oauth2:${{ secrets.GITHUB_TOKEN }}@${host}/${GITHUB_REPOSITORY}.git" /tmp/sf-build/src + + - name: Toolchain + run: | + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq + apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd \ + libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev >/dev/null + rm -rf /var/lib/apt/lists/* + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path + /tmp/sf-build/cargo/bin/rustc --version + + - name: Build, sign, upload + env: + SF_SIGNING_KEY: ${{ secrets.SF_SIGNING_KEY }} + SF_PACKAGE_TOKEN: ${{ secrets.SF_PACKAGE_TOKEN }} + run: | + export PATH="/tmp/sf-build/cargo/bin:$PATH" + cd /tmp/sf-build/src + bash tools/pkg/packages.sh --upload + + - name: Clean up + if: always() + run: | + rm -rf /tmp/sf-build + df -h / | tail -1 diff --git a/.gitignore b/.gitignore index 6409846..62fa6a6 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ /image/stage /image/ovmf-vars.fd /image/out +/image/secrets diff --git a/Cargo.lock b/Cargo.lock index 016b242..5e5d57d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -341,12 +341,24 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bincode" version = "2.0.1" @@ -419,6 +431,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -716,6 +737,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "convert_case" version = "0.10.0" @@ -771,6 +798,15 @@ version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -826,6 +862,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "ctor" version = "0.10.1" @@ -841,6 +887,33 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "custom_debug" version = "0.6.2" @@ -968,6 +1041,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -991,6 +1074,16 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1094,6 +1187,30 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.19.0" @@ -1249,6 +1366,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "field-offset" version = "0.3.6" @@ -1534,6 +1657,16 @@ dependencies = [ "libc", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1544,6 +1677,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1793,6 +1937,22 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "i-slint-backend-linuxkms" version = "1.18.1" @@ -3485,6 +3645,16 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -3661,6 +3831,15 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -3805,6 +3984,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rowan" version = "0.17.0" @@ -3887,12 +4080,56 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ruzstd" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8" +dependencies = [ + "twox-hash", +] + [[package]] name = "same-file" version = "1.0.6" @@ -4044,6 +4281,35 @@ dependencies = [ "tokio", ] +[[package]] +name = "sf-update" +version = "0.1.0" +dependencies = [ + "anyhow", + "base64 0.22.1", + "ed25519-dalek", + "env_logger", + "log", + "ruzstd", + "serde", + "serde_json", + "sf-ipc", + "tar", + "toml 0.9.12+spec-1.1.0", + "ureq", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -4066,6 +4332,15 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -4333,6 +4608,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4403,6 +4688,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.16.1" @@ -4812,6 +5103,12 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typed-index-collections" version = "3.5.0" @@ -4822,6 +5119,12 @@ dependencies = [ "serde", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "udev" version = "0.9.3" @@ -4899,12 +5202,47 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "unty" version = "0.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" +[[package]] +name = "ureq" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -4923,7 +5261,7 @@ version = "0.48.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" dependencies = [ - "base64", + "base64 0.23.1", "data-url", "flate2", "fontdb", @@ -4945,6 +5283,12 @@ dependencies = [ "xmlwriter", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -5224,6 +5568,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -6018,6 +6371,12 @@ dependencies = [ "synstructure 0.14.0", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 38dbbff..e868610 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/sf-ipc", "crates/sf-launcher", "crates/sf-remote"] +members = ["crates/sf-ipc", "crates/sf-launcher", "crates/sf-remote", "crates/sf-update"] [workspace.package] version = "0.1.0" diff --git a/apps/airplay/app.toml b/apps/airplay/app.toml index 4269a2f..c4145bc 100644 --- a/apps/airplay/app.toml +++ b/apps/airplay/app.toml @@ -1,5 +1,6 @@ id = "airplay" name = "AirPlay" +version = "1.0.0" kind = "exec" category = "Képernyőtükrözés" description = "iPhone, iPad vagy Mac képernyőjének tükrözése. A Vezérlőközpontban válaszd a SmartFoxot." diff --git a/apps/miracast/app.toml b/apps/miracast/app.toml index 5582150..cdc55c1 100644 --- a/apps/miracast/app.toml +++ b/apps/miracast/app.toml @@ -1,5 +1,6 @@ id = "miracast" name = "Miracast" +version = "1.0.0" kind = "exec" category = "Képernyőtükrözés · Kísérleti" description = "Android telefon képernyőjének tükrözése Wi-Fi Directen keresztül." diff --git a/apps/netflex/app.toml b/apps/netflex/app.toml index 43d9a06..a0398a5 100644 --- a/apps/netflex/app.toml +++ b/apps/netflex/app.toml @@ -1,5 +1,6 @@ id = "netflex" name = "Netflex" +version = "1.0.0" kind = "web" category = "Saját streaming" description = "Filmek, sorozatok és anime a saját szerveredről. Válaszd ki, és már nézheted is, miközben töltődik." diff --git a/apps/settings/app.toml b/apps/settings/app.toml index 79dcb47..ad78913 100644 --- a/apps/settings/app.toml +++ b/apps/settings/app.toml @@ -1,5 +1,6 @@ id = "settings" name = "Beállítások" +version = "1.0.0" kind = "builtin" category = "Rendszer" description = "Kijelző felbontás, Siri Remote és Bluetooth eszközök, hálózat és rendszer." diff --git a/apps/youtube/app.toml b/apps/youtube/app.toml index 1c6a3aa..b019f81 100644 --- a/apps/youtube/app.toml +++ b/apps/youtube/app.toml @@ -1,5 +1,6 @@ id = "youtube" name = "YouTube" +version = "1.0.0" kind = "web" category = "Videó · Castolható" description = "A YouTube TV-s felülete. Telefonról a YouTube appban a cast ikonnal küldhetsz ide videót." diff --git a/crates/sf-ipc/src/manifest.rs b/crates/sf-ipc/src/manifest.rs index 6733d10..fe9bf36 100644 --- a/crates/sf-ipc/src/manifest.rs +++ b/crates/sf-ipc/src/manifest.rs @@ -23,6 +23,10 @@ pub struct AppManifest { pub id: String, pub name: String, pub kind: AppKind, + /// Package version (semver). Published as `sf-app-` 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, @@ -50,6 +54,11 @@ pub struct AppManifest { pub web: WebOptions, #[serde(default)] pub dial: Option, + /// 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, /// Folder the manifest was loaded from (not serialized). #[serde(skip)] pub dir: PathBuf, @@ -74,6 +83,10 @@ pub struct DialOptions { pub name: String, } +fn default_version() -> String { + "0.0.0".into() +} + fn default_accent() -> String { "#ffffff".into() } @@ -99,10 +112,46 @@ pub fn load_apps(dir: &Path) -> Result> { Err(e) => log::warn!("skipping {}: {e:#}", path.display()), } } - apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); + 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> { + let mut apps: Vec = Vec::new(); + let mut found = false; + for dir in dirs { + if !dir.is_dir() { + continue; + } + found = true; + for app in load_apps(dir)? { + 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) +} + +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. +pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { + let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(3).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) +} + fn load_one(path: &Path) -> Result { let text = std::fs::read_to_string(path)?; let mut app: AppManifest = toml::from_str(&text)?; @@ -133,5 +182,14 @@ mod tests { 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"); + } + + #[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); } } diff --git a/crates/sf-launcher/src/main.rs b/crates/sf-launcher/src/main.rs index 14f9590..1dd1ca6 100644 --- a/crates/sf-launcher/src/main.rs +++ b/crates/sf-launcher/src/main.rs @@ -31,26 +31,31 @@ slint::include_modules!(); const CROSSFADE: f32 = 0.35; struct Options { - apps_dir: PathBuf, + /// Factory apps, then installed app packages (`--apps` may repeat). + apps_dirs: Vec, settings_path: PathBuf, fullscreen: bool, } fn parse_args() -> Options { - let mut apps_dir = None; + let mut apps_dirs = Vec::new(); let mut settings_path = None; let mut fullscreen = false; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match a.as_str() { - "--apps" => apps_dir = args.next().map(PathBuf::from), + "--apps" => apps_dirs.extend(args.next().map(PathBuf::from)), "--settings" => settings_path = args.next().map(PathBuf::from), "--fullscreen" | "-f" => fullscreen = true, other => log::warn!("unknown argument {other}"), } } Options { - apps_dir: apps_dir.or_else(find_apps_dir).unwrap_or_else(|| PathBuf::from("/usr/share/smartfox/apps")), + apps_dirs: if apps_dirs.is_empty() { + vec![find_apps_dir().unwrap_or_else(|| PathBuf::from("/usr/share/smartfox/apps"))] + } else { + apps_dirs + }, settings_path: settings_path.unwrap_or_else(default_settings_path), fullscreen, } @@ -311,8 +316,9 @@ fn main() -> Result<()> { } let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(".")); - let apps = sf_ipc::load_apps(&opts.apps_dir).with_context(|| format!("loading apps from {}", opts.apps_dir.display()))?; - log::info!("{} apps from {}", apps.len(), opts.apps_dir.display()); + let apps = sf_ipc::manifest::load_apps_from(&opts.apps_dirs).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?; + log::info!("{} apps from {:?}", apps.len(), opts.apps_dirs); + system::confirm_shell_trial(); let ui = App::new()?; let entries: Vec = apps.iter().map(|a| entry_of(a, &settings)).collect(); diff --git a/crates/sf-launcher/src/settings_screen.rs b/crates/sf-launcher/src/settings_screen.rs index c40021f..17e413c 100644 --- a/crates/sf-launcher/src/settings_screen.rs +++ b/crates/sf-launcher/src/settings_screen.rs @@ -10,7 +10,7 @@ use std::time::{Duration, Instant}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; -use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, Wifi, WifiNetwork}; +use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork}; use crate::power; use crate::{App, SettingRow, keyboard}; @@ -21,6 +21,7 @@ const DISPLAY: i32 = 0; const DEVICES: i32 = 1; const NETWORK: i32 = 2; const ENERGY: i32 = 3; +const SYSTEM: i32 = 4; #[derive(Clone, PartialEq)] enum Action { @@ -50,6 +51,9 @@ enum Action { SuspendAfter, PickSuspendAfter(u32), StandbyNow, + Updates, + UpdateCheck, + UpdateInstall, } #[derive(Clone, PartialEq)] @@ -64,6 +68,7 @@ enum Sub { RemoteDebug, PowerMode, SuspendAfter, + Updates, } struct Pending { @@ -88,6 +93,9 @@ enum Loaded { Removed { name: String, result: Result<(), String>, then_pair: bool }, RemoteDebug(RemoteDebug), RemoteDebugSet { on: bool, result: Result<(), String> }, + /// sf-update's status.json (None: it never ran). + Updates(Option), + UpdateRequested { install: bool, result: Result<(), String> }, } struct State { @@ -105,6 +113,8 @@ struct State { info: Option, /// Whether sshd runs (remote debugging); None until queried. remote_debug: Option, + /// Package updates; None until read, Some(None) if sf-update never ran. + updates: Option>, remote_status: String, /// One-line feedback shown under the page title (e.g. "AirPods eltávolítva"). notice: String, @@ -182,6 +192,7 @@ impl Screen { wifi_pending: None, info: None, remote_debug: None, + updates: None, remote_status: String::new(), notice: String::new(), actions: Vec::new(), @@ -253,6 +264,7 @@ impl Screen { post(|| Loaded::Net(system::network())); post(|| Loaded::Wifi(wifi_result(system::wifi()))); post(|| Loaded::RemoteDebug(system::remote_debug())); + post(|| Loaded::Updates(system::update_status())); if self.state.borrow().info.is_none() { post(|| Loaded::Info(system::device_info())); } @@ -271,6 +283,10 @@ impl Screen { if sub == Sub::KeepMode { self.rebuild(None); } + // The updater reports progress through a file: cheap to poll. + if self.is_open() && category == SYSTEM && matches!(sub, Sub::None | Sub::Updates) && ticks % 2 == 0 { + post(|| Loaded::Updates(system::update_status())); + } if !self.is_open() || sub != Sub::None || ticks % 4 != 0 { return; } @@ -401,6 +417,21 @@ impl Screen { } } Loaded::Info(i) => self.state.borrow_mut().info = Some(i), + Loaded::Updates(u) => self.state.borrow_mut().updates = Some(u), + Loaded::UpdateRequested { install, result } => { + self.state.borrow_mut().notice = match result { + Ok(()) if install => "Telepítés folyamatban. Utána a felület magától újraindul.".into(), + Ok(()) => "Frissítések keresése…".into(), + Err(e) => { + log::warn!("update request: {e}"); + format!("Nem sikerült: {}", short_err(&e)) + } + }; + post(|| { + std::thread::sleep(Duration::from_millis(700)); + Loaded::Updates(system::update_status()) + }); + } Loaded::RemoteDebug(on) => self.state.borrow_mut().remote_debug = Some(on), Loaded::RemoteDebugSet { on, result } => { { @@ -687,6 +718,18 @@ impl Screen { Some(true) => self.run(Action::SetRemoteDebug(false)), None => {} }, + Action::Updates => { + self.state.borrow_mut().notice.clear(); + self.enter(Sub::Updates, 0); + } + Action::UpdateCheck | Action::UpdateInstall => { + let install = action == Action::UpdateInstall; + log::info!("updates: {}", if install { "install" } else { "check" }); + post(move || Loaded::UpdateRequested { + install, + result: system::request_update(if install { "install" } else { "check" }).map_err(|e| format!("{e:#}")), + }); + } Action::SetRemoteDebug(on) => { log::info!("remote debug: turning {}", if on { "on" } else { "off" }); self.state.borrow_mut().busy = true; @@ -855,6 +898,31 @@ impl Screen { push(row("Mégse", "", "", "action"), Action::Back); ("Felület újraindítása".to_string(), "A futó alkalmazás bezárul, a kezdőképernyő újraindul.".to_string()) } + (Sub::Updates, _) => { + let status = st.updates.clone().flatten(); + let busy = status.as_ref().is_some_and(UpdateStatus::busy); + let updates: Vec<_> = status.as_ref().map(|s| s.updates().into_iter().cloned().collect()).unwrap_or_default(); + if !updates.is_empty() { + let label = if busy { "Folyamatban…" } else { "Telepítés most" }; + push(row(label, "", "A felület utána újraindul", "danger"), Action::UpdateInstall); + } + let label = if busy { "Folyamatban…" } else { "Frissítések keresése" }; + push(row(label, "", "", "action"), Action::UpdateCheck); + for p in status.iter().flat_map(|s| s.packages.iter()) { + let (value, detail) = match p.update() { + Some(v) if p.ready() => (format!("{} → {v}", p.installed), "Letöltve, újraindításkor települ".to_string()), + Some(v) => (format!("{} → {v}", p.installed), "Új verzió".to_string()), + None => (p.installed.clone(), String::new()), + }; + push(row(p.title.clone(), value, detail, "info"), Action::None); + } + push(row("Vissza", "", "", "action"), Action::Back); + let subtitle = match &status { + None => "A frissítő még nem futott ezen a gépen.".to_string(), + Some(s) => update_summary(s).1, + }; + ("Frissítések".to_string(), notice_or(&subtitle)) + } (Sub::RemoteDebug, _) => { let label = if st.busy { "Bekapcsolás…" } else { "Bekapcsolás" }; push(row(label, "", "", "danger"), Action::SetRemoteDebug(true)); @@ -1012,6 +1080,12 @@ impl Screen { (false, Some(_)) => ("Ki".to_string(), "SSH a helyi hálózatról".to_string()), }; push(row("Távoli hibakeresés", value, detail, "action"), Action::RemoteDebug); + let (value, detail) = match &st.updates { + None => ("…".to_string(), String::new()), + Some(None) => ("Nem elérhető".to_string(), "A frissítő még nem futott".to_string()), + Some(Some(u)) => update_summary(u), + }; + push(row("Frissítések", value, detail, "action"), Action::Updates); push(row("Felület újraindítása", "", "", "action"), Action::Restart); ("Rendszer".to_string(), notice_or("Az eszköz adatai.")) } @@ -1089,3 +1163,29 @@ pub fn glass(ui: &App, scale: f32) -> Vec { } out } + +/// Value and detail for the Updates row: "2 frissítés" / "SmartFox felület 0.2.0 · YouTube 1.1.0". +fn update_summary(u: &UpdateStatus) -> (String, String) { + let checked = || { + use chrono::TimeZone; + match chrono::Local.timestamp_opt(u.checked_at, 0).single() { + Some(t) if u.checked_at > 0 => format!("Utoljára ellenőrizve: {}", t.format("%m. %d. %H:%M")), + _ => "Még nem kereste".to_string(), + } + }; + match u.state.as_str() { + "checking" => return ("Keresés…".into(), String::new()), + "downloading" => return ("Letöltés…".into(), u.message.clone()), + "installing" => return ("Telepítés…".into(), String::new()), + "error" => return ("Hiba".into(), short_err(&u.message)), + _ => {} + } + let updates = u.updates(); + if updates.is_empty() { + return ("Naprakész".into(), checked()); + } + let list = updates.iter().map(|p| format!("{} {}", p.title, p.update().unwrap_or_default())).collect::>().join(" · "); + let value = if updates.len() == 1 { "1 frissítés".to_string() } else { format!("{} frissítés", updates.len()) }; + let detail = if updates.iter().all(|p| p.ready()) { format!("{list} · újraindításkor települ") } else { list }; + (value, detail) +} diff --git a/crates/sf-launcher/src/system.rs b/crates/sf-launcher/src/system.rs index 9357237..e75e014 100644 --- a/crates/sf-launcher/src/system.rs +++ b/crates/sf-launcher/src/system.rs @@ -5,6 +5,7 @@ //! backend with in-memory state keeps the settings screen usable. //! All calls can block for a moment, so run them off the UI thread. +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -855,6 +856,139 @@ pub fn set_remote_debug(on: bool) -> Result<()> { bail!("ssh.service is still {}", if on { "stopped" } else { "running" }) } +// ---- updates (sf-update, docs/updates.md) -------------------------------- + +/// Written by sf-update (root), readable by everyone. +const UPDATE_STATUS: &str = "/var/lib/sf-pkg/status.json"; +/// The launcher asks sf-update for things by dropping empty files here. +const UPDATE_REQUESTS: &str = "/var/lib/smartfox/update-requests"; + +static DEMO_UPDATE: Mutex = Mutex::new(0); + +#[derive(Debug, Clone, Default)] +pub struct UpdateStatus { + /// idle | checking | downloading | installing | error + pub state: String, + pub message: String, + /// Unix time of the last check, 0 if never. + pub checked_at: i64, + pub packages: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct UpdatePackage { + /// Display name ("SmartFox felület", "YouTube"). + pub title: String, + pub installed: String, + pub available: Option, + pub staged: Option, +} + +impl UpdatePackage { + /// The newer version on the server, if there is one. + pub fn update(&self) -> Option<&str> { + self.available.as_deref().filter(|a| sf_ipc::manifest::version_cmp(a, &self.installed).is_gt()) + } + + /// Downloaded already, goes live at the next start. + pub fn ready(&self) -> bool { + self.update().is_some() && self.staged.as_deref() == self.update() + } +} + +impl UpdateStatus { + pub fn busy(&self) -> bool { + matches!(self.state.as_str(), "checking" | "downloading" | "installing") + } + + pub fn updates(&self) -> Vec<&UpdatePackage> { + self.packages.iter().filter(|p| p.update().is_some()).collect() + } +} + +/// "sf-shell" -> "SmartFox felület", "sf-app-youtube" -> the app's name. +fn package_title(name: &str) -> String { + if name == "sf-shell" { + return "SmartFox felület".into(); + } + let id = name.strip_prefix("sf-app-").unwrap_or(name); + let dirs = [PathBuf::from("/usr/share/smartfox/apps"), PathBuf::from("/var/lib/sf-pkg/apps")]; + sf_ipc::manifest::load_apps_from(&dirs) + .ok() + .and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name)) + .unwrap_or_else(|| id.to_string()) +} + +/// What sf-update last reported; None if it never ran. +pub fn update_status() -> Option { + if demo() { + let step = *DEMO_UPDATE.lock().unwrap(); + let pkg = |title: &str, installed: &str, available: &str| UpdatePackage { + title: title.into(), + installed: installed.into(), + available: Some(available.into()), + staged: None, + }; + let packages = match step { + 0 => vec![pkg("SmartFox felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")], + _ => vec![pkg("SmartFox felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")], + }; + return Some(UpdateStatus { state: "idle".into(), message: String::new(), checked_at: 1_792_800_000, packages }); + } + let text = std::fs::read_to_string(UPDATE_STATUS).ok()?; + let v: serde_json::Value = serde_json::from_str(&text).ok()?; + let s = |v: &serde_json::Value, k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_string); + let packages = v + .get("packages") + .and_then(|p| p.as_array()) + .map(|list| { + list.iter() + .map(|p| UpdatePackage { + title: package_title(&s(p, "name").unwrap_or_default()), + installed: s(p, "installed").unwrap_or_default(), + available: s(p, "available"), + staged: s(p, "staged"), + }) + .collect() + }) + .unwrap_or_default(); + Some(UpdateStatus { + state: s(&v, "state").unwrap_or_else(|| "idle".into()), + message: s(&v, "message").unwrap_or_default(), + checked_at: v.get("checked_at").and_then(|x| x.as_i64()).unwrap_or(0), + packages, + }) +} + +/// Asks sf-update (root) to `check` or `install`; it runs from +/// sf-update-requests.path and reports through status.json. +pub fn request_update(what: &str) -> Result<()> { + if demo() { + if what == "install" { + *DEMO_UPDATE.lock().unwrap() = 1; + } + return Ok(()); + } + let path = Path::new(UPDATE_REQUESTS).join(what); + std::fs::write(&path, b"").with_context(|| format!("writing {}", path.display())) +} + +/// A freshly installed shell is on trial (sf-launcher-start sets +/// SMARTFOX_SHELL_TRIAL); once it has run for a while it tells sf-update to +/// keep it. If it never gets here, sf-update rolls it back. +pub fn confirm_shell_trial() { + if std::env::var_os("SMARTFOX_SHELL_TRIAL").is_none() { + return; + } + std::thread::spawn(|| { + std::thread::sleep(Duration::from_secs(30)); + match request_update("confirm") { + Ok(()) => log::info!("new shell confirmed"), + Err(e) => log::warn!("confirming the new shell: {e:#}"), + } + }); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/sf-update/Cargo.toml b/crates/sf-update/Cargo.toml new file mode 100644 index 0000000..0ded4c9 --- /dev/null +++ b/crates/sf-update/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "sf-update" +description = "SmartFox package updater: signed shell and app packages from the Gitea package registry" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +sf-ipc.workspace = true +anyhow.workspace = true +log.workspace = true +env_logger.workspace = true +serde.workspace = true +serde_json.workspace = true +toml.workspace = true +ureq = "3" +ed25519-dalek = "2" +base64 = "0.22" +tar = "0.4" +ruzstd = "0.8" diff --git a/crates/sf-update/src/config.rs b/crates/sf-update/src/config.rs new file mode 100644 index 0000000..9606cc9 --- /dev/null +++ b/crates/sf-update/src/config.rs @@ -0,0 +1,97 @@ +//! Updater settings: /usr/share/smartfox/update.toml from the image, with +//! /var/lib/sf-pkg/update.toml (if present) overriding single keys, so a TV +//! can be pointed elsewhere or get a new token without reinstalling. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use base64::Engine; +use serde::Deserialize; + +const IMAGE_CONFIG: &str = "/usr/share/smartfox/update.toml"; +const LOCAL_CONFIG: &str = "/var/lib/sf-pkg/update.toml"; + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +struct File { + server: Option, + owner: Option, + token_file: Option, + public_key: Option, + root: Option, + requests: Option, + factory: Option, +} + +impl File { + fn read(path: &Path) -> Result { + let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + toml::from_str(&text).with_context(|| format!("parsing {}", path.display())) + } + + fn overlay(self, o: File) -> File { + File { + server: o.server.or(self.server), + owner: o.owner.or(self.owner), + token_file: o.token_file.or(self.token_file), + public_key: o.public_key.or(self.public_key), + root: o.root.or(self.root), + requests: o.requests.or(self.requests), + factory: o.factory.or(self.factory), + } + } +} + +pub struct Config { + /// Gitea base URL, e.g. https://gitea.example.org + pub server: String, + /// User or organization that owns the packages. + pub owner: String, + /// "user:token" for HTTP basic auth (read:package scope), if any. + pub auth: Option, + /// Ed25519 key that signs every package. + pub public_key: [u8; 32], + /// Installed packages and status.json (root-owned). + pub root: PathBuf, + /// Request files from the launcher (tv-owned folder). + pub requests: PathBuf, + /// Versions of the copies built into the image. + pub factory: PathBuf, +} + +impl Config { + pub fn load() -> Result { + let mut file = match std::env::var_os("SF_UPDATE_CONFIG") { + Some(p) => File::read(Path::new(&p))?, + None => File::read(Path::new(IMAGE_CONFIG))?, + }; + if Path::new(LOCAL_CONFIG).exists() && std::env::var_os("SF_UPDATE_CONFIG").is_none() { + file = file.overlay(File::read(Path::new(LOCAL_CONFIG))?); + } + let Some(server) = file.server else { bail!("update.toml: server is missing") }; + let Some(owner) = file.owner else { bail!("update.toml: owner is missing") }; + let Some(key) = file.public_key else { bail!("update.toml: public_key is missing") }; + let key = base64::engine::general_purpose::STANDARD.decode(key.trim()).context("public_key: not base64")?; + let public_key: [u8; 32] = key.try_into().map_err(|_| anyhow::anyhow!("public_key: not a 32-byte Ed25519 key"))?; + let auth = match &file.token_file { + Some(p) if p.exists() => { + let t = std::fs::read_to_string(p).with_context(|| format!("reading {}", p.display()))?; + Some(t.trim().to_string()).filter(|t| !t.is_empty()) + } + Some(p) => { + log::warn!("token file {} missing, trying without login", p.display()); + None + } + None => None, + }; + Ok(Config { + server: server.trim_end_matches('/').to_string(), + owner, + auth, + public_key, + root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()), + requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()), + factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()), + }) + } +} diff --git a/crates/sf-update/src/main.rs b/crates/sf-update/src/main.rs new file mode 100644 index 0000000..71a3ef3 --- /dev/null +++ b/crates/sf-update/src/main.rs @@ -0,0 +1,216 @@ +//! sf-update: installs signed SmartFox packages (the shell and the apps) from +//! the Gitea package registry onto the writable data partition. The root +//! file system stays read-only and keeps the factory copies as a fallback. +//! +//! Protocol and layout: docs/updates.md. +//! +//! sf-update check ask the server what's new (status.json) +//! sf-update auto check, then download and stage what's new (timer) +//! sf-update apply switch staged packages live (at boot) +//! sf-update install check, download, apply now and restart the UI +//! sf-update requests handle the launcher's request files (path unit) +//! sf-update status print status.json + +mod config; +mod registry; +mod store; + +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; + +use crate::config::Config; +use crate::store::Store; + +fn main() { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let cmd = std::env::args().nth(1).unwrap_or_default(); + if let Err(e) = run(&cmd) { + log::error!("{cmd}: {e:#}"); + std::process::exit(1); + } +} + +fn run(cmd: &str) -> Result<()> { + let cfg = Config::load()?; + let store = Store::open(&cfg)?; + match cmd { + "status" => { + println!("{}", serde_json::to_string_pretty(&store.read_status())?); + return Ok(()); + } + "check" | "auto" | "apply" | "install" | "requests" => {} + _ => bail!("usage: sf-update check|auto|apply|install|requests|status"), + } + // One run at a time (timer, boot and launcher requests can overlap). + let _lock = store.lock(Duration::from_secs(600))?; + match cmd { + "check" => check(&cfg, &store).map(drop), + "auto" => auto(&cfg, &store), + "apply" => apply(&store).map(drop), + "install" => install(&cfg, &store), + "requests" => requests(&cfg, &store), + _ => unreachable!(), + } +} + +/// Asks the registry for the newest version of every package and records +/// which ones are newer than what's installed. +fn check(cfg: &Config, store: &Store) -> Result> { + store.set_state("checking", ""); + let latest = match registry::latest_versions(cfg) { + Ok(l) => l, + Err(e) => { + store.set_state("error", &format!("{e:#}")); + return Err(e); + } + }; + let pending = store.refresh(&latest); + store.set_state("idle", ""); + log::info!("{} update(s) available", pending.len()); + Ok(pending) +} + +/// Downloads and stages each pending package. Failures of one package don't +/// stop the others; the first error is reported. +fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result { + let mut first_err = None; + let mut done = 0; + for p in pending { + if store.staged(&p.name).as_deref() == Some(p.version.as_str()) { + done += 1; + continue; + } + store.set_state("downloading", &format!("{} {}", p.name, p.version)); + let result = (|| -> Result<()> { + let dir = store.download_dir()?; + let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?; + store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?; + store.stage(&p.name, &p.version) + })(); + let _ = std::fs::remove_dir_all(store.download_dir_path()); + match result { + Ok(()) => { + log::info!("staged {} {}", p.name, p.version); + done += 1; + } + Err(e) => { + log::error!("{} {}: {e:#}", p.name, p.version); + first_err.get_or_insert(e.context(format!("{} {}", p.name, p.version))); + } + } + } + store.write_status(|_| {}); + match first_err { + Some(e) => { + store.set_state("error", &format!("{e:#}")); + Err(e) + } + None => { + store.set_state("idle", ""); + Ok(done) + } + } +} + +fn auto(cfg: &Config, store: &Store) -> Result<()> { + let pending = check(cfg, store)?; + download(cfg, store, &pending)?; + store.gc(); + Ok(()) +} + +/// Switches staged packages live. Returns which kinds changed. +fn apply(store: &Store) -> Result { + let applied = store.apply_staged()?; + store.gc(); + store.write_status(|_| {}); + Ok(applied) +} + +fn install(cfg: &Config, store: &Store) -> Result<()> { + let pending = check(cfg, store)?; + let result = download(cfg, store, &pending); + store.set_state("installing", ""); + let applied = apply(store)?; + store.set_state("idle", ""); + restart(&applied); + result.map(drop) +} + +/// Restarts what an update touched: the remote driver for a new shell, the +/// TV session (cage + launcher) for a new shell or new apps. +fn restart(applied: &store::Applied) { + if applied.shell { + systemctl(&["restart", "sf-remote.service"]); + } + if applied.shell || applied.apps { + restart_ui(); + } +} + +fn restart_ui() { + let _ = std::process::Command::new("pkill").args(["-x", "sf-launcher"]).status(); + systemctl(&["restart", "getty@tty1.service"]); +} + +fn systemctl(args: &[&str]) { + match std::process::Command::new("systemctl").args(args).status() { + Ok(s) if s.success() => {} + other => log::warn!("systemctl {}: {other:?}", args.join(" ")), + } +} + +/// The launcher (user tv) can't run anything as root; it drops empty files +/// named after a request into the requests folder, sf-update-requests.path +/// starts this. Only the file names are used, never their contents. +fn requests(cfg: &Config, store: &Store) -> Result<()> { + const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"]; + let dir = &cfg.requests; + let mut result = Ok(()); + for _ in 0..10 { + let mut any = false; + for name in ORDER { + if take(dir, name) { + any = true; + log::info!("request: {name}"); + let r = match name { + "rollback" => rollback(store), + "confirm" => store.confirm_shell(), + "install" => install(cfg, store), + _ => check(cfg, store).map(drop), + }; + if let Err(e) = r { + log::error!("{name}: {e:#}"); + result = Err(e); + } + } + } + // Unknown files: remove so the path unit doesn't loop on them. + if let Ok(entries) = std::fs::read_dir(dir) { + for e in entries.flatten() { + log::warn!("ignoring request {:?}", e.file_name()); + let _ = std::fs::remove_file(e.path()); + } + } + if !any { + break; + } + } + result +} + +/// Removes a request file; true if it was there. Never follows symlinks. +fn take(dir: &Path, name: &str) -> bool { + std::fs::remove_file(dir.join(name)).is_ok() +} + +fn rollback(store: &Store) -> Result<()> { + if store.rollback_shell().context("rolling back the shell")? { + systemctl(&["restart", "sf-remote.service"]); + restart_ui(); + } + Ok(()) +} + diff --git a/crates/sf-update/src/registry.rs b/crates/sf-update/src/registry.rs new file mode 100644 index 0000000..3b204f8 --- /dev/null +++ b/crates/sf-update/src/registry.rs @@ -0,0 +1,132 @@ +//! Gitea generic package registry client. +//! +//! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf- +//! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig) + +use std::collections::BTreeMap; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use base64::Engine; +use serde::Deserialize; +use sf_ipc::manifest::version_cmp; + +/// Largest package we'll download. +const MAX_PACKAGE: u64 = 1024 * 1024 * 1024; + +use crate::config::Config; + +/// Package names this updater handles. +pub fn is_ours(name: &str) -> bool { + name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) +} + +/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped). +pub fn is_release(version: &str) -> bool { + !version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3 +} + +fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_recv_body(Some(Duration::from_secs(1800))) + .timeout_recv_response(Some(Duration::from_secs(60))) + .https_only(false) + .build() + .into() +} + +fn get(cfg: &Config, agent: &ureq::Agent, url: &str) -> Result> { + let mut req = agent.get(url); + if let Some(auth) = &cfg.auth { + let b64 = base64::engine::general_purpose::STANDARD.encode(auth); + req = req.header("Authorization", format!("Basic {b64}")); + } + req.call().with_context(|| format!("GET {}", strip_query(url))) +} + +fn strip_query(url: &str) -> &str { + url.split('?').next().unwrap_or(url) +} + +#[derive(Deserialize)] +struct PackageVersion { + name: String, + version: String, +} + +/// Newest release version of every package on the server. +pub fn latest_versions(cfg: &Config) -> Result> { + let agent = agent(); + let mut latest: BTreeMap = BTreeMap::new(); + for page in 1..=100 { + let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner); + let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?; + let list: Vec = serde_json::from_str(&text).context("package list")?; + if list.is_empty() { + break; + } + for p in list { + if !is_ours(&p.name) || !is_release(&p.version) { + continue; + } + match latest.get(&p.name) { + Some(v) if version_cmp(v, &p.version).is_ge() => {} + _ => { + latest.insert(p.name, p.version); + } + } + } + } + Ok(latest) +} + +/// File name of a package in the registry. +pub fn file_name(name: &str, version: &str) -> String { + format!("{name}-{version}.tar.zst") +} + +/// Downloads a package and its signature into `dir`. +pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec)> { + if !is_ours(name) || !is_release(version) { + bail!("refusing package {name} {version}"); + } + let agent = agent(); + let file = file_name(name, version); + let base = format!("{}/api/packages/{}/generic/{name}/{version}", cfg.server, cfg.owner); + + let mut sig = Vec::new(); + get(cfg, &agent, &format!("{base}/{file}.sig"))?.into_body().into_reader().take(1024).read_to_end(&mut sig)?; + + let path = dir.join(&file); + let mut out = std::fs::File::create(&path).with_context(|| format!("creating {}", path.display()))?; + let resp = get(cfg, &agent, &format!("{base}/{file}"))?; + let mut body = resp.into_body().into_reader().take(MAX_PACKAGE + 1); + let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {file}"))?; + if n > MAX_PACKAGE { + bail!("{file} is larger than {MAX_PACKAGE} bytes"); + } + out.sync_all()?; + log::info!("downloaded {file} ({n} bytes)"); + Ok((path, sig)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_versions() { + assert!(is_ours("sf-shell")); + assert!(is_ours("sf-app-youtube")); + assert!(!is_ours("sf-app-")); + assert!(!is_ours("sf-app-../x")); + assert!(!is_ours("other")); + assert!(is_release("1.2.3")); + assert!(!is_release("1.2.3-rc1")); + assert!(!is_release("1..2")); + assert!(!is_release("../1")); + } +} diff --git a/crates/sf-update/src/store.rs b/crates/sf-update/src/store.rs new file mode 100644 index 0000000..5ce6a66 --- /dev/null +++ b/crates/sf-update/src/store.rs @@ -0,0 +1,363 @@ +//! Installed packages on the data partition (root-owned, default /var/lib/sf-pkg): +//! +//! // unpacked package +//! /current -> the live copy (none: factory copy) +//! /previous -> for rollback +//! /staged -> downloaded, goes live at the next apply +//! /bad versions that failed, never installed again +//! sf-shell/trial a new shell that hasn't confirmed a good start yet +//! apps/ -> ../sf-app-/current (the launcher reads this folder) +//! status.json for the launcher's Updates row + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result, bail}; +use ed25519_dalek::{Signature, VerifyingKey}; +use serde::{Deserialize, Serialize}; +use sf_ipc::manifest::version_cmp; + +use crate::config::Config; +use crate::registry; + +pub const SHELL: &str = "sf-shell"; + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct Status { + /// idle | checking | downloading | installing | error + pub state: String, + pub message: String, + /// Unix time of the last successful check (0: never). + pub checked_at: u64, + pub packages: Vec, + /// Shell version on trial (installed, not yet confirmed by the launcher). + pub shell_trial: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PackageStatus { + pub name: String, + /// What runs now: the installed package or the factory copy, whichever is newer. + pub installed: String, + /// Newest version on the server (from the last check). + pub available: Option, + /// Downloaded, goes live at the next boot. + pub staged: Option, +} + +pub struct Pending { + pub name: String, + pub version: String, +} + +#[derive(Debug, Default)] +pub struct Applied { + pub shell: bool, + pub apps: bool, +} + +#[derive(Deserialize)] +struct PkgInfo { + name: String, + version: String, +} + +#[cfg(unix)] +fn symlink(target: impl AsRef, link: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, link) +} + +/// The updater only runs on the TV; elsewhere it builds but can't install. +#[cfg(not(unix))] +fn symlink(_target: impl AsRef, _link: &Path) -> std::io::Result<()> { + Err(std::io::Error::other("symlinks need Linux")) +} + +pub struct Store { + root: PathBuf, + factory: BTreeMap, +} + +pub struct Lock(#[allow(dead_code)] fs::File); + +impl Store { + pub fn open(cfg: &Config) -> Result { + fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?; + let factory = match fs::read_to_string(&cfg.factory) { + Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?, + Err(_) => BTreeMap::new(), + }; + Ok(Store { root: cfg.root.clone(), factory }) + } + + pub fn lock(&self, wait: Duration) -> Result { + let f = fs::OpenOptions::new().create(true).truncate(false).write(true).open(self.root.join(".lock"))?; + let start = Instant::now(); + loop { + match f.try_lock() { + Ok(()) => return Ok(Lock(f)), + Err(fs::TryLockError::WouldBlock) if start.elapsed() < wait => std::thread::sleep(Duration::from_millis(500)), + Err(fs::TryLockError::WouldBlock) => bail!("another sf-update is still running"), + Err(fs::TryLockError::Error(e)) => return Err(e.into()), + } + } + } + + fn dir(&self, name: &str) -> PathBuf { + self.root.join(name) + } + + fn link(&self, name: &str, which: &str) -> Option { + let target = fs::read_link(self.dir(name).join(which)).ok()?; + let v = target.file_name()?.to_str()?.to_string(); + self.dir(name).join(&v).is_dir().then_some(v) + } + + /// Points `/` at `` (atomically, via rename). + fn set_link(&self, name: &str, which: &str, version: &str) -> Result<()> { + let dir = self.dir(name); + let tmp = dir.join(format!(".{which}.tmp")); + let _ = fs::remove_file(&tmp); + symlink(version, &tmp)?; + fs::rename(&tmp, dir.join(which))?; + Ok(()) + } + + fn remove_link(&self, name: &str, which: &str) { + let _ = fs::remove_file(self.dir(name).join(which)); + } + + pub fn staged(&self, name: &str) -> Option { + self.link(name, "staged") + } + + /// The version running now: installed package or factory copy, the newer one. + fn installed(&self, name: &str) -> Option { + let current = self.link(name, "current"); + let factory = self.factory.get(name).cloned(); + match (current, factory) { + (Some(c), Some(f)) => Some(if version_cmp(&c, &f).is_ge() { c } else { f }), + (c, f) => c.or(f), + } + } + + fn bad(&self, name: &str) -> BTreeSet { + fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect() + } + + /// Names of all packages: on the server, installed or built in. + fn names(&self, latest: &BTreeMap) -> BTreeSet { + let mut names: BTreeSet = latest.keys().cloned().collect(); + names.extend(self.factory.keys().cloned()); + if let Ok(entries) = fs::read_dir(&self.root) { + names.extend(entries.flatten().filter_map(|e| e.file_name().into_string().ok()).filter(|n| registry::is_ours(n))); + } + names + } + + /// Records the server's versions; returns the packages that need an update. + pub fn refresh(&self, latest: &BTreeMap) -> Vec { + let mut pending = Vec::new(); + for name in self.names(latest) { + let Some(v) = latest.get(&name) else { continue }; + let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt()); + if newer && !self.bad(&name).contains(v) { + pending.push(Pending { name: name.clone(), version: v.clone() }); + } + } + let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + self.write_status(|s| { + s.checked_at = now; + s.packages = self + .names(latest) + .into_iter() + .map(|name| PackageStatus { available: latest.get(&name).cloned(), installed: String::new(), staged: None, name }) + .collect(); + }); + pending + } + + pub fn download_dir_path(&self) -> PathBuf { + self.root.join(".download") + } + + pub fn download_dir(&self) -> Result { + let d = self.download_dir_path(); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d)?; + Ok(d) + } + + /// Checks the signature and unpacks into `//`. + pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> { + let data = fs::read(pkg)?; + let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?; + let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?; + key.verify_strict(&data, &sig).context("bad signature")?; + + let dir = self.dir(name); + fs::create_dir_all(&dir)?; + let dest = dir.join(version); + if dest.is_dir() { + if self.link(name, "current").as_deref() == Some(version) || self.link(name, "previous").as_deref() == Some(version) { + return Ok(()); + } + fs::remove_dir_all(&dest)?; + } + let tmp = dir.join(format!(".tmp-{version}")); + let _ = fs::remove_dir_all(&tmp); + fs::create_dir_all(&tmp)?; + let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?; + let mut archive = tar::Archive::new(decoder); + archive.set_preserve_permissions(true); + archive.set_preserve_ownerships(false); + archive.unpack(&tmp).context("unpacking")?; + + let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?; + if info.name != name || info.version != version { + let _ = fs::remove_dir_all(&tmp); + bail!("package says it is {} {}, expected {name} {version}", info.name, info.version); + } + fs::rename(&tmp, &dest)?; + Ok(()) + } + + pub fn stage(&self, name: &str, version: &str) -> Result<()> { + self.set_link(name, "staged", version) + } + + /// Makes every staged package live. + pub fn apply_staged(&self) -> Result { + let mut applied = Applied::default(); + let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) }; + for e in entries.flatten() { + let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue }; + let Some(v) = self.staged(&name) else { continue }; + if self.link(&name, "current").as_deref() != Some(v.as_str()) { + if let Some(cur) = self.link(&name, "current") { + self.set_link(&name, "previous", &cur)?; + } + self.set_link(&name, "current", &v)?; + log::info!("{name} {v} is live"); + if name == SHELL { + fs::write(self.dir(&name).join("trial"), &v)?; + applied.shell = true; + } else { + applied.apps = true; + } + } + self.remove_link(&name, "staged"); + } + self.link_apps()?; + Ok(applied) + } + + /// apps/ -> ../sf-app-/current for every installed app. + fn link_apps(&self) -> Result<()> { + let apps = self.root.join("apps"); + fs::create_dir_all(&apps)?; + let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) }; + for e in entries.flatten() { + let Some(name) = e.file_name().into_string().ok() else { continue }; + let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue }; + let link = apps.join(id); + if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() { + symlink(format!("../{name}/current"), &link)?; + } + } + Ok(()) + } + + /// The launcher started fine on the new shell. + pub fn confirm_shell(&self) -> Result<()> { + if fs::remove_file(self.dir(SHELL).join("trial")).is_ok() { + log::info!("shell {} confirmed", self.link(SHELL, "current").unwrap_or_default()); + } + self.write_status(|_| {}); + Ok(()) + } + + /// The new shell keeps failing: back to the previous one (or the factory + /// copy) and never install this version again. True if anything changed. + pub fn rollback_shell(&self) -> Result { + let trial = self.dir(SHELL).join("trial"); + if !trial.exists() { + return Ok(false); + } + if let Some(bad) = self.link(SHELL, "current") { + log::warn!("shell {bad} failed to start, rolling back"); + let mut list = self.bad(SHELL); + list.insert(bad); + fs::write(self.dir(SHELL).join("bad"), list.into_iter().collect::>().join("\n") + "\n")?; + } + match self.link(SHELL, "previous") { + Some(prev) => { + self.set_link(SHELL, "current", &prev)?; + self.remove_link(SHELL, "previous"); + } + None => self.remove_link(SHELL, "current"), + } + fs::remove_file(&trial)?; + self.gc(); + self.write_status(|_| {}); + Ok(true) + } + + /// Removes versions nothing points at, and leftovers of failed unpacks. + pub fn gc(&self) { + let Ok(entries) = fs::read_dir(&self.root) else { return }; + for e in entries.flatten() { + let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue }; + let keep: BTreeSet = ["current", "previous", "staged"].iter().filter_map(|w| self.link(&name, w)).collect(); + let Ok(versions) = fs::read_dir(e.path()) else { continue }; + for v in versions.flatten() { + let file = v.file_name().to_string_lossy().to_string(); + let is_version = registry::is_release(&file) && v.path().is_dir() && !v.path().is_symlink(); + if (is_version && !keep.contains(&file)) || file.starts_with(".tmp-") { + log::info!("removing {name}/{file}"); + let _ = fs::remove_dir_all(v.path()); + } + } + } + } + + pub fn read_status(&self) -> Status { + fs::read_to_string(self.root.join("status.json")).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default() + } + + /// Updates status.json; installed/staged are always re-read from disk. + pub fn write_status(&self, f: impl FnOnce(&mut Status)) { + let mut s = self.read_status(); + if s.state.is_empty() { + s.state = "idle".into(); + } + f(&mut s); + let mut names: BTreeSet = s.packages.iter().map(|p| p.name.clone()).collect(); + names.extend(self.names(&BTreeMap::new())); + let old: BTreeMap> = s.packages.iter().map(|p| (p.name.clone(), p.available.clone())).collect(); + s.packages = names + .into_iter() + .map(|name| PackageStatus { + installed: self.installed(&name).unwrap_or_default(), + available: old.get(&name).cloned().flatten(), + staged: self.staged(&name), + name, + }) + .collect(); + s.shell_trial = fs::read_to_string(self.dir(SHELL).join("trial")).ok().map(|t| t.trim().to_string()); + let tmp = self.root.join(".status.json.tmp"); + let ok = serde_json::to_vec_pretty(&s).ok().and_then(|data| fs::write(&tmp, data).ok()).and_then(|_| fs::rename(&tmp, self.root.join("status.json")).ok()); + if ok.is_none() { + log::warn!("could not write status.json"); + } + } + + pub fn set_state(&self, state: &str, message: &str) { + self.write_status(|s| { + s.state = state.into(); + s.message = message.into(); + }); + } +} diff --git a/docs/updates.md b/docs/updates.md new file mode 100644 index 0000000..da49c26 --- /dev/null +++ b/docs/updates.md @@ -0,0 +1,80 @@ +# Frissítések (csomagok) + +A TV nem image-et frissít, hanem csomagokat: +- `sf-shell`: a felület (`sf-launcher`, `sf-remote`, `sf-pair`); +- `sf-app-`: egy-egy app (`apps//` tartalma). + +Az image (rendszer, scriptek, unitok, `sf-update`) csak újratelepítéssel változik. A gyári shell és a gyári appok az image-ben maradnak, és tartalékként mindig elérhetők. + +## Kiadás +Egy csomag akkor jelenik meg, ha a verziója még nincs fent a registryben. Kiadáshoz emeld a verziót, és pushold a `main` ágat: +- shell: `Cargo.toml` → `[workspace.package] version`; +- app: `apps//app.toml` → `version`. + +A `.gitea/workflows/packages.yml` workflow a `build` runneren lefordítja, aláírja és feltölti a csomagot (`tools/pkg/packages.sh --upload`). Ugyanez kézzel, a WSL-ből: +```sh +SF_SIGNING_KEY_FILE=~/.smartfox/signing-key.pem SF_PACKAGE_TOKEN= bash tools/pkg/packages.sh --upload shell app:youtube +``` +A `--upload` nélkül csak a `target/packages/` mappába építi a csomagot. + +**A runner hostja közös és kevés rajta a hely, ezért a workflow:** +- a hoston már meglévő `runner-images:ubuntu-latest` image-ben fut, nem tölt le újat; +- nem használ `uses:` actiont, így action-cache sem keletkezik; +- minden fájlját a `/tmp/sf-build` mappában tartja, és a végén törli. + +## Protokoll +Registry: Gitea generic packages, `https://gitea.bluefox.support`, tulajdonos: `bluefox`. + +| Mit | Kérés | +|---|---| +| Verziók listája | `GET /api/v1/packages/bluefox?type=generic&q=sf-&limit=50&page=N` | +| Csomag | `GET /api/packages/bluefox/generic///-.tar.zst` | +| Aláírás | ugyanez `.sig` végződéssel | + +**A csomag:** `tar.zst`, a gyökerében egy `pkg.toml` fájllal (`name`, `version`). +- `sf-shell`: `bin/sf-launcher`, `bin/sf-remote`, `bin/sf-pair`; +- `sf-app-`: az `app.toml` és az app többi fájlja. + +**Aláírás:** a `.sig` 64 bájtos Ed25519 aláírás a teljes `.tar.zst` fájlon (`openssl pkeyutl -sign -rawin`). +- A publikus kulcs a `/usr/share/smartfox/update.toml` fájlban van (`public_key`). +- A privát kulcs: a `SF_SIGNING_KEY` CI-secret, és egy példány a fejlesztő gépén (`%USERPROFILE%\.smartfox\signing-key.pem`). +- Aláírás nélküli vagy hibásan aláírt csomagot a TV nem telepít. Azt sem, amelyiknek a `pkg.toml`-ja más nevet vagy verziót mond. + +**Csak release verzió települ** (`1.2.3`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le. + +**Belépés:** a `fox-tv` felhasználó tokenje, csak `read:package` joggal. Az image építésekor az `image/secrets/update-token` fájlból kerül a `/usr/share/smartfox/update-token` fájlba (`fox-tv:`; a fájl nincs a gitben). Egy adott TV-n felülírható a `/var/lib/sf-pkg/update.toml` fájllal (`token_file`, `server` stb.). + +## A TV-n +``` +/var/lib/sf-pkg/ root írja + // kibontott csomag + /current -> ami fut (ha nincs: a gyári példány) + /previous -> visszaálláshoz + /staged -> letöltve, a következő induláskor élesedik + /bad hibás verziók, többé nem települnek + sf-shell/trial új shell, még nincs visszaigazolva + apps/ -> ../sf-app-/current + status.json a launcher Frissítések sora ezt mutatja +/var/lib/smartfox/update-requests/ a launcher (tv) kérései: check, install, confirm, rollback +``` + +**Unitok:** +- `sf-update-auto.timer`: indulás után 10 perccel, majd 6 óránként letölti az újdonságokat (`sf-update auto`). Ezek csak a következő induláskor élesednek. +- `sf-update-apply.service`: induláskor, még a felület előtt élesíti a letöltött csomagokat (`sf-update apply`). +- `sf-update-requests.path`: ha a launcher kérésfájlt tesz a mappába, rootként lefuttatja az `sf-update requests` parancsot. A kérésnek csak a fájlneve számít, a tartalma nem. +- A Beállítások → Rendszer → **Frissítések** oldalon a „Telepítés most” azonnal letölt, élesít, és újraindítja a felületet (`install`). + +**Ha az új shell nem indul el:** +1. Élesítéskor a `sf-shell/trial` fájl jelzi, hogy az új shell próbaidőn van. +2. Az `sf-launcher-start` számolja az indításokat. A launcher 30 mp futás után `confirm` kérést küld, ezzel a próbaidő véget ér. +3. Ha 3 indítás alatt nem jön `confirm`, az `sf-launcher-start` `rollback` kérést küld, és addig a gyári launchert indítja. +4. Az `sf-update` visszaáll az előző verzióra (vagy a gyárira), a hibás verziót felírja a `bad` fájlba, és újraindítja a felületet. + +Az `sf-remote` a `sf-shell-exec` wrapperen át ugyanígy a telepített példányt futtatja, ha van ilyen. + +**Hibakeresés:** +```sh +sf-update status # status.json +journalctl -u 'sf-update*' +systemctl start sf-update-auto.service # keresés és letöltés most +``` diff --git a/image/build.sh b/image/build.sh index 02281ea..dbdd7c7 100644 --- a/image/build.sh +++ b/image/build.sh @@ -21,7 +21,7 @@ if ! command -v cargo >/dev/null; then [ -x "$HOME/.cargo/bin/cargo" ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal export PATH="$HOME/.cargo/bin:$PATH" fi -cargo build --release -p sf-launcher -p sf-remote +cargo build --release -p sf-launcher -p sf-remote -p sf-update echo "== stage" STAGE="$WORK/image/stage" @@ -29,9 +29,27 @@ rm -rf "$STAGE" install -Dm755 target/release/sf-launcher "$STAGE/usr/bin/sf-launcher" install -Dm755 target/release/sf-remote "$STAGE/usr/bin/sf-remote" install -Dm755 tools/siri-remote/fastpair.py "$STAGE/usr/bin/sf-pair" +install -Dm755 target/release/sf-update "$STAGE/usr/bin/sf-update" +# Registry login for sf-update (read:package only). Kept out of git; without it +# the TV can only update if the registry allows anonymous downloads. +if [ -f image/secrets/update-token ]; then + install -Dm600 image/secrets/update-token "$STAGE/usr/share/smartfox/update-token" +else + echo "warning: image/secrets/update-token is missing, sf-update will log in anonymously" +fi mkdir -p "$STAGE/usr/share/smartfox" cp -r apps "$STAGE/usr/share/smartfox/apps" -chmod +x image/mkosi.postinst.chroot image/mkosi.extra/usr/bin/sf-session image/mkosi.extra/usr/bin/sf-launcher-start image/mkosi.extra/usr/bin/sf-remote-debug image/mkosi.extra/usr/bin/sf-diag image/*.sh tools/vm/*.sh tools/siri-remote/*.sh tools/siri-remote/*.py +# Versions of the factory copies: sf-update only installs newer packages. +{ + echo "sf-shell = \"$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' Cargo.toml)\"" + for d in apps/*/; do + v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$d/app.toml" | head -1) + [ -n "$v" ] && echo "sf-app-$(basename "$d") = \"$v\"" + done +} >"$STAGE/usr/share/smartfox/factory-versions.toml" +mkdir -p "$STAGE/usr/share/doc/smartfox" +cp docs/updates.md "$STAGE/usr/share/doc/smartfox/updates.md" +chmod +x image/mkosi.postinst.chroot image/mkosi.extra/usr/bin/sf-session image/mkosi.extra/usr/bin/sf-launcher-start image/mkosi.extra/usr/bin/sf-remote-debug image/mkosi.extra/usr/bin/sf-diag image/mkosi.extra/usr/bin/sf-shell-exec image/*.sh tools/vm/*.sh tools/siri-remote/*.sh tools/siri-remote/*.py echo "== mkosi" # Cache and output stay on the Linux filesystem (NTFS mounts break mkosi). diff --git a/image/mkosi.extra/usr/bin/sf-launcher-start b/image/mkosi.extra/usr/bin/sf-launcher-start index 20ad470..2754d84 100644 --- a/image/mkosi.extra/usr/bin/sf-launcher-start +++ b/image/mkosi.extra/usr/bin/sf-launcher-start @@ -5,4 +5,30 @@ if [ -n "${SMARTFOX_MODE:-}" ]; then wlr-randr --output "$OUT" --custom-mode "$SMARTFOX_MODE" || echo "sf-launcher-start: could not set $SMARTFOX_MODE on $OUT" fi -exec /usr/bin/sf-launcher --fullscreen --apps /usr/share/smartfox/apps + +# The launcher from the installed sf-shell package, else the factory copy. +# A new shell is on trial until it has run for a while (it then drops a +# "confirm" request). If it doesn't get there in 3 starts, ask sf-update to +# roll it back and start the factory launcher meanwhile (docs/updates.md). +PKG=/var/lib/sf-pkg/sf-shell +REQ=/var/lib/smartfox/update-requests +TRIES=/var/lib/smartfox/shell-tries +LAUNCHER=/usr/bin/sf-launcher +if [ -x "$PKG/current/bin/sf-launcher" ]; then + LAUNCHER="$PKG/current/bin/sf-launcher" + if [ -f "$PKG/trial" ]; then + n=$(($(cat "$TRIES" 2>/dev/null || echo 0) + 1)) + echo "$n" >"$TRIES" + if [ "$n" -gt 3 ]; then + echo "sf-launcher-start: shell $(cat "$PKG/trial") failed $((n - 1)) times, rolling back" + rm -f "$TRIES" + touch "$REQ/rollback" + LAUNCHER=/usr/bin/sf-launcher + else + export SMARTFOX_SHELL_TRIAL=1 + fi + else + rm -f "$TRIES" + fi +fi +exec "$LAUNCHER" --fullscreen --apps /usr/share/smartfox/apps --apps /var/lib/sf-pkg/apps diff --git a/image/mkosi.extra/usr/bin/sf-shell-exec b/image/mkosi.extra/usr/bin/sf-shell-exec new file mode 100644 index 0000000..b7f2432 --- /dev/null +++ b/image/mkosi.extra/usr/bin/sf-shell-exec @@ -0,0 +1,9 @@ +#!/bin/sh +# Runs a shell binary: the installed sf-shell package if there is one, else +# the factory copy in /usr/bin (sf-update, docs/updates.md). +# sf-shell-exec sf-remote --home-socket ... +name=$1 +shift +pkg=/var/lib/sf-pkg/sf-shell/current/bin/$name +[ -x "$pkg" ] && exec "$pkg" "$@" +exec "/usr/bin/$name" "$@" diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service b/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service index 5d3ec3c..d1ad63b 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service @@ -4,7 +4,7 @@ After=bluetooth.service Wants=bluetooth.service [Service] -ExecStart=/usr/bin/sf-remote --home-socket /run/user/1000/smartfox.sock +ExecStart=/usr/bin/sf-shell-exec sf-remote --home-socket /run/user/1000/smartfox.sock Environment=RUST_LOG=info Restart=always RestartSec=2 diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service new file mode 100644 index 0000000..9968260 --- /dev/null +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service @@ -0,0 +1,15 @@ +[Unit] +Description=SmartFox: switch downloaded packages live before the TV starts +DefaultDependencies=no +RequiresMountsFor=/var +After=local-fs.target sf-data-init.service +Before=getty@tty1.service sf-remote.service +ConditionPathIsMountPoint=/var + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/usr/bin/sf-update apply + +[Install] +WantedBy=multi-user.target diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service new file mode 100644 index 0000000..693b62a --- /dev/null +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service @@ -0,0 +1,10 @@ +[Unit] +Description=SmartFox: download new shell and app packages (live at next boot) +Wants=network-online.target +After=network-online.target sf-update-apply.service + +[Service] +Type=oneshot +ExecStart=/usr/bin/sf-update auto +Nice=10 +IOSchedulingClass=idle diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer new file mode 100644 index 0000000..2da177b --- /dev/null +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer @@ -0,0 +1,10 @@ +[Unit] +Description=SmartFox: look for package updates a few times a day + +[Timer] +OnBootSec=10min +OnUnitActiveSec=6h +RandomizedDelaySec=30min + +[Install] +WantedBy=timers.target diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path new file mode 100644 index 0000000..c1680fa --- /dev/null +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path @@ -0,0 +1,10 @@ +[Unit] +Description=SmartFox: watch for update requests from the launcher +Documentation=file:/usr/share/doc/smartfox/updates.md + +[Path] +DirectoryNotEmpty=/var/lib/smartfox/update-requests +Unit=sf-update-requests.service + +[Install] +WantedBy=paths.target diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service new file mode 100644 index 0000000..a0b1d4f --- /dev/null +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service @@ -0,0 +1,7 @@ +[Unit] +Description=SmartFox: handle update requests (check, install, confirm, rollback) +After=network-online.target sf-update-apply.service + +[Service] +Type=oneshot +ExecStart=/usr/bin/sf-update requests diff --git a/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf b/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf index 41986f0..ba505be 100644 --- a/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf +++ b/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf @@ -1,2 +1,6 @@ # The launcher (user tv) writes the remote debugging switch here. d /var/lib/smartfox 0755 tv tv - +# sf-update: installed packages (root only writes here) and the launcher's +# request files (check, install, confirm, rollback; see docs/updates.md). +d /var/lib/sf-pkg 0755 root root - +d /var/lib/smartfox/update-requests 0755 tv tv - diff --git a/image/mkosi.extra/usr/share/smartfox/update.toml b/image/mkosi.extra/usr/share/smartfox/update.toml new file mode 100644 index 0000000..548dd76 --- /dev/null +++ b/image/mkosi.extra/usr/share/smartfox/update.toml @@ -0,0 +1,9 @@ +# sf-update: where the shell and app packages come from (docs/updates.md). +# Per-TV overrides (another server, a new token): /var/lib/sf-pkg/update.toml +server = "https://gitea.bluefox.support" +owner = "bluefox" +# "user:token" with read:package only; put there by image/build.sh from +# image/secrets/update-token (not in git). +token_file = "/usr/share/smartfox/update-token" +# Ed25519 key that signs every package (private half: CI secret SF_SIGNING_KEY). +public_key = "8CX4spdfqE17SPGoXWMrLxJCusyAxIZndOc/0zvaal4=" diff --git a/image/mkosi.postinst.chroot b/image/mkosi.postinst.chroot index c97967d..657432c 100644 --- a/image/mkosi.postinst.chroot +++ b/image/mkosi.postinst.chroot @@ -18,7 +18,7 @@ fi getent group netdev >/dev/null || groupadd -r netdev usermod -aG netdev tv -systemctl enable systemd-networkd systemd-resolved iwd bluetooth sf-remote.service sf-data-init.service sf-remote-debug-boot.service sf-remote-debug.path +systemctl enable systemd-networkd systemd-resolved iwd bluetooth sf-remote.service sf-data-init.service sf-remote-debug-boot.service sf-remote-debug.path sf-update-apply.service sf-update-requests.path sf-update-auto.timer # sshd only runs when remote debugging is on (Settings > System, sf-remote-debug). systemctl disable ssh.service ssh.socket 2>/dev/null || true systemctl set-default multi-user.target @@ -62,7 +62,7 @@ printf '[Icon Theme]\nName=smartfox-blank\nComment=Invisible cursor\n' >/usr/sha mkdir -p /usr/share/icons/default printf '[Icon Theme]\nInherits=smartfox-blank\n' >/usr/share/icons/default/index.theme -chmod +x /usr/bin/sf-session /usr/bin/sf-pair /usr/bin/sf-remote-debug /usr/bin/sf-diag 2>/dev/null || true +chmod +x /usr/bin/sf-session /usr/bin/sf-pair /usr/bin/sf-remote-debug /usr/bin/sf-diag /usr/bin/sf-shell-exec 2>/dev/null || true # Factory copy of /var: sf-data-init.service fills the empty data partition from it. rm -rf /usr/share/factory/var diff --git a/tools/pkg/packages.sh b/tools/pkg/packages.sh new file mode 100644 index 0000000..dfd191f --- /dev/null +++ b/tools/pkg/packages.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Builds, signs and uploads SmartFox packages (protocol: docs/updates.md). +# +# tools/pkg/packages.sh [--upload] [shell] [app:...] [apps] +# +# With no package names it does the shell and every app. A package whose +# version is already in the registry is skipped (bump the version to publish): +# shell version = [workspace.package] version in Cargo.toml +# app: version = "version" in apps//app.toml +# +# Environment: +# SF_SIGNING_KEY Ed25519 private key (PEM), or SF_SIGNING_KEY_FILE +# SF_PACKAGE_TOKEN "user:token", or a token of SF_OWNER, with write:package (upload only) +# SF_GITEA default https://gitea.bluefox.support +# SF_OWNER default bluefox +# SF_OUT output folder, default target/packages +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +GITEA="${SF_GITEA:-https://gitea.bluefox.support}" +OWNER="${SF_OWNER:-bluefox}" +OUT="${SF_OUT:-$ROOT/target/packages}" +# Binaries in the shell package (built with cargo --release). +SHELL_BINS=(sf-launcher sf-remote) + +UPLOAD=0 +WANT=() +for a in "$@"; do + case "$a" in + --upload) UPLOAD=1 ;; + shell | apps | app:*) WANT+=("$a") ;; + *) echo "unknown argument: $a" >&2; exit 2 ;; + esac +done +[ ${#WANT[@]} -gt 0 ] || WANT=(shell apps) + +KEY_FILE="${SF_SIGNING_KEY_FILE:-}" +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT +if [ -z "$KEY_FILE" ]; then + [ -n "${SF_SIGNING_KEY:-}" ] || { echo "SF_SIGNING_KEY or SF_SIGNING_KEY_FILE is needed" >&2; exit 2; } + KEY_FILE="$TMP/key.pem" + (umask 077; printf '%s\n' "$SF_SIGNING_KEY" >"$KEY_FILE") +fi + +auth() { + case "${SF_PACKAGE_TOKEN:-}" in + *:*) printf -- '-u\n%s\n' "$SF_PACKAGE_TOKEN" ;; + ?*) printf -- '-u\n%s:%s\n' "$OWNER" "$SF_PACKAGE_TOKEN" ;; + esac +} +mapfile -t AUTH < <(auth) + +url() { echo "$GITEA/api/packages/$OWNER/generic/$1/$2/$1-$2.tar.zst"; } + +published() { + [ "$UPLOAD" = 1 ] || return 1 + local code + code=$(curl -s -o /dev/null -w '%{http_code}' -I "${AUTH[@]}" "$(url "$1" "$2")") + [ "$code" = 200 ] +} + +# pack : tar.zst + .sig in $OUT, uploaded with --upload. +pack() { + local name=$1 version=$2 dir=$3 file + printf 'name = "%s"\nversion = "%s"\n' "$name" "$version" >"$dir/pkg.toml" + mkdir -p "$OUT" + file="$OUT/$name-$version.tar.zst" + tar --sort=name --owner=0 --group=0 --numeric-owner --mtime=@0 -C "$dir" -cf - . | zstd -q -19 -T0 -f -o "$file" + openssl pkeyutl -sign -inkey "$KEY_FILE" -rawin -in "$file" -out "$file.sig" + echo "built $(basename "$file") ($(du -h "$file" | cut -f1))" + if [ "$UPLOAD" = 1 ]; then + for f in "$file" "$file.sig"; do + curl -fsS "${AUTH[@]}" --upload-file "$f" "$GITEA/api/packages/$OWNER/generic/$name/$version/$(basename "$f")" >/dev/null + done + echo "uploaded $name $version" + fi +} + +toml_version() { sed -n 's/^version *= *"\(.*\)".*/\1/p' "$1" | head -1; } + +do_shell() { + local version + version=$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' "$ROOT/Cargo.toml") + if published sf-shell "$version"; then + echo "sf-shell $version: already published" + return + fi + local args=() + for b in "${SHELL_BINS[@]}"; do args+=(-p "$b"); done + (cd "$ROOT" && cargo build --release --locked "${args[@]}") + local dir="$TMP/sf-shell" + rm -rf "$dir" + mkdir -p "$dir/bin" + for b in "${SHELL_BINS[@]}"; do install -m755 "$ROOT/target/release/$b" "$dir/bin/$b"; done + install -m755 "$ROOT/tools/siri-remote/fastpair.py" "$dir/bin/sf-pair" + pack sf-shell "$version" "$dir" +} + +do_app() { + local id=$1 src="$ROOT/apps/$1" version + [ -f "$src/app.toml" ] || { echo "no app $id" >&2; return 1; } + version=$(toml_version "$src/app.toml") + [ -n "$version" ] || { echo "apps/$id/app.toml has no version, skipped"; return; } + if published "sf-app-$id" "$version"; then + echo "sf-app-$id $version: already published" + return + fi + local dir="$TMP/sf-app-$id" + rm -rf "$dir" + cp -r "$src" "$dir" + chmod -R u=rwX,go=rX "$dir" + pack "sf-app-$id" "$version" "$dir" +} + +for w in "${WANT[@]}"; do + case "$w" in + shell) do_shell ;; + apps) for d in "$ROOT"/apps/*/; do do_app "$(basename "$d")"; done ;; + app:*) do_app "${w#app:}" ;; + esac +done