From 64bfeccccb80f038dc628017fa94cce34e410242 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:40 -0500 Subject: [PATCH 01/10] Catalogue, dependencies and updates in the engine engine catalog [--refresh], catalog-plan ..., catalog-install ... [--any-car], updates [--refresh], update ... | --all | hmgapi, update-check (wifi.sh runs it each time home Wi-Fi comes up; the owner switches no_update_check and auto_stage_updates). - The catalogue: catalog/ on GitHub, from index.json (tools/catalog.py index) or GitHub's listing of the folder; cached in /data/hmgapi/catalog, updates also in public/updates.json. HMG-API's own release: its newest from the releases API (pre-releases only on one), the update zip's SHA-256 from SHA256SUMS. - Dependencies: requires met by what's installed, or by the catalogue's version installed first; a required mod that's off is turned on; the downloaded package's mod.json is read again for requires its entry doesn't name. Loops, conflicts, unmet ranges, a mod for a newer HMG-API (and, without --any-car, another car) are refused; everything is downloaded and checked before the first install. Removing a mod others require says which. - Trust: the entry's SHA-256, then Packages' signature check with the entry's author key (--uuid) on a first install; HMG-API's release key for HMG-API (UsbUpdates). Nothing applied. - tools/catalog.py: entries carry requires/conflicts (from mod.json, checked in bumps); catalog.py index. catalog-test.sh plays GitHub from files. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + core/hmgapid/hmgapid.c | 14 +- core/runtime/catalog-test.sh | 234 +++++ core/runtime/homewifi-test.sh | 3 + core/runtime/java/hmgapi/engine/Catalog.java | 920 ++++++++++++++++++ core/runtime/java/hmgapi/engine/Engine.java | 7 + core/runtime/java/hmgapi/engine/HomeWifi.java | 8 + docs/mod-reference.md | 4 +- tools/catalog.py | 41 +- tools/test-all.sh | 4 +- 10 files changed, 1227 insertions(+), 15 deletions(-) create mode 100644 core/runtime/catalog-test.sh create mode 100644 core/runtime/java/hmgapi/engine/Catalog.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 53f5e802..062e326b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- **Dependencies are installed with a mod.** A mod's `requires` (copied into its catalogue + entry by `catalog.py add`, and read again from the downloaded package's `mod.json`) are met + by what's installed, or by the catalogue's version, installed first; a required mod that's + turned off is turned on. Loops, conflicts, a requirement newer than the catalogue's or not + in it, and a mod for a newer HMG-API are refused before anything is downloaded or installed. + Everything is downloaded and checked before the first install. Removing a mod others + require says which won't load. - **Home Wi-Fi joins on cars whose Wi-Fi library checks a checksum** (Ioniq 5 US 260507). The stock library starts the car's Wi-Fi client only if `wpa_supplicant_crc32.conf` holds the CRC-32 of `wpa_supplicant.conf`; HMG-API's saved networks didn't update it, so the client diff --git a/core/hmgapid/hmgapid.c b/core/hmgapid/hmgapid.c index 1ea04bf3..829b55e4 100644 --- a/core/hmgapid/hmgapid.c +++ b/core/hmgapid/hmgapid.c @@ -642,10 +642,14 @@ static int op_engine(int fd, int argc, char **argv) if (!(seq(sub, "plan") || seq(sub, "apply") || seq(sub, "keep") || seq(sub, "restore") || seq(sub, "status") || seq(sub, "recover") || seq(sub, "install") || seq(sub, "remove") || seq(sub, "map") || seq(sub, "verify-map") || seq(sub, "usb-scan") || seq(sub, "update-hmgapi") || seq(sub, "apps") || seq(sub, "probe") - || seq(sub, "map-car") || seq(sub, "report") || seq(sub, "problem") || seq(sub, "nemesis-sync"))) { + || seq(sub, "map-car") || seq(sub, "report") || seq(sub, "problem") || seq(sub, "nemesis-sync") + || seq(sub, "catalog") || seq(sub, "catalog-plan") || seq(sub, "catalog-install") || seq(sub, "updates") + || seq(sub, "update") || seq(sub, "update-check"))) { say(fd, "usage: engine plan | apply [--trial] [--force] | keep | restore | status | recover | install | remove " " | nemesis-sync | map | map-car [--local | --write | --forget] | verify-map | report [--usb]" - " | problem record [--no-log] [--crash-dumps] [--crash-reports] [--kernel] [--usb] [--seconds N] | problem stop\n"); + " | problem record [--no-log] [--crash-dumps] [--crash-reports] [--kernel] [--usb] [--seconds N] | problem stop" + " | catalog [--refresh] | catalog-plan ... | catalog-install ... [--any-car] | updates [--refresh]" + " | update ... | --all | hmgapi | update-check\n"); return 2; } a[n++] = APP_PROCESS; @@ -1718,8 +1722,10 @@ static int op_allow(int fd, int argc, char **argv) unsigned long long st[16]; if (seq(argv[1], "commands_reset") && argc == 3 && seq(argv[2], "on")) return forget_answers(fd); if (!seq(argv[1], "startup_notice") && !seq(argv[1], "block_ambient_light") && !seq(argv[1], "trust_commands") - && !seq(argv[1], "ota_updates") && !seq(argv[1], "home_wifi") && !seq(argv[1], "testing_maps") && !seq(argv[1], "no_local_points") && !answer_name(argv[1])) { - say(fd, "unknown switch (startup_notice, block_ambient_light, trust_commands, ota_updates, home_wifi, testing_maps, no_local_points, cmd.., " + && !seq(argv[1], "ota_updates") && !seq(argv[1], "home_wifi") && !seq(argv[1], "testing_maps") && !seq(argv[1], "no_local_points") + && !seq(argv[1], "no_update_check") && !seq(argv[1], "auto_stage_updates") && !answer_name(argv[1])) { + say(fd, "unknown switch (startup_notice, block_ambient_light, trust_commands, ota_updates, home_wifi, testing_maps, no_local_points, " + "no_update_check, auto_stage_updates, cmd.., " "nocmd.., commands_reset)\n"); return 2; } diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh new file mode 100644 index 00000000..c744a166 --- /dev/null +++ b/core/runtime/catalog-test.sh @@ -0,0 +1,234 @@ +#!/bin/sh +# Off-car test of the catalogue and updates (Catalog): the catalogue fetched (index.json, or GitHub's +# folder listing), what each mod would do here, dependencies (requires installed first, a required +# mod that's off turned on, requires only the package names, loops, conflicts, what isn't in the +# catalogue), downloads checked (SHA-256, the package being what the entry says, the author key), +# updates (mods and HMG-API's own release), the automatic check, and a removal's warning. +# GitHub is played by files (HMGAPI_TEST_WEB: NativeFetch.Web). +set -e +cd "$(dirname "$0")/../.." +CP=$(mktemp -d); T=$(mktemp -d); trap 'rm -rf "$T" "$CP"' EXIT +sh tools/engine-classes.sh "$CP" 2>/dev/null +R=$T/root D=$T/root/data/hmgapi W=$T/web +fail=0 +check() { if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: wanted [$2], got [$3]"; fail=1; fi; } +has() { case "$3" in *"$2"*) echo "ok $1" ;; *) echo "FAIL $1: wanted [$2] in [$3]"; fail=1 ;; esac; } +hasnt() { case "$3" in *"$2"*) echo "FAIL $1: [$2] in [$3]"; fail=1 ;; *) echo "ok $1" ;; esac; } +eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 HMGAPI_TEST_WEB=$W java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +offline() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +sig() { java -cp "$CP" hmgapi.engine.Signing "$@"; } +js() { python3 -c "import json,sys; d=json.loads(sys.stdin.read()[sys.stdin.read and 0:]); print(eval(sys.argv[1]))" "$1"; } +j() { printf '%s' "$out" | python3 -c "import json,sys; t=sys.stdin.read(); d=json.loads(t[t.index('{'):]); print(eval(sys.argv[1]))" "$1"; } +installed() { [ -f "$D/mods/$1/mod.json" ] && python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['version'])" "$D/mods/$1/mod.json" || echo none; } + +mkdir -p "$D/mods" "$D/settings" "$D/maps" "$W" +sig keygen $T/author.key > /dev/null +sig keygen $T/other.key > /dev/null +U=$(sig uuid $T/author.key); O=$(sig uuid $T/other.key) +printf '{"authors": {"%s": {"name": "Test Author"}}}\n' "$U" > "$D/maps/authors.json" +CAT=$W/raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog +DL=$W/github.com/test/releases/download +mkdir -p "$CAT" "$DL" "$W/objects.githubusercontent.com/r" + +# pkg [key]: a signed package, served from a release (through GitHub's +# redirect to its asset host), and its catalogue entry (extras for the entry: $ENTRY) +pkg() { + rm -rf $T/m; mkdir -p $T/m + printf '{"id": "%s", "name": "%s mod", "version": "%s", "hmgapi": ">=1.0.0"%s}\n' "$1" "$1" "$2" "$3" > $T/m/mod.json + sig sign $T/m ${4:-$T/author.key} > /dev/null + z=$W/objects.githubusercontent.com/r/$1-$2.zip + (cd $T/m && rm -f "$z" && zip -q -r -X "$z" .) + echo "https://objects.githubusercontent.com/r/$1-$2.zip" > "$DL/$1-$2.zip.redirect" + sha=$(python3 -c "import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" "$z") + printf '{"id": "%s", "name": "%s mod", "description": "the %s mod", "authors": ["tester"], "uuid": "%s", "version": "%s", "repo": "https://github.com/test/%s", "download": "https://github.com/test/releases/download/%s-%s.zip", "sha256": "%s", "hmgapi": ">=1.0.0"%s}\n' \ + "$1" "$1" "$1" "$U" "$2" "$1" "$1" "$2" "$sha" "$ENTRY" > "$CAT/$1.json" + ENTRY= +} +listing() { # GitHub's folder listing, from the entries there + mkdir -p $W/api.github.com/repos/Open-HMG/HMG-API/contents + (cd "$CAT" && ls *.json | python3 -c "import json,sys; print(json.dumps([{'name': n.strip(), 'type': 'file'} for n in sys.stdin]))") \ + > "$W/api.github.com/repos/Open-HMG/HMG-API/contents/catalog_ref=main" +} +mkdir -p $W/api.github.com/repos/Open-HMG/HMG-API +echo '[]' > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" + +ENTRY=', "requires": ["base >=1.0.0"]'; pkg app 1.0.0 ', "requires": ["base >=1.0.0"]' +pkg base 1.0.0 +ENTRY=', "hmgapi": ">=9.0.0"'; pkg future 1.0.0 '' +listing + +# ---- before any check +eng catalog +check "no catalogue yet: an empty list" 0 "$(j 'len(d["mods"])')" +check "... online (here: the test web)" True "$(j 'd["online"]')" + +# ---- home Wi-Fi off: nothing fetched +offline catalog --refresh +has "home Wi-Fi off: not fetched, said why" "Home Wi-Fi is off" "$out" +check "... nothing asked of GitHub" no "$([ -f $W/requests.log ] && echo yes || echo no)" +mkdir -p "$D/public"; echo '{"state": "searching", "rssi": 0, "freq": 0}' > "$D/public/wifi.json" +offline catalog --refresh +has "home Wi-Fi not joined yet: said so" "home Wi-Fi isn't connected (searching)" "$out" + +# ---- the catalogue, from GitHub's listing (no index.json) +eng catalog --refresh +check "fetched" 0 $rc +hasnt "... no error" '"error"' "$out" +check "three entries" "app base future" "$(j '" ".join(m["id"] for m in d["mods"])')" +has "... the listing came from GitHub's API" "api.github.com/repos/Open-HMG/HMG-API/contents/catalog?ref=main" "$(cat $W/requests.log)" +check "base: new" new "$(j '[m for m in d["mods"] if m["id"]=="base"][0]["status"]')" +check "app: its requires" "['base >=1.0.0']" "$(j '[m for m in d["mods"] if m["id"]=="app"][0]["requires"]')" +check "the author on the trusted list" True "$(j '[m for m in d["mods"] if m["id"]=="app"][0]["trusted"]')" +check "future: not for this HMG-API" "needs HMG-API >=9.0.0 (this is $(j 'd["hmgapi"]'))" "$(j '[m for m in d["mods"] if m["id"]=="future"][0]["unfit"]')" +check "cached for the app" yes "$([ -s $D/catalog/catalog.json ] && echo yes)" + +# ---- installing a mod takes what it requires, first +eng catalog-plan app +check "plan: base first, for app, then app" "base install app|app install None" "$(j '"|".join(s["id"]+" "+s["action"]+" "+str(s.get("for")) for s in d["steps"])')" +check "plan: ok" True "$(j 'd["ok"]')" +check "plan: nothing installed by it" none "$(installed base)" +eng catalog-install app +check "install app" 0 $rc +has "... base downloaded through the redirect, checked" "downloaded base 1.0.0" "$out" +has "... base installed first" "installing base 1.0.0 (app needs it)" "$out" +check "... both in place" "1.0.0 1.0.0" "$(installed base) $(installed app)" +has "... said to apply" "Apply changes (engine apply)" "$out" +check "... base before app" "base app" "$(printf '%s\n' "$out" | sed -n 's/^installing \([a-z]*\).*/\1/p' | tr '\n' ' ' | sed 's/ $//')" +eng catalog +check "both now the same as the catalogue" "same same" "$(j '" ".join(m["status"] for m in d["mods"] if m["id"] in ("app","base"))')" +eng catalog-install app +has "installed already: nothing to do" "nothing to install" "$out" +eng catalog-install future +check "a mod for a newer HMG-API: refused" 1 $rc +has "... why" "can't: future 1.0.0, which needs HMG-API >=9.0.0" "$out" +eng catalog-install nosuch +has "not in the catalogue" "nosuch isn't in the catalogue" "$out" + +# ---- a required mod that's turned off is turned on +: > "$D/mods/base/.disabled" +ENTRY=', "requires": ["base"]'; pkg tool 1.0.0 ', "requires": ["base"]'; listing +eng catalog --refresh +eng catalog-install tool +check "install tool" 0 $rc +has "... base turned on for it" "turned on base 1.0.0 (tool needs it)" "$out" +check "... base on" no "$([ -f $D/mods/base/.disabled ] && echo yes || echo no)" + +# ---- the package requires more than its entry says (an older entry): learned, installed first +pkg helper 1.0.0 +pkg extra 1.0.0 ', "requires": ["helper"]'; listing +eng catalog --refresh +eng catalog-install extra +check "install extra" 0 $rc +has "... helper, which only the package names, installed" "installing helper 1.0.0 (extra needs it)" "$out" +check "... both" "1.0.0 1.0.0" "$(installed helper) $(installed extra)" + +# ---- what can't be met: nothing installed +ENTRY=', "requires": ["missing >=1.0.0"]'; pkg lonely 1.0.0 ', "requires": ["missing >=1.0.0"]' +ENTRY=', "requires": ["base >=5.0.0"]'; pkg greedy 1.0.0 ', "requires": ["base >=5.0.0"]' +ENTRY=', "requires": ["loopb"]'; pkg loopa 1.0.0 ', "requires": ["loopb"]' +ENTRY=', "requires": ["loopa"]'; pkg loopb 1.0.0 ', "requires": ["loopa"]' +ENTRY=', "conflicts": ["app"]'; pkg rival 1.0.0 ', "conflicts": ["app"]' +ENTRY=', "requires": [{"id": "base"}, {"id": "nowhere", "optional": true}]'; pkg relaxed 1.0.0 '' +listing; eng catalog --refresh +eng catalog-install lonely +has "a requirement not in the catalogue" "lonely needs missing >=1.0.0, which isn't in the catalogue" "$out" +eng catalog-install greedy +has "a requirement newer than the catalogue's" "greedy needs base >=5.0.0, but the catalogue has base 1.0.0 (1.0.0 is installed)" "$out" +eng catalog-install loopa +has "a requires loop" "a requires loop" "$out" +check "... none of them installed" "none none none" "$(installed lonely) $(installed greedy) $(installed loopa)" +eng catalog-install rival +has "a conflict with an installed mod" "rival 1.0.0 conflicts with app 1.0.0 (installed)" "$out" +check "... not installed" none "$(installed rival)" +eng catalog-install relaxed +check "an optional requirement (NEMESIS's): not needed here" 0 $rc + +# ---- downloads that aren't what the entry says +pkg tampered 1.0.0 +python3 - "$CAT/tampered.json" <<'P' +import json,sys; d=json.load(open(sys.argv[1])); d["sha256"]="0"*64; json.dump(d,open(sys.argv[1],"w")) +P +pkg wrongkey 1.0.0 '' $T/other.key +listing; eng catalog --refresh +eng catalog-install tampered +has "another SHA-256: refused" "refused tampered 1.0.0: the download's SHA-256 is" "$out" +check "... not installed" none "$(installed tampered)" +check "... nothing left behind" no "$([ -d $D/catalog/downloads ] && echo yes || echo no)" +eng catalog-install wrongkey +has "signed by another key than the entry's: refused" "is signed by author key $O, not the expected $U" "$out" +check "... not installed" none "$(installed wrongkey)" + +# ---- updates: base 2.0.0 and an app 2.0.0 that needs it +ENTRY=', "requires": ["base >=2.0.0"]'; pkg app 2.0.0 ', "requires": ["base >=2.0.0"]' +pkg base 2.0.0; listing +eng updates --refresh +check "updates: app and base" "app base" "$(j '" ".join(m["id"] for m in d["mods"])')" +check "... in public/ for the app" "$(j 'd["count"]')" "$(python3 -c "import json; print(json.load(open('$D/public/updates.json'))['count'])")" +eng update app +check "update app" 0 $rc +has "... base updated first, for it" "updating base 1.0.0 -> 2.0.0 (app needs it)" "$out" +check "... both 2.0.0" "2.0.0 2.0.0" "$(installed base) $(installed app)" +eng updates +check "... none left" 0 "$(j 'd["count"]')" +check "... public/ says so too" 0 "$(python3 -c "import json; print(json.load(open('$D/public/updates.json'))['count'])")" +eng update base +has "update of an up-to-date mod: nothing" "nothing to install" "$out" +eng update rival +has "update of a mod that isn't installed: install it instead" "rival isn't installed" "$out" + +# ---- the automatic check (wifi.sh, when home Wi-Fi comes up), and staging if the owner allowed it +pkg helper 1.1.0; listing +eng update-check +check "update-check" 0 $rc +has "... logged" "checked: 1 update(s)" "$(cat $D/logs/hmgapi/updates.log)" +check "... nothing staged without the owner's switch" 1.0.0 "$(installed helper)" +mkdir -p "$D/settings/allow"; : > "$D/settings/allow/auto_stage_updates" +eng update-check +check "update-check, staging allowed" 0 $rc +check "... staged" 1.1.0 "$(installed helper)" +has "... logged" "staged: [helper] (the owner applies them)" "$(cat $D/logs/hmgapi/updates.log)" +rm "$D/settings/allow/auto_stage_updates" + +# ---- HMG-API's own release +cat > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" <<'J' +[{"tag_name": "v9.0.0", "draft": true, "prerelease": false, "assets": []}, + {"tag_name": "v1.1.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v1.1.0", + "assets": [{"name": "hmgapi-1.1.0-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip"}, + {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS"}]}, + {"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}] +J +mkdir -p $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0 +echo "not a release" > $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip +printf '%s hmgapi-1.1.0-update.zip\n' "$(printf '%064d' 0)" > $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS +eng updates --refresh +check "HMG-API's newer release offered (not the draft)" 1.1.0 "$(j 'd["hmgapi"]["version"]')" +check "... counted" 1 "$(j 'd["count"]')" +eng update hmgapi +has "a release that isn't its SHA256SUMS: refused" "refused HMG-API 1.1.0: the download's SHA-256 is" "$out" +echo '[{"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}]' > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" +eng updates --refresh +check "only older releases: nothing offered" None "$(j 'd.get("hmgapi")')" + +# ---- an index.json, when the repo has one, instead of the listing +python3 - "$CAT" <<'P' +import json,os,sys; c=sys.argv[1]; json.dump({"mods": [json.load(open(os.path.join(c,"base.json")))]}, open(os.path.join(c,"index.json"),"w")) +P +: > $W/requests.log +eng catalog --refresh +check "index.json: its mods" base "$(j '" ".join(m["id"] for m in d["mods"])')" +hasnt "... no API call" "api.github.com/repos/Open-HMG/HMG-API/contents" "$(cat $W/requests.log)" +echo '{"mods": [{"id": "Bad Id"}, {"id": "nohttps", "version": "1.0.0", "download": "http://x/y.zip", "sha256": "'"$(printf '%064d' 0)"'", "uuid": "x"}]}' > "$CAT/index.json" +eng catalog --refresh +check "bad entries left out" 0 "$(j 'len(d["mods"])')" +has "... with a note" "nohttps: left out (download isn't https)" "$out" +touch "$W/raw.githubusercontent.com.down" +eng catalog --refresh +has "GitHub not answering: said, the old catalogue kept" "no connection" "$out" +rm "$W/raw.githubusercontent.com.down" + +# ---- removing a mod others require: warned +eng remove base +has "a removal others need: warned" "app requires base: it won't load until base is installed again" "$out" + +[ $fail = 0 ] && echo "all catalogue checks passed" +exit $fail diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index 940f8929..550e499c 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -302,6 +302,9 @@ printf 10.10.10.100 > "$F/fw/props/dhcp.wlan0.dns1" : > "$F/fw/ndc.log" log=$(wk) has "up" "home Wi-Fi up: the mods that asked go through it; the car stays on mobile data" "$log" +check "... the update check started, once" "update check" "$(cat "$X/data/hmgapi/wifi/update-check.test")" +mkdir -p "$X/proc/sys/net/ipv4/conf/wlan0"; wk >/dev/null +check "... not again while still up" 1 "$(grep -c . "$X/data/hmgapi/wifi/update-check.test")" check "status: up, signal, channel, no network name" '{"state": "up", "rssi": -61, "freq": 2437}' "$(pub)" hasnt "the car's default route back off Wi-Fi" "default via 10.4.0.1 dev wlan0 table main" "$(cat "$F/fw/ip4.route")" has "table 95: Wi-Fi's default" "default via 10.4.0.1 dev wlan0 table 95" "$(cat "$F/fw/ip4.route")" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java new file mode 100644 index 00000000..7eb1eacb --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -0,0 +1,920 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * The mod catalogue and updates over home Wi-Fi: no server of our own, only GitHub. The catalogue is + * HMG-API's catalog/ folder (catalog/.json per mod, tools/catalog.py; catalog/index.json when the + * repo has one, else GitHub's folder listing); HMG-API itself comes from its GitHub releases. + * + * engine catalog [--refresh] the catalogue and what each mod would do here (JSON, for the app) + * engine catalog-plan ... what installing them takes: their requires, in order (JSON) + * engine catalog-install ... [--any-car] download, check and install them with what they require + * engine updates [--refresh] installed mods (and HMG-API) with a newer version (JSON) + * engine update ... | --all | hmgapi update them (with any new requires); hmgapi: HMG-API itself + * engine update-check wifi.sh, each time home Wi-Fi comes up: refresh, and stage the + * mods' updates if the owner allowed it (allow auto_stage_updates) + * + * Network: home Wi-Fi only (NativeFetch: its socket is marked for table 95), never the car's + * mobile data; a refresh refuses to start unless home Wi-Fi is up. Trust: an entry only says where + * to look. Its download must have its SHA-256, and Packages checks its signature: an update needs + * the installed mod's author key, a first install the entry's (--uuid), and HMG-API itself needs + * the release key (UsbUpdates). Nothing is applied here: the owner applies (engine apply) as after + * any install. Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and, + * to be sure, from the downloaded package's mod.json; each is met by what's installed, or by the + * catalogue's version, installed first. A required mod that's turned off is turned on. + */ +final class Catalog { + static final String BASE = "https://raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog/"; + static final String RELEASES = "https://api.github.com/repos/Open-HMG/HMG-API/releases?per_page=15"; + static final int MAX_JSON = 1 << 20, MAX_ENTRY = 64 << 10, MAX_ENTRIES = 500; + static final String ID = "[a-z0-9][a-z0-9-]{0,63}"; + + final Engine e; + final File dir, cacheFile, updatesFile; + Map cache; + + Catalog(Engine e) { + this.e = e; + dir = new File(e.data, "catalog"); + cacheFile = new File(dir, "catalog.json"); + updatesFile = new File(dir, "updates.json"); + } + + // ---- the ops + + static int run(Engine e, String[] args) throws Exception { + Catalog c = new Catalog(e); + String cmd = args[0]; + List ids = new ArrayList(); + boolean refresh = false, anyCar = false, all = false; + for (int i = 1; i < args.length; i++) { + if ("--refresh".equals(args[i])) refresh = true; + else if ("--any-car".equals(args[i])) anyCar = true; + else if ("--all".equals(args[i])) all = true; + else if (args[i].matches(ID)) ids.add(args[i]); + else { + e.out.add("not a mod id: " + args[i]); + return 2; + } + } + c.load(); + if ("catalog".equals(cmd) || "updates".equals(cmd)) { + String err = refresh ? c.refresh() : null; + Map rep = "catalog".equals(cmd) ? c.report() : c.updates(); + if (err != null) rep.put("error", err); + e.out.add(Json.write(rep)); + return 0; + } + if ("update-check".equals(cmd)) return c.updateCheck(); + if (c.cache == null) { + String err = c.refresh(); + if (err != null) { + e.out.add("no catalogue yet: " + err); + return 1; + } + } + if ("update".equals(cmd) && ids.remove("hmgapi")) { + if (!ids.isEmpty() || all) { + e.out.add("update HMG-API on its own: engine update hmgapi"); + return 2; + } + return c.updateHmgApi(); + } + if ("update".equals(cmd) && all) { + for (Object o : (List) c.updates().get("mods")) ids.add(String.valueOf(((Map) o).get("id"))); + if (ids.isEmpty()) { + e.out.add("every installed mod is up to date with the catalogue"); + return 0; + } + } + if (ids.isEmpty()) { + e.out.add("usage: engine " + cmd + " ..." + ("update".equals(cmd) ? " | --all | hmgapi" : "")); + return 2; + } + Plan p = c.plan(ids, "update".equals(cmd), anyCar); + if ("catalog-plan".equals(cmd)) { + e.out.add(Json.write(p.toJson())); + return 0; + } + if (e.journalFile.exists()) { + e.out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); + return 1; + } + return c.execute(p, anyCar); + } + + // ---- the catalogue: fetched, cached in /data/hmgapi/catalog/catalog.json + + @SuppressWarnings("unchecked") + void load() { + try { + if (cacheFile.isFile()) cache = Json.object(Engine.read(cacheFile)); + } catch (Exception x) { + cache = null; // unreadable: fetched again + } + } + + /** the catalogue's folder: hmgapi.json "catalog": {"base": ...} (a fork, a test), else HMG-API's own */ + @SuppressWarnings("unchecked") + String base() { + Object c = e.hmgapi.get("catalog"); + if (c instanceof Map && ((Map) c).get("base") instanceof String) { + String b = (String) ((Map) c).get("base"); + if (b.startsWith("https://") && b.endsWith("/")) return b; + } + return BASE; + } + + @SuppressWarnings("unchecked") + boolean prereleases() { + Object c = e.hmgapi.get("catalog"); + if (c instanceof Map && Boolean.TRUE.equals(((Map) c).get("prereleases"))) return true; + return !new Version(installedHmgApi()).tag.isEmpty(); // on a pre-release: offered the next ones + } + + String installedHmgApi() { + return UsbUpdates.installedVersion(e); + } + + /** null when home Wi-Fi is up (or the tests' web is there), else why not */ + String offline() { + if (e.host && Engine.env("HMGAPI_TEST_WEB", null) != null) return null; + File f = new File(e.data, "public/wifi.json"); + try { + Object st = f.isFile() ? Json.object(Engine.read(f)).get("state") : null; + if ("up".equals(st)) return null; + if (st == null || "off".equals(st)) return "Home Wi-Fi is off (HMG-API settings): HMG-API only goes online through it"; + return "home Wi-Fi isn't connected (" + st + "): it joins while the car is off, or with Connect now in P"; + } catch (Exception x) { + return "home Wi-Fi's state can't be read"; + } + } + + /** Fetches the catalogue and HMG-API's releases; null when it worked, else why not (the old cache stays). */ + @SuppressWarnings("unchecked") + String refresh() throws Exception { + String off = offline(); + if (off != null) return off; + List why = new ArrayList(); + Http.Transport t = NativeFetch.forEngine(e, why); + if (t == null) return why.get(0); + File tmp = new File(dir, "tmp-" + System.nanoTime()); // a refresh may run next to another (the app's, wifi.sh's) + tmp.mkdirs(); + try { + Http http = new Http(t, tmp); + List notes = new ArrayList(); + List mods = new ArrayList(); + String base = base(); + File f = new File(tmp, "index.json"); + Http.Result r = http.get(base + "index.json", f, MAX_JSON); + if (r.ok()) { + Object idx = Json.parse(Engine.read(f)); + Object list = idx instanceof Map ? ((Map) idx).get("mods") : idx; + if (!(list instanceof List)) return "the catalogue's index.json isn't a list of mods"; + for (Object o : (List) list) add(mods, o, notes); + } else if (r.status == 404) { + // no index: GitHub's listing of the folder, then each entry from raw (one API call) + String api = listing(base); + if (api == null) return "no catalog/index.json at " + base; + r = http.get(api, f, MAX_JSON); + if (!r.ok()) return "the catalogue's listing: " + r; + Object list = Json.parse(Engine.read(f)); + if (!(list instanceof List)) return "the catalogue's listing isn't a list"; + for (Object o : (List) list) { + if (!(o instanceof Map)) continue; + String name = String.valueOf(((Map) o).get("name")); + if (!name.matches(ID + "\\.json") || "index.json".equals(name)) continue; + if (mods.size() >= MAX_ENTRIES) break; + File ef = new File(tmp, name); + Http.Result er = http.get(base + name, ef, MAX_ENTRY); + if (!er.ok()) { + notes.add(name + ": " + er); + continue; + } + try { + add(mods, Json.parse(Engine.read(ef)), notes); + } catch (Exception x) { + notes.add(name + ": not JSON"); + } + } + } else { + return "the catalogue: " + r; + } + Map rel = null; + String relErr = null; + try { + rel = latestRelease(http, tmp); + } catch (Exception x) { + relErr = x.getMessage(); + } + Map c = new LinkedHashMap(); + c.put("checked", System.currentTimeMillis()); + c.put("base", base); + c.put("mods", mods); + if (rel != null) c.put("hmgapi", rel); + else if (relErr != null && cache != null && cache.get("hmgapi") != null) c.put("hmgapi", cache.get("hmgapi")); // kept + if (relErr != null) notes.add("HMG-API's releases: " + relErr); + if (!notes.isEmpty()) c.put("notes", notes); + dir.mkdirs(); + File n = new File(dir, ".catalog.json.tmp"); + Engine.write(n, Json.write(c)); + if (!n.renameTo(cacheFile)) throw new IOException("can't write " + cacheFile); + cache = c; + writeUpdates(); + return null; + } finally { + Engine.rm(tmp); + } + } + + /** GitHub's API listing for a raw.githubusercontent.com folder, or null */ + static String listing(String base) { + java.util.regex.Matcher m = java.util.regex.Pattern + .compile("https://raw\\.githubusercontent\\.com/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/([A-Za-z0-9._/-]+?)/((?:[A-Za-z0-9._-]+/)*)$") + .matcher(base); + if (!m.matches()) return null; + String path = m.group(4).isEmpty() ? "" : m.group(4).substring(0, m.group(4).length() - 1); + return "https://api.github.com/repos/" + m.group(1) + "/" + m.group(2) + "/contents/" + path + "?ref=" + m.group(3); + } + + /** one entry, kept if it is well-formed (what install relies on), with a note if not */ + @SuppressWarnings("unchecked") + static void add(List mods, Object o, List notes) { + if (!(o instanceof Map)) return; + Map m = (Map) o; + String id = String.valueOf(m.get("id")); + String bad = null; + if (!id.matches(ID) || "hmgapi".equals(id)) bad = "bad id"; + else if (!(m.get("version") instanceof String) || !valid((String) m.get("version"))) bad = "bad version"; + else if (!(m.get("download") instanceof String) || !((String) m.get("download")).startsWith("https://")) bad = "download isn't https"; + else if (!(m.get("sha256") instanceof String) || !((String) m.get("sha256")).matches("[0-9a-f]{64}")) bad = "bad sha256"; + else if (!(m.get("uuid") instanceof String)) bad = "no author key"; + for (Object x : mods) if (id.equals(((Map) x).get("id"))) bad = "listed twice"; + if (bad != null) notes.add(id + ": left out (" + bad + ")"); + else mods.add(m); + } + + static boolean valid(String v) { + try { + new Version(v); + return v.matches("v?\\d+(\\.\\d+){0,2}([-+][0-9A-Za-z.+-]+)?"); + } catch (IllegalArgumentException x) { + return false; + } + } + + /** + * HMG-API's newest release this unit is offered (pre-releases only on a pre-release, or with + * hmgapi.json "catalog": {"prereleases": true}): its update zip and the SHA-256 from its + * SHA256SUMS; null if none is newer than what's installed. + */ + @SuppressWarnings("unchecked") + Map latestRelease(Http http, File tmp) throws Exception { + File f = new File(tmp, "releases.json"); + Http.Result r = http.get(RELEASES, f, MAX_JSON); + if (!r.ok()) throw new IOException(r.toString()); + Object list = Json.parse(Engine.read(f)); + if (!(list instanceof List)) throw new IOException("not a list of releases"); + Map best = null; + Version bv = new Version(installedHmgApi()); + boolean pre = prereleases(); + for (Object o : (List) list) { + if (!(o instanceof Map)) continue; + Map rel = (Map) o; + if (Boolean.TRUE.equals(rel.get("draft"))) continue; + if (Boolean.TRUE.equals(rel.get("prerelease")) && !pre) continue; + String tag = String.valueOf(rel.get("tag_name")); + if (!tag.matches("v\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.]+)?")) continue; + Version v = new Version(tag); + if (v.compareTo(bv) <= 0) continue; + String zip = null, sums = null; + Object assets = rel.get("assets"); + for (Object a : assets instanceof List ? (List) assets : new ArrayList()) { + Map am = (Map) a; + String name = String.valueOf(am.get("name")), url = String.valueOf(am.get("browser_download_url")); + if (name.equals("hmgapi-" + tag.substring(1) + "-update.zip")) zip = url; + if (name.equals("SHA256SUMS")) sums = url; + } + if (zip == null || sums == null) continue; + best = new LinkedHashMap(); + best.put("version", tag.substring(1)); + best.put("prerelease", Boolean.TRUE.equals(rel.get("prerelease"))); + best.put("download", zip); + best.put("sums", sums); + best.put("page", String.valueOf(rel.get("html_url"))); + bv = v; + } + if (best == null) return null; + File s = new File(tmp, "SHA256SUMS"); + r = http.get((String) best.get("sums"), s, MAX_ENTRY); + if (!r.ok()) throw new IOException("SHA256SUMS: " + r); + String want = "hmgapi-" + best.get("version") + "-update.zip"; + for (String l : Engine.read(s).split("\n")) { + String[] p = l.trim().split("\\s+"); + if (p.length == 2 && p[1].replaceFirst("^\\*", "").equals(want) && p[0].matches("[0-9a-f]{64}")) best.put("sha256", p[0]); + } + if (best.get("sha256") == null) throw new IOException("SHA256SUMS doesn't list " + want); + best.remove("sums"); + return best; + } + + // ---- what's installed, and what the catalogue offers each + + static final class Inst { + String version; + boolean enabled; + } + + @SuppressWarnings("unchecked") + Map installed() { + Map m = new TreeMap(); + File[] ds = new File(e.data, "mods").listFiles(); + for (File d : ds == null ? new File[0] : ds) { + File mj = new File(d, "mod.json"); + if (!d.getName().matches(ID) || !mj.isFile()) continue; + try { + Inst i = new Inst(); + i.version = String.valueOf(Json.object(Engine.read(mj)).get("version")); + i.enabled = !new File(d, ".disabled").exists(); + m.put(d.getName(), i); + } catch (Exception x) { + // a broken mod.json: the engine's other checks say so + } + } + return m; + } + + @SuppressWarnings("unchecked") + Map> entries() { + Map> m = new LinkedHashMap>(); + if (cache == null || !(cache.get("mods") instanceof List)) return m; + for (Object o : (List) cache.get("mods")) m.put(String.valueOf(((Map) o).get("id")), (Map) o); + return m; + } + + /** a dependency list (requires or conflicts), optional ones left out (only NEMESIS's package builder honours them) */ + @SuppressWarnings("unchecked") + static List deps(Object list) { + List out = new ArrayList(); + if (!(list instanceof List)) return out; + for (Object o : (List) list) { + if (o instanceof Map && Boolean.TRUE.equals(((Map) o).get("optional"))) continue; + out.addAll(Version.deps(Arrays.asList(o))); + } + return out; + } + + /** why this unit can't take the entry, or null: its HMG-API range; "car: ..." for its "system" (an override exists) */ + @SuppressWarnings("unchecked") + String unfit(Map en) { + Object need = en.get("hmgapi"); + if (need != null && !Version.meetsHmgapi(installedHmgApi(), String.valueOf(need))) { + return "needs HMG-API " + need + " (this is " + installedHmgApi() + ")"; + } + if (en.get("system") != null) { + String sys = SystemCheck.check(en.get("system"), e.facts, false); + if (sys != null) return "car: " + sys; + } + return null; + } + + static String status(String have, String offered) { + if (have == null) return "new"; + int c; + try { + c = new Version(offered).compareTo(new Version(have)); + } catch (IllegalArgumentException x) { + return "same"; + } + return c > 0 ? "update" : c == 0 ? "same" : "older"; + } + + @SuppressWarnings("unchecked") + Map report() { + Map rep = new LinkedHashMap(); + rep.put("hmgapi", installedHmgApi()); + rep.put("online", offline() == null); + if (offline() != null) rep.put("offline", offline()); + if (cache == null) { + rep.put("mods", new ArrayList()); + return rep; + } + rep.put("checked", cache.get("checked")); + Map inst = installed(); + List out = new ArrayList(); + for (Map en : entries().values()) { + Map m = new LinkedHashMap(); + String id = String.valueOf(en.get("id")); + for (String k : new String[] {"id", "name", "version", "description", "authors", "license", "repo", "uuid"}) { + if (en.get(k) != null) m.put(k, en.get(k)); + } + Inst i = inst.get(id); + if (i != null) { + m.put("installed", i.version); + m.put("enabled", i.enabled); + } + m.put("status", status(i == null ? null : i.version, String.valueOf(en.get("version")))); + String unfit = unfit(en); + if (unfit != null) m.put("unfit", unfit); + List req = new ArrayList(); + for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); + if (!req.isEmpty()) m.put("requires", req); + m.put("trusted", Packages.trustedAuthor(e, String.valueOf(en.get("uuid"))) != null); + out.add(m); + } + rep.put("mods", out); + if (cache.get("hmgapi") != null) rep.put("hmgapi_update", hmgapiOffer()); + if (cache.get("notes") != null) rep.put("notes", cache.get("notes")); + return rep; + } + + /** HMG-API's newer release from the cache, if it's still newer than what's installed */ + @SuppressWarnings("unchecked") + Map hmgapiOffer() { + Object h = cache == null ? null : cache.get("hmgapi"); + if (!(h instanceof Map)) return null; + Map m = (Map) h; + if (!"update".equals(status(installedHmgApi(), String.valueOf(m.get("version"))))) return null; + Map out = new LinkedHashMap(m); + out.put("installed", installedHmgApi()); + return out; + } + + /** installed mods with a newer catalogue version this unit can take, and HMG-API's own */ + @SuppressWarnings("unchecked") + Map updates() { + Map rep = new LinkedHashMap(); + rep.put("online", offline() == null); + List list = new ArrayList(); + if (cache != null) { + rep.put("checked", cache.get("checked")); + Map> cat = entries(); + for (Map.Entry i : installed().entrySet()) { + Map en = cat.get(i.getKey()); + if (en == null || !"update".equals(status(i.getValue().version, String.valueOf(en.get("version"))))) continue; + String unfit = unfit(en); + if (unfit != null && !unfit.startsWith("car: ")) continue; // not for this HMG-API: not offered + Map m = new LinkedHashMap(); + m.put("id", i.getKey()); + m.put("name", en.get("name") == null ? i.getKey() : en.get("name")); + m.put("installed", i.getValue().version); + m.put("version", en.get("version")); + if (en.get("description") != null) m.put("description", en.get("description")); + List req = new ArrayList(); + for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); + if (!req.isEmpty()) m.put("requires", req); + list.add(m); + } + Map h = hmgapiOffer(); + if (h != null) rep.put("hmgapi", h); + } + rep.put("mods", list); + rep.put("count", list.size() + (rep.get("hmgapi") != null ? 1 : 0)); + return rep; + } + + /** updates.json, also in public/ for the app (the Mods tab's "Updates (n)") */ + void writeUpdates() throws IOException { + String text = Json.write(updates()); + dir.mkdirs(); + Engine.write(updatesFile, text); + File pub = new File(e.data, "public"); + pub.mkdirs(); + File tmp = new File(pub, ".updates.json.tmp"); + Engine.write(tmp, text); + tmp.setReadable(true, false); + if (!tmp.renameTo(new File(pub, "updates.json"))) throw new IOException("can't write public/updates.json"); + } + + // ---- dependencies: what installing some mods takes, in order (what they require first) + + static final class Step { + final String id, action, version, installed, because; + final Map entry; + File zip; + + Step(String id, String action, String version, String installed, String because, Map entry) { + this.id = id; + this.action = action; + this.version = version; + this.installed = installed; + this.because = because; + this.entry = entry; + } + } + + final class Plan { + final List steps = new ArrayList(); + final List problems = new ArrayList(), notes = new ArrayList(); + final Map> cat = entries(); + final Map inst = installed(); + /** requires learned from the downloaded packages (their mod.json), by id */ + final Map> learned = new LinkedHashMap>(); + final Set visiting = new LinkedHashSet(); + boolean anyCar; + + Step planned(String id) { + for (Step s : steps) if (s.id.equals(id)) return s; + return null; + } + + List requires(String id, Map en) { + List r = new ArrayList(deps(en.get("requires"))); + if (learned.containsKey(id)) r.addAll(learned.get(id)); + return r; + } + + boolean fits(Map en, String who) { + String unfit = unfit(en); + if (unfit == null) return true; + if (unfit.startsWith("car: ") && anyCar) { + notes.add(en.get("id") + " isn't listed for this head unit (" + unfit.substring(5) + "): installing it anyway, at your own risk"); + return true; + } + problems.add((who != null ? who + " needs " : "") + en.get("id") + " " + en.get("version") + ", which " + + (unfit.startsWith("car: ") ? "isn't for this head unit: " + unfit.substring(5) : unfit)); + return false; + } + + /** a mod asked for by the owner: installed, or updated */ + void want(String id, boolean update) { + Map en = cat.get(id); + Inst i = inst.get(id); + if (en == null) { + problems.add(id + " isn't in the catalogue"); + return; + } + String st = status(i == null ? null : i.version, String.valueOf(en.get("version"))); + if ("same".equals(st) || "older".equals(st)) { + if (i != null && !i.enabled && !update) add(new Step(id, "enable", i.version, i.version, null, en)); + else notes.add(id + " " + i.version + " is installed" + ("older".equals(st) ? " (newer than the catalogue's " + en.get("version") + ")" : "")); + return; + } + if (update && i == null) { + problems.add(id + " isn't installed: install it from the catalogue"); + return; + } + if (fits(en, null)) take(en, null); + } + + /** a requirement: met by what's installed (turned on if it's off) or planned, else the catalogue's */ + void need(Version.Dep d, String who) { + Step p = planned(d.id); + if (p != null && !"enable".equals(p.action)) { + if (!Version.satisfies(p.version, d.range)) problems.add(who + " needs " + d + ", but " + d.id + " " + p.version + " is the one being installed"); + return; + } + Inst i = inst.get(d.id); + if (i != null && Version.satisfies(i.version, d.range)) { + if (!i.enabled && p == null) add(new Step(d.id, "enable", i.version, i.version, who, cat.get(d.id))); + return; + } + Map en = cat.get(d.id); + if (en == null) { + problems.add(who + " needs " + d + (i != null ? " (" + i.version + " is installed)" : "") + ", which isn't in the catalogue"); + return; + } + if (!Version.satisfies(String.valueOf(en.get("version")), d.range)) { + problems.add(who + " needs " + d + ", but the catalogue has " + d.id + " " + en.get("version") + + (i != null ? " (" + i.version + " is installed)" : "")); + return; + } + if (i != null && "older".equals(status(i.version, String.valueOf(en.get("version"))))) { + problems.add(who + " needs " + d + ": the installed " + d.id + " " + i.version + " doesn't fit and the catalogue's is older"); + return; + } + if (fits(en, who)) take(en, who); + } + + void take(Map en, String who) { + String id = String.valueOf(en.get("id")); + if (planned(id) != null) return; + if (!visiting.add(id)) { + problems.add("a requires loop: " + visiting + " -> " + id); + return; + } + for (Version.Dep d : requires(id, en)) need(d, id); + visiting.remove(id); + Inst i = inst.get(id); + add(new Step(id, i == null ? "install" : "update", String.valueOf(en.get("version")), i == null ? null : i.version, who, en)); + } + + void add(Step s) { + if (planned(s.id) == null) steps.add(s); + } + + /** conflicts: theirs (entry, package) against what's installed and on, and what's planned */ + void conflicts(Map> pkgConflicts) { + for (Step s : steps) { + if ("enable".equals(s.action) || s.entry == null) continue; + List cs = new ArrayList(deps(s.entry.get("conflicts"))); + if (pkgConflicts.containsKey(s.id)) cs.addAll(pkgConflicts.get(s.id)); + for (Version.Dep c : cs) { + Step p = planned(c.id); + Inst i = inst.get(c.id); + String v = p != null ? p.version : i != null && i.enabled ? i.version : null; + if (v != null && Version.satisfies(v, c.range)) { + problems.add(s.id + " " + s.version + " conflicts with " + c.id + " " + v + (p != null ? " (being installed)" : " (installed)") + + ": remove or update " + c.id + " first"); + } + } + } + } + + Map toJson() { + Map m = new LinkedHashMap(); + m.put("ok", problems.isEmpty()); + List st = new ArrayList(); + for (Step s : steps) { + Map x = new LinkedHashMap(); + x.put("id", s.id); + x.put("name", s.entry != null && s.entry.get("name") != null ? s.entry.get("name") : s.id); + x.put("action", s.action); + x.put("version", s.version); + if (s.installed != null) x.put("installed", s.installed); + if (s.because != null) x.put("for", s.because); + if (s.entry != null) x.put("trusted", Packages.trustedAuthor(e, String.valueOf(s.entry.get("uuid"))) != null); + st.add(x); + } + m.put("steps", st); + if (!problems.isEmpty()) m.put("problems", problems); + if (!notes.isEmpty()) m.put("notes", notes); + return m; + } + } + + Plan plan(List ids, boolean update, boolean anyCar) { + Plan p = new Plan(); + p.anyCar = anyCar; + for (String id : ids) p.want(id, update); + p.conflicts(new LinkedHashMap>()); + return p; + } + + // ---- doing it: everything downloaded and checked first, then installed in order + + @SuppressWarnings("unchecked") + int execute(Plan p, boolean anyCar) throws Exception { + if (!p.problems.isEmpty()) { + for (String x : p.problems) e.out.add("can't: " + x); + return 1; + } + if (p.steps.isEmpty()) { + for (String n : p.notes) e.out.add(n); + e.out.add("nothing to install"); + return 0; + } + String off = offline(); + if (off != null && needsDownload(p)) { + e.out.add("can't download: " + off); + return 1; + } + File dl = new File(dir, "downloads"); + Engine.rm(dl); + dl.mkdirs(); + try { + Http http = null; + // a package can require more than its entry says (an entry from before catalog.py copied + // requires): its own mod.json is the truth, so the plan is made again until nothing new turns up + Map> pkgConflicts = new LinkedHashMap>(); + for (int round = 0; ; round++) { + boolean more = false; + for (Step s : p.steps) { + if ("enable".equals(s.action) || s.zip != null) continue; + if (http == null) { + List why = new ArrayList(); + Http.Transport t = NativeFetch.forEngine(e, why); + if (t == null) { + e.out.add("can't download: " + why.get(0)); + return 1; + } + http = new Http(t, dl); + } + File z = new File(dl, s.id + "-" + s.version + ".zip"); + Http.Result r = http.get(String.valueOf(s.entry.get("download")), z, (int) Packages.MAX_BYTES); + if (!r.ok()) { + e.out.add("can't download " + s.id + " " + s.version + ": " + r + " (nothing was installed)"); + return 1; + } + String sha = Sha256.hex(z), want = String.valueOf(s.entry.get("sha256")); + if (!sha.equals(want)) { + e.out.add("refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", the catalogue says " + want + + " (nothing was installed)"); + return 1; + } + Map mj = modJson(z); + if (mj == null || !s.id.equals(mj.get("id")) || !s.version.equals(String.valueOf(mj.get("version")))) { + e.out.add("refused " + s.id + " " + s.version + ": the package is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")) + + " (nothing was installed)"); + return 1; + } + s.zip = z; + e.out.add("downloaded " + s.id + " " + s.version + " (" + z.length() + " bytes, SHA-256 as the catalogue's)"); + pkgConflicts.put(s.id, deps(mj.get("conflicts"))); + List req = deps(mj.get("requires")), known = p.requires(s.id, s.entry); + for (Version.Dep d : req) { + boolean have = false; + for (Version.Dep k : known) have |= k.id.equals(d.id) && String.valueOf(k.range).equals(String.valueOf(d.range)); + if (!have) { + if (!p.learned.containsKey(s.id)) p.learned.put(s.id, new ArrayList()); + p.learned.get(s.id).add(d); + more = true; + } + } + } + if (!more) break; + if (round >= 5) { + e.out.add("can't: the packages' requires keep changing (nothing was installed)"); + return 1; + } + // again with what the packages said; the downloads already made are kept + Plan q = new Plan(); + q.anyCar = anyCar; + q.learned.putAll(p.learned); + List wanted = new ArrayList(); + for (Step s : p.steps) if (s.because == null) wanted.add(s.id); + for (String id : wanted) q.want(id, false); + for (Step s : q.steps) { + Step old = p.planned(s.id); + if (old != null && old.version.equals(s.version)) s.zip = old.zip; + } + if (!q.problems.isEmpty()) { + for (String x : q.problems) e.out.add("can't: " + x); + e.out.add("(nothing was installed)"); + return 1; + } + p = q; + } + p.conflicts(pkgConflicts); + if (!p.problems.isEmpty()) { + for (String x : p.problems) e.out.add("can't: " + x); + e.out.add("(nothing was installed)"); + return 1; + } + for (String n : p.notes) e.out.add(n); + int done = 0; + for (Step s : p.steps) { + if ("enable".equals(s.action)) { + new File(e.data, "mods/" + s.id + "/.disabled").delete(); + e.out.add("turned on " + s.id + " " + s.version + (s.because != null ? " (" + s.because + " needs it)" : "")); + done++; + continue; + } + e.out.add((s.installed == null ? "installing " : "updating ") + s.id + (s.installed != null ? " " + s.installed + " ->" : "") + " " + + s.version + (s.because != null ? " (" + s.because + " needs it)" : "")); + int rc = Packages.install(e, s.zip.getPath(), String.valueOf(s.entry.get("uuid")), false, anyCar); + if (rc != 0) { + e.out.add("stopped at " + s.id + (done > 0 ? ": the " + done + " before it are installed (not applied yet)" : ": nothing was installed")); + if (done > 0) NemesisSync.run(e); + writeUpdates(); + return rc; + } + done++; + } + NemesisSync.run(e); + LiveState.publish(e); + writeUpdates(); + e.out.add("done: " + done + (done == 1 ? " mod" : " mods") + ". Apply changes (engine apply) to use " + + (done == 1 ? "it" : "them")); + return 0; + } finally { + Engine.rm(dl); + } + } + + /** installed mods that require id (for a removal's warning) */ + static List dependents(Engine e, String id) { + List out = new ArrayList(); + File[] ds = new File(e.data, "mods").listFiles(); + for (File d : ds == null ? new File[0] : ds) { + File mj = new File(d, "mod.json"); + if (d.getName().equals(id) || !mj.isFile()) continue; + try { + for (Version.Dep x : deps(Json.object(Engine.read(mj)).get("requires"))) if (x.id.equals(id)) out.add(d.getName()); + } catch (Exception ignored) { + // a broken mod.json: not this check's to report + } + } + return out; + } + + static boolean needsDownload(Plan p) { + for (Step s : p.steps) if (!"enable".equals(s.action)) return true; + return false; + } + + /** the package's mod.json (at its top, or in its one folder), or null */ + @SuppressWarnings("unchecked") + static Map modJson(File zip) { + ZipFile z = null; + try { + z = new ZipFile(zip); + java.util.Enumeration en = z.entries(); + while (en.hasMoreElements()) { + ZipEntry x = en.nextElement(); + String n = x.getName(); + if (n.equals("mod.json") || (n.endsWith("/mod.json") && n.indexOf('/') == n.length() - 9)) { + if (x.getSize() > MAX_ENTRY) return null; + InputStream in = z.getInputStream(x); + return Json.object(new String(Engine.readAll(in), "UTF-8")); + } + } + return null; + } catch (Exception x) { + return null; + } finally { + if (z != null) try { z.close(); } catch (IOException ignored) { /* read already */ } + } + } + + /** HMG-API itself: its update zip, checked against SHA256SUMS, then its own installer (UsbUpdates: the release key) */ + @SuppressWarnings("unchecked") + int updateHmgApi() throws Exception { + Map h = hmgapiOffer(); + if (h == null) { + e.out.add("HMG-API " + installedHmgApi() + " is the newest release offered here (engine updates --refresh checks again)"); + return 0; + } + String off = offline(); + if (off != null) { + e.out.add("can't download: " + off); + return 1; + } + List why = new ArrayList(); + Http.Transport t = NativeFetch.forEngine(e, why); + if (t == null) { + e.out.add("can't download: " + why.get(0)); + return 1; + } + File dl = new File(dir, "downloads"); + Engine.rm(dl); + dl.mkdirs(); + try { + File z = new File(dl, "hmgapi-" + h.get("version") + "-update.zip"); + Http.Result r = new Http(t, dl).get(String.valueOf(h.get("download")), z, 128 << 20); + if (!r.ok()) { + e.out.add("can't download HMG-API " + h.get("version") + ": " + r); + return 1; + } + String sha = Sha256.hex(z); + if (!sha.equals(h.get("sha256"))) { + e.out.add("refused HMG-API " + h.get("version") + ": the download's SHA-256 is " + sha + ", its SHA256SUMS says " + h.get("sha256")); + return 1; + } + e.out.add("downloaded HMG-API " + h.get("version") + " (" + z.length() + " bytes, SHA-256 as its release's SHA256SUMS)"); + return UsbUpdates.updateHmgApi(e, z.getPath(), false); + } finally { + Engine.rm(dl); + } + } + + /** + * wifi.sh, when home Wi-Fi comes up: refresh, write updates.json, and stage the mods' updates if + * the owner allowed it (hmgapid allow auto_stage_updates on). HMG-API itself is never updated + * here. What happened goes to logs/hmgapi/updates.log. + */ + @SuppressWarnings("unchecked") + int updateCheck() throws Exception { + List log = new ArrayList(); + String err = refresh(); + Map u = updates(); + if (err != null) log.add("check: " + err); + else log.add("checked: " + u.get("count") + " update(s)" + (u.get("hmgapi") != null ? " (HMG-API " + ((Map) u.get("hmgapi")).get("version") + " among them)" : "")); + int rc = 0; + if (err == null && new File(e.data, "settings/allow/auto_stage_updates").exists() && !((List) u.get("mods")).isEmpty()) { + List ids = new ArrayList(); + for (Object o : (List) u.get("mods")) ids.add(String.valueOf(((Map) o).get("id"))); + if (e.journalFile.exists()) { + log.add("not staged: an earlier apply isn't finished"); + } else { + int before = e.out.size(); + rc = execute(plan(ids, true, false), false); + log.addAll(e.out.subList(before, e.out.size())); + log.add(rc == 0 ? "staged: " + ids + " (the owner applies them)" : "not staged (" + rc + ")"); + } + } + File lf = new File(e.data, "logs/hmgapi/updates.log"); + lf.getParentFile().mkdirs(); + String old = lf.isFile() ? Engine.read(lf) : ""; + if (old.length() > 64 << 10) old = old.substring(old.length() - (32 << 10)); + StringBuilder b = new StringBuilder(old); + String when = new java.text.SimpleDateFormat("MM-dd HH:mm:ss", java.util.Locale.US).format(new java.util.Date()); + for (String l : log) b.append(when).append(' ').append(l).append('\n'); + Engine.write(lf, b.toString()); + e.out.addAll(log.subList(0, Math.min(1, log.size()))); + return err != null ? 1 : rc; + } +} diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..b56d62e3 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -147,6 +147,8 @@ static String ownsWhy(String types) { boolean lock(String cmd) throws IOException, InterruptedException { if ("status".equals(cmd) || "map".equals(cmd) || "problem".equals(cmd) || "1".equals(env(LOCKED_ENV, null))) return true; + // the catalogue's reads (and refreshes: written whole, each in its own temporary folder) don't wait for an apply + if ("catalog".equals(cmd) || "updates".equals(cmd) || "catalog-plan".equals(cmd)) return true; File f = new File(stateDir, "engine.lock"); java.io.RandomAccessFile raf = new java.io.RandomAccessFile(f, "rw"); long wait = Long.parseLong(env("HMGAPI_LOCK_WAIT", "900")) * 1000000000L, start = System.nanoTime(); @@ -375,6 +377,8 @@ int run(String[] args) throws Exception { if ("report".equals(cmd)) return Report.run(this, args.length > 1 && "--usb".equals(args[1])); if ("problem".equals(cmd)) return ProblemLog.run(this, args); if ("usb-scan".equals(cmd)) return UsbUpdates.scan(this); + if ("catalog".equals(cmd) || "catalog-plan".equals(cmd) || "catalog-install".equals(cmd) || "updates".equals(cmd) + || "update".equals(cmd) || "update-check".equals(cmd)) return Catalog.run(this, args); if ("publish-state".equals(cmd)) return LiveState.publish(this); if ("apps".equals(cmd)) return ModApps.sync(this); if ("probe".equals(cmd)) { // a mod's install-time probe again (its answer is kept until then) @@ -408,6 +412,9 @@ int run(String[] args) throws Exception { boolean fromNemesis = java.util.Arrays.asList(args).contains("--from-nemesis"); int rc; if ("remove".equals(cmd)) { + for (String d : Catalog.dependents(this, args[1])) { + out.add("note " + d + " requires " + args[1] + ": it won't load until " + args[1] + " is installed again"); + } rc = Packages.remove(this, args[1]); } else { String uuid = null; diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index 07739e15..7bff611a 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -279,6 +279,13 @@ static List describe(Engine e, Map> json, Se "# marked for home Wi-Fi (the mods that asked, HMG-API's own downloads) fails instead of falling", "# through to the main table and the car's mobile data", "no_route() { [ -n \"$(ip route show table $T 2>/dev/null)\" ] || ip route add unreachable default table $T 2>/dev/null; }", + "# HMG-API's update check, once each time home Wi-Fi comes up (Catalog: the catalogue, nothing installed", + "# unless the owner chose that); off with the owner's switch no_update_check", + "update_check() {", + " [ -z \"$X\" ] || { echo \"update check\" >> $W/update-check.test; return; }", + " [ -f /data/hmgapi/settings/allow/no_update_check ] && return", + " (hmgapid engine update-check >/dev/null 2>&1 &)", + "}", "route_up() {", " gw=", " for r in $(ip route show dev $I 2>/dev/null | while read -r a b c rest; do [ \"$a\" = default ] && [ \"$b\" = via ] && echo $c; done); do gw=$r; done", @@ -315,6 +322,7 @@ static List describe(Engine e, Map> json, Se " iptables -A HMGAPI_HOMELO -i $I -d 127.0.0.0/8 -j DROP", " echo \"$gw $d1\" > $W/lease", " say \"home Wi-Fi up: the mods that asked go through it; the car stays on mobile data\"", + " update_check", " fi", "}", "route_down() {", diff --git a/docs/mod-reference.md b/docs/mod-reference.md index c9308e9c..0524fc3d 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -362,8 +362,8 @@ is switched on again, the client goes off and the hotspot comes back as it was. next to the hotspot, on a second interface, didn't hold up on these units' Wi-Fi driver.) While joined, the traffic of the mods that ask (their apps, and their services) goes through home Wi-Fi; the car's own stays on mobile data. A mod that asks while the switch is off has no -internet (the plan says so). IPv4 only for now. This is also how HMG-API itself is meant to -check for updates. +internet (the plan says so). IPv4 only for now. HMG-API itself checks its catalogue and +updates this way (`Catalog`), each time home Wi-Fi comes up. How it's routed, for a mod that wants to know: its packets are marked (`0x2951`) and go out by table 95 (home Wi-Fi's default; an unreachable default while home Wi-Fi is down), masqueraded diff --git a/tools/catalog.py b/tools/catalog.py index 1b72b37f..80261ad8 100755 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -25,6 +25,8 @@ newer than the entry, signed with the entry's author key tools/catalog.py wiki the Community mods page + tools/catalog.py index [] + catalog/index.json: every entry in one file, for the head unit's catalogue (one request) """ import argparse, hashlib, json, os, re, shutil, subprocess, sys, tempfile, urllib.request, zipfile @@ -38,7 +40,8 @@ VERSION = re.compile(r'^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$') FINAL = re.compile(r'^\d+\.\d+\.\d+$') # what an entry's "version" is: no pre-releases (docs/releasing.md) HTTPS = re.compile(r'^https://[A-Za-z0-9.-]+(:\d+)?/[^\s<>()\[\]"\']*$') -FIELDS = {'id', 'name', 'description', 'authors', 'license', 'uuid', 'version', 'repo', 'download', 'sha256', 'system', 'hmgapi'} +FIELDS = {'id', 'name', 'description', 'authors', 'license', 'uuid', 'version', 'repo', 'download', 'sha256', 'system', 'hmgapi', + 'requires', 'conflicts'} # requires/conflicts: as the package's mod.json (HMG-API's catalogue installs requires first) NEEDED = ['id', 'name', 'description', 'authors', 'uuid', 'version', 'repo', 'download', 'sha256'] @@ -148,7 +151,7 @@ def fetch(url, dest): def entries(): if not os.path.isdir(CATALOG): return {} - return {f[:-5]: load(os.path.join(CATALOG, f)) for f in sorted(os.listdir(CATALOG)) if f.endswith('.json')} + return {f[:-5]: load(os.path.join(CATALOG, f)) for f in sorted(os.listdir(CATALOG)) if f.endswith('.json') and f != 'index.json'} # ---- add @@ -181,6 +184,9 @@ def cmd_add(a): e['hmgapi'] = mod['hmgapi'] if mod.get('system'): e['system'] = mod['system'] + for k in ('requires', 'conflicts'): # what the head unit's catalogue resolves before downloading + if mod.get(k): + e[k] = mod[k] if not e['license']: del e['license'] os.makedirs(CATALOG, exist_ok=True) @@ -236,6 +242,10 @@ def check_entry(name, e, authors): for k in ('name', 'description', 'license'): if k in e and (not isinstance(e[k], str) or '\n' in e[k]): say(f'"{k}" is one line of text') + for k in ('requires', 'conflicts'): + if k in e and not (isinstance(e[k], list) and all( + (isinstance(d, str) and ID.match(d.split(' ')[0])) or (isinstance(d, dict) and ID.match(str(d.get('id', '')))) for d in e[k])): + say(f'"{k}" is a list of " [range]" or {{"id": ..., "version": ...}}, as in mod.json') return p @@ -311,7 +321,7 @@ def cmd_check(a): print(f'ok {len(es)} catalogue entries, {len(au.get("authors", {}))} authors') -BUMP = {'version', 'download', 'sha256', 'description'} # what a version bump may change +BUMP = {'version', 'download', 'sha256', 'description', 'requires', 'conflicts'} # what a version bump may change def cmd_bump(a): @@ -352,10 +362,13 @@ def cmd_bump(a): z, why = download(n, new, work) if why: no.append(why) - elif 'description' in changed: - desc = load(os.path.join(unpack(z, os.path.join(work, 'mod')), 'mod.json')).get('description', '') - if desc != new['description']: + elif changed & {'description', 'requires', 'conflicts'}: + pm = load(os.path.join(unpack(z, os.path.join(work, 'mod')), 'mod.json')) + if 'description' in changed and pm.get('description', '') != new['description']: no.append(f'{files[0]}: the description isn\'t the package\'s mod.json description') + for k in ('requires', 'conflicts'): + if k in changed and (pm.get(k) or None) != (new.get(k) or None): + no.append(f'{files[0]}: "{k}" isn\'t the package\'s mod.json "{k}"') finally: shutil.rmtree(work, ignore_errors=True) for x in no: @@ -486,6 +499,18 @@ def cars(system): return '; '.join(out) +def cmd_index(a): + """catalog/index.json: every entry in one file, so a head unit fetches the catalogue in one request + (without it, HMG-API asks GitHub's API for the folder's listing, then each entry)""" + es = entries() + p = check_all(es, load(AUTHORS)) + if p: + die('\n'.join(p)) + out = a.out or os.path.join(CATALOG, 'index.json') + save(out, {'mods': [es[n] for n in sorted(es)]}) + print(f'{os.path.relpath(out, REPO) if out.startswith(REPO) else out}: {len(es)} mods') + + def cmd_wiki(a): es, au = entries(), load(AUTHORS).get('authors', {}) L = ['# Community mods', '', @@ -541,12 +566,14 @@ def main(): s.add_argument('--list', help='the ids (and pre-release pins) from this file, e.g. tools/release-mods.txt') s = sub.add_parser('wiki') s.add_argument('out') + s = sub.add_parser('index') + s.add_argument('out', nargs='?') a = ap.parse_args() if a.cmd == 'add' and not HTTPS.match(a.download): die('--download is an https:// link') if a.cmd == 'add' and a.repo and not HTTPS.match(a.repo): die('--repo is an https:// link') - {'add': cmd_add, 'check': cmd_check, 'bump': cmd_bump, 'fetch': cmd_fetch, 'wiki': cmd_wiki}[a.cmd](a) + {'add': cmd_add, 'check': cmd_check, 'bump': cmd_bump, 'fetch': cmd_fetch, 'wiki': cmd_wiki, 'index': cmd_index}[a.cmd](a) if _engine and _engine != os.environ.get('HMGAPI_ENGINE_CLASSES'): # ours, not the caller's shutil.rmtree(_engine, ignore_errors=True) diff --git a/tools/test-all.sh b/tools/test-all.sh index 3464b82e..1760fc90 100755 --- a/tools/test-all.sh +++ b/tools/test-all.sh @@ -7,9 +7,9 @@ # Each test: "ok" (its checks, and how many it skipped), "skip" (it skipped everything, # and why) or "FAIL" (its failed checks). cd "$(dirname "$0")/.." -ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" +ALL="core/hmgapid/test.sh core/zygote/test.sh tools/lpatch/test.sh core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/catalog-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/common/install-test.sh install/common/orders-test.sh install/usb/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/cars-test.sh tools/sdk-test.sh tools/check-scripts.sh" # no build, no ARM toolchain: all but hmgapid, the zygote wrapper, lpatch, the installers and the SDK -FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" +FAST="core/runtime/engine-test.sh core/runtime/signing-test.sh core/runtime/system-test.sh core/runtime/safety-test.sh core/runtime/packages-test.sh core/runtime/map-test.sh core/runtime/local-map-test.sh core/runtime/usb-test.sh core/runtime/hooks-test.sh core/runtime/mod-dex-test.sh core/runtime/live-test.sh core/runtime/native-test.sh core/runtime/runtime-test.sh core/runtime/net-test.sh core/runtime/problem-test.sh core/runtime/homewifi-test.sh core/runtime/fetch-test.sh core/runtime/catalog-test.sh core/runtime/overlap-test.sh core/runtime/keys-test.sh core/runtime/commands-test.sh core/runtime/scriptcheck-test.sh core/hookpoints/test.sh core/app/qr-test.sh install/common/test.sh install/nemesis/mod-test.sh install/nemesis/sync-test.sh tools/mod-draft-test.sh tools/catalog-test.sh tools/car-triage-test.sh tools/version-test.sh tools/mkicon-test.sh tools/micom-decode-test.sh tools/check-scripts.sh" # these write out/ (usb: out/payload and out/dist; sdk: out/mods, out/packages, out/dist) or read # what another writes (install-test: out/payload), so they run one after another SERIAL="install/common/install-test.sh install/usb/test.sh tools/sdk-test.sh" From f1e44222443e67a4e5cc712f3bd9c1a26ad58a98 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:28:47 -0500 Subject: [PATCH 02/10] Catalogue: trust, the result as a whole, staged updates aside until apply From the review of 2026-11-26: - Trust: the catalogue isn't signed, so a first install's author key must already be on the unit's maps/authors.json (only HMG-API's releases bring it), or the owner says yes for that mod (--any-author=). Nothing here writes authors.json. - The plan is checked as a whole: every mod that will be on keeps what it requires, in range and on, and conflicts count from either side (an installed mod's list naming a planned one too). update --all leaves out each mod that can't go now, with why, and updates the rest. - unfit() honours the owner's any-car choice (overrides.ignore_system) and a hotspot mod's unpowered chip; --any-car=,... per mod. - Every package is checked (Packages.check: signature, key, HMG-API, car) before the first install, and installed from the unzipped folder. - An unreadable range is a plan problem, not an exception. - Requires a package adds are kept (learned.json); if they change the plan, nothing is installed and the new plan comes back (exit 5) for a second OK. - update-check stages only pure updates signed with the installed key, into /data/hmgapi/pending/, which nothing loads; engine apply puts them in place before it plans (previous version kept in previous/), and puts them back if the apply is refused. engine plan lists them. - A plan or install refreshes a catalogue over 15 minutes old when online; one entry that doesn't come keeps the last check's; a bad index.json is an error, not a crash; per-run temporary names. - update-check at most every 6 hours. - A unit on a pre-release is offered only that version's next ones (rc.10: 1.1.0, not 1.2.0-alpha), unless the owner opts in. - update hmgapi refuses while a mod that's on wouldn't take the new version (--force: a warning instead). - Installs and removals outside the catalogue update the Updates count. - catalog.py: downloads only from GitHub's hosts, ranges checked, copies wifi.hotspot, writes index.json again on add when the repo keeps one and check refuses a stale one; bump allows an index written with the entry. catalog-test.sh 154 checks (was 71), tools/catalog-test.sh 113; test-all.sh --fast passes. Not on a car. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 17 +- core/hmgapid/hmgapid.c | 4 +- core/runtime/catalog-test.sh | 264 ++++- core/runtime/java/hmgapi/engine/Catalog.java | 961 ++++++++++++++---- core/runtime/java/hmgapi/engine/Engine.java | 12 +- core/runtime/java/hmgapi/engine/Packages.java | 4 + core/runtime/java/hmgapi/engine/Version.java | 10 + tools/catalog-test.sh | 60 +- tools/catalog.py | 91 +- 9 files changed, 1183 insertions(+), 240 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 062e326b..94ae5169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,20 @@ entry by `catalog.py add`, and read again from the downloaded package's `mod.json`) are met by what's installed, or by the catalogue's version, installed first; a required mod that's turned off is turned on. Loops, conflicts, a requirement newer than the catalogue's or not - in it, and a mod for a newer HMG-API are refused before anything is downloaded or installed. - Everything is downloaded and checked before the first install. Removing a mod others - require says which won't load. + in it, an unreadable range, and a mod for a newer HMG-API are refused before anything is + downloaded or installed. The result is checked as a whole: every mod that will be on keeps + what it requires (an update that breaks another mod's range is refused), and conflicts count + whichever side lists them. Every package is downloaded and checked (SHA-256, signature, + author key, HMG-API, car) before the first install. When a package requires more than the + plan said, nothing is installed and the new plan is shown for a second OK. Removing a mod + others require says which won't load. +- **A first install from the catalogue needs a known author.** The catalogue isn't signed, so + a new mod's author key from it must already be on the head unit's trusted author list (which + only HMG-API's releases bring), or the owner says yes for that mod. +- **Staged updates wait for apply.** The automatic check stages only plain updates (nothing new + installed or turned on, signed with the installed key) into `/data/hmgapi/pending/`, which + nothing loads; `engine apply` puts them in place first and keeps the previous version in + `/data/hmgapi/previous/`. - **Home Wi-Fi joins on cars whose Wi-Fi library checks a checksum** (Ioniq 5 US 260507). The stock library starts the car's Wi-Fi client only if `wpa_supplicant_crc32.conf` holds the CRC-32 of `wpa_supplicant.conf`; HMG-API's saved networks didn't update it, so the client diff --git a/core/hmgapid/hmgapid.c b/core/hmgapid/hmgapid.c index 829b55e4..d87a9d28 100644 --- a/core/hmgapid/hmgapid.c +++ b/core/hmgapid/hmgapid.c @@ -648,8 +648,8 @@ static int op_engine(int fd, int argc, char **argv) say(fd, "usage: engine plan | apply [--trial] [--force] | keep | restore | status | recover | install | remove " " | nemesis-sync | map | map-car [--local | --write | --forget] | verify-map | report [--usb]" " | problem record [--no-log] [--crash-dumps] [--crash-reports] [--kernel] [--usb] [--seconds N] | problem stop" - " | catalog [--refresh] | catalog-plan ... | catalog-install ... [--any-car] | updates [--refresh]" - " | update ... | --all | hmgapi | update-check\n"); + " | catalog [--refresh] | catalog-plan ... [--update] | catalog-install ... [--any-car[=,...]]" + " [--any-author=,...] | updates [--refresh] | update ... | --all | hmgapi [--force] | update-check\n"); return 2; } a[n++] = APP_PROCESS; diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index c744a166..223f7183 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -1,9 +1,13 @@ #!/bin/sh # Off-car test of the catalogue and updates (Catalog): the catalogue fetched (index.json, or GitHub's -# folder listing), what each mod would do here, dependencies (requires installed first, a required -# mod that's off turned on, requires only the package names, loops, conflicts, what isn't in the -# catalogue), downloads checked (SHA-256, the package being what the entry says, the author key), -# updates (mods and HMG-API's own release), the automatic check, and a removal's warning. +# folder listing; a bad index, an entry that doesn't come), what each mod would do here, dependencies +# (requires installed first, a required mod that's off turned on, requires only the package names and +# a second OK for them, loops, conflicts either way, the result as a whole, unreadable ranges, what +# isn't in the catalogue), trust (a first install's key must be on the unit's list, or the owner's yes +# per mod), every download checked before the first install (SHA-256, the package being what the entry +# says, the author key), the owner's any-car choice per mod, updates (mods and HMG-API's own release, +# its pre-releases, mods it would leave behind), the automatic check (every 6 hours, staging only pure +# updates aside until apply), and a removal's warning. # GitHub is played by files (HMGAPI_TEST_WEB: NativeFetch.Web). set -e cd "$(dirname "$0")/../.." @@ -14,7 +18,9 @@ fail=0 check() { if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: wanted [$2], got [$3]"; fail=1; fi; } has() { case "$3" in *"$2"*) echo "ok $1" ;; *) echo "FAIL $1: wanted [$2] in [$3]"; fail=1 ;; esac; } hasnt() { case "$3" in *"$2"*) echo "FAIL $1: [$2] in [$3]"; fail=1 ;; *) echo "ok $1" ;; esac; } -eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 HMGAPI_TEST_WEB=$W java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 HMGAPI_TEST_WEB=$W HMGAPI_TEST_CHECK_GAP=${GAP-0} java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +# without the harness's HMGAPI_TEST_ANY_CAR (it only turns off the hook map here, but the owner's any-car path must not need it) +eng0() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_WEB=$W HMGAPI_TEST_CHECK_GAP=${GAP-0} java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } offline() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } sig() { java -cp "$CP" hmgapi.engine.Signing "$@"; } js() { python3 -c "import json,sys; d=json.loads(sys.stdin.read()[sys.stdin.read and 0:]); print(eval(sys.argv[1]))" "$1"; } @@ -31,7 +37,7 @@ DL=$W/github.com/test/releases/download mkdir -p "$CAT" "$DL" "$W/objects.githubusercontent.com/r" # pkg [key]: a signed package, served from a release (through GitHub's -# redirect to its asset host), and its catalogue entry (extras for the entry: $ENTRY) +# redirect to its asset host), and its catalogue entry (extras for the entry: $ENTRY; its author key: $EUUID, else the trusted one) pkg() { rm -rf $T/m; mkdir -p $T/m printf '{"id": "%s", "name": "%s mod", "version": "%s", "hmgapi": ">=1.0.0"%s}\n' "$1" "$1" "$2" "$3" > $T/m/mod.json @@ -41,8 +47,8 @@ pkg() { echo "https://objects.githubusercontent.com/r/$1-$2.zip" > "$DL/$1-$2.zip.redirect" sha=$(python3 -c "import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" "$z") printf '{"id": "%s", "name": "%s mod", "description": "the %s mod", "authors": ["tester"], "uuid": "%s", "version": "%s", "repo": "https://github.com/test/%s", "download": "https://github.com/test/releases/download/%s-%s.zip", "sha256": "%s", "hmgapi": ">=1.0.0"%s}\n' \ - "$1" "$1" "$1" "$U" "$2" "$1" "$1" "$2" "$sha" "$ENTRY" > "$CAT/$1.json" - ENTRY= + "$1" "$1" "$1" "${EUUID:-$U}" "$2" "$1" "$1" "$2" "$sha" "$ENTRY" > "$CAT/$1.json" + ENTRY= EUUID= } listing() { # GitHub's folder listing, from the entries there mkdir -p $W/api.github.com/repos/Open-HMG/HMG-API/contents @@ -118,7 +124,14 @@ pkg helper 1.0.0 pkg extra 1.0.0 ', "requires": ["helper"]'; listing eng catalog --refresh eng catalog-install extra -check "install extra" 0 $rc +check "install extra: the plan the owner saw missed a step, so stopped for a second OK" 5 $rc +has "... said why" "the packages require more than the catalogue says" "$out" +check "... the new plan handed back" "helper install extra|extra install None" "$(j '"|".join(s["id"]+" "+s["action"]+" "+str(s.get("for")) for s in d["steps"])')" +check "... nothing installed" "none none" "$(installed helper) $(installed extra)" +eng catalog-plan extra +check "... the next plan has it (learned from the package)" "helper extra" "$(j '" ".join(s["id"] for s in d["steps"])')" +eng catalog-install extra +check "install extra again" 0 $rc has "... helper, which only the package names, installed" "installing helper 1.0.0 (extra needs it)" "$out" check "... both" "1.0.0 1.0.0" "$(installed helper) $(installed extra)" @@ -155,7 +168,7 @@ has "another SHA-256: refused" "refused tampered 1.0.0: the download's SHA-256 i check "... not installed" none "$(installed tampered)" check "... nothing left behind" no "$([ -d $D/catalog/downloads ] && echo yes || echo no)" eng catalog-install wrongkey -has "signed by another key than the entry's: refused" "is signed by author key $O, not the expected $U" "$out" +has "signed by another key than the entry's: refused" "refused wrongkey 1.0.0: wrongkey is signed by author key $O, not the expected $U" "$out" check "... not installed" none "$(installed wrongkey)" # ---- updates: base 2.0.0 and an app 2.0.0 that needs it @@ -185,8 +198,27 @@ check "... nothing staged without the owner's switch" 1.0.0 "$(installed helper) mkdir -p "$D/settings/allow"; : > "$D/settings/allow/auto_stage_updates" eng update-check check "update-check, staging allowed" 0 $rc -check "... staged" 1.1.0 "$(installed helper)" -has "... logged" "staged: [helper] (the owner applies them)" "$(cat $D/logs/hmgapi/updates.log)" +has "... logged" "staged: helper 1.0.0 -> 1.1.0 (it goes in when you apply)" "$(cat $D/logs/hmgapi/updates.log)" +check "... staged aside, not installed: nothing loads it before an apply" "1.0.0 1.1.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +eng updates +check "... the update says it's staged" True "$(j '[m for m in d["mods"] if m["id"]=="helper"][0].get("staged")')" +eng plan +has "... the plan names it" "update helper 1.0.0 -> 1.1.0 (staged by the automatic check" "$out" +check "... still not installed" 1.0.0 "$(installed helper)" +eng update-check +hasnt "... checked again: not staged twice" "not staged: helper" "$(cat $D/logs/hmgapi/updates.log)" +# an apply that's refused leaves it staged +mkdir -p "$D/mods/broken"; echo '{"id": "notbroken", "version": "1.0.0"}' > "$D/mods/broken/mod.json"; echo '{"changes": []}' > "$D/mods/broken/patches.json" +eng apply +check "an apply with a problem" 3 $rc +check "... the staged update back to staged" "1.0.0 yes" "$(installed helper) $([ -d $D/pending/helper ] && echo yes)" +has "... said so" "the staged updates (helper) stay staged" "$out" +rm -r "$D/mods/broken" +eng apply +check "apply" 0 $rc +has "... the staged update put in place first" "update helper 1.0.0 -> 1.1.0 (staged by the automatic check; 1.0.0 kept in /data/hmgapi/previous/helper)" "$out" +check "... installed, the previous version kept" "1.1.0 1.0.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/previous/helper/mod.json'))['version'])")" +check "... nothing left staged" no "$([ -d $D/pending/helper ] && echo yes || echo no)" rm "$D/settings/allow/auto_stage_updates" # ---- HMG-API's own release @@ -209,6 +241,210 @@ echo '[{"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []} eng updates --refresh check "only older releases: nothing offered" None "$(j 'd.get("hmgapi")')" +# ---- HMG-API's pre-releases: a unit on 1.1.0-rc.10 is offered 1.1.0 and 1.1.0's next rcs, never 1.2.0's +REL=$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15 +rel() { # rel : a release JSON object with its assets, and its SHA256SUMS served + v=${1#v}; d=$W/github.com/Open-HMG/HMG-API/releases/download/$1; mkdir -p $d + echo "not a release" > $d/hmgapi-$v-update.zip + printf '%s hmgapi-%s-update.zip\n' "$(printf '%064d' 0)" "$v" > $d/SHA256SUMS + printf '{"tag_name": "%s", "draft": false, "prerelease": %s, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/%s", "assets": [{"name": "hmgapi-%s-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/%s/hmgapi-%s-update.zip"}, {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/%s/SHA256SUMS"}]}' \ + "$1" "$2" "$1" "$v" "$1" "$v" "$1" +} +echo "version 1.1.0-rc.10" > "$D/installed.txt" +echo "[$(rel v1.2.0-alpha.1 true), $(rel v1.1.0 false), $(rel v1.1.0-rc.11 true)]" > "$REL" +eng updates --refresh +check "on rc.10: 1.1.0 offered, not 1.2.0-alpha.1" 1.1.0 "$(j 'd["hmgapi"]["version"]')" +echo "[$(rel v1.2.0-alpha.1 true), $(rel v1.1.0-rc.11 true)]" > "$REL" +eng updates --refresh +check "... with no 1.1.0 yet: the next rc" 1.1.0-rc.11 "$(j 'd["hmgapi"]["version"]')" +python3 - "$D/settings/hmgapi.json" <<'P' +import json, os, sys +f = sys.argv[1]; d = json.load(open(f)) if os.path.exists(f) else {}; d["catalog"] = {"prereleases": True}; json.dump(d, open(f, "w")) +P +eng updates --refresh +check "... the owner's opt-in: every pre-release" 1.2.0-alpha.1 "$(j 'd["hmgapi"]["version"]')" +python3 - "$D/settings/hmgapi.json" <<'P' +import json, sys +f = sys.argv[1]; d = json.load(open(f)); del d["catalog"]; json.dump(d, open(f, "w")) +P +# ---- updating HMG-API when an installed mod's "hmgapi" range wouldn't take the new version +echo "[$(rel v1.1.0 false)]" > "$REL" +eng updates --refresh +mkdir -p "$D/mods/oldapi"; echo '{"id": "oldapi", "version": "1.0.0", "hmgapi": "<=1.1.0-rc.10"}' > "$D/mods/oldapi/mod.json" +eng update hmgapi +check "a mod that wouldn't take the new HMG-API: not yet" 1 $rc +has "... names it" "these mods wouldn't load, and applying stops until they're updated or turned off: oldapi 1.0.0 (needs HMG-API <=1.1.0-rc.10)" "$out" +hasnt "... nothing downloaded" "downloaded HMG-API" "$out" +eng update hmgapi --force +has "... the owner's override: a warning" "WARNING: with HMG-API 1.1.0 these mods won't load" "$out" +has "... then the usual checks" "refused HMG-API 1.1.0: the download's SHA-256 is" "$out" +: > "$D/mods/oldapi/.disabled" +eng update hmgapi +hasnt "... a mod that's off doesn't count" "not yet" "$out" +rm -r "$D/mods/oldapi" "$D/installed.txt" +echo '[]' > "$REL" + +# ---- trust: a first install's author key must already be on this unit's list (the catalogue isn't signed) +cp "$D/maps/authors.json" $T/authors.json +EUUID=$O; pkg stranger 1.0.0 '' $T/other.key +EUUID=$O; pkg strangedep 1.0.0 '' $T/other.key +ENTRY=', "requires": ["strangedep"]'; pkg needsstranger 1.0.0 ', "requires": ["strangedep"]' +listing; eng catalog --refresh +check "an unknown author: not trusted" False "$(j '[m for m in d["mods"] if m["id"]=="stranger"][0]["trusted"]')" +eng catalog-plan stranger +check "... the plan isn't ok" False "$(j 'd["ok"]')" +has "... why" "stranger 1.0.0 is by author key $O, which isn't on this head unit's trusted author list" "$out" +check "... the owner may say yes, for this mod" "stranger author" "$(j '" ".join(o["id"]+" "+o["kind"] for o in d["overrides"])')" +eng catalog-install stranger +check "... refused" 1 $rc +check "... not installed" none "$(installed stranger)" +eng catalog-install needsstranger +has "... a dependency by an unknown author too" "strangedep 1.0.0 is by author key $O" "$out" +check "... nothing installed" "none none" "$(installed strangedep) $(installed needsstranger)" +eng catalog-install needsstranger --any-author=needsstranger +check "... a yes for one mod isn't one for another" 1 $rc +eng catalog-install stranger --any-author=stranger +check "... the owner's yes, for that mod" 0 $rc +has "... with a warning" "WARNING: stranger is by author key $O" "$out" +check "... installed" 1.0.0 "$(installed stranger)" +EUUID=$O; pkg stranger 1.1.0 '' $T/other.key; listing; eng catalog --refresh +eng update stranger +check "... its update: the installed key, no yes needed" 0 $rc +check "... updated" 1.1.0 "$(installed stranger)" +check "... maps/authors.json never changed by the catalogue" "$(cat $T/authors.json)" "$(cat $D/maps/authors.json)" + +# ---- the result as a whole: what everything that will be on requires, and conflicts either way +pkg lib 1.0.0 +ENTRY=', "requires": ["lib ^1.0.0"]'; pkg user 1.0.0 ', "requires": ["lib ^1.0.0"]' +listing; eng catalog --refresh; eng catalog-install user +check "user and lib 1.0.0" "1.0.0 1.0.0" "$(installed user) $(installed lib)" +pkg lib 2.0.0; listing; eng catalog --refresh +eng update lib +check "an update that breaks what an installed mod requires: refused" 1 $rc +has "... why" "the installed user 1.0.0 needs lib ^1.0.0, but lib 2.0.0 would be the one installed" "$out" +eng update --all +has "... update --all leaves it out, says why" "not updated: lib: the installed user 1.0.0 needs lib ^1.0.0" "$out" +check "... lib unchanged" 1.0.0 "$(installed lib)" +pkg c 1.0.0 +ENTRY=', "requires": ["c ^1.0.0"]'; pkg a 1.0.0 ', "requires": ["c ^1.0.0"]' +listing; eng catalog --refresh; eng catalog-install a +pkg c 2.0.0 +ENTRY=', "requires": ["c >=2.0.0"]'; pkg b 1.0.0 ', "requires": ["c >=2.0.0"]' +listing; eng catalog --refresh +eng catalog-plan b +check "diamond: b needs c >=2, the installed a needs c ^1: not ok" False "$(j 'd["ok"]')" +has "... why" "the installed a 1.0.0 needs c ^1.0.0, but c 2.0.0 would be the one installed" "$out" +eng catalog-install b +check "... nothing installed" "none 1.0.0" "$(installed b) $(installed c)" +ENTRY=', "conflicts": ["peace"]'; pkg hawk 1.0.0 ', "conflicts": ["peace"]' +pkg peace 1.0.0 +listing; eng catalog --refresh; eng catalog-install hawk +eng catalog-plan peace +check "an installed mod's conflicts naming the new one: not ok" False "$(j 'd["ok"]')" +has "... why" "the installed hawk 1.0.0 conflicts with peace 1.0.0 (its conflicts list: peace): remove or update hawk first" "$out" +: > "$D/mods/hawk/.disabled" +eng catalog-plan peace +check "... with hawk off: ok" True "$(j 'd["ok"]')" +ENTRY=', "conflicts": ["peace"]'; pkg dove 1.0.0 '' +listing; eng catalog --refresh +eng catalog-plan dove peace +has "... and between two mods being installed" "dove 1.0.0 conflicts with peace 1.0.0 (being installed)" "$out" +eng remove hawk + +# ---- a range that can't be read: a plan problem, never a crash +ENTRY=', "requires": ["lib ^x.y"]'; pkg badrange 1.0.0 '' +listing; eng catalog --refresh +eng catalog-plan badrange +check "a bad range in an entry: a plan" 0 $rc +has "... with the problem" 'badrange 1.0.0: its requires \"lib ^x.y\" can'"'"'t be read' "$out" +hasnt "... no exception" "Exception" "$out" +eng catalog-install badrange +check "... not installed" "1 none" "$rc $(installed badrange)" +mkdir -p "$D/mods/oddrange"; echo '{"id": "oddrange", "version": "1.0.0", "requires": ["lib ^x.y"], "conflicts": ["c ~q"]}' > "$D/mods/oddrange/mod.json" +eng catalog-plan peace +check "... an installed mod's bad range doesn't stop other installs" True "$(j 'd["ok"]')" +rm -r "$D/mods/oddrange" + +# ---- every package checked before the first one goes in +pkg dep 1.0.0 +ENTRY=', "requires": ["dep"]'; pkg top 1.0.0 ', "requires": ["dep"]' $T/other.key +listing; eng catalog --refresh +eng catalog-install top +check "top signed with another key than its entry's: refused" 3 $rc +has "... before anything went in" "refused top 1.0.0: top is signed by author key $O, not the expected $U (nothing was installed)" "$out" +check "... its dependency not installed on its own" none "$(installed dep)" + +# ---- the owner's any-car choice: per mod, and kept (without the harness's HMGAPI_TEST_ANY_CAR) +ENTRY=', "system": {"model": ["ZZEV"]}'; pkg othercar 1.0.0 ', "system": {"model": ["ZZEV"]}' +pkg plain 1.0.0 +listing; eng0 catalog --refresh +has "othercar: not for this head unit" "car: " "$(j '[m for m in d["mods"] if m["id"]=="othercar"][0]["unfit"]')" +eng0 catalog-plan othercar plain +check "... the plan isn't ok" False "$(j 'd["ok"]')" +check "... the owner may say yes, for that mod" "othercar car" "$(j '" ".join(o["id"]+" "+o["kind"] for o in d["overrides"])')" +eng0 catalog-install othercar plain --any-car=othercar +check "... installed with a yes for othercar only" 0 $rc +check "... both" "1.0.0 1.0.0" "$(installed othercar) $(installed plain)" +has "... the choice noted" "noted: othercar runs on this head unit at your own risk" "$out" +eng0 catalog +check "... and shown" True "$(j '[m for m in d["mods"] if m["id"]=="othercar"][0].get("any_car")')" +ENTRY=', "system": {"model": ["ZZEV"]}'; pkg othercar 1.1.0 ', "system": {"model": ["ZZEV"]}' +pkg plain 1.1.0; listing; eng0 catalog --refresh +eng0 update --all +check "update --all with an any-car mod installed: the others aren't held back" "1.1.0 1.1.0" "$(installed othercar) $(installed plain)" +hasnt "... nothing refused for the car" "isn't for this head unit:" "$out" + +# ---- a hotspot mod on a unit whose Wi-Fi chip is never powered: for this head unit (SystemCheck's unpowered chip) +mkdir -p "$R/system/wifi" "$R/system/etc/permissions"; : > "$R/system/wifi/bcmdhd.ko"; : > "$R/system/wifi/fw_bcmdhd.bin" +printf '\n' > "$R/system/etc/permissions/wifi.xml" +ENTRY=', "system": {"features": ["hmgapi.wifi"]}, "wifi": {"hotspot": true}'; pkg hotspot 1.0.0 ', "system": {"features": ["hmgapi.wifi"]}, "wifi": {"hotspot": true}' +ENTRY=', "system": {"features": ["hmgapi.wifi"]}'; pkg wifionly 1.0.0 ', "system": {"features": ["hmgapi.wifi"]}' +listing; eng0 catalog --refresh +check "a hotspot mod, unpowered chip: for this head unit" None "$(j '[m for m in d["mods"] if m["id"]=="hotspot"][0].get("unfit")')" +has "... a mod that doesn't power it: not" "never powers it" "$(j '[m for m in d["mods"] if m["id"]=="wifionly"][0].get("unfit")')" +rm -r "$R/system/wifi" "$R/system/etc/permissions/wifi.xml" + +# ---- the automatic check stages only pure updates: nothing new installed, nothing turned on +: > "$D/settings/allow/auto_stage_updates" +pkg newdep 1.0.0 +ENTRY=', "requires": ["newdep"]'; pkg plain 1.2.0 ', "requires": ["newdep"]' +: > "$D/mods/helper/.disabled" +ENTRY=', "requires": ["helper"]'; pkg extra 1.1.0 ', "requires": ["helper"]' +listing +: > $T/before.log; [ -f $D/logs/hmgapi/updates.log ] && cp $D/logs/hmgapi/updates.log $T/before.log +eng update-check +L=$(diff $T/before.log $D/logs/hmgapi/updates.log || true) +has "an update that needs a new mod: not staged" "not staged: plain: it takes installing newdep 1.0.0 too" "$L" +has "an update that needs a mod turned on: not staged" "not staged: extra: it takes turning on helper too" "$L" +check "... neither staged, newdep not installed, helper still off" "no no none yes" "$([ -d $D/pending/plain ] && echo yes || echo no) $([ -d $D/pending/extra ] && echo yes || echo no) $(installed newdep) $([ -f $D/mods/helper/.disabled ] && echo yes)" +rm "$D/mods/helper/.disabled" "$D/settings/allow/auto_stage_updates" + +# ---- update-check at most every 6 hours (2 GitHub API calls of 60 an hour each) +: > $W/requests.log +GAP=21600 eng update-check +has "a check within 6 hours of the last: not made" "not checked: the last check was 0 min ago" "$(cat $D/logs/hmgapi/updates.log)" +check "... nothing asked of GitHub" "" "$(cat $W/requests.log)" + +# ---- a plan refreshes a catalogue that's old, when it can +pkg fresh 1.0.0; listing; eng catalog --refresh +pkg fresh 1.1.0; listing +eng catalog-plan fresh +check "a fresh catalogue: as checked" 1.0.0 "$(j 'd["steps"][0]["version"]')" +python3 - "$D/catalog/catalog.json" <<'P' +import json, sys +f = sys.argv[1]; d = json.load(open(f)); d["checked"] = 0; json.dump(d, open(f, "w")) +P +eng catalog-plan fresh +check "... an old one: checked again first" 1.1.0 "$(j 'd["steps"][0]["version"]')" + +# ---- one entry that doesn't come: the last check's stays +mv "$CAT/fresh.json" $T/fresh.json +eng catalog --refresh +has "an entry that didn't come: still there" "fresh" "$(j '" ".join(m["id"] for m in d["mods"])')" +has "... noted" "fresh.json: HTTP 404 (the last check's entry kept)" "$(j '" ".join(d.get("notes", []))')" +mv $T/fresh.json "$CAT/fresh.json" +check "no temporary files left" "" "$(ls -a $D/catalog $D/public | grep '\.tmp$' || true)" + # ---- an index.json, when the repo has one, instead of the listing python3 - "$CAT" <<'P' import json,os,sys; c=sys.argv[1]; json.dump({"mods": [json.load(open(os.path.join(c,"base.json")))]}, open(os.path.join(c,"index.json"),"w")) @@ -221,6 +457,10 @@ echo '{"mods": [{"id": "Bad Id"}, {"id": "nohttps", "version": "1.0.0", "downloa eng catalog --refresh check "bad entries left out" 0 "$(j 'len(d["mods"])')" has "... with a note" "nohttps: left out (download isn't https)" "$out" +echo '{"mods": [' > "$CAT/index.json" +eng catalog --refresh +has "an index.json that isn't JSON: said" "the catalogue's index.json isn't JSON" "$out" +check "... the old catalogue kept" 0 "$(j 'len(d["mods"])')" touch "$W/raw.githubusercontent.com.down" eng catalog --refresh has "GitHub not answering: said, the old catalogue kept" "no connection" "$out" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index 7eb1eacb..8e5679c9 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -20,30 +21,56 @@ * repo has one, else GitHub's folder listing); HMG-API itself comes from its GitHub releases. * * engine catalog [--refresh] the catalogue and what each mod would do here (JSON, for the app) - * engine catalog-plan ... what installing them takes: their requires, in order (JSON) - * engine catalog-install ... [--any-car] download, check and install them with what they require + * engine catalog-plan ... [--update] | --update --all + * what installing (updating) them takes: their requires, in order (JSON) + * engine catalog-install ... download, check and install them with what they require * engine updates [--refresh] installed mods (and HMG-API) with a newer version (JSON) - * engine update ... | --all | hmgapi update them (with any new requires); hmgapi: HMG-API itself - * engine update-check wifi.sh, each time home Wi-Fi comes up: refresh, and stage the - * mods' updates if the owner allowed it (allow auto_stage_updates) + * engine update ... | --all | hmgapi [--force] + * update them (with any new requires); hmgapi: HMG-API itself + * engine update-check wifi.sh, each time home Wi-Fi comes up (at most every 6 hours): + * refresh, and stage the mods' updates if the owner allowed it + * overrides, the owner's own choice, per mod: --any-car=,... (not listed for this head unit), + * --any-author=,... (a first install by an author key that isn't on this unit's trusted list); + * --any-car alone: every mod in the batch * * Network: home Wi-Fi only (NativeFetch: its socket is marked for table 95), never the car's - * mobile data; a refresh refuses to start unless home Wi-Fi is up. Trust: an entry only says where - * to look. Its download must have its SHA-256, and Packages checks its signature: an update needs - * the installed mod's author key, a first install the entry's (--uuid), and HMG-API itself needs - * the release key (UsbUpdates). Nothing is applied here: the owner applies (engine apply) as after - * any install. Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and, - * to be sure, from the downloaded package's mod.json; each is met by what's installed, or by the - * catalogue's version, installed first. A required mod that's turned off is turned on. + * mobile data; a refresh refuses to start unless home Wi-Fi is up. + * + * Trust: the catalogue isn't signed, so an entry only says where to look and what to expect. Its + * download must have its SHA-256, and Packages checks its signature: an update needs the installed + * mod's author key; a first install needs the entry's key, and that key must already be on this + * unit's trusted author list (maps/authors.json, which only HMG-API's own signed releases bring: + * never refreshed from the catalogue), else the owner says yes per mod (--any-author=). + * HMG-API itself needs the release key (UsbUpdates). Every package is checked (Packages.check) + * before the first one goes in. Nothing is applied here: the owner applies (engine apply) as after + * any install. + * + * Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and from the + * downloaded package's mod.json (kept in learned.json, so the next plan has them); each is met by + * what's installed, or by the catalogue's version, installed first. A required mod that's turned off + * is turned on. After planning, every mod that will be on is checked against the result: its + * requires met, and no conflicts either way. When a package requires more than the plan the owner + * saw, nothing is installed and the new plan is handed back (exit 5) for a second OK. + * + * The automatic check stages only pure updates (nothing else installed or turned on, signed with the + * installed key) into /data/hmgapi/pending/, which the hook loader and apps never read; engine + * apply puts them in place (the previous version kept in /data/hmgapi/previous/) right before + * it plans, so new code never runs next to the old version's files. */ final class Catalog { static final String BASE = "https://raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog/"; static final String RELEASES = "https://api.github.com/repos/Open-HMG/HMG-API/releases?per_page=15"; static final int MAX_JSON = 1 << 20, MAX_ENTRY = 64 << 10, MAX_ENTRIES = 500; static final String ID = "[a-z0-9][a-z0-9-]{0,63}"; + /** a plan or install refreshes a catalogue older than this when it can */ + static final long STALE_MS = 15 * 60 * 1000L; + /** update-check: at most one every 6 hours (each is 2 of GitHub's 60 API calls an hour) */ + static final long CHECK_GAP_S = 6 * 3600; + /** catalog-install / update: the packages require more than the plan said; the new plan is in the output */ + static final int PLAN_CHANGED = 5; final Engine e; - final File dir, cacheFile, updatesFile; + final File dir, cacheFile, updatesFile, learnedFile; Map cache; Catalog(Engine e) { @@ -51,22 +78,40 @@ final class Catalog { dir = new File(e.data, "catalog"); cacheFile = new File(dir, "catalog.json"); updatesFile = new File(dir, "updates.json"); + learnedFile = new File(dir, "learned.json"); + } + + /** the owner's per-mod choices for this run */ + static final class Overrides { + boolean anyCarAll; + final Set anyCar = new LinkedHashSet(), anyAuthor = new LinkedHashSet(); + + boolean car(String id) { + return anyCarAll || anyCar.contains(id); + } } // ---- the ops + @SuppressWarnings("unchecked") static int run(Engine e, String[] args) throws Exception { Catalog c = new Catalog(e); String cmd = args[0]; List ids = new ArrayList(); - boolean refresh = false, anyCar = false, all = false; + boolean refresh = false, all = false, update = "update".equals(cmd), force = false; + Overrides ov = new Overrides(); for (int i = 1; i < args.length; i++) { - if ("--refresh".equals(args[i])) refresh = true; - else if ("--any-car".equals(args[i])) anyCar = true; - else if ("--all".equals(args[i])) all = true; - else if (args[i].matches(ID)) ids.add(args[i]); + String a = args[i]; + if ("--refresh".equals(a)) refresh = true; + else if ("--any-car".equals(a)) ov.anyCarAll = true; + else if (a.startsWith("--any-car=") && idList(a.substring(10), ov.anyCar)) continue; + else if (a.startsWith("--any-author=") && idList(a.substring(13), ov.anyAuthor)) continue; + else if ("--all".equals(a)) all = true; + else if ("--update".equals(a) && "catalog-plan".equals(cmd)) update = true; + else if ("--force".equals(a) && "update".equals(cmd)) force = true; + else if (a.matches(ID)) ids.add(a); else { - e.out.add("not a mod id: " + args[i]); + e.out.add("not a mod id: " + a); return 2; } } @@ -79,32 +124,36 @@ static int run(Engine e, String[] args) throws Exception { return 0; } if ("update-check".equals(cmd)) return c.updateCheck(); - if (c.cache == null) { + // planning and installing: the catalogue as it is now, when home Wi-Fi is up + String stale = null; + if (c.cache == null || (c.offline() == null && c.stale())) { String err = c.refresh(); - if (err != null) { + if (err != null && c.cache == null) { e.out.add("no catalogue yet: " + err); return 1; } + if (err != null) stale = "the catalogue couldn't be checked again (" + err + "): this is the last check's"; } if ("update".equals(cmd) && ids.remove("hmgapi")) { if (!ids.isEmpty() || all) { e.out.add("update HMG-API on its own: engine update hmgapi"); return 2; } - return c.updateHmgApi(); + return c.updateHmgApi(force); } - if ("update".equals(cmd) && all) { + if (update && all) { for (Object o : (List) c.updates().get("mods")) ids.add(String.valueOf(((Map) o).get("id"))); - if (ids.isEmpty()) { + if (ids.isEmpty() && "update".equals(cmd)) { e.out.add("every installed mod is up to date with the catalogue"); return 0; } } - if (ids.isEmpty()) { - e.out.add("usage: engine " + cmd + " ..." + ("update".equals(cmd) ? " | --all | hmgapi" : "")); + if (ids.isEmpty() && !(update && all)) { + e.out.add("usage: engine " + cmd + " ..." + ("update".equals(cmd) ? " | --all | hmgapi" : "catalog-plan".equals(cmd) ? " [--update] | --update --all" : "")); return 2; } - Plan p = c.plan(ids, "update".equals(cmd), anyCar); + Plan p = update && all ? c.planEach(ids, ov) : c.plan(ids, update, ov); + if (stale != null) p.notes.add(stale); if ("catalog-plan".equals(cmd)) { e.out.add(Json.write(p.toJson())); return 0; @@ -113,7 +162,15 @@ static int run(Engine e, String[] args) throws Exception { e.out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); return 1; } - return c.execute(p, anyCar); + return c.execute(p); + } + + static boolean idList(String s, Set into) { + for (String x : s.split(",")) { + if (!x.matches(ID)) return false; + into.add(x); + } + return true; } // ---- the catalogue: fetched, cached in /data/hmgapi/catalog/catalog.json @@ -127,6 +184,17 @@ void load() { } } + /** older than STALE_MS, or checked "in the future" (the clock was set back since) */ + boolean stale() { + long now = System.currentTimeMillis(), t = checked(); + return now - t > STALE_MS || now < t; + } + + long checked() { + Object t = cache == null ? null : cache.get("checked"); + return t instanceof Number ? ((Number) t).longValue() : 0; + } + /** the catalogue's folder: hmgapi.json "catalog": {"base": ...} (a fork, a test), else HMG-API's own */ @SuppressWarnings("unchecked") String base() { @@ -138,11 +206,21 @@ String base() { return BASE; } + /** hmgapi.json "catalog": {"prereleases": true}: every pre-release offered */ @SuppressWarnings("unchecked") boolean prereleases() { Object c = e.hmgapi.get("catalog"); - if (c instanceof Map && Boolean.TRUE.equals(((Map) c).get("prereleases"))) return true; - return !new Version(installedHmgApi()).tag.isEmpty(); // on a pre-release: offered the next ones + return c instanceof Map && Boolean.TRUE.equals(((Map) c).get("prereleases")); + } + + /** + * Is HMG-API's pre-release v offered here? With the owner's opt-in, any; else only the next ones of + * the pre-release this unit is on (1.1.0-rc.10: 1.1.0-rc.11, never 1.2.0-alpha.1). + */ + boolean offered(Version v) { + if (prereleases()) return true; + Version have = new Version(installedHmgApi()); + return !have.tag.isEmpty() && Arrays.equals(have.n, v.n); } String installedHmgApi() { @@ -163,6 +241,22 @@ String offline() { } } + /** a name for a file written whole and renamed into place: its own per run (a refresh may run next to another) */ + static File tmpName(File dir, String name) { + return new File(dir, "." + name + "." + System.nanoTime() + ".tmp"); + } + + static void writeWhole(File f, String text, boolean world) throws IOException { + f.getParentFile().mkdirs(); + File n = tmpName(f.getParentFile(), f.getName()); + Engine.write(n, text); + if (world) n.setReadable(true, false); + if (!n.renameTo(f)) { + n.delete(); + throw new IOException("can't write " + f); + } + } + /** Fetches the catalogue and HMG-API's releases; null when it worked, else why not (the old cache stays). */ @SuppressWarnings("unchecked") String refresh() throws Exception { @@ -177,11 +271,17 @@ String refresh() throws Exception { Http http = new Http(t, tmp); List notes = new ArrayList(); List mods = new ArrayList(); + Map> before = entries(); String base = base(); File f = new File(tmp, "index.json"); Http.Result r = http.get(base + "index.json", f, MAX_JSON); if (r.ok()) { - Object idx = Json.parse(Engine.read(f)); + Object idx; + try { + idx = Json.parse(Engine.read(f)); + } catch (Exception x) { + return "the catalogue's index.json isn't JSON (" + x.getMessage() + ")"; + } Object list = idx instanceof Map ? ((Map) idx).get("mods") : idx; if (!(list instanceof List)) return "the catalogue's index.json isn't a list of mods"; for (Object o : (List) list) add(mods, o, notes); @@ -191,7 +291,12 @@ String refresh() throws Exception { if (api == null) return "no catalog/index.json at " + base; r = http.get(api, f, MAX_JSON); if (!r.ok()) return "the catalogue's listing: " + r; - Object list = Json.parse(Engine.read(f)); + Object list; + try { + list = Json.parse(Engine.read(f)); + } catch (Exception x) { + return "the catalogue's listing isn't JSON"; + } if (!(list instanceof List)) return "the catalogue's listing isn't a list"; for (Object o : (List) list) { if (!(o instanceof Map)) continue; @@ -200,15 +305,23 @@ String refresh() throws Exception { if (mods.size() >= MAX_ENTRIES) break; File ef = new File(tmp, name); Http.Result er = http.get(base + name, ef, MAX_ENTRY); - if (!er.ok()) { - notes.add(name + ": " + er); - continue; + String bad = er.ok() ? null : er.toString(); + Object en = null; + if (bad == null) { + try { + en = Json.parse(Engine.read(ef)); + } catch (Exception x) { + bad = "not JSON"; + } } - try { - add(mods, Json.parse(Engine.read(ef)), notes); - } catch (Exception x) { - notes.add(name + ": not JSON"); + if (bad != null) { + // one entry that didn't come: the last check's stays, rather than the mod vanishing + Map old = before.get(name.substring(0, name.length() - 5)); + notes.add(name + ": " + bad + (old != null ? " (the last check's entry kept)" : "")); + if (old != null) add(mods, old, notes); + continue; } + add(mods, en, notes); } } else { return "the catalogue: " + r; @@ -228,10 +341,7 @@ String refresh() throws Exception { else if (relErr != null && cache != null && cache.get("hmgapi") != null) c.put("hmgapi", cache.get("hmgapi")); // kept if (relErr != null) notes.add("HMG-API's releases: " + relErr); if (!notes.isEmpty()) c.put("notes", notes); - dir.mkdirs(); - File n = new File(dir, ".catalog.json.tmp"); - Engine.write(n, Json.write(c)); - if (!n.renameTo(cacheFile)) throw new IOException("can't write " + cacheFile); + writeWhole(cacheFile, Json.write(c), false); cache = c; writeUpdates(); return null; @@ -277,9 +387,8 @@ static boolean valid(String v) { } /** - * HMG-API's newest release this unit is offered (pre-releases only on a pre-release, or with - * hmgapi.json "catalog": {"prereleases": true}): its update zip and the SHA-256 from its - * SHA256SUMS; null if none is newer than what's installed. + * HMG-API's newest release this unit is offered (pre-releases as offered() says): its update zip + * and the SHA-256 from its SHA256SUMS; null if none is newer than what's installed. */ @SuppressWarnings("unchecked") Map latestRelease(Http http, File tmp) throws Exception { @@ -290,15 +399,14 @@ Map latestRelease(Http http, File tmp) throws Exception { if (!(list instanceof List)) throw new IOException("not a list of releases"); Map best = null; Version bv = new Version(installedHmgApi()); - boolean pre = prereleases(); for (Object o : (List) list) { if (!(o instanceof Map)) continue; Map rel = (Map) o; if (Boolean.TRUE.equals(rel.get("draft"))) continue; - if (Boolean.TRUE.equals(rel.get("prerelease")) && !pre) continue; String tag = String.valueOf(rel.get("tag_name")); if (!tag.matches("v\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.]+)?")) continue; Version v = new Version(tag); + if ((Boolean.TRUE.equals(rel.get("prerelease")) || !v.tag.isEmpty()) && !offered(v)) continue; if (v.compareTo(bv) <= 0) continue; String zip = null, sums = null; Object assets = rel.get("assets"); @@ -336,6 +444,7 @@ Map latestRelease(Http http, File tmp) throws Exception { static final class Inst { String version; boolean enabled; + Object requires, conflicts; } @SuppressWarnings("unchecked") @@ -346,9 +455,12 @@ Map installed() { File mj = new File(d, "mod.json"); if (!d.getName().matches(ID) || !mj.isFile()) continue; try { + Map j = Json.object(Engine.read(mj)); Inst i = new Inst(); - i.version = String.valueOf(Json.object(Engine.read(mj)).get("version")); + i.version = String.valueOf(j.get("version")); i.enabled = !new File(d, ".disabled").exists(); + i.requires = j.get("requires"); + i.conflicts = j.get("conflicts"); m.put(d.getName(), i); } catch (Exception x) { // a broken mod.json: the engine's other checks say so @@ -377,20 +489,48 @@ static List deps(Object list) { return out; } - /** why this unit can't take the entry, or null: its HMG-API range; "car: ..." for its "system" (an override exists) */ - @SuppressWarnings("unchecked") + /** deps(), the unreadable ones (bad id or range) left out: for what's installed, which the engine's plan reports itself */ + static List readable(Object list) { + List out = new ArrayList(); + for (Version.Dep d : deps(list)) if (d.id.matches(ID) && (d.range == null || Version.rangeError(d.range) == null)) out.add(d); + return out; + } + + static boolean sat(String v, String range) { + try { + return Version.satisfies(v, range); + } catch (IllegalArgumentException x) { + return false; + } + } + + static boolean has(List l, Version.Dep d) { + for (Version.Dep k : l) if (k.toString().equals(d.toString())) return true; + return false; + } + + /** + * why this unit can't take the entry, or null: its HMG-API range; "car: ..." for its "system" (an + * override exists, and the owner's earlier choice, hmgapi.json overrides.ignore_system, counts) + */ String unfit(Map en) { Object need = en.get("hmgapi"); - if (need != null && !Version.meetsHmgapi(installedHmgApi(), String.valueOf(need))) { - return "needs HMG-API " + need + " (this is " + installedHmgApi() + ")"; + if (need != null) { + String bad = Version.rangeError(String.valueOf(need)); + if (bad != null) return "its \"hmgapi\" " + bad; + if (!Version.meetsHmgapi(installedHmgApi(), String.valueOf(need))) return "needs HMG-API " + need + " (this is " + installedHmgApi() + ")"; } if (en.get("system") != null) { - String sys = SystemCheck.check(en.get("system"), e.facts, false); + String sys = SystemCheck.check(en.get("system"), e.facts, SystemCheck.asksHotspot(en)); if (sys != null) return "car: " + sys; } return null; } + boolean carChosen(String id) { + return SystemCheck.ignored(e.hmgapi, id); + } + static String status(String have, String offered) { if (have == null) return "new"; int c; @@ -429,6 +569,7 @@ Map report() { m.put("status", status(i == null ? null : i.version, String.valueOf(en.get("version")))); String unfit = unfit(en); if (unfit != null) m.put("unfit", unfit); + if (unfit != null && unfit.startsWith("car: ") && carChosen(id)) m.put("any_car", true); List req = new ArrayList(); for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); if (!req.isEmpty()) m.put("requires", req); @@ -476,6 +617,7 @@ Map updates() { List req = new ArrayList(); for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); if (!req.isEmpty()) m.put("requires", req); + if (String.valueOf(en.get("version")).equals(stagedVersion(e, i.getKey()))) m.put("staged", true); list.add(m); } Map h = hmgapiOffer(); @@ -486,17 +628,62 @@ Map updates() { return rep; } - /** updates.json, also in public/ for the app (the Mods tab's "Updates (n)") */ + /** updates.json, also in public/ for the app (the Mods tab's "Updates (n)"); after any install or removal too */ void writeUpdates() throws IOException { String text = Json.write(updates()); - dir.mkdirs(); - Engine.write(updatesFile, text); - File pub = new File(e.data, "public"); - pub.mkdirs(); - File tmp = new File(pub, ".updates.json.tmp"); - Engine.write(tmp, text); - tmp.setReadable(true, false); - if (!tmp.renameTo(new File(pub, "updates.json"))) throw new IOException("can't write public/updates.json"); + writeWhole(updatesFile, text, false); + writeWhole(new File(e.data, "public/updates.json"), text, true); + } + + /** the same, from an install or removal outside the catalogue (a USB stick, adb): never fails it */ + static void updatesChanged(Engine e) { + try { + Catalog c = new Catalog(e); + c.load(); + if (c.cache != null) c.writeUpdates(); + } catch (Exception x) { + // the count catches up at the next check + } + } + + // ---- what the downloaded packages said: requires and conflicts their entries didn't have + + @SuppressWarnings("unchecked") + Map learned() { + try { + if (learnedFile.isFile()) return Json.object(Engine.read(learnedFile)); + } catch (Exception x) { + // unreadable: learned again from the next download + } + return new LinkedHashMap(); + } + + static String key(Map en) { + return en.get("id") + " " + en.get("version") + " " + en.get("sha256"); + } + + /** keeps the package's requires and conflicts for its entry (this exact download); true if the plan didn't know one */ + @SuppressWarnings("unchecked") + boolean learn(Plan p, Step s, Map mj) throws IOException { + boolean more = false; + for (String k : new String[] {"requires", "conflicts"}) { + List known = "requires".equals(k) ? p.requires(s.id, s.entry) : p.conflicts(s.id, s.entry); + for (Version.Dep d : deps(mj.get(k))) more |= !has(known, d); + } + if (!more) return false; + Map all = learned(); + Map one = new LinkedHashMap(); + one.put("requires", mj.get("requires") instanceof List ? mj.get("requires") : new ArrayList()); + one.put("conflicts", mj.get("conflicts") instanceof List ? mj.get("conflicts") : new ArrayList()); + all.put(key(s.entry), one); + for (String old : new ArrayList(all.keySet())) { // only the current entries' packages are kept + Map en = p.cat.get(old.split(" ")[0]); + if (en == null || !old.equals(key(en))) all.remove(old); + } + writeWhole(learnedFile, Json.write(all), false); + p.learned.clear(); + p.learned.putAll(all); + return true; } // ---- dependencies: what installing some mods takes, in order (what they require first) @@ -504,7 +691,9 @@ void writeUpdates() throws IOException { static final class Step { final String id, action, version, installed, because; final Map entry; - File zip; + /** a required mod that's off and is installed again: turned on too */ + boolean turnOn; + File dir; Step(String id, String action, String version, String installed, String because, Map entry) { this.id = id; @@ -514,47 +703,106 @@ static final class Step { this.because = because; this.entry = entry; } + + String same() { + return id + " " + action + " " + version + " " + turnOn; + } + } + + /** a mod as it would be after the plan */ + static final class Fin { + String version; + boolean on, changed; + List requires, conflicts; } final class Plan { final List steps = new ArrayList(); final List problems = new ArrayList(), notes = new ArrayList(); + /** what the owner may say yes to: {"id", "kind": "car" | "author", "why"} */ + final List overrides = new ArrayList(); + /** update --all: the mods left out, each {"id", "why", "overrides"} */ + final List skipped = new ArrayList(); final Map> cat = entries(); final Map inst = installed(); - /** requires learned from the downloaded packages (their mod.json), by id */ - final Map> learned = new LinkedHashMap>(); + final Map learned = learned(); final Set visiting = new LinkedHashSet(); - boolean anyCar; + final List wanted = new ArrayList(); + final Overrides ov; + boolean update; + + Plan(Overrides ov) { + this.ov = ov == null ? new Overrides() : ov; + } + + void problem(String s) { + if (!problems.contains(s)) problems.add(s); + } + + void override(String id, String kind, String why) { + Map m = new LinkedHashMap(); + m.put("id", id); + m.put("kind", kind); + m.put("why", why); + if (!overrides.contains(m)) overrides.add(m); + } Step planned(String id) { for (Step s : steps) if (s.id.equals(id)) return s; return null; } - List requires(String id, Map en) { - List r = new ArrayList(deps(en.get("requires"))); - if (learned.containsKey(id)) r.addAll(learned.get(id)); + /** a dependency list from an entry or a package: an unreadable one (bad id or range) is a problem */ + List checked(Object list, String owner, String what, List into) { + for (Version.Dep d : deps(list)) { + String bad = !d.id.matches(ID) ? "\"" + d.id + "\" isn't a mod id" : d.range == null ? null : Version.rangeError(d.range); + if (bad != null) problem(owner + ": its " + what + " \"" + d + "\" can't be read: " + bad); + else if (!has(into, d)) into.add(d); + } + return into; + } + + @SuppressWarnings("unchecked") + List fromEntry(String id, Map en, String k) { + String owner = id + " " + en.get("version"); + List r = checked(en.get(k), owner, k, new ArrayList()); + Object l = learned.get(key(en)); + if (l instanceof Map) checked(((Map) l).get(k), owner, k, r); return r; } + List requires(String id, Map en) { + return fromEntry(id, en, "requires"); + } + + List conflicts(String id, Map en) { + return fromEntry(id, en, "conflicts"); + } + boolean fits(Map en, String who) { String unfit = unfit(en); if (unfit == null) return true; - if (unfit.startsWith("car: ") && anyCar) { - notes.add(en.get("id") + " isn't listed for this head unit (" + unfit.substring(5) + "): installing it anyway, at your own risk"); - return true; + String id = String.valueOf(en.get("id")); + if (unfit.startsWith("car: ")) { + if (ov.car(id) || carChosen(id)) { + notes.add(id + " isn't listed for this head unit (" + unfit.substring(5) + "): " + (ov.car(id) ? "installing it anyway, at your own risk" + : "you chose to use it here anyway")); + return true; + } + override(id, "car", unfit.substring(5)); } - problems.add((who != null ? who + " needs " : "") + en.get("id") + " " + en.get("version") + ", which " + problem((who != null ? who + " needs " : "") + id + " " + en.get("version") + ", which " + (unfit.startsWith("car: ") ? "isn't for this head unit: " + unfit.substring(5) : unfit)); return false; } /** a mod asked for by the owner: installed, or updated */ void want(String id, boolean update) { + if (!wanted.contains(id)) wanted.add(id); Map en = cat.get(id); Inst i = inst.get(id); if (en == null) { - problems.add(id + " isn't in the catalogue"); + problem(id + " isn't in the catalogue"); return; } String st = status(i == null ? null : i.version, String.valueOf(en.get("version"))); @@ -564,7 +812,7 @@ void want(String id, boolean update) { return; } if (update && i == null) { - problems.add(id + " isn't installed: install it from the catalogue"); + problem(id + " isn't installed: install it from the catalogue"); return; } if (fits(en, null)) take(en, null); @@ -572,71 +820,141 @@ void want(String id, boolean update) { /** a requirement: met by what's installed (turned on if it's off) or planned, else the catalogue's */ void need(Version.Dep d, String who) { + Inst i = inst.get(d.id); Step p = planned(d.id); - if (p != null && !"enable".equals(p.action)) { - if (!Version.satisfies(p.version, d.range)) problems.add(who + " needs " + d + ", but " + d.id + " " + p.version + " is the one being installed"); + if (p != null && !"enable".equals(p.action)) { // its version: settle() checks it against everything that will be on + if (i != null && !i.enabled) p.turnOn = true; return; } - Inst i = inst.get(d.id); - if (i != null && Version.satisfies(i.version, d.range)) { + if (i != null && sat(i.version, d.range)) { if (!i.enabled && p == null) add(new Step(d.id, "enable", i.version, i.version, who, cat.get(d.id))); return; } Map en = cat.get(d.id); if (en == null) { - problems.add(who + " needs " + d + (i != null ? " (" + i.version + " is installed)" : "") + ", which isn't in the catalogue"); + problem(who + " needs " + d + (i != null ? " (" + i.version + " is installed)" : "") + ", which isn't in the catalogue"); return; } - if (!Version.satisfies(String.valueOf(en.get("version")), d.range)) { - problems.add(who + " needs " + d + ", but the catalogue has " + d.id + " " + en.get("version") + if (!sat(String.valueOf(en.get("version")), d.range)) { + problem(who + " needs " + d + ", but the catalogue has " + d.id + " " + en.get("version") + (i != null ? " (" + i.version + " is installed)" : "")); return; } if (i != null && "older".equals(status(i.version, String.valueOf(en.get("version"))))) { - problems.add(who + " needs " + d + ": the installed " + d.id + " " + i.version + " doesn't fit and the catalogue's is older"); + problem(who + " needs " + d + ": the installed " + d.id + " " + i.version + " doesn't fit and the catalogue's is older"); return; } - if (fits(en, who)) take(en, who); + if (fits(en, who)) { + take(en, who); + Step s = planned(d.id); + if (s != null && i != null && !i.enabled) s.turnOn = true; + } } void take(Map en, String who) { String id = String.valueOf(en.get("id")); if (planned(id) != null) return; if (!visiting.add(id)) { - problems.add("a requires loop: " + visiting + " -> " + id); + problem("a requires loop: " + visiting + " -> " + id); return; } + Inst i = inst.get(id); + if (i == null) trust(id, en); for (Version.Dep d : requires(id, en)) need(d, id); visiting.remove(id); - Inst i = inst.get(id); add(new Step(id, i == null ? "install" : "update", String.valueOf(en.get("version")), i == null ? null : i.version, who, en)); } + /** + * A first install's author key comes from the catalogue, which isn't signed: it must already be on this + * unit's trusted list (maps/authors.json, from HMG-API's own release), or the owner says yes for this mod. + */ + void trust(String id, Map en) { + String uuid = String.valueOf(en.get("uuid")); + if (Packages.trustedAuthor(e, uuid) != null) return; + if (ov.anyAuthor.contains(id)) { + notes.add("WARNING: " + id + " is by author key " + uuid + ", which isn't on this head unit's trusted author list: installing it" + + " because you said so. Its updates must come from this same key."); + return; + } + override(id, "author", "author key " + uuid + " isn't on this head unit's trusted author list"); + problem(id + " " + en.get("version") + " is by author key " + uuid + ", which isn't on this head unit's trusted author list" + + " (it comes with HMG-API's releases). The catalogue isn't signed, so HMG-API doesn't take a new author's key from it" + + " on its own: install it only if you trust its author (\"Install anyway\", or --any-author=" + id + ")"); + } + void add(Step s) { if (planned(s.id) == null) steps.add(s); } - /** conflicts: theirs (entry, package) against what's installed and on, and what's planned */ - void conflicts(Map> pkgConflicts) { + /** + * The result as a whole: every mod that will be on has what it requires, on and in range, and no mod + * that will be on conflicts with another, whichever side lists it. Only what this plan changes is + * checked (what was already broken isn't this install's to refuse). pkgs: the downloaded packages' + * mod.json, by id, once there are any. + */ + void settle(Map> pkgs) { + if (!problems.isEmpty()) return; + Map fin = new TreeMap(); + for (Map.Entry x : inst.entrySet()) { + Fin f = new Fin(); + f.version = x.getValue().version; + f.on = x.getValue().enabled; + f.requires = readable(x.getValue().requires); + f.conflicts = readable(x.getValue().conflicts); + fin.put(x.getKey(), f); + } for (Step s : steps) { - if ("enable".equals(s.action) || s.entry == null) continue; - List cs = new ArrayList(deps(s.entry.get("conflicts"))); - if (pkgConflicts.containsKey(s.id)) cs.addAll(pkgConflicts.get(s.id)); - for (Version.Dep c : cs) { - Step p = planned(c.id); - Inst i = inst.get(c.id); - String v = p != null ? p.version : i != null && i.enabled ? i.version : null; - if (v != null && Version.satisfies(v, c.range)) { - problems.add(s.id + " " + s.version + " conflicts with " + c.id + " " + v + (p != null ? " (being installed)" : " (installed)") - + ": remove or update " + c.id + " first"); - } + Fin old = fin.get(s.id); + if ("enable".equals(s.action)) { + if (old != null) old.on = old.changed = true; + continue; + } + Fin f = new Fin(); + f.version = s.version; + f.on = old == null || old.on || s.turnOn; + f.changed = true; + f.requires = requires(s.id, s.entry); + f.conflicts = conflicts(s.id, s.entry); + Map pk = pkgs.get(s.id); + if (pk != null) { + checked(pk.get("requires"), s.id + " " + s.version, "requires", f.requires); + checked(pk.get("conflicts"), s.id + " " + s.version, "conflicts", f.conflicts); } + fin.put(s.id, f); } + for (Map.Entry x : fin.entrySet()) { + String id = x.getKey(); + Fin a = x.getValue(); + if (!a.on) continue; + String who = (a.changed ? "" : "the installed ") + id + " " + a.version; + for (Version.Dep d : a.requires) { + Fin b = fin.get(d.id); + if (!a.changed && (b == null || !b.changed)) continue; + if (b != null && b.on && sat(b.version, d.range)) continue; + problem(who + " needs " + d + ", but " + (b == null ? d.id + " wouldn't be installed" + : !b.on ? d.id + " would stay turned off" : d.id + " " + b.version + " would be " + (b.changed ? "the one installed" : "installed"))); + } + for (Version.Dep c : a.conflicts) { + Fin b = fin.get(c.id); + if (b == null || !b.on || c.id.equals(id) || (!a.changed && !b.changed) || !sat(b.version, c.range)) continue; + problem(a.changed ? id + " " + a.version + " conflicts with " + c.id + " " + b.version + (b.changed ? " (being installed)" : " (installed)") + + ": remove or update " + c.id + " first" + : who + " conflicts with " + c.id + " " + b.version + " (its conflicts list: " + c + "): remove or update " + id + " first"); + } + } + } + + String sameAs() { + StringBuilder b = new StringBuilder(); + for (Step s : steps) b.append(s.same()).append('|'); + return b.toString(); } Map toJson() { Map m = new LinkedHashMap(); m.put("ok", problems.isEmpty()); + m.put("wanted", wanted); List st = new ArrayList(); for (Step s : steps) { Map x = new LinkedHashMap(); @@ -646,28 +964,99 @@ Map toJson() { x.put("version", s.version); if (s.installed != null) x.put("installed", s.installed); if (s.because != null) x.put("for", s.because); + if (s.turnOn) x.put("turn_on", true); if (s.entry != null) x.put("trusted", Packages.trustedAuthor(e, String.valueOf(s.entry.get("uuid"))) != null); + if (ov.car(s.id)) x.put("any_car", true); st.add(x); } m.put("steps", st); if (!problems.isEmpty()) m.put("problems", problems); + if (!overrides.isEmpty()) m.put("overrides", overrides); + if (!skipped.isEmpty()) m.put("skipped", skipped); if (!notes.isEmpty()) m.put("notes", notes); return m; } } - Plan plan(List ids, boolean update, boolean anyCar) { - Plan p = new Plan(); - p.anyCar = anyCar; + Plan plan(List ids, boolean update, Overrides ov) { + Plan p = new Plan(ov); + p.update = update; for (String id : ids) p.want(id, update); - p.conflicts(new LinkedHashMap>()); + p.settle(new LinkedHashMap>()); return p; } + /** update --all: each mod that can't be updated now is left out (with why), the rest planned together */ + Plan planEach(List ids, Overrides ov) { + List ok = new ArrayList(); + List skipped = new ArrayList(); + for (String id : ids) { + Plan one = plan(Arrays.asList(id), true, ov); + if (one.problems.isEmpty()) { + ok.add(id); + continue; + } + Map m = new LinkedHashMap(); + m.put("id", id); + m.put("why", join(one.problems, "; ")); + if (!one.overrides.isEmpty()) m.put("overrides", one.overrides); + skipped.add(m); + } + Plan p = plan(ok, true, ov); + p.skipped.addAll(skipped); + return p; + } + + static String join(List l, String sep) { + StringBuilder b = new StringBuilder(); + for (String s : l) b.append(b.length() > 0 ? sep : "").append(s); + return b.toString(); + } + // ---- doing it: everything downloaded and checked first, then installed in order + /** downloads one step's package into dl, checks its SHA-256 and that it is what the entry says, unzips it; null, or why not */ @SuppressWarnings("unchecked") - int execute(Plan p, boolean anyCar) throws Exception { + String fetch(Http http, File dl, Step s, Map> pkgs) throws Exception { + File z = new File(dl, s.id + "-" + s.version + ".zip"); + Http.Result r = http.get(String.valueOf(s.entry.get("download")), z, (int) Packages.MAX_BYTES); + if (!r.ok()) return "can't download " + s.id + " " + s.version + ": " + r; + String sha = Sha256.hex(z), want = String.valueOf(s.entry.get("sha256")); + if (!sha.equals(want)) return "refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", the catalogue says " + want; + File u = new File(dl, s.id + "-" + s.version); + Map mj = null; + try { + Packages.unzip(z, u); + File root = Packages.root(u); + mj = Json.object(Engine.read(new File(root, "mod.json"))); + s.dir = root; + } catch (Exception x) { + mj = null; + } + z.delete(); + if (mj == null || !s.id.equals(mj.get("id")) || !s.version.equals(String.valueOf(mj.get("version")))) { + return "refused " + s.id + " " + s.version + ": the package is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")); + } + pkgs.put(s.id, mj); + e.out.add("downloaded " + s.id + " " + s.version + " (SHA-256 as the catalogue's)"); + return null; + } + + Http http(File dl) { + List why = new ArrayList(); + Http.Transport t = NativeFetch.forEngine(e, why); + if (t == null) { + e.out.add("can't download: " + why.get(0)); + return null; + } + return new Http(t, dl); + } + + int execute(Plan p) throws Exception { + for (Object o : p.skipped) { + @SuppressWarnings("unchecked") Map m = (Map) o; + e.out.add("not updated: " + m.get("id") + ": " + m.get("why")); + } if (!p.problems.isEmpty()) { for (String x : p.problems) e.out.add("can't: " + x); return 1; @@ -675,7 +1064,7 @@ int execute(Plan p, boolean anyCar) throws Exception { if (p.steps.isEmpty()) { for (String n : p.notes) e.out.add(n); e.out.add("nothing to install"); - return 0; + return p.skipped.isEmpty() ? 0 : 1; } String off = offline(); if (off != null && needsDownload(p)) { @@ -687,83 +1076,46 @@ int execute(Plan p, boolean anyCar) throws Exception { dl.mkdirs(); try { Http http = null; - // a package can require more than its entry says (an entry from before catalog.py copied - // requires): its own mod.json is the truth, so the plan is made again until nothing new turns up - Map> pkgConflicts = new LinkedHashMap>(); - for (int round = 0; ; round++) { - boolean more = false; - for (Step s : p.steps) { - if ("enable".equals(s.action) || s.zip != null) continue; - if (http == null) { - List why = new ArrayList(); - Http.Transport t = NativeFetch.forEngine(e, why); - if (t == null) { - e.out.add("can't download: " + why.get(0)); - return 1; - } - http = new Http(t, dl); - } - File z = new File(dl, s.id + "-" + s.version + ".zip"); - Http.Result r = http.get(String.valueOf(s.entry.get("download")), z, (int) Packages.MAX_BYTES); - if (!r.ok()) { - e.out.add("can't download " + s.id + " " + s.version + ": " + r + " (nothing was installed)"); - return 1; - } - String sha = Sha256.hex(z), want = String.valueOf(s.entry.get("sha256")); - if (!sha.equals(want)) { - e.out.add("refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", the catalogue says " + want - + " (nothing was installed)"); - return 1; - } - Map mj = modJson(z); - if (mj == null || !s.id.equals(mj.get("id")) || !s.version.equals(String.valueOf(mj.get("version")))) { - e.out.add("refused " + s.id + " " + s.version + ": the package is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")) - + " (nothing was installed)"); - return 1; - } - s.zip = z; - e.out.add("downloaded " + s.id + " " + s.version + " (" + z.length() + " bytes, SHA-256 as the catalogue's)"); - pkgConflicts.put(s.id, deps(mj.get("conflicts"))); - List req = deps(mj.get("requires")), known = p.requires(s.id, s.entry); - for (Version.Dep d : req) { - boolean have = false; - for (Version.Dep k : known) have |= k.id.equals(d.id) && String.valueOf(k.range).equals(String.valueOf(d.range)); - if (!have) { - if (!p.learned.containsKey(s.id)) p.learned.put(s.id, new ArrayList()); - p.learned.get(s.id).add(d); - more = true; - } - } - } - if (!more) break; - if (round >= 5) { - e.out.add("can't: the packages' requires keep changing (nothing was installed)"); + Map> pkgs = new LinkedHashMap>(); + boolean more = false; + for (Step s : p.steps) { + if ("enable".equals(s.action)) continue; + if (http == null && (http = http(dl)) == null) return 1; + String bad = fetch(http, dl, s, pkgs); + if (bad != null) { + e.out.add(bad + " (nothing was installed)"); return 1; } - // again with what the packages said; the downloads already made are kept - Plan q = new Plan(); - q.anyCar = anyCar; - q.learned.putAll(p.learned); - List wanted = new ArrayList(); - for (Step s : p.steps) if (s.because == null) wanted.add(s.id); - for (String id : wanted) q.want(id, false); - for (Step s : q.steps) { - Step old = p.planned(s.id); - if (old != null && old.version.equals(s.version)) s.zip = old.zip; - } - if (!q.problems.isEmpty()) { + more |= learn(p, s, pkgs.get(s.id)); + } + // a package can require more than its entry says (an entry from before catalog.py copied requires): + // its own mod.json is the truth. If that changes what this takes, the owner sees the new plan first. + if (more) { + Plan q = p.skipped.isEmpty() ? plan(p.wanted, p.update, p.ov) : planEach(p.wanted, p.ov); + if (!q.problems.isEmpty() || !q.sameAs().equals(p.sameAs())) { + e.out.add(q.problems.isEmpty() ? "the packages require more than the catalogue says, so this takes more steps:" + + " nothing was installed. Check the new plan and install again" : "can't, with what the packages require:"); for (String x : q.problems) e.out.add("can't: " + x); - e.out.add("(nothing was installed)"); - return 1; + if (q.problems.isEmpty()) e.out.add("(nothing was installed)"); + e.out.add(Json.write(q.toJson())); + return q.problems.isEmpty() ? PLAN_CHANGED : 1; } - p = q; } - p.conflicts(pkgConflicts); + p.settle(pkgs); if (!p.problems.isEmpty()) { for (String x : p.problems) e.out.add("can't: " + x); e.out.add("(nothing was installed)"); return 1; } + // every package checked as its install will check it (signature, author key, HMG-API, car), before the first goes in + for (Step s : p.steps) { + if ("enable".equals(s.action)) continue; + Packages.Verdict v = Packages.check(e, s.dir, String.valueOf(s.entry.get("uuid")), false, p.ov.car(s.id)); + if (v.code != 0) { + e.out.add("refused " + s.id + " " + s.version + ": " + v.reason + " (nothing was installed)"); + return v.code; + } + } for (String n : p.notes) e.out.add(n); int done = 0; for (Step s : p.steps) { @@ -775,13 +1127,16 @@ int execute(Plan p, boolean anyCar) throws Exception { } e.out.add((s.installed == null ? "installing " : "updating ") + s.id + (s.installed != null ? " " + s.installed + " ->" : "") + " " + s.version + (s.because != null ? " (" + s.because + " needs it)" : "")); - int rc = Packages.install(e, s.zip.getPath(), String.valueOf(s.entry.get("uuid")), false, anyCar); + int rc = Packages.install(e, s.dir.getPath(), String.valueOf(s.entry.get("uuid")), false, p.ov.car(s.id)); if (rc != 0) { e.out.add("stopped at " + s.id + (done > 0 ? ": the " + done + " before it are installed (not applied yet)" : ": nothing was installed")); if (done > 0) NemesisSync.run(e); writeUpdates(); return rc; } + if (s.turnOn && new File(e.data, "mods/" + s.id + "/.disabled").delete()) { + e.out.add("turned on " + s.id + " (" + s.because + " needs it)"); + } done++; } NemesisSync.run(e); @@ -840,31 +1195,61 @@ static Map modJson(File zip) { } } - /** HMG-API itself: its update zip, checked against SHA256SUMS, then its own installer (UsbUpdates: the release key) */ + /** installed mods (turned on) whose "hmgapi" range the given HMG-API version doesn't meet */ + List outgrown(String version) { + List out = new ArrayList(); + File[] ds = new File(e.data, "mods").listFiles(); + for (File d : ds == null ? new File[0] : ds) { + File mj = new File(d, "mod.json"); + if (!mj.isFile() || new File(d, ".disabled").exists()) continue; + try { + Map j = Json.object(Engine.read(mj)); + Object need = j.get("hmgapi"); + if (need != null && !Version.meetsHmgapi(version, String.valueOf(need))) { + out.add(d.getName() + " " + j.get("version") + " (needs HMG-API " + need + ")"); + } + } catch (Exception x) { + // a broken mod.json or range: the engine's plan says so + } + } + return out; + } + + /** + * HMG-API itself: its update zip, checked against SHA256SUMS, then its own installer (UsbUpdates: the + * release key). Refused while a mod that's on wouldn't take the new version (applies would stop on it), + * unless the owner says so (--force). + */ @SuppressWarnings("unchecked") - int updateHmgApi() throws Exception { + int updateHmgApi(boolean force) throws Exception { Map h = hmgapiOffer(); if (h == null) { e.out.add("HMG-API " + installedHmgApi() + " is the newest release offered here (engine updates --refresh checks again)"); return 0; } + List wont = outgrown(String.valueOf(h.get("version"))); + if (!wont.isEmpty()) { + String list = join(wont, ", "); + if (!force) { + e.out.add("not yet: with HMG-API " + h.get("version") + " these mods wouldn't load, and applying stops until they're updated or" + + " turned off: " + list + ". Update or turn them off first, or update anyway (engine update hmgapi --force)"); + return 1; + } + e.out.add("WARNING: with HMG-API " + h.get("version") + " these mods won't load until they're updated or turned off: " + list); + } String off = offline(); if (off != null) { e.out.add("can't download: " + off); return 1; } - List why = new ArrayList(); - Http.Transport t = NativeFetch.forEngine(e, why); - if (t == null) { - e.out.add("can't download: " + why.get(0)); - return 1; - } File dl = new File(dir, "downloads"); Engine.rm(dl); dl.mkdirs(); try { + Http http = http(dl); + if (http == null) return 1; File z = new File(dl, "hmgapi-" + h.get("version") + "-update.zip"); - Http.Result r = new Http(t, dl).get(String.valueOf(h.get("download")), z, 128 << 20); + Http.Result r = http.get(String.valueOf(h.get("download")), z, 128 << 20); if (!r.ok()) { e.out.add("can't download HMG-API " + h.get("version") + ": " + r); return 1; @@ -881,29 +1266,55 @@ int updateHmgApi() throws Exception { } } + // ---- the automatic check, and staged updates + + long checkGapMs() { + String t = e.host ? Engine.env("HMGAPI_TEST_CHECK_GAP", null) : null; + return (t != null ? Long.parseLong(t) : CHECK_GAP_S) * 1000L; + } + /** - * wifi.sh, when home Wi-Fi comes up: refresh, write updates.json, and stage the mods' updates if - * the owner allowed it (hmgapid allow auto_stage_updates on). HMG-API itself is never updated - * here. What happened goes to logs/hmgapi/updates.log. + * wifi.sh, when home Wi-Fi comes up: refresh (at most every 6 hours), write updates.json, and stage + * the mods' pure updates if the owner allowed it (hmgapid allow auto_stage_updates on). HMG-API itself + * is never updated here. What happened goes to logs/hmgapi/updates.log. */ @SuppressWarnings("unchecked") int updateCheck() throws Exception { List log = new ArrayList(); - String err = refresh(); - Map u = updates(); - if (err != null) log.add("check: " + err); - else log.add("checked: " + u.get("count") + " update(s)" + (u.get("hmgapi") != null ? " (HMG-API " + ((Map) u.get("hmgapi")).get("version") + " among them)" : "")); - int rc = 0; - if (err == null && new File(e.data, "settings/allow/auto_stage_updates").exists() && !((List) u.get("mods")).isEmpty()) { - List ids = new ArrayList(); - for (Object o : (List) u.get("mods")) ids.add(String.valueOf(((Map) o).get("id"))); - if (e.journalFile.exists()) { - log.add("not staged: an earlier apply isn't finished"); - } else { - int before = e.out.size(); - rc = execute(plan(ids, true, false), false); - log.addAll(e.out.subList(before, e.out.size())); - log.add(rc == 0 ? "staged: " + ids + " (the owner applies them)" : "not staged (" + rc + ")"); + File lastFile = new File(dir, "last-check"); + long now = System.currentTimeMillis(), last = checked(); + try { + if (lastFile.isFile()) last = Math.max(last, Long.parseLong(Engine.read(lastFile).trim())); + } catch (Exception x) { + // unreadable: as if never + } + String err = null; + if (now >= last && now - last < checkGapMs()) { + log.add("not checked: the last check was " + (now - last) / 60000 + " min ago (at most one every " + checkGapMs() / 3600000 + + " hours: GitHub allows 60 requests an hour)"); + } else { + if (offline() == null) writeWhole(lastFile, String.valueOf(now), false); // an attempt that reached for GitHub + err = refresh(); + Map u = updates(); + if (err != null) log.add("check: " + err); + else log.add("checked: " + u.get("count") + " update(s)" + (u.get("hmgapi") != null ? " (HMG-API " + ((Map) u.get("hmgapi")).get("version") + " among them)" : "")); + if (err == null && new File(e.data, "settings/allow/auto_stage_updates").exists() && !((List) u.get("mods")).isEmpty()) { + if (e.journalFile.exists()) { + log.add("not staged: an earlier apply isn't finished"); + } else { + for (Object o : (List) u.get("mods")) { + Map m = (Map) o; + if (Boolean.TRUE.equals(m.get("staged"))) continue; + String id = String.valueOf(m.get("id")); + int before = e.out.size(); + String why = stage(id); + log.addAll(e.out.subList(before, e.out.size())); + while (e.out.size() > before) e.out.remove(e.out.size() - 1); + log.add(why == null ? "staged: " + id + " " + m.get("installed") + " -> " + m.get("version") + " (it goes in when you apply)" + : "not staged: " + id + ": " + why); + } + writeUpdates(); + } } } File lf = new File(e.data, "logs/hmgapi/updates.log"); @@ -915,6 +1326,152 @@ int updateCheck() throws Exception { for (String l : log) b.append(when).append(' ').append(l).append('\n'); Engine.write(lf, b.toString()); e.out.addAll(log.subList(0, Math.min(1, log.size()))); - return err != null ? 1 : rc; + return err != null ? 1 : 0; // a mod not staged is in the log, not a failed check + } + + /** why a plan isn't a pure update of id (that one step, nothing else installed or turned on), or null */ + static String pure(Plan p, String id) { + if (!p.problems.isEmpty()) return join(p.problems, "; "); + List more = new ArrayList(); + for (Step s : p.steps) { + if (s.id.equals(id) && "update".equals(s.action) && !s.turnOn) continue; + more.add(("enable".equals(s.action) || s.turnOn ? "turning on " : "install".equals(s.action) ? "installing " : "updating ") + s.id + + ("enable".equals(s.action) ? "" : " " + s.version)); + } + if (p.steps.isEmpty()) return "nothing to update"; + if (!more.isEmpty()) return "it takes " + join(more, ", ") + " too: update it yourself (Updates in the Mods tab)"; + return null; + } + + /** + * The automatic check's staging of one mod: only a pure update, signed with the installed key, into + * /data/hmgapi/pending/ (engine apply puts it in place). null when staged, else why not. + */ + String stage(String id) throws Exception { + Plan p = plan(Arrays.asList(id), true, null); + String why = pure(p, id); + if (why != null) return why; + Step s = p.steps.get(0); + String have = Packages.installedUuid(new File(e.data, "mods/" + id)); + if (have == null || !have.equalsIgnoreCase(String.valueOf(s.entry.get("uuid")))) { + return "the catalogue names another author key than the installed " + id + "'s: update it yourself"; + } + String off = offline(); + if (off != null) return off; + File dl = new File(dir, "downloads"); + Engine.rm(dl); + dl.mkdirs(); + try { + Http http = http(dl); + if (http == null) return "can't download"; + Map> pkgs = new LinkedHashMap>(); + String bad = fetch(http, dl, s, pkgs); + if (bad != null) return bad; + if (learn(p, s, pkgs.get(id))) { + Plan q = plan(Arrays.asList(id), true, null); + why = pure(q, id); + if (why != null) return why + " (as its package says)"; + } + p.settle(pkgs); + if (!p.problems.isEmpty()) return join(p.problems, "; "); + Packages.Verdict v = Packages.check(e, s.dir, have, false, false); + if (v.code != 0) return v.reason; + File pend = new File(e.data, "pending/" + id); + Engine.rm(pend); + pend.getParentFile().mkdirs(); + if (!s.dir.renameTo(pend)) throw new IOException("can't put the staged " + id + " in " + pend); + return null; + } finally { + Engine.rm(dl); + } + } + + /** the version staged for id (pending/), or null */ + static String stagedVersion(Engine e, String id) { + return versionIn(new File(e.data, "pending/" + id)); + } + + static String installedVersion(Engine e, String id) { + return versionIn(new File(e.data, "mods/" + id)); + } + + static String versionIn(File d) { + File mj = new File(d, "mod.json"); + try { + return mj.isFile() ? String.valueOf(Json.object(Engine.read(mj)).get("version")) : null; + } catch (Exception x) { + return null; + } + } + + /** engine plan: the staged updates, which go in at apply (their own changes are planned then) */ + static void stagedReport(Engine e) { + File[] ps = new File(e.data, "pending").listFiles(); + for (File p : ps == null ? new File[0] : ps) { + String id = p.getName(), want = stagedVersion(e, id), have = installedVersion(e, id); + if (!id.matches(ID) || want == null || have == null) continue; + e.out.add("update " + id + " " + have + " -> " + want + " (staged by the automatic check: it goes in when you apply, and its changes" + + " are worked out then)"); + } + } + + /** + * engine apply, before it plans: each staged update checked again (the installed key, this car, + * this HMG-API) and put in place, the version it replaces kept in /data/hmgapi/previous/. + * Returns the ids put in place (stagedBack undoes them if the apply doesn't go ahead). + */ + static List stagedIn(Engine e) throws Exception { + List done = new ArrayList(); + File[] ps = new File(e.data, "pending").listFiles(); + if (ps != null) Arrays.sort(ps); + for (File p : ps == null ? new File[0] : ps) { + String id = p.getName(); + if (!id.matches(ID) || !p.isDirectory()) { + Engine.rm(p); + continue; + } + File inst = new File(e.data, "mods/" + id); + String want = stagedVersion(e, id), have = installedVersion(e, id), why = null; + if (want == null) why = "it isn't a mod"; + else if (have == null) why = id + " was removed since"; + else if (!"update".equals(status(have, want))) why = "the installed " + have + " is as new"; + else { + Packages.Verdict v = Packages.check(e, p, Packages.installedUuid(inst), false, false); + if (v.code != 0) why = v.reason; + } + if (why != null) { + e.out.add("dropped the staged " + id + (want != null ? " " + want : "") + ": " + why); + Engine.rm(p); + continue; + } + File prev = new File(e.data, "previous/" + id); + Engine.rm(prev); + prev.getParentFile().mkdirs(); + boolean off = new File(inst, ".disabled").exists(); + if (!inst.renameTo(prev)) throw new IOException("can't move the installed " + id + " aside"); + if (!p.renameTo(inst)) { + prev.renameTo(inst); + throw new IOException("can't put the staged " + id + " in place"); + } + if (off) new File(inst, ".disabled").createNewFile(); + e.chmodTree(inst); + e.out.add("update " + id + " " + have + " -> " + want + " (staged by the automatic check; " + have + " kept in /data/hmgapi/previous/" + id + ")"); + done.add(id); + } + return done; + } + + /** an apply that didn't go ahead: the staged updates back to staged, the versions they replaced back in place */ + static void stagedBack(Engine e, List ids) { + for (String id : ids) { + File inst = new File(e.data, "mods/" + id), prev = new File(e.data, "previous/" + id), pend = new File(e.data, "pending/" + id); + Engine.rm(pend); + if (!prev.isDirectory() || !inst.renameTo(pend) || !prev.renameTo(inst)) { + e.out.add("couldn't put " + id + "'s previous version back: the staged one stays installed"); + continue; + } + new File(pend, ".disabled").delete(); + } + if (!ids.isEmpty()) e.out.add("the staged updates (" + join(ids, ", ") + ") stay staged until an apply goes through"); } } diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index b56d62e3..44805b89 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -447,7 +447,16 @@ int run(String[] args) throws Exception { out.add("usage: engine plan | apply [--trial] | keep | restore | status | recover | firmware-reset | install | remove | nemesis-sync | map | map-car [--local [--if-needed] | --write | --forget] | verify-map | report [--usb] | usb-scan | update-hmgapi | publish-state | apps"); return 2; } - Plan p = plan(restoreAll, force); + // updates the automatic check staged (pending/): in place right before an apply plans, never earlier + List staged = "apply".equals(cmd) ? Catalog.stagedIn(this) : new ArrayList(); + if ("plan".equals(cmd)) Catalog.stagedReport(this); + Plan p; + try { + p = plan(restoreAll, force); + } catch (Exception x) { + Catalog.stagedBack(this, staged); + throw x; + } p.report(this); if (!restoreAll) { out.addAll(hookPlan().report()); @@ -460,6 +469,7 @@ int run(String[] args) throws Exception { if (!problems.isEmpty()) { out.add("nothing changed: " + problems.size() + " problem(s)"); for (String s : problems) out.add(" " + s); + Catalog.stagedBack(this, staged); return 3; } if ("plan".equals(cmd)) return 0; diff --git a/core/runtime/java/hmgapi/engine/Packages.java b/core/runtime/java/hmgapi/engine/Packages.java index 12e7acc4..256cc5b2 100644 --- a/core/runtime/java/hmgapi/engine/Packages.java +++ b/core/runtime/java/hmgapi/engine/Packages.java @@ -66,6 +66,7 @@ static int install(Engine e, String path, String uuid, boolean force, boolean an } if (wasOff) new File(installed, ".disabled").createNewFile(); Engine.rm(prev); + Engine.rm(new File(e.data, "pending/" + v.id)); // an update staged by the automatic check: this one replaces it if (anyCar && v.otherCar != null) ignoreSystem(e, v.id, true); e.chmodTree(installed); e.out.add("installed " + v.id + " " + v.version + (v.uuid != null ? " (author key " + v.uuid + ")" : " (unsigned)") @@ -73,6 +74,7 @@ static int install(Engine e, String path, String uuid, boolean force, boolean an scriptWarnings(e, installed); e.out.add("run `engine apply` (Apply changes in the app) to use it"); LiveState.publish(e); + Catalog.updatesChanged(e); return 0; } finally { Engine.rm(stage); @@ -210,11 +212,13 @@ static int remove(Engine e, String id) throws Exception { return 1; } Engine.rm(installed); + Engine.rm(new File(e.data, "pending/" + id)); File cache = new File(e.data, "dalvik-cache"); DexCacheCleanup.removeObsoleteShared(cache); DexCacheCleanup.removeMod(cache, id); ignoreSystem(e, id, false); LiveState.publish(e); + Catalog.updatesChanged(e); e.out.add("removed " + id + " (its settings stay in /data/hmgapi/settings); run `engine apply` to put its files back to stock"); return 0; } diff --git a/core/runtime/java/hmgapi/engine/Version.java b/core/runtime/java/hmgapi/engine/Version.java index 40d67794..44dbbc05 100644 --- a/core/runtime/java/hmgapi/engine/Version.java +++ b/core/runtime/java/hmgapi/engine/Version.java @@ -87,6 +87,16 @@ public static boolean satisfies(String v, String range) { return true; } + /** why a range can't be read ("^x.y"), or null when it can */ + public static String rangeError(String range) { + try { + satisfies("0.0.0", range); + return null; + } catch (IllegalArgumentException x) { + return "\"" + range + "\" isn't a version range (" + x.getMessage() + ")"; + } + } + /** * Does HMG-API version core meet a mod's "hmgapi" range? A range of final versions * is checked against the release a pre-release leads to (1.1.0-rc.1 meets ">=1.1.0", diff --git a/tools/catalog-test.sh b/tools/catalog-test.sh index fcf8ae76..106cdb8c 100755 --- a/tools/catalog-test.sh +++ b/tools/catalog-test.sh @@ -27,20 +27,20 @@ pkg() { rm -rf $T/$1; cp -r mods/examples/hello $T/$1 python3 - $T/$1/mod.json $2 <<'P' import json, os, sys -m = json.load(open(sys.argv[1])); m['version'] = sys.argv[2]; m['authors'] = ['Test Author']; m['repo'] = 'https://example.org/hello' +m = json.load(open(sys.argv[1])); m['version'] = sys.argv[2]; m['authors'] = ['Test Author']; m['repo'] = 'https://github.com/example/hello' if os.environ.get('DESC'): m['description'] = os.environ['DESC'] json.dump(m, open(sys.argv[1], 'w')) P S sign $T/$1 $3 >/dev/null (cd $T/$1 && rm -f $4 && zip -qr $4 .) } -DL=https://example.org/hello/releases/hello.zip +DL=https://github.com/example/hello/releases/hello.zip J() { python3 -c "import json,sys; f=sys.argv[1]; d=json.load(open(f)); exec(sys.argv[2]); json.dump(d,open(f,'w'))" "$@"; } pkg h1 1.0.0 $T/a.key $T/h1.zip C add $T/h1.zip --download $DL; check "add" 0 $rc; has "says what" "hello 1.0.0, author key $UA (added to maps/authors.json as Test Author)" "$out" check "entry's sha256" "$(sha256sum $T/h1.zip | cut -d' ' -f1)" "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["sha256"])' $R/catalog/hello.json)" -check "repo from mod.json" "https://example.org/hello" "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["repo"])' $R/catalog/hello.json)" +check "repo from mod.json" "https://github.com/example/hello" "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["repo"])' $R/catalog/hello.json)" has "author listed" "\"$UA\"" "$(cat $R/maps/authors.json)" C check --base HEAD; check "check a new entry" 0 $rc G add -A && G -c user.name=t -c user.email=t@t commit -qm hello @@ -68,7 +68,7 @@ G checkout -q -- . cp $T/h1.zip $T/dl/hello.zip # fetch --list (tools/release-mods.txt): ids, and a HMG-API pre-release's pins of mod pre-releases -PB=https://example.org/hello/releases/download/v1.1.0-beta.1 +PB=https://github.com/example/hello/releases/download/v1.1.0-beta.1 pkg hp 1.1.0-beta.1 $T/a.key $T/dl/hello-1.1.0-beta.1.zip SP=$(sha256sum $T/dl/hello-1.1.0-beta.1.zip | cut -d' ' -f1) L() { printf '# test\n%s\n' "$@" > $T/list.txt; } @@ -88,7 +88,7 @@ L "hello 1.1.0 $PB/hello-1.1.0-beta.1.zip $SP" F fetch $T/pl4 --list $T/list.txt; check "pin: a final version refused" 1 $rc; has "says why" "a pin outside the catalogue is for a pre-release" "$out" L "hello 1.0.0-beta.1 $PB/hello-1.1.0-beta.1.zip $SP" F fetch $T/pl4 --list $T/list.txt; check "pin: not newer than the entry refused" 1 $rc; has "says why" "not newer than the catalogue's 1.0.0" "$out" -L "hello 1.1.0-beta.1 https://example.org/hello-fork/releases/download/v1/hello-1.1.0-beta.1.zip $SP" +L "hello 1.1.0-beta.1 https://github.com/example/hello-fork/releases/download/v1/hello-1.1.0-beta.1.zip $SP" F fetch $T/pl4 --list $T/list.txt; check "pin: a download outside the entry's repo releases refused" 1 $rc; has "says why" "a release of the mod's own repo" "$out" L "hello 1.1.0-beta.1 $PB/hello-1.1.0-beta.1.zip $(sha256sum < $T/h1.zip | cut -d' ' -f1)" F fetch $T/pl4 --list $T/list.txt; check "pin: other bytes than the pin's refused" 1 $rc; has "says why" "tools/release-mods.txt: hello: the download's SHA-256 is" "$out" @@ -105,8 +105,8 @@ check "... nothing kept" "" "$(ls $T/pl4 2>/dev/null)" G checkout -q -- . pkg h2 1.1.0 $T/a.key $T/h2.zip -C add $T/h2.zip --download $DL --repo https://example.org/hello/sub; check "update" 0 $rc -check "author's repo not repeated under its root" 1 "$(grep -c example.org $R/maps/authors.json)" +C add $T/h2.zip --download $DL --repo https://github.com/example/hello/sub; check "update" 0 $rc +check "author's repo not repeated under its root" 1 "$(grep -c github.com/example $R/maps/authors.json)" C check --base HEAD; check "check an update" 0 $rc G checkout -q -- . @@ -145,8 +145,50 @@ cp $R/catalog/hello.json $R/catalog/other.json C check; check "file name is the id" 1 $rc rm $R/catalog/other.json +# what the head unit couldn't use: a download off GitHub (Http only goes there), a range it can't read +C add $T/h1.zip --download https://example.org/hello/releases/hello.zip; check "add: a download off GitHub refused" 1 $rc +has "says why" "the head unit only downloads from GitHub" "$out" +J $R/catalog/hello.json "d['download']='https://example.org/hello.zip'" +C check; check "check: a download off GitHub refused" 1 $rc; has "says why" '"download" is on example.org' "$out" +G checkout -q -- . +J $R/catalog/hello.json "d['requires']=['lib ^x.y', {'id': 'other', 'version': '>=1 =1 =1.0.0 <2', {'id': 'x', 'version': '~1.1.0-rc.1'}, 'plain']; d['conflicts']=['z *']; d['hmgapi']='>=1.1.0-rc.1'" +C check; check "check: readable ranges" 0 $rc +J $R/catalog/hello.json "d['hmgapi']='newest'" +C check; check "check: an unreadable hmgapi range refused" 1 $rc; has "says why" '"hmgapi": "newest" isn'"'"'t a version range' "$out" +G checkout -q -- . + +# "wifi": {"hotspot": true} copied, so the head unit judges "system" as the install will +python3 - $T/h1/mod.json <<'P' +import json, sys +m = json.load(open(sys.argv[1])); m['wifi'] = {'hotspot': True}; json.dump(m, open(sys.argv[1], 'w')) +P +rm -f $T/h1/extra.txt; S sign $T/h1 $T/a.key >/dev/null; (cd $T/h1 && rm -f $T/hw.zip && zip -qr $T/hw.zip .) +C add $T/hw.zip --download $DL; check "add: a hotspot mod" 0 $rc +check "... its wifi.hotspot in the entry" "{'hotspot': True}" "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("wifi"))' $R/catalog/hello.json)" +J $R/catalog/hello.json "d['wifi']={'hotspot': 'yes'}" +C check; check "check: another wifi shape refused" 1 $rc +G checkout -q -- . + +# index.json, once the repo keeps one: add writes it again, check refuses a stale one +C index; check "index" 0 $rc +G add -A && G -c user.name=t -c user.email=t@t commit -qm index +C check; check "check: the index is the entries" 0 $rc +J $R/catalog/hello.json "d['description']='changed'" +C check; check "check: an index that isn't the entries refused" 1 $rc; has "says why" "catalog/index.json isn't the entries" "$out" +G checkout -q -- . +C add $T/h2.zip --download $DL; check "add with an index" 0 $rc; has "... written again" "catalog/index.json: written again" "$out" +check "... it has the new version" 1.1.0 "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["mods"][0]["version"])' $R/catalog/index.json)" +C check; check "... and check passes" 0 $rc +G checkout -q -- . +G rm -q catalog/index.json && G -c user.name=t -c user.email=t@t commit -qm "no index" + # bump (the auto-merge workflow): head against base, downloads served from $T/dl -BD=https://example.org/hello/releases/download/v1.1.0/hello.zip +BD=https://github.com/example/hello/releases/download/v1.1.0/hello.zip B() { G -c user.name=t -c user.email=t@t commit -qam "$1"; F bump --base main --head HEAD; } G branch -q -M main bump_entry() { # [python edit]: the entry pointing at that zip as $BD @@ -162,7 +204,7 @@ G checkout -q main; G checkout -qb pr3; bump_entry $T/h2.zip "d['description']=' B desc; check "bump: a description not the package's refused" 1 $rc; has "says why" "the description isn't the package's" "$out" G checkout -q main; G checkout -qb pr4; DESC='Says hi, louder' pkg hd 1.1.0 $T/a.key $T/hd.zip; bump_entry $T/hd.zip "d['description']='Says hi, louder'" B desc-ok; check "bump: the package's description" 0 $rc -G checkout -q main; G checkout -qb pr5; bump_entry $T/h2.zip "d['download']='https://example.org/fork/releases/download/v1.1.0/hello.zip'" +G checkout -q main; G checkout -qb pr5; bump_entry $T/h2.zip "d['download']='https://github.com/example/fork/releases/download/v1.1.0/hello.zip'" B fork; check "bump: a download outside the repo's releases refused" 1 $rc; has "says why" "a release of the mod's own repo" "$out" G checkout -q main; G checkout -qb pr6; pkg hb2 1.1.0 $T/b.key $T/hb2.zip; bump_entry $T/hb2.zip B otherkey; check "bump: signed by another key refused" 1 $rc diff --git a/tools/catalog.py b/tools/catalog.py index 80261ad8..72ceb6b6 100755 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -26,7 +26,8 @@ tools/catalog.py wiki the Community mods page tools/catalog.py index [] - catalog/index.json: every entry in one file, for the head unit's catalogue (one request) + catalog/index.json: every entry in one file, for the head unit's catalogue (one request); + once the repo has one, add writes it again and check refuses one that isn't the entries """ import argparse, hashlib, json, os, re, shutil, subprocess, sys, tempfile, urllib.request, zipfile @@ -41,7 +42,14 @@ FINAL = re.compile(r'^\d+\.\d+\.\d+$') # what an entry's "version" is: no pre-releases (docs/releasing.md) HTTPS = re.compile(r'^https://[A-Za-z0-9.-]+(:\d+)?/[^\s<>()\[\]"\']*$') FIELDS = {'id', 'name', 'description', 'authors', 'license', 'uuid', 'version', 'repo', 'download', 'sha256', 'system', 'hmgapi', - 'requires', 'conflicts'} # requires/conflicts: as the package's mod.json (HMG-API's catalogue installs requires first) + 'requires', 'conflicts', 'wifi'} # requires/conflicts: as the package's mod.json (HMG-API's catalogue installs requires first); +# wifi: {"hotspot": true} as mod.json (a chip the unit never powers will do, SystemCheck) +# the only hosts the head unit downloads from (Http.HOSTS): a download anywhere else could never install +GITHUB = {'github.com', 'api.github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com', + 'release-assets.githubusercontent.com', 'codeload.github.com'} +# a version range as the engine reads it (Version.one): each part an operator and a version, or "" / "*" +RANGE_PART = re.compile(r'^(>=|<=|>|<|=|\^|~)?v?\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$') +INDEX = os.path.join(CATALOG, 'index.json') NEEDED = ['id', 'name', 'description', 'authors', 'uuid', 'version', 'repo', 'download', 'sha256'] @@ -148,6 +156,38 @@ def fetch(url, dest): f.write(b) +def range_error(r): + """why the engine couldn't read version range r, or None""" + if not isinstance(r, str): + return f'{r!r} isn\'t text' + if r.strip() in ('', '*'): + return None + bad = [x for x in r.split() if not RANGE_PART.match(x)] + return f'"{r}" isn\'t a version range ({", ".join(bad)})' if bad else None + + +def dep_error(d): + """why a requires/conflicts item can't be read, or None""" + if isinstance(d, str): + mid, _, r = d.strip().partition(' ') + elif isinstance(d, dict): + mid, r = str(d.get('id', '')), d.get('version') + else: + return f'{d!r} isn\'t " [range]" or {{"id": ..., "version": ...}}' + if not ID.match(mid): + return f'{mid!r} isn\'t a mod id' + return range_error(r) if r not in (None, '') else None + + +def host(url): + m = re.match(r'^https://([^/:]+)', str(url)) + return m[1].lower() if m else '' + + +def index_of(es): + return {'mods': [es[n] for n in sorted(es)]} + + def entries(): if not os.path.isdir(CATALOG): return {} @@ -187,6 +227,8 @@ def cmd_add(a): for k in ('requires', 'conflicts'): # what the head unit's catalogue resolves before downloading if mod.get(k): e[k] = mod[k] + if isinstance(mod.get('wifi'), dict) and mod['wifi'].get('hotspot') is True: + e['wifi'] = {'hotspot': True} # so the head unit judges "system" as the install will (an unpowered chip will do) if not e['license']: del e['license'] os.makedirs(CATALOG, exist_ok=True) @@ -201,9 +243,12 @@ def cmd_add(a): listed['repos'].append(repo) save(AUTHORS, au) print(f'catalog/{mid}.json: {mid} {ver}, author key {uuid}' + ('' if listed else f' (added to maps/authors.json as {authors[0]})')) - problems = check_all(entries(), au) + problems = check_all(entries(), au, index=False) if problems: die('\n'.join(problems)) + if os.path.exists(INDEX): # the repo keeps one: it stays the entries + save(INDEX, index_of(entries())) + print('catalog/index.json: written again') # ---- check @@ -235,6 +280,8 @@ def check_entry(name, e, authors): for k in ('repo', 'download'): if e.get(k) and not HTTPS.match(str(e[k])): say(f'"{k}" isn\'t an https:// link') + if e.get('download') and HTTPS.match(str(e['download'])) and host(e['download']) not in GITHUB: + say(f'"download" is on {host(e["download"])}: the head unit only downloads from GitHub ({", ".join(sorted(GITHUB))})') if e.get('sha256') and not re.match(r'^[0-9a-f]{64}$', str(e['sha256'])): say('"sha256" isn\'t 64 lowercase hex digits') if not isinstance(e.get('authors', []), list) or not all(isinstance(x, str) and x for x in e.get('authors', [])): @@ -243,13 +290,20 @@ def check_entry(name, e, authors): if k in e and (not isinstance(e[k], str) or '\n' in e[k]): say(f'"{k}" is one line of text') for k in ('requires', 'conflicts'): - if k in e and not (isinstance(e[k], list) and all( - (isinstance(d, str) and ID.match(d.split(' ')[0])) or (isinstance(d, dict) and ID.match(str(d.get('id', '')))) for d in e[k])): + if k in e and not isinstance(e[k], list): say(f'"{k}" is a list of " [range]" or {{"id": ..., "version": ...}}, as in mod.json') + for d in e.get(k) or [] if isinstance(e.get(k), list) else []: + why = dep_error(d) + if why: + say(f'"{k}": {why}') + if 'hmgapi' in e and range_error(e['hmgapi']): + say(f'"hmgapi": {range_error(e["hmgapi"])}') + if 'wifi' in e and e['wifi'] != {'hotspot': True}: + say('"wifi" is {"hotspot": true}, as in mod.json, or left out') return p -def check_all(es, au): +def check_all(es, au, index=True): authors = au.get('authors', {}) p = [] for uuid, a in authors.items(): @@ -262,6 +316,8 @@ def check_all(es, au): p.append(f'maps/authors.json: {uuid}: {r!r} isn\'t an https:// link') for name, e in es.items(): p += check_entry(name, e, authors) + if index and os.path.exists(INDEX) and load(INDEX) != index_of(es): + p.append('catalog/index.json isn\'t the entries: write it again (tools/catalog.py index)') return p @@ -321,7 +377,7 @@ def cmd_check(a): print(f'ok {len(es)} catalogue entries, {len(au.get("authors", {}))} authors') -BUMP = {'version', 'download', 'sha256', 'description', 'requires', 'conflicts'} # what a version bump may change +BUMP = {'version', 'download', 'sha256', 'description', 'requires', 'conflicts', 'wifi'} # what a version bump may change def cmd_bump(a): @@ -334,6 +390,15 @@ def cmd_bump(a): if r.returncode != 0: die(f'git diff {a.base}...{a.head}: {r.stderr.strip()}') files = r.stdout.split() + if 'catalog/index.json' in files and len(files) == 2: # the repo's index, written again with the bump: it must be just that + head = {} + lt = subprocess.run(['git', '-C', REPO, 'ls-tree', '--name-only', a.head, 'catalog/'], capture_output=True, text=True) + for f in lt.stdout.split(): + if f.endswith('.json') and f != 'catalog/index.json': + head[os.path.basename(f)[:-5]] = git_show(a.head, f) + if git_show(a.head, 'catalog/index.json') != index_of(head): + no.append('catalog/index.json isn\'t the entries') + files.remove('catalog/index.json') m = re.fullmatch(r'catalog/([a-z0-9][a-z0-9-]{0,63})\.json', files[0]) if len(files) == 1 else None if not m: no.append(f'changes {len(files)} files ({", ".join(files[:5])}), not one catalogue entry') @@ -362,10 +427,12 @@ def cmd_bump(a): z, why = download(n, new, work) if why: no.append(why) - elif changed & {'description', 'requires', 'conflicts'}: + elif changed & {'description', 'requires', 'conflicts', 'wifi'}: pm = load(os.path.join(unpack(z, os.path.join(work, 'mod')), 'mod.json')) if 'description' in changed and pm.get('description', '') != new['description']: no.append(f'{files[0]}: the description isn\'t the package\'s mod.json description') + if 'wifi' in changed and (new.get('wifi') or None) != ({'hotspot': True} if (pm.get('wifi') or {}).get('hotspot') is True else None): + no.append(f'{files[0]}: "wifi" isn\'t the package\'s mod.json "wifi.hotspot"') for k in ('requires', 'conflicts'): if k in changed and (pm.get(k) or None) != (new.get(k) or None): no.append(f'{files[0]}: "{k}" isn\'t the package\'s mod.json "{k}"') @@ -503,11 +570,11 @@ def cmd_index(a): """catalog/index.json: every entry in one file, so a head unit fetches the catalogue in one request (without it, HMG-API asks GitHub's API for the folder's listing, then each entry)""" es = entries() - p = check_all(es, load(AUTHORS)) + p = check_all(es, load(AUTHORS), index=False) if p: die('\n'.join(p)) - out = a.out or os.path.join(CATALOG, 'index.json') - save(out, {'mods': [es[n] for n in sorted(es)]}) + out = a.out or INDEX + save(out, index_of(es)) print(f'{os.path.relpath(out, REPO) if out.startswith(REPO) else out}: {len(es)} mods') @@ -571,6 +638,8 @@ def main(): a = ap.parse_args() if a.cmd == 'add' and not HTTPS.match(a.download): die('--download is an https:// link') + if a.cmd == 'add' and host(a.download) not in GITHUB: + die(f'--download is on {host(a.download)}: the head unit only downloads from GitHub ({", ".join(sorted(GITHUB))})') if a.cmd == 'add' and a.repo and not HTTPS.match(a.repo): die('--repo is an https:// link') {'add': cmd_add, 'check': cmd_check, 'bump': cmd_bump, 'fetch': cmd_fetch, 'wiki': cmd_wiki, 'index': cmd_index}[a.cmd](a) From b175f7f56b181db9af9d4358a584b0dade1fd7f3 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:30:31 -0500 Subject: [PATCH 03/10] Catalogue: keep HMG-API's release notes for the app (no browser needed) Co-Authored-By: Claude Opus 5.5 --- core/runtime/catalog-test.sh | 3 ++- core/runtime/java/hmgapi/engine/Catalog.java | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index 223f7183..af0e9d95 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -224,7 +224,7 @@ rm "$D/settings/allow/auto_stage_updates" # ---- HMG-API's own release cat > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" <<'J' [{"tag_name": "v9.0.0", "draft": true, "prerelease": false, "assets": []}, - {"tag_name": "v1.1.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v1.1.0", + {"tag_name": "v1.1.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v1.1.0", "body": "What's new in 1.1.0", "assets": [{"name": "hmgapi-1.1.0-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip"}, {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS"}]}, {"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}] @@ -235,6 +235,7 @@ printf '%s hmgapi-1.1.0-update.zip\n' "$(printf '%064d' 0)" > $W/github.com/Ope eng updates --refresh check "HMG-API's newer release offered (not the draft)" 1.1.0 "$(j 'd["hmgapi"]["version"]')" check "... counted" 1 "$(j 'd["count"]')" +check "... with its release notes, for the app" "What's new in 1.1.0" "$(j 'd["hmgapi"]["notes"]')" eng update hmgapi has "a release that isn't its SHA256SUMS: refused" "refused HMG-API 1.1.0: the download's SHA-256 is" "$out" echo '[{"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}]' > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index 8e5679c9..cfdb4588 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -423,6 +423,10 @@ Map latestRelease(Http http, File tmp) throws Exception { best.put("download", zip); best.put("sums", sums); best.put("page", String.valueOf(rel.get("html_url"))); + String body = rel.get("body") instanceof String ? ((String) rel.get("body")).trim() : ""; // the release notes, for the app + if (body.length() > 6000) body = body.substring(0, 6000) + "\n…"; + if (!body.isEmpty()) best.put("notes", body); + else best.remove("notes"); bv = v; } if (best == null) return null; From 67ee0a2c3b4a566c0b45e98610a33bb4df46c60d Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sat, 28 Nov 2026 09:17:34 -0500 Subject: [PATCH 04/10] Catalogue: staged updates back in pending/ when the apply fails stagedIn puts them in mods/ right before an apply plans, and they went back only when the plan was refused. An apply that fails part-way (an exception, the files rolled back or left for recover) left them in mods/, where their code loads at the next boot, on /system files built for the versions before them. Found combining the open PRs: with #433's gear check and #434's in-run rollback there are more such paths; whichever lands after this puts them back there too. Co-Authored-By: Claude Opus 5.5 --- core/runtime/java/hmgapi/engine/Engine.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 44805b89..551703f9 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -478,7 +478,14 @@ int run(String[] args) throws Exception { if ("apply".equals(cmd)) LiveState.publish(this); // a switch with no file change still reaches running apps return 0; } - apply(p, trial); + // a staged update stays in mods/ only if the apply that takes it goes through: its code loads + // from there at boot, and must never run on the /system files of the version before it + try { + apply(p, trial); + } catch (Throwable x) { + Catalog.stagedBack(this, staged); + throw x; + } LiveState.publish(this); return 0; } From 49c1a5c8963ab85e331328949baf09371a4ada9f Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sat, 28 Nov 2026 10:38:15 -0500 Subject: [PATCH 05/10] Catalogue: updates for mods outside it, from their own GitHub releases A mod the catalogue doesn't list (USB or adb, private, waiting for its PR) gets updates from the repo its own mod.json names ("repo", inside the signed package, so the author's key chose it). One API call per repo, at most 10 a refresh (longest unchecked first); the newest release newer than what's installed, with its zip ("release_asset", else -.zip), becomes an entry like the catalogue's ("source": "release"), so planning, staging and installing are unchanged. Finals only, unless the installed version is a pre-release or the owner opted in. Trust is the installed key: a release is only ever an update by it (never a first install, a key change or a downgrade), its package must be the tag's id and version, its SHA-256 is checked when the release gives one (SHA256SUMS, or GitHub's digest), size capped. That is what catalog-automerge already merges for a catalogue entry with no one looking. - engine update-source catalogue | releases | off | default: the owner's choice per mod (a listed mod from a fork's releases, or no updates), in hmgapi.json catalog.update_source. - catalog/withdrawn.json: versions maintainers stopped, for both sources; installed ones are listed in updates. catalog.py checks it and never takes it for an entry. - updates: each row's source, repo, release page and notes; every installed mod's source. - GitHub's API limit: said, and the last answers kept. Co-Authored-By: Claude Opus 5.5 --- core/hmgapid/hmgapid.c | 5 +- core/runtime/catalog-test.sh | 155 ++++++++- core/runtime/java/hmgapi/engine/Catalog.java | 203 +++++++++++- core/runtime/java/hmgapi/engine/Engine.java | 2 +- core/runtime/java/hmgapi/engine/Releases.java | 310 ++++++++++++++++++ docs/mod-reference.md | 23 ++ tools/catalog-test.sh | 11 + tools/catalog.py | 22 +- wiki/Making-mods.md | 6 + 9 files changed, 721 insertions(+), 16 deletions(-) create mode 100644 core/runtime/java/hmgapi/engine/Releases.java diff --git a/core/hmgapid/hmgapid.c b/core/hmgapid/hmgapid.c index d87a9d28..8c2fdcbf 100644 --- a/core/hmgapid/hmgapid.c +++ b/core/hmgapid/hmgapid.c @@ -644,12 +644,13 @@ static int op_engine(int fd, int argc, char **argv) || seq(sub, "usb-scan") || seq(sub, "update-hmgapi") || seq(sub, "apps") || seq(sub, "probe") || seq(sub, "map-car") || seq(sub, "report") || seq(sub, "problem") || seq(sub, "nemesis-sync") || seq(sub, "catalog") || seq(sub, "catalog-plan") || seq(sub, "catalog-install") || seq(sub, "updates") - || seq(sub, "update") || seq(sub, "update-check"))) { + || seq(sub, "update") || seq(sub, "update-check") || seq(sub, "update-source"))) { say(fd, "usage: engine plan | apply [--trial] [--force] | keep | restore | status | recover | install | remove " " | nemesis-sync | map | map-car [--local | --write | --forget] | verify-map | report [--usb]" " | problem record [--no-log] [--crash-dumps] [--crash-reports] [--kernel] [--usb] [--seconds N] | problem stop" " | catalog [--refresh] | catalog-plan ... [--update] | catalog-install ... [--any-car[=,...]]" - " [--any-author=,...] | updates [--refresh] | update ... | --all | hmgapi [--force] | update-check\n"); + " [--any-author=,...] | updates [--refresh] | update ... | --all | hmgapi [--force] | update-check" + " | update-source catalogue | releases | off | default\n"); return 2; } a[n++] = APP_PROCESS; diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index af0e9d95..422454d7 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -7,7 +7,9 @@ # per mod), every download checked before the first install (SHA-256, the package being what the entry # says, the author key), the owner's any-car choice per mod, updates (mods and HMG-API's own release, # its pre-releases, mods it would leave behind), the automatic check (every 6 hours, staging only pure -# updates aside until apply), and a removal's warning. +# updates aside until apply), mods outside the catalogue updated from their own GitHub releases (by +# the installed key only; SHA-256 when given; withdrawn versions; the owner's choice of source; the +# API limit), and a removal's warning. # GitHub is played by files (HMGAPI_TEST_WEB: NativeFetch.Web). set -e cd "$(dirname "$0")/../.." @@ -467,6 +469,157 @@ eng catalog --refresh has "GitHub not answering: said, the old catalogue kept" "no connection" "$out" rm "$W/raw.githubusercontent.com.down" +# ---- mods outside the catalogue: updates from their own GitHub releases (mod.json "repo") +rm -f "$CAT/index.json"; listing +# rpkg [key]: a signed package as a release asset; sets $ZSHA, $ZSIZE +rpkg() { + rm -rf $T/m; mkdir -p $T/m + printf '{"id": "%s", "name": "%s mod", "version": "%s", "hmgapi": ">=1.0.0", "repo": "https://github.com/%s"%s}\n' "$2" "$2" "$3" "$1" "$4" > $T/m/mod.json + sig sign $T/m ${5:-$T/author.key} > /dev/null + z=$W/objects.githubusercontent.com/r/$1/$2-$3.zip; mkdir -p "$(dirname "$z")" "$W/github.com/$1/releases/download/v$3" + (cd $T/m && rm -f "$z" && zip -q -r -X "$z" .) + echo "https://objects.githubusercontent.com/r/$1/$2-$3.zip" > "$W/github.com/$1/releases/download/v$3/$2-$3.zip.redirect" + ZSHA=$(python3 -c "import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" "$z") + ZSIZE=$(wc -c < "$z" | tr -d ' ') +} +# rel : one release's JSON +rel() { printf '{"tag_name": "%s", "draft": false, "prerelease": %s, "html_url": "https://github.com/%s/releases/tag/%s", "body": "notes for %s", "assets": [%s]}' "$2" "$3" "$1" "$2" "$2" "$4"; } +asset() { printf '{"name": "%s", "browser_download_url": "https://github.com/%s/releases/download/%s/%s", "size": %s%s}' "$3" "$1" "$2" "$3" "$4" "$5"; } +releases() { r=$1; shift; mkdir -p "$W/api.github.com/repos/$r"; (IFS=,; echo "[$*]") > "$W/api.github.com/repos/$r/releases_per_page=10"; } +u() { printf '%s' "$out" | python3 -c "import json,sys; t=sys.stdin.read(); d=json.loads(t[t.index('{'):]); m=[x for x in d['mods'] if x['id']==sys.argv[1]]; print(eval(sys.argv[2]) if m else None)" "$1" "$2"; } + +rpkg dev/side side 1.0.0 '' +eng install $W/objects.githubusercontent.com/r/dev/side/side-1.0.0.zip +check "an unlisted mod with a repo, installed by hand" 1.0.0 "$(installed side)" +rpkg dev/side side 1.1.0 ''; S11=$ZSHA; A11=$(asset dev/side v1.1.0 side-1.1.0.zip $ZSIZE ", \"digest\": \"sha256:$ZSHA\"") +rpkg dev/side side 1.2.0-beta.1 ''; A12=$(asset dev/side v1.2.0-beta.1 side-1.2.0-beta.1.zip $ZSIZE '') +releases dev/side "$(printf '{"tag_name": "v2.0.0", "draft": true, "prerelease": false, "assets": []}')" "$(rel dev/side v1.2.0-beta.1 true "$A12")" \ + "$(rel dev/side v1.1.0 false "$A11,$(asset dev/side v1.1.0 other-1.1.0.zip 10 '')")" "$(rel dev/side v0.9.0 false '')" +: > $W/requests.log +eng updates --refresh +check "its releases: the newest final, not the draft or the beta" 1.1.0 "$(u side 'm[0]["version"]')" +check "... said where from" "release https://github.com/dev/side" "$(u side 'm[0]["source"]+" "+m[0]["repo"]')" +check "... with the release's notes" "notes for v1.1.0" "$(u side 'm[0]["notes"]')" +check "... its source: releases" releases "$(j 'd["sources"]["side"]["source"]')" +check "... one API call for its repo" 1 "$(grep -c 'api.github.com/repos/dev/side/releases?per_page=10' $W/requests.log)" +hasnt "... none for mods with no repo" "repos/test/" "$(cat $W/requests.log)" +check "... the release's SHA-256 kept (its digest)" "$S11" "$(python3 -c "import json,sys; print([m for m in json.load(open(sys.argv[1]))['mods'] if m['id']=='side'][0]['sha256'])" $D/catalog/releases.json)" +eng catalog +hasnt "... not in the Catalogue tab" '"side"' "$out" +eng update side +check "update from its release" 0 $rc +has "... checked against the release's SHA-256" "downloaded side 1.1.0 from its release (SHA-256 as the release's)" "$out" +check "... installed" 1.1.0 "$(installed side)" + +# a release whose zip isn't what its digest says; one with no SHA-256 at all (the signature decides) +rpkg dev/side side 1.3.0 '' +releases dev/side "$(rel dev/side v1.3.0 false "$(asset dev/side v1.3.0 side-1.3.0.zip $ZSIZE ", \"digest\": \"sha256:$(printf '%064d' 0)\"")")" +eng updates --refresh +eng update side +check "a digest that doesn't match: refused" 1 $rc +has "... why" "the download's SHA-256 is $ZSHA, its release says" "$out" +releases dev/side "$(rel dev/side v1.3.0 false "$(asset dev/side v1.3.0 side-1.3.0.zip $ZSIZE '')")" +eng updates --refresh +eng update side +check "no SHA-256 given: the signature decides" "0 1.3.0" "$rc $(installed side)" +has "... said so" "no SHA-256 given: its signature decides" "$out" + +# SHA256SUMS in the release, a zip by another key (as a key change), a package that isn't the tag's version +rpkg dev/side side 1.4.0 '' $T/other.key +printf '%s side-1.4.0.zip\n' "$ZSHA" > "$W/github.com/dev/side/releases/download/v1.4.0/SHA256SUMS" +releases dev/side "$(rel dev/side v1.4.0 false "$(asset dev/side v1.4.0 side-1.4.0.zip $ZSIZE ''),$(asset dev/side v1.4.0 SHA256SUMS 80 '')")" +eng updates --refresh +check "SHA256SUMS: its SHA-256 used" "$ZSHA" "$(python3 -c "import json,sys; print([m for m in json.load(open(sys.argv[1]))['mods'] if m['id']=='side'][0]['sha256'])" $D/catalog/releases.json)" +eng update side +check "a release by another author key (a key change): refused" "3 1.3.0" "$rc $(installed side)" +has "... why" "signed by a different author (uuid $O, installed mod has $U)" "$out" +rpkg dev/side side 1.6.0 '' +mkdir -p $W/github.com/dev/side/releases/download/v1.5.0; mv $W/github.com/dev/side/releases/download/v1.6.0/side-1.6.0.zip.redirect $W/github.com/dev/side/releases/download/v1.5.0/side-1.5.0.zip.redirect +releases dev/side "$(rel dev/side v1.5.0 false "$(asset dev/side v1.5.0 side-1.5.0.zip $ZSIZE '')")" +eng updates --refresh +eng update side +check "a package that isn't the release's version: refused" 1 $rc +has "... why" "the package is side 1.6.0" "$out" + +# too large, no matching zip, a download from elsewhere: not offered, with a note +releases dev/side "$(rel dev/side v1.7.0 false "$(asset dev/side v1.7.0 side-1.7.0.zip 99999999999 '')")" +eng catalog --refresh +has "a zip larger than HMG-API takes: noted" "side 1.7.0: its zip is 99999999999 bytes" "$(j '" ".join(d.get("notes", []))')" +releases dev/side "$(rel dev/side v1.7.0 false "$(asset dev/side v1.7.0 notes.txt 10 '')")" +eng catalog --refresh +has "no zip for it: noted" "side 1.7.0: its release has no side-....zip asset" "$(j '" ".join(d.get("notes", []))')" +releases dev/side "$(rel dev/side v1.7.0 false '{"name": "side-1.7.0.zip", "browser_download_url": "https://example.com/side-1.7.0.zip", "size": 10}')" +eng updates --refresh +check "a zip from outside its repo's releases: not offered" None "$(u side 'm[0]["version"]')" + +# withdrawn by a maintainer: skipped for the newest one that isn't +rpkg dev/side side 1.7.0 ''; A17=$(asset dev/side v1.7.0 side-1.7.0.zip $ZSIZE '') +rpkg dev/side side 1.8.0 ''; A18=$(asset dev/side v1.8.0 side-1.8.0.zip $ZSIZE '') +releases dev/side "$(rel dev/side v1.8.0 false "$A18")" "$(rel dev/side v1.7.0 false "$A17")" +echo '{"withdrawn": [{"id": "side", "versions": ">=1.8.0", "why": "breaks the camera"}, {"id": "base", "versions": "2.0.0", "why": "test"}]}' > "$CAT/withdrawn.json" +listing +eng catalog --refresh +hasnt "withdrawn.json isn't taken for an entry" "withdrawn: left out" "$out" +eng updates +check "a withdrawn release: the one before it offered" 1.7.0 "$(u side 'm[0]["version"]')" +check "... an installed version that's withdrawn: said" "base 2.0.0 test" "$(j '" ".join(w["id"]+" "+w["version"]+" "+w["why"] for w in d.get("withdrawn", []))')" +eng catalog +check "... and in the Catalogue tab" test "$(j '[m for m in d["mods"] if m["id"]=="base"][0].get("withdrawn")')" +rm "$CAT/withdrawn.json"; listing + +# staged by the automatic check, like a catalogue update +: > "$D/settings/allow/auto_stage_updates" +GAP=0 eng update-check +has "staged from its release" "staged: side 1.3.0 -> 1.8.0" "$(cat $D/logs/hmgapi/updates.log)" +check "... in pending/" 1.8.0 "$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['version'])" $D/pending/side/mod.json)" +rm -rf "$D/pending/side" "$D/settings/allow/auto_stage_updates" + +# the owner's choice: off, then back; a listed mod from its releases instead +eng update-source side off +has "updates off" "side: updates from nowhere" "$out" +eng updates +check "... not offered" None "$(u side 'm[0]["version"]')" +eng update side +has "... updating it says why not" "side's updates are turned off" "$out" +eng update-source side default +has "... default again: its releases" "side: updates from dev/side's releases" "$out" +eng update-source base releases +check "releases for a mod with no repo: refused" 1 $rc +has "... why" "names no GitHub repo" "$out" +eng update-source side catalogue +has "the catalogue for a mod it doesn't list: refused" "side isn't in the catalogue" "$out" +eng update-source nosuch off +has "a mod that isn't installed: refused" "nosuch isn't installed" "$out" +ENTRY=; pkg both 1.0.0 ', "repo": "https://github.com/dev/both"'; listing +eng catalog --refresh +eng catalog-install both +check "a listed mod with a repo" 1.0.0 "$(installed both)" +rpkg dev/both both 1.1.0 ''; releases dev/both "$(rel dev/both v1.1.0 false "$(asset dev/both v1.1.0 both-1.1.0.zip $ZSIZE '')")" +: > $W/requests.log +eng updates --refresh +check "... from the catalogue: no update, its releases not asked" "None 0" "$(u both 'm[0]["version"]') $(grep -c 'repos/dev/both' $W/requests.log || true)" +eng update-source both releases +eng updates --refresh +check "... its releases, chosen: offered" "1.1.0 release" "$(u both 'm[0]["version"]+" "+m[0]["source"]')" +eng update-source both default + +# a beta tester stays on that mod's betas +rpkg dev/beta beta 2.0.0-beta.1 '' +eng install $W/objects.githubusercontent.com/r/dev/beta/beta-2.0.0-beta.1.zip +rpkg dev/beta beta 2.0.0-beta.2 ''; releases dev/beta "$(rel dev/beta v2.0.0-beta.2 true "$(asset dev/beta v2.0.0-beta.2 beta-2.0.0-beta.2.zip $ZSIZE '')")" +eng updates --refresh +check "a beta installed: its next beta offered" 2.0.0-beta.2 "$(u beta 'm[0]["version"]')" + +# GitHub's API limit: said, the last answer kept +echo 403 > "$W/api.github.com/repos/dev/beta/releases_per_page=10.status" +echo 403 > "$W/api.github.com/repos/dev/side/releases_per_page=10.status" +eng catalog --refresh +has "the API limit: said" "GitHub's API limit (60 an hour) is reached" "$(j '" ".join(d.get("notes", []))')" +eng updates +check "... the last answers kept" "2.0.0-beta.2 1.8.0" "$(u beta 'm[0]["version"]') $(u side 'm[0]["version"]')" +rm "$W/api.github.com/repos/dev/beta/releases_per_page=10.status" "$W/api.github.com/repos/dev/side/releases_per_page=10.status" +eng remove beta; eng remove side; eng remove both + # ---- removing a mod others require: warned eng remove base has "a removal others need: warned" "app requires base: it won't load until base is installed again" "$out" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index cfdb4588..ddcc541f 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -29,6 +29,8 @@ * update them (with any new requires); hmgapi: HMG-API itself * engine update-check wifi.sh, each time home Wi-Fi comes up (at most every 6 hours): * refresh, and stage the mods' updates if the owner allowed it + * engine update-source catalogue | releases | off | default + * where an installed mod's updates come from (the owner's choice) * overrides, the owner's own choice, per mod: --any-car=,... (not listed for this head unit), * --any-author=,... (a first install by an author key that isn't on this unit's trusted list); * --any-car alone: every mod in the batch @@ -45,6 +47,10 @@ * before the first one goes in. Nothing is applied here: the owner applies (engine apply) as after * any install. * + * Mods outside the catalogue: their own GitHub releases (Releases), when their mod.json names the + * repo. Each installed mod has one update source (source()): the catalogue, its releases, or none. + * A maintainer can stop a version on both: catalog/withdrawn.json (withdrawn()). + * * Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and from the * downloaded package's mod.json (kept in learned.json, so the next plan has them); each is met by * what's installed, or by the catalogue's version, installed first. A required mod that's turned off @@ -64,10 +70,11 @@ final class Catalog { static final String ID = "[a-z0-9][a-z0-9-]{0,63}"; /** a plan or install refreshes a catalogue older than this when it can */ static final long STALE_MS = 15 * 60 * 1000L; - /** update-check: at most one every 6 hours (each is 2 of GitHub's 60 API calls an hour) */ + /** update-check: at most one every 6 hours (each is 2 of GitHub's 60 API calls an hour, and one per repo of mods updated from their releases) */ static final long CHECK_GAP_S = 6 * 3600; /** catalog-install / update: the packages require more than the plan said; the new plan is in the output */ static final int PLAN_CHANGED = 5; + static final String FROM_CATALOGUE = "catalogue", FROM_RELEASES = "releases", FROM_NONE = "off"; final Engine e; final File dir, cacheFile, updatesFile, learnedFile; @@ -124,6 +131,7 @@ static int run(Engine e, String[] args) throws Exception { return 0; } if ("update-check".equals(cmd)) return c.updateCheck(); + if ("update-source".equals(cmd)) return c.setSource(args); // planning and installing: the catalogue as it is now, when home Wi-Fi is up String stale = null; if (c.cache == null || (c.offline() == null && c.stale())) { @@ -301,7 +309,7 @@ String refresh() throws Exception { for (Object o : (List) list) { if (!(o instanceof Map)) continue; String name = String.valueOf(((Map) o).get("name")); - if (!name.matches(ID + "\\.json") || "index.json".equals(name)) continue; + if (!name.matches(ID + "\\.json") || "index.json".equals(name) || "withdrawn.json".equals(name)) continue; if (mods.size() >= MAX_ENTRIES) break; File ef = new File(tmp, name); Http.Result er = http.get(base + name, ef, MAX_ENTRY); @@ -340,9 +348,36 @@ String refresh() throws Exception { if (rel != null) c.put("hmgapi", rel); else if (relErr != null && cache != null && cache.get("hmgapi") != null) c.put("hmgapi", cache.get("hmgapi")); // kept if (relErr != null) notes.add("HMG-API's releases: " + relErr); + // what maintainers withdrew: a 404 is none; anything else keeps the last check's + File wf = new File(tmp, "withdrawn.json"); + Http.Result wr = http.get(base + "withdrawn.json", wf, MAX_JSON); + Object wd = null; + if (wr.ok()) { + try { + Object w = Json.parse(Engine.read(wf)); + wd = w instanceof Map ? ((Map) w).get("withdrawn") : w; + } catch (Exception x) { + wd = null; + } + if (!(wd instanceof List)) notes.add("the catalogue's withdrawn.json isn't a list: the last check's kept"); + } else if (wr.status == 404) { + wd = new ArrayList(); + } else { + notes.add("the catalogue's withdrawn.json: " + wr + " (the last check's kept)"); + } + if (!(wd instanceof List) && cache != null && cache.get("withdrawn") instanceof List) wd = cache.get("withdrawn"); + if (wd instanceof List) c.put("withdrawn", wd); + cache = c; // the new catalogue first: which mods it lists decides their source + Set listed = new HashSet(); + for (Object o : mods) listed.add(String.valueOf(((Map) o).get("id"))); + List fromReleases = new ArrayList(); + for (String id : installed().keySet()) { + Releases.Mod m = Releases.mod(e, id); + if (m != null && FROM_RELEASES.equals(source(id, m, listed))) fromReleases.add(m); + } + Releases.check(this, http, tmp, fromReleases, notes); if (!notes.isEmpty()) c.put("notes", notes); writeWhole(cacheFile, Json.write(c), false); - cache = c; writeUpdates(); return null; } finally { @@ -473,14 +508,134 @@ Map installed() { return m; } + /** the catalogue's own entries, as listed (the Catalogue tab) */ @SuppressWarnings("unchecked") - Map> entries() { + Map> listed() { Map> m = new LinkedHashMap>(); if (cache == null || !(cache.get("mods") instanceof List)) return m; for (Object o : (List) cache.get("mods")) m.put(String.valueOf(((Map) o).get("id")), (Map) o); return m; } + /** + * What planning and updates go by: the catalogue's entries, none that's withdrawn, with each mod whose + * update source is its releases taking its release entry instead (by the installed key; none if no + * newer release was found). + */ + Map> entries() { + Map> m = listed(); + for (String id : new ArrayList(m.keySet())) { + if (withdrawn(id, String.valueOf(m.get(id).get("version"))) != null) m.remove(id); + } + Map> rel = Releases.entries(this); + Set ids = listed().keySet(); + for (String id : installed().keySet()) { + Releases.Mod mod = Releases.mod(e, id); + if (mod == null || !FROM_RELEASES.equals(source(id, mod, ids))) continue; + m.remove(id); + Map en = rel.get(id); + if (en != null && mod.uuid != null && mod.uuid.equalsIgnoreCase(String.valueOf(en.get("uuid"))) + && withdrawn(id, String.valueOf(en.get("version"))) == null) m.put(id, en); + } + return m; + } + + /** why a maintainer withdrew id's version (catalog/withdrawn.json: [{"id", "versions": range, "why"}]), or null */ + @SuppressWarnings("unchecked") + String withdrawn(String id, String version) { + Object l = cache == null ? null : cache.get("withdrawn"); + for (Object o : l instanceof List ? (List) l : new ArrayList()) { + if (!(o instanceof Map)) continue; + Map w = (Map) o; + if (!id.equals(w.get("id"))) continue; + Object r = w.get("versions"); + if (r != null && !sat(version, String.valueOf(r))) continue; + return w.get("why") instanceof String ? (String) w.get("why") : "withdrawn by HMG-API's maintainers"; + } + return null; + } + + // ---- where each installed mod's updates come from + + /** the owner's choices: hmgapi.json "catalog": {"update_source": {"": "catalogue" | "releases" | "off"}} */ + @SuppressWarnings("unchecked") + Map choices() { + Object c = e.hmgapi.get("catalog"); + Object u = c instanceof Map ? ((Map) c).get("update_source") : null; + return u instanceof Map ? (Map) u : new LinkedHashMap(); + } + + /** + * id's update source: the owner's choice, else the catalogue when it lists the mod, else its releases + * when its mod.json names a GitHub repo, else none. A choice that can't be met (the catalogue for a + * mod it doesn't list, releases with no GitHub repo) is none. + */ + String source(String id, Releases.Mod m, Set listed) { + Object ch = choices().get(id); + String s = ch instanceof String ? (String) ch : listed.contains(id) ? FROM_CATALOGUE : FROM_RELEASES; + if (FROM_CATALOGUE.equals(s)) return listed.contains(id) ? FROM_CATALOGUE : FROM_NONE; + if (FROM_RELEASES.equals(s)) return m != null && m.repo != null ? FROM_RELEASES : FROM_NONE; + return FROM_NONE; + } + + /** each installed mod's update source, for the app: {id: {"source", "choice"?, "repo"?, "listed"}} */ + Map sources() { + Map out = new TreeMap(); + Set ids = listed().keySet(); + Map ch = choices(); + for (String id : installed().keySet()) { + Releases.Mod m = Releases.mod(e, id); + Map x = new LinkedHashMap(); + x.put("source", source(id, m, ids)); + if (ch.get(id) instanceof String) x.put("choice", ch.get(id)); + if (m != null && m.repo != null) x.put("repo", m.repo); + x.put("listed", ids.contains(id)); + out.put(id, x); + } + return out; + } + + /** engine update-source catalogue | releases | off | default: the owner's choice, kept in hmgapi.json */ + @SuppressWarnings("unchecked") + int setSource(String[] args) throws IOException { + if (args.length != 3 || !args[1].matches(ID) || !Arrays.asList(FROM_CATALOGUE, FROM_RELEASES, FROM_NONE, "default").contains(args[2])) { + e.out.add("usage: engine update-source catalogue | releases | off | default"); + return 2; + } + String id = args[1], to = args[2]; + Map inst = installed(); + if (!inst.containsKey(id)) { + e.out.add(id + " isn't installed"); + return 1; + } + Releases.Mod m = Releases.mod(e, id); + if (FROM_RELEASES.equals(to) && (m == null || m.repo == null)) { + e.out.add(id + "'s mod.json names no GitHub repo (\"repo\": \"https://github.com//\"), so it has no releases to check"); + return 1; + } + if (FROM_CATALOGUE.equals(to) && !listed().containsKey(id)) { + e.out.add(id + " isn't in the catalogue" + (cache == null ? " (it hasn't been checked yet)" : "")); + return 1; + } + Object c = e.hmgapi.get("catalog"); + Map cat = c instanceof Map ? (Map) c : new LinkedHashMap(); + Map ch = new TreeMap(choices()); + for (String k : new ArrayList(ch.keySet())) if (!inst.containsKey(k)) ch.remove(k); // removed mods' choices go + if ("default".equals(to)) ch.remove(id); + else ch.put(id, to); + if (ch.isEmpty()) cat.remove("update_source"); + else cat.put("update_source", ch); + e.hmgapi.put("catalog", cat); + File lj = new File(e.data, "settings/hmgapi.json"); + lj.getParentFile().mkdirs(); + Engine.write(lj, Json.write(e.hmgapi)); + String now = source(id, m, listed().keySet()); + e.out.add(id + ": updates from " + (FROM_CATALOGUE.equals(now) ? "the catalogue" : FROM_RELEASES.equals(now) ? m.repo + "'s releases" : "nowhere (not checked)") + + (FROM_RELEASES.equals(now) ? " (checked at the next refresh)" : "")); + if (cache != null) writeUpdates(); + return 0; + } + /** a dependency list (requires or conflicts), optional ones left out (only NEMESIS's package builder honours them) */ @SuppressWarnings("unchecked") static List deps(Object list) { @@ -559,7 +714,7 @@ Map report() { rep.put("checked", cache.get("checked")); Map inst = installed(); List out = new ArrayList(); - for (Map en : entries().values()) { + for (Map en : listed().values()) { Map m = new LinkedHashMap(); String id = String.valueOf(en.get("id")); for (String k : new String[] {"id", "name", "version", "description", "authors", "license", "repo", "uuid"}) { @@ -578,6 +733,8 @@ Map report() { for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); if (!req.isEmpty()) m.put("requires", req); m.put("trusted", Packages.trustedAuthor(e, String.valueOf(en.get("uuid"))) != null); + String wd = withdrawn(id, String.valueOf(en.get("version"))); + if (wd != null) m.put("withdrawn", wd); out.add(m); } rep.put("mods", out); @@ -607,9 +764,12 @@ Map updates() { if (cache != null) { rep.put("checked", cache.get("checked")); Map> cat = entries(); + Map src = sources(); for (Map.Entry i : installed().entrySet()) { Map en = cat.get(i.getKey()); if (en == null || !"update".equals(status(i.getValue().version, String.valueOf(en.get("version"))))) continue; + Object s = src.get(i.getKey()); + if (s instanceof Map && FROM_NONE.equals(((Map) s).get("source"))) continue; // the owner turned its updates off String unfit = unfit(en); if (unfit != null && !unfit.startsWith("car: ")) continue; // not for this HMG-API: not offered Map m = new LinkedHashMap(); @@ -622,8 +782,24 @@ Map updates() { for (Version.Dep d : deps(en.get("requires"))) req.add(d.toString()); if (!req.isEmpty()) m.put("requires", req); if (String.valueOf(en.get("version")).equals(stagedVersion(e, i.getKey()))) m.put("staged", true); + if ("release".equals(en.get("source"))) { // from the mod's own releases: said so, with its notes + m.put("source", "release"); + for (String k : new String[] {"repo", "page", "notes", "prerelease"}) if (en.get(k) != null) m.put(k, en.get(k)); + } list.add(m); } + List wd = new ArrayList(); // what's installed that a maintainer withdrew + for (Map.Entry i : installed().entrySet()) { + String why = withdrawn(i.getKey(), i.getValue().version); + if (why == null) continue; + Map w = new LinkedHashMap(); + w.put("id", i.getKey()); + w.put("version", i.getValue().version); + w.put("why", why); + wd.add(w); + } + if (!wd.isEmpty()) rep.put("withdrawn", wd); + rep.put("sources", src); Map h = hmgapiOffer(); if (h != null) rep.put("hmgapi", h); } @@ -806,7 +982,11 @@ void want(String id, boolean update) { Map en = cat.get(id); Inst i = inst.get(id); if (en == null) { - problem(id + " isn't in the catalogue"); + Releases.Mod m = i == null ? null : Releases.mod(e, id); + String src = m == null ? null : source(id, m, listed().keySet()); + problem(FROM_RELEASES.equals(src) ? id + ": no newer release in " + m.repo + "'s releases (as last checked)" + : FROM_NONE.equals(src) && i != null && choices().get(id) != null ? id + "'s updates are turned off (update-source)" + : id + " isn't in the catalogue"); return; } String st = status(i == null ? null : i.version, String.valueOf(en.get("version"))); @@ -1025,8 +1205,12 @@ String fetch(Http http, File dl, Step s, Map> pkgs) File z = new File(dl, s.id + "-" + s.version + ".zip"); Http.Result r = http.get(String.valueOf(s.entry.get("download")), z, (int) Packages.MAX_BYTES); if (!r.ok()) return "can't download " + s.id + " " + s.version + ": " + r; - String sha = Sha256.hex(z), want = String.valueOf(s.entry.get("sha256")); - if (!sha.equals(want)) return "refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", the catalogue says " + want; + boolean rel = "release".equals(s.entry.get("source")); + String sha = Sha256.hex(z), want = s.entry.get("sha256") == null ? null : String.valueOf(s.entry.get("sha256")); + if (want == null && !rel) return "refused " + s.id + " " + s.version + ": its catalogue entry has no SHA-256"; + if (want != null && !sha.equals(want)) { + return "refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", " + (rel ? "its release says " : "the catalogue says ") + want; + } File u = new File(dl, s.id + "-" + s.version); Map mj = null; try { @@ -1042,7 +1226,8 @@ String fetch(Http http, File dl, Step s, Map> pkgs) return "refused " + s.id + " " + s.version + ": the package is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")); } pkgs.put(s.id, mj); - e.out.add("downloaded " + s.id + " " + s.version + " (SHA-256 as the catalogue's)"); + e.out.add("downloaded " + s.id + " " + s.version + (!rel ? " (SHA-256 as the catalogue's)" : want != null ? " from its release (SHA-256 as the release's)" + : " from its release (no SHA-256 given: its signature decides)")); return null; } diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 551703f9..df4c43aa 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -378,7 +378,7 @@ int run(String[] args) throws Exception { if ("problem".equals(cmd)) return ProblemLog.run(this, args); if ("usb-scan".equals(cmd)) return UsbUpdates.scan(this); if ("catalog".equals(cmd) || "catalog-plan".equals(cmd) || "catalog-install".equals(cmd) || "updates".equals(cmd) - || "update".equals(cmd) || "update-check".equals(cmd)) return Catalog.run(this, args); + || "update".equals(cmd) || "update-check".equals(cmd) || "update-source".equals(cmd)) return Catalog.run(this, args); if ("publish-state".equals(cmd)) return LiveState.publish(this); if ("apps".equals(cmd)) return ModApps.sync(this); if ("probe".equals(cmd)) { // a mod's install-time probe again (its answer is kept until then) diff --git a/core/runtime/java/hmgapi/engine/Releases.java b/core/runtime/java/hmgapi/engine/Releases.java new file mode 100644 index 00000000..83642122 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Releases.java @@ -0,0 +1,310 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Updates for installed mods from their own GitHub releases: for a mod the catalogue doesn't list + * (installed from USB or adb, a private mod, one waiting for its catalogue PR), or one whose owner + * chose its releases (a test build from a fork, an entry that fell behind). + * + * Where to look: "repo" in the installed mod's own mod.json. It came inside the signed package, so + * only the author's key chose it. Which zip: "release_asset" in mod.json ("my-mod-v{version}.zip"), + * else the one .zip asset named "-...". Each mod's update source (Catalog.source): the owner's + * choice (engine update-source), else the catalogue when it lists the mod, else its releases when + * its repo is on GitHub, else none. + * + * Each release found becomes an entry shaped like a catalogue entry ("source": "release"), kept in + * /data/hmgapi/catalog/releases.json, so planning, staging and installing are the catalogue's own. + * Trust is the installed mod's author key: a release is only ever an update by that key (never a + * first install, a key change or a downgrade), checked by Packages as any update is; the package's + * id and version must be the release's; its SHA-256 is checked when the release gives one + * (SHA256SUMS, or the asset's digest). That is what catalog-automerge.yml takes for a catalogue + * entry with no one looking: a newer version from the mod's own repo's releases, the same key. + * A maintainer can still stop a bad version: catalog/withdrawn.json (Catalog.withdrawn) holds + * for both. + * + * GitHub allows 60 API calls an hour without an account: one call per repo (mods from one repo + * share it), at most MAX_REPOS a refresh, the repos checked longest ago first; the rest keep + * their last answer until the next. + */ +final class Releases { + static final int MAX_REPOS = 10, PER_PAGE = 10, MAX_NOTES = 6000; + static final Pattern REPO = Pattern.compile("https://github\\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+?)(?:\\.git)?/?"); + static final String TAG = "v?\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.]+)?"; + + private Releases() { + } + + /** "owner/repo" for a GitHub repo link, else null */ + static String repoOf(Object repo) { + if (!(repo instanceof String)) return null; + Matcher m = REPO.matcher((String) repo); + return m.matches() ? m.group(1) + "/" + m.group(2) : null; + } + + /** an installed mod, as a release check needs it */ + static final class Mod { + String id, version, name, description, repo, asset, uuid; + } + + @SuppressWarnings("unchecked") + static Mod mod(Engine e, String id) { + File d = new File(e.data, "mods/" + id); + try { + Map j = Json.object(Engine.read(new File(d, "mod.json"))); + Mod m = new Mod(); + m.id = id; + m.version = String.valueOf(j.get("version")); + m.name = j.get("name") instanceof String ? (String) j.get("name") : id; + m.description = j.get("description") instanceof String ? (String) j.get("description") : null; + m.repo = repoOf(j.get("repo")); + m.asset = j.get("release_asset") instanceof String ? (String) j.get("release_asset") : null; + m.uuid = Packages.installedUuid(d); + return m; + } catch (Exception x) { + return null; + } + } + + /** + * Checks the repos of the mods given (their source is releases) and writes releases.json; notes + * get what was left out and why. The last answer for a repo not checked this time is kept. + */ + @SuppressWarnings("unchecked") + static void check(Catalog c, Http http, File tmp, List mods, List notes) throws IOException { + Map old = load(c); + Map oldRepos = old.get("repos") instanceof Map ? (Map) old.get("repos") : new LinkedHashMap(); + Map> byRepo = new TreeMap>(); + for (Mod m : mods) { + if (m.repo == null || m.uuid == null) continue; + if (!byRepo.containsKey(m.repo)) byRepo.put(m.repo, new ArrayList()); + byRepo.get(m.repo).add(m); + } + // the repos checked longest ago (or never) first + List order = new ArrayList(byRepo.keySet()); + final Map or = oldRepos; + Collections.sort(order, new Comparator() { + public int compare(String a, String b) { + long x = when(or.get(a)), y = when(or.get(b)); + return x < y ? -1 : x > y ? 1 : a.compareTo(b); + } + }); + Map repos = new TreeMap(); + List entries = new ArrayList(); + int asked = 0; + boolean limited = false; + for (String repo : order) { + Map last = or.get(repo) instanceof Map ? (Map) or.get(repo) : null; + List list = null; + if (!limited && asked < MAX_REPOS) { + asked++; + File f = new File(tmp, "rel-" + asked + ".json"); + Http.Result r = http.get("https://api.github.com/repos/" + repo + "/releases?per_page=" + PER_PAGE, f, Catalog.MAX_JSON); + if (r.status == 403 || r.status == 429) { + limited = true; + notes.add("GitHub's API limit (60 an hour) is reached: " + repo + " and the rest are checked next time"); + } else if (!r.ok()) { + notes.add(repo + "'s releases: " + r + (r.status == 404 ? " (is its mod.json \"repo\" right, and the repo public?)" : "")); + } else { + try { + Object o = Json.parse(Engine.read(f)); + if (o instanceof List) list = (List) o; + else notes.add(repo + "'s releases: not a list"); + } catch (Exception x) { + notes.add(repo + "'s releases: not JSON"); + } + } + } + if (list == null) { // not asked this time, or it failed: the last answer stays + if (last != null) { + repos.put(repo, last); + for (Object en : last.get("entries") instanceof List ? (List) last.get("entries") : new ArrayList()) entries.add(en); + } + continue; + } + Map got = new LinkedHashMap(); + got.put("checked", System.currentTimeMillis()); + List found = new ArrayList(); + for (Mod m : byRepo.get(repo)) { + Map en = newest(c, http, tmp, m, list, notes); + if (en != null) found.add(en); + } + got.put("entries", found); + repos.put(repo, got); + entries.addAll(found); + } + Map out = new LinkedHashMap(); + out.put("checked", System.currentTimeMillis()); + out.put("repos", repos); + out.put("mods", entries); + Catalog.writeWhole(file(c), Json.write(out), false); + } + + static long when(Object repo) { + Object t = repo instanceof Map ? ((Map) repo).get("checked") : null; + return t instanceof Number ? ((Number) t).longValue() : 0; + } + + static File file(Catalog c) { + return new File(c.dir, "releases.json"); + } + + static Map load(Catalog c) { + try { + if (file(c).isFile()) return Json.object(Engine.read(file(c))); + } catch (Exception x) { + // unreadable: checked again + } + return new LinkedHashMap(); + } + + /** the release entries kept, by id */ + @SuppressWarnings("unchecked") + static Map> entries(Catalog c) { + Map> m = new LinkedHashMap>(); + Object l = load(c).get("mods"); + for (Object o : l instanceof List ? (List) l : new ArrayList()) { + if (o instanceof Map) m.put(String.valueOf(((Map) o).get("id")), (Map) o); + } + return m; + } + + /** + * The newest release of m's repo that this unit is offered, newer than what's installed, with its + * zip, as an entry; null if none (said why in notes when one was close). + */ + @SuppressWarnings("unchecked") + static Map newest(Catalog c, Http http, File tmp, Mod m, List list, List notes) { + Version have; + try { + have = new Version(m.version); + } catch (IllegalArgumentException x) { + notes.add(m.id + ": its installed version " + m.version + " can't be compared"); + return null; + } + // a beta tester stays on that mod's betas; anyone else gets finals, unless the owner opted in to pre-releases + boolean pre = c.prereleases() || !have.tag.isEmpty(); + Version bv = have; + Map bestAsset = null, bestRel = null; + String bestVer = null, skipped = null; + for (Object o : list) { + if (!(o instanceof Map)) continue; + Map rel = (Map) o; + if (Boolean.TRUE.equals(rel.get("draft"))) continue; + String tag = String.valueOf(rel.get("tag_name")); + if (!tag.matches(TAG)) continue; + String ver = tag.startsWith("v") ? tag.substring(1) : tag; + if (!Catalog.valid(ver)) continue; + Version v = new Version(ver); + if ((Boolean.TRUE.equals(rel.get("prerelease")) || !v.tag.isEmpty()) && !pre) continue; + if (v.compareTo(bv) <= 0) continue; + String why = c.withdrawn(m.id, ver); + if (why != null) { + skipped = m.id + " " + ver + " is withdrawn (" + why + ")"; + continue; + } + Map a = asset(m, ver, rel.get("assets")); + if (a == null) { + skipped = m.id + " " + ver + ": its release has no " + (m.asset != null ? m.asset.replace("{version}", ver) : m.id + "-....zip") + " asset"; + continue; + } + Object size = a.get("size"); + if (size instanceof Number && ((Number) size).longValue() > Packages.MAX_BYTES) { + skipped = m.id + " " + ver + ": its zip is " + size + " bytes, more than HMG-API takes (" + Packages.MAX_BYTES + ")"; + continue; + } + String url = String.valueOf(a.get("browser_download_url")); + if (!url.startsWith("https://github.com/" + m.repo + "/releases/download/")) { + skipped = m.id + " " + ver + ": its zip isn't a download from " + m.repo + "'s releases"; + continue; + } + bestAsset = a; + bestRel = rel; + bestVer = ver; + bv = v; + } + if (bestRel == null) { + if (skipped != null) notes.add(skipped); + return null; + } + String ver = bestVer; + Map en = new LinkedHashMap(); + en.put("id", m.id); + en.put("name", m.name); + if (m.description != null) en.put("description", m.description); + en.put("version", ver); + en.put("uuid", m.uuid); + en.put("repo", "https://github.com/" + m.repo); + en.put("download", bestAsset.get("browser_download_url")); + if (bestAsset.get("size") instanceof Number) en.put("size", bestAsset.get("size")); + String sha = sha256(http, tmp, m, String.valueOf(bestAsset.get("name")), bestRel.get("assets"), bestAsset); + if (sha != null) en.put("sha256", sha); + en.put("source", "release"); + en.put("prerelease", Boolean.TRUE.equals(bestRel.get("prerelease")) || !bv.tag.isEmpty()); + if (bestRel.get("html_url") instanceof String) en.put("page", bestRel.get("html_url")); + String body = bestRel.get("body") instanceof String ? ((String) bestRel.get("body")).trim() : ""; + if (body.length() > MAX_NOTES) body = body.substring(0, MAX_NOTES) + "\n…"; + if (!body.isEmpty()) en.put("notes", body); + return en; + } + + /** the release's zip for m: "release_asset" with {version}, else the one .zip named "-..." (the one with the version, if several) */ + @SuppressWarnings("unchecked") + static Map asset(Mod m, String ver, Object assets) { + List> zips = new ArrayList>(); + for (Object o : assets instanceof List ? (List) assets : new ArrayList()) { + if (!(o instanceof Map)) continue; + Map a = (Map) o; + String n = String.valueOf(a.get("name")); + if (m.asset != null) { + if (n.equals(m.asset.replace("{version}", ver))) return a; + continue; + } + if (n.startsWith(m.id + "-") && n.endsWith(".zip")) zips.add(a); + } + if (zips.size() == 1) return zips.get(0); + Map hit = null; + for (Map a : zips) { + String n = String.valueOf(a.get("name")); + if (n.equals(m.id + "-" + ver + ".zip") || n.equals(m.id + "-v" + ver + ".zip")) { + if (hit != null) return null; + hit = a; + } + } + return hit; + } + + /** the zip's SHA-256: from the release's SHA256SUMS, else GitHub's digest of the asset, else null (the signature decides) */ + @SuppressWarnings("unchecked") + static String sha256(Http http, File tmp, Mod m, String name, Object assets, Map asset) { + for (Object o : assets instanceof List ? (List) assets : new ArrayList()) { + if (!(o instanceof Map) || !"SHA256SUMS".equals(((Map) o).get("name"))) continue; + String url = String.valueOf(((Map) o).get("browser_download_url")); + if (!url.startsWith("https://github.com/" + m.repo + "/releases/download/")) break; + try { + File s = new File(tmp, "sums-" + m.id); + if (!http.get(url, s, Catalog.MAX_ENTRY).ok()) break; + for (String l : Engine.read(s).split("\n")) { + String[] p = l.trim().split("\\s+"); + if (p.length == 2 && p[1].replaceFirst("^\\*", "").equals(name) && p[0].matches("[0-9a-f]{64}")) return p[0]; + } + } catch (IOException x) { + // no sums: the digest, or the signature alone + } + break; + } + Object d = asset.get("digest"); + if (d instanceof String && ((String) d).matches("sha256:[0-9a-f]{64}")) return ((String) d).substring(7); + return null; + } +} diff --git a/docs/mod-reference.md b/docs/mod-reference.md index dccf83c4..dacac64f 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -540,6 +540,29 @@ your source. Keep your key private and backed up: a lost key means a new UUID, and owners would have to remove the old mod before installing yours again. +### Updates from your own releases + +A mod the catalogue doesn't list (installed from USB or adb, private, or waiting for +its catalogue PR) still gets updates over home Wi-Fi when its `mod.json` has +`"repo": "https://github.com//"`. The head unit checks that repo's GitHub +releases (one API call per repo, at most every 6 hours) and offers the newest one +that is newer than what's installed, in the Updates tab, saying where it came from: + +- Tag releases `vX.Y.Z` (or `vX.Y.Z-beta.N`, marked as a pre-release). An owner on a + final version gets finals; an owner on a pre-release gets that mod's pre-releases too. +- Attach the signed zip as `-.zip` or `-v.zip`, or name your + own pattern in `mod.json`: `"release_asset": "my-mod-v{version}.zip"` (needed when one + release carries several mods). +- A `SHA256SUMS` asset is optional. Without it, GitHub's digest of the asset is checked, + if it has one. +- Only your key updates your mod: a release signed with another key, a zip whose + `mod.json` isn't the tag's id and version, or one over 64 MB is never taken. + +For a listed mod the catalogue stays the source; the owner can choose its releases +instead (a test build from a fork), or turn updates off, on the mod's page +(`hmgapid engine update-source catalogue | releases | off | default`). +HMG-API's maintainers can stop a version for both sources in `catalog/withdrawn.json`. + ## Building a mod outside this repo A mod in its own repository builds with the HMG-API mod SDK, `hmgapi-mod-sdk-.zip` diff --git a/tools/catalog-test.sh b/tools/catalog-test.sh index 106cdb8c..e21550b0 100755 --- a/tools/catalog-test.sh +++ b/tools/catalog-test.sh @@ -226,4 +226,15 @@ has "page escapes text" 'Says \hi\ \[x\]\(https://evil\)' "$P" has "page links the download" "(<$DL>)" "$P" has "page shows the key" "\`$UA\`" "$P" +# catalog/withdrawn.json: not an entry; its form checked +echo '{"withdrawn": [{"id": "hello", "versions": ">=1.0.0", "why": "breaks things"}]}' > $R/catalog/withdrawn.json +C check +check "withdrawn.json: not taken for an entry, and fine" 0 $rc +echo '{"withdrawn": [{"id": "hello"}, {"id": "Bad"}, {"id": "x", "why": "y", "versions": ">>1"}]}' > $R/catalog/withdrawn.json +C check +has "withdrawn.json: a why is needed" 'hello: say "why"' "$out" +has "... an id" 'entry 2 has no mod "id"' "$out" +has "... a readable range" 'x: "versions"' "$out" +rm $R/catalog/withdrawn.json + [ $fail = 0 ] && echo "catalog: all ok" || { echo "catalog: FAILED"; exit 1; } diff --git a/tools/catalog.py b/tools/catalog.py index 72ceb6b6..87445d2a 100755 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -50,6 +50,10 @@ # a version range as the engine reads it (Version.one): each part an operator and a version, or "" / "*" RANGE_PART = re.compile(r'^(>=|<=|>|<|=|\^|~)?v?\d+(\.\d+){0,2}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$') INDEX = os.path.join(CATALOG, 'index.json') +# catalog/withdrawn.json: versions maintainers stopped ([{"id", "versions": range, "why"}]); head units skip +# them, from the catalogue or a mod's own releases. A maintainer's change: never part of a submission. +WITHDRAWN = os.path.join(CATALOG, 'withdrawn.json') +NOT_ENTRIES = ('index.json', 'withdrawn.json') NEEDED = ['id', 'name', 'description', 'authors', 'uuid', 'version', 'repo', 'download', 'sha256'] @@ -191,7 +195,7 @@ def index_of(es): def entries(): if not os.path.isdir(CATALOG): return {} - return {f[:-5]: load(os.path.join(CATALOG, f)) for f in sorted(os.listdir(CATALOG)) if f.endswith('.json') and f != 'index.json'} + return {f[:-5]: load(os.path.join(CATALOG, f)) for f in sorted(os.listdir(CATALOG)) if f.endswith('.json') and f not in NOT_ENTRIES} # ---- add @@ -318,6 +322,18 @@ def check_all(es, au, index=True): p += check_entry(name, e, authors) if index and os.path.exists(INDEX) and load(INDEX) != index_of(es): p.append('catalog/index.json isn\'t the entries: write it again (tools/catalog.py index)') + if os.path.exists(WITHDRAWN): + w = load(WITHDRAWN) + w = w.get('withdrawn') if isinstance(w, dict) else w + if not isinstance(w, list): + p.append('catalog/withdrawn.json: {"withdrawn": [{"id", "versions", "why"}, ...]}') + for i, x in enumerate(w if isinstance(w, list) else []): + if not isinstance(x, dict) or not ID.fullmatch(str(x.get('id', ''))): + p.append(f'catalog/withdrawn.json: entry {i + 1} has no mod "id"') + elif not isinstance(x.get('why'), str) or not x['why'].strip(): + p.append(f'catalog/withdrawn.json: {x["id"]}: say "why" (owners see it)') + elif 'versions' in x and range_error(str(x['versions'])): + p.append(f'catalog/withdrawn.json: {x["id"]}: "versions" {range_error(str(x["versions"]))}') return p @@ -343,7 +359,7 @@ def check_base(es, au, ref): r = subprocess.run(['git', '-C', REPO, 'ls-tree', '--name-only', ref, 'catalog/'], capture_output=True, text=True) for f in r.stdout.split(): n = os.path.basename(f)[:-5] - if f.endswith('.json') and n not in es: + if f.endswith('.json') and n not in es and os.path.basename(f) not in NOT_ENTRIES: changed.add(str((git_show(ref, f) or {}).get('uuid', '')).lower()) # a removal: its author's to make old_au = (git_show(ref, 'maps/authors.json') or {}).get('authors', {}) new_au = au.get('authors', {}) @@ -394,7 +410,7 @@ def cmd_bump(a): head = {} lt = subprocess.run(['git', '-C', REPO, 'ls-tree', '--name-only', a.head, 'catalog/'], capture_output=True, text=True) for f in lt.stdout.split(): - if f.endswith('.json') and f != 'catalog/index.json': + if f.endswith('.json') and os.path.basename(f) not in NOT_ENTRIES: head[os.path.basename(f)[:-5]] = git_show(a.head, f) if git_show(a.head, 'catalog/index.json') != index_of(head): no.append('catalog/index.json isn\'t the entries') diff --git a/wiki/Making-mods.md b/wiki/Making-mods.md index c3876c48..a7557ccc 100644 --- a/wiki/Making-mods.md +++ b/wiki/Making-mods.md @@ -82,6 +82,12 @@ request changes only its own author's entry in the trusted list. Listing means t package is whole and signed by you; the maintainer reviews each new author before merging. +Not listed (yet)? Put `"repo": "https://github.com/you/my-mod"` in `mod.json` and +tag your releases `vX.Y.Z` with the zip attached as `my-mod-X.Y.Z.zip`: owners who +installed it by hand are offered your new releases in the Updates tab, signed by +your key only. Listing is still how owners find your mod and how its first install +is trusted. + ## Scripts on the head unit The head unit's shell is mksh with a small toolbox: no `sed`, `tr`, `awk`, `head`, From 2ffd4e351b3402946fbe19385e089ebfabdf299e Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sat, 28 Nov 2026 10:42:14 -0500 Subject: [PATCH 06/10] Catalogue: a mod's repo moved to another owner still gets its releases GitHub's API follows a transfer or rename, but the downloads it lists are the new repo's. The repo is taken from the release's page, and the zip (and SHA256SUMS) must be from that same repo; the package still has to be signed by the installed key. Co-Authored-By: Claude Opus 5.5 --- core/runtime/catalog-test.sh | 13 ++++++++ core/runtime/java/hmgapi/engine/Releases.java | 33 ++++++++++++++----- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index 422454d7..3c30f393 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -610,6 +610,19 @@ rpkg dev/beta beta 2.0.0-beta.2 ''; releases dev/beta "$(rel dev/beta v2.0.0-bet eng updates --refresh check "a beta installed: its next beta offered" 2.0.0-beta.2 "$(u beta 'm[0]["version"]')" +# a repo moved to another owner (GitHub's API follows it): its downloads are the new repo's +rm -rf "$W/objects.githubusercontent.com/r/org"; mkdir -p "$W/objects.githubusercontent.com/r/org/beta" "$W/github.com/org/beta/releases/download/v2.0.0-beta.3" +rpkg dev/beta beta 2.0.0-beta.3 '' +mv $W/github.com/dev/beta/releases/download/v2.0.0-beta.3/beta-2.0.0-beta.3.zip.redirect $W/github.com/org/beta/releases/download/v2.0.0-beta.3/ +releases dev/beta "$(rel org/beta v2.0.0-beta.3 true "$(asset org/beta v2.0.0-beta.3 beta-2.0.0-beta.3.zip $ZSIZE '')")" +eng updates --refresh +check "a moved repo: offered, from where it is now" "2.0.0-beta.3 https://github.com/org/beta" "$(u beta 'm[0]["version"]+" "+m[0]["repo"]')" +releases dev/beta "$(rel dev/beta v2.0.0-beta.3 true "$(asset org/beta v2.0.0-beta.3 beta-2.0.0-beta.3.zip $ZSIZE '')")" +eng updates --refresh +check "... a download from another repo than its release's: not offered" None "$(u beta 'm[0]["version"]')" +releases dev/beta "$(rel dev/beta v2.0.0-beta.2 true "$(asset dev/beta v2.0.0-beta.2 beta-2.0.0-beta.2.zip 100 '')")" +eng updates --refresh + # GitHub's API limit: said, the last answer kept echo 403 > "$W/api.github.com/repos/dev/beta/releases_per_page=10.status" echo 403 > "$W/api.github.com/repos/dev/side/releases_per_page=10.status" diff --git a/core/runtime/java/hmgapi/engine/Releases.java b/core/runtime/java/hmgapi/engine/Releases.java index 83642122..05debe07 100644 --- a/core/runtime/java/hmgapi/engine/Releases.java +++ b/core/runtime/java/hmgapi/engine/Releases.java @@ -196,7 +196,7 @@ static Map newest(Catalog c, Http http, File tmp, Mod m, List bestAsset = null, bestRel = null; - String bestVer = null, skipped = null; + String bestVer = null, bestAt = null, skipped = null; for (Object o : list) { if (!(o instanceof Map)) continue; Map rel = (Map) o; @@ -223,11 +223,12 @@ static Map newest(Catalog c, Http http, File tmp, Mod m, List newest(Catalog c, Http http, File tmp, Mod m, List newest(Catalog c, Http http, File tmp, Mod m, List rel, String repo) { + Object page = rel.get("html_url"); + if (page instanceof String) { + Matcher m = Pattern.compile("https://github\\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/releases/tag/.+").matcher((String) page); + if (m.matches()) return m.group(1); + } + return repo; + } + /** the release's zip for m: "release_asset" with {version}, else the one .zip named "-..." (the one with the version, if several) */ @SuppressWarnings("unchecked") static Map asset(Mod m, String ver, Object assets) { @@ -286,13 +301,13 @@ static Map asset(Mod m, String ver, Object assets) { /** the zip's SHA-256: from the release's SHA256SUMS, else GitHub's digest of the asset, else null (the signature decides) */ @SuppressWarnings("unchecked") - static String sha256(Http http, File tmp, Mod m, String name, Object assets, Map asset) { + static String sha256(Http http, File tmp, String repo, String name, Object assets, Map asset) { for (Object o : assets instanceof List ? (List) assets : new ArrayList()) { if (!(o instanceof Map) || !"SHA256SUMS".equals(((Map) o).get("name"))) continue; String url = String.valueOf(((Map) o).get("browser_download_url")); - if (!url.startsWith("https://github.com/" + m.repo + "/releases/download/")) break; + if (!url.startsWith("https://github.com/" + repo + "/releases/download/")) break; try { - File s = new File(tmp, "sums-" + m.id); + File s = new File(tmp, "sums-" + name); if (!http.get(url, s, Catalog.MAX_ENTRY).ok()) break; for (String l : Engine.read(s).split("\n")) { String[] p = l.trim().split("\\s+"); From d4f5245d687f244bf1353cbe4f12065b25dc34a1 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sat, 28 Nov 2026 14:03:59 -0500 Subject: [PATCH 07/10] Catalogue: staged updates are part of the apply; withdrawn ones dropped; the check after Wi-Fi is up Review fixes (isaacwisdom): - Staged updates moved into mods/ are recorded (state/staged-swap.json) before the first move until the apply is final. engine recover puts them back with the /system files: a cut-off apply (with or without its journal yet, even between the two moves) and an undone trial. engine keep and a finished apply drop the record; an apply or install waits while it's there, and boot.sh runs recover for it as for a journal. - A staged version withdrawn since (catalog/withdrawn.json) is dropped at the apply, not put in. - wifi.sh starts the update check only after wifi.json says "up": the engine reads that to know it's online, and the check runs once per connection. Co-Authored-By: Claude Opus 5.5 --- core/runtime/catalog-test.sh | 45 ++++++++++++++ core/runtime/homewifi-test.sh | 1 + core/runtime/java/hmgapi/engine/Catalog.java | 58 ++++++++++++++++++- core/runtime/java/hmgapi/engine/Engine.java | 13 ++++- core/runtime/java/hmgapi/engine/HomeWifi.java | 5 +- install/common/boot.sh | 3 +- 6 files changed, 119 insertions(+), 6 deletions(-) diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index 3c30f393..ebf2cdc2 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -221,6 +221,51 @@ check "apply" 0 $rc has "... the staged update put in place first" "update helper 1.0.0 -> 1.1.0 (staged by the automatic check; 1.0.0 kept in /data/hmgapi/previous/helper)" "$out" check "... installed, the previous version kept" "1.1.0 1.0.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/previous/helper/mod.json'))['version'])")" check "... nothing left staged" no "$([ -d $D/pending/helper ] && echo yes || echo no)" +check "... its record gone: the apply is final" no "$([ -f $D/state/staged-swap.json ] && echo yes || echo no)" + +# staged updates are part of the apply: a cut-off apply or an undone trial puts them back, like the /system files +pkg helper 1.2.0; listing; eng catalog --refresh +GAP=0 eng update-check +check "helper 1.2.0 staged" 1.2.0 "$(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +# cut off between moving 1.1.0 aside and putting 1.2.0 in: only the record and previous/ are there +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +eng apply +check "an apply cut off in its staged updates: the next one waits for recover" 1 $rc +eng recover +check "... recover: the old version back, the update staged again" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +check "... its record gone" no "$([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +# cut off after both moves, before the journal was written (the apply was still planning) +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +eng recover +check "cut off before its journal: recover puts the old version back" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +has "... and says so (boot.sh restarts on it)" "rolled back the staged update of helper" "$out" +# a trial that's undone: its journal and the staged update's record go back together +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": True, "committed": True, "entries": [], "state": st}, open(os.path.join(d, "journal.json"), "w")) +J +eng keep +check "a trial kept: the staged update stays in" "0 1.2.0 no" "$rc $(installed helper) $([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +rm -rf "$D/mods/helper"; mv "$D/previous/helper" "$D/mods/helper"; pkg helper 1.2.0; listing; eng catalog --refresh; GAP=0 eng update-check +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": True, "committed": True, "entries": [], "state": st}, open(os.path.join(d, "journal.json"), "w")) +J +eng recover +check "a trial undone: the staged update goes back with it" "1.1.0 1.2.0 no" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])") $([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +has "... trial undone" "trial undone" "$out" + +# withdrawn after it was staged: dropped at the apply, not put in +echo '{"withdrawn": [{"id": "helper", "versions": "1.2.0", "why": "breaks the cluster"}]}' > "$CAT/withdrawn.json" +eng catalog --refresh +eng apply +check "a staged update withdrawn since: not put in" "0 1.1.0 no" "$rc $(installed helper) $([ -d $D/pending/helper ] && echo yes || echo no)" +has "... said why" "dropped the staged helper 1.2.0: HMG-API's maintainers withdrew it since (breaks the cluster)" "$out" +rm "$CAT/withdrawn.json"; pkg helper 1.1.0; listing; eng catalog --refresh rm "$D/settings/allow/auto_stage_updates" # ---- HMG-API's own release diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index e3741866..ccc4c23c 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -347,6 +347,7 @@ printf 10.10.10.100 > "$F/fw/props/dhcp.wlan0.dns1" log=$(wk) has "up" "home Wi-Fi up: the mods that asked go through it; the car stays on mobile data" "$log" check "... the update check started, once" "update check" "$(cat "$X/data/hmgapi/wifi/update-check.test")" +has "... after wifi.json says up (the engine reads it to know it's online)" '"state": "up"' "$(cat "$X/data/hmgapi/wifi/update-check.pub")" mkdir -p "$X/proc/sys/net/ipv4/conf/wlan0"; wk >/dev/null check "... not again while still up" 1 "$(grep -c . "$X/data/hmgapi/wifi/update-check.test")" check "status: up, signal, channel, no network name" '{"state": "up", "rssi": -61, "freq": 2437}' "$(pub)" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index ddcc541f..84157ff7 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -1609,8 +1609,54 @@ static void stagedReport(Engine e) { * this HMG-API) and put in place, the version it replaces kept in /data/hmgapi/previous/. * Returns the ids put in place (stagedBack undoes them if the apply doesn't go ahead). */ + /** + * The staged updates an apply put in mods/ (each one's previous version in previous/), kept in + * state/staged-swap.json from before the first is moved until the apply is final: a cut-off apply + * or a trial that's undone puts them back (engine recover), as it does the /system files. + */ + static File swapFile(Engine e) { + return new File(e.stateDir, "staged-swap.json"); + } + + @SuppressWarnings("unchecked") + static List swapped(Engine e) { + List ids = new ArrayList(); + try { + if (!swapFile(e).isFile()) return ids; + Object l = Json.object(Engine.read(swapFile(e))).get("ids"); + for (Object o : l instanceof List ? (List) l : new ArrayList()) if (String.valueOf(o).matches(ID)) ids.add(String.valueOf(o)); + } catch (Exception x) { + // unreadable: as if none (mods/ and previous/ stay as they are) + } + return ids; + } + + static void recordSwap(Engine e, List ids) throws IOException { + Map m = new LinkedHashMap(); + m.put("ids", ids); + writeWhole(swapFile(e), Json.write(m), false); + } + + /** the apply that took them is final (not a trial, or a trial kept): nothing to put back any more */ + static void stagedDone(Engine e) { + swapFile(e).delete(); + } + + /** engine recover: staged updates a cut-off apply or an undone trial left in mods/ go back to pending/ */ + static void stagedRecover(Engine e) { + List ids = swapped(e); + if (ids.isEmpty()) { + swapFile(e).delete(); + return; + } + stagedBack(e, ids); + for (String id : ids) e.out.add("rolled back the staged update of " + id + " (its previous version is installed again)"); + } + static List stagedIn(Engine e) throws Exception { List done = new ArrayList(); + Catalog c = new Catalog(e); + c.load(); File[] ps = new File(e.data, "pending").listFiles(); if (ps != null) Arrays.sort(ps); for (File p : ps == null ? new File[0] : ps) { @@ -1624,6 +1670,7 @@ static List stagedIn(Engine e) throws Exception { if (want == null) why = "it isn't a mod"; else if (have == null) why = id + " was removed since"; else if (!"update".equals(status(have, want))) why = "the installed " + have + " is as new"; + else if (c.withdrawn(id, want) != null) why = "HMG-API's maintainers withdrew it since (" + c.withdrawn(id, want) + ")"; else { Packages.Verdict v = Packages.check(e, p, Packages.installedUuid(inst), false, false); if (v.code != 0) why = v.reason; @@ -1636,6 +1683,8 @@ static List stagedIn(Engine e) throws Exception { File prev = new File(e.data, "previous/" + id); Engine.rm(prev); prev.getParentFile().mkdirs(); + done.add(id); + recordSwap(e, done); // before the move: a cut-off apply finds it and puts it back boolean off = new File(inst, ".disabled").exists(); if (!inst.renameTo(prev)) throw new IOException("can't move the installed " + id + " aside"); if (!p.renameTo(inst)) { @@ -1645,8 +1694,8 @@ static List stagedIn(Engine e) throws Exception { if (off) new File(inst, ".disabled").createNewFile(); e.chmodTree(inst); e.out.add("update " + id + " " + have + " -> " + want + " (staged by the automatic check; " + have + " kept in /data/hmgapi/previous/" + id + ")"); - done.add(id); } + if (done.isEmpty()) swapFile(e).delete(); return done; } @@ -1654,6 +1703,12 @@ static List stagedIn(Engine e) throws Exception { static void stagedBack(Engine e, List ids) { for (String id : ids) { File inst = new File(e.data, "mods/" + id), prev = new File(e.data, "previous/" + id), pend = new File(e.data, "pending/" + id); + if (!prev.isDirectory() && !inst.isDirectory() && pend.isDirectory()) continue; // cut off before its move: still staged + if (!prev.isDirectory() && inst.isDirectory() && pend.isDirectory()) continue; // cut off before its move: the old one is still in mods/ + if (prev.isDirectory() && !inst.isDirectory() && pend.isDirectory()) { // cut off between the moves: the old one back + if (!prev.renameTo(inst)) e.out.add("couldn't put " + id + "'s previous version back: it's in /data/hmgapi/previous/" + id); + continue; + } Engine.rm(pend); if (!prev.isDirectory() || !inst.renameTo(pend) || !prev.renameTo(inst)) { e.out.add("couldn't put " + id + "'s previous version back: the staged one stays installed"); @@ -1662,5 +1717,6 @@ static void stagedBack(Engine e, List ids) { new File(pend, ".disabled").delete(); } if (!ids.isEmpty()) e.out.add("the staged updates (" + join(ids, ", ") + ") stay staged until an apply goes through"); + swapFile(e).delete(); } } diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index df4c43aa..cd500363 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -399,7 +399,7 @@ int run(String[] args) throws Exception { return 0; } if ("install".equals(cmd) || "remove".equals(cmd)) { - if (journalFile.exists()) { + if (journalFile.exists() || Catalog.swapFile(this).exists()) { out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); return 1; } @@ -432,7 +432,7 @@ int run(String[] args) throws Exception { if ("recover".equals(cmd)) return recover(); if ("keep".equals(cmd)) return keep(); if ("firmware-reset".equals(cmd)) return firmwareReset(); - if (journalFile.exists() && !"keep".equals(cmd)) { + if ((journalFile.exists() || Catalog.swapFile(this).exists()) && !"keep".equals(cmd)) { out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); return 1; } @@ -475,6 +475,7 @@ int run(String[] args) throws Exception { if ("plan".equals(cmd)) return 0; if (p.isEmpty()) { out.add("nothing to do"); + if ("apply".equals(cmd)) Catalog.stagedDone(this); // the staged updates changed no /system file: they're in for good if ("apply".equals(cmd)) LiveState.publish(this); // a switch with no file change still reaches running apps return 0; } @@ -486,6 +487,8 @@ int run(String[] args) throws Exception { Catalog.stagedBack(this, staged); throw x; } + // a trial's staged updates stay on the record with it: `engine keep` keeps them, undoing the trial puts them back + if (!trial) Catalog.stagedDone(this); LiveState.publish(this); return 0; } @@ -2154,6 +2157,7 @@ int keep() throws Exception { } journalFile.delete(); rm(prevDir); + Catalog.stagedDone(this); out.add("kept"); return 0; } @@ -2161,6 +2165,10 @@ int keep() throws Exception { @SuppressWarnings("unchecked") int recover() throws Exception { if (!journalFile.exists()) { + if (Catalog.swapFile(this).exists()) { // cut off after staged updates went in, before its journal: those go back + Catalog.stagedRecover(this); + return 0; + } out.add("nothing to recover"); return 0; } @@ -2186,6 +2194,7 @@ int recover() throws Exception { write(stateFile, Json.write(j.get("state"))); journalFile.delete(); rm(prevDir); + Catalog.stagedRecover(this); // the mod code that went in with it goes too out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); return 0; } diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index 38644925..72c49c6c 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -289,7 +289,7 @@ static List describe(Engine e, Map> json, Se "# HMG-API's update check, once each time home Wi-Fi comes up (Catalog: the catalogue, nothing installed", "# unless the owner chose that); off with the owner's switch no_update_check", "update_check() {", - " [ -z \"$X\" ] || { echo \"update check\" >> $W/update-check.test; return; }", + " [ -z \"$X\" ] || { echo \"update check\" >> $W/update-check.test; cp $PUB $W/update-check.pub; return; }", " [ -f /data/hmgapi/settings/allow/no_update_check ] && return", " (hmgapid engine update-check >/dev/null 2>&1 &)", "}", @@ -319,7 +319,7 @@ static List describe(Engine e, Map> json, Se " iptables -F HMGAPI_HOMELO 2>/dev/null # the guard for the new server: lo_guard builds it", " echo \"$gw $d1\" > $W/lease", " say \"home Wi-Fi up: the mods that asked go through it; the car stays on mobile data\"", - " update_check", + " fresh=1 # the update check, once wifi.json says up (the engine reads it to see it's online)", " fi", " # checked on every pass, not only when the lease changes: the stock firewall (iptrules) restarting", " # flushes INPUT and can put its own rules first", @@ -479,6 +479,7 @@ static List describe(Engine e, Map> json, Se " if [ \"$(echo \"$st\" | field wpa_state)\" = COMPLETED ] && route_up; then", " rssi=$(wpa SIGNAL_POLL | field RSSI)", " status up \"$rssi\" \"$(echo \"$st\" | field freq)\"", + " [ -z \"$fresh\" ] || { fresh=; update_check; }", " else", " [ -f $W/lease ] && { route_down; say \"home Wi-Fi lost\"; }", " status searching", diff --git a/install/common/boot.sh b/install/common/boot.sh index 6128e957..f0d197bc 100644 --- a/install/common/boot.sh +++ b/install/common/boot.sh @@ -32,7 +32,8 @@ if [ -x $ROOT/system/xbin/nemesis ]; then (sleep 120; $H engine nemesis-sync) $D/map-local.log 2>&1 & fi -if [ -f $D/state/journal.json ]; then +# a journal, or staged updates an apply put in mods/ (state/staged-swap.json) before it was cut off +if [ -f $D/state/journal.json ] || [ -f $D/state/staged-swap.json ]; then # Restart only after a recover that finished (it takes the journal away). One that # failed part-way has "rolled back" in its log too and keeps the journal: restarting # on that would come straight back here, at every start. It's tried again at the From 6703880cf17de547c1ce7961bd0060a1f299ed29 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 29 Nov 2026 18:56:45 -0500 Subject: [PATCH 08/10] Catalogue: say "mod zip", not "package" (NEMESIS has packages) The messages, docs and comments this PR adds call the file a mod zip (or just the zip), so it isn't confused with a NEMESIS package. Lines from main are left as they are. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++--- core/fetch/fetch.c | 4 +-- core/runtime/catalog-test.sh | 24 +++++++------- core/runtime/java/hmgapi/engine/Catalog.java | 32 +++++++++---------- .../java/hmgapi/engine/NativeFetch.java | 2 +- core/runtime/java/hmgapi/engine/Releases.java | 6 ++-- core/runtime/java/hmgapi/engine/Sha256.java | 2 +- tools/catalog-test.sh | 2 +- tools/catalog.py | 8 ++--- 9 files changed, 44 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82845c44..a426e0cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,14 +3,14 @@ ## Unreleased - **Dependencies are installed with a mod.** A mod's `requires` (copied into its catalogue - entry by `catalog.py add`, and read again from the downloaded package's `mod.json`) are met + entry by `catalog.py add`, and read again from the downloaded zip's `mod.json`) are met by what's installed, or by the catalogue's version, installed first; a required mod that's turned off is turned on. Loops, conflicts, a requirement newer than the catalogue's or not in it, an unreadable range, and a mod for a newer HMG-API are refused before anything is downloaded or installed. The result is checked as a whole: every mod that will be on keeps what it requires (an update that breaks another mod's range is refused), and conflicts count - whichever side lists them. Every package is downloaded and checked (SHA-256, signature, - author key, HMG-API, car) before the first install. When a package requires more than the + whichever side lists them. Every mod zip is downloaded and checked (SHA-256, signature, + author key, HMG-API, car) before the first install. When a mod zip requires more than the plan said, nothing is installed and the new plan is shown for a second OK. Removing a mod others require says which won't load. - **A first install from the catalogue needs a known author.** The catalogue isn't signed, so @@ -52,7 +52,7 @@ - **HMG-API's own HTTPS** (`/data/hmgapi/lib/libhmgapi_fetch.so`, `core/fetch`): Android 4.4's Java TLS can't reach GitHub, so the engine uses the unit's own `libssl.so` (TLS 1.2), on a socket marked for home Wi-Fi only, with its own DNS lookup on home Wi-Fi's server. Tested - first as a mod on an Ioniq 5 US 260507 (HMG-API rc.10): the catalogue and three packages + first as a mod on an Ioniq 5 US 260507 (HMG-API rc.10): the catalogue and three mods over home Wi-Fi, each with its SHA-256. Each socket has home Wi-Fi's mark and is bound to `wlan0`, or the call fails (never an unmarked socket on the main table's mobile data, even before the fwmark rule is in), with 20 s send and receive timeouts (connect, the handshake, diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c index 10bc561f..d6f851f0 100644 --- a/core/fetch/fetch.c +++ b/core/fetch/fetch.c @@ -1,5 +1,5 @@ /* libhmgapi_fetch.so: one HTTPS request, or one DNS query, for HMG-API's engine (hmgapi.engine.NativeFetch): - * the catalogue, mod packages and HMG-API releases, over home Wi-Fi only (Catalog). + * the catalogue, mod zips and HMG-API releases, over home Wi-Fi only (Catalog). * * Android 4.4's Java TLS shares no cipher suite with GitHub, but the unit's own libssl.so * (OpenSSL 1.0.1) has TLS 1.2 with ECDHE and AES-GCM. This opens a TCP connection, does the @@ -9,7 +9,7 @@ * * The server's certificate is NOT checked here: the unit's 2013 root store doesn't know GitHub's * roots and its clock isn't reliable. Nothing fetched is trusted because of where it came from: - * a package must have the SHA-256 its catalogue entry names, and the engine checks its signature + * a mod zip must have the SHA-256 its catalogue entry names, and the engine checks its signature * (the installed mod's author key; HMG-API's release key for HMG-API itself) and refuses a * downgrade. A hostile network can make a check find nothing, not get code installed. * diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index ebf2cdc2..2cc08141 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -1,10 +1,10 @@ #!/bin/sh # Off-car test of the catalogue and updates (Catalog): the catalogue fetched (index.json, or GitHub's # folder listing; a bad index, an entry that doesn't come), what each mod would do here, dependencies -# (requires installed first, a required mod that's off turned on, requires only the package names and +# (requires installed first, a required mod that's off turned on, requires only the zip names and # a second OK for them, loops, conflicts either way, the result as a whole, unreadable ranges, what # isn't in the catalogue), trust (a first install's key must be on the unit's list, or the owner's yes -# per mod), every download checked before the first install (SHA-256, the package being what the entry +# per mod), every download checked before the first install (SHA-256, the zip being what the entry # says, the author key), the owner's any-car choice per mod, updates (mods and HMG-API's own release, # its pre-releases, mods it would leave behind), the automatic check (every 6 hours, staging only pure # updates aside until apply), mods outside the catalogue updated from their own GitHub releases (by @@ -38,7 +38,7 @@ CAT=$W/raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog DL=$W/github.com/test/releases/download mkdir -p "$CAT" "$DL" "$W/objects.githubusercontent.com/r" -# pkg [key]: a signed package, served from a release (through GitHub's +# pkg [key]: a signed mod zip, served from a release (through GitHub's # redirect to its asset host), and its catalogue entry (extras for the entry: $ENTRY; its author key: $EUUID, else the trusted one) pkg() { rm -rf $T/m; mkdir -p $T/m @@ -121,20 +121,20 @@ check "install tool" 0 $rc has "... base turned on for it" "turned on base 1.0.0 (tool needs it)" "$out" check "... base on" no "$([ -f $D/mods/base/.disabled ] && echo yes || echo no)" -# ---- the package requires more than its entry says (an older entry): learned, installed first +# ---- the zip requires more than its entry says (an older entry): learned, installed first pkg helper 1.0.0 pkg extra 1.0.0 ', "requires": ["helper"]'; listing eng catalog --refresh eng catalog-install extra check "install extra: the plan the owner saw missed a step, so stopped for a second OK" 5 $rc -has "... said why" "the packages require more than the catalogue says" "$out" +has "... said why" "the mod zips require more than the catalogue says" "$out" check "... the new plan handed back" "helper install extra|extra install None" "$(j '"|".join(s["id"]+" "+s["action"]+" "+str(s.get("for")) for s in d["steps"])')" check "... nothing installed" "none none" "$(installed helper) $(installed extra)" eng catalog-plan extra -check "... the next plan has it (learned from the package)" "helper extra" "$(j '" ".join(s["id"] for s in d["steps"])')" +check "... the next plan has it (learned from the zip)" "helper extra" "$(j '" ".join(s["id"] for s in d["steps"])')" eng catalog-install extra check "install extra again" 0 $rc -has "... helper, which only the package names, installed" "installing helper 1.0.0 (extra needs it)" "$out" +has "... helper, which only the zip names, installed" "installing helper 1.0.0 (extra needs it)" "$out" check "... both" "1.0.0 1.0.0" "$(installed helper) $(installed extra)" # ---- what can't be met: nothing installed @@ -413,7 +413,7 @@ eng catalog-plan peace check "... an installed mod's bad range doesn't stop other installs" True "$(j 'd["ok"]')" rm -r "$D/mods/oddrange" -# ---- every package checked before the first one goes in +# ---- every mod zip checked before the first one goes in pkg dep 1.0.0 ENTRY=', "requires": ["dep"]'; pkg top 1.0.0 ', "requires": ["dep"]' $T/other.key listing; eng catalog --refresh @@ -516,7 +516,7 @@ rm "$W/raw.githubusercontent.com.down" # ---- mods outside the catalogue: updates from their own GitHub releases (mod.json "repo") rm -f "$CAT/index.json"; listing -# rpkg [key]: a signed package as a release asset; sets $ZSHA, $ZSIZE +# rpkg [key]: a signed mod zip as a release asset; sets $ZSHA, $ZSIZE rpkg() { rm -rf $T/m; mkdir -p $T/m printf '{"id": "%s", "name": "%s mod", "version": "%s", "hmgapi": ">=1.0.0", "repo": "https://github.com/%s"%s}\n' "$2" "$2" "$3" "$1" "$4" > $T/m/mod.json @@ -569,7 +569,7 @@ eng update side check "no SHA-256 given: the signature decides" "0 1.3.0" "$rc $(installed side)" has "... said so" "no SHA-256 given: its signature decides" "$out" -# SHA256SUMS in the release, a zip by another key (as a key change), a package that isn't the tag's version +# SHA256SUMS in the release, a zip by another key (as a key change), a zip that isn't the tag's version rpkg dev/side side 1.4.0 '' $T/other.key printf '%s side-1.4.0.zip\n' "$ZSHA" > "$W/github.com/dev/side/releases/download/v1.4.0/SHA256SUMS" releases dev/side "$(rel dev/side v1.4.0 false "$(asset dev/side v1.4.0 side-1.4.0.zip $ZSIZE ''),$(asset dev/side v1.4.0 SHA256SUMS 80 '')")" @@ -583,8 +583,8 @@ mkdir -p $W/github.com/dev/side/releases/download/v1.5.0; mv $W/github.com/dev/s releases dev/side "$(rel dev/side v1.5.0 false "$(asset dev/side v1.5.0 side-1.5.0.zip $ZSIZE '')")" eng updates --refresh eng update side -check "a package that isn't the release's version: refused" 1 $rc -has "... why" "the package is side 1.6.0" "$out" +check "a zip that isn't the release's version: refused" 1 $rc +has "... why" "the zip is side 1.6.0" "$out" # too large, no matching zip, a download from elsewhere: not offered, with a note releases dev/side "$(rel dev/side v1.7.0 false "$(asset dev/side v1.7.0 side-1.7.0.zip 99999999999 '')")" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index 84157ff7..96ccf4b8 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -52,10 +52,10 @@ * A maintainer can stop a version on both: catalog/withdrawn.json (withdrawn()). * * Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and from the - * downloaded package's mod.json (kept in learned.json, so the next plan has them); each is met by + * downloaded zip's mod.json (kept in learned.json, so the next plan has them); each is met by * what's installed, or by the catalogue's version, installed first. A required mod that's turned off * is turned on. After planning, every mod that will be on is checked against the result: its - * requires met, and no conflicts either way. When a package requires more than the plan the owner + * requires met, and no conflicts either way. When a mod zip requires more than the plan the owner * saw, nothing is installed and the new plan is handed back (exit 5) for a second OK. * * The automatic check stages only pure updates (nothing else installed or turned on, signed with the @@ -72,7 +72,7 @@ final class Catalog { static final long STALE_MS = 15 * 60 * 1000L; /** update-check: at most one every 6 hours (each is 2 of GitHub's 60 API calls an hour, and one per repo of mods updated from their releases) */ static final long CHECK_GAP_S = 6 * 3600; - /** catalog-install / update: the packages require more than the plan said; the new plan is in the output */ + /** catalog-install / update: the mod zips require more than the plan said; the new plan is in the output */ static final int PLAN_CHANGED = 5; static final String FROM_CATALOGUE = "catalogue", FROM_RELEASES = "releases", FROM_NONE = "off"; @@ -826,7 +826,7 @@ static void updatesChanged(Engine e) { } } - // ---- what the downloaded packages said: requires and conflicts their entries didn't have + // ---- what the downloaded zips said: requires and conflicts their entries didn't have @SuppressWarnings("unchecked") Map learned() { @@ -842,7 +842,7 @@ static String key(Map en) { return en.get("id") + " " + en.get("version") + " " + en.get("sha256"); } - /** keeps the package's requires and conflicts for its entry (this exact download); true if the plan didn't know one */ + /** keeps the zip's requires and conflicts for its entry (this exact download); true if the plan didn't know one */ @SuppressWarnings("unchecked") boolean learn(Plan p, Step s, Map mj) throws IOException { boolean more = false; @@ -856,7 +856,7 @@ boolean learn(Plan p, Step s, Map mj) throws IOException { one.put("requires", mj.get("requires") instanceof List ? mj.get("requires") : new ArrayList()); one.put("conflicts", mj.get("conflicts") instanceof List ? mj.get("conflicts") : new ArrayList()); all.put(key(s.entry), one); - for (String old : new ArrayList(all.keySet())) { // only the current entries' packages are kept + for (String old : new ArrayList(all.keySet())) { // only the current entries' zips are kept Map en = p.cat.get(old.split(" ")[0]); if (en == null || !old.equals(key(en))) all.remove(old); } @@ -932,7 +932,7 @@ Step planned(String id) { return null; } - /** a dependency list from an entry or a package: an unreadable one (bad id or range) is a problem */ + /** a dependency list from an entry or a mod zip: an unreadable one (bad id or range) is a problem */ List checked(Object list, String owner, String what, List into) { for (Version.Dep d : deps(list)) { String bad = !d.id.matches(ID) ? "\"" + d.id + "\" isn't a mod id" : d.range == null ? null : Version.rangeError(d.range); @@ -1074,7 +1074,7 @@ void add(Step s) { /** * The result as a whole: every mod that will be on has what it requires, on and in range, and no mod * that will be on conflicts with another, whichever side lists it. Only what this plan changes is - * checked (what was already broken isn't this install's to refuse). pkgs: the downloaded packages' + * checked (what was already broken isn't this install's to refuse). pkgs: the downloaded zips' * mod.json, by id, once there are any. */ void settle(Map> pkgs) { @@ -1199,7 +1199,7 @@ static String join(List l, String sep) { // ---- doing it: everything downloaded and checked first, then installed in order - /** downloads one step's package into dl, checks its SHA-256 and that it is what the entry says, unzips it; null, or why not */ + /** downloads one step's mod zip into dl, checks its SHA-256 and that it is what the entry says, unzips it; null, or why not */ @SuppressWarnings("unchecked") String fetch(Http http, File dl, Step s, Map> pkgs) throws Exception { File z = new File(dl, s.id + "-" + s.version + ".zip"); @@ -1223,7 +1223,7 @@ String fetch(Http http, File dl, Step s, Map> pkgs) } z.delete(); if (mj == null || !s.id.equals(mj.get("id")) || !s.version.equals(String.valueOf(mj.get("version")))) { - return "refused " + s.id + " " + s.version + ": the package is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")); + return "refused " + s.id + " " + s.version + ": the zip is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")); } pkgs.put(s.id, mj); e.out.add("downloaded " + s.id + " " + s.version + (!rel ? " (SHA-256 as the catalogue's)" : want != null ? " from its release (SHA-256 as the release's)" @@ -1277,13 +1277,13 @@ int execute(Plan p) throws Exception { } more |= learn(p, s, pkgs.get(s.id)); } - // a package can require more than its entry says (an entry from before catalog.py copied requires): + // a mod zip can require more than its entry says (an entry from before catalog.py copied requires): // its own mod.json is the truth. If that changes what this takes, the owner sees the new plan first. if (more) { Plan q = p.skipped.isEmpty() ? plan(p.wanted, p.update, p.ov) : planEach(p.wanted, p.ov); if (!q.problems.isEmpty() || !q.sameAs().equals(p.sameAs())) { - e.out.add(q.problems.isEmpty() ? "the packages require more than the catalogue says, so this takes more steps:" - + " nothing was installed. Check the new plan and install again" : "can't, with what the packages require:"); + e.out.add(q.problems.isEmpty() ? "the mod zips require more than the catalogue says, so this takes more steps:" + + " nothing was installed. Check the new plan and install again" : "can't, with what the mod zips require:"); for (String x : q.problems) e.out.add("can't: " + x); if (q.problems.isEmpty()) e.out.add("(nothing was installed)"); e.out.add(Json.write(q.toJson())); @@ -1296,7 +1296,7 @@ int execute(Plan p) throws Exception { e.out.add("(nothing was installed)"); return 1; } - // every package checked as its install will check it (signature, author key, HMG-API, car), before the first goes in + // every mod zip checked as its install will check it (signature, author key, HMG-API, car), before the first goes in for (Step s : p.steps) { if ("enable".equals(s.action)) continue; Packages.Verdict v = Packages.check(e, s.dir, String.valueOf(s.entry.get("uuid")), false, p.ov.car(s.id)); @@ -1360,7 +1360,7 @@ static boolean needsDownload(Plan p) { return false; } - /** the package's mod.json (at its top, or in its one folder), or null */ + /** the zip's mod.json (at its top, or in its one folder), or null */ @SuppressWarnings("unchecked") static Map modJson(File zip) { ZipFile z = null; @@ -1559,7 +1559,7 @@ String stage(String id) throws Exception { if (learn(p, s, pkgs.get(id))) { Plan q = plan(Arrays.asList(id), true, null); why = pure(q, id); - if (why != null) return why + " (as its package says)"; + if (why != null) return why + " (as its mod zip says)"; } p.settle(pkgs); if (!p.problems.isEmpty()) return join(p.problems, "; "); diff --git a/core/runtime/java/hmgapi/engine/NativeFetch.java b/core/runtime/java/hmgapi/engine/NativeFetch.java index 4320613e..d964d033 100644 --- a/core/runtime/java/hmgapi/engine/NativeFetch.java +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -10,7 +10,7 @@ * The engine's HTTPS on the unit: /data/hmgapi/lib/libhmgapi_fetch.so (core/fetch/fetch.c), over the * unit's own libssl, its socket marked for home Wi-Fi. The server's certificate isn't checked * (the unit's root store and clock can't be relied on): Catalog trusts a download only through - * the SHA-256 its catalogue entry names and the package's signature, which the engine checks. + * the SHA-256 its catalogue entry names and the zip's signature, which the engine checks. * * Off the car (the tests) Web stands in for it: HMGAPI_TEST_WEB= serves //. */ diff --git a/core/runtime/java/hmgapi/engine/Releases.java b/core/runtime/java/hmgapi/engine/Releases.java index 05debe07..091ae731 100644 --- a/core/runtime/java/hmgapi/engine/Releases.java +++ b/core/runtime/java/hmgapi/engine/Releases.java @@ -17,7 +17,7 @@ * (installed from USB or adb, a private mod, one waiting for its catalogue PR), or one whose owner * chose its releases (a test build from a fork, an entry that fell behind). * - * Where to look: "repo" in the installed mod's own mod.json. It came inside the signed package, so + * Where to look: "repo" in the installed mod's own mod.json. It came inside the signed zip, so * only the author's key chose it. Which zip: "release_asset" in mod.json ("my-mod-v{version}.zip"), * else the one .zip asset named "-...". Each mod's update source (Catalog.source): the owner's * choice (engine update-source), else the catalogue when it lists the mod, else its releases when @@ -26,7 +26,7 @@ * Each release found becomes an entry shaped like a catalogue entry ("source": "release"), kept in * /data/hmgapi/catalog/releases.json, so planning, staging and installing are the catalogue's own. * Trust is the installed mod's author key: a release is only ever an update by that key (never a - * first install, a key change or a downgrade), checked by Packages as any update is; the package's + * first install, a key change or a downgrade), checked by Packages as any update is; the zip's * id and version must be the release's; its SHA-256 is checked when the release gives one * (SHA256SUMS, or the asset's digest). That is what catalog-automerge.yml takes for a catalogue * entry with no one looking: a newer version from the mod's own repo's releases, the same key. @@ -262,7 +262,7 @@ static Map newest(Catalog c, Http http, File tmp, Mod m, List rel, String repo) { Object page = rel.get("html_url"); diff --git a/core/runtime/java/hmgapi/engine/Sha256.java b/core/runtime/java/hmgapi/engine/Sha256.java index cf072ff7..e6caab99 100644 --- a/core/runtime/java/hmgapi/engine/Sha256.java +++ b/core/runtime/java/hmgapi/engine/Sha256.java @@ -1,7 +1,7 @@ package hmgapi.engine; /** - * SHA-256 (FIPS 180-4) in plain Java, for the catalogue's package checksums. Under app_process, + * SHA-256 (FIPS 180-4) in plain Java, for the catalogue's download checksums. Under app_process, * Android 4.4's MessageDigest SHA-256 can be missing (Conscrypt's class didn't load in a mod's * service on an Ioniq 5 US 260507), so the downloads don't depend on it. */ diff --git a/tools/catalog-test.sh b/tools/catalog-test.sh index e21550b0..4cc20cf4 100755 --- a/tools/catalog-test.sh +++ b/tools/catalog-test.sh @@ -201,7 +201,7 @@ G checkout -q main; G checkout -qb pr2; bump_entry $T/h2.zip "d['description']=d J $R/catalog/hello.json "d['name']='Hi'" B name; check "bump: another field changed refused" 1 $rc; has "says why" "changes name" "$out" G checkout -q main; G checkout -qb pr3; bump_entry $T/h2.zip "d['description']='Something else'" -B desc; check "bump: a description not the package's refused" 1 $rc; has "says why" "the description isn't the package's" "$out" +B desc; check "bump: a description not the package's refused" 1 $rc; has "says why" "the description isn't the zip's" "$out" G checkout -q main; G checkout -qb pr4; DESC='Says hi, louder' pkg hd 1.1.0 $T/a.key $T/hd.zip; bump_entry $T/hd.zip "d['description']='Says hi, louder'" B desc-ok; check "bump: the package's description" 0 $rc G checkout -q main; G checkout -qb pr5; bump_entry $T/h2.zip "d['download']='https://github.com/example/fork/releases/download/v1.1.0/hello.zip'" diff --git a/tools/catalog.py b/tools/catalog.py index 87445d2a..bef81a33 100755 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -42,7 +42,7 @@ FINAL = re.compile(r'^\d+\.\d+\.\d+$') # what an entry's "version" is: no pre-releases (docs/releasing.md) HTTPS = re.compile(r'^https://[A-Za-z0-9.-]+(:\d+)?/[^\s<>()\[\]"\']*$') FIELDS = {'id', 'name', 'description', 'authors', 'license', 'uuid', 'version', 'repo', 'download', 'sha256', 'system', 'hmgapi', - 'requires', 'conflicts', 'wifi'} # requires/conflicts: as the package's mod.json (HMG-API's catalogue installs requires first); + 'requires', 'conflicts', 'wifi'} # requires/conflicts: as the zip's mod.json (HMG-API's catalogue installs requires first); # wifi: {"hotspot": true} as mod.json (a chip the unit never powers will do, SystemCheck) # the only hosts the head unit downloads from (Http.HOSTS): a download anywhere else could never install GITHUB = {'github.com', 'api.github.com', 'raw.githubusercontent.com', 'objects.githubusercontent.com', @@ -446,12 +446,12 @@ def cmd_bump(a): elif changed & {'description', 'requires', 'conflicts', 'wifi'}: pm = load(os.path.join(unpack(z, os.path.join(work, 'mod')), 'mod.json')) if 'description' in changed and pm.get('description', '') != new['description']: - no.append(f'{files[0]}: the description isn\'t the package\'s mod.json description') + no.append(f'{files[0]}: the description isn\'t the zip\'s mod.json description') if 'wifi' in changed and (new.get('wifi') or None) != ({'hotspot': True} if (pm.get('wifi') or {}).get('hotspot') is True else None): - no.append(f'{files[0]}: "wifi" isn\'t the package\'s mod.json "wifi.hotspot"') + no.append(f'{files[0]}: "wifi" isn\'t the zip\'s mod.json "wifi.hotspot"') for k in ('requires', 'conflicts'): if k in changed and (pm.get(k) or None) != (new.get(k) or None): - no.append(f'{files[0]}: "{k}" isn\'t the package\'s mod.json "{k}"') + no.append(f'{files[0]}: "{k}" isn\'t the zip\'s mod.json "{k}"') finally: shutil.rmtree(work, ignore_errors=True) for x in no: From 0b82eaa30a09ec3a95b5bd9d7224bb7bfb3618bd Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Mon, 30 Nov 2026 16:42:29 -0500 Subject: [PATCH 09/10] Catalogue: the apply's journal carries its staged updates (no power-cut window) Review: a non-trial apply deleted its journal, and only afterwards did run() remove staged-swap.json; a cut between the two made recover put the old mod code back over the new /system files. Now apply() writes the staged ids into the journal ("staged") and deletes staged-swap.json right after, so deleting the journal makes the staged updates final with the files in one step, and recover puts them back from the journal. staged-swap.json only covers the moments before the journal is written. Tests: a cut-off apply with the ids only on the journal, and a finished apply (no journal, no record) that recover leaves alone. Co-Authored-By: Claude Opus 5.5 --- core/runtime/catalog-test.sh | 15 +++++++++++++++ core/runtime/java/hmgapi/engine/Catalog.java | 13 +++++++++---- core/runtime/java/hmgapi/engine/Engine.java | 15 +++++++++++++-- 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index 2cc08141..0cd1e554 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -258,6 +258,21 @@ J eng recover check "a trial undone: the staged update goes back with it" "1.1.0 1.2.0 no" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])") $([ -f $D/state/staged-swap.json ] && echo yes || echo no)" has "... trial undone" "trial undone" "$out" +# from the journal on, it carries the staged updates (no record of their own): cut off mid-apply +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": False, "committed": False, "entries": [], "state": st, "staged": ["helper"]}, open(os.path.join(d, "journal.json"), "w")) +J +eng recover +check "cut off mid-apply, the staged update only on the journal: recover puts it back" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +has "... says so" "rolled back the staged update of helper" "$out" +# the journal deleted (the apply is final): nothing left to put back, even before the run's own clean-up +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper" +eng recover +check "an apply that finished (no journal, no record): recover leaves the update in" "nothing to recover 1.2.0" "$out $(installed helper)" +mv "$D/mods/helper" "$D/pending/helper"; mv "$D/previous/helper" "$D/mods/helper" # withdrawn after it was staged: dropped at the apply, not put in echo '{"withdrawn": [{"id": "helper", "versions": "1.2.0", "why": "breaks the cluster"}]}' > "$CAT/withdrawn.json" diff --git a/core/runtime/java/hmgapi/engine/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java index 96ccf4b8..4717d974 100644 --- a/core/runtime/java/hmgapi/engine/Catalog.java +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -1611,8 +1611,9 @@ static void stagedReport(Engine e) { */ /** * The staged updates an apply put in mods/ (each one's previous version in previous/), kept in - * state/staged-swap.json from before the first is moved until the apply is final: a cut-off apply - * or a trial that's undone puts them back (engine recover), as it does the /system files. + * state/staged-swap.json from before the first is moved until the apply's journal is written, which + * then carries them ("staged"): a cut-off apply or a trial that's undone puts them back (engine + * recover), as it does the /system files, and deleting the journal makes them final with those. */ static File swapFile(Engine e) { return new File(e.stateDir, "staged-swap.json"); @@ -1642,9 +1643,13 @@ static void stagedDone(Engine e) { swapFile(e).delete(); } - /** engine recover: staged updates a cut-off apply or an undone trial left in mods/ go back to pending/ */ - static void stagedRecover(Engine e) { + /** + * engine recover: staged updates a cut-off apply or an undone trial left in mods/ go back to pending/: + * those its journal names (fromJournal), and any still only on their own record (cut off before the journal) + */ + static void stagedRecover(Engine e, List fromJournal) { List ids = swapped(e); + for (String id : fromJournal) if (id.matches(ID) && !ids.contains(id)) ids.add(id); if (ids.isEmpty()) { swapFile(e).delete(); return; diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index cd500363..0d2823c7 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -449,6 +449,7 @@ int run(String[] args) throws Exception { } // updates the automatic check staged (pending/): in place right before an apply plans, never earlier List staged = "apply".equals(cmd) ? Catalog.stagedIn(this) : new ArrayList(); + stagedNow = staged; if ("plan".equals(cmd)) Catalog.stagedReport(this); Plan p; try { @@ -1854,6 +1855,9 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply + /** the staged updates this apply put in place (Catalog.stagedIn): its journal carries them */ + List stagedNow = new ArrayList(); + @SuppressWarnings("unchecked") void apply(Plan p, boolean trial) throws Exception { Map files = (Map) p.state.get("files"); @@ -1887,7 +1891,12 @@ void apply(Plan p, boolean trial) throws Exception { j.put("committed", false); j.put("entries", entries); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below + // the staged updates go on the journal: from here, deleting it makes them final with the /system + // files in one step, and a recover puts them back with those files; their own record only covered + // the moments before this + j.put("staged", new ArrayList(stagedNow)); write(journalFile, Json.write(j)); + Catalog.swapFile(this).delete(); // files taken as found (changed outside HMG-API): their old backups no longer say what was there for (String path : p.rebased.keySet()) { @@ -2166,7 +2175,7 @@ int keep() throws Exception { int recover() throws Exception { if (!journalFile.exists()) { if (Catalog.swapFile(this).exists()) { // cut off after staged updates went in, before its journal: those go back - Catalog.stagedRecover(this); + Catalog.stagedRecover(this, new ArrayList()); return 0; } out.add("nothing to recover"); @@ -2194,7 +2203,9 @@ int recover() throws Exception { write(stateFile, Json.write(j.get("state"))); journalFile.delete(); rm(prevDir); - Catalog.stagedRecover(this); // the mod code that went in with it goes too + List staged = new ArrayList(); // the mod code that went in with it goes too + if (j.get("staged") instanceof List) for (Object o : (List) j.get("staged")) staged.add(String.valueOf(o)); + Catalog.stagedRecover(this, staged); out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); return 0; } From 5db3ff1f703f54a50213f25b6489426a1340794f Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Wed, 2 Dec 2026 11:25:55 -0500 Subject: [PATCH 10/10] catalog-test: HMG-API's fake newer release is 8.0.0 release/2.0 carries version 1.1.0, so a fake 1.1.0 release was no longer newer and the update offer, its notes and the SHA256SUMS refusal weren't tested. 8.0.0 stays newer through 2.x; the 9.0.0 draft is still there to be skipped. Co-Authored-By: Claude Opus 5.5 --- core/runtime/catalog-test.sh | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh index 0cd1e554..d16e2b02 100644 --- a/core/runtime/catalog-test.sh +++ b/core/runtime/catalog-test.sh @@ -283,23 +283,23 @@ has "... said why" "dropped the staged helper 1.2.0: HMG-API's maintainers withd rm "$CAT/withdrawn.json"; pkg helper 1.1.0; listing; eng catalog --refresh rm "$D/settings/allow/auto_stage_updates" -# ---- HMG-API's own release +# ---- HMG-API's own release (8.0.0: newer than any version this engine will carry; the 9.0.0 draft must be skipped) cat > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" <<'J' [{"tag_name": "v9.0.0", "draft": true, "prerelease": false, "assets": []}, - {"tag_name": "v1.1.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v1.1.0", "body": "What's new in 1.1.0", - "assets": [{"name": "hmgapi-1.1.0-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip"}, - {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS"}]}, + {"tag_name": "v8.0.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v8.0.0", "body": "What's new in 8.0.0", + "assets": [{"name": "hmgapi-8.0.0-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v8.0.0/hmgapi-8.0.0-update.zip"}, + {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v8.0.0/SHA256SUMS"}]}, {"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}] J -mkdir -p $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0 -echo "not a release" > $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip -printf '%s hmgapi-1.1.0-update.zip\n' "$(printf '%064d' 0)" > $W/github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS +mkdir -p $W/github.com/Open-HMG/HMG-API/releases/download/v8.0.0 +echo "not a release" > $W/github.com/Open-HMG/HMG-API/releases/download/v8.0.0/hmgapi-8.0.0-update.zip +printf '%s hmgapi-8.0.0-update.zip\n' "$(printf '%064d' 0)" > $W/github.com/Open-HMG/HMG-API/releases/download/v8.0.0/SHA256SUMS eng updates --refresh -check "HMG-API's newer release offered (not the draft)" 1.1.0 "$(j 'd["hmgapi"]["version"]')" +check "HMG-API's newer release offered (not the draft)" 8.0.0 "$(j 'd["hmgapi"]["version"]')" check "... counted" 1 "$(j 'd["count"]')" -check "... with its release notes, for the app" "What's new in 1.1.0" "$(j 'd["hmgapi"]["notes"]')" +check "... with its release notes, for the app" "What's new in 8.0.0" "$(j 'd["hmgapi"]["notes"]')" eng update hmgapi -has "a release that isn't its SHA256SUMS: refused" "refused HMG-API 1.1.0: the download's SHA-256 is" "$out" +has "a release that isn't its SHA256SUMS: refused" "refused HMG-API 8.0.0: the download's SHA-256 is" "$out" echo '[{"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}]' > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" eng updates --refresh check "only older releases: nothing offered" None "$(j 'd.get("hmgapi")')"