From 95a8ccd07750c466c707642177e98a2ee9e11da0 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 15 Nov 2026 22:15:03 -0500 Subject: [PATCH 01/69] Mod SDK: HMG-API's maps and a plan test for mods The SDK carries maps/ (without the repo's coverage baseline), and test/lib.sh has plan_test [...]: for each car the mod's "system" names that has a map, a fake head unit (stand-ins for the stock files the map was made from, their md5s in the unit's copy of the maps; the features the mods ask for) with the mods on it, and engine plan as that car. It checks the plan's problems (not the stand-ins' files), the mod's "system" (engine plan checks it only for mods with file changes), that the car's map is used, that every declared hook point is mapped and the hooks load, lists the points the mod shares, and checks its native recipes against the required mods' for the same library build (RecipeCheck, in the SDK's test jar). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + build.sh | 10 +- .../test/hmgapi/engine/RecipeCheck.java | 133 +++++++++ docs/mod-reference.md | 19 ++ docs/mod-repos.md | 2 + tools/sdk-test.sh | 69 +++++ tools/sdk/README.txt | 19 +- tools/sdk/lib.sh | 64 +++++ tools/sdk/plan.py | 265 ++++++++++++++++++ 9 files changed, 590 insertions(+), 4 deletions(-) create mode 100644 core/runtime/test/hmgapi/engine/RecipeCheck.java create mode 100644 tools/sdk/plan.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 602c0cae..5d75e594 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## Unreleased + +### Mod SDK + +- **A plan test for mods, with HMG-API's hook maps in the SDK.** The SDK now carries + `maps/`, and `test/lib.sh` has `plan_test [...]`: for each car the + mod's `"system"` names that has a map, it makes a fake head unit (stand-ins for the stock + files, no car files) with the mod and the mods it requires, and runs `engine plan` as + that car. It checks that the plan has no problems, the `"system"` takes the unit, every + hook point the mod declares is mapped, its hooks load, which points it shares with other + mods, and that its native recipes stay clear of a required mod's recipes for the same + library build. Mod repos no longer need HMG-API's source for its maps. + ## 1.1.0-rc.2 (2026-11-15) The second release candidate: fixes from a review of rc.1, nothing new in HMG-API itself. diff --git a/build.sh b/build.sh index d75544e3..f16224b4 100755 --- a/build.sh +++ b/build.sh @@ -138,9 +138,11 @@ sdk() { # the engine on its own (no Android classes): host tests, Signing, ScriptCheck javac --release 8 -Xlint:-options -nowarn -d "$OUT/sdk-build/engine" core/runtime/java/hmgapi/engine/*.java jarof "$OUT/sdk-build/engine" "$S/lib/hmgapi-engine.jar" - # MemRecipeTest: a mod's native recipes on real libraries ( triples) + # MemRecipeTest: a mod's native recipes on real libraries ( triples); + # RecipeCheck: without them, against the recipes of the mods it requires (test/lib.sh plan_test) mkdir -p "$OUT/sdk-build/engine-test" - javac --release 8 -Xlint:-options -nowarn -cp "$OUT/sdk-build/engine" -d "$OUT/sdk-build/engine-test" core/runtime/test/hmgapi/engine/MemRecipeTest.java + javac --release 8 -Xlint:-options -nowarn -cp "$OUT/sdk-build/engine" -d "$OUT/sdk-build/engine-test" \ + core/runtime/test/hmgapi/engine/MemRecipeTest.java core/runtime/test/hmgapi/engine/RecipeCheck.java jarof "$OUT/sdk-build/engine-test" "$S/test/hmgapi-engine-test.jar" cp "$OUT/lpatch-host" "$S/bin/" cp tools/lpatch/lpatch.c tools/lpatch/build.sh "$S/src/lpatch/" @@ -150,6 +152,10 @@ sdk() { cp -r install/nemesis/mod "$S/nemesis/mod" cp install/nemesis/bin/open.sh "$S/nemesis/bin/" cp tools/sdk/lib.sh "$S/test/lib.sh" + cp tools/sdk/plan.py "$S/test/plan.py" + # the hook maps (public: point names and md5s), for test/lib.sh's plan test + cp -r maps "$S/maps" + rm -f "$S/maps/coverage.json" # tools/test-hooks.py's baseline, for the repo only cp tools/sdk/README.txt LICENSE "$S/" cp core/hookpoints/*.json "$S/catalogue/" python3 -c 'import glob,json; [print(p["id"]) for f in sorted(glob.glob("core/hookpoints/*.json")) for p in json.load(open(f))["points"]]' > "$S/points.txt" diff --git a/core/runtime/test/hmgapi/engine/RecipeCheck.java b/core/runtime/test/hmgapi/engine/RecipeCheck.java new file mode 100644 index 00000000..baabd35f --- /dev/null +++ b/core/runtime/test/hmgapi/engine/RecipeCheck.java @@ -0,0 +1,133 @@ +package hmgapi.engine; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A mod's native recipes (mod.json hooks.native) beside other mods' (the ones it requires), + * without the libraries: each recipe parses (MemRecipe, as on the car), and none of its + * verify regions overlaps a region of another mod's recipe for the same library build. + * On the car, an overlapping recipe isn't applied (hmgapi.hook.NativePatch: "conflict + * with ..."), so one of the two mods loses its patch. + * + * A library's recipes in mod.json are alternatives (one per library build; the first that + * fits is applied), so only recipes for the same build are compared. The build is the + * stock md5 the recipe was made from, when the recipe says it ("from stock ", as + * mkrecipe.py and mkmemrecipe.py write it), else the 8 hex digits its id ends with + * (aa-tbt-48ee793a); a recipe with neither is compared with every recipe of that library. + * + * java -cp hmgapi-engine.jar:hmgapi-engine-test.jar hmgapi.engine.RecipeCheck [...] + * prints "ok"/"FAIL" lines (and "info" for pairs of different builds); exit 1 on a FAIL. + */ +public final class RecipeCheck { + static final Pattern STOCK = Pattern.compile("from stock ([0-9a-f]{32})"); + static final Pattern ID_BUILD = Pattern.compile("-([0-9a-f]{8})$"); + + static final class R { + String mod, path, build; + MemRecipe recipe; + } + + public static void main(String[] a) throws Exception { + if (a.length < 1) { + System.err.println("usage: RecipeCheck [...]"); + System.exit(2); + } + int fail = 0; + List>>> mods = new ArrayList>>>(); + String self = null; + for (String dir : a) { + List>> libs = new ArrayList>>(); + Map mj = Json.object(new String(Files.readAllBytes(new File(dir, "mod.json").toPath()), "UTF-8")); + String id = String.valueOf(mj.get("id")); + if (self == null) self = id; + Object hooks = mj.get("hooks"); + Object nat = hooks instanceof Map ? ((Map) hooks).get("native") : null; + if (nat != null && !(nat instanceof Map)) { + System.out.println("FAIL " + id + ": hooks.native must be an object {\"\": [\"\", ...]}"); + fail = 1; + nat = null; + } + if (nat != null) { + for (Map.Entry e : ((Map) nat).entrySet()) { + List rs = new ArrayList(); + Object v = e.getValue(); + List paths = v instanceof List ? (List) v : java.util.Collections.singletonList(v); + for (Object p : paths) { + R r = new R(); + r.mod = id; + r.path = String.valueOf(p); + File f = new File(dir, r.path); + try { + String text = new String(Files.readAllBytes(f.toPath()), "UTF-8"); + r.recipe = MemRecipe.parse(text); + Matcher m = STOCK.matcher(text); + Matcher i = ID_BUILD.matcher(r.recipe.id); + r.build = m.find() ? m.group(1) : i.find() ? i.group(1) : null; + if (mods.isEmpty()) { + System.out.println("ok " + id + " " + r.path + " parses (recipe " + r.recipe.id + ", " + + r.recipe.verifies.size() + " verify, " + r.recipe.patchAt.size() + " patch)"); + } + rs.add(r); + } catch (Exception x) { + String why = x instanceof java.nio.file.NoSuchFileException ? "no such file in the mod" : x.getMessage(); + if (mods.isEmpty()) { + System.out.println("FAIL " + id + " " + r.path + ": " + why); + fail = 1; + } else { // another mod's: not this mod's to fix, and not compared + System.out.println("info " + id + " " + r.path + ": " + why); + } + } + } + libs.add(new java.util.AbstractMap.SimpleEntry>(String.valueOf(e.getKey()), rs)); + } + } + mods.add(libs); + } + for (int k = 1; k < mods.size(); k++) { + for (Map.Entry> ours : mods.get(0)) { + for (Map.Entry> theirs : mods.get(k)) { + if (!ours.getKey().equals(theirs.getKey())) continue; + for (R x : ours.getValue()) { + for (R y : theirs.getValue()) { + String what = x.mod + " " + x.recipe.id + " and " + y.mod + " " + y.recipe.id + " (" + ours.getKey() + ")"; + if (x.build != null && y.build != null && !sameBuild(x.build, y.build)) { + System.out.println("info " + what + ": other library builds"); + continue; + } + long[] at = overlap(x.recipe, y.recipe); + if (at == null) { + System.out.println("ok " + what + ": no region overlaps"); + } else { + System.out.println("FAIL " + what + ": overlap at 0x" + Long.toHexString(at[0]) + "-0x" + Long.toHexString(at[1]) + + "; on the car only one of them is applied"); + fail = 1; + } + } + } + } + } + } + System.exit(fail); + } + + /** a stock md5 and an id's 8 digits: the same build if one starts with the other */ + static boolean sameBuild(String a, String b) { + return a.startsWith(b) || b.startsWith(a); + } + + /** the first overlap of two recipes' regions, [from, to), or null */ + static long[] overlap(MemRecipe a, MemRecipe b) { + for (long[] x : a.regions()) { + for (long[] y : b.regions()) { + if (x[0] < y[1] && y[0] < x[1]) return new long[] { Math.max(x[0], y[0]), Math.min(x[1], y[1]) }; + } + } + return null; + } +} diff --git a/docs/mod-reference.md b/docs/mod-reference.md index e394c5bc..e438b56f 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -382,6 +382,25 @@ A `test.sh` sources `$HMGAPI_SDK/test/lib.sh` for `check`, `has`, `eng` (the eng your machine, on a fake head unit in `$R`) and `tree`. `mods/examples/hello/test.sh` is the template. The README in the SDK lists the rest. +`plan_test` (in the same `lib.sh`) runs your mod through `engine plan` on a fake head unit +for each car its `"system"` names that HMG-API has a hook map for (the SDK carries the +maps): no problems in the plan, the `"system"` takes the unit, HMG-API uses the car's +map, every point in `hooks.points` is mapped there, your hooks load, which points you +share with other mods, and your native recipes (`hooks.native`) stay clear of the +recipes of the mods you require for the same library build. Give it your mod's folder +and the folder of each mod in `"requires"` (each with its `mod.json` and the files it +names, such as recipes; no build needed): + +``` +. "$HMGAPI_SDK/test/lib.sh" +plan_test "$(dirname "$0")" ../other-mod/other-mod +exit $fail +``` + +A unit there has stand-ins, not the car's files, so file changes (`patches.json`) are +left to the stock-file tests below. `PLAN_POINTS` adds points your code reads by name +(through `Points`) to the mapped check; `HMGAPI_MAPS` uses another HMG-API's `maps/`. + A test that needs a car's stock files gets them from `car_tree` (and `car_prop`), and skips without them; never a path of your own. `tools/cars.py test --mods ` in an HMG-API checkout then runs your tests on every stock tree you have diff --git a/docs/mod-repos.md b/docs/mod-repos.md index 9f30a597..ac850362 100644 --- a/docs/mod-repos.md +++ b/docs/mod-repos.md @@ -90,6 +90,8 @@ installs `android.jar` and `d8` as core's CI does). | `bin/check-scripts.sh`, `unit-commands.txt` | `tools/check-scripts.sh`, `core/runtime/unit-commands.txt` | unit-only commands in mod scripts | | `bin/mkrecipe.py`, `bin/mkdelta.py`, `bin/mkmemrecipe.py`, `bin/mkicon.sh`, `bin/mod-draft.py` | `tools/` | recipes, delta sets, tile pictures, new mod drafts | | `test/lib.sh` | the `check`/`has`/`eng` helpers every mod `test.sh` copies today | mod tests | +| `test/plan.py`, `test/hmgapi-engine-test.jar` (`RecipeCheck`, `MemRecipeTest`) | `tools/sdk/plan.py`, `core/runtime/test` | `test/lib.sh`'s plan test, native recipes | +| `maps/` | `maps/` (without `coverage.json`) | the plan test: a fake head unit per car with a map | | `points.txt`, `catalogue/*.json` | `core/hookpoints` | check the mod's `hooks.points` exist | | `VERSION` | `Engine.HMGAPI_VERSION` | | diff --git a/tools/sdk-test.sh b/tools/sdk-test.sh index e708215e..d22385a7 100644 --- a/tools/sdk-test.sh +++ b/tools/sdk-test.sh @@ -124,6 +124,75 @@ set +e; o=$(cd $T/c && sh $S/mknemesismod.sh out/packages/conf-1.0.0.zip 2>&1); check "... refusing hmgapi itself: refused" 1 "$([ $r -ne 0 ] && echo 1)" has "... says why" "both needs and refuses hmgapi" "$o" +# ---- the plan test (test/lib.sh plan_test): HMG-API's maps in the SDK, fake units built from them +check "the maps, without the repo's coverage baseline" "$(cd $REPO/maps && find . -type f -name '*.json' ! -name coverage.json | sort)" "$(cd $T/sdk/maps && find . -type f | sort)" +P=$T/plan; mkdir -p $P/base/recipes $P/user/recipes +H=0123456789abcdef0123456789abcdef +rcp() { # rcp : a one-region recipe for libx.so + printf '# generated by mkmemrecipe.py from stock %s -> patched %s\nid %s\nfile /system/lib/libx.so\nverify %s 16 %s %s\npatch %s 00\n' \ + "$3" "$H" "$2" "$4" "$H" "$H" "$4" > "$1" +} +rcp $P/base/recipes/b.recipe base-x 11111111$H 0x100 +rcp $P/user/recipes/same.recipe user-same 11111111$H 0x108 +rcp $P/user/recipes/other.recipe user-other 22222222$H 0x100 +printf '{"id": "base", "version": "1.0.0", "system": {"product": "CVEV.USA."}, "hooks": {"jar": "hooks.jar", "entry": "b.B", + "points": {"gpm.navigation_status.next_turn": "observe"}, "native": {"libx.so": ["recipes/b.recipe"]}}}\n' > $P/base/mod.json +printf '{"id": "user", "version": "1.0.0", "requires": ["base ^1.0"], "system": {"product": "CVEV.USA."}, "hooks": {"jar": "hooks.jar", "entry": "u.U", + "points": {"gpm.navigation_status.next_turn": "observe", "gpm.navigation_status.status": "change"}, + "native": {"libx.so": ["recipes/other.recipe", "recipes/same.recipe"]}}}\n' > $P/user/mod.json +cat > $P/t.sh <<'EOF' +set -e +. "$HMGAPI_SDK/test/lib.sh" +plan_test "$@" +exit $fail +EOF +pt() { set +e; o=$(HMGAPI_SDK=$T/sdk sh $P/t.sh "$@" 2>&1); r=$?; set -e; } +pt $P/user $P/base +check "plan_test: an overlap with a required mod's recipe fails" 1 $r +has "... the car its \"system\" names, with the map's product" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): no problems in the plan" "$o" +check "... only that car" 1 "$(echo "$o" | grep -c 'no problems in the plan')" +has "... HMG-API uses the car's map" "(kia/ev6/usa/260507): HMG-API uses the car's map" "$o" +has "... every point mapped" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): every hook point user uses is mapped" "$o" +has "... its hooks load" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): user's hooks load" "$o" +has "... the point it shares, and with whom" "info CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): shares gpm.navigation_status.next_turn: base (observe)" "$o" +has "... its recipes parse" "ok user recipes/same.recipe parses" "$o" +has "... a recipe for another build isn't compared" "info user user-other and base base-x (libx.so): other library builds" "$o" +has "... the overlap, named" "FAIL user user-same and base base-x (libx.so): overlap at 0x108-0x110" "$o" +rcp $P/user/recipes/same.recipe user-same 11111111$H 0x110 +pt $P/user $P/base +check "... clear of it: passes" 0 $r +[ $r = 0 ] || echo "$o" +has "... says so" "ok user user-same and base base-x (libx.so): no region overlaps" "$o" +pt $P/user +check "plan_test without a required mod's folder: fails" 1 $r +has "... names it" "FAIL user requires base: give the folder of each" "$o" +cp $P/user/mod.json $P/user.json +sed 's/"product": "CVEV.USA."/"product": "CVEV.USA.", "features": ["hmgapi.wifi", "com.example.x"]/' $P/user.json > $P/user/mod.json +pt $P/user $P/base +check "... the features the mods ask for: the fake unit has them" 0 $r +has "... and the mod's \"system\" is checked there" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): user's \"system\" takes this unit" "$o" +sed 's/"product": "CVEV.USA."/"product": "CVEV.USA.", "android": "4.4.3"/' $P/user.json > $P/user/mod.json +pt $P/user $P/base +check "... a \"system\" that refuses the unit otherwise: fails" 1 $r +has "... says why" "takes this unit: wanted [], got [user: needs android 4.4.3" "$o" +cp $P/user.json $P/user/mod.json +python3 - $P/user/mod.json <<'PY2' +import json, sys +m = json.load(open(sys.argv[1])); m["hooks"]["points"]["gpm.no_such_point"] = "observe" +m["system"] = {"model": "NEEV23", "region": "USA"} +json.dump(m, open(sys.argv[1], "w")) +PY2 +o=$(HMGAPI_SDK=$T/sdk sh -c '. "$HMGAPI_SDK/test/lib.sh"; plan_cars "$1"' - $P/user) +check "plan_cars: each map and product the \"system\" names" "hyundai/neev/usa/260507 NEEV23.USA.0000.V000.000.260507|hyundai/neev23/usa/260903 NEEV23.USA.0000.V000.000.260903|" "$(echo "$o" | tr '\n' '|')" +printf '{"id": "base", "version": "1.0.0", "patches": "patches.json"}\n' > $P/base/mod.json +printf '{"changes": [{"path": "/system/lib/libx.so", "type": "delta", "delta": "x.delta", "stock": ["%s"], "result": "%s"}]}\n' $H $H > $P/base/patches.json +printf '{"changes": [{"type": "prop", "key": "ro.x", "value": "1"}]}\n' > $P/user/patches.json +pt $P/user $P/base +check "... a mod.json mistake, a point HMG-API hasn't: fails" 1 $r +has "... the mistake is a problem" "got [user: prop ro.x: only persist.* properties" "$o" +check "... the fake unit's stand-in files aren't" "" "$(echo "$o" | grep 'libx.so: not on this head unit' || true)" +has "... names the point" "gpm.no_such_point: not in this car's map" "$o" + # ---- check-scripts.sh and check-points.py o=$(sh $S/check-scripts.sh hello side-panel 2>&1) && r=0 || r=$? check "check-scripts.sh: the examples pass" 0 $r diff --git a/tools/sdk/README.txt b/tools/sdk/README.txt index c0a3c87d..6fa30c5c 100644 --- a/tools/sdk/README.txt +++ b/tools/sdk/README.txt @@ -18,11 +18,26 @@ the Android SDK (build-tools, a platform android.jar) and set ANDROID_HOME. bin/lpatch-host, src/lpatch/ lpatch for host tests (src/lpatch/build.sh builds it elsewhere) bin/mkrecipe.py, mkdelta.py, mkmemrecipe.py, mkicon.sh, mod-draft.py as in HMG-API's tools/ test/lib.sh check/has/eng/tree for a mod's test.sh; car_tree/car_prop: the - stock car files tools/cars.py test runs it on (HMGAPI_CAR) - test/hmgapi-engine-test.jar hmgapi.engine.MemRecipeTest: native recipes on real libraries + stock car files tools/cars.py test runs it on (HMGAPI_CAR); + plan_test [...]: the plan test (below) + test/plan.py the fake head units plan_test makes from maps/ + test/hmgapi-engine-test.jar hmgapi.engine.MemRecipeTest: native recipes on real libraries; + hmgapi.engine.RecipeCheck: without them, against other mods' + maps/ HMG-API's hook maps (public: point names and the md5s of the + stock files each map was made from; no car files) points.txt, catalogue/ the hook points this release has, and their catalogue nemesis/ the NEMESIS package templates +The plan test: in a mod's test.sh, after `. "$HMGAPI_SDK/test/lib.sh"`, + plan_test [...] +makes a fake head unit for each car the mod's "system" names that has a map here, puts +the mods on it and runs engine plan as that car: no problems in the plan, the "system" +takes the unit, HMG-API uses the car's map, every hook point the mod declares (and those +in PLAN_POINTS) is mapped, its hooks load, which points it shares with other mods (info), +and its native recipes stay clear of the required mods' recipes for the same library +build. File changes aren't tested there (the unit has stand-ins, not stock files): test +them on stock files with car_tree. HMGAPI_MAPS: other maps (a newer HMG-API's maps/). + A key: java -cp lib/hmgapi-engine.jar hmgapi.engine.Signing keygen How mods are built outside HMG-API: docs/mod-reference.md in the HMG-API repo, "Building a mod outside this repo". AGPL-3.0 (LICENSE). diff --git a/tools/sdk/lib.sh b/tools/sdk/lib.sh index 8628dd62..84ef8633 100644 --- a/tools/sdk/lib.sh +++ b/tools/sdk/lib.sh @@ -25,3 +25,67 @@ install_mod() { mkdir -p $R/data/hmgapi/mods && rm -rf "$R/data/hmgapi/mods/$(ba car_tree() { [ -n "${HMGAPI_CAR:-}" ] && [ -d "$HMGAPI_CAR" ] && echo "$HMGAPI_CAR"; } # a value from that tree's build.prop, e.g. car_prop ro.build.product car_prop() { [ -f "$HMGAPI_CAR/build.prop" ] && sed -n "s/^$1=//p" "$HMGAPI_CAR/build.prop" | sed -n 1p; } + +# ---- the plan test: the mod through engine plan on a fake head unit for each car HMG-API has a +# map for (the SDK's maps/, or HMGAPI_MAPS), as the car would plan it. A unit has the car's +# maps, a stand-in for each stock file they were made from (no car files), and the mods. +# plan_test [...] +# runs it all per car the mod's "system" names, as ok/FAIL/info lines (fail=1 on a FAIL): +# no problems in the plan (mod.json, a required mod, conflicts; not the stand-ins' files), +# the mod's "system" takes the unit (the unit has the features the mods ask for), HMG-API uses the car's map, every hook point the mod declares (and those in PLAN_POINTS, +# points the mod reads by name) is mapped, its hooks load, the points it shares with other +# mods (info), and its native recipes (hooks.native) parse and stay clear of the required +# mods' recipes for the same library build. A required mod's folder needs only its +# mod.json and what that names (its built folder, or its repo's). +# The parts, for checks of your own (R: the unit's root; out, rc: the last plan): +# plan_cars " " per car the mod is for +# plan_unit ... R becomes that car's unit; engine plan +# plan_eng the engine on that unit, as that car +# plan_problems, plan_shared from $out; plan_unmapped [...] +# plan_system why the mod's "system" refuses the unit (if it does) +# recipes_clear [...] +MAPS=${HMGAPI_MAPS:-$HMGAPI_SDK/maps} +PLAN=$HMGAPI_SDK/test/plan.py +plan_cars() { python3 "$PLAN" cars "$MAPS" "$1"; } +plan_unit() { + python3 "$PLAN" unit "$R" "$MAPS" "$@" || { echo "FAIL plan_unit $*: no fake unit"; fail=1; return 1; } + read PLAN_MAP PLAN_PRODUCT PLAN_ONEBIN < "$R/.plan-car" + plan_eng plan +} +plan_eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR= HMGAPI_PRODUCT=$PLAN_PRODUCT HMGAPI_ONEBIN=$PLAN_ONEBIN \ + HMGAPI_LPATCH=$LPATCH java -cp "$ENGINE" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +# plan_system : nothing if the mod's "system" takes the unit, else why (and exit 1) +plan_system() { HMGAPI_ROOT=$R HMGAPI_PRODUCT=$PLAN_PRODUCT HMGAPI_ONEBIN=$PLAN_ONEBIN java -cp "$ENGINE" hmgapi.engine.SystemCheck "$1" 2>&1 | grep -v '^ok: '; [ $? = 1 ]; } +plan_problems() { printf '%s\n' "$out" | python3 "$PLAN" problems; } +plan_shared() { printf '%s\n' "$out" | python3 "$PLAN" shared "$1"; } +plan_unmapped() { python3 "$PLAN" unmapped "$R" "$@"; } +recipes_clear() { java -cp "$ENGINE:$HMGAPI_SDK/test/hmgapi-engine-test.jar" hmgapi.engine.RecipeCheck "$@"; } +plan_test() { + _pm=$1; shift + _pid=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["id"])' "$_pm/mod.json") + _pneed=$(python3 "$PLAN" requires "$_pm" "$@" | sed -n 'H; ${x; s/\n/ /g; s/^ //; p; }') + if [ -n "$_pneed" ]; then + echo "FAIL $_pid requires $_pneed: give the folder of each (plan_test ...)"; fail=1; return 0 + fi + _pcars=$(plan_cars "$_pm") || { echo "FAIL plan_cars $_pm"; fail=1; return 0; } + [ -n "$_pcars" ] || echo "skip $_pid: no car its \"system\" names has a hook map in $MAPS" + _pR=${R-}; _pT=$(mktemp -d); R=$_pT/unit + while read -r _pmap _pprod <&3; do + [ -n "$_pmap" ] || continue + _pl="$_pprod ($_pmap)" + plan_unit "$_pmap" "$_pprod" "$_pm" "$@" || continue + check "$_pl: no problems in the plan" "" "$(plan_problems)" + # engine plan checks "system" only for mods with file changes; the mod loader, every mod's + check "$_pl: $_pid's \"system\" takes this unit" "" "$(plan_system "$_pm" || true)" + check "$_pl: HMG-API uses the car's map" "" "$(printf '%s\n' "$out" | grep '^hooks are off' || true)" + check "$_pl: every hook point $_pid uses is mapped" "" "$(plan_unmapped "$_pm" ${PLAN_POINTS:-})" + check "$_pl: $_pid's hooks load" "" "$(printf '%s\n' "$out" | grep "^hooks *$_pid won't load" || true)" + plan_shared "$_pid" | sed "s#^#info $_pl: shares #" + done 3<&1); _prc=$?; set -e + [ -z "$_pr" ] || printf '%s\n' "$_pr" + [ $_prc = 0 ] || fail=1 +} diff --git a/tools/sdk/plan.py b/tools/sdk/plan.py new file mode 100644 index 00000000..d70f6eeb --- /dev/null +++ b/tools/sdk/plan.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""Fake head units for a mod's plan test, from HMG-API's hook maps (in the mod SDK as +test/plan.py; test/lib.sh's plan_* functions call it, see there). + + plan.py cars + one line per car the mod's "system" names that has a map: " ", + e.g. "kia/ev6/usa/260507 CVEV.USA.0000.V015.012.260507". A map with several + products (the 2022 and 2023 Ioniq 5) gives a line for each. Only what a map says + about a car counts (make, model, name, region, firmware, product): the rest of + "system" (features, props, year...) is the fake unit's to fake (below). + plan.py unit ... + a fake head unit at (emptied first) for that car: its maps, a stand-in for + every stock file a map was made from (the maps' md5s are the stand-ins', so the + engine takes the map as this car's), the features the mods' "system" ask for, and + the mods in data/hmgapi/mods/ (without test.sh). No car file is in it. + plan.py unmapped [...] + the hook points the mod declares (hooks.points), and any named, that the unit's + map hasn't: one per line, with why. Nothing when all are mapped. + plan.py requires [...] + the ids the first mod requires ("requires") that none of the others is. + plan.py problems [file] + engine plan's problems (stdin or file) except those about the fake unit's stand-in + files, which no stock file was ever behind (missing, not stock, a delta that + doesn't fit): mod.json mistakes, a required mod missing, conflicts between mods. + plan.py shared [file] + the hook points engine plan's output says the mod shares: ": ". + +No manufacturer files: the maps are HMG-API's (point names, md5s), the stand-ins a line +of text each. Only python3's standard library. +""" +import glob +import hashlib +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile + +# what a map tells about a car; the rest of "system" is the fake unit's (features) or unknown here +CAR_KEYS = ("make", "model", "name", "region", "firmware", "product") +MIDDLE = "0000.V000.000." # a product's middle fields, when the map gives no whole product + + +def die(msg): + sys.stderr.write("plan.py: %s\n" % msg) + sys.exit(2) + + +def load(path): + try: + with open(path) as f: + return json.load(f) + except (OSError, ValueError) as e: + die("%s: %s" % (path, e)) + + +def mod_json(mod): + m = load(os.path.join(mod, "mod.json")) + if not isinstance(m, dict) or not m.get("id"): + die("%s/mod.json has no id" % mod) + return m + + +def setups(system): + """mod.json "system" as a list of setups (dicts); [] for any unit""" + if system is None or system in ("all", "*"): + return [] + return system if isinstance(system, list) else [system] + + +def maps_of(maps): + out = [] + for cj in sorted(glob.glob(os.path.join(maps, "*", "*", "*", "*", "car.json"))): + out.append((os.path.relpath(os.path.dirname(cj), maps), load(cj))) + return out + + +def sdk_jar(): + here = os.path.dirname(os.path.abspath(__file__)) + for j in (os.path.join(here, "..", "lib", "hmgapi-engine.jar"), os.environ.get("ENGINE", "")): + if j and os.path.isfile(j): + return j + die("no hmgapi-engine.jar (run from the SDK's test/, or set ENGINE)") + + +def cars(maps, mod): + m = mod_json(mod) + wanted = setups(m.get("system")) + # the engine's own check (SystemCheck), on the car keys of each setup only + keep = [{k: v for k, v in s.items() if k in CAR_KEYS} for s in wanted if isinstance(s, dict)] + tmp = tempfile.mkdtemp() + try: + with open(os.path.join(tmp, "mod.json"), "w") as f: + json.dump({"id": m["id"], "system": keep if keep else "all"}, f) + os.makedirs(os.path.join(tmp, "root")) + for folder, car in maps_of(maps): + whole = (car.get("verified") or {}).get("product") or "" + for prefix in car.get("products") or []: + product = whole if whole.startswith(prefix) else prefix + MIDDLE + str(car.get("firmware")) + env = dict(os.environ, HMGAPI_ROOT=os.path.join(tmp, "root"), HMGAPI_PRODUCT=product) + r = subprocess.run(["java", "-cp", sdk_jar(), "hmgapi.engine.SystemCheck", tmp], env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + if r.returncode == 0: + print(folder, product) + elif not r.stdout.startswith(m["id"] + ": "): + die("SystemCheck: " + r.stdout.strip()) + finally: + shutil.rmtree(tmp) + + +def unit(root, maps, folder, product, mods): + if not os.path.isfile(os.path.join(maps, folder, "car.json")): + die("no map %s in %s" % (folder, maps)) + if os.path.exists(root): + shutil.rmtree(root) + data = os.path.join(root, "data", "hmgapi") + for d in ("system/etc/permissions", "data/hmgapi/mods", "data/hmgapi/settings/allow", "data/hmgapi/public"): + os.makedirs(os.path.join(root, d)) + model, region = (product.split(".") + ["", ""])[:2] + # the onebin folder isn't in the maps: _<2 letters of the region> (cvev_us on the US EV6) + onebin = os.environ.get("HMGAPI_ONEBIN") or "%s_%s" % (model.lower(), region[:2].lower()) + props = {"ro.build.product": product, "ro.build.version.release": "4.4.2", "ro.mobis.onebindir": onebin} + with open(os.path.join(root, "props.txt"), "w") as f: + f.writelines("%s=%s\n" % kv for kv in props.items()) + with open(os.path.join(root, "system", "build.prop"), "w") as f: + f.writelines("%s=%s\n" % kv for kv in props.items()) + shutil.copytree(maps, os.path.join(data, "maps")) + # every point this HMG-API has (the SDK's points.txt): a point a map lacks is "newer than the map" + sdk_points = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "points.txt") + if not os.path.isfile(os.path.join(data, "maps", "points.txt")) and os.path.isfile(sdk_points): + shutil.copy(sdk_points, os.path.join(data, "maps", "points.txt")) + # a stand-in for each stock file a map was made from, and the maps' md5s the stand-ins' + for cj in glob.glob(os.path.join(data, "maps", "*", "*", "*", "*", "car.json")): + car = load(cj) + files = car.get("files") + if not isinstance(files, dict): + continue + for path in files: + f = root + path + if not os.path.exists(f): + os.makedirs(os.path.dirname(f), exist_ok=True) + with open(f, "wb") as o: + o.write(("stand-in for " + path + "\n").encode()) + with open(f, "rb") as i: + files[path] = hashlib.md5(i.read()).hexdigest() + with open(cj, "w") as o: + json.dump(car, o, indent=2) + # a map not checked on a car yet (mapped, probed) runs as with the app's "testing maps" switch + open(os.path.join(data, "settings", "allow", "testing_maps"), "w").close() + # the features the mods ask for: the fake unit has them (hmgapi.wifi: a Wi-Fi chip seen once) + features = set() + ids = [] + for mod in mods: + m = mod_json(mod) + ids.append(m["id"]) + for s in setups(m.get("system")): + fs = s.get("features") if isinstance(s, dict) else None + for x in ([fs] if isinstance(fs, str) else fs or []): + if isinstance(x, str) and not x.startswith("!") and x not in ("all", "*"): + features.add(x) + dst = os.path.join(data, "mods", m["id"]) + if os.path.exists(dst): + die("two mods with the id %s" % m["id"]) + shutil.copytree(mod, dst, symlinks=True) + if os.path.exists(os.path.join(dst, "test.sh")): + os.remove(os.path.join(dst, "test.sh")) + if "hmgapi.wifi" in features: + features.discard("hmgapi.wifi") + open(os.path.join(data, "public", "wifi-chip"), "w").close() + with open(os.path.join(root, "system", "etc", "permissions", "hmgapi-plan-test.xml"), "w") as f: + f.write("\n%s\n" % "".join(' \n' % x for x in sorted(features))) + with open(os.path.join(root, ".plan-car"), "w") as f: + f.write("%s %s %s\n" % (folder, product, onebin)) + + +def unmapped(root, mod, extra): + try: + with open(os.path.join(root, ".plan-car")) as f: + folder = f.read().split()[0] + except OSError: + die("%s isn't a fake unit from plan.py unit" % root) + d = os.path.join(root, "data", "hmgapi", "maps", folder) + car = load(os.path.join(d, "car.json")) + have = {} + for app in car.get("apps") or []: + have.update(load(os.path.join(d, app + ".json"))) + missing = car.get("missing") or {} + points = (mod_json(mod).get("hooks") or {}).get("points") or {} + want = list(points) + [p for p in extra if p not in points] + for p in want: + if p in missing: + print("%s: not found in this car's apps (%s)" % (p, missing[p])) + elif p not in have: + print("%s: not in this car's map (newer than the map, or not a point HMG-API has)" % p) + + +def requires(mod, given): + """the ids the mod requires that none of the given mod folders is""" + have = {mod_json(g)["id"] for g in given} + r = mod_json(mod).get("requires") + for dep in (r if isinstance(r, list) else []): # as the engine reads it (Version.deps) + dep_id = str(dep.get("id")) if isinstance(dep, dict) else (str(dep).split() or [""])[0] + if dep_id and dep_id not in have: + print(dep_id) + + +def lines(path): + if path: + with open(path) as f: + return f.read().splitlines() + return sys.stdin.read().splitlines() + + +# problems the fake unit causes: a file a mod changes isn't there, or is a stand-in, not stock +UNIT_FILE = re.compile(r"^/\S+: (not on this head unit|not the stock file|already on the head unit|" + r".*doesn't fit|can't add classes\.dex|codec changes need the file|" + r".* built \S+, not the expected result|the props edit would lose)") + + +def problems(path): + seen = False + for line in lines(path): + if re.match(r"^nothing changed: \d+ problem", line): + seen = True + continue + if not seen or not line.startswith(" "): + continue + p = line[2:] + if UNIT_FILE.match(re.sub(r"^conflict: ", "", p)): + continue + print(p) + + +def shared(mod_id, path): + for line in lines(path): + m = re.match(r"^hooks +(\S+): (.*) share it$", line) + if not m: + continue + mods = [x.strip() for x in m.group(2).split(", ")] + if any(x.split(" (")[0] == mod_id for x in mods): + print("%s: %s" % (m.group(1), ", ".join(x for x in mods if x.split(" (")[0] != mod_id))) + + +def main(a): + if len(a) >= 3 and a[0] == "cars": + cars(a[1], a[2]) + elif len(a) >= 6 and a[0] == "unit": + unit(a[1], a[2], a[3], a[4], a[5:]) + elif len(a) >= 3 and a[0] == "unmapped": + unmapped(a[1], a[2], a[3:]) + elif len(a) in (1, 2) and a[0] == "problems": + problems(a[1] if len(a) > 1 else None) + elif len(a) >= 2 and a[0] == "requires": + requires(a[1], a[2:]) + elif len(a) in (2, 3) and a[0] == "shared": + shared(a[1], a[2] if len(a) > 2 else None) + else: + sys.stderr.write(__doc__) + sys.exit(2) + + +if __name__ == "__main__": + main(sys.argv[1:]) From 08daf0284831e5de14d511c5fc180ff59049fae5 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 15 Nov 2026 22:27:05 -0500 Subject: [PATCH 02/69] Mod workflow and build-mod.sh: a mod's own build.sh, ids from mod.json build-mod.sh runs an executable /build.sh after building hooks.jar and the app, with the SDK, the runtime, hmgapi-client.jar and the Android tools in its environment; what it writes there goes into the package. mkmodpkg.sh packages the mod folder with that build on top (HMGAPI_MOD_BUILD, or it runs build-mod.sh), so the package is what the tests saw and build.sh runs once. It refuses a HMGAPI_MOD_BUILD that is another mod's build. The mod's id comes from mod.json, not the folder name, in build-mod.sh and the reusable workflow: the workflow builds into out/build/ and refuses two folders with one id and ids the engine would refuse. For mods like egmp-aa-ev (folder hmgapi-mod/, a relay service jar). Packages of today's mods have the same files as before. sdk-test.sh covers a build.sh mod in a folder not named by its id, and runs mod.yml's own steps. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/mod.yml | 50 ++++++++++++----- CHANGELOG.md | 13 +++++ docs/mod-reference.md | 51 ++++++++++++++--- docs/mod-repos.md | 2 +- tools/build-mod.sh | 26 ++++++++- tools/mkmodpkg.sh | 16 ++++-- tools/sdk-test.sh | 114 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 239 insertions(+), 33 deletions(-) diff --git a/.github/workflows/mod.yml b/.github/workflows/mod.yml index a9bb951d..69014b41 100644 --- a/.github/workflows/mod.yml +++ b/.github/workflows/mod.yml @@ -10,9 +10,11 @@ # {"version": "1.1.0", "sha256": ""} the release's hmgapi-mod-sdk-.zip, refused # unless its sha256 is this one # Then, for each mod: its "hmgapi" floor and hook points (bin/check-points.py), the build -# (bin/build-mod.sh), its test.sh and tools/*/test.sh (with HMGAPI_SDK and HMGAPI_MOD_BUILD), -# check-scripts, and the package and NEMESIS package, signed with a throwaway key (a test -# build: releases are signed by the mod repo's own release workflow, with its MOD_KEY). +# (bin/build-mod.sh: src/, app/, then the mod's own executable build.sh), its test.sh and +# tools/*/test.sh (with HMGAPI_SDK and HMGAPI_MOD_BUILD), check-scripts, and the package and +# NEMESIS package, signed with a throwaway key (a test build: releases are signed by the mod +# repo's own release workflow, with its MOD_KEY). A mod's id is its mod.json "id", whatever +# its folder is called; its build is in out/build/. # With ndk: that Android NDK (sdkmanager's version) installed first, in NDK and ANDROID_NDK_HOME, # for a mod whose build.sh compiles native code (hmgapi-adbd: 21.4.7075529, r21e, for API 19). # HMG-API's own CI runs it on mods/examples/hello (ci.yml, mod-workflow; weekly with an NDK too). @@ -150,8 +152,27 @@ jobs: [ -f "$m/mod.json" ] || { echo "$m has no mod.json"; exit 1; } done [ -n "$MODS" ] || { echo "no mod folders (a folder with a mod.json)"; exit 1; } + # each mod's id, from its mod.json: " " lines in MOD_IDS + python3 - $MODS > "$RUNNER_TEMP/mod-ids" <<'PY' + import json, re, sys + seen = {} + for m in sys.argv[1:]: + m = m.rstrip("/") + try: + j = json.load(open(m + "/mod.json")) + except ValueError as e: + sys.exit("%s/mod.json isn't valid JSON: %s" % (m, e)) + i = j.get("id") if isinstance(j, dict) else None + if not isinstance(i, str) or not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,63}", i) or i == "hmgapi": + sys.exit('%s/mod.json: "id" is a mod id (a-z, 0-9 and -, up to 64), not %r' % (m, i)) + if i in seen: + sys.exit("%s and %s are both mod %s" % (seen[i], m, i)) + seen[i] = m + print(m, i) + PY + echo "MOD_IDS=$RUNNER_TEMP/mod-ids" >> "$GITHUB_ENV" echo "MODS=$(echo $MODS)" >> "$GITHUB_ENV" - echo "Mods: $MODS" >> "$GITHUB_STEP_SUMMARY" + echo "Mods: $(awk '{ printf "%s%s", (NR > 1 ? ", " : ""), ($1 == $2 ? $1 : $1 " (" $2 ")") }' "$RUNNER_TEMP/mod-ids")" >> "$GITHUB_STEP_SUMMARY" - name: HMG-API floor and hook points env: @@ -161,24 +182,23 @@ jobs: - name: Build run: | cp="" - for m in $MODS; do - id=$(basename "$m") + while read -r m id; do # mods built before this one are on the classpath (a mod that requires another in this repo) - HMGAPI_MOD_CP="$cp" sh "$HMGAPI_SDK/bin/build-mod.sh" "$m" "out/build/$id" "out/work/$id" + HMGAPI_MOD_CP="$cp" sh "$HMGAPI_SDK/bin/build-mod.sh" "$m" "out/build/$id" "out/work/$id" < /dev/null if [ -d "out/work/$id/classes" ]; then cp="${cp:+$cp:}$PWD/out/work/$id/classes"; fi - done + done < "$MOD_IDS" - name: Tests run: | rc=0 - for m in $MODS; do + while read -r m id; do for t in "$m/test.sh" "$m"/tools/*/test.sh; do [ -f "$t" ] || continue echo "::group::$t" - HMGAPI_MOD_BUILD="$PWD/out/build/$(basename "$m")" sh "$t" || { echo "::error::$t failed"; rc=1; } + HMGAPI_MOD_BUILD="$PWD/out/build/$id" sh "$t" < /dev/null || { echo "::error::$t failed"; rc=1; } echo "::endgroup::" done - done + done < "$MOD_IDS" exit $rc - name: Scripts only use what the head unit has @@ -187,11 +207,11 @@ jobs: - name: Packages (throwaway key) run: | java -cp "$HMGAPI_SDK/lib/hmgapi-engine.jar" hmgapi.engine.Signing keygen "$RUNNER_TEMP/throwaway.key" - for m in $MODS; do - out=$(HMGAPI_MOD_BUILD="$PWD/out/build/$(basename "$m")" sh "$HMGAPI_SDK/bin/mkmodpkg.sh" "$m" "$RUNNER_TEMP/throwaway.key") + while read -r m id; do + out=$(HMGAPI_MOD_BUILD="$PWD/out/build/$id" sh "$HMGAPI_SDK/bin/mkmodpkg.sh" "$m" "$RUNNER_TEMP/throwaway.key" < /dev/null) echo "$out" - sh "$HMGAPI_SDK/bin/mknemesismod.sh" "$(echo "$out" | tail -1)" # its last line: the zip - done + sh "$HMGAPI_SDK/bin/mknemesismod.sh" "$(echo "$out" | tail -1)" < /dev/null # its last line: the zip + done < "$MOD_IDS" rm -f "$RUNNER_TEMP"/throwaway.key* - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 602c0cae..da9cd0ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## Unreleased + +- **Mod SDK and mod workflow:** `build-mod.sh` now runs a mod's own build step, an + executable `build.sh` in its folder, after building `hooks.jar` and the app: what it + writes in the build folder (a service's jar, a native binary) goes into the package, and + the mod's tests see it too. `mkmodpkg.sh` packages that build (from `HMGAPI_MOD_BUILD`, + or building it itself) instead of running `build.sh` again. A mod's folder needn't be + named by its id any more: `build-mod.sh` and the reusable mod workflow take the id from + `mod.json` (the workflow refuses two folders with one id, and an id the engine would + refuse). Packages come out with the same files as before, a `build.sh`'s too; a mod + with a `build.sh` now needs what it needs (hmgapi-adbd: the NDK) for `build-mod.sh` as + well. (docs/mod-reference.md, "Building a mod outside this repo") + ## 1.1.0-rc.2 (2026-11-15) The second release candidate: fixes from a review of rc.1, nothing new in HMG-API itself. diff --git a/docs/mod-reference.md b/docs/mod-reference.md index e394c5bc..d0467a0e 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -347,9 +347,10 @@ yours again. A mod in its own repository builds with the HMG-API mod SDK, `hmgapi-mod-sdk-.zip` on each HMG-API release from 1.1.0, its betas and release candidates included (or `./build.sh sdk` here, into `out/dist`). Put the -mod in a folder named by its id (`my-mod/mod.json`), with `README.md`, `LICENSE` and +mod in its own folder (`my-mod/mod.json`), with `README.md`, `LICENSE` and `.github/` at the repository root: everything in the mod folder but `build.sh`, -`test.sh`, `src`, `tools` and `native` goes into the package. +`test.sh`, `src`, `tools` and `native` goes into the package. The folder is usually +named by the mod's id, but needn't be: the id is always `mod.json`'s `"id"`. Pin the SDK in `hmgapi-sdk.json` at the root, and call HMG-API's mod workflow from `.github/workflows/ci.yml` (`jobs: mod: uses: Open-HMG/HMG-API/.github/workflows/mod.yml@`): @@ -360,22 +361,56 @@ Pin the SDK in `hmgapi-sdk.json` at the root, and call HMG-API's mod workflow fr | a release (from 1.1.0-beta.1) | `{"version": "1.1.0", "sha256": ""}` | `@v1.1.0` | The workflow checks the mod's `"hmgapi"` floor (at or below the SDK; every -`hooks.points` entry in that release's points), builds it, runs its `test.sh` and -`tools/*/test.sh`, checks its scripts, and packages it with a throwaway key. Your +`hooks.points` entry in that release's points), builds it (into `out/build/`), runs its +`test.sh` and `tools/*/test.sh` (with that build in `HMGAPI_MOD_BUILD`), checks its scripts, +and packages that build with a throwaway key. Your release workflow signs with your own key. A new hook point is a HMG-API pull request first (`docs/mod-repos.md`, section 4). +`build-mod.sh` builds `hooks.jar` from `src/` and the app from `app/`. Anything else the +package needs (a service's jar, a native binary, files made from others) comes from the +mod's own build step: an executable `build.sh` in the mod folder (`chmod +x`, and +`git update-index --chmod=+x`; one that isn't executable is skipped, with a warning). +`build-mod.sh` runs it last, as `sh /build.sh ` (SDKs after 1.1.0-rc.2; older +ones run it only in `mkmodpkg.sh`, on the package's folder): + +- `` is an absolute path, and already holds the mod's `*.json`, `hooks.jar` and + the APK. Whatever the script writes there goes into the package; it can also replace + those files (a `hooks.jar` built its own way). +- It runs from the directory `build-mod.sh` was run in (the repository root in the + workflow), so it finds its own folder with `$(dirname "$0")`. +- It gets `HMGAPI_SDK`, `HMGAPI_CP` (HMG-API's runtime, compile only), `HMGAPI_CLIENT` + (`hmgapi-client.jar`, for a service or app to bundle), `HMGAPI_MOD_CP`, `ANDROID_JAR`, + `D8` and `BT` (the build-tools folder). +- Its sources stay out of the package: in `tools/` or outside the mod folder. Not in + `src/` if `build.sh` builds `hooks.jar` itself: `build-mod.sh` compiles `src/` alone + first, with nothing but HMG-API and `stubs/` on the class path. + +`mkmodpkg.sh` packages the mod folder with the build on top: from `HMGAPI_MOD_BUILD` +(as the workflow does, so the package is what the tests saw), or it runs `build-mod.sh` +itself. For example, a service jar with `hmgapi-client.jar` inside, from `tools/relay/src`: + +``` +#!/bin/sh +set -e +W=$(mktemp -d); trap 'rm -rf "$W"' EXIT +(cd "$W" && jar xf "$HMGAPI_CLIENT" hmgapi) +javac --release 8 -cp "$ANDROID_JAR:$HMGAPI_CLIENT" -d "$W" $(find "$(dirname "$0")/tools/relay/src" -name '*.java') +"$D8" --release --min-api 19 --lib "$ANDROID_JAR" --output "$1/relay.jar" $(find "$W" -name '*.class') +``` + A mod whose `build.sh` compiles native code can ask for an Android NDK with `with: ndk: ""`, as `sdkmanager` names it (hmgapi-adbd: `21.4.7075529`, r21e). The workflow installs it before the build, with `NDK` and `ANDROID_NDK_HOME` pointing at it. -On your machine, with the SDK unpacked in `$HMGAPI_SDK` and the Android SDK in `ANDROID_HOME`: +On your machine, with the SDK unpacked in `$HMGAPI_SDK` and the Android SDK in `ANDROID_HOME` +(`my-mod` is the folder, `` its `mod.json` id): ``` -$HMGAPI_SDK/bin/build-mod.sh my-mod out/build/my-mod -HMGAPI_SDK=$HMGAPI_SDK HMGAPI_MOD_BUILD=out/build/my-mod sh my-mod/test.sh +$HMGAPI_SDK/bin/build-mod.sh my-mod out/build/ +HMGAPI_SDK=$HMGAPI_SDK HMGAPI_MOD_BUILD=$PWD/out/build/ sh my-mod/test.sh $HMGAPI_SDK/bin/check-scripts.sh my-mod -$HMGAPI_SDK/bin/mkmodpkg.sh my-mod +HMGAPI_MOD_BUILD=$PWD/out/build/ $HMGAPI_SDK/bin/mkmodpkg.sh my-mod ``` A `test.sh` sources `$HMGAPI_SDK/test/lib.sh` for `check`, `has`, `eng` (the engine on diff --git a/docs/mod-repos.md b/docs/mod-repos.md index 9f30a597..24736c72 100644 --- a/docs/mod-repos.md +++ b/docs/mod-repos.md @@ -85,7 +85,7 @@ installs `android.jar` and `d8` as core's CI does). | `lib/hmgapi-client.jar` | `./build.sh client` | mods' own apps and services (bundled, as now) | | `lib/hmgapi-engine.jar` | `core/runtime/java/hmgapi/engine` | host tests (`Engine` with `HMGAPI_HOST=1`), `Signing`, `ScriptCheck` | | `bin/lpatch-host` + `src/lpatch/` | `tools/lpatch` | host tests of patches and recipes; source to build it on macOS | -| `bin/build-mod.sh` | `build.sh mods()`, one mod | `hooks.jar` and app APK from a mod folder | +| `bin/build-mod.sh` | `build.sh mods()`, one mod | `hooks.jar` and app APK from a mod folder, then the mod's own `build.sh` | | `bin/mkmodpkg.sh`, `bin/mknemesismod.sh`, `bin/nemesis-meta.py`, `bin/nemesis-version.py`, `nemesis/mod/` | `tools/`, `install/nemesis/mod/`, `install/nemesis/bin/open.sh` | signed package, NEMESIS package | | `bin/check-scripts.sh`, `unit-commands.txt` | `tools/check-scripts.sh`, `core/runtime/unit-commands.txt` | unit-only commands in mod scripts | | `bin/mkrecipe.py`, `bin/mkdelta.py`, `bin/mkmemrecipe.py`, `bin/mkicon.sh`, `bin/mod-draft.py` | `tools/` | recipes, delta sets, tile pictures, new mod drafts | diff --git a/tools/build-mod.sh b/tools/build-mod.sh index bf7ed006..ed546e31 100644 --- a/tools/build-mod.sh +++ b/tools/build-mod.sh @@ -1,11 +1,18 @@ #!/bin/sh # Build one mod folder: hooks.jar from src/ (against HMG-API's runtime, compile only), -# the app APK from app/ (with hmgapi-client.jar inside), and the mod's *.json. +# the app APK from app/ (with hmgapi-client.jar inside), and the mod's *.json, then the +# mod's own build step, an executable /build.sh, if it has one. # build.sh mods runs it for every mod in this repo; in the mod SDK it's bin/build-mod.sh. # build-mod.sh [work dir] # Puts mod.json etc., hooks.jar and the APK (at the mod's first "apps" entry) in ; # the compiled classes stay in /classes (default: a temp dir) for mods that -# require this one (HMGAPI_MOD_CP). +# require this one (HMGAPI_MOD_CP). The mod's id is mod.json's "id" (the folder can have +# any name). mkmodpkg.sh packages the mod folder with on top. +# /build.sh is run last, as sh /build.sh (an absolute path), +# from the directory this script was run in, with HMGAPI_CP, HMGAPI_CLIENT, HMGAPI_MOD_CP, +# ANDROID_JAR, D8 and BT (build-tools) set, and HMGAPI_SDK in the mod SDK. What it writes +# in goes into the package (a service jar, a binary); it can replace what the +# steps above put there. # Env: HMGAPI_CP the runtime to compile against (default: the SDK's lib/hmgapi-runtime.jar # and lib/hmgapi-runtime-stubs.jar, beside this script) # HMGAPI_CLIENT hmgapi-client.jar (default: the SDK's lib/hmgapi-client.jar) @@ -23,8 +30,12 @@ CP=${HMGAPI_CP:-$LIB/hmgapi-runtime.jar:$LIB/hmgapi-runtime-stubs.jar} CLIENT=${HMGAPI_CLIENT:-$LIB/hmgapi-client.jar} W=$3 if [ -z "$W" ]; then W=$(mktemp -d); trap 'rm -rf "$W"' EXIT; fi -id=$(basename "$M") +[ -f "$M/mod.json" ] || { echo "build-mod: no $M/mod.json"; exit 1; } +id=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("id") or "")' "$M/mod.json") \ + || { echo "build-mod: $M/mod.json isn't valid JSON"; exit 1; } +[ -n "$id" ] || { echo "build-mod: no \"id\" in $M/mod.json"; exit 1; } mkdir -p "$O" +O=$(cd "$O" && pwd) cp "$M"/*.json "$O/" deps=${HMGAPI_MOD_CP:+$HMGAPI_MOD_CP:} if [ -d "$M/src" ]; then @@ -63,4 +74,13 @@ if [ -f "$M/app/AndroidManifest.xml" ]; then --v2-signing-enabled false --v3-signing-enabled false --out "$O/$apk" "$A/aligned.apk" 2>/dev/null echo "mod $id: app $apk" fi +# build.sh: the mod's own build step (a service jar, native code, files made from others) +if [ -x "$M/build.sh" ]; then + if [ -f "$LIB/hmgapi-runtime.jar" ]; then HMGAPI_SDK=$(cd "$HERE/.." && pwd); export HMGAPI_SDK; fi + HMGAPI_CP=$CP HMGAPI_CLIENT=$CLIENT HMGAPI_MOD_CP=$HMGAPI_MOD_CP ANDROID_JAR=$ANDROID_JAR D8=$D8 BT=$BT \ + sh "$M/build.sh" "$O" || { echo "build-mod: $M/build.sh $O failed"; exit 1; } + echo "mod $id: $M/build.sh" +elif [ -f "$M/build.sh" ]; then + echo "build-mod: $M/build.sh isn't executable, so it isn't run (chmod +x, and git update-index --chmod=+x)" >&2 +fi echo "mod $id" diff --git a/tools/mkmodpkg.sh b/tools/mkmodpkg.sh index 97b6cd51..7bacabea 100755 --- a/tools/mkmodpkg.sh +++ b/tools/mkmodpkg.sh @@ -1,6 +1,8 @@ #!/bin/sh -# Make a signed mod package: out/packages/-.zip from mods/ -# (its build.sh first, if it has one), signed with the author's key. +# Make a signed mod package: out/packages/-.zip from mods/, signed +# with the author's key: the mod folder (but build.sh, test.sh, src, tools, native) with +# what build-mod.sh built on top (hooks.jar, the APK, and what the mod's executable +# build.sh, if it has one, wrote in build-mod.sh's out dir). # tools/mkmodpkg.sh mods/ # New key: java -cp out/engine-host hmgapi.engine.Signing keygen # In the mod SDK (bin/mkmodpkg.sh), the mod dir is relative to where it's run, the @@ -28,18 +30,20 @@ APPSRC=no; [ -f "$M/app/AndroidManifest.xml" ] && APPSRC=yes # app/ is the mod for f in "$M"/*; do case "${f##*/}" in build.sh|test.sh|src|tools|native) ;; app) [ $APPSRC = yes ] || cp -r "$f" "$W/$ID/" ;; *) cp -r "$f" "$W/$ID/" ;; esac done -if [ -d "$M/src" ] || [ $APPSRC = yes ]; then +if [ -d "$M/src" ] || [ $APPSRC = yes ] || [ -x "$M/build.sh" ]; then if [ $SDK = no ]; then ./build.sh mods >/dev/null || exit 1; B=out/mods/$ID elif [ -n "$HMGAPI_MOD_BUILD" ]; then B=$HMGAPI_MOD_BUILD else B=$W/build; sh "$HERE/build-mod.sh" "$M" "$B" "$W/work" >/dev/null || exit 1 fi + [ "$(sed -n 's/.*"id": *"\([^"]*\)".*/\1/p' "$B/mod.json" 2>/dev/null | head -1)" = "$ID" ] \ + || { echo "mkmodpkg.sh: $B isn't $ID as built (build-mod.sh's out dir for $M, with its mod.json)"; exit 1; } + cp -R "$B"/. "$W/$ID/" # what build-mod.sh built, the mod's build.sh's files too fi -[ -d "$M/src" ] && cp "$B/hooks.jar" "$W/$ID/" +[ -d "$M/src" ] && { [ -f "$W/$ID/hooks.jar" ] || { echo "mkmodpkg.sh: no hooks.jar in $B"; exit 1; }; } if [ $APPSRC = yes ]; then APK=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["apps"][0]["apk"])' "$M/mod.json") - mkdir -p "$W/$ID/$(dirname "$APK")" && cp "$B/$APK" "$W/$ID/$APK" || { echo "no built $APK"; exit 1; } + [ -f "$W/$ID/$APK" ] || { echo "no built $APK"; exit 1; } fi -[ -x "$M/build.sh" ] && sh "$M/build.sh" "$W/$ID" >/dev/null # Everything in the mod's folder goes into the package, which is public: a signing key # left there (the author key itself, an app's keystore) would go out with it, signed. LEAK=$(cd "$W/$ID" && { diff --git a/tools/sdk-test.sh b/tools/sdk-test.sh index e708215e..fdd9e29e 100644 --- a/tools/sdk-test.sh +++ b/tools/sdk-test.sh @@ -152,4 +152,118 @@ has "... says to pin a newer SDK" "but the SDK is $V" "$o" pts "<3" "\"$P1\": \"observe\"" set +e; o=$(HMGAPI_FLOOR_POINTS=$T/floor.txt python3 $S/check-points.py $T/p/p 2>&1); r=$?; set -e check "... points but no floor: fails" 1 $r + +# ---- a mod's own build step (an executable build.sh) in a folder not named by its id, as egmp-aa-ev +# has: hooks.jar from src/, then build.sh's service jar, built from tools/ (left out of the package) +R=$T/r; mkdir -p $R && cd $R +F=relay-folder +mkdir -p $F/tools/relay/src/example/relay && cp -r $M/hello/src $F/ +printf '{"id": "built-step", "version": "1.0.0", "hmgapi": ">=1.0.0", "hooks": {"jar": "hooks.jar", "entry": "example.hello.Hello"},\n "services": [{"name": "relay", "jar": "relay.jar", "class": "example.relay.Relay", "user": "system"}]}\n' > $F/mod.json +printf 'package example.relay;\npublic class Relay { public static void main(String[] a) { System.out.println(hmgapi.client.HmgApi.class.getName()); } }\n' \ + > $F/tools/relay/src/example/relay/Relay.java +cat > $F/build.sh <<'SH' +#!/bin/sh +# the relay service: relay.jar, with hmgapi-client.jar's classes inside +set -e +O=${1:?usage: build.sh } +W=$(mktemp -d); trap 'rm -rf "$W"' EXIT +(cd "$W" && jar xf "$HMGAPI_CLIENT" hmgapi) +javac --release 8 -Xlint:-options -nowarn -cp "$ANDROID_JAR:$HMGAPI_CLIENT" -d "$W" $(find "$(dirname "$0")/tools/relay/src" -name '*.java') +"$D8" --release --min-api 19 --lib "$ANDROID_JAR" --output "$O/relay.jar" $(find "$W" -name '*.class') +echo "relay.jar: sdk=$HMGAPI_SDK out=$O" +SH +chmod 755 $F/build.sh +printf '#!/bin/sh\n[ -f "$HMGAPI_MOD_BUILD/relay.jar" ] && [ -f "$HMGAPI_MOD_BUILD/hooks.jar" ] && echo "ok built-step: relay.jar and hooks.jar"\n' > $F/test.sh +o=$(sh $S/build-mod.sh $F out/b 2>&1) && r=0 || r=$? +check "build-mod.sh: a mod with a build.sh builds" 0 $r +[ $r = 0 ] || echo "$o" +check "... its id is mod.json's, not the folder's" "mod built-step" "$(echo "$o" | tail -1)" +check "... hooks.jar from src/, then build.sh's relay.jar" yes "$([ -f out/b/hooks.jar ] && [ -f out/b/relay.jar ] && echo yes)" +unzip -p out/b/relay.jar classes.dex > $T/relay.dex +check "... hmgapi-client inside relay.jar" yes "$(grep -q 'Lhmgapi/client/HmgApi;' $T/relay.dex && grep -q 'Lexample/relay/Relay;' $T/relay.dex && echo yes)" +has "... build.sh got the out dir as an absolute path, and HMGAPI_SDK" "relay.jar: sdk=$T/sdk out=$R/out/b" "$o" +o=$(HMGAPI_MOD_BUILD=$R/out/b sh $S/mkmodpkg.sh $F $T/author.key 2>&1) || echo "$o" +check "mkmodpkg.sh: named by the id" yes "$([ -f out/packages/built-step-1.0.0.zip ] && echo yes)" +check "... with what build.sh built, without build.sh, src or tools" "hooks.jar|mod.json|relay.jar|" \ + "$(unzip -Z1 out/packages/built-step-1.0.0.zip | grep -v '^META-HMGAPI/' | sort | tr '\n' '|')" +cp out/packages/built-step-1.0.0.zip $T/built-step.zip +o=$(sh $S/mkmodpkg.sh $F $T/author.key 2>&1) || echo "$o" +check "... building it itself (no HMGAPI_MOD_BUILD) gives the same files" "$(pkg $T/built-step.zip)" "$(pkg $R/out/packages/built-step-1.0.0.zip)" +set +e; o=$(HMGAPI_MOD_BUILD=$T/b/hello sh $S/mkmodpkg.sh $F $T/author.key 2>&1); r=$?; set -e +check "... another mod's build in HMGAPI_MOD_BUILD: refused" 1 "$([ $r -ne 0 ] && echo 1)" +has "... says so" "isn't built-step as built" "$o" +printf '#!/bin/sh\necho "no NDK here"; exit 3\n' > $T/fail.sh +cp -r $F failing && cp $T/fail.sh failing/build.sh && chmod 755 failing/build.sh +set +e; o=$(sh $S/build-mod.sh failing out/f 2>&1); r=$?; set -e +check "build-mod.sh: a failing build.sh fails the build" 1 "$([ $r -ne 0 ] && echo 1)" +has "... with its output, and names it" "no NDK here|build-mod: failing/build.sh $R/out/f failed" "$(echo "$o" | tr '\n' '|')" +chmod 644 failing/build.sh +o=$(sh $S/build-mod.sh failing out/f 2>&1) && r=0 || r=$? +check "... a build.sh that isn't executable isn't run (as mkmodpkg.sh)" 0 $r +has "... and says so" "failing/build.sh isn't executable, so it isn't run" "$o" +rm -rf failing out +mkdir -p noid && printf '{"version": "1.0.0"}\n' > noid/mod.json +set +e; o=$(sh $S/build-mod.sh noid out/x 2>&1); r=$?; set -e +check "build-mod.sh: a mod.json without an id: refused" 1 "$([ $r -ne 0 ] && echo 1)" +has "... says so" 'no "id" in noid/mod.json' "$o" +rm -rf noid out + +# ---- the reusable workflow's own steps (.github/workflows/mod.yml), run here as Actions runs them +# (bash -e, GITHUB_ENV between steps), on this mod repo: hello, and built-step in relay-folder/ +cp -r $M/hello hello +GH=$T/gh; mkdir -p $GH; : > $GH/env +ghstep() { # ghstep [VAR=value...]: that step's run: script, with what earlier steps put in + # GITHUB_ENV, and the step's env: (the VAR=value) + python3 - "$REPO/.github/workflows/mod.yml" "$1" > $GH/step.sh <<'PY' || return 1 +import sys, textwrap +lines = open(sys.argv[1]).read().split("\n") +ind = lambda l: len(l) - len(l.lstrip()) +i = next(i for i, l in enumerate(lines) if l.strip() == "- name: " + sys.argv[2]) +j = next(j for j in range(i + 1, len(lines)) if lines[j].strip().startswith("run:")) +if lines[j].strip() != "run: |": + print(lines[j].strip()[4:].strip()) +else: + body = [] + for l in lines[j + 1:]: + if l.strip() and ind(l) <= ind(lines[j]): + break + body.append(l) + print(textwrap.dedent("\n".join(body))) +PY + (while IFS= read -r kv; do export "$kv"; done < $GH/env + shift; for kv in "$@"; do export "$kv"; done + GITHUB_ENV=$GH/env GITHUB_STEP_SUMMARY=$GH/summary RUNNER_TEMP=$GH HMGAPI_SDK=$T/sdk bash -e $GH/step.sh) +} +o=$(ghstep "Which mods" MODS= 2>&1) || echo "$o" +check "workflow, which mods: every folder with a mod.json, by mod.json's id" "hello hello|relay-folder built-step|" "$(tr '\n' '|' < $GH/mod-ids)" +has "... the summary names both" "Mods: hello, relay-folder (built-step)" "$(cat $GH/summary)" +o=$(ghstep "HMG-API floor and hook points" REPO=Open-HMG/HMG-API 2>&1) && r=0 || r=$? +check "workflow, floor and hook points" 0 $r +[ $r = 0 ] || echo "$o" +o=$(ghstep "Build" 2>&1) && r=0 || r=$? +check "workflow, build: out/build/" 0 $r +[ $r = 0 ] || echo "$o" +check "... relay-folder in out/build/built-step, its build.sh's relay.jar too" yes "$([ -f out/build/built-step/relay.jar ] && [ -f out/build/hello/hooks.jar ] && echo yes)" +o=$(ghstep "Tests" 2>&1) && r=0 || r=$? +check "workflow, tests: each with its own build in HMGAPI_MOD_BUILD" 0 $r +has "... built-step's test.sh ran" "ok built-step: relay.jar and hooks.jar" "$o" +o=$(ghstep "Scripts only use what the head unit has" 2>&1) && r=0 || r=$? +check "workflow, check-scripts" 0 $r +o=$(ghstep "Packages (throwaway key)" 2>&1) && r=0 || r=$? +check "workflow, packages" 0 $r +[ $r = 0 ] || echo "$o" +check "... both packages and NEMESIS packages, by id" "built-step-1.0.0-nemesis-package.zip|built-step-1.0.0-nemesis.zip|hello-1.0.0-nemesis-package.zip|hello-1.0.0-nemesis.zip|built-step-1.0.0.zip|hello-1.0.0.zip|" \ + "$(ls out/dist out/packages | grep zip | tr '\n' '|')" +check "... built-step's package has relay.jar" yes "$(unzip -Z1 out/packages/built-step-1.0.0.zip | grep -qx relay.jar && echo yes)" +check "... the throwaway key is gone" "" "$(ls $GH | grep throwaway || true)" +# which mods: refused before anything is built +mkdir -p twin && cp hello/mod.json twin/ +set +e; o=$(ghstep "Which mods" MODS= 2>&1); r=$?; set -e +check "workflow, which mods: two folders with one id: refused" 1 "$([ $r -ne 0 ] && echo 1)" +has "... names them" "hello and twin are both mod hello" "$o" +printf '{"id": "Bad_Id"}\n' > twin/mod.json +set +e; o=$(ghstep "Which mods" MODS=twin 2>&1); r=$?; set -e +check "... an id the engine refuses: refused" 1 "$([ $r -ne 0 ] && echo 1)" +has "... says what an id is" "\"id\" is a mod id (a-z, 0-9 and -, up to 64), not 'Bad_Id'" "$o" +cd $REPO exit $fail From 1bcf114f5fd27690cbbfa2e0e95b8f043926b5bc Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 15 Nov 2026 22:30:37 -0500 Subject: [PATCH 03/69] Mod SDK: hmgapi-mod, a mod's whole loop in one command bin/hmgapi-mod wraps the SDK's tools, from a mod repo's root: new (a mod folder, an entry class, a test.sh running plan_test, the SDK pin, CI, .gitignore), build (build-mod.sh), check (check-points.py, check-scripts.sh), deps, test (build, deps, the mod's test.sh or the plan test), package (mkmodpkg.sh, mknemesismod.sh). deps (bin/mod-deps.py) gets each mod "requires" names, and what those require, from HMG-API's catalogue: the version against the range as the engine reads it (Requires, in the SDK's test jar), the download against the entry's SHA-256, the signature against its author key, which must be on maps/authors.json; cached in .hmgapi/deps. hmgapi-deps.txt pins a pre-release from the mod's own repo, same key. Over adb: install --adb (push, engine install, engine apply, wait for adb as the apply may restart adbd, then engine status if the link dropped, hmgapid reboot), logs (the mod's lines in HMG-API's log file, or a service's log) and settings get|set (pushed as a file and read on the unit, so the JSON keeps its quotes). Exit codes come back as a last line, since adb shell on Android 4.4 always exits 0. Each takes --dry-run; tested against a fake adb only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + build.sh | 7 +- core/runtime/test/hmgapi/engine/Requires.java | 33 ++ docs/mod-reference.md | 34 +- docs/mod-repos.md | 3 +- tools/sdk-test.sh | 180 +++++++++++ tools/sdk/README.txt | 25 ++ tools/sdk/hmgapi-mod | 299 ++++++++++++++++++ tools/sdk/mod-deps.py | 270 ++++++++++++++++ 9 files changed, 855 insertions(+), 4 deletions(-) create mode 100644 core/runtime/test/hmgapi/engine/Requires.java create mode 100755 tools/sdk/hmgapi-mod create mode 100755 tools/sdk/mod-deps.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d75e594..1102c105 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ hook point the mod declares is mapped, its hooks load, which points it shares with other mods, and that its native recipes stay clear of a required mod's recipes for the same library build. Mod repos no longer need HMG-API's source for its maps. +- **`hmgapi-mod`: a mod's whole loop in one command.** The SDK's `bin/hmgapi-mod` wraps its + tools: `new` (a mod folder, its test, the SDK pin and CI), `build`, `check`, `test` + (with the plan test), `package` (the signed and the NEMESIS package), and `deps`, which + gets the mods `"requires"` names from HMG-API's catalogue, checks each download's SHA-256 + and author key, and caches it. On a head unit over adb: `install --adb` (install, apply, + wait for adb after adbd's restart, restart the unit), `logs` (HMG-API's log file, not + logcat's few seconds) and `settings get|set` (pushed as a file, so the JSON keeps its + quotes); each with `--dry-run`. ## 1.1.0-rc.2 (2026-11-15) diff --git a/build.sh b/build.sh index f16224b4..3e9383fa 100755 --- a/build.sh +++ b/build.sh @@ -139,10 +139,12 @@ sdk() { javac --release 8 -Xlint:-options -nowarn -d "$OUT/sdk-build/engine" core/runtime/java/hmgapi/engine/*.java jarof "$OUT/sdk-build/engine" "$S/lib/hmgapi-engine.jar" # MemRecipeTest: a mod's native recipes on real libraries ( triples); - # RecipeCheck: without them, against the recipes of the mods it requires (test/lib.sh plan_test) + # RecipeCheck: without them, against the recipes of the mods it requires (test/lib.sh plan_test); + # Requires: a mod's "requires" read and matched as the engine does (bin/mod-deps.py) mkdir -p "$OUT/sdk-build/engine-test" javac --release 8 -Xlint:-options -nowarn -cp "$OUT/sdk-build/engine" -d "$OUT/sdk-build/engine-test" \ - core/runtime/test/hmgapi/engine/MemRecipeTest.java core/runtime/test/hmgapi/engine/RecipeCheck.java + core/runtime/test/hmgapi/engine/MemRecipeTest.java core/runtime/test/hmgapi/engine/RecipeCheck.java \ + core/runtime/test/hmgapi/engine/Requires.java jarof "$OUT/sdk-build/engine-test" "$S/test/hmgapi-engine-test.jar" cp "$OUT/lpatch-host" "$S/bin/" cp tools/lpatch/lpatch.c tools/lpatch/build.sh "$S/src/lpatch/" @@ -151,6 +153,7 @@ sdk() { cp tools/requirements.txt core/runtime/unit-commands.txt "$S/" cp -r install/nemesis/mod "$S/nemesis/mod" cp install/nemesis/bin/open.sh "$S/nemesis/bin/" + cp tools/sdk/hmgapi-mod tools/sdk/mod-deps.py "$S/bin/" # the mod's loop, wrapping the tools above cp tools/sdk/lib.sh "$S/test/lib.sh" cp tools/sdk/plan.py "$S/test/plan.py" # the hook maps (public: point names and md5s), for test/lib.sh's plan test diff --git a/core/runtime/test/hmgapi/engine/Requires.java b/core/runtime/test/hmgapi/engine/Requires.java new file mode 100644 index 00000000..d6077afd --- /dev/null +++ b/core/runtime/test/hmgapi/engine/Requires.java @@ -0,0 +1,33 @@ +package hmgapi.engine; + +import java.io.File; +import java.nio.file.Files; +import java.util.Map; + +/** + * A mod's "requires", read and matched as the engine does (Version.deps, Version.satisfies), + * for the mod SDK's bin/mod-deps.py: + * Requires list one " " line per required mod ("" alone: any version) + * Requires satisfies exit 0 if the version is in the range, 1 if not, 2 if either is malformed + */ +public final class Requires { + public static void main(String[] a) throws Exception { + if (a.length == 2 && "list".equals(a[0])) { + Map mj = Json.object(new String(Files.readAllBytes(new File(a[1], "mod.json").toPath()), "UTF-8")); + for (Version.Dep d : Version.deps(mj.get("requires"))) { + System.out.println(d.id + (d.range == null ? "" : " " + d.range)); + } + return; + } + if (a.length == 3 && "satisfies".equals(a[0])) { + try { + System.exit(Version.satisfies(a[1], a[2]) ? 0 : 1); + } catch (IllegalArgumentException e) { + System.err.println(e.getMessage()); + System.exit(2); + } + } + System.err.println("usage: Requires list | satisfies "); + System.exit(2); + } +} diff --git a/docs/mod-reference.md b/docs/mod-reference.md index e438b56f..baa84a6f 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -369,7 +369,36 @@ A mod whose `build.sh` compiles native code can ask for an Android NDK with `with: ndk: ""`, as `sdkmanager` names it (hmgapi-adbd: `21.4.7075529`, r21e). The workflow installs it before the build, with `NDK` and `ANDROID_NDK_HOME` pointing at it. -On your machine, with the SDK unpacked in `$HMGAPI_SDK` and the Android SDK in `ANDROID_HOME`: +On your machine, with the SDK unpacked in `$HMGAPI_SDK` and the Android SDK in +`ANDROID_HOME`, `hmgapi-mod` runs the whole loop from the repository's root: + +``` +$HMGAPI_SDK/bin/hmgapi-mod new my-mod --name "My mod" # my-mod/, hmgapi-sdk.json, CI +$HMGAPI_SDK/bin/hmgapi-mod build # out/build/my-mod +$HMGAPI_SDK/bin/hmgapi-mod check # the "hmgapi" floor, points, scripts +$HMGAPI_SDK/bin/hmgapi-mod test # build, deps, my-mod/test.sh +$HMGAPI_SDK/bin/hmgapi-mod package --key ~/keys/me.key # out/packages, out/dist (NEMESIS) +$HMGAPI_SDK/bin/hmgapi-mod install --adb # on the head unit, then it restarts +$HMGAPI_SDK/bin/hmgapi-mod logs my-mod +$HMGAPI_SDK/bin/hmgapi-mod settings set my-mod my-settings.json +``` + +Your author key: `java -cp $HMGAPI_SDK/lib/hmgapi-engine.jar hmgapi.engine.Signing keygen `, +kept out of the repository. `deps` gets each mod your `"requires"` names from HMG-API's +catalogue (`catalog/`): the download, checked against the entry's SHA-256 and signed by its +author key, which must be on HMG-API's author list; cached in `.hmgapi/deps`. A required +mod's pre-release isn't in the catalogue: pin it in `hmgapi-deps.txt` at the root, +` `, from a release of that mod's own repository. `test` passes +the folders to your `test.sh` in `HMGAPI_MOD_DEPS`, for `plan_test` (below). + +`install --adb` pushes `out/packages/-.zip`, runs `hmgapid engine install` and +`engine apply`, waits for adb to come back (an apply can restart adbd: then it asks +`engine status` how the apply went), and restarts the head unit (`--no-reboot` to skip). +`logs` reads HMG-API's log file, as logcat holds only seconds on these units. `settings set` +pushes the file and reads it on the unit: JSON written through a shell command line loses +its quotes. Each takes `--dry-run`, which prints the adb commands and runs none. + +The same steps by hand, which is what `hmgapi-mod` runs: ``` $HMGAPI_SDK/bin/build-mod.sh my-mod out/build/my-mod @@ -397,6 +426,9 @@ plan_test "$(dirname "$0")" ../other-mod/other-mod exit $fail ``` +The `test.sh` that `hmgapi-mod new` writes takes them from `HMGAPI_MOD_DEPS` (set by +`hmgapi-mod test`), or runs `hmgapi-mod deps` itself (HMG-API's mod workflow, in CI). + A unit there has stand-ins, not the car's files, so file changes (`patches.json`) are left to the stock-file tests below. `PLAN_POINTS` adds points your code reads by name (through `Points`) to the mapped check; `HMGAPI_MAPS` uses another HMG-API's `maps/`. diff --git a/docs/mod-repos.md b/docs/mod-repos.md index ac850362..3717bd37 100644 --- a/docs/mod-repos.md +++ b/docs/mod-repos.md @@ -85,12 +85,13 @@ installs `android.jar` and `d8` as core's CI does). | `lib/hmgapi-client.jar` | `./build.sh client` | mods' own apps and services (bundled, as now) | | `lib/hmgapi-engine.jar` | `core/runtime/java/hmgapi/engine` | host tests (`Engine` with `HMGAPI_HOST=1`), `Signing`, `ScriptCheck` | | `bin/lpatch-host` + `src/lpatch/` | `tools/lpatch` | host tests of patches and recipes; source to build it on macOS | +| `bin/hmgapi-mod`, `bin/mod-deps.py` | `tools/sdk/` | the mod's loop (new, build, check, deps, test, package, install over adb, logs, settings), wrapping the rest | | `bin/build-mod.sh` | `build.sh mods()`, one mod | `hooks.jar` and app APK from a mod folder | | `bin/mkmodpkg.sh`, `bin/mknemesismod.sh`, `bin/nemesis-meta.py`, `bin/nemesis-version.py`, `nemesis/mod/` | `tools/`, `install/nemesis/mod/`, `install/nemesis/bin/open.sh` | signed package, NEMESIS package | | `bin/check-scripts.sh`, `unit-commands.txt` | `tools/check-scripts.sh`, `core/runtime/unit-commands.txt` | unit-only commands in mod scripts | | `bin/mkrecipe.py`, `bin/mkdelta.py`, `bin/mkmemrecipe.py`, `bin/mkicon.sh`, `bin/mod-draft.py` | `tools/` | recipes, delta sets, tile pictures, new mod drafts | | `test/lib.sh` | the `check`/`has`/`eng` helpers every mod `test.sh` copies today | mod tests | -| `test/plan.py`, `test/hmgapi-engine-test.jar` (`RecipeCheck`, `MemRecipeTest`) | `tools/sdk/plan.py`, `core/runtime/test` | `test/lib.sh`'s plan test, native recipes | +| `test/plan.py`, `test/hmgapi-engine-test.jar` (`RecipeCheck`, `MemRecipeTest`, `Requires`) | `tools/sdk/plan.py`, `core/runtime/test` | `test/lib.sh`'s plan test, native recipes | | `maps/` | `maps/` (without `coverage.json`) | the plan test: a fake head unit per car with a map | | `points.txt`, `catalogue/*.json` | `core/hookpoints` | check the mod's `hooks.points` exist | | `VERSION` | `Engine.HMGAPI_VERSION` | | diff --git a/tools/sdk-test.sh b/tools/sdk-test.sh index d22385a7..40d1da8a 100644 --- a/tools/sdk-test.sh +++ b/tools/sdk-test.sh @@ -193,6 +193,186 @@ has "... the mistake is a problem" "got [user: prop ro.x: only persist.* propert check "... the fake unit's stand-in files aren't" "" "$(echo "$o" | grep 'libx.so: not on this head unit' || true)" has "... names the point" "gpm.no_such_point: not in this car's map" "$o" +# ---- bin/hmgapi-mod: a mod repo's loop, from its root, with the SDK alone +HM="sh $T/sdk/bin/hmgapi-mod" +mkdir -p $T/repo && cd $T/repo +o=$($HM new my-mod --name "My mod" --author Tester 2>&1) || echo "$o" +check "new: the mod, its test, the SDK pin, CI and .gitignore" \ + "./.github/workflows/ci.yml ./.gitignore ./hmgapi-sdk.json ./my-mod/mod.json ./my-mod/src/mod/my_mod/MyMod.java ./my-mod/test.sh" \ + "$(find . -type f | sort | tr '\n' ' ' | sed 's/ $//')" +check "... mod.json: id, name, author, the SDK's release as the floor, its entry class" "my-mod|My mod|Tester|>=${V%%-*}|mod.my_mod.MyMod" \ + "$(python3 -c 'import json; m=json.load(open("my-mod/mod.json")); print("|".join([m["id"], m["name"], m["authors"][0], m["hmgapi"], m["hooks"]["entry"]]))')" +check "... CI calls HMG-API's mod workflow at the SDK's release" " uses: Open-HMG/HMG-API/.github/workflows/mod.yml@v$V" "$(grep 'uses:' .github/workflows/ci.yml)" +set +e; o=$($HM new my-mod --author Tester 2>&1); r=$?; set -e +check "... an existing folder: refused" "2|hmgapi-mod: my-mod already exists" "$r|$o" +set +e; o=$($HM new My_Mod --author Tester 2>&1); r=$?; set -e +check "... not an id: refused" 2 $r +o=$($HM build 2>&1) && r=0 || r=$? +check "build: the one mod here, into out/build/" "0|yes" "$r|$([ -f out/build/my-mod/hooks.jar ] && echo yes)" +check "... the same hooks.jar as bin/build-mod.sh" "$(sh $S/build-mod.sh my-mod $T/bm >/dev/null 2>&1; md5 $T/bm/hooks.jar)" "$(md5 out/build/my-mod/hooks.jar)" +o=$($HM check 2>&1) && r=0 || r=$? +check "check: check-points.py and check-scripts.sh pass" 0 $r +has "... check-points.py ran" 'my-mod: "hmgapi"' "$o" +printf '#!/system/bin/sh\necho x | tr x y\n' > my-mod/s.sh +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["services"]=[{"name": "s", "script": "s.sh"}]; json.dump(m, open("my-mod/mod.json", "w"))' +set +e; o=$($HM check 2>&1); r=$?; set -e +check "... a script calling tr: fails" 1 $r +has "... names it" "tr" "$o" +rm my-mod/s.sh; python3 -c 'import json; m=json.load(open("my-mod/mod.json")); del m["services"]; json.dump(m, open("my-mod/mod.json", "w"))' +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["system"]={"product": "CVEV.USA."}; json.dump(m, open("my-mod/mod.json", "w"))' +o=$($HM test 2>&1) && r=0 || r=$? +check "test: builds, then its test.sh (the plan test)" 0 $r +[ $r = 0 ] || echo "$o" +has "... on the cars its \"system\" names" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): my-mod's hooks load" "$o" +has "... no mods required" 'no "requires" in mod.json' "$o" +mkdir -p $T/nt && cp -r my-mod $T/nt/ && rm $T/nt/my-mod/test.sh +o=$(cd $T/nt && $HM test 2>&1) && r=0 || r=$? +check "... without a test.sh: the plan test" "0|yes" "$r|$(echo "$o" | grep -q "my-mod's hooks load" && echo yes)" +mkdir $T/empty; set +e; o=$(cd $T/empty && $HM build 2>&1); r=$?; set -e +check "no mod here: says so" "2" "$r" +has "... and what to do" "name the mod's folder" "$o" + +# deps: a catalogue (catalog/ and maps/authors.json, as HMG-API has them) with a signed base mod in it +C=$T/core; mkdir -p $C/catalog $C/maps $C/dl $T/repo/base +java -cp $T/sdk/lib/hmgapi-engine.jar hmgapi.engine.Signing keygen $T/other.key > /dev/null +UUID=$(java -cp $T/sdk/lib/hmgapi-engine.jar hmgapi.engine.Signing uuid $T/author.key) +printf '{"id": "base", "version": "1.2.0", "hmgapi": ">=1.0.0", "system": {"product": "CVEV.USA."}}\n' > base/mod.json +(OUT=$T/bo sh $S/mkmodpkg.sh base $T/author.key > /dev/null) && cp $T/bo/packages/base-1.2.0.zip $C/dl/ +cat > $T/entry.py <<'EOF' +import hashlib, json, sys +d, uuid, url, ver = sys.argv[1:5] +json.dump({"id": "base", "name": "Base", "description": "x", "authors": ["Tester"], "uuid": uuid, "version": ver, + "repo": "https://example.invalid/base", "download": url, + "sha256": hashlib.sha256(open(sys.argv[5], "rb").read()).hexdigest()}, open(d + "/catalog/base.json", "w")) +json.dump({"authors": {uuid: {"name": "Tester"}}}, open(d + "/maps/authors.json", "w")) +EOF +python3 $T/entry.py $C $UUID file://$C/dl/base-1.2.0.zip 1.2.0 $C/dl/base-1.2.0.zip +rm -rf base +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["requires"]=["base ^1.1"]; json.dump(m, open("my-mod/mod.json", "w"))' +export HMGAPI_CATALOG=$C/catalog +o=$($HM deps 2>$T/err) && r=0 || r=$? +TP=$(cd $T && pwd -P) # mktemp's folder, as the tools see it (macOS: /private/var/...) +check "deps: the required mod from the catalogue, its folder printed" "0|$TP/repo/.hmgapi/deps/base-1.2.0" "$r|$o" +has "... SHA-256 and signature checked" "ok base 1.2.0: downloaded from the catalogue, SHA-256 and signature match (author key $UUID)" "$(cat $T/err)" +check "... the mod folder, as signed" yes "$(java -cp $T/sdk/lib/hmgapi-engine.jar hmgapi.engine.Signing verify $o $UUID > /dev/null && echo yes)" +mv $C/dl/base-1.2.0.zip $C/dl/away.zip +o=$($HM deps 2>$T/err) && r=0 || r=$? +check "... next time from the cache (nothing to download)" "0|ok base 1.2.0: cached ($TP/repo/.hmgapi/deps/base-1.2.0.zip)" "$r|$(cat $T/err)" +mv $C/dl/away.zip $C/dl/base-1.2.0.zip +o=$($HM test 2>&1) && r=0 || r=$? +check "test: with the required mod beside it" 0 $r +has "... in the plan" "ok CVEV.USA.0000.V015.012.260507 (kia/ev6/usa/260507): my-mod's hooks load" "$o" +rm -rf .hmgapi +dep() { set +e; o=$($HM deps 2>&1); r=$?; set -e; } +printf 'tampered' >> $C/dl/base-1.2.0.zip +dep; check "... a download that isn't the catalogue's SHA-256: fails" 1 $r +has "... says so" "base 1.2.0: the download's SHA-256 is" "$o" +check "... nothing cached" "" "$(ls .hmgapi/deps)" +cp $T/bo/packages/base-1.2.0.zip $C/dl/ +OTHER=$(java -cp $T/sdk/lib/hmgapi-engine.jar hmgapi.engine.Signing uuid $T/other.key) +python3 $T/entry.py $C $OTHER file://$C/dl/base-1.2.0.zip 1.2.0 $C/dl/base-1.2.0.zip +dep; check "... signed with another key than the entry's: fails" 1 $r +has "... names the key" "$OTHER" "$o" +python3 $T/entry.py $C $UUID file://$C/dl/base-1.2.0.zip 1.2.0 $C/dl/base-1.2.0.zip +printf '{"authors": {}}\n' > $C/maps/authors.json +dep; check "... an author key HMG-API doesn't list: fails" 1 $r +has "... says so" "isn't on HMG-API's author list" "$o" +python3 $T/entry.py $C $UUID file://$C/dl/base-1.2.0.zip 1.2.0 $C/dl/base-1.2.0.zip +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["requires"]=["base >=2.0.0-rc.1"]; json.dump(m, open("my-mod/mod.json", "w"))' +dep; check "... a range the catalogue's version isn't in: fails" 1 $r +has "... says which, and how to pin a pre-release" "my-mod requires base >=2.0.0-rc.1, but the catalogue has 1.2.0 (a pre-release can be pinned: hmgapi-deps.txt)" "$o" +echo "base 2.0.0-rc.1 file://$C/dl/base-1.2.0.zip $(python3 -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1], "rb").read()).hexdigest())' $C/dl/base-1.2.0.zip)" > hmgapi-deps.txt +dep; check "... a pin outside the mod's own repo: refused" 1 $r +has "... says where it must be" "must be a release of the mod's own repo (https://example.invalid/base/releases/download/...)" "$o" +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["requires"]=["nothere"]; json.dump(m, open("my-mod/mod.json", "w"))' +rm hmgapi-deps.txt +dep; check "... a mod not in the catalogue: fails" 1 $r +has "... says so" "my-mod requires nothere, which isn't in HMG-API's catalogue" "$o" +python3 -c 'import json; m=json.load(open("my-mod/mod.json")); m["requires"]=["base ^1.1"]; json.dump(m, open("my-mod/mod.json", "w"))' +unset HMGAPI_CATALOG + +# package: the signed package and the NEMESIS one +o=$($HM package --key $T/author.key 2>&1) && r=0 || r=$? +check "package: out/packages and out/dist" "0|yes" "$r|$([ -f out/packages/my-mod-0.1.0.zip ] && [ -f out/dist/my-mod-0.1.0-nemesis-package.zip ] && echo yes)" +set +e; o=$($HM package 2>&1); r=$?; set -e +has "... without --key: says how to make one" "Signing keygen" "$o" + +# the adb commands, against a fake adb: it runs each "adb shell" line here with a fake hmgapid, +# /data/ under $FK, and drops the link once during apply, as adbd's restart does +FK=$T/fake; mkdir -p $FK/bin $FK/data/local/tmp $FK/data/hmgapi/settings $FK/data/hmgapi/logs/hmgapi +cat > $FK/bin/adb <> $FK/bin/adb <<'EOF' +echo "adb $*" >> $FK/adb.log +case $1 in +get-state) echo device ;; +push) cp "$2" "$FK$3" ;; +shell) + shift; c=$(printf '%s' "$*" | sed "s#/data/#$FK/data/#g") # adb joins its arguments, the unit's shell splits them + if [ -f $FK/down ]; then rm $FK/down; echo "error: device offline" >&2; exit 1; fi + case $c in + *"engine apply"*) + [ -f $FK/drop ] || { PATH=$FK/bin:$PATH sh -c "$c"; exit 0; } + rm $FK/drop; PATH=$FK/bin:$PATH hmgapid engine apply; touch $FK/down; exit 0 ;; # no exit code: the link dropped + esac + PATH=$FK/bin:$PATH sh -c "$c" | sed 's/$/\r/' ;; # adb shell's line ends +esac +EOF +cat > $FK/bin/hmgapid <<'EOF' +#!/bin/sh +FK=${0%/bin/hmgapid} +echo "hmgapid $*" >> $FK/hmgapid.log +case $1 in +version) echo "hmgapid 1.1.0" ;; +engine) case $2 in install) echo "installed $3" ;; apply) echo "change ..."; echo "applied" ;; status) echo "HMG-API owns no files" ;; esac ;; +reboot) echo restarting ;; +setting-set) printf '%s' "$3" > $FK/data/hmgapi/settings/$2.json; echo saved ;; +setting-get) cat $FK/data/hmgapi/settings/$2.json ;; +service-log) echo "log of $2/$3" ;; +sh) sh -c "$2" ;; +*) exit 2 ;; +esac +EOF +chmod 755 $FK/bin/adb $FK/bin/hmgapid +export ADB=$FK/bin/adb HMGAPI_ADB_WAIT=10 +o=$($HM install --adb --dry-run 2>&1) && r=0 || r=$? +check "install --adb --dry-run: runs no adb command" "0|" "$r|$(cat $FK/adb.log 2>/dev/null)" +has "... prints them: push, install, apply, wait, restart" "+ $ADB push out/packages/my-mod-0.1.0.zip /data/local/tmp/my-mod-0.1.0.zip|+ $ADB shell 'hmgapid engine install /data/local/tmp/my-mod-0.1.0.zip'|+ $ADB shell 'rm -f /data/local/tmp/my-mod-0.1.0.zip'|+ $ADB shell 'hmgapid engine apply'|+ $ADB wait-for-device, then $ADB shell echo until it answers|+ $ADB shell 'hmgapid reboot'|(dry run: nothing was sent)|" "$(echo "$o" | tr '\n' '|')" +o=$($HM install --adb 2>&1) && r=0 || r=$? +check "install --adb: push, install, apply, restart" 0 $r +[ $r = 0 ] || echo "$o" +check "... the head unit's commands, in order" "hmgapid version|hmgapid engine install $FK/data/local/tmp/my-mod-0.1.0.zip|hmgapid engine apply|hmgapid reboot|" "$(tr '\n' '|' < $FK/hmgapid.log)" +check "... the package pushed, then removed" "" "$(ls $FK/data/local/tmp)" +rm $FK/hmgapid.log; touch $FK/drop +o=$($HM install --adb --no-reboot 2>&1) && r=0 || r=$? +check "... adb dropped during the apply: waits, asks the engine" 0 $r +[ $r = 0 ] || echo "$o" +has "... says so" "adb dropped during the apply (it restarts adbd): asking the engine how it went" "$o" +check "... then status, no restart (--no-reboot)" "hmgapid version|hmgapid engine install $FK/data/local/tmp/my-mod-0.1.0.zip|hmgapid engine apply|hmgapid engine status|" "$(tr '\n' '|' < $FK/hmgapid.log)" +J='{"name": "it'"'"'s \"quoted\"", "list": [1, 2], "path": "a b;c $HOME"}' +printf '%s\n' "$J" > $T/s.json +o=$($HM settings set my-mod $T/s.json 2>&1) && r=0 || r=$? +check "settings set: a JSON file reaches the unit as it is (quotes, spaces, \$)" "0|$J" "$r|$(cat $FK/data/hmgapi/settings/my-mod.json)" +check "... pushed as a file, then removed" "" "$(ls $FK/data/local/tmp)" +o=$($HM settings get my-mod 2>&1) && r=0 || r=$? +check "settings get: the settings, indented" "0|$(python3 -c 'import json,sys; print(json.dumps(json.loads(sys.argv[1]), indent=2))' "$J")" "$r|$o" +printf '{"a":' > $T/bad.json +set +e; o=$($HM settings set my-mod $T/bad.json 2>&1); r=$?; set -e +check "... not JSON: refused before adb" "2|yes|" "$r|$(echo "$o" | grep -q "isn't a JSON object" && echo yes)|$(grep -c bad.json $FK/adb.log | grep -v '^0$' || true)" +printf '11-15 10:00:00.000 I/HMG-API( 1): [my-mod] old\n' > $FK/data/hmgapi/logs/hmgapi/log.log.1 +printf '11-15 10:00:01.000 I/HMG-API( 1): [other] x\n11-15 10:00:02.000 I/HMG-API( 1): [my-mod] zygote: version 0.1.0\n' > $FK/data/hmgapi/logs/hmgapi/log.log +o=$($HM logs my-mod 2>&1) && r=0 || r=$? +check "logs: the mod's lines in HMG-API's log, older file first" "0|11-15 10:00:00.000 I/HMG-API( 1): [my-mod] old|11-15 10:00:02.000 I/HMG-API( 1): [my-mod] zygote: version 0.1.0" "$r|$(echo "$o" | tr '\n' '|' | sed 's/|$//')" +o=$($HM logs my-mod relay 2>&1) && r=0 || r=$? +check "... a service's log" "0|log of my-mod/relay" "$r|$o" +sed 's/^version) echo "hmgapid 1.1.0" ;;/version) echo "hmgapid: daemon not running" ;;/' $FK/bin/hmgapid > $FK/h && mv $FK/h $FK/bin/hmgapid && chmod 755 $FK/bin/hmgapid +set +e; o=$($HM settings get my-mod 2>&1); r=$?; set -e +check "... HMG-API not running on the unit: says so" "2|hmgapi-mod: HMG-API isn't running on the unit (hmgapid version: hmgapid: daemon not running)" "$r|$o" +unset ADB HMGAPI_ADB_WAIT +cd $M + # ---- check-scripts.sh and check-points.py o=$(sh $S/check-scripts.sh hello side-panel 2>&1) && r=0 || r=$? check "check-scripts.sh: the examples pass" 0 $r diff --git a/tools/sdk/README.txt b/tools/sdk/README.txt index 6fa30c5c..9786a379 100644 --- a/tools/sdk/README.txt +++ b/tools/sdk/README.txt @@ -10,6 +10,8 @@ the Android SDK (build-tools, a platform android.jar) and set ANDROID_HOME. lib/hmgapi-runtime-stubs.jar the car classes runtime signatures name: compile only lib/hmgapi-client.jar for a mod's own app or service (bundled in it) lib/hmgapi-engine.jar the engine on this machine (HMGAPI_HOST=1), Signing, ScriptCheck + bin/hmgapi-mod a mod's whole loop, wrapping the tools below (see under) + bin/mod-deps.py the mods it requires, from HMG-API's catalogue (hmgapi-mod deps) bin/build-mod.sh hooks.jar from src/, the APK from app/ bin/mkmodpkg.sh the signed package, out/packages/-.zip bin/mknemesismod.sh the same mod as a NEMESIS package, out/dist/ @@ -28,6 +30,29 @@ the Android SDK (build-tools, a platform android.jar) and set ANDROID_HOME. points.txt, catalogue/ the hook points this release has, and their catalogue nemesis/ the NEMESIS package templates +hmgapi-mod, from the mod repository's root (: the mod's folder, by default the one +folder there with a mod.json): + hmgapi-mod new [--name ] [--author ] / (mod.json, an entry class, + test.sh), hmgapi-sdk.json, .github/workflows/ci.yml, .gitignore + hmgapi-mod build [] bin/build-mod.sh into out/build/ + hmgapi-mod check [] bin/check-points.py and bin/check-scripts.sh + hmgapi-mod deps [] each mod "requires" names (and what those require), from HMG-API's + catalogue: its SHA-256 and author key checked, cached in + .hmgapi/deps; prints their folders. HMGAPI_CATALOG: a catalog/ + folder or URL; hmgapi-deps.txt: " " + pins of a pre-release, from the mod's own repo, same author key + hmgapi-mod test [] build, deps, then its test.sh (HMGAPI_MOD_BUILD, HMGAPI_MOD_DEPS + set), or the plan test if it has none + hmgapi-mod package [] --key bin/mkmodpkg.sh, then bin/mknemesismod.sh + hmgapi-mod install --adb [|] [--no-reboot] push, hmgapid engine install, engine + apply, wait for adb (the apply may restart adbd), hmgapid reboot + hmgapi-mod logs [] its lines in HMG-API's log (logcat only holds + seconds on these units), or one of its services' log + hmgapi-mod settings get | set its settings; set pushes the file (JSON + in a shell command line loses its quotes) +The adb commands need HMG-API on the unit and USB adb; --dry-run prints them instead. +ADB: the adb binary; ANDROID_SERIAL: which device. + The plan test: in a mod's test.sh, after `. "$HMGAPI_SDK/test/lib.sh"`, plan_test [...] makes a fake head unit for each car the mod's "system" names that has a map here, puts diff --git a/tools/sdk/hmgapi-mod b/tools/sdk/hmgapi-mod new file mode 100755 index 00000000..c28cb830 --- /dev/null +++ b/tools/sdk/hmgapi-mod @@ -0,0 +1,299 @@ +#!/bin/sh +# hmgapi-mod: a mod's whole loop with the HMG-API mod SDK, from its repository's root +# (in the SDK as bin/hmgapi-mod; it wraps the SDK's other tools). +# +# hmgapi-mod new [--name ] [--author ] a new mod: /, hmgapi-sdk.json, CI +# hmgapi-mod build [] bin/build-mod.sh into out/build/ +# hmgapi-mod check [] bin/check-points.py and bin/check-scripts.sh +# hmgapi-mod deps [] the mods it requires, from HMG-API's catalogue, +# checked and cached in .hmgapi/deps (bin/mod-deps.py) +# hmgapi-mod test [] build, deps, then the mod's test.sh, or without one +# the plan test (test/lib.sh plan_test) +# hmgapi-mod package [] --key bin/mkmodpkg.sh, then bin/mknemesismod.sh +# hmgapi-mod install --adb [|] [--no-reboot] over adb: push, engine install, +# engine apply, wait for adb, restart the head unit +# hmgapi-mod logs [] the mod's lines in HMG-API's log, or a service's log +# hmgapi-mod settings get its settings (/data/hmgapi/settings/.json) +# hmgapi-mod settings set a JSON file as its settings +# +# : the mod's folder; by default the one folder here with a mod.json (or this one). +# The adb commands take --dry-run (print the adb commands, run none); ADB names the adb +# binary (default adb) and ANDROID_SERIAL picks the device, as for adb itself. +# HMGAPI_SDK: the SDK (default: the one this script is in). Plain sh; python3 and a JDK. +set -e +HERE=$(cd "$(dirname "$0")" && pwd) +HMGAPI_SDK=${HMGAPI_SDK:-$(cd "$HERE/.." && pwd)} +export HMGAPI_SDK +B=$HMGAPI_SDK/bin +ADB=${ADB:-adb} +DRY= +REMOTE_DIR=/data/local/tmp + +die() { echo "hmgapi-mod: $*" >&2; exit 2; } +usage() { sed -n '4,22s/^# \{0,1\}//p' "$0" >&2; exit 2; } +jget() { python3 -c 'import json,sys; v=json.load(open(sys.argv[1])).get(sys.argv[2], ""); print(v if isinstance(v, str) else "")' "$1" "$2"; } +valid_id() { printf '%s\n' "$1" | grep -Eq '^[a-z0-9][a-z0-9-]{0,63}$'; } + +# the mod folder: the argument, or the one folder here with a mod.json, or here +mod_dir() { + if [ -n "$1" ]; then + [ -f "$1/mod.json" ] || die "no mod.json in $1" + M=${1%/}; return + fi + if [ -f mod.json ]; then M=.; return; fi + found=$(for f in */mod.json; do [ ! -f "$f" ] || dirname "$f"; done) + case $(printf '%s\n' "$found" | grep -c . || true) in + 0) die "no mod here (no /mod.json): name the mod's folder, or make one with hmgapi-mod new " ;; + 1) M=$found ;; + *) die "several mods here ($(echo $found)): name one" ;; + esac +} +mod_id() { ID=$(jget "$M/mod.json" id); valid_id "$ID" || die "$M/mod.json: \"id\" is \"$ID\", not a mod id (a-z, 0-9 and -)"; } + +# ---- adb: each command printed with --dry-run instead of run; output without adb's \r +adb_do() { + if [ -n "$DRY" ]; then echo "+ $ADB $*"; return 0; fi + "$ADB" "$@" +} +# adb_sh : on the unit, its output shown and its exit code returned (adb shell on +# Android 4.4 always exits 0, so the code comes back as a last line); 255: the link dropped +adb_sh() { + if [ -n "$DRY" ]; then echo "+ $ADB shell '$1'"; return 0; fi + set +e + # (on a line of its own: setting-get's JSON has no newline at the end) + "$ADB" shell "$1; hmgapi_mod_rc=\$?; echo; echo hmgapi-mod-rc=\$hmgapi_mod_rc" > "$TMPF" 2>&1 + set -e + tr -d '\r' < "$TMPF" | sed -e '/^hmgapi-mod-rc=/d' | sed -e '$ { /^$/d; }' + r=$(tr -d '\r' < "$TMPF" | sed -n 's/^hmgapi-mod-rc=\([0-9]*\)$/\1/p') + return "${r:-255}" +} +# the unit back on adb (apply restarts adbd): up to HMGAPI_ADB_WAIT seconds (default 120) +adb_wait() { + if [ -n "$DRY" ]; then echo "+ $ADB wait-for-device, then $ADB shell echo until it answers"; return 0; fi + n=0 max=${HMGAPI_ADB_WAIT:-120} + while [ $n -lt "$max" ]; do + if "$ADB" shell echo hmgapi-mod-up 2>/dev/null | tr -d '\r' | grep -q '^hmgapi-mod-up$'; then return 0; fi + sleep 2; n=$((n + 2)) + done + die "the head unit didn't come back on adb within $max s (HMGAPI_ADB_WAIT)" +} +adb_ready() { + [ -n "$DRY" ] && return 0 + command -v "$ADB" >/dev/null 2>&1 || die "no $ADB: install Android's platform-tools, or set ADB" + st=$("$ADB" get-state 2>&1 | tr -d '\r') || true + [ "$st" = device ] || die "no head unit on adb ($ADB get-state: $st): USB adb on, cable in the USB port" + v=$("$ADB" shell 'hmgapid version' 2>&1 | tr -d '\r') + case $v in "hmgapid "[0-9]*) ;; *) die "HMG-API isn't running on the unit (hmgapid version: $v)" ;; esac +} + +TMPF=$(mktemp); trap 'rm -f "$TMPF"' EXIT +cmd=${1:-}; [ $# -gt 0 ] && shift +case $cmd in +new) + id=${1:-}; [ $# -gt 0 ] && shift + valid_id "$id" || die "new : an id is a-z, 0-9 and -, starting with a letter or digit" + name=$id author=$(git config user.name 2>/dev/null || true) + while [ $# -gt 0 ]; do + case $1 in + --name) name=${2:?--name }; shift 2 ;; + --author) author=${2:?--author }; shift 2 ;; + *) die "new: unknown option $1" ;; + esac + done + [ -n "$author" ] || die "new: give --author (no git user.name here)" + [ ! -e "$id" ] || die "$id already exists" + V=$(cat "$HMGAPI_SDK/VERSION") + pkg=mod.$(echo "$id" | sed 's/-/_/g') + # the entry class: the id in CamelCase (my-mod: MyMod), Mod first if it starts with a digit + cls=$(python3 -c 'import sys; c="".join(p[:1].upper() + p[1:] for p in sys.argv[1].split("-") if p); print(("Mod" if c[0].isdigit() else "") + c)' "$id") + mkdir -p "$id/src/$(echo "$pkg" | sed 's#\.#/#g')" + python3 - "$id" "$name" "$author" "${V%%-*}" "$pkg.$cls" <<'PY' +import json, sys +mid, name, author, floor, entry = sys.argv[1:] +m = {"id": mid, "name": name, "version": "0.1.0", "hmgapi": ">=" + floor, "authors": [author], "license": "AGPL-3.0", + "description": "", "system": "all", "hooks": {"jar": "hooks.jar", "entry": entry, "points": {}}} +open(mid + "/mod.json", "w").write(json.dumps(m, indent=2) + "\n") +PY + cat > "$id/src/$(echo "$pkg" | sed 's#\.#/#g')/$cls.java" < "$id/test.sh" <<'EOF' +#!/bin/sh +# Off-car test: this mod through HMG-API's plan on a fake head unit for each car its +# "system" names that HMG-API has a map for (the SDK's test/lib.sh, plan_test), beside +# the mods it requires (hmgapi-mod test passes them in HMGAPI_MOD_DEPS; without it, they +# come from HMG-API's catalogue here). Add your own checks below (check, has, eng...). +set -e +M=$(cd "$(dirname "$0")" && pwd) +. "${HMGAPI_SDK:?set HMGAPI_SDK to the unpacked HMG-API mod SDK}/test/lib.sh" +DEPS=${HMGAPI_MOD_DEPS-$("$HMGAPI_SDK/bin/hmgapi-mod" deps "$M")} +plan_test "$M" $DEPS +exit $fail +EOF + chmod 755 "$id/test.sh" + [ -e hmgapi-sdk.json ] || printf '{"version": "%s", "sha256": ""}\n' "$V" > hmgapi-sdk.json + if [ ! -e .github/workflows/ci.yml ]; then + mkdir -p .github/workflows + printf 'name: ci\non: [push, pull_request]\njobs:\n mod:\n uses: Open-HMG/HMG-API/.github/workflows/mod.yml@v%s\n' "$V" > .github/workflows/ci.yml + fi + [ -e .gitignore ] || printf 'out/\n.hmgapi/\n*.key\n' > .gitignore + echo "$id/: mod.json, src/$(echo "$pkg" | sed 's#\.#/#g')/$cls.java, test.sh" + echo "$id/mod.json: \"system\" is \"all\" (any head unit): name the cars the mod is for, with their region (\"product\": [\"CVEV.USA.\"])" + echo "hmgapi-sdk.json: pins SDK $V; put its sha256 in (SHA256SUMS on HMG-API's v$V release)" + echo "next: hmgapi-mod build, hmgapi-mod test (docs/mod-reference.md in HMG-API: \"Building a mod outside this repo\")" + ;; +build) + mod_dir "${1:-}"; mod_id + sh "$B/build-mod.sh" "$M" "out/build/$ID" "out/build-work/$ID" + echo "built: out/build/$ID" + ;; +check) + mod_dir "${1:-}" + r=0 + python3 "$B/check-points.py" "$M" || r=1 + sh "$B/check-scripts.sh" "$M" || r=1 + exit $r + ;; +deps) + mod_dir "${1:-}" + python3 "$B/mod-deps.py" "$M" + ;; +test) + mod_dir "${1:-}"; mod_id + sh "$B/build-mod.sh" "$M" "out/build/$ID" "out/build-work/$ID" > "$TMPF" 2>&1 || { cat "$TMPF"; die "build failed"; } + HMGAPI_MOD_DEPS=$(python3 "$B/mod-deps.py" "$M") || die "the mods $ID requires aren't all here (above)" + HMGAPI_MOD_BUILD=$PWD/out/build/$ID + export HMGAPI_MOD_DEPS HMGAPI_MOD_BUILD + r=0 + if [ -f "$M/test.sh" ]; then + sh "$M/test.sh" || r=$? + else + sh -c 'set -e; . "$HMGAPI_SDK/test/lib.sh"; plan_test "$1" $HMGAPI_MOD_DEPS; exit $fail' - "$M" || r=$? + fi + exit $r + ;; +package) + key=; arg= + while [ $# -gt 0 ]; do + case $1 in + --key) key=${2:?--key }; shift 2 ;; + -*) die "package: unknown option $1" ;; + *) arg=$1; shift ;; + esac + done + [ -n "$key" ] || die "package: --key (new one: java -cp \$HMGAPI_SDK/lib/hmgapi-engine.jar hmgapi.engine.Signing keygen ; keep it out of the repo)" + mod_dir "$arg"; mod_id + sh "$B/mkmodpkg.sh" "$M" "$key" + V=$(jget "$M/mod.json" version) + sh "$B/mknemesismod.sh" "out/packages/$ID-$V.zip" + ;; +install) + adb=; arg=; reboot=1 + while [ $# -gt 0 ]; do + case $1 in + --adb) adb=1; shift ;; + --dry-run) DRY=1; shift ;; + --no-reboot) reboot=; shift ;; + -*) die "install: unknown option $1" ;; + *) arg=$1; shift ;; + esac + done + [ -n "$adb" ] || die "install: only --adb for now (a USB stick or NEMESIS: HMG-API's docs)" + case $arg in + *.zip) Z=$arg; [ -f "$Z" ] || die "no $Z" ;; + *) mod_dir "$arg"; mod_id; V=$(jget "$M/mod.json" version); Z=out/packages/$ID-$V.zip + [ -f "$Z" ] || die "no $Z: hmgapi-mod package --key first" ;; + esac + base=$(basename "$Z") + printf '%s\n' "$base" | grep -Eq '^[A-Za-z0-9._+-]+$' || die "$base: a package name is letters, digits and . _ + -" + adb_ready + adb_do push "$Z" "$REMOTE_DIR/$base" + r=0; adb_sh "hmgapid engine install $REMOTE_DIR/$base" || r=$? + adb_sh "rm -f $REMOTE_DIR/$base" || true + [ $r = 0 ] || die "engine install failed (exit $r)" + # apply restarts adbd when a mod changes it: the link may drop before the exit code comes back + r=0; adb_sh "hmgapid engine apply" || r=$? + adb_wait + if [ $r = 255 ]; then + echo "adb dropped during the apply (it restarts adbd): asking the engine how it went" + r=0; adb_sh "hmgapid engine status" || r=$? + if [ -z "$DRY" ] && grep -q "an apply didn't finish" "$TMPF"; then die "the apply didn't finish (engine status above)"; fi + [ $r = 0 ] || [ $r = 255 ] || die "engine status: exit $r (above)" + elif [ $r != 0 ]; then + die "engine apply failed (exit $r): nothing changed, see above" + fi + if [ -n "$DRY" ]; then + [ -z "$reboot" ] || adb_sh "hmgapid reboot" + echo "(dry run: nothing was sent)" + elif [ -n "$reboot" ]; then + adb_sh "hmgapid reboot" || true + echo "the head unit restarts; installed $base" + else + echo "installed $base (applied; restart the head unit for hooks and file changes)" + fi + ;; +logs) + while [ $# -gt 0 ]; do case $1 in --dry-run) DRY=1; shift ;; *) break ;; esac; done + id=${1:-}; svc=${2:-} + valid_id "$id" || die "logs []" + adb_ready + if [ -n "$svc" ]; then + printf '%s\n' "$svc" | grep -Eq '^[A-Za-z0-9._-]+$' || die "$svc: not a service name" + adb_sh "hmgapid service-log $id $svc" + exit $? + fi + # the log keeper's file (logcat only holds seconds on these units), the older part first + L=/data/hmgapi/logs/hmgapi/log.log + if [ -n "$DRY" ]; then adb_sh "hmgapid sh 'cat $L.1 $L 2>/dev/null'"; echo "+ (lines with [$id])"; exit 0; fi + r=0; adb_sh "hmgapid sh 'cat $L.1 $L 2>/dev/null'" > "$TMPF.log" || r=$? + [ $r = 0 ] || [ $r = 1 ] || { cat "$TMPF.log"; rm -f "$TMPF.log"; die "can't read $L (exit $r)"; } + grep -F "[$id]" "$TMPF.log" || echo "no lines from $id in HMG-API's log (yet)" >&2 + rm -f "$TMPF.log" + ;; +settings) + while [ $# -gt 0 ]; do case $1 in --dry-run) DRY=1; shift ;; *) break ;; esac; done + sub=${1:-}; id=${2:-} + valid_id "$id" || die "settings get | settings set " + case $sub in + get) + adb_ready + if [ -n "$DRY" ]; then adb_sh "hmgapid setting-get $id"; exit 0; fi + r=0; adb_sh "hmgapid setting-get $id" > "$TMPF.json" || r=$? + [ $r = 0 ] || { cat "$TMPF.json"; rm -f "$TMPF.json"; die "setting-get: exit $r"; } + python3 -c 'import json,sys; print(json.dumps(json.load(open(sys.argv[1])), indent=2))' "$TMPF.json" 2>/dev/null || cat "$TMPF.json" + rm -f "$TMPF.json" + ;; + set) + f=${3:-}; [ -f "$f" ] || die "settings set $id : no file $f" + python3 -c 'import json,sys; v=json.load(open(sys.argv[1])); sys.exit(0 if isinstance(v, dict) else "a JSON object, {...}")' "$f" \ + || die "$f isn't a JSON object" + adb_ready + # pushed as a file and read on the unit: JSON in a shell command line loses its quotes + T=$REMOTE_DIR/hmgapi-mod-settings.json + adb_do push "$f" "$T" + r=0; adb_sh "hmgapid setting-set $id \"\$(cat $T)\"; r=\$?; rm -f $T; (exit \$r)" || r=$? + [ $r = 0 ] || die "setting-set: exit $r" + ;; + *) die "settings get | settings set " ;; + esac + ;; +''|-h|--help|help) usage ;; +*) die "unknown command $cmd (hmgapi-mod help)" ;; +esac diff --git a/tools/sdk/mod-deps.py b/tools/sdk/mod-deps.py new file mode 100755 index 00000000..d6176098 --- /dev/null +++ b/tools/sdk/mod-deps.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""The mods a mod requires ("requires" in mod.json), from HMG-API's mod catalogue (in the +mod SDK as bin/mod-deps.py; `hmgapi-mod deps` runs it). + + mod-deps.py [--catalog ] [--cache ] [--pins ] + +For each required mod, and each mod those require: its catalogue entry (catalog/.json +in HMG-API: the download, its SHA-256 and the author key), the version checked against the +range (as the engine reads it), the download fetched, its SHA-256 checked, unpacked, and +its signature checked against the entry's author key (hmgapi.engine.Signing, as the head +unit does), which must be on HMG-API's author list (maps/authors.json). Each lands in the +cache, -.zip and its mod folder -/ (as signed), and is used from +there next time (the zip's SHA-256 checked again, no download). + +Prints the mod folders, one per line (what test/lib.sh's plan_test takes); what it did +goes to stderr. Exit 1 with the reasons if any can't be had. + + --catalog a catalog/ folder (an HMG-API checkout's), or its URL. Default: + $HMGAPI_CATALOG, else Open-HMG/HMG-API's main branch on GitHub + (https://raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog). + The author list is maps/authors.json beside it. + --cache default .hmgapi/deps (in the folder it's run from) + --pins default hmgapi-deps.txt, if there: " " lines, + for a pre-release the catalogue doesn't list yet (it lists final releases). + A pin keeps the catalogue entry's author key, and its download must be a + release of the entry's own repo (/releases/download/...), as + tools/release-mods.txt pins in HMG-API. +""" +import argparse, hashlib, json, os, re, shutil, subprocess, sys, tempfile, urllib.error, urllib.parse, urllib.request, zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +SDK = os.path.dirname(HERE) +CP = os.pathsep.join([os.path.join(SDK, 'lib', 'hmgapi-engine.jar'), os.path.join(SDK, 'test', 'hmgapi-engine-test.jar')]) +DEFAULT_CATALOG = 'https://raw.githubusercontent.com/Open-HMG/HMG-API/main/catalog' +ID = re.compile(r'^[a-z0-9][a-z0-9-]{0,63}$') +VERSION = re.compile(r'^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$') +SHA = re.compile(r'^[0-9a-f]{64}$') +MAX_FILES, MAX_BYTES = 2000, 64 << 20 # the engine's limits (Packages.java) + + +class Fail(Exception): + pass + + +def say(msg): + print(msg, file=sys.stderr) + + +def java(*args): + return subprocess.run(['java', '-cp', CP] + list(args), capture_output=True, text=True) + + +def is_url(s): + return re.match(r'^[a-z][a-z0-9+.-]*://', s) is not None + + +def get(src, what): + """the bytes of a file in a folder or at a URL; None if it isn't there""" + if not is_url(src): + try: + with open(src, 'rb') as f: + return f.read() + except FileNotFoundError: + return None + req = urllib.request.Request(src, headers={'User-Agent': 'hmgapi-mod deps'}) + try: + with urllib.request.urlopen(req, timeout=60) as r: + out, n = bytearray(), 0 + for b in iter(lambda: r.read(1 << 20), b''): + n += len(b) + if n > MAX_BYTES: + raise Fail(f'{what}: bigger than {MAX_BYTES >> 20} MB') + out += b + return bytes(out) + except urllib.error.HTTPError as e: + if e.code == 404: + return None + raise Fail(f'{what}: {src}: {e}') + except (urllib.error.URLError, OSError) as e: + raise Fail(f'{what}: can\'t fetch {src}: {e}') + + +def join(base, name): + return base.rstrip('/') + '/' + name if is_url(base) else os.path.join(base, name) + + +def authors_of(catalog): + """maps/authors.json beside the catalog folder (or URL)""" + if is_url(catalog): + u = urllib.parse.urlsplit(catalog) + path = u.path.rstrip('/') + src = urllib.parse.urlunsplit(u._replace(path=path.rsplit('/', 1)[0] + '/maps/authors.json')) + else: + src = os.path.join(os.path.dirname(os.path.abspath(catalog)), 'maps', 'authors.json') + b = get(src, 'authors') + if b is None: + raise Fail(f'no author list at {src} (HMG-API\'s maps/authors.json beside the catalogue)') + return json.loads(b).get('authors', {}) + + +def pins(path): + out = {} + if not path or not os.path.isfile(path): + return out + for i, line in enumerate(open(path).read().split('\n'), 1): + w = line.split('#', 1)[0].split() + if not w: + continue + if len(w) != 4 or not ID.match(w[0]) or not VERSION.match(w[1]) or not SHA.match(w[3]): + raise Fail(f'{path}:{i}: wanted " " (sha256: 64 lowercase hex digits)') + out[w[0]] = {'version': w[1], 'download': w[2], 'sha256': w[3]} + return out + + +def unpack(zpath, dest): + """the package's files under dest (refusing paths out of it, links and oversize), then its + mod folder: dest itself or its one subfolder, as the engine takes it""" + with zipfile.ZipFile(zpath) as z: + infos = [i for i in z.infolist() if not i.is_dir()] + if len(infos) > MAX_FILES or sum(i.file_size for i in infos) > MAX_BYTES: + raise Fail(f'{zpath}: more than {MAX_FILES} files or {MAX_BYTES >> 20} MB') + for i in infos: + n = i.filename + if n.startswith('/') or '\\' in n or '..' in n.split('/') or (i.external_attr >> 16) & 0o170000 == 0o120000: + raise Fail(f'{zpath}: refused entry {n!r}') + out = os.path.join(dest, n) + os.makedirs(os.path.dirname(out), exist_ok=True) + with z.open(i) as src, open(out, 'wb') as dst: + shutil.copyfileobj(src, dst) + if os.path.isfile(os.path.join(dest, 'mod.json')): + return dest + subs = [d for d in os.listdir(dest) if os.path.isdir(os.path.join(dest, d))] + if len(subs) == 1 and os.path.isfile(os.path.join(dest, subs[0], 'mod.json')): + return os.path.join(dest, subs[0]) + raise Fail(f'{zpath}: no mod.json') + + +def sha256(path): + h = hashlib.sha256() + with open(path, 'rb') as f: + for b in iter(lambda: f.read(1 << 20), b''): + h.update(b) + return h.hexdigest() + + +def requires(moddir): + r = java('hmgapi.engine.Requires', 'list', moddir) + if r.returncode: + raise Fail(f'{moddir}/mod.json: {(r.stdout + r.stderr).strip()}') + return [(l.split(' ', 1) + [''])[:2] for l in r.stdout.splitlines() if l.strip()] + + +def satisfies(v, rng): + if not rng: + return True + r = java('hmgapi.engine.Requires', 'satisfies', v, rng) + if r.returncode == 2: + raise Fail(f'"{rng}": {r.stderr.strip()}') + return r.returncode == 0 + + +def one(mid, rng, who, catalog, authors, pinned, cache): + """the mod folder of a required mod, from the cache or downloaded and checked""" + if not ID.match(mid): + raise Fail(f'{who} requires "{mid}": not a mod id') + b = get(join(catalog, mid + '.json'), mid) + if b is None: + raise Fail(f'{who} requires {mid}, which isn\'t in HMG-API\'s catalogue ({join(catalog, mid + ".json")}): ' + 'a required mod comes from the catalogue (its author adds it: tools/catalog.py add)') + e = json.loads(b) + if e.get('id') != mid or not SHA.match(str(e.get('sha256', ''))) or not e.get('uuid') or not e.get('download'): + raise Fail(f'catalog/{mid}.json: no id, download, sha256 or uuid') + uuid = str(e['uuid']).lower() + if uuid not in authors: + raise Fail(f'catalog/{mid}.json: author key {uuid} isn\'t on HMG-API\'s author list (maps/authors.json)') + src = 'the catalogue' + if mid in pinned: + p = pinned[mid] + base = str(e.get('repo', '')).rstrip('/') + '/releases/download/' + if not e.get('repo') or not p['download'].startswith(base): + raise Fail(f'pin {mid} {p["version"]}: the download must be a release of the mod\'s own repo ({base}...)') + e = dict(e, **p) + src = 'a pin' + v = str(e.get('version', '')) + if not satisfies(v, rng): + raise Fail(f'{who} requires {mid} {rng}, but {src} has {v}' + + ('' if src == 'a pin' else ' (a pre-release can be pinned: hmgapi-deps.txt)')) + z = os.path.join(cache, f'{mid}-{v}.zip') + d = os.path.join(cache, f'{mid}-{v}') + ok = d + '.checked' # beside the mod folder: in it, the signature check would count it + if os.path.isfile(z) and os.path.isfile(ok) and sha256(z) == e['sha256'] and open(ok).read().strip() == e['sha256'] + ' ' + uuid: + say(f'ok {mid} {v}: cached ({z})') + return d + tmp = tempfile.mkdtemp(prefix='hmgapi-mod-deps-', dir=cache) + try: + tz = os.path.join(tmp, 'pkg.zip') + b = get(e['download'], mid) + if b is None: + raise Fail(f'{mid} {v}: no such download: {e["download"]}') + with open(tz, 'wb') as f: + f.write(b) + got = sha256(tz) + if got != e['sha256']: + raise Fail(f'{mid} {v}: the download\'s SHA-256 is {got}, {src} says {e["sha256"]}') + md = unpack(tz, os.path.join(tmp, 'mod')) + r = java('hmgapi.engine.Signing', 'verify', md, uuid) + if r.returncode: + raise Fail(f'{mid} {v}: {(r.stdout + r.stderr).strip()}') + man = json.load(open(os.path.join(md, 'META-HMGAPI', 'manifest.json'))) + if (man.get('id'), man.get('version')) != (mid, v): + raise Fail(f'{mid} {v}: the download is {man.get("id")} {man.get("version")}') + shutil.rmtree(d, ignore_errors=True) + os.replace(md, d) + os.replace(tz, z) + with open(ok, 'w') as f: + f.write(e['sha256'] + ' ' + uuid + '\n') + finally: + shutil.rmtree(tmp, ignore_errors=True) + say(f'ok {mid} {v}: downloaded from {src}, SHA-256 and signature match (author key {uuid})') + return d + + +def main(): + ap = argparse.ArgumentParser(description='the mods a mod requires, from HMG-API\'s catalogue') + ap.add_argument('mod') + ap.add_argument('--catalog', default=os.environ.get('HMGAPI_CATALOG') or DEFAULT_CATALOG) + ap.add_argument('--cache', default=os.path.join('.hmgapi', 'deps')) + ap.add_argument('--pins', default='hmgapi-deps.txt') + a = ap.parse_args() + if not os.path.isfile(os.path.join(a.mod, 'mod.json')): + say(f'FAIL no mod.json in {a.mod}') + return 1 + try: + todo = [(d, r, os.path.basename(os.path.abspath(a.mod))) for d, r in requires(a.mod)] + if not todo: + say('ok no "requires" in mod.json') + return 0 + os.makedirs(a.cache, exist_ok=True) + authors, pinned = authors_of(a.catalog), pins(a.pins) + done, out, fails = {}, [], [] + while todo: + mid, rng, who = todo.pop(0) + if mid in done: + if done[mid] and not satisfies(done[mid][0], rng): + fails.append(f'{who} requires {mid} {rng}, but {done[mid][0]} is the one the others need') + continue + try: + d = one(mid, rng, who, a.catalog, authors, pinned, os.path.abspath(a.cache)) + except Fail as x: + fails.append(str(x)) + done[mid] = None + continue + v = json.load(open(os.path.join(d, 'mod.json'))).get('version', '') + done[mid] = (v, d) + out.append(d) + todo += [(x, r, mid) for x, r in requires(d)] + except Fail as x: + fails = [str(x)] + out = [] + for f in fails: + say('FAIL ' + f) + if fails: + return 1 + for d in out: + print(d) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) From dc72b8e67c662dae60f6fa27085d4173284de37f Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 15 Nov 2026 22:33:21 -0500 Subject: [PATCH 04/69] mkmodpkg.sh: mod.json's top-level id; say what changes for an existing build.sh The id and version (and the built mod's id) came from the first "id" and "version" anywhere in mod.json, so a nested one before the top-level one named the package wrong or failed the "as built" check. Read the top-level fields with python3, as build-mod.sh does, and refuse a mod.json without them. An existing build.sh used to get the package's folder, a copy of the whole mod folder; now it gets build-mod.sh's out dir. CHANGELOG and mod-reference.md say so, and what to do: one that only adds files works as it is, one that changed the folder's files writes its copy to the same path in the out dir, which wins in the package. sdk-test.sh checks both. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++++++++--- docs/mod-reference.md | 15 ++++++++++++--- tools/mkmodpkg.sh | 9 ++++++--- tools/sdk-test.sh | 9 +++++++-- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da9cd0ce..262fab40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,14 @@ or building it itself) instead of running `build.sh` again. A mod's folder needn't be named by its id any more: `build-mod.sh` and the reusable mod workflow take the id from `mod.json` (the workflow refuses two folders with one id, and an id the engine would - refuse). Packages come out with the same files as before, a `build.sh`'s too; a mod - with a `build.sh` now needs what it needs (hmgapi-adbd: the NDK) for `build-mod.sh` as - well. (docs/mod-reference.md, "Building a mod outside this repo") + refuse). Mods without a `build.sh` package as before. + **For an existing `build.sh`:** it used to get the package's folder (a copy of the whole + mod folder); now it gets the build folder, with only the mod's `*.json`, `hooks.jar` and + APK in it. One that only adds files (hmgapi-adbd) works as it is, but now needs its tools + (hmgapi-adbd: the NDK) for `build-mod.sh` too. One that changed the folder's files in + place (a script, an asset) must now write its changed copy to the same path in the build + folder, where it replaces the folder's file in the package. (docs/mod-reference.md, + "Building a mod outside this repo") ## 1.1.0-rc.2 (2026-11-15) diff --git a/docs/mod-reference.md b/docs/mod-reference.md index d0467a0e..00205d73 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -375,8 +375,9 @@ mod's own build step: an executable `build.sh` in the mod folder (`chmod +x`, an ones run it only in `mkmodpkg.sh`, on the package's folder): - `` is an absolute path, and already holds the mod's `*.json`, `hooks.jar` and - the APK. Whatever the script writes there goes into the package; it can also replace - those files (a `hooks.jar` built its own way). + the APK, nothing else from the folder. Whatever the script writes there goes into the + package, over the folder's own file at the same path: a `hooks.jar` built its own way, + a script edited at build time. It can't take one of the folder's files out. - It runs from the directory `build-mod.sh` was run in (the repository root in the workflow), so it finds its own folder with `$(dirname "$0")`. - It gets `HMGAPI_SDK`, `HMGAPI_CP` (HMG-API's runtime, compile only), `HMGAPI_CLIENT` @@ -388,7 +389,15 @@ ones run it only in `mkmodpkg.sh`, on the package's folder): `mkmodpkg.sh` packages the mod folder with the build on top: from `HMGAPI_MOD_BUILD` (as the workflow does, so the package is what the tests saw), or it runs `build-mod.sh` -itself. For example, a service jar with `hmgapi-client.jar` inside, from `tools/relay/src`: +itself. + +A `build.sh` written for older SDKs: their `mkmodpkg.sh` ran it on the package's folder, a +copy of the whole mod folder (`scripts/` and all), and `build-mod.sh` didn't run it. Now it +gets `build-mod.sh`'s out dir, which has no copy of the folder's other files. One that only +adds files (hmgapi-adbd's `files/hmgapi-adbd`) works as it is. One that changed a file of +the folder in place (a script, an asset) now finds nothing there to change: have it read +the folder's file and write the changed one to the same path in `` instead, for +example `mkdir -p "$1/scripts" && sed 's/x/y/' "$(dirname "$0")/scripts/a.sh" > "$1/scripts/a.sh"`. For example, a service jar with `hmgapi-client.jar` inside, from `tools/relay/src`: ``` #!/bin/sh diff --git a/tools/mkmodpkg.sh b/tools/mkmodpkg.sh index 7bacabea..58de0a3c 100755 --- a/tools/mkmodpkg.sh +++ b/tools/mkmodpkg.sh @@ -22,8 +22,11 @@ else PKGS=$PWD/out/packages mkdir -p "$CP" && javac --release 8 -Xlint:-options -nowarn -d "$CP" core/runtime/java/hmgapi/engine/*.java 2>/dev/null fi -ID=$(sed -n 's/.*"id": *"\([^"]*\)".*/\1/p' "$M/mod.json" | head -1) -VER=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' "$M/mod.json" | head -1) +# mod.json's top-level "id" and "version" (not one nested in "requires" or "apps") +field() { python3 -c 'import json,sys; j=json.load(open(sys.argv[1])); v=j.get(sys.argv[2]) if isinstance(j, dict) else None; print(v if isinstance(v, str) else "")' "$1" "$2"; } +ID=$(field "$M/mod.json" id) || { echo "mkmodpkg.sh: $M/mod.json isn't valid JSON"; exit 1; } +VER=$(field "$M/mod.json" version) +[ -n "$ID" ] && [ -n "$VER" ] || { echo "mkmodpkg.sh: $M/mod.json needs an \"id\" and a \"version\""; exit 1; } W=$(mktemp -d); trap 'rm -rf "$W"' EXIT mkdir -p "$W/$ID" APPSRC=no; [ -f "$M/app/AndroidManifest.xml" ] && APPSRC=yes # app/ is the mod's APK source: the package gets the built APK @@ -35,7 +38,7 @@ if [ -d "$M/src" ] || [ $APPSRC = yes ] || [ -x "$M/build.sh" ]; then elif [ -n "$HMGAPI_MOD_BUILD" ]; then B=$HMGAPI_MOD_BUILD else B=$W/build; sh "$HERE/build-mod.sh" "$M" "$B" "$W/work" >/dev/null || exit 1 fi - [ "$(sed -n 's/.*"id": *"\([^"]*\)".*/\1/p' "$B/mod.json" 2>/dev/null | head -1)" = "$ID" ] \ + [ -f "$B/mod.json" ] && [ "$(field "$B/mod.json" id 2>/dev/null)" = "$ID" ] \ || { echo "mkmodpkg.sh: $B isn't $ID as built (build-mod.sh's out dir for $M, with its mod.json)"; exit 1; } cp -R "$B"/. "$W/$ID/" # what build-mod.sh built, the mod's build.sh's files too fi diff --git a/tools/sdk-test.sh b/tools/sdk-test.sh index fdd9e29e..50627a79 100644 --- a/tools/sdk-test.sh +++ b/tools/sdk-test.sh @@ -158,7 +158,9 @@ check "... points but no floor: fails" 1 $r R=$T/r; mkdir -p $R && cd $R F=relay-folder mkdir -p $F/tools/relay/src/example/relay && cp -r $M/hello/src $F/ -printf '{"id": "built-step", "version": "1.0.0", "hmgapi": ">=1.0.0", "hooks": {"jar": "hooks.jar", "entry": "example.hello.Hello"},\n "services": [{"name": "relay", "jar": "relay.jar", "class": "example.relay.Relay", "user": "system"}]}\n' > $F/mod.json +# an "id" nested before the top-level one: the top-level one is the id +printf '{"notes": {"id": "not-me"}, "id": "built-step", "version": "1.0.0", "hmgapi": ">=1.0.0", "hooks": {"jar": "hooks.jar", "entry": "example.hello.Hello"},\n "services": [{"name": "relay", "jar": "relay.jar", "class": "example.relay.Relay", "user": "system"}, {"name": "s", "script": "scripts/s.sh", "user": "root"}]}\n' > $F/mod.json +mkdir -p $F/scripts && printf '#!/system/bin/sh\necho MODE=source\n' > $F/scripts/s.sh printf 'package example.relay;\npublic class Relay { public static void main(String[] a) { System.out.println(hmgapi.client.HmgApi.class.getName()); } }\n' \ > $F/tools/relay/src/example/relay/Relay.java cat > $F/build.sh <<'SH' @@ -171,6 +173,8 @@ W=$(mktemp -d); trap 'rm -rf "$W"' EXIT javac --release 8 -Xlint:-options -nowarn -cp "$ANDROID_JAR:$HMGAPI_CLIENT" -d "$W" $(find "$(dirname "$0")/tools/relay/src" -name '*.java') "$D8" --release --min-api 19 --lib "$ANDROID_JAR" --output "$O/relay.jar" $(find "$W" -name '*.class') echo "relay.jar: sdk=$HMGAPI_SDK out=$O" +# one of the folder's files, changed at build time: written to the same path in the out dir +mkdir -p "$O/scripts" && sed 's/MODE=source/MODE=built/' "$(dirname "$0")/scripts/s.sh" > "$O/scripts/s.sh" SH chmod 755 $F/build.sh printf '#!/bin/sh\n[ -f "$HMGAPI_MOD_BUILD/relay.jar" ] && [ -f "$HMGAPI_MOD_BUILD/hooks.jar" ] && echo "ok built-step: relay.jar and hooks.jar"\n' > $F/test.sh @@ -184,8 +188,9 @@ check "... hmgapi-client inside relay.jar" yes "$(grep -q 'Lhmgapi/client/HmgApi has "... build.sh got the out dir as an absolute path, and HMGAPI_SDK" "relay.jar: sdk=$T/sdk out=$R/out/b" "$o" o=$(HMGAPI_MOD_BUILD=$R/out/b sh $S/mkmodpkg.sh $F $T/author.key 2>&1) || echo "$o" check "mkmodpkg.sh: named by the id" yes "$([ -f out/packages/built-step-1.0.0.zip ] && echo yes)" -check "... with what build.sh built, without build.sh, src or tools" "hooks.jar|mod.json|relay.jar|" \ +check "... with what build.sh built, without build.sh, src or tools" "hooks.jar|mod.json|relay.jar|scripts/s.sh|" \ "$(unzip -Z1 out/packages/built-step-1.0.0.zip | grep -v '^META-HMGAPI/' | sort | tr '\n' '|')" +check "... build.sh's copy of a folder file over the folder's" "echo MODE=built" "$(unzip -p out/packages/built-step-1.0.0.zip scripts/s.sh | grep MODE)" cp out/packages/built-step-1.0.0.zip $T/built-step.zip o=$(sh $S/mkmodpkg.sh $F $T/author.key 2>&1) || echo "$o" check "... building it itself (no HMGAPI_MOD_BUILD) gives the same files" "$(pkg $T/built-step.zip)" "$(pkg $R/out/packages/built-step-1.0.0.zip)" From 9b9be64d0a441a5bbeaaa838589fbfab0ce518f3 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Sun, 15 Nov 2026 22:38:05 -0500 Subject: [PATCH 05/69] hmgapi-mod new: a Java package for any id, and the SDK pin's sha256 An id starting with a digit (3d-view) or a Java keyword (new) gave a package that doesn't compile (mod.3d_view): it gets an m first now (mod.m3d_view, mod.mnew), as the class gets Mod. hmgapi-sdk.json gets the release zip's sha256 from that release's SHA256SUMS when it can be fetched (HMGAPI_SDK_SUMS: another URL or file); otherwise it's left empty and new says to fill it in, as before. Co-Authored-By: Claude Opus 5.5 --- tools/sdk-test.sh | 16 +++++++++++++++- tools/sdk/README.txt | 3 ++- tools/sdk/hmgapi-mod | 33 ++++++++++++++++++++++++++++++--- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/tools/sdk-test.sh b/tools/sdk-test.sh index 40d1da8a..70a10dff 100644 --- a/tools/sdk-test.sh +++ b/tools/sdk-test.sh @@ -196,7 +196,11 @@ has "... names the point" "gpm.no_such_point: not in this car's map" "$o" # ---- bin/hmgapi-mod: a mod repo's loop, from its root, with the SDK alone HM="sh $T/sdk/bin/hmgapi-mod" mkdir -p $T/repo && cd $T/repo -o=$($HM new my-mod --name "My mod" --author Tester 2>&1) || echo "$o" +SUM=$(printf 'ab%.0s' $(seq 32)) +printf 'aa other.zip\n%s hmgapi-mod-sdk-%s.zip\n' "$SUM" "$V" > $T/SHA256SUMS +o=$(HMGAPI_SDK_SUMS=$T/SHA256SUMS $HM new my-mod --name "My mod" --author Tester 2>&1) || echo "$o" +check "... hmgapi-sdk.json: the SDK's release, its SHA-256 from that release's SHA256SUMS" \ + "{\"version\": \"$V\", \"sha256\": \"$SUM\"}" "$(cat hmgapi-sdk.json)" check "new: the mod, its test, the SDK pin, CI and .gitignore" \ "./.github/workflows/ci.yml ./.gitignore ./hmgapi-sdk.json ./my-mod/mod.json ./my-mod/src/mod/my_mod/MyMod.java ./my-mod/test.sh" \ "$(find . -type f | sort | tr '\n' ' ' | sed 's/ $//')" @@ -207,6 +211,16 @@ set +e; o=$($HM new my-mod --author Tester 2>&1); r=$?; set -e check "... an existing folder: refused" "2|hmgapi-mod: my-mod already exists" "$r|$o" set +e; o=$($HM new My_Mod --author Tester 2>&1); r=$?; set -e check "... not an id: refused" 2 $r +# ids that can't start a Java name (a digit first, a keyword), and no SHA256SUMS to read +mkdir -p $T/dg && (cd $T/dg && HMGAPI_SDK_SUMS=$T/none $HM new 3d-view --author Tester > $T/dg.out 2>&1 && $HM new new --author Tester > /dev/null 2>&1) +entry() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["hooks"]["entry"])' "$1/mod.json"; } +check "... a digit-first id: package mod.m3d_view, class Mod3dView" "mod.m3d_view.Mod3dView|yes" \ + "$(entry $T/dg/3d-view)|$([ -f $T/dg/3d-view/src/mod/m3d_view/Mod3dView.java ] && echo yes)" +check "... builds" yes "$(cd $T/dg && sh $S/build-mod.sh 3d-view $T/dg/b3 > /dev/null 2>&1 && [ -f $T/dg/b3/hooks.jar ] && echo yes)" +check "... a keyword id (new): mod.mnew.New, builds" "mod.mnew.New|yes" \ + "$(entry $T/dg/new)|$(cd $T/dg && sh $S/build-mod.sh new $T/dg/bn > /dev/null 2>&1 && [ -f $T/dg/bn/hooks.jar ] && echo yes)" +check "... no SHA256SUMS to read: the pin's sha256 left empty, and said so" "{\"version\": \"$V\", \"sha256\": \"\"}|yes" \ + "$(cat $T/dg/hmgapi-sdk.json)|$(grep -q 'put its sha256 in' $T/dg.out && echo yes)" o=$($HM build 2>&1) && r=0 || r=$? check "build: the one mod here, into out/build/" "0|yes" "$r|$([ -f out/build/my-mod/hooks.jar ] && echo yes)" check "... the same hooks.jar as bin/build-mod.sh" "$(sh $S/build-mod.sh my-mod $T/bm >/dev/null 2>&1; md5 $T/bm/hooks.jar)" "$(md5 out/build/my-mod/hooks.jar)" diff --git a/tools/sdk/README.txt b/tools/sdk/README.txt index 9786a379..a90d517e 100644 --- a/tools/sdk/README.txt +++ b/tools/sdk/README.txt @@ -33,7 +33,8 @@ the Android SDK (build-tools, a platform android.jar) and set ANDROID_HOME. hmgapi-mod, from the mod repository's root (: the mod's folder, by default the one folder there with a mod.json): hmgapi-mod new [--name ] [--author ] / (mod.json, an entry class, - test.sh), hmgapi-sdk.json, .github/workflows/ci.yml, .gitignore + test.sh), hmgapi-sdk.json (this SDK's release, its sha256 from + the release's SHA256SUMS if it can be fetched), CI, .gitignore hmgapi-mod build [] bin/build-mod.sh into out/build/ hmgapi-mod check [] bin/check-points.py and bin/check-scripts.sh hmgapi-mod deps [] each mod "requires" names (and what those require), from HMG-API's diff --git a/tools/sdk/hmgapi-mod b/tools/sdk/hmgapi-mod index c28cb830..487f2fc7 100755 --- a/tools/sdk/hmgapi-mod +++ b/tools/sdk/hmgapi-mod @@ -103,7 +103,15 @@ new) [ -n "$author" ] || die "new: give --author (no git user.name here)" [ ! -e "$id" ] || die "$id already exists" V=$(cat "$HMGAPI_SDK/VERSION") - pkg=mod.$(echo "$id" | sed 's/-/_/g') + # the package: mod., with an m first where the id can't start a Java name + # (a digit: 3d-view is mod.m3d_view; a keyword: new is mod.mnew) + pkg=mod.$(python3 -c 'import sys +s = sys.argv[1].replace("-", "_") +java = ("abstract assert boolean break byte case catch char class const continue default do double else enum extends final " + "finally float for goto if implements import instanceof int interface long native new package private protected public " + "return short static strictfp super switch synchronized this throw throws transient try void volatile while true false " + "null var record yield sealed permits").split() +print("m" + s if s[0].isdigit() or s in java else s)' "$id") # the entry class: the id in CamelCase (my-mod: MyMod), Mod first if it starts with a digit cls=$(python3 -c 'import sys; c="".join(p[:1].upper() + p[1:] for p in sys.argv[1].split("-") if p); print(("Mod" if c[0].isdigit() else "") + c)' "$id") mkdir -p "$id/src/$(echo "$pkg" | sed 's#\.#/#g')" @@ -148,7 +156,22 @@ plan_test "$M" $DEPS exit $fail EOF chmod 755 "$id/test.sh" - [ -e hmgapi-sdk.json ] || printf '{"version": "%s", "sha256": ""}\n' "$V" > hmgapi-sdk.json + # the pin: the release's zip and its SHA-256 from that release's SHA256SUMS, when it can be + # fetched (HMGAPI_SDK_SUMS: another URL or file); otherwise left for the author to fill in + sum= + if [ ! -e hmgapi-sdk.json ]; then + sum=$(python3 -c 'import re, sys, urllib.request +v, src = sys.argv[1:] +if re.match(r"^[a-z][a-z0-9+.-]*://", src): + text = urllib.request.urlopen(urllib.request.Request(src, headers={"User-Agent": "hmgapi-mod new"}), timeout=15).read().decode() +else: + text = open(src).read() +for line in text.splitlines(): + w = line.split() + if len(w) == 2 and w[1].lstrip("*") == "hmgapi-mod-sdk-%s.zip" % v and re.match(r"^[0-9a-f]{64}$", w[0]): + print(w[0])' "$V" "${HMGAPI_SDK_SUMS:-https://github.com/Open-HMG/HMG-API/releases/download/v$V/SHA256SUMS}" 2>/dev/null || true) + printf '{"version": "%s", "sha256": "%s"}\n' "$V" "$sum" > hmgapi-sdk.json + fi if [ ! -e .github/workflows/ci.yml ]; then mkdir -p .github/workflows printf 'name: ci\non: [push, pull_request]\njobs:\n mod:\n uses: Open-HMG/HMG-API/.github/workflows/mod.yml@v%s\n' "$V" > .github/workflows/ci.yml @@ -156,7 +179,11 @@ EOF [ -e .gitignore ] || printf 'out/\n.hmgapi/\n*.key\n' > .gitignore echo "$id/: mod.json, src/$(echo "$pkg" | sed 's#\.#/#g')/$cls.java, test.sh" echo "$id/mod.json: \"system\" is \"all\" (any head unit): name the cars the mod is for, with their region (\"product\": [\"CVEV.USA.\"])" - echo "hmgapi-sdk.json: pins SDK $V; put its sha256 in (SHA256SUMS on HMG-API's v$V release)" + if [ -n "$sum" ]; then + echo "hmgapi-sdk.json: pins SDK $V (sha256 from the v$V release's SHA256SUMS)" + elif grep -q '"sha256": ""' hmgapi-sdk.json; then + echo "hmgapi-sdk.json: pins SDK $V; put its sha256 in (SHA256SUMS on HMG-API's v$V release; CI fails without it)" + fi echo "next: hmgapi-mod build, hmgapi-mod test (docs/mod-reference.md in HMG-API: \"Building a mod outside this repo\")" ;; build) From 0562c7742f7515ba84c12ed728779fea37c3e5fd Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:39 -0500 Subject: [PATCH 06/69] Home Wi-Fi: keep the car's Wi-Fi checksum in step, so the client starts The stock Wi-Fi library (seen on an Ioniq 5 US 260507) starts the car's Wi-Fi client only when /data/misc/wifi/wpa_supplicant_crc32.conf holds the CRC-32 of wpa_supplicant.conf (8 upper-case hex digits). wifi.sh's join and forget edited the networks file and left it stale: logcat said "Wi-Fi will not be enabled" and home Wi-Fi stayed "searching". WifiAp crc writes it (only when it differs, owned system:wifi 660); wifi.sh runs it after every edit and before switching the client on. The test checks it against the pair the car's library wrote for its own template. A first network no longer needs printf (not on the unit): the config starts from the car's own template (/system/etc/wifi/wpa_supplicant.conf), as its library does. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++++++ core/runtime/homewifi-test.sh | 9 +++++ core/runtime/java/hmgapi/engine/HomeWifi.java | 14 +++++++- core/runtime/java/hmgapi/engine/WifiAp.java | 35 +++++++++++++++++++ .../test/hmgapi/engine/WifiApTest.java | 28 +++++++++++++++ 5 files changed, 95 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..5f62794b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- **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 + never started ("Wi-Fi will not be enabled") and home Wi-Fi stayed "searching". Adding or + forgetting a network now updates it, and it's checked before each switch to home Wi-Fi. + A first network no longer needs `printf` (not on the unit): the config starts from the car's + own template. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index a7e7d4ea..e36e521d 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -209,6 +209,7 @@ case "$3 $4" in fi ;; "client on") : > "$FW/client"; echo running > "$FW/props/init.svc.wpa_supplicant"; echo "client on" ;; "client off") rm -f "$FW/client"; echo stopped > "$FW/props/init.svc.wpa_supplicant"; echo "client off" ;; + "crc "*) echo crc >> "$FW/crc.log"; echo 01234567 ;; esac S printf '#!/bin/sh\n:\n' > "$F/bin/chown" @@ -255,7 +256,9 @@ out=$(HMGAPI_WIFI_PSK='has"quote' verb join "Cascadia" || true) has "join: a key that could break the config refused" "can't be used" "$out" out=$(HMGAPI_WIFI_PSK= verb join 'Bad"Name' || true) has "join: a name that could break the config refused" "can't be used" "$out" +: > "$F/fw/crc.log" check "join: saved" "saved: Cascadia" "$(HMGAPI_WIFI_PSK=cascadia-key verb join Cascadia)" +check "... the checksum the car's Wi-Fi library checks, updated" crc "$(cat "$F/fw/crc.log")" check "... both now" "Willows Cascadia" "$(verb saved)" has "... Android's own settings kept" "p2p_disabled=1" "$(cat "$NET")" @@ -268,12 +271,18 @@ check "forget" "forgotten: Cafe" "$(verb forget Cafe)" check "... gone, the others kept" "Cascadia Willows" "$(verb saved | sort)" check "seen: nothing before home Wi-Fi was on" "" "$(verb seen)" +mv "$NET" "$NET.keep"; mkdir -p "$X/system/etc/wifi"; printf 'update_config=1\nctrl_interface=wlan0\npmf=1\n' > "$X/system/etc/wifi/wpa_supplicant.conf" +HMGAPI_WIFI_PSK=first-net-key verb join First >/dev/null +has "join with no config yet: started from the car's template" "pmf=1" "$(cat "$NET")" +has "... with the network" 'ssid="First"' "$(cat "$NET")" +mv "$NET.keep" "$NET" # parked: the hotspot off, the car's client on echo "wpa_state=SCANNING" > "$F/fw/wpa.status" : > "$F/fw/apps.log" log=$(wk) has "parked: switched at once" "the car off: the hotspot off, the car's Wi-Fi client on" "$log" +has "... the checksum checked before the client goes on" crc "$(cat "$F/fw/crc.log")" check "... the hotspot off" no "$([ -f "$F/fw/ap" ] && echo yes || echo no)" has "... through Android's Wi-Fi service" "hmgapi.engine.WifiAp client on" "$(cat "$F/fw/apps.log")" check "... looking" searching "$(state)" diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index 58372e77..adbe2282 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -208,6 +208,10 @@ static List describe(Engine e, Map> json, Se "status() { echo \"{\\\"state\\\": \\\"$1\\\", \\\"rssi\\\": ${2:-0}, \\\"freq\\\": ${3:-0}}\" > $PUB.tmp && chmod 644 $PUB.tmp && mv $PUB.tmp $PUB; }", "reading() { hmgapid vehicle \"$1\" 2>/dev/null | while read -r k v; do [ \"$k\" = \"$1\" ] && echo \"$v\"; done; }", "tool() { CLASSPATH=$JAR app_process /system/bin hmgapi.engine.WifiAp \"$@\" 2>&1; }", + "# the car's Wi-Fi library starts the client only if wpa_supplicant_crc32.conf holds the networks", + "# file's CRC-32 (WifiAp.crc): after every edit here, and before switching the client on", + "crc_fix() { [ -f $NET ] && tool crc $NET >/dev/null; }", + "TEMPLATE=$X/system/etc/wifi/wpa_supplicant.conf # what the car's library starts a new config from", "boot() { cat $X/proc/sys/kernel/random/boot_id 2>/dev/null; }", "wants() { [ -f $ASKS ] && while read -r w rest; do [ \"$w\" = \"$1\" ] && { echo \"${rest:-$w}\"; }; done < $ASKS; }", "wifi_svc() { case $(service check wifi 2>/dev/null) in *\": found\"*) true ;; *) false ;; esac; }", @@ -242,6 +246,7 @@ static List describe(Engine e, Map> json, Se " echo -n \"$1\" > $NET.hmgapi", " chown wifi:wifi $NET.hmgapi 2>/dev/null; chmod 660 $NET.hmgapi", " mv $NET.hmgapi $NET", + " crc_fix", "}", "join() {", " s=$1 k=$HMGAPI_WIFI_PSK", @@ -249,7 +254,9 @@ static List describe(Engine e, Map> json, Se " safe \"$k\" || { echo \"that key can't be used (quotes, backslashes)\"; return 2; }", " if [ -n \"$k\" ] && [ ${#k} -lt 8 -o ${#k} -gt 63 ]; then echo \"a Wi-Fi key is 8 to 63 characters\"; return 2; fi", " client_mode && { echo \"home Wi-Fi is on right now (parked): add networks while the car is on\"; return 1; }", - " [ -f $NET ] || printf 'ctrl_interface=wlan0\\nupdate_config=1\\n' > $NET", + " if [ ! -f $NET ]; then # no printf on the unit; the car's own template, as its library does", + " if [ -f $TEMPLATE ]; then cat $TEMPLATE > $NET; else { echo ctrl_interface=wlan0; echo update_config=1; } > $NET; fi", + " fi", " c=$(without \"$s\")", " c=\"$c${nl}network={$nl\tssid=\\\"$s\\\"$nl\"", " if [ -n \"$k\" ]; then c=\"$c\tpsk=\\\"$k\\\"$nl\tkey_mgmt=WPA-PSK$nl\"; else c=\"$c\tkey_mgmt=NONE$nl\"; fi", @@ -268,6 +275,10 @@ static List describe(Engine e, Map> json, Se "}", "", "# ---- while joined: the car's own traffic on mobile data, the mods that asked on home Wi-Fi", + "# table 95 is never empty: while home Wi-Fi isn't up it holds an unreachable default, so traffic", + "# 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; }", "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", @@ -309,6 +320,7 @@ static List describe(Engine e, Map> json, Se " [ \"$m\" = 1 ] || [ \"$m\" = 2 ] || m=2 # the hotspot wasn't on: the projection one when it comes back", " echo $m > $W/apmode", " boot > $W/mode", + " crc_fix", " r=$(tool client on)", " if manual && [ \"$pw\" = on ]; then say \"on request: the hotspot off, the car's Wi-Fi client on ($r)\"", " else say \"the car off: the hotspot off, the car's Wi-Fi client on ($r)\"; fi", diff --git a/core/runtime/java/hmgapi/engine/WifiAp.java b/core/runtime/java/hmgapi/engine/WifiAp.java index 46163ae8..3e4912ab 100644 --- a/core/runtime/java/hmgapi/engine/WifiAp.java +++ b/core/runtime/java/hmgapi/engine/WifiAp.java @@ -85,12 +85,47 @@ private static boolean clientSavedOn(Class type, Object wifi) throws Reflecti } } + /** + * crc : the checksum the car's own Wi-Fi library checks before it starts + * the client. The stock libhardware_legacy (Ioniq 5 US 260507, and other Gen5W builds) keeps + * wpa_supplicant_crc32.conf next to the networks file: the file's CRC-32, 8 upper-case hex + * digits, no newline. If it doesn't match (any edit not made through Android's Wi-Fi settings), + * the library logs "Wi-Fi will not be enabled" and the client never starts. Written only when + * it differs, owned as the library makes it (system:wifi 660). Prints the checksum. + */ + static int crc(java.io.File conf) throws Exception { + if (!conf.isFile()) { + System.out.println("no " + conf); + return 1; + } + java.util.zip.CRC32 c = new java.util.zip.CRC32(); + c.update(Engine.readAll(new java.io.FileInputStream(conf))); + String want = String.format("%08X", c.getValue()); + java.io.File f = new java.io.File(conf.getParentFile(), "wpa_supplicant_crc32.conf"); + String have = f.isFile() ? Engine.read(f).trim() : null; + if (!want.equals(have)) { + java.io.File t = new java.io.File(f.getPath() + ".hmgapi"); + java.io.FileOutputStream o = new java.io.FileOutputStream(t); + try { + o.write(want.getBytes("US-ASCII")); + } finally { + o.close(); + } + Engine.child(new ProcessBuilder("chown", "system:wifi", t.getPath())).start().waitFor(); + Engine.child(new ProcessBuilder("chmod", "660", t.getPath())).start().waitFor(); + if (!t.renameTo(f)) throw new java.io.IOException("can't write " + f); + } + System.out.println(want); + return 0; + } + /** * restart: off and on again, the same mode. stop: off, printing the mode it had ("2" the projection * AP, "1" the plain hotspot, "0" it wasn't on). start : on again in that mode. */ public static void main(String[] args) throws Exception { String v = args.length > 0 ? args[0] : ""; + if ("crc".equals(v) && args.length == 2) System.exit(crc(new java.io.File(args[1]))); boolean client = "client".equals(v) && args.length == 2 && ("on".equals(args[1]) || "off".equals(args[1])); boolean ensure = "ensure-projection".equals(v) && args.length == 1; if (!(("restart".equals(v) || "stop".equals(v)) && args.length == 1) && !("start".equals(v) && args.length == 2) && !client && !ensure) { diff --git a/core/runtime/test/hmgapi/engine/WifiApTest.java b/core/runtime/test/hmgapi/engine/WifiApTest.java index e72eb35c..8890a797 100644 --- a/core/runtime/test/hmgapi/engine/WifiApTest.java +++ b/core/runtime/test/hmgapi/engine/WifiApTest.java @@ -77,7 +77,35 @@ private static void attach(String name, Manager m, String home, String says, int System.out.println("ok " + name); } + /** WifiAp.crc: the checksum file the car's Wi-Fi library checks (Ioniq 5 US 260507: its own pair below). */ + private static void crcChecks() throws Exception { + java.io.File d = java.nio.file.Files.createTempDirectory("crc").toFile(); + java.io.File conf = new java.io.File(d, "wpa_supplicant.conf"), crc = new java.io.File(d, "wpa_supplicant_crc32.conf"); + // the car's template (/system/etc/wifi/wpa_supplicant.conf, 98 bytes) and the checksum its library wrote for it + String template = "update_config=1\nctrl_interface=wlan0\neapol_version=1\nap_scan=1\nfast_reauth=1\np2p_disabled=1\npmf=1\n"; + java.nio.file.Files.write(conf.toPath(), template.getBytes("US-ASCII")); + java.io.PrintStream was = System.out; + System.setOut(new java.io.PrintStream(new java.io.ByteArrayOutputStream())); + try { + if (WifiAp.crc(conf) != 0) throw new AssertionError("crc: failed"); + String got = Engine.read(crc); + if (!"54931C7F".equals(got)) throw new AssertionError("crc: the car's library wrote 54931C7F for its template, got [" + got + "]"); + long t = crc.lastModified(); + crc.setLastModified(t - 100000); + WifiAp.crc(conf); + if (crc.lastModified() != t - 100000) throw new AssertionError("crc: rewritten though it matched"); + java.nio.file.Files.write(conf.toPath(), (template + "\nnetwork={\n\tssid=\"x\"\n\tkey_mgmt=NONE\n}\n").getBytes("US-ASCII")); + WifiAp.crc(conf); + if ("54931C7F".equals(Engine.read(crc)) || Engine.read(crc).length() != 8) throw new AssertionError("crc: not updated after an edit"); + if (WifiAp.crc(new java.io.File(d, "none")) == 0) throw new AssertionError("crc: no networks file is not ok"); + } finally { + System.setOut(was); + } + System.out.println("ok WifiAp crc: the car's checksum, 8 upper-case digits, written only when it changed"); + } + public static void main(String[] args) throws Exception { + crcChecks(); attach("attach: projection AP already up is left alone", new Manager(true, 2), null, "already up", 0); attach("attach: AP off is started in mode 2", new Manager(false, 0), "off", "started in mode 2", 1); attach("attach: plain hotspot is switched to mode 2 (as ensureHotspot did)", new Manager(true, 1), null, "started in mode 2", 1); From 4df02ccc4835566c7c796d6a133ed328c5a69960 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:39 -0500 Subject: [PATCH 07/69] Home Wi-Fi: mods' connections and their services' lookups get through Both found on an Ioniq 5 US 260507 (rc.10) with a mod that downloads over home Wi-Fi. - Connections were refused. The mods' cellular block sat in filter OUTPUT, where -o is the route a packet had before HMG-API's mark (mangle OUTPUT) moved it to table 95: a connection whose first route was the main table's (mobile data) was rejected there, though it would have left on wlan0. With home Wi-Fi on, the IPv4 block for the home group and the mods that asked runs after the reroute instead (mangle POSTROUTING, HMGAPI_HOMECELL: nothing marked leaves on rmnet), and table 95 is never empty: an unreachable default while home Wi-Fi is down, so marked traffic fails rather than falling through to mobile data. IPv6, and everything with home Wi-Fi off, is refused in OUTPUT as before. - A service's resolver (ANDROID_DNS_MODE=local) has no servers in its process and asks 127.0.0.1:53. The DNAT to home Wi-Fi's server kept 127.0.0.1 as the source, which the kernel won't route out of wlan0. While home Wi-Fi is up: route_localnet on wlan0 (the queries are masqueraded by HMGAPI_HOMEOUT), and HMGAPI_HOMELO lets only answers come back in for 127.x. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 ++++++++ core/runtime/homewifi-test.sh | 30 ++++++++++++------- core/runtime/java/hmgapi/engine/HomeWifi.java | 15 ++++++++++ core/runtime/java/hmgapi/engine/Network.java | 26 ++++++++++++---- docs/mod-reference.md | 7 +++++ 5 files changed, 74 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f62794b..6fd5a1b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ forgetting a network now updates it, and it's checked before each switch to home Wi-Fi. A first network no longer needs `printf` (not on the unit): the config starts from the car's own template. +- **Mods' connections over home Wi-Fi are no longer refused** (Ioniq 5 US 260507). The block + that keeps mods off mobile data was in `filter OUTPUT`, where `-o` is the route a packet had + before HMG-API's mark moved it to home Wi-Fi: every connection that started on the main + table (mobile data) was refused. With home Wi-Fi on, the block now runs after the move + (`mangle POSTROUTING`, `HMGAPI_HOMECELL`: nothing marked for home Wi-Fi leaves on `rmnet`), + and table 95 holds an unreachable default while home Wi-Fi is down, so marked traffic never + falls through to mobile data. IPv6, and everything with home Wi-Fi off, stays refused as before. +- **Mods' services can look names up on home Wi-Fi** (Ioniq 5 US 260507). Their resolver + (`ANDROID_DNS_MODE=local`) has no servers in the service's process and asks 127.0.0.1; + HMG-API's redirect to home Wi-Fi's DNS server kept that source address, so no query left the + unit. While home Wi-Fi is up, `route_localnet` is on for `wlan0` (the queries are + masqueraded) and only the answers may come back in for 127.x (`HMGAPI_HOMELO`). ## 1.1.0-rc.10 (2026-11-25) diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index e36e521d..940f8929 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -105,9 +105,12 @@ v=4; case $1 in -4) shift ;; -6) v=6; shift ;; esac o=$1 c=$2; shift 2 f=$FW/ip$v.$o; touch "$f" case $o.$c in - route.show) if [ "$1" = dev ]; then grep -- " dev $2 .*table main\$" "$f" | sed 's/ table main$//' || true; else grep -- " table ${3:-main}\$" "$f" || true; fi ;; + route.show) if [ "$1" = dev ]; then grep -- " dev $2 .*table main\$" "$f" | sed 's/ table main$//' || true + elif [ "$1" = table ]; then grep -- " table $2\$" "$f" | sed "s/ table $2\$//" || true; else grep -- " table main\$" "$f" || true; fi ;; route.replace) n=$#; if [ "${@:$((n-1)):1}" = table ]; then tb=${!n}; set -- "${@:1:$((n-2))}"; else tb=main; fi grep -v -- "^$1 .*table $tb\$" "$f" > "$f.new"; mv "$f.new" "$f"; echo "$* table $tb" >> "$f" ;; + route.add) n=$#; if [ "${@:$((n-1)):1}" = table ]; then tb=${!n}; set -- "${@:1:$((n-2))}"; else tb=main; fi + echo "$* table $tb" >> "$f" ;; route.del) grep -q -e "^$1 .*dev $3 .*table main\$" -e "^$1 dev $3 .*table main\$" "$f" || exit 2 awk -v r="$1" -v d="$3" '!x && $1 == r && index($0, " dev " d " ") { x = 1; next } { print }' "$f" > "$f.new"; mv "$f.new" "$f" ;; route.flush) grep -v -- " table $2\$" "$f" > "$f.new"; mv "$f.new" "$f" ;; @@ -143,11 +146,11 @@ printf 'com.example.dl dl\ncom.example.quiet quiet\n' > "$D/state/apps.txt" log=$(keeper once) has "mods kept off cellular" "mods kept off cellular: 2 app(s) and every mod service, home Wi-Fi routing in" "$log" check "the cellular chain first in OUTPUT" "-A OUTPUT -j HMGAPI_CELL" "$(ipt -S OUTPUT | grep -m1 '^-A')" -check "its rules: both services' groups and both apps' uids" "-o rmnet+ -m owner --gid-owner 2950 -j REJECT --o rmnet+ -m owner --gid-owner 2951 -j REJECT --o rmnet+ -m owner --uid-owner 10071 -j REJECT +check "its IPv4 rules: the plain group and the app that didn't ask (home ones: after the reroute)" "-o rmnet+ -m owner --gid-owner 2950 -j REJECT -o rmnet+ -m owner --uid-owner 10072 -j REJECT" "$(cat "$F/fw/4/filter/HMGAPI_CELL")" -check "IPv6 too" 4 "$(grep -c REJECT "$F/fw/6/filter/HMGAPI_CELL")" +check "IPv6: all four (never routed to home Wi-Fi)" 4 "$(grep -c REJECT "$F/fw/6/filter/HMGAPI_CELL")" +check "home Wi-Fi traffic never out on mobile data, checked after the reroute" "-o rmnet+ -m mark --mark 0x2951 -j DROP" "$(cat "$F/fw/4/mangle/HMGAPI_HOMECELL")" +check "... first in POSTROUTING" "-j HMGAPI_HOMECELL" "$(head -1 "$F/fw/4/mangle/POSTROUTING")" check "only the mod that asked marked for home Wi-Fi (and the home group)" "-m owner --gid-owner 2951 -j MARK --set-mark 0x2951 -m owner --uid-owner 10071 -j MARK --set-mark 0x2951" "$(cat "$F/fw/4/mangle/HMGAPI_HOME")" check "masqueraded on wlan0 (home Wi-Fi: the car's own client)" "-o wlan0 -m mark --mark 0x2951 -j MASQUERADE" "$(cat "$F/fw/4/nat/HMGAPI_HOMEOUT")" @@ -160,14 +163,16 @@ has "moved: put back first" "mods' cellular block put back" "$(keeper once)" check "... first again" "-A OUTPUT -j HMGAPI_CELL" "$(ipt -S OUTPUT | grep -m1 '^-A')" printf 'com.example.dl 10091 0 /data/data/com.example.dl default 3003\ncom.example.quiet 10072 0 /data/data/com.example.quiet default 3003\n' > "$F/packages.list" keeper once >/dev/null -has "a reinstalled app's new uid" "--uid-owner 10091 -j REJECT" "$(cat "$F/fw/4/filter/HMGAPI_CELL")" -hasnt "... the old one gone" "10071" "$(cat "$F/fw/4/filter/HMGAPI_CELL")" +has "a reinstalled app's new uid" "--uid-owner 10091 -j REJECT" "$(cat "$F/fw/6/filter/HMGAPI_CELL")" +has "... marked with it" "--uid-owner 10091 -j MARK" "$(cat "$F/fw/4/mangle/HMGAPI_HOME")" +hasnt "... the old one gone" "10071" "$(cat "$F/fw/6/filter/HMGAPI_CELL" "$F/fw/4/mangle/HMGAPI_HOME")" rm "$D/settings/allow/home_wifi" eng publish-state keeper once >/dev/null check "home Wi-Fi off: no marks" no "$([ -f "$F/fw/4/mangle/HMGAPI_HOME" ] && echo yes || echo no)" hasnt "... no routing rule" "900:" "$(cat "$F/fw/ip4.rule")" -check "... still off cellular" 4 "$(grep -c REJECT "$F/fw/4/filter/HMGAPI_CELL")" +check "... still off cellular: all four refused in OUTPUT again" 4 "$(grep -c REJECT "$F/fw/4/filter/HMGAPI_CELL")" +check "... no post-reroute block (nothing is marked)" no "$([ -f "$F/fw/4/mangle/HMGAPI_HOMECELL" ] && echo yes || echo no)" keeper down >/dev/null hasnt "down: the cellular chain gone" "HMGAPI_CELL" "$(ipt -S OUTPUT)" : > "$D/settings/allow/home_wifi" @@ -175,7 +180,7 @@ eng publish-state # ---- the home Wi-Fi keeper, against fake tools X=$T/unit -mkdir -p "$X/data/misc/wifi/sockets" "$X/data/hmgapi/public" "$X/proc/sys/kernel/random" +mkdir -p "$X/data/misc/wifi/sockets" "$X/data/hmgapi/public" "$X/proc/sys/kernel/random" "$X/proc/sys/net/ipv4/conf/wlan0" echo boot-1 > "$X/proc/sys/kernel/random/boot_id" echo "1000.00 2000.00" > "$X/proc/uptime" cat > "$F/bin/hmgapid" <<'S' @@ -306,6 +311,9 @@ has "wlan0's DNS servers for the mods" "resolver setifdns wlan0 10.10.10.100" " has "a DNS server off the subnet: through the gateway" "10.10.10.100/32 via 10.4.0.1 dev wlan0 metric 1000" "$(cat "$F/fw/ip4.route")" check "mods' services' DNS to the home router's" "-m owner --gid-owner 2951 -p udp --dport 53 -j DNAT --to-destination 10.10.10.100 -m owner --gid-owner 2951 -p tcp --dport 53 -j DNAT --to-destination 10.10.10.100" "$(cat "$F/fw/4/nat/HMGAPI_HOMEDNS")" +has "services' lookups (their resolver asks 127.0.0.1) may come back in through wlan0, answers only" "-i wlan0 -d 127.0.0.0/8 -m state --state ESTABLISHED,RELATED -j RETURN +-i wlan0 -d 127.0.0.0/8 -j DROP" "$(cat "$F/fw/4/filter/HMGAPI_HOMELO")" +check "... first in INPUT" "-j HMGAPI_HOMELO" "$(head -1 "$F/fw/4/filter/INPUT")" has "what it saw, for the app" "2437 -61 [WPA2-PSK-CCMP][ESS] Willows" "$(verb seen)" hasnt "the key never in the log" "secret" "$log" FW=$F/fw PATH=$F/bin:$PATH ip route replace default via 10.4.0.1 dev wlan0 # Android puts it back (a renewal) @@ -320,7 +328,9 @@ has "the car on: back" "back to the car's Wi-Fi (the car is on): the car's Wi-Fi check "... the projection hotspot, in its mode" 2 "$(cat "$F/fw/ap")" check "... client off, then the hotspot" "client off start 2" "$(grep -o 'client off\|start [12]' "$F/fw/apps.log")" -check "... table 95 empty" "" "$(grep 'table 95' "$F/fw/ip4.route" || true)" +check "... table 95: unreachable, never the main table's mobile data" "unreachable default table 95" "$(grep 'table 95' "$F/fw/ip4.route" || true)" +check "... route_localnet off again" 0 "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet")" +check "... the 127.x guard gone" no "$([ -f "$F/fw/4/filter/HMGAPI_HOMELO" ] && echo yes || echo no)" check "... waiting again" waiting "$(state)" # the car off without parked (the screen goes dark with it): 30 s, then home Wi-Fi diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index adbe2282..07739e15 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -303,12 +303,26 @@ static List describe(Engine e, Map> json, Se " iptables -t nat -N HMGAPI_HOMEDNS 2>/dev/null; iptables -t nat -F HMGAPI_HOMEDNS", " iptables -t nat -C OUTPUT -j HMGAPI_HOMEDNS 2>/dev/null || iptables -t nat -I OUTPUT 1 -j HMGAPI_HOMEDNS", " for p in udp tcp; do iptables -t nat -A HMGAPI_HOMEDNS -m owner --gid-owner " + HOME_GID + " -p $p --dport 53 -j DNAT --to-destination $d1; done", + " # a service's resolver (ANDROID_DNS_MODE=local) has no servers in its process on these units, so", + " # it asks 127.0.0.1:53: the DNAT above sends that on to $d1 with the source still 127.0.0.1,", + " # which the kernel only routes out of (and back in through) wlan0 with route_localnet. Masqueraded", + " # (HMGAPI_HOMEOUT: marked), so nothing leaves as 127.0.0.1; only the answers to those queries may", + " # come in for 127.x on wlan0 (HMGAPI_HOMELO), nothing a home network sends on its own", + " echo 1 > $X/proc/sys/net/ipv4/conf/$I/route_localnet 2>/dev/null", + " iptables -N HMGAPI_HOMELO 2>/dev/null; iptables -F HMGAPI_HOMELO", + " iptables -C INPUT -j HMGAPI_HOMELO 2>/dev/null || iptables -I INPUT 1 -j HMGAPI_HOMELO", + " iptables -A HMGAPI_HOMELO -i $I -d 127.0.0.0/8 -m state --state ESTABLISHED,RELATED -j RETURN", + " 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\"", " fi", "}", "route_down() {", " ip route flush table $T 2>/dev/null", + " no_route", + " echo 0 > $X/proc/sys/net/ipv4/conf/$I/route_localnet 2>/dev/null", + " for _ in 1 2 3 4; do iptables -D INPUT -j HMGAPI_HOMELO 2>/dev/null || break; done", + " iptables -F HMGAPI_HOMELO 2>/dev/null; iptables -X HMGAPI_HOMELO 2>/dev/null", " iptables -t nat -F HMGAPI_HOMEDNS 2>/dev/null", " for r in $(cat $W/dnsroutes 2>/dev/null); do ip route del $r dev $I 2>/dev/null; done", " rm -f $W/dnsroutes $W/lease", @@ -454,6 +468,7 @@ static List describe(Engine e, Map> json, Se " forget) forget \"$2\"; exit $? ;;", "esac", "trap 'down; say stopped; exit 0' TERM # never left with the hotspot off", + "no_route", "tick() { t0=$(now); sleep $nap; d=$(($(now) - t0)); [ $d -le $((nap + 60)) ] || woke $d; }", "while :; do", " keep", diff --git a/core/runtime/java/hmgapi/engine/Network.java b/core/runtime/java/hmgapi/engine/Network.java index 55e80035..6598539b 100644 --- a/core/runtime/java/hmgapi/engine/Network.java +++ b/core/runtime/java/hmgapi/engine/Network.java @@ -676,6 +676,8 @@ static List describe(String id, Ask a, boolean allowed) { " for _ in 1 2 3 4 5 6 7 8; do iptables -t mangle -D OUTPUT -j HMGAPI_HOME 2>/dev/null || break; done", " iptables -t mangle -F HMGAPI_HOME 2>/dev/null; iptables -t mangle -X HMGAPI_HOME 2>/dev/null", " for _ in 1 2 3 4 5 6 7 8; do iptables -t nat -D POSTROUTING -j HMGAPI_HOMEOUT 2>/dev/null || break; done", + " for _ in 1 2 3 4 5 6 7 8; do iptables -t mangle -D POSTROUTING -j HMGAPI_HOMECELL 2>/dev/null || break; done", + " iptables -t mangle -F HMGAPI_HOMECELL 2>/dev/null; iptables -t mangle -X HMGAPI_HOMECELL 2>/dev/null", " iptables -t nat -F HMGAPI_HOMEOUT 2>/dev/null; iptables -t nat -X HMGAPI_HOMEOUT 2>/dev/null", " for _ in 1 2 3 4 5 6 7 8; do ip rule del priority " + HomeWifi.PRIORITY + " 2>/dev/null || break; done", "}", @@ -684,16 +686,24 @@ static List describe(String id, Ask a, boolean allowed) { " case $mode in block|home) ndc resolver setifaceforuidrange " + HomeWifi.IFACE + " $u $u >/dev/null 2>&1 ;; esac", " done < \"$MA\"", "}", + "# The home group and the mods that asked for home Wi-Fi: their IPv4 packets start on the main table's", + "# route (mobile data) and HMG-API's mark (mangle OUTPUT) moves them to table 95 afterwards. -o in", + "# OUTPUT is the route from before that move, so refusing them there refused every home Wi-Fi", + "# connection (seen on an Ioniq 5 US 260507). With home Wi-Fi on they're refused after the move instead", + "# (mangle POSTROUTING, HMGAPI_HOMECELL: anything marked for home Wi-Fi never leaves on rmnet), and", + "# table 95 is never empty (wifi.sh: an unreachable default while home Wi-Fi is down). IPv6 isn't", + "# routed to home Wi-Fi, so it stays refused in OUTPUT; so does everything with home Wi-Fi off.", "mods_up() {", + " home=; grep -q '^homewifi' \"$MA\" && home=1", " for v in 4 6; do", " ipt $v -N HMGAPI_CELL 2>/dev/null; ipt $v -F HMGAPI_CELL; ipt $v -I OUTPUT 1 -j HMGAPI_CELL", - " for g in " + HomeWifi.SERVICE_GID + " " + HomeWifi.HOME_GID + "; do ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --gid-owner $g -j REJECT; done", + " ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --gid-owner " + HomeWifi.SERVICE_GID + " -j REJECT", + " [ -n \"$home\" ] && [ $v = 4 ] || ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --gid-owner " + HomeWifi.HOME_GID + " -j REJECT", " done", - " home=", " while read -r mode u; do", " case $mode in", - " block|home) for v in 4 6; do ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --uid-owner $u -j REJECT; done ;;", - " homewifi) home=1 ;;", + " block) for v in 4 6; do ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --uid-owner $u -j REJECT; done ;;", + " home) for v in 4 6; do [ -n \"$home\" ] && [ $v = 4 ] || ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --uid-owner $u -j REJECT; done ;;", " esac", " done < \"$MA\"", " mods_dns", @@ -703,6 +713,8 @@ static List describe(String id, Ask a, boolean allowed) { " while read -r mode u; do", " [ \"$mode\" = home ] && iptables -t mangle -A HMGAPI_HOME -m owner --uid-owner $u -j MARK --set-mark " + HomeWifi.MARK, " done < \"$MA\"", + " iptables -t mangle -N HMGAPI_HOMECELL 2>/dev/null; iptables -t mangle -F HMGAPI_HOMECELL; iptables -t mangle -I POSTROUTING 1 -j HMGAPI_HOMECELL", + " iptables -t mangle -A HMGAPI_HOMECELL -o rmnet+ -m mark --mark " + HomeWifi.MARK + " -j DROP", " iptables -t nat -N HMGAPI_HOMEOUT 2>/dev/null; iptables -t nat -F HMGAPI_HOMEOUT; iptables -t nat -I POSTROUTING 1 -j HMGAPI_HOMEOUT", " iptables -t nat -A HMGAPI_HOMEOUT -o " + HomeWifi.IFACE + " -m mark --mark " + HomeWifi.MARK + " -j MASQUERADE", " ip rule add priority " + HomeWifi.PRIORITY + " fwmark " + HomeWifi.MARK + " table " + HomeWifi.TABLE, @@ -713,11 +725,13 @@ static List describe(String id, Ask a, boolean allowed) { " first=$(ipt $v -S OUTPUT 2>/dev/null | while read -r a b rest; do [ \"$a\" = -A ] && { echo \"$rest\"; break; }; done)", " [ \"$first\" = '-j HMGAPI_CELL' ] || return 1", " have=0; for l in $(ipt $v -S HMGAPI_CELL 2>/dev/null | while read -r a rest; do [ \"$a\" = -A ] && echo x; done); do have=$((have + 1)); done", - " want=2; while read -r mode u; do case $mode in block|home) want=$((want + 1)) ;; esac; done < \"$MA\"", + " want=2; grep -q '^homewifi' \"$MA\" && [ $v = 4 ] && want=1", + " while read -r mode u; do case $mode in block) want=$((want + 1)) ;; home) [ $v = 4 ] || want=$((want + 1)) ;; esac; done < \"$MA\"", " [ $have = $want ] || return 1", " done", " grep -q '^homewifi' \"$MA\" || return 0", - " iptables -t mangle -C OUTPUT -j HMGAPI_HOME 2>/dev/null && iptables -t nat -C POSTROUTING -j HMGAPI_HOMEOUT 2>/dev/null || return 1", + " iptables -t mangle -C OUTPUT -j HMGAPI_HOME 2>/dev/null && iptables -t mangle -C POSTROUTING -j HMGAPI_HOMECELL 2>/dev/null \\", + " && iptables -t nat -C POSTROUTING -j HMGAPI_HOMEOUT 2>/dev/null || return 1", " out=$(ip rule show 2>/dev/null); case $out in *\"" + HomeWifi.PRIORITY + ":\"*) ;; *) return 1 ;; esac", "}", "mods_down() { mods_fw_down; rm -f \"$MA\"; }", diff --git a/docs/mod-reference.md b/docs/mod-reference.md index 663fe6cf..c9308e9c 100644 --- a/docs/mod-reference.md +++ b/docs/mod-reference.md @@ -365,6 +365,13 @@ home Wi-Fi; the car's own stays on mobile data. A mod that asks while the switch internet (the plan says so). IPv4 only for now. This is also how HMG-API itself is meant to check for updates. +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 +to `wlan0`'s address; anything marked never leaves on `rmnet` (checked after the reroute, +`mangle POSTROUTING`). A service's own lookups (its resolver asks 127.0.0.1:53) are redirected +to home Wi-Fi's DNS server. A root service may also mark its own sockets (`SO_MARK` 0x2951) so +their route is table 95's from the start. + - Check before a download: `HmgApi.homeWifiUp()`, or `HmgApi.homeWifi()` (`{"state": "up", "rssi": -61, "freq": 2437}`; `state` up, waiting (the car is on), searching, nonetworks, stock (the car's own Wi-Fi settings have the Wi-Fi), off). It never From 9c47c3ecbbd44ff99ff23e5e22ae535f526f8575 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:40 -0500 Subject: [PATCH 08/69] The engine's HTTPS: the unit's own libssl, home Wi-Fi only For the catalogue and updates (next). Android 4.4's Java TLS shares no cipher suite with GitHub, and its MessageDigest SHA-256 can be missing under app_process, so: - core/fetch/fetch.c -> /data/hmgapi/lib/libhmgapi_fetch.so (built like the loader: no libc, dlopen/dlsym only; installed into /data, nothing new on /system). One TLS 1.2 request through the unit's libssl.so; the socket carries home Wi-Fi's mark (SO_MARK 0x2951), so it leaves on home Wi-Fi or not at all. The certificate isn't checked (the unit's 2013 roots and its clock can't be relied on): what's downloaded is trusted only through a SHA-256 and a signature. - NativeFetch (with NativeFetch.Web, files standing in for GitHub off the car), Http (https, GitHub's hosts only, redirects between them, a size cap), DnsLookup (home Wi-Fi's DNS server, asked directly), Sha256 (plain Java). - fetch-test.sh. The same C, built for a computer, fetched catalogue entries and packages from GitHub; first run on an Ioniq 5 US 260507 as a mod. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + build.sh | 22 +- core/fetch/fetch.c | 202 ++++++++++++++++++ core/runtime/fetch-test.sh | 9 + .../runtime/java/hmgapi/engine/DnsLookup.java | 114 ++++++++++ core/runtime/java/hmgapi/engine/Http.java | 174 +++++++++++++++ .../java/hmgapi/engine/NativeFetch.java | 128 +++++++++++ core/runtime/java/hmgapi/engine/Sha256.java | 76 +++++++ .../runtime/test/hmgapi/engine/FetchTest.java | 87 ++++++++ install/common/install.sh | 5 + tools/test-all.sh | 4 +- 11 files changed, 820 insertions(+), 6 deletions(-) create mode 100644 core/fetch/fetch.c create mode 100644 core/runtime/fetch-test.sh create mode 100644 core/runtime/java/hmgapi/engine/DnsLookup.java create mode 100644 core/runtime/java/hmgapi/engine/Http.java create mode 100644 core/runtime/java/hmgapi/engine/NativeFetch.java create mode 100644 core/runtime/java/hmgapi/engine/Sha256.java create mode 100644 core/runtime/test/hmgapi/engine/FetchTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fd5a1b4..53f5e802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,11 @@ HMG-API's redirect to home Wi-Fi's DNS server kept that source address, so no query left the unit. While home Wi-Fi is up, `route_localnet` is on for `wlan0` (the queries are masqueraded) and only the answers may come back in for 127.x (`HMGAPI_HOMELO`). +- **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 + over home Wi-Fi, each with its SHA-256. ## 1.1.0-rc.10 (2026-11-25) diff --git a/build.sh b/build.sh index 8736fa21..8907ec09 100755 --- a/build.sh +++ b/build.sh @@ -34,6 +34,20 @@ loader() { md5sum "$OUT/libhmgapi_hook.so" } +fetchlib() { + # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc, + # only dlopen/dlsym from the unit's libdl (the loader's stand-in), and a JDK's jni.h + sh core/loader/syslib-stubs.sh "$OUT/syslib" >/dev/null + J=${JAVA_HOME:-$(cd "$(dirname "$(readlink -f "$(command -v javac)")")/.." && pwd)} + case "$(uname -s)" in Darwin) JOS=darwin ;; *) JOS=linux ;; esac + clang --target=armv7a-linux-androideabi -mthumb -march=armv7-a -mfloat-abi=softfp -Os -fPIC \ + -ffreestanding -fno-builtin -nostdlib -shared -fno-stack-protector -fno-exceptions -fno-asynchronous-unwind-tables -fuse-ld=lld \ + -I"$J/include" -I"$J/include/$JOS" \ + -Wl,-z,now -Wl,--no-rosegment -Wl,--hash-style=sysv -Wl,-z,defs -Wl,--build-id=none -Wl,-soname,libhmgapi_fetch.so \ + -o "$OUT/libhmgapi_fetch.so" core/fetch/fetch.c "$OUT/syslib/libdl.so" + md5sum "$OUT/libhmgapi_fetch.so" +} + runtime() { rm -rf "$OUT/classes" "$OUT/runtime-stubs" && mkdir -p "$OUT/classes" "$OUT/runtime-stubs" # stubs/: signatures of the car's own classes the runtime extends (compile only, never in the jar) @@ -95,7 +109,7 @@ lpatch() { OUT="$OUT" sh tools/lpatch/build.sh; } payload() { P="$OUT/payload" rm -rf "$P" && mkdir -p "$P" - for f in hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk; do + for f in hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk; do [ -f "$OUT/$f" ] || { echo "payload: no out/$f (build it first)"; exit 1; } cp "$OUT/$f" "$P/" done @@ -120,7 +134,7 @@ payload() { (cd "$P" && find maps -type f | LC_ALL=C sort | xargs md5sum > MAPS.md5) sed -n 's/.*HMGAPI_VERSION = "\(.*\)";/\1/p' core/runtime/java/hmgapi/engine/Engine.java > "$P/VERSION" echo "$(git rev-parse --short HEAD 2>/dev/null || echo local)$(git diff --quiet HEAD 2>/dev/null || echo +) $(date -u +%Y-%m-%d)" > "$P/BUILD" - (cd "$P" && md5sum hmgapid lpatch app_process libhmgapi_hook.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 $(find nemesis -type f | LC_ALL=C sort) > MANIFEST) + (cd "$P" && md5sum hmgapid lpatch app_process libhmgapi_hook.so libhmgapi_fetch.so hmgapi-hook.jar HmgApi.apk install.sh uninstall.sh lib.sh stock.txt app-pending.sh app-open.sh hook-check.sh boot.sh MAPS.md5 $(find nemesis -type f | LC_ALL=C sort) > MANIFEST) echo "payload $(cat "$P/VERSION") ($(cat "$P/BUILD")): $P" } @@ -166,11 +180,11 @@ sdk() { } if [ $# -eq 0 ]; then - set -- hmgapid zygote loader runtime client mods app lpatch payload + set -- hmgapid zygote loader fetchlib runtime client mods app lpatch payload fi for part in "$@"; do case $part in - hmgapid|zygote|loader|runtime|client|mods|app|lpatch|payload|sdk) $part ;; + hmgapid|zygote|loader|fetchlib|runtime|client|mods|app|lpatch|payload|sdk) $part ;; *) echo "unknown part: $part"; exit 2 ;; esac done diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c new file mode 100644 index 00000000..c13465aa --- /dev/null +++ b/core/fetch/fetch.c @@ -0,0 +1,202 @@ +/* libhmgapi_fetch.so: one HTTPS request for HMG-API's engine (hmgapi.engine.NativeFetch): the + * catalogue, mod packages 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 + * handshake with that library, sends the request bytes Java made and writes every response + * byte (headers and body) to a file, up to a cap. Java parses the HTTP. + * + * 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 + * (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. + * + * The socket carries home Wi-Fi's mark (SO_MARK 0x2951: table 95, HomeWifi), so it goes out on home + * Wi-Fi or not at all (table 95 holds an unreachable default while home Wi-Fi is down), never + * on the car's mobile data. Root only (the engine is). + * + * Built with no libc (as the loader): everything comes through dlopen/dlsym from the unit's + * libc.so and libssl.so. On a computer (-DHOST, the off-car tests) it uses the system's headers + * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. + * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. + */ +#include + +#ifdef HOST +#include +#include +#include +#include +#include +#include +#define LIBC_SYM(name) ((void *) name) +typedef socklen_t sock_len; +#else +void *dlopen(const char *path, int flags); +void *dlsym(void *handle, const char *name); +#define RTLD_NOW 2 +typedef unsigned int sock_len; +struct sockaddr; +struct addrinfo { /* bionic, 32-bit ARM */ + int ai_flags, ai_family, ai_socktype, ai_protocol; + sock_len ai_addrlen; + char *ai_canonname; + struct sockaddr *ai_addr; + struct addrinfo *ai_next; +}; +#define AF_INET 2 +#define SOCK_STREAM 1 +#define O_WRONLY 01 +#define O_CREAT 0100 +#define O_TRUNC 01000 +static void *libc_handle; +#define LIBC_SYM(name) dlsym(libc_handle, #name) +static void *memset(void *p, int c, unsigned long n) { unsigned char *b = p; while (n--) *b++ = (unsigned char) c; return p; } +#endif + +/* error codes (negative), so Java can say which step failed */ +enum { E_LIB = -1, E_SYM = -2, E_RESOLVE = -3, E_CONNECT = -4, E_CTX = -5, E_HANDSHAKE = -6, E_SEND = -7, + E_FILE = -8, E_TOO_BIG = -9, E_READ = -10, E_ARGS = -11 }; + +#define SSL_CTRL_OPTIONS 32 +#define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L + +/* host is "name" or "name@address": the name goes in the TLS server name, and the connection goes + * to the address when there is one (Java's own lookup, DnsLookup: the unit's resolver can't be + * used by a mod's service on home Wi-Fi, see there) */ +static int fetch(const char *ssl_lib, const char *c_lib, const char *host_arg, const char *port, + const char *request, int request_len, const char *out_path, int max_bytes) { + char host[256]; + const char *addr = host_arg; + int hn = 0; + while (host_arg[hn] && host_arg[hn] != '@' && hn < (int) sizeof host - 1) { host[hn] = host_arg[hn]; hn++; } + host[hn] = 0; + if (host_arg[hn] == '@') addr = host_arg + hn + 1; + else if (host_arg[hn]) return E_ARGS; + else addr = host; + void *ssl_h = dlopen(ssl_lib, RTLD_NOW); + if (!ssl_h) return E_LIB; +#ifndef HOST + libc_handle = dlopen(c_lib, RTLD_NOW); + if (!libc_handle) return E_LIB; +#else + (void) c_lib; +#endif + int (*p_getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **) = LIBC_SYM(getaddrinfo); + void (*p_freeaddrinfo)(struct addrinfo *) = LIBC_SYM(freeaddrinfo); + int (*p_socket)(int, int, int) = LIBC_SYM(socket); + int (*p_connect)(int, const struct sockaddr *, sock_len) = LIBC_SYM(connect); + int (*p_setsockopt)(int, int, int, const void *, sock_len) = LIBC_SYM(setsockopt); + int (*p_close)(int) = LIBC_SYM(close); + int (*p_open)(const char *, int, ...) = LIBC_SYM(open); + long (*p_write)(int, const void *, unsigned long) = LIBC_SYM(write); + if (!p_getaddrinfo || !p_freeaddrinfo || !p_socket || !p_connect || !p_close || !p_open || !p_write) return E_SYM; + + /* OpenSSL 1.0.x names first (the unit), then 1.1+/3 (a computer) */ + int (*p_init_old)(void) = dlsym(ssl_h, "SSL_library_init"); + int (*p_init_new)(unsigned long long, const void *) = dlsym(ssl_h, "OPENSSL_init_ssl"); + const void *(*p_method)(void) = dlsym(ssl_h, "SSLv23_client_method"); + if (!p_method) p_method = dlsym(ssl_h, "TLS_client_method"); + void *(*p_ctx_new)(const void *) = dlsym(ssl_h, "SSL_CTX_new"); + void (*p_ctx_free)(void *) = dlsym(ssl_h, "SSL_CTX_free"); + long (*p_ctx_ctrl)(void *, int, long, void *) = dlsym(ssl_h, "SSL_CTX_ctrl"); + unsigned long (*p_ctx_set_options)(void *, unsigned long) = dlsym(ssl_h, "SSL_CTX_set_options"); + void *(*p_new)(void *) = dlsym(ssl_h, "SSL_new"); + void (*p_free)(void *) = dlsym(ssl_h, "SSL_free"); + long (*p_ctrl)(void *, int, long, void *) = dlsym(ssl_h, "SSL_ctrl"); + int (*p_set_fd)(void *, int) = dlsym(ssl_h, "SSL_set_fd"); + int (*p_ssl_connect)(void *) = dlsym(ssl_h, "SSL_connect"); + int (*p_ssl_write)(void *, const void *, int) = dlsym(ssl_h, "SSL_write"); + int (*p_ssl_read)(void *, void *, int) = dlsym(ssl_h, "SSL_read"); + int (*p_shutdown)(void *) = dlsym(ssl_h, "SSL_shutdown"); + if ((!p_init_old && !p_init_new) || !p_method || !p_ctx_new || !p_ctx_free || !p_new || !p_free || !p_ctrl + || !p_set_fd || !p_ssl_connect || !p_ssl_write || !p_ssl_read) return E_SYM; + + struct addrinfo hints, *res = 0, *a; + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_INET; /* home Wi-Fi is IPv4 only for mods */ + hints.ai_socktype = SOCK_STREAM; + if (p_getaddrinfo(addr, port, &hints, &res) != 0 || !res) return E_RESOLVE; + int fd = -1; + for (a = res; a; a = a->ai_next) { + fd = p_socket(a->ai_family, a->ai_socktype, a->ai_protocol); + if (fd < 0) continue; +#ifndef HOST + /* home Wi-Fi's mark on the socket itself, so the connection's route is table 95's from the + * start (home Wi-Fi, or unreachable): never the main table's mobile data */ + if (p_setsockopt) { + unsigned int mark = 0x2951; + p_setsockopt(fd, 1 /* SOL_SOCKET */, 36 /* SO_MARK */, &mark, sizeof mark); + } +#endif + if (p_connect(fd, a->ai_addr, a->ai_addrlen) == 0) break; + p_close(fd); + fd = -1; + } + p_freeaddrinfo(res); + if (fd < 0) return E_CONNECT; + + int rc; + void *ctx = 0, *ssl = 0; + int out = -1; + if (p_init_new) p_init_new(0, 0); else p_init_old(); + ctx = p_ctx_new(p_method()); + if (!ctx) { rc = E_CTX; goto done; } + if (p_ctx_set_options) p_ctx_set_options(ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); + else if (p_ctx_ctrl) p_ctx_ctrl(ctx, SSL_CTRL_OPTIONS, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3, 0); + ssl = p_new(ctx); + if (!ssl) { rc = E_CTX; goto done; } + p_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *) host); /* server name: GitHub's hosts need it */ + if (p_set_fd(ssl, fd) != 1 || p_ssl_connect(ssl) != 1) { rc = E_HANDSHAKE; goto done; } + int sent = 0; + while (sent < request_len) { + int n = p_ssl_write(ssl, request + sent, request_len - sent); + if (n <= 0) { rc = E_SEND; goto done; } + sent += n; + } + out = p_open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0600); + if (out < 0) { rc = E_FILE; goto done; } + static char buf[16384]; + int total = 0; + for (;;) { + int n = p_ssl_read(ssl, buf, sizeof buf); + if (n <= 0) break; /* the server closes after the response (Connection: close) */ + if (total + n > max_bytes) { rc = E_TOO_BIG; goto done; } + int w = 0; + while (w < n) { + long k = p_write(out, buf + w, (unsigned long) (n - w)); + if (k <= 0) { rc = E_FILE; goto done; } + w += (int) k; + } + total += n; + } + rc = total > 0 ? total : E_READ; +done: + if (out >= 0) p_close(out); + if (ssl) { if (p_shutdown) p_shutdown(ssl); p_free(ssl); } + if (ctx) p_ctx_free(ctx); + p_close(fd); + return rc; +} + +JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_fetch(JNIEnv *env, jclass cls, jstring ssl_lib, jstring c_lib, + jstring host, jstring port, jbyteArray request, jstring out_path, jint max_bytes) { + (void) cls; + if (!ssl_lib || !c_lib || !host || !port || !request || !out_path || max_bytes <= 0) return E_ARGS; + const char *s = (*env)->GetStringUTFChars(env, ssl_lib, 0), *c = (*env)->GetStringUTFChars(env, c_lib, 0); + const char *h = (*env)->GetStringUTFChars(env, host, 0), *p = (*env)->GetStringUTFChars(env, port, 0); + const char *o = (*env)->GetStringUTFChars(env, out_path, 0); + jsize len = (*env)->GetArrayLength(env, request); + jbyte *req = (*env)->GetByteArrayElements(env, request, 0); + int rc = (s && c && h && p && o && req) ? fetch(s, c, h, p, (const char *) req, (int) len, o, (int) max_bytes) : E_ARGS; + if (req) (*env)->ReleaseByteArrayElements(env, request, req, JNI_ABORT); + if (o) (*env)->ReleaseStringUTFChars(env, out_path, o); + if (p) (*env)->ReleaseStringUTFChars(env, port, p); + if (h) (*env)->ReleaseStringUTFChars(env, host, h); + if (c) (*env)->ReleaseStringUTFChars(env, c_lib, c); + if (s) (*env)->ReleaseStringUTFChars(env, ssl_lib, s); + return rc; +} diff --git a/core/runtime/fetch-test.sh b/core/runtime/fetch-test.sh new file mode 100644 index 00000000..9d1fc5d1 --- /dev/null +++ b/core/runtime/fetch-test.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Off-car test of the engine's HTTPS pieces (Http, NativeFetch.Web, Sha256, DnsLookup); the library +# itself (core/fetch/fetch.c) needs the unit's libssl, or a computer's: catalog-test.sh's notes. +set -e +cd "$(dirname "$0")/../.." +CP=$(mktemp -d); trap 'rm -rf "$CP"' EXIT +sh tools/engine-classes.sh "$CP" 2>/dev/null +javac --release 8 -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/FetchTest.java 2>/dev/null +java -cp "$CP" hmgapi.engine.FetchTest diff --git a/core/runtime/java/hmgapi/engine/DnsLookup.java b/core/runtime/java/hmgapi/engine/DnsLookup.java new file mode 100644 index 00000000..59d40141 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/DnsLookup.java @@ -0,0 +1,114 @@ +package hmgapi.engine; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +/** + * A host's IPv4 addresses, asked of home Wi-Fi's own DNS server (dhcp.wlan0.dns1) over UDP, for the + * engine's downloads (NativeFetch). Not the system resolver: the engine runs as root outside netd's + * per-app setup, where lookups would go to the car's carrier DNS on mobile data. wifi.sh routes + * wlan0's DNS servers through wlan0, so this query goes out on home Wi-Fi or not at all. + */ +final class DnsLookup { + private DnsLookup() {} + + static final int TRIES = 3, TIMEOUT_MS = 3000; + + /** the server: home Wi-Fi's DHCP DNS, or its gateway; null when home Wi-Fi gave neither */ + static String server(Engine e) { + for (String p : new String[] {"dhcp.wlan0.dns1", "dhcp.wlan0.gateway"}) { + String v = e.getprop(p); + if (v != null && v.matches("\\d{1,3}(\\.\\d{1,3}){3}")) return v; + } + return null; + } + + /** host's A records (dotted), first answer first; empty if none */ + static List lookup(String server, String host) throws IOException { + Random rnd = new Random(); + IOException last = null; + for (int t = 0; t < TRIES; t++) { + int id = rnd.nextInt(0x10000); + byte[] q = query(id, host); + DatagramSocket s = new DatagramSocket(); + try { + s.setSoTimeout(TIMEOUT_MS); + s.connect(InetAddress.getByAddress(dotted(server)), 53); + s.send(new DatagramPacket(q, q.length)); + byte[] r = new byte[1500]; + DatagramPacket p = new DatagramPacket(r, r.length); + s.receive(p); + return answers(r, p.getLength(), id); + } catch (IOException e) { + last = e; + } finally { + s.close(); + } + } + throw last != null ? last : new IOException("no answer"); + } + + static byte[] query(int id, String host) { + ByteArrayOutputStream o = new ByteArrayOutputStream(); + o.write(id >> 8); o.write(id); o.write(1); o.write(0); // recursion desired + o.write(0); o.write(1); for (int i = 0; i < 6; i++) o.write(0); + for (String l : host.split("\\.")) { + if (l.isEmpty() || l.length() > 63) throw new IllegalArgumentException("bad host " + host); + o.write(l.length()); + for (int i = 0; i < l.length(); i++) o.write(l.charAt(i)); + } + o.write(0); o.write(0); o.write(1); o.write(0); o.write(1); // A, IN + return o.toByteArray(); + } + + /** the A records of an answer to query id; a wrong id or an error code is an IOException */ + static List answers(byte[] r, int n, int id) throws IOException { + if (n < 12 || u16(r, 0) != id || (r[2] & 0x80) == 0) throw new IOException("not an answer to this query"); + int rcode = r[3] & 0xf; + if (rcode == 3) return new ArrayList(); // no such name + if (rcode != 0) throw new IOException("DNS error " + rcode); + int qd = u16(r, 4), an = u16(r, 6), off = 12; + for (int i = 0; i < qd; i++) off = skipName(r, n, off) + 4; + List out = new ArrayList(); + for (int i = 0; i < an; i++) { + off = skipName(r, n, off); + if (off + 10 > n) throw new IOException("short answer"); + int type = u16(r, off), klass = u16(r, off + 2), len = u16(r, off + 8); + off += 10; + if (off + len > n) throw new IOException("short answer"); + if (type == 1 && klass == 1 && len == 4) + out.add((r[off] & 0xff) + "." + (r[off + 1] & 0xff) + "." + (r[off + 2] & 0xff) + "." + (r[off + 3] & 0xff)); + off += len; + } + return out; + } + + private static int skipName(byte[] r, int n, int off) throws IOException { + for (int guard = 0; guard < 128; guard++) { + if (off >= n) throw new IOException("short answer"); + int l = r[off] & 0xff; + if (l == 0) return off + 1; + if ((l & 0xc0) == 0xc0) return off + 2; // a pointer ends the name + off += 1 + l; + } + throw new IOException("bad name"); + } + + private static int u16(byte[] r, int off) { + return ((r[off] & 0xff) << 8) | (r[off + 1] & 0xff); + } + + private static byte[] dotted(String a) { + String[] p = a.split("\\."); + byte[] b = new byte[4]; + for (int i = 0; i < 4; i++) b[i] = (byte) Integer.parseInt(p[i]); + return b; + } +} diff --git a/core/runtime/java/hmgapi/engine/Http.java b/core/runtime/java/hmgapi/engine/Http.java new file mode 100644 index 00000000..9ccd7108 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Http.java @@ -0,0 +1,174 @@ +package hmgapi.engine; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * HTTPS GET to a file, for the catalogue and updates (Catalog), over a transport that only moves + * bytes (NativeFetch on the unit, files in the off-car tests). Only https, only GitHub's hosts, + * redirects followed between them, a size cap. Nothing is trusted because of where it came from + * (see NativeFetch). + */ +final class Http { + interface Transport { + /** sends request to host:443 over TLS and writes the whole raw answer to rawOut; bytes written, or a negative error */ + int exchange(String host, byte[] request, File rawOut, int maxBytes); + } + + static final Set HOSTS = new HashSet(Arrays.asList("github.com", "api.github.com", "raw.githubusercontent.com", + "objects.githubusercontent.com", "release-assets.githubusercontent.com", "codeload.github.com")); + static final int MAX_REDIRECTS = 5; + /** headers and chunk framing on top of the body's cap */ + static final int OVERHEAD = 65536; + + static final class Result { + final int status; + final String error; + + Result(int status, String error) { + this.status = status; + this.error = error; + } + + boolean ok() { + return status == 200 && error == null; + } + + @Override + public String toString() { + return error != null ? error : "HTTP " + status; + } + } + + private final Transport transport; + private final File tmp; + + Http(Transport transport, File tmpDir) { + this.transport = transport; + this.tmp = new File(tmpDir, "answer.raw"); + } + + /** GET url into out (replaced only on a 200); maxBytes: the body's cap */ + Result get(String url, File out, int maxBytes) throws IOException { + for (int hop = 0; hop <= MAX_REDIRECTS; hop++) { + if (!url.startsWith("https://")) return new Result(0, "not https: " + url); + String rest = url.substring(8); + int slash = rest.indexOf('/'); + String host = slash < 0 ? rest : rest.substring(0, slash), path = slash < 0 ? "/" : rest.substring(slash); + if (!HOSTS.contains(host)) return new Result(0, "host not allowed: " + host); + if (path.indexOf(' ') >= 0 || path.indexOf('\r') >= 0 || path.indexOf('\n') >= 0) return new Result(0, "bad path"); + byte[] request = ("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\nUser-Agent: HMG-API/" + Engine.HMGAPI_VERSION + "\r\n" + + ("api.github.com".equals(host) ? "Accept: application/vnd.github+json\r\nX-GitHub-Api-Version: 2022-11-28\r\n" : "Accept: */*\r\n") + + "Accept-Encoding: identity\r\nConnection: close\r\n\r\n").getBytes("US-ASCII"); + int n = transport.exchange(host, request, tmp, maxBytes + OVERHEAD); + try { + if (n < 0) return new Result(0, host + ": " + NativeFetch.why(n)); + InputStream in = new BufferedInputStream(new FileInputStream(tmp)); + try { + String statusLine = line(in); + String[] sp = statusLine.split(" "); + if (sp.length < 2 || !sp[0].startsWith("HTTP/1.")) return new Result(0, "not an HTTP answer"); + int status; + try { + status = Integer.parseInt(sp[1]); + } catch (NumberFormatException e) { + return new Result(0, "not an HTTP answer"); + } + Map headers = new HashMap(); + for (String l = line(in); !l.isEmpty(); l = line(in)) { + int c = l.indexOf(':'); + if (c > 0) headers.put(l.substring(0, c).trim().toLowerCase(Locale.US), l.substring(c + 1).trim()); + } + if (status == 301 || status == 302 || status == 303 || status == 307 || status == 308) { + String to = headers.get("location"); + if (to == null) return new Result(status, "redirect without a location"); + url = to.startsWith("/") ? "https://" + host + to : to; + continue; + } + if (status != 200) return new Result(status, null); + File part = new File(out.getPath() + ".part"); + OutputStream o = new FileOutputStream(part); + long got; + try { + got = "chunked".equalsIgnoreCase(headers.get("transfer-encoding")) ? chunked(in, o, maxBytes) : copy(in, o, maxBytes); + } finally { + o.close(); + } + String len = headers.get("content-length"); + if (got < 0 || (len != null && !len.equals(String.valueOf(got)))) { + part.delete(); + return new Result(status, got < 0 ? "larger than " + maxBytes + " bytes" : "cut off: " + got + " of " + len + " bytes"); + } + if (!part.renameTo(out)) { + part.delete(); + return new Result(status, "can't write " + out); + } + return new Result(200, null); + } finally { + in.close(); + } + } finally { + tmp.delete(); + } + } + return new Result(0, "too many redirects"); + } + + private static String line(InputStream in) throws IOException { + ByteArrayOutputStream b = new ByteArrayOutputStream(); + for (int c = in.read(); c >= 0 && c != '\n'; c = in.read()) { + if (c != '\r') b.write(c); + if (b.size() > 8192) throw new IOException("header line too long"); + } + return b.toString("ISO-8859-1"); + } + + /** bytes copied, or -1 past the cap */ + private static long copy(InputStream in, OutputStream out, int max) throws IOException { + byte[] buf = new byte[8192]; + long total = 0; + for (int n = in.read(buf); n > 0; n = in.read(buf)) { + total += n; + if (total > max) return -1; + out.write(buf, 0, n); + } + return total; + } + + private static long chunked(InputStream in, OutputStream out, int max) throws IOException { + long total = 0; + byte[] buf = new byte[8192]; + for (;;) { + String l = line(in); + int semi = l.indexOf(';'); + int size; + try { + size = Integer.parseInt((semi < 0 ? l : l.substring(0, semi)).trim(), 16); + } catch (NumberFormatException e) { + throw new IOException("bad chunk size"); + } + if (size == 0) return total; + total += size; + if (total > max) return -1; + for (int left = size; left > 0; ) { + int n = in.read(buf, 0, Math.min(left, buf.length)); + if (n <= 0) throw new IOException("chunk cut off"); + out.write(buf, 0, n); + left -= n; + } + line(in); // the CRLF after the chunk + } + } +} diff --git a/core/runtime/java/hmgapi/engine/NativeFetch.java b/core/runtime/java/hmgapi/engine/NativeFetch.java new file mode 100644 index 00000000..4c6047fc --- /dev/null +++ b/core/runtime/java/hmgapi/engine/NativeFetch.java @@ -0,0 +1,128 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +/** + * 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. + * + * Off the car (the tests) Web stands in for it: HMGAPI_TEST_WEB= serves //. + */ +final class NativeFetch implements Http.Transport { + static final String LIB = "/data/hmgapi/lib/libhmgapi_fetch.so", SSL = "/system/lib/libssl.so", LIBC = "/system/lib/libc.so"; + + private final Engine e; + private final String sslLib, cLib; + + private NativeFetch(Engine e, String lib, String sslLib, String cLib) { + System.load(lib); + this.e = e; + this.sslLib = sslLib; + this.cLib = cLib; + } + + /** the transport for this engine: the library on the unit, files in the tests; null (said why) when there's none */ + static Http.Transport forEngine(Engine e, List why) { + String web = Engine.env("HMGAPI_TEST_WEB", null); + if (e.host && web != null) return new Web(new File(web)); + File lib = new File(e.root + LIB); + if (!lib.isFile()) { + why.add("HMG-API's HTTPS library isn't installed (" + LIB + "): install HMG-API again"); + return null; + } + try { + // off the car (a live test from a computer): that computer's TLS library + String ssl = e.host ? Engine.env("HMGAPI_TEST_SSL", SSL) : SSL; + return new NativeFetch(e, lib.getPath(), ssl, LIBC); + } catch (Throwable t) { + why.add("HMG-API's HTTPS library didn't load: " + t); + return null; + } + } + + static native int fetch(String sslLib, String cLib, String host, String port, byte[] request, String outPath, int maxBytes); + + @Override + public int exchange(String host, byte[] request, File rawOut, int maxBytes) { + String dns = DnsLookup.server(e); + if (dns == null) return -3; + String target; + try { + List a = DnsLookup.lookup(dns, host); + if (a.isEmpty()) return -3; + target = host + "@" + a.get(0); + } catch (IOException x) { + return -3; + } + return fetch(sslLib, cLib, target, "443", request, rawOut.getPath(), maxBytes); + } + + static String why(int code) { + switch (code) { + case -1: return "the TLS or C library can't be opened"; + case -2: return "a function is missing from the TLS or C library"; + case -3: return "the name didn't resolve (is home Wi-Fi up?)"; + case -4: return "no connection (home Wi-Fi up, with internet?)"; + case -5: return "TLS setup failed"; + case -6: return "TLS handshake failed"; + case -7: return "the request couldn't be sent"; + case -8: return "the file couldn't be written"; + case -9: return "the answer is larger than allowed"; + case -10: return "no answer"; + default: return "error " + code; + } + } + + /** + * Off-car tests: // (a query's '?' as '_'), 200 with its bytes; .redirect holds a + * Location for a 302; .status a status to answer with instead; anything else 404. Each request's + * host and path is appended to /requests.log. + */ + static final class Web implements Http.Transport { + private final File dir; + + Web(File dir) { + this.dir = dir; + } + + @Override + public int exchange(String host, byte[] request, File rawOut, int maxBytes) { + try { + String req = new String(request, "US-ASCII"); + String path = req.substring(4, req.indexOf(' ', 4)); + File log = new File(dir, "requests.log"); + Engine.write(log, (log.isFile() ? Engine.read(log) : "") + host + path + "\n"); + if (new File(dir, host + ".down").exists()) return -4; + File f = new File(dir, host + path.replace('?', '_')); + String head; + byte[] body = new byte[0]; + if (new File(f.getPath() + ".redirect").isFile()) { + head = "HTTP/1.1 302 Found\r\nLocation: " + Engine.read(new File(f.getPath() + ".redirect")).trim() + "\r\nContent-Length: 0\r\n"; + } else if (new File(f.getPath() + ".status").isFile()) { + head = "HTTP/1.1 " + Engine.read(new File(f.getPath() + ".status")).trim() + " X\r\nContent-Length: 0\r\n"; + } else if (f.isFile()) { + body = Engine.readAll(new java.io.FileInputStream(f)); + head = "HTTP/1.1 200 OK\r\nContent-Length: " + body.length + "\r\n"; + } else { + head = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n"; + } + OutputStream o = new FileOutputStream(rawOut); + try { + o.write((head + "\r\n").getBytes("US-ASCII")); + o.write(body); + } finally { + o.close(); + } + return (int) rawOut.length(); + } catch (Exception x) { + return -10; + } + } + } +} diff --git a/core/runtime/java/hmgapi/engine/Sha256.java b/core/runtime/java/hmgapi/engine/Sha256.java new file mode 100644 index 00000000..cf072ff7 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Sha256.java @@ -0,0 +1,76 @@ +package hmgapi.engine; + +/** + * SHA-256 (FIPS 180-4) in plain Java, for the catalogue's package 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. + */ +final class Sha256 { + private static final int[] K = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + + private final int[] h = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + private final byte[] block = new byte[64]; + private final int[] w = new int[64]; + private int fill; + private long bytes; + + void update(byte[] b, int off, int len) { + bytes += len; + while (len > 0) { + int n = Math.min(len, 64 - fill); + System.arraycopy(b, off, block, fill, n); + fill += n; off += n; len -= n; + if (fill == 64) { compress(); fill = 0; } + } + } + + byte[] digest() { + long bits = bytes * 8; + byte[] pad = new byte[(fill < 56 ? 56 - fill : 120 - fill) + 8]; + pad[0] = (byte) 0x80; + for (int i = 0; i < 8; i++) pad[pad.length - 1 - i] = (byte) (bits >>> (8 * i)); + update(pad, 0, pad.length); + byte[] out = new byte[32]; + for (int i = 0; i < 8; i++) for (int j = 0; j < 4; j++) out[i * 4 + j] = (byte) (h[i] >>> (24 - 8 * j)); + return out; + } + + private void compress() { + for (int i = 0; i < 16; i++) + w[i] = ((block[i * 4] & 0xff) << 24) | ((block[i * 4 + 1] & 0xff) << 16) | ((block[i * 4 + 2] & 0xff) << 8) | (block[i * 4 + 3] & 0xff); + for (int i = 16; i < 64; i++) { + int s0 = Integer.rotateRight(w[i - 15], 7) ^ Integer.rotateRight(w[i - 15], 18) ^ (w[i - 15] >>> 3); + int s1 = Integer.rotateRight(w[i - 2], 17) ^ Integer.rotateRight(w[i - 2], 19) ^ (w[i - 2] >>> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + int a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; i++) { + int t1 = hh + (Integer.rotateRight(e, 6) ^ Integer.rotateRight(e, 11) ^ Integer.rotateRight(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]; + int t2 = (Integer.rotateRight(a, 2) ^ Integer.rotateRight(a, 13) ^ Integer.rotateRight(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; + } + h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; + } + + static String hex(java.io.File f) throws java.io.IOException { + Sha256 d = new Sha256(); + java.io.InputStream in = new java.io.FileInputStream(f); + try { + byte[] buf = new byte[16384]; + for (int n; (n = in.read(buf)) > 0; ) d.update(buf, 0, n); + } finally { + in.close(); + } + StringBuilder sb = new StringBuilder(); + for (byte x : d.digest()) sb.append(Character.forDigit((x >> 4) & 0xf, 16)).append(Character.forDigit(x & 0xf, 16)); + return sb.toString(); + } +} diff --git a/core/runtime/test/hmgapi/engine/FetchTest.java b/core/runtime/test/hmgapi/engine/FetchTest.java new file mode 100644 index 00000000..9d0d5ae5 --- /dev/null +++ b/core/runtime/test/hmgapi/engine/FetchTest.java @@ -0,0 +1,87 @@ +package hmgapi.engine; + +import java.io.File; +import java.nio.file.Files; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Random; + +/** The engine's HTTPS pieces without a network: Http over NativeFetch.Web (files), Sha256, DnsLookup's reader. */ +public final class FetchTest { + static int failed; + + static void check(String what, boolean ok) { + System.out.println((ok ? "ok " : "FAIL ") + what); + if (!ok) failed++; + } + + static void put(File web, String path, String body) throws Exception { + File f = new File(web, path); + f.getParentFile().mkdirs(); + Files.write(f.toPath(), body.getBytes("UTF-8")); + } + + public static void main(String[] args) throws Exception { + File d = Files.createTempDirectory("fetch").toFile(), web = new File(d, "web"), tmp = new File(d, "tmp"); + tmp.mkdirs(); + Http http = new Http(new NativeFetch.Web(web), tmp); + File out = new File(d, "out"); + + put(web, "raw.githubusercontent.com/a.txt", "hello, car"); + check("200: written", http.get("https://raw.githubusercontent.com/a.txt", out, 100).ok() && "hello, car".equals(Engine.read(out))); + put(web, "github.com/r.zip.redirect", "https://objects.githubusercontent.com/x.zip"); + put(web, "objects.githubusercontent.com/x.zip", "zip bytes"); + check("a redirect to GitHub's asset host: followed", http.get("https://github.com/r.zip", out, 100).ok() && "zip bytes".equals(Engine.read(out))); + put(web, "github.com/evil.redirect", "https://example.com/x"); + Http.Result r = http.get("https://github.com/evil", out, 100); + check("a redirect to another host: refused (" + r + ")", !r.ok() && r.toString().contains("host not allowed")); + check("plain http: refused", !http.get("http://github.com/a", out, 100).ok()); + check("another host: refused", !http.get("https://example.com/a", out, 100).ok()); + put(web, "api.github.com/repos/x/y/contents/c_ref=main", "[]"); + check("the API, with a query", http.get("https://api.github.com/repos/x/y/contents/c?ref=main", out, 100).ok()); + put(web, "raw.githubusercontent.com/big", new String(new char[500]).replace('\0', 'x')); + File big = new File(d, "big"); + r = http.get("https://raw.githubusercontent.com/big", big, 100); + check("over the cap: refused, nothing left (" + r + ")", !r.ok() && !big.exists() && !new File(d, "big.part").exists()); + check("404: reported", http.get("https://raw.githubusercontent.com/none", out, 100).status == 404); + new File(web, "raw.githubusercontent.com.down").createNewFile(); + r = http.get("https://raw.githubusercontent.com/a.txt", out, 100); + check("no connection: said (" + r + ")", !r.ok() && r.toString().contains("no connection")); + + boolean same = true; + Random rnd = new Random(7); + for (int len : new int[] {0, 1, 55, 56, 63, 64, 65, 119, 120, 1000, 100000}) { + byte[] data = new byte[len]; + rnd.nextBytes(data); + Sha256 s = new Sha256(); + s.update(data, 0, Math.min(len, 7)); + if (len > 7) s.update(data, 7, len - 7); + same &= Arrays.equals(s.digest(), MessageDigest.getInstance("SHA-256").digest(data)); + } + check("SHA-256: the JDK's at every length tried", same); + Files.write(out.toPath(), "abc".getBytes("US-ASCII")); + check("SHA-256 of a file, hex", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad".equals(Sha256.hex(out))); + + byte[] q = DnsLookup.query(0x1234, "raw.githubusercontent.com"); + java.io.ByteArrayOutputStream a = new java.io.ByteArrayOutputStream(); + a.write(q, 0, q.length); + byte[] ans = a.toByteArray(); + ans[2] = (byte) 0x81; ans[3] = (byte) 0x80; ans[7] = 3; + a.reset(); a.write(ans, 0, ans.length); + for (int[] rr : new int[][] {{0xc0, 12, 0, 5, 0, 1, 0, 0, 0, 60, 0, 2, 0xc0, 12}, + {0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 185, 199, 108, 133}, {0xc0, 12, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 185, 199, 109, 133}}) { + for (int b : rr) a.write(b); + } + byte[] dr = a.toByteArray(); + check("DNS: A records read, a CNAME skipped", DnsLookup.answers(dr, dr.length, 0x1234).toString().equals("[185.199.108.133, 185.199.109.133]")); + boolean refused = false; + try { DnsLookup.answers(dr, dr.length, 0x4321); } catch (java.io.IOException x) { refused = true; } + check("DNS: an answer to another query refused", refused); + refused = false; + try { DnsLookup.answers(dr, dr.length - 3, 0x1234); } catch (java.io.IOException x) { refused = true; } + check("DNS: a cut-off answer refused", refused); + dr[3] = (byte) 0x83; + check("DNS: no such name: none", DnsLookup.answers(dr, dr.length, 0x1234).isEmpty()); + System.exit(failed == 0 ? 0 : 1); + } +} diff --git a/install/common/install.sh b/install/common/install.sh index bc889914..d56e153e 100644 --- a/install/common/install.sh +++ b/install/common/install.sh @@ -304,6 +304,11 @@ cp "$P/uninstall.sh" "$P/lib.sh" "$P/stock.txt" "$P/app-pending.sh" "$P/hook-che # open.sh (NEMESIS Manager's Launch, adb) installs the app from this copy if it's missing, then opens it cp "$P/app-open.sh" "$D/open.sh" && chmod 700 "$D/open.sh" || fail "keep open.sh" cp "$P/HmgApi.apk" "$D/HmgApi.apk" && chmod 644 "$D/HmgApi.apk" || fail "keep a copy of the app" +# the engine's HTTPS (the catalogue and updates over home Wi-Fi, Catalog): in /data, nothing on /system for it +if [ -f "$P/libhmgapi_fetch.so" ]; then + mkdir -p "$D/lib" && cp "$P/libhmgapi_fetch.so" "$D/lib/libhmgapi_fetch.so.new" && chmod 644 "$D/lib/libhmgapi_fetch.so.new" \ + && mv "$D/lib/libhmgapi_fetch.so.new" "$D/lib/libhmgapi_fetch.so" || fail "keep the engine's HTTPS library" +fi # HMG-API's NEMESIS scripts and incompatible packages: engine nemesis-sync lists HMG-API and its mods in NEMESIS with them if [ -d "$P/nemesis" ]; then rm -rf "$D/nemesis" && cp -r "$P/nemesis" "$D/nemesis" && chmod -R 700 "$D/nemesis" || fail "keep the NEMESIS scripts" diff --git a/tools/test-all.sh b/tools/test-all.sh index 0d50eb41..3464b82e 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/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/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/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/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 65577e1fe0216c913a1dc978dd3525168a50b748 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:36:01 -0500 Subject: [PATCH 09/69] fetch.c: no jni.h on the unit's build (it pulls in the build machine's libc headers) The few JNI pieces it uses are declared at their places in the standard table, checked at compile time; the library is byte-for-byte the same. CI's Linux headers failed for the ARM target. Co-Authored-By: Claude Opus 5.5 --- build.sh | 7 ++----- core/fetch/fetch.c | 28 ++++++++++++++++++++++++++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/build.sh b/build.sh index 8907ec09..c570d173 100755 --- a/build.sh +++ b/build.sh @@ -35,14 +35,11 @@ loader() { } fetchlib() { - # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc, - # only dlopen/dlsym from the unit's libdl (the loader's stand-in), and a JDK's jni.h + # libhmgapi_fetch.so (core/fetch/fetch.c): the engine's HTTPS through the unit's own libssl; no libc + # or system headers, only dlopen/dlsym from the unit's libdl (the loader's stand-in) sh core/loader/syslib-stubs.sh "$OUT/syslib" >/dev/null - J=${JAVA_HOME:-$(cd "$(dirname "$(readlink -f "$(command -v javac)")")/.." && pwd)} - case "$(uname -s)" in Darwin) JOS=darwin ;; *) JOS=linux ;; esac clang --target=armv7a-linux-androideabi -mthumb -march=armv7-a -mfloat-abi=softfp -Os -fPIC \ -ffreestanding -fno-builtin -nostdlib -shared -fno-stack-protector -fno-exceptions -fno-asynchronous-unwind-tables -fuse-ld=lld \ - -I"$J/include" -I"$J/include/$JOS" \ -Wl,-z,now -Wl,--no-rosegment -Wl,--hash-style=sysv -Wl,-z,defs -Wl,--build-id=none -Wl,-soname,libhmgapi_fetch.so \ -o "$OUT/libhmgapi_fetch.so" core/fetch/fetch.c "$OUT/syslib/libdl.so" md5sum "$OUT/libhmgapi_fetch.so" diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c index c13465aa..020be2d5 100644 --- a/core/fetch/fetch.c +++ b/core/fetch/fetch.c @@ -21,9 +21,8 @@ * and an OpenSSL 1.1+/3 library, which is why each OpenSSL call has an old and a new name. * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. */ -#include - #ifdef HOST +#include #include #include #include @@ -52,6 +51,31 @@ struct addrinfo { /* bionic, 32-bit ARM */ #define O_TRUNC 01000 static void *libc_handle; #define LIBC_SYM(name) dlsym(libc_handle, #name) +/* the few JNI pieces used here, at their places in the standard function table (as jni.h has + * them), so the unit's build needs no system headers (jni.h pulls in the build machine's libc) */ +typedef int jint; +typedef jint jsize; +typedef signed char jbyte; +typedef unsigned char jboolean; +typedef void *jobject; +typedef jobject jclass, jstring, jbyteArray; +struct JNINativeInterface_ { + void *before169[169]; + const char *(*GetStringUTFChars)(void *, jstring, jboolean *); /* 169 */ + void (*ReleaseStringUTFChars)(void *, jstring, const char *); /* 170 */ + jsize (*GetArrayLength)(void *, jbyteArray); /* 171 */ + void *before184[184 - 172]; + jbyte *(*GetByteArrayElements)(void *, jbyteArray, jboolean *); /* 184 */ + void *before192[192 - 185]; + void (*ReleaseByteArrayElements)(void *, jbyteArray, jbyte *, jint); /* 192 */ +}; +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, GetStringUTFChars) == 169 * sizeof(void *), "JNI table"); +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, GetByteArrayElements) == 184 * sizeof(void *), "JNI table"); +_Static_assert(__builtin_offsetof(struct JNINativeInterface_, ReleaseByteArrayElements) == 192 * sizeof(void *), "JNI table"); +typedef const struct JNINativeInterface_ *JNIEnv; +#define JNIEXPORT __attribute__((visibility("default"))) +#define JNICALL +#define JNI_ABORT 2 static void *memset(void *p, int c, unsigned long n) { unsigned char *b = p; while (n--) *b++ = (unsigned char) c; return p; } #endif From 64bfeccccb80f038dc628017fa94cce34e410242 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:40 -0500 Subject: [PATCH 10/69] 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 c90d6aab60cf7a0cac6c0e01cd5e58ab87ed68fb Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Thu, 26 Nov 2026 10:29:40 -0500 Subject: [PATCH 11/69] App: Get mods and Updates in the Mods tab - Mods tab -> Get mods (CatalogActivity): the catalogue with what each mod would do here, its requires, whether its author is on the trusted list; Install / Update / Turn on, showing first every step it takes (CatalogFlow: catalog-plan, then catalog-install), "Install anyway" for another car. Offline: the last check, and "Connect to home Wi-Fi (15 min)" (in P). - Mods tab -> Updates (n) (ModUpdatesActivity): installed mods with a newer version, Update and Update all, HMG-API's own release with its installer and a restart; the switches for the automatic check and for staging mod updates. A mod's row says "update x.y.z", its page has Update; Remove names the mods that need it. - Back on the main screen after installs, the plan and apply as after a USB install. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 23 +- core/app/AndroidManifest.xml | 7 + core/app/java/hmgapi/app/CatalogActivity.java | 154 +++++++++++ core/app/java/hmgapi/app/CatalogFlow.java | 195 ++++++++++++++ core/app/java/hmgapi/app/MainActivity.java | 1 + .../java/hmgapi/app/ModUpdatesActivity.java | 240 ++++++++++++++++++ core/app/java/hmgapi/app/ModsTab.java | 77 +++++- 7 files changed, 688 insertions(+), 9 deletions(-) create mode 100644 core/app/java/hmgapi/app/CatalogActivity.java create mode 100644 core/app/java/hmgapi/app/CatalogFlow.java create mode 100644 core/app/java/hmgapi/app/ModUpdatesActivity.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 062e326b..ca4468a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **Get mods: HMG-API's catalogue on the head unit.** Mods tab → Get mods lists `catalog/` + (each mod's own GitHub release, pinned by SHA-256 and author key) with what installing it + would do here; Install downloads it over home Wi-Fi and installs it. No server of our own: + the catalogue comes from `catalog/index.json` when there is one (`tools/catalog.py index`), + else from GitHub's listing of the folder. Engine: `catalog`, `catalog-plan`, `catalog-install`. - **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 @@ -9,6 +14,19 @@ 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. +- **Updates.** Mods tab → Updates (with how many) lists installed mods with a newer catalogue + version, and a newer HMG-API release (pre-releases only on a pre-release), with Update and + Update all; a mod's row in the list says "update x.y.z". HMG-API checks by itself each time + home Wi-Fi comes up (owner switch `no_update_check` turns that off), and can also download and + stage the mods' updates then (`auto_stage_updates`, off by default); the owner still applies. + HMG-API itself only updates on the owner's tap: its update zip is checked against its + release's `SHA256SUMS`, then against the release key as from a USB stick. Engine: `updates`, + `update ... | --all | hmgapi`, `update-check`; `logs/hmgapi/updates.log`. +- **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 + over home Wi-Fi, each with its SHA-256. - **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 @@ -28,11 +46,6 @@ HMG-API's redirect to home Wi-Fi's DNS server kept that source address, so no query left the unit. While home Wi-Fi is up, `route_localnet` is on for `wlan0` (the queries are masqueraded) and only the answers may come back in for 127.x (`HMGAPI_HOMELO`). -- **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 - over home Wi-Fi, each with its SHA-256. ## 1.1.0-rc.10 (2026-11-25) diff --git a/core/app/AndroidManifest.xml b/core/app/AndroidManifest.xml index 53917f7f..91529577 100644 --- a/core/app/AndroidManifest.xml +++ b/core/app/AndroidManifest.xml @@ -26,6 +26,13 @@ + + + () { + @Override + Hmgapid.Result work() throws Exception { + return refresh ? Hmgapid.call(180000, "engine", "catalog", "--refresh") : Hmgapid.call(60000, "engine", "catalog"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + rows.removeAllViews(); + JSONObject d; + try { + if (e != null) throw e; + d = CatalogFlow.json(r.output); + } catch (Exception x) { + message.setText(e != null ? Hmgapid.unreachable(e) : "Couldn't read the catalogue: " + x.getMessage()); + return; + } + boolean online = d.optBoolean("online"); + connect.setVisibility(online ? View.GONE : View.VISIBLE); + when.setText(CatalogFlow.checked(d)); + JSONArray mods = d.optJSONArray("mods"); + if (d.has("error")) message.setText("Not checked: " + d.optString("error")); + else if (mods == null || mods.length() == 0) message.setText(online ? "Tap Check now to get the catalogue." + : "Not checked yet. " + d.optString("offline", "") + ". Tap Connect to home Wi-Fi, in P, to check now."); + else message.setText(online ? "" : "Offline (" + d.optString("offline") + "): showing the last check."); + for (int i = 0; mods != null && i < mods.length(); i++) row(mods.optJSONObject(i), online); + } + }.start(this); + } + + private void row(final JSONObject m, boolean online) { + Ui.gap(rows, 14); + String st = m.optString("status"); + boolean unfit = m.has("unfit"), hmgapiUnfit = unfit && !m.optString("unfit").startsWith("car: "); + Ui.text(rows, m.optString("name", m.optString("id")) + " " + m.optString("version"), 22, true, hmgapiUnfit ? Color.GRAY : Color.WHITE); + String what; + if ("same".equals(st)) what = "Installed" + (m.optBoolean("enabled", true) ? "" : " (turned off)"); + else if ("update".equals(st)) what = "Update from " + m.optString("installed"); + else if ("older".equals(st)) what = "Installed " + m.optString("installed") + " (newer than the catalogue's)"; + else what = "Not installed"; + Ui.text(rows, what, 16, false, "update".equals(st) ? Ui.GREEN : Color.LTGRAY); + if (m.optString("description").length() > 0) Ui.text(rows, m.optString("description"), 15, false, Color.GRAY); + JSONArray au = m.optJSONArray("authors"); + StringBuilder by = new StringBuilder(); + for (int i = 0; au != null && i < au.length(); i++) by.append(i > 0 ? ", " : "").append(au.optString(i)); + if (by.length() > 0) Ui.text(rows, "By " + by + (m.optBoolean("trusted") ? "" : " · not on HMG-API's trusted author list"), 15, false, + m.optBoolean("trusted") ? Color.GRAY : Ui.WARN); + JSONArray req = m.optJSONArray("requires"); + if (req != null && req.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < req.length(); i++) b.append(i > 0 ? ", " : "").append(req.optString(i)); + Ui.text(rows, "Needs " + b + " (installed with it if missing)", 15, false, Color.GRAY); + } + if (unfit) Ui.text(rows, hmgapiUnfit ? "Can't install: " + m.optString("unfit") : "Not listed for this head unit: " + m.optString("unfit").substring(5), + 15, false, hmgapiUnfit ? Ui.ERROR : Ui.WARN); + if (hmgapiUnfit || "older".equals(st) || ("same".equals(st) && m.optBoolean("enabled", true))) return; + final boolean update = "update".equals(st); + String label = update ? "Update" : "same".equals(st) ? "Turn on" : "Install"; + Button b = Ui.button(rows, label, new View.OnClickListener() { + @Override + public void onClick(View v) { + CatalogFlow.start(CatalogActivity.this, Arrays.asList(m.optString("id")), update, false, new CatalogFlow.Done() { + @Override + public void installed(String output) { + installed = true; + new AlertDialog.Builder(CatalogActivity.this).setTitle("Installed") + .setMessage(MainActivity.readable(output) + "\n\nGo back to apply the changes.") + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(CatalogActivity.this).setTitle("Not installed").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + }); + } + }); + if (!online && !"same".equals(st)) b.setEnabled(false); + } +} diff --git a/core/app/java/hmgapi/app/CatalogFlow.java b/core/app/java/hmgapi/app/CatalogFlow.java new file mode 100644 index 00000000..a3ba434b --- /dev/null +++ b/core/app/java/hmgapi/app/CatalogFlow.java @@ -0,0 +1,195 @@ +package hmgapi.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Installing or updating from the catalogue, for the Catalogue and Updates screens: what it takes + * first (engine catalog-plan: the mods they require, in order), the owner's OK, then the downloads + * and installs (engine catalog-install / update). Nothing is applied here: the screen hands back + * RESULT_OK and the main screen applies (plan first), as after a USB install. + */ +final class CatalogFlow { + private CatalogFlow() {} + + interface Done { + void installed(String output); + + void failed(String output); + } + + /** JSON in an engine answer (it may print notes first) */ + static JSONObject json(String output) throws Exception { + String t = output.trim(); + int i = t.indexOf('{'); + if (i < 0) throw new Exception(t.isEmpty() ? "no answer" : t); + return new JSONObject(t.substring(i)); + } + + /** "update": engine update (ids are installed mods), else engine catalog-install */ + static void start(final Activity a, final List ids, final boolean update, final boolean anyCar, final Done done) { + final AlertDialog wait = new AlertDialog.Builder(a).setMessage("Checking what it needs…").show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + List c = new ArrayList(Arrays.asList("engine", "catalog-plan")); + c.addAll(ids); + if (anyCar) c.add("--any-car"); + return Hmgapid.call(120000, c.toArray(new String[0])); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + JSONObject p; + try { + if (e != null) throw e; + p = json(r.output); + } catch (Exception x) { + done.failed("Couldn't check: " + x.getMessage()); + return; + } + confirm(a, p, ids, update, anyCar, done); + } + }.start(a); + } + + private static void confirm(final Activity a, JSONObject p, final List ids, final boolean update, final boolean anyCar, final Done done) { + StringBuilder msg = new StringBuilder(); + JSONArray steps = p.optJSONArray("steps"); + boolean untrusted = false; + int n = steps == null ? 0 : steps.length(); + for (int i = 0; i < n; i++) { + JSONObject s = steps.optJSONObject(i); + String act = s.optString("action"); + String line = "enable".equals(act) ? "Turn on " + s.optString("name") + : "update".equals(act) ? "Update " + s.optString("name") + " from " + s.optString("installed") + " to " + s.optString("version") + : "Install " + s.optString("name") + " " + s.optString("version"); + if (s.has("for")) line += " (needed by " + s.optString("for") + ")"; + msg.append("• ").append(line).append('\n'); + if (!"enable".equals(act) && !s.optBoolean("trusted", true)) untrusted = true; + } + JSONArray probs = p.optJSONArray("problems"); + JSONArray notes = p.optJSONArray("notes"); + if (probs != null && probs.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < probs.length(); i++) b.append("• ").append(probs.optString(i)).append('\n'); + boolean car = false; + for (int i = 0; i < probs.length(); i++) car |= probs.optString(i).contains("isn't for this head unit"); + AlertDialog.Builder d = new AlertDialog.Builder(a).setTitle("Can't install it").setMessage(b.toString().trim()); + d.setPositiveButton("OK", null); + if (car && !anyCar) { + d.setNeutralButton("Install anyway…", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + new AlertDialog.Builder(a).setTitle("Install anyway?") + .setMessage("Its author didn't list this head unit. It may not work here. HMG-API keeps a backup of every " + + "file it changes, and removing the mod puts them back. Install it only if you know it suits this car.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Install anyway", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface y, int ww) { + start(a, ids, update, true, done); + } + }).show(); + } + }); + } + d.show(); + return; + } + if (n == 0) { + String t = notes != null && notes.length() > 0 ? notes.optString(0) : "Nothing to install: it's installed already."; + new AlertDialog.Builder(a).setMessage(t).setPositiveButton("OK", null).show(); + return; + } + for (int i = 0; notes != null && i < notes.length(); i++) msg.append('\n').append(notes.optString(i)).append('\n'); + msg.append("\nDownloaded over home Wi-Fi from each mod's GitHub release, checked against the catalogue's checksum and " + + "the author's signature. Nothing changes on the head unit until you apply."); + if (untrusted) { + msg.append("\n\nSome of these are by authors who aren't on HMG-API's trusted author list. A mod's code runs inside " + + "the head unit's apps: install mods only from authors you trust."); + } + new AlertDialog.Builder(a) + .setTitle(n == 1 ? (update ? "Update this mod?" : "Install this mod?") : "These " + n + " steps?") + .setMessage(msg.toString().trim()) + .setNegativeButton("Cancel", null) + .setPositiveButton(update ? "Update" : "Install", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int w) { + run(a, ids, update, anyCar, done); + } + }).show(); + } + + private static void run(final Activity a, final List ids, final boolean update, final boolean anyCar, final Done done) { + final AlertDialog wait = new AlertDialog.Builder(a) + .setMessage("Downloading and installing… (leave the head unit on)").setCancelable(false).show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + List c = new ArrayList(Arrays.asList("engine", update ? "update" : "catalog-install")); + c.addAll(ids); + if (anyCar) c.add("--any-car"); + return Hmgapid.call(900000, c.toArray(new String[0])); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + if (e != null) done.failed("Lost contact with HMG-API: " + e.getMessage()); + else if (r.code != 0) done.failed(MainActivity.readable(r.output)); + else done.installed(r.output); + } + }.start(a); + } + + /** "checked …" for a time the engine saved, when the unit's clock was plausible */ + static String checked(JSONObject d) { + long t = d.optLong("checked", 0); + if (t <= 0) return "Not checked yet."; + if (t < 1735689600000L) return "Checked since the head unit started."; // the clock before GPS time: 2015 + return "Checked " + new java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.US).format(new java.util.Date(t)) + "."; + } + + /** Home Wi-Fi for a while (the car in P), so a check can run now: hmgapid wifi now 15 */ + static void connect(final Activity a, final Runnable then) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + Hmgapid.Result r = Hmgapid.call("wifi", "now", "15"); + if (r.code != 0) return r; + for (int i = 0; i < 45; i++) { // up to 90 s to join + Thread.sleep(2000); + java.io.File f = new java.io.File("/data/hmgapi/public/wifi.json"); + try { + if ("up".equals(new JSONObject(UsbFolders.read(f)).optString("state"))) return r; + } catch (Exception ignored) { + // not written yet + } + } + r.code = 1; + r.output = "Home Wi-Fi didn't connect within 90 seconds. Is the car near your network, and is it saved in Settings → Home Wi-Fi?"; + return r; + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e != null || r.code != 0) { + new AlertDialog.Builder(a).setTitle("Not connected").setMessage(e != null ? e.getMessage() : r.output.trim()) + .setPositiveButton("OK", null).show(); + return; + } + then.run(); + } + }.start(a); + } +} diff --git a/core/app/java/hmgapi/app/MainActivity.java b/core/app/java/hmgapi/app/MainActivity.java index cc499f09..541d1b5e 100644 --- a/core/app/java/hmgapi/app/MainActivity.java +++ b/core/app/java/hmgapi/app/MainActivity.java @@ -239,6 +239,7 @@ void needRestart() { @Override protected void onActivityResult(int request, int result, Intent data) { + if (request == UPDATES && current == 0) show(0); // the Mods tab again: new mods, versions, the updates count if (request == UPDATES && result == RESULT_OK) plan(); // mods were installed: apply them (plan first) } diff --git a/core/app/java/hmgapi/app/ModUpdatesActivity.java b/core/app/java/hmgapi/app/ModUpdatesActivity.java new file mode 100644 index 00000000..919bfeb4 --- /dev/null +++ b/core/app/java/hmgapi/app/ModUpdatesActivity.java @@ -0,0 +1,240 @@ +package hmgapi.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.graphics.Color; +import android.os.Bundle; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.Switch; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Updates: installed mods with a newer version in the catalogue, and a newer HMG-API release + * (engine updates; HMG-API checks by itself each time home Wi-Fi comes up, "Check now" checks + * again). An update takes any new mods it requires (CatalogFlow); HMG-API's own runs its + * installer, then the head unit restarts. Mod updates are applied by the main screen. + */ +public class ModUpdatesActivity extends Activity { + private LinearLayout rows; + private TextView message, when; + private Button connect, all; + private boolean installed; + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + LinearLayout list = Ui.page(this); + Ui.text(list, "Updates", 30, true, Ui.GREEN); + Ui.text(list, "Newer versions of your mods from HMG-API's catalogue, and of HMG-API itself. HMG-API checks each time " + + "the head unit joins your home Wi-Fi (the car off at home), and never over the car's mobile data.", 16, false, Color.GRAY); + when = Ui.text(list, "", 15, false, Color.GRAY); + message = Ui.text(list, "", 18, false, Ui.WARN); + LinearLayout buttons = Ui.row(this); + Ui.button(buttons, "Check now", new View.OnClickListener() { + @Override + public void onClick(View v) { + load(true); + } + }); + connect = Ui.button(buttons, "Connect to home Wi-Fi (15 min)", new View.OnClickListener() { + @Override + public void onClick(View v) { + message.setText("Connecting to home Wi-Fi… (wireless CarPlay and Android Auto are off meanwhile)"); + CatalogFlow.connect(ModUpdatesActivity.this, new Runnable() { + @Override + public void run() { + load(true); + } + }); + } + }); + connect.setVisibility(View.GONE); + all = Ui.button(buttons, "Update all mods", true, null); + all.setVisibility(View.GONE); + list.addView(buttons); + rows = new LinearLayout(this); + rows.setOrientation(LinearLayout.VERTICAL); + list.addView(rows); + + Ui.line(list); + Ui.text(list, "Automatic", 21, true, Ui.GREEN); + Switch check = Ui.switchRow(list, "Check for updates when home Wi-Fi connects"); + Ui.allowSwitch(this, check, "no_update_check", true, null); + Switch stage = Ui.switchRow(list, "Also download mod updates then (you still apply them)"); + Ui.allowSwitch(this, stage, "auto_stage_updates", false, null); + Ui.text(list, "HMG-API itself is only ever updated when you tap its Update.", 15, false, Color.GRAY); + load(false); + } + + @Override + public void finish() { + setResult(installed ? RESULT_OK : RESULT_CANCELED); + super.finish(); + } + + private void load(final boolean refresh) { + message.setText(refresh ? "Checking for updates…" : "Loading…"); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return refresh ? Hmgapid.call(180000, "engine", "updates", "--refresh") : Hmgapid.call(60000, "engine", "updates"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + rows.removeAllViews(); + JSONObject d; + try { + if (e != null) throw e; + d = CatalogFlow.json(r.output); + } catch (Exception x) { + message.setText(e != null ? Hmgapid.unreachable(e) : "Couldn't read the updates: " + x.getMessage()); + return; + } + final boolean online = d.optBoolean("online"); + connect.setVisibility(online ? View.GONE : View.VISIBLE); + when.setText(CatalogFlow.checked(d)); + JSONArray mods = d.optJSONArray("mods"); + int n = d.optInt("count"); + if (d.has("error")) message.setText("Not checked: " + d.optString("error")); + else if (n == 0) message.setText(d.optLong("checked", 0) > 0 ? "Everything is up to date." : "Not checked yet: tap Check now" + + (online ? "." : " (home Wi-Fi isn't connected: Connect to home Wi-Fi, in P).")); + else message.setText(n + (n == 1 ? " update" : " updates") + " available" + (online ? "." : " (offline: connect to install).")); + if (d.has("hmgapi")) hmgapiRow(d.optJSONObject("hmgapi"), online); + final List ids = new ArrayList(); + for (int i = 0; mods != null && i < mods.length(); i++) { + JSONObject m = mods.optJSONObject(i); + ids.add(m.optString("id")); + row(m, online); + } + all.setVisibility(ids.size() > 1 ? View.VISIBLE : View.GONE); + all.setEnabled(online); + all.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + update(ids); + } + }); + } + }.start(this); + } + + private void row(final JSONObject m, boolean online) { + Ui.gap(rows, 14); + Ui.text(rows, m.optString("name", m.optString("id")), 22, true, Color.WHITE); + Ui.text(rows, m.optString("installed") + " → " + m.optString("version"), 16, false, Ui.GREEN); + if (m.optString("description").length() > 0) Ui.text(rows, m.optString("description"), 15, false, Color.GRAY); + JSONArray req = m.optJSONArray("requires"); + if (req != null && req.length() > 0) { + StringBuilder b = new StringBuilder(); + for (int i = 0; i < req.length(); i++) b.append(i > 0 ? ", " : "").append(req.optString(i)); + Ui.text(rows, "Needs " + b + " (installed or updated with it if needed)", 15, false, Color.GRAY); + } + Button b = Ui.button(rows, "Update", new View.OnClickListener() { + @Override + public void onClick(View v) { + update(Arrays.asList(m.optString("id"))); + } + }); + b.setEnabled(online); + } + + private void update(List ids) { + CatalogFlow.start(this, ids, true, false, new CatalogFlow.Done() { + @Override + public void installed(String output) { + installed = true; + new AlertDialog.Builder(ModUpdatesActivity.this).setTitle("Updated") + .setMessage(MainActivity.readable(output) + "\n\nGo back to apply the changes.") + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(ModUpdatesActivity.this).setTitle("Not updated").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + }); + } + + private void hmgapiRow(final JSONObject h, boolean online) { + Ui.gap(rows, 14); + Ui.text(rows, "HMG-API", 22, true, Color.WHITE); + Ui.text(rows, h.optString("installed") + " → " + h.optString("version") + (h.optBoolean("prerelease") ? " (pre-release)" : ""), + 16, false, Ui.GREEN); + Ui.text(rows, "Release notes: " + h.optString("page"), 15, false, Color.GRAY); + Button b = Ui.button(rows, "Update HMG-API", true, new View.OnClickListener() { + @Override + public void onClick(View v) { + new AlertDialog.Builder(ModUpdatesActivity.this) + .setTitle("Update HMG-API to " + h.optString("version") + "?") + .setMessage("It's downloaded over home Wi-Fi and checked against its release's checksums and HMG-API's release " + + "key. Then HMG-API's installer runs (a minute; leave the head unit on) and the head unit needs a restart. " + + "Your mods and settings stay.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Update", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int w) { + updateHmgApi(); + } + }).show(); + } + }); + b.setEnabled(online); + } + + private void updateHmgApi() { + final AlertDialog wait = new AlertDialog.Builder(this) + .setMessage("Downloading and installing HMG-API… (leave the head unit on)").setCancelable(false).show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call(900000, "engine", "update", "hmgapi"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + if (e != null) { + message.setText("Lost contact while updating (" + e.getMessage() + "). The installer finishes on its own; restart the " + + "head unit once it's done."); + return; + } + AlertDialog.Builder d = new AlertDialog.Builder(ModUpdatesActivity.this) + .setTitle(r.code == 0 ? "HMG-API updated" : "Not updated").setMessage(MainActivity.readable(r.output)); + if (r.code == 0) { + d.setNegativeButton("Later", null).setPositiveButton("Restart now", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("reboot"); + } + + @Override + void done(Hmgapid.Result rr, Exception ee) {} + }.start(ModUpdatesActivity.this); + } + }); + } else { + d.setPositiveButton("OK", null); + } + d.show(); + message.setText(r.code == 0 ? "HMG-API updated: restart the head unit." : "Not updated."); + } + }.start(this); + } +} diff --git a/core/app/java/hmgapi/app/ModsTab.java b/core/app/java/hmgapi/app/ModsTab.java index 9baaa9f2..f38aa5f8 100644 --- a/core/app/java/hmgapi/app/ModsTab.java +++ b/core/app/java/hmgapi/app/ModsTab.java @@ -26,9 +26,12 @@ final class ModsTab { LinearLayout list, detail; List mods = new ArrayList(); String chosen; + int updates; // public/updates.json's count (mods and HMG-API) static final class Mod { String id, name, version = "", description = "", authors = "", license = "", state, error; + String update; // a newer version in the catalogue (public/updates.json), or null + List requires = new ArrayList(); boolean enabled, hasCode; List services = new ArrayList(); @@ -80,6 +83,14 @@ List work() throws Exception { // hooks not running: states unknown } List out = new ArrayList(); + JSONObject up = null; + try { + up = new JSONObject(UsbFolders.read(new java.io.File("/data/hmgapi/public/updates.json"))); + } catch (Exception ignored) { + // no check yet + } + updates = up == null ? 0 : up.optInt("count"); + JSONArray ups = up == null ? null : up.optJSONArray("mods"); for (String line : Hmgapid.call("mods").output.split("\n")) { String[] w = line.split("\t"); if (w.length < 2) continue; @@ -96,6 +107,12 @@ List work() throws Exception { JSONArray au = j.optJSONArray("authors"); for (int i = 0; au != null && i < au.length(); i++) m.authors += (i > 0 ? ", " : "") + au.optString(i); m.hasCode = j.has("hooks"); + JSONArray rq = j.optJSONArray("requires"); + for (int i = 0; rq != null && i < rq.length(); i++) { + Object o = rq.get(i); + String rid = o instanceof JSONObject ? ((JSONObject) o).optString("id") : String.valueOf(o).trim().split(" ")[0]; + if (!(o instanceof JSONObject && ((JSONObject) o).optBoolean("optional"))) m.requires.add(rid); + } JSONArray sv = j.optJSONArray("services"); for (int i = 0; sv != null && i < sv.length(); i++) m.services.add(sv.getJSONObject(i).optString("name")); } catch (Exception e) { @@ -109,6 +126,10 @@ List work() throws Exception { if (m.state == null) m.state = s.optString("state"); if (m.error == null && s.has("error")) m.error = s.optString("error"); } + for (int i = 0; ups != null && i < ups.length(); i++) { + JSONObject u = ups.getJSONObject(i); + if (m.id.equals(u.optString("id")) && m.version.equals(u.optString("installed"))) m.update = u.optString("version"); + } out.add(m); } return out; @@ -123,8 +144,9 @@ void done(List r, Exception e) { } mods = r; if (r.isEmpty()) { - Ui.text(list, " No mods installed. Put mod packages in HMGAPI/updates/ on a USB stick and use Check USB updates.", - 17, false, Ui.GREY); + drawStore(); + Ui.text(list, " No mods installed. Get mods from the catalogue (over home Wi-Fi), or put mod packages in " + + "HMGAPI/updates/ on a USB stick and use Check USB updates.", 17, false, Ui.GREY); return; } if (chosen == null) chosen = r.get(0).id; @@ -134,8 +156,28 @@ void done(List r, Exception e) { }.start(a); } + /** the catalogue's two ways in, at the top of the list: Get mods, and Updates (with how many) */ + void drawStore() { + LinearLayout b = Ui.row(a); + b.setPadding(Ui.dp(a, 12), Ui.dp(a, 8), Ui.dp(a, 12), Ui.dp(a, 4)); + Ui.button(b, "Get mods", new View.OnClickListener() { + @Override + public void onClick(View v) { + a.startActivityForResult(new android.content.Intent(a, CatalogActivity.class), MainActivity.UPDATES); + } + }); + Ui.button(b, updates > 0 ? "Updates (" + updates + ")" : "Updates", updates > 0, new View.OnClickListener() { + @Override + public void onClick(View v) { + a.startActivityForResult(new android.content.Intent(a, ModUpdatesActivity.class), MainActivity.UPDATES); + } + }); + list.addView(b); + } + void drawList() { list.removeAllViews(); + drawStore(); for (final Mod m : mods) { LinearLayout row = Ui.row(a); row.setPadding(Ui.dp(a, 18), Ui.dp(a, 10), Ui.dp(a, 12), Ui.dp(a, 10)); @@ -143,7 +185,8 @@ void drawList() { row.addView(Ui.dot(a, m.color(), 18)); LinearLayout t = Ui.column(a); Ui.text(t, m.name, 19, false, Ui.TEXT).setPadding(0, 0, 0, 0); - TextView sub = Ui.text(t, m.version + " · " + m.label(), 15, false, m.color() == Ui.ACCENT || m.color() == Ui.OFF ? Ui.GREY : m.color()); + TextView sub = Ui.text(t, m.version + " · " + m.label() + (m.update != null ? " · update " + m.update : ""), 15, false, + m.color() == Ui.ACCENT || m.color() == Ui.OFF ? (m.update != null ? Ui.GREEN : Ui.GREY) : m.color()); sub.setPadding(0, 0, 0, 0); row.addView(t); row.setOnClickListener(new View.OnClickListener() { @@ -215,6 +258,28 @@ public void onClick(View v) { Ui.pill(detail, m.label(), m.color()); } if (!m.description.isEmpty()) Ui.text(detail, m.description, 16, false, Ui.GREY); + if (m.update != null) { + Ui.text(detail, "Version " + m.update + " is in the catalogue.", 17, false, Ui.GREEN); + Ui.button(detail, "Update to " + m.update, true, new View.OnClickListener() { + @Override + public void onClick(View v) { + CatalogFlow.start(a, java.util.Arrays.asList(m.id), true, false, new CatalogFlow.Done() { + @Override + public void installed(String output) { + a.message("Updated " + m.name, MainActivity.readable(output)); + load(); + a.plan(); + } + + @Override + public void failed(String output) { + a.message("Not updated", output); + } + }); + } + }); + } + if (!m.requires.isEmpty()) Ui.text(detail, "Needs " + join(m.requires.toArray(new String[0])).replace(" · ", ", "), 15, false, Ui.GREY); Ui.line(detail); Ui.text(detail, "Settings", 21, true, Ui.GREEN); @@ -281,9 +346,13 @@ static String tail(String s, int lines) { /** A mod off the head unit: its folder goes now; what it changed goes back to stock with the next apply. */ void confirmRemove(final Mod m) { + List need = new ArrayList(); + for (Mod o : mods) if (o.requires.contains(m.id)) need.add(o.name); new AlertDialog.Builder(a) .setTitle("Remove " + m.name + "?") - .setMessage("Everything it changed goes back to stock when you apply the changes. Its settings are kept " + .setMessage((need.isEmpty() ? "" : join(need.toArray(new String[0])).replace(" · ", ", ") + (need.size() == 1 ? " needs" : " need") + + " it: " + (need.size() == 1 ? "it" : "they") + " won't load until it's installed again.\n\n") + + "Everything it changed goes back to stock when you apply the changes. Its settings are kept " + "in case you install it again.") .setNegativeButton("Cancel", null) .setPositiveButton("Remove", new DialogInterface.OnClickListener() { From e65afc3c36a2ce824041f200aef9407390520c9d Mon Sep 17 00:00:00 2001 From: Nicholas Torkos Date: Fri, 27 Nov 2026 02:30:13 -0500 Subject: [PATCH 12/69] Installer: sync once the stock app_process copy is made, before the wrapper app_process.hmgapi-stock is made under a new name, and the kernel can keep a new file's data in memory for up to ~30 s; the wrapper then goes over app_process (or .real), and a rename over an existing file reaches storage at once. A hard reset (Reset pinhole, power loss) before the install's final sync could leave the wrapper running an empty stock copy: no zygote, and no stock app_process left. Now sync runs as soon as the stock copy is made. The uninstall was already safe: stock goes back over the existing files, then sync. install-test.sh: a sync stand-in records what was on /system when it ran; the first sync of a fresh install must see the stock copy in place and app_process still stock. It fails without this change. 263 checks pass under dash and mksh; test.sh, check-scripts and orders-test pass. Off-car only. --- CHANGELOG.md | 12 ++++++++++++ install/common/install-test.sh | 4 ++++ install/common/install.sh | 6 ++++++ 3 files changed, 22 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..7abe1b1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## Unreleased + +- **The stock copy is on storage before the wrapper goes in.** The installer makes + `app_process.hmgapi-stock` under a new name, and the kernel can keep a new file's data in + memory for up to ~30 s; the wrapper then goes over `app_process` (or `.real`), which reaches + storage at once. A hard reset (Reset pinhole, power loss) in the seconds before the + install's final `sync` could leave the wrapper running an empty stock copy: no zygote, and + no stock `app_process` left on `/system`. The install now runs `sync` as soon as the stock + copy is made. The uninstall was already safe (stock goes back over existing files, then + `sync`). The same gap in NEMESIS 1.17's `app_process.real` was reported to NEMESIS. + Tested off-car only. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/install/common/install-test.sh b/install/common/install-test.sh index dd8aa7da..0786ddd8 100644 --- a/install/common/install-test.sh +++ b/install/common/install-test.sh @@ -24,6 +24,8 @@ printf '#!/bin/sh\necho "setprop $*" >> "%s/calls.log"\n' "$T" > $T/bin/setprop # INSTALL_FAILED_INVALID_URI, as on the car (#187) printf '#!/bin/sh\necho "pm $*" >> "%s/calls.log"\ncase "$1" in path) [ -n "$FAKE_HAVE_APP" ] && echo package:/data/app/hmgapi.app-1.apk ;; install) case "$(ls -l "$3" | cut -c8)" in r) echo "${FAKE_PM:-Success}" ;; *) echo "Failure [INSTALL_FAILED_INVALID_URI]" ;; esac ;; esac\nexit 0\n' "$T" > $T/bin/pm printf '#!/bin/sh\necho "am $*" >> "%s/calls.log"\n' "$T" > $T/bin/am +# sync: what was on /system when it ran (the stock copy, and whether a wrapper was in yet) +printf '#!/bin/sh\nk=$(md5sum < "%s/system/bin/app_process.hmgapi-stock" 2>/dev/null | cut -c1-32)\na=$(md5sum < "%s/system/bin/app_process" | cut -c1-32)\necho "keep=${k:-none} app_process=$a" >> "%s/sync.log"\n' "$R" "$R" "$T" > $T/bin/sync chmod +x $T/bin/* calls() { cat $T/calls.log 2>/dev/null || true; : > $T/calls.log; } run() { set +e; out=$(cd $T && env PATH="$T/bin:$PATH" ROOT=$R CAPCHECK=0 $SH "$@" 2>&1); rc=$?; set -e; } @@ -84,8 +86,10 @@ has "... before anything changed" "Nothing was changed." "$out" mv $T/maps.away $P/maps check "still stock after refusals" "$BEFORE" "$(tree)" +rm -f $T/sync.log run $P/install.sh $P has "install finishes" "installed. Restart the head unit" "$out" +check "the stock copy reaches storage (sync) before the wrapper is written" "keep=$(md5sum < $T/real | cut -c1-32) app_process=$(md5sum < $T/real | cut -c1-32)" "$(sed -n 1p $T/sync.log)" check "app_process is the wrapper" "$(md5sum < $P/app_process)" "$(md5sum < $R/system/bin/app_process)" check "stock app_process kept beside it" "$(md5sum < $T/real)" "$(md5sum < $R/system/bin/app_process.hmgapi-stock)" check "stock app_process backed up" "$(md5sum < $T/real)" "$(md5sum < $R/data/hmgapi/stock/system/bin/app_process)" diff --git a/install/common/install.sh b/install/common/install.sh index bc889914..951ded0b 100644 --- a/install/common/install.sh +++ b/install/common/install.sh @@ -275,6 +275,12 @@ elif [ -n "$RESCUE" ]; then mv "$KEEP.hmgapi-new" "$KEEP" || fail "keep stock app_process" log "app_process.hmgapi-stock: back from the stock backup ($RBAK)" fi +# on storage before anything runs it: a new file's data can stay in memory for up to ~30 s +# (the kernel's writeback; a rename onto a new name doesn't force it out, a rename over an +# existing file does). The wrapper below goes over app_process (or .real) and so reaches +# storage at once; a hard reset (Reset pinhole, power loss) before this sync could then leave +# the wrapper running an empty stock copy: no zygote, and no stock app_process left on /system +sync # the last word before the wrapper goes in: it runs app_process.hmgapi-stock, which must be a # stock binary, or no zygote starts [ -f "$KEEP" ] && ! not_stock "$KEEP" || fail "app_process.hmgapi-stock isn't a stock binary, so the wrapper wasn't written (HMG-API's other files are, harmless without it). Please send this line to the HMG-API maintainers." From a4258bc9b74e948c51f6baf99663ad8dc8ba93c5 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:09:17 -0500 Subject: [PATCH 13/69] Home Wi-Fi: a checksum that can't be written is said; join writes once crc_fix no longer hides WifiAp's output and status: a failure is said in the keeper's log and in join's and forget's answer. WifiAp.crc checks chown and chmod, names the one that failed, and leaves the old checksum file as it was. join builds the whole config text (from the existing file, the car's template, or the two default lines) before put_net, instead of first writing the template to wpa_supplicant.conf as root. Tested off-car only (homewifi-test.sh, bash; no mksh here). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++- core/runtime/homewifi-test.sh | 27 ++++++++++++-- core/runtime/java/hmgapi/engine/HomeWifi.java | 19 ++++++---- core/runtime/java/hmgapi/engine/WifiAp.java | 35 ++++++++++++++++--- .../test/hmgapi/engine/WifiApTest.java | 15 ++++++++ 5 files changed, 86 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f62794b..8f9219fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,10 @@ never started ("Wi-Fi will not be enabled") and home Wi-Fi stayed "searching". Adding or forgetting a network now updates it, and it's checked before each switch to home Wi-Fi. A first network no longer needs `printf` (not on the unit): the config starts from the car's - own template. + own template, and the whole text is built before the one write that sets Android's owner and + mode. A checksum that can't be written (its `chown` or `chmod` failing) is said in the + keeper's log and in the answer to adding or forgetting a network, instead of home Wi-Fi only + staying "searching". ## 1.1.0-rc.10 (2026-11-25) diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index e36e521d..193a545c 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -12,7 +12,11 @@ UNIT_SH=${UNIT_SH:-$(command -v mksh || command -v bash)} CP=$(mktemp -d) sh tools/engine-classes.sh "$CP" javac --release 8 -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/WifiApTest.java -java -cp "$CP" hmgapi.engine.WifiApTest +# WifiAp.crc's chown system:wifi: a stand-in that fails only for a "chownfail" path (the test's failure case) +CB=$(mktemp -d) +printf '#!/bin/sh\ncase "$*" in *chownfail*) echo "chown: not permitted" >&2; exit 1 ;; esac\nexit 0\n' > "$CB/chown"; chmod +x "$CB/chown" +PATH=$CB:$PATH java -cp "$CP" hmgapi.engine.WifiApTest +rm -rf "$CB" T=$(mktemp -d) cleanup() { r=$?; [ $r != 0 ] && [ -z "$done" ] && echo "FAIL stopped (exit $r) after: ${last:-the start}"; [ -f "$T/fake/fw/wpa.sleep" ] && kill "$(cat "$T/fake/fw/wpa.sleep")" 2>/dev/null || true; rm -rf "$T" "$CP"; } trap cleanup EXIT @@ -209,7 +213,9 @@ case "$3 $4" in fi ;; "client on") : > "$FW/client"; echo running > "$FW/props/init.svc.wpa_supplicant"; echo "client on" ;; "client off") rm -f "$FW/client"; echo stopped > "$FW/props/init.svc.wpa_supplicant"; echo "client off" ;; - "crc "*) echo crc >> "$FW/crc.log"; echo 01234567 ;; + "crc "*) echo crc >> "$FW/crc.log" + [ -f "$FW/crc.fail" ] && { echo "checksum not written: chown system:wifi: exit 1"; exit 1; } + echo 01234567 ;; esac S printf '#!/bin/sh\n:\n' > "$F/bin/chown" @@ -271,18 +277,33 @@ check "forget" "forgotten: Cafe" "$(verb forget Cafe)" check "... gone, the others kept" "Cascadia Willows" "$(verb saved | sort)" check "seen: nothing before home Wi-Fi was on" "" "$(verb seen)" +: > "$F/fw/crc.fail" +out=$(HMGAPI_WIFI_PSK= verb join Cafe) +has "join: a checksum that can't be written is said" "the car's Wi-Fi checksum not updated, so its Wi-Fi client may not start: checksum not written: chown" "$out" +has "... the network still saved" "saved: Cafe" "$out" +verb forget Cafe >/dev/null; rm "$F/fw/crc.fail" mv "$NET" "$NET.keep"; mkdir -p "$X/system/etc/wifi"; printf 'update_config=1\nctrl_interface=wlan0\npmf=1\n' > "$X/system/etc/wifi/wpa_supplicant.conf" -HMGAPI_WIFI_PSK=first-net-key verb join First >/dev/null +# put_net's chown says whether a config was already there: join writes nothing of its own before put_net +printf '#!/bin/sh\n[ -n "$NETCHK" ] && { [ -e "$NETCHK" ] && echo there || echo none; } >> "$FW/net.before"\nexit 0\n' > "$F/bin/chown" +: > "$F/fw/net.before" +NETCHK=$NET HMGAPI_WIFI_PSK=first-net-key verb join First >/dev/null +check "join with no config yet: no config of ours before put_net" none "$(cat "$F/fw/net.before")" +printf '#!/bin/sh\n:\n' > "$F/bin/chown" has "join with no config yet: started from the car's template" "pmf=1" "$(cat "$NET")" has "... with the network" 'ssid="First"' "$(cat "$NET")" +check "... the template's lines first, as the car's library writes them" "update_config=1" "$(sed -n 1p "$NET")" +check "... Android's mode" "-rw-rw----" "$(ls -l "$NET" | cut -c1-10)" mv "$NET.keep" "$NET" # parked: the hotspot off, the car's client on echo "wpa_state=SCANNING" > "$F/fw/wpa.status" : > "$F/fw/apps.log" +: > "$F/fw/crc.fail" log=$(wk) +rm "$F/fw/crc.fail" has "parked: switched at once" "the car off: the hotspot off, the car's Wi-Fi client on" "$log" has "... the checksum checked before the client goes on" crc "$(cat "$F/fw/crc.log")" +has "... a checksum that can't be written: in the keeper's log, not just \"searching\"" "the car's Wi-Fi checksum not updated" "$log" check "... the hotspot off" no "$([ -f "$F/fw/ap" ] && echo yes || echo no)" has "... through Android's Wi-Fi service" "hmgapi.engine.WifiAp client on" "$(cat "$F/fw/apps.log")" check "... looking" searching "$(state)" diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index adbe2282..04602127 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -209,8 +209,14 @@ static List describe(Engine e, Map> json, Se "reading() { hmgapid vehicle \"$1\" 2>/dev/null | while read -r k v; do [ \"$k\" = \"$1\" ] && echo \"$v\"; done; }", "tool() { CLASSPATH=$JAR app_process /system/bin hmgapi.engine.WifiAp \"$@\" 2>&1; }", "# the car's Wi-Fi library starts the client only if wpa_supplicant_crc32.conf holds the networks", - "# file's CRC-32 (WifiAp.crc): after every edit here, and before switching the client on", - "crc_fix() { [ -f $NET ] && tool crc $NET >/dev/null; }", + "# file's CRC-32 (WifiAp.crc): after every edit here, and before switching the client on. A failure", + "# is said (the keeper's log; join's and forget's answer): otherwise home Wi-Fi only stays \"searching\"", + "crc_fix() {", + " [ -f $NET ] || return 0", + " r=$(tool crc $NET) && return 0", + " say \"the car's Wi-Fi checksum not updated, so its Wi-Fi client may not start: $r\"", + " return 1", + "}", "TEMPLATE=$X/system/etc/wifi/wpa_supplicant.conf # what the car's library starts a new config from", "boot() { cat $X/proc/sys/kernel/random/boot_id 2>/dev/null; }", "wants() { [ -f $ASKS ] && while read -r w rest; do [ \"$w\" = \"$1\" ] && { echo \"${rest:-$w}\"; }; done < $ASKS; }", @@ -254,10 +260,11 @@ static List describe(Engine e, Map> json, Se " safe \"$k\" || { echo \"that key can't be used (quotes, backslashes)\"; return 2; }", " if [ -n \"$k\" ] && [ ${#k} -lt 8 -o ${#k} -gt 63 ]; then echo \"a Wi-Fi key is 8 to 63 characters\"; return 2; fi", " client_mode && { echo \"home Wi-Fi is on right now (parked): add networks while the car is on\"; return 1; }", - " if [ ! -f $NET ]; then # no printf on the unit; the car's own template, as its library does", - " if [ -f $TEMPLATE ]; then cat $TEMPLATE > $NET; else { echo ctrl_interface=wlan0; echo update_config=1; } > $NET; fi", - " fi", - " c=$(without \"$s\")", + " # the text first, then one put_net: with no config yet, the car's own template (as its library", + " # does; no printf on the unit), never a file of ours written before put_net sets its owner", + " if [ -f $NET ]; then c=$(without \"$s\")", + " elif [ -f $TEMPLATE ]; then c=$(cat $TEMPLATE)", + " else c=\"ctrl_interface=wlan0${nl}update_config=1\"; fi", " c=\"$c${nl}network={$nl\tssid=\\\"$s\\\"$nl\"", " if [ -n \"$k\" ]; then c=\"$c\tpsk=\\\"$k\\\"$nl\tkey_mgmt=WPA-PSK$nl\"; else c=\"$c\tkey_mgmt=NONE$nl\"; fi", " c=\"$c\tpriority=1$nl}$nl\"", diff --git a/core/runtime/java/hmgapi/engine/WifiAp.java b/core/runtime/java/hmgapi/engine/WifiAp.java index 3e4912ab..d87d7374 100644 --- a/core/runtime/java/hmgapi/engine/WifiAp.java +++ b/core/runtime/java/hmgapi/engine/WifiAp.java @@ -91,7 +91,8 @@ private static boolean clientSavedOn(Class type, Object wifi) throws Reflecti * wpa_supplicant_crc32.conf next to the networks file: the file's CRC-32, 8 upper-case hex * digits, no newline. If it doesn't match (any edit not made through Android's Wi-Fi settings), * the library logs "Wi-Fi will not be enabled" and the client never starts. Written only when - * it differs, owned as the library makes it (system:wifi 660). Prints the checksum. + * it differs, owned as the library makes it (system:wifi 660); a chown or chmod that fails is an + * error and leaves the old file as it was. Prints the checksum. */ static int crc(java.io.File conf) throws Exception { if (!conf.isFile()) { @@ -111,21 +112,45 @@ static int crc(java.io.File conf) throws Exception { } finally { o.close(); } - Engine.child(new ProcessBuilder("chown", "system:wifi", t.getPath())).start().waitFor(); - Engine.child(new ProcessBuilder("chmod", "660", t.getPath())).start().waitFor(); - if (!t.renameTo(f)) throw new java.io.IOException("can't write " + f); + try { + run("chown", "system:wifi", t.getPath()); + run("chmod", "660", t.getPath()); + if (!t.renameTo(f)) throw new java.io.IOException("can't write " + f); + } finally { + t.delete(); // gone already once renamed + } } System.out.println(want); return 0; } + /** a tool the checksum file needs (chown, chmod): its failure, with what it said, is an IOException */ + private static void run(String... cmd) throws Exception { + Process p = Engine.child(new ProcessBuilder(cmd).redirectErrorStream(true)).start(); + String said = new String(Engine.readAll(p.getInputStream()), "UTF-8").trim(); + int rc = p.waitFor(); + if (rc == 0) return; + StringBuilder b = new StringBuilder(); + for (String c : cmd) b.append(b.length() == 0 ? "" : " ").append(c); + throw new java.io.IOException(b + ": exit " + rc + (said.length() == 0 ? "" : " (" + said + ")")); + } + /** * restart: off and on again, the same mode. stop: off, printing the mode it had ("2" the projection * AP, "1" the plain hotspot, "0" it wasn't on). start : on again in that mode. */ public static void main(String[] args) throws Exception { String v = args.length > 0 ? args[0] : ""; - if ("crc".equals(v) && args.length == 2) System.exit(crc(new java.io.File(args[1]))); + if ("crc".equals(v) && args.length == 2) { + int rc; + try { + rc = crc(new java.io.File(args[1])); + } catch (Exception x) { // one line for the keeper's log, not a stack trace + System.out.println("checksum not written: " + x.getMessage()); + rc = 1; + } + System.exit(rc); + } boolean client = "client".equals(v) && args.length == 2 && ("on".equals(args[1]) || "off".equals(args[1])); boolean ensure = "ensure-projection".equals(v) && args.length == 1; if (!(("restart".equals(v) || "stop".equals(v)) && args.length == 1) && !("start".equals(v) && args.length == 2) && !client && !ensure) { diff --git a/core/runtime/test/hmgapi/engine/WifiApTest.java b/core/runtime/test/hmgapi/engine/WifiApTest.java index 8890a797..9b0c7cdb 100644 --- a/core/runtime/test/hmgapi/engine/WifiApTest.java +++ b/core/runtime/test/hmgapi/engine/WifiApTest.java @@ -98,10 +98,25 @@ private static void crcChecks() throws Exception { WifiAp.crc(conf); if ("54931C7F".equals(Engine.read(crc)) || Engine.read(crc).length() != 8) throw new AssertionError("crc: not updated after an edit"); if (WifiAp.crc(new java.io.File(d, "none")) == 0) throw new AssertionError("crc: no networks file is not ok"); + // homewifi-test.sh's chown fails for a path with "chownfail" in it + java.io.File bad = new java.io.File(d, "chownfail"); + bad.mkdir(); + java.io.File badConf = new java.io.File(bad, "wpa_supplicant.conf"); + java.nio.file.Files.write(badConf.toPath(), template.getBytes("US-ASCII")); + boolean threw = false; + try { + WifiAp.crc(badConf); + } catch (java.io.IOException x) { + threw = x.getMessage().contains("chown"); + } + if (!threw) throw new AssertionError("crc: a chown that fails is an error that names it"); + String[] left = bad.list(); + if (left.length != 1) throw new AssertionError("crc: after a failure only the networks file, got " + java.util.Arrays.toString(left)); } finally { System.setOut(was); } System.out.println("ok WifiAp crc: the car's checksum, 8 upper-case digits, written only when it changed"); + System.out.println("ok WifiAp crc: a chown that fails is said, nothing left behind"); } public static void main(String[] args) throws Exception { From 76376c78d39f8c7c87ba520ae12d2f912c86e346 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:12:38 -0500 Subject: [PATCH 14/69] Catalogue: projection-tbt 1.0.0 and wireless-carplay-aa 3.0.0, prepared Both entries are made from the mods' mod.json files ahead of their releases, with a zero SHA-256, so the catalogue's download check refuses them until they're regenerated with tools/catalog.py add from the published zips. Both in one pull request on purpose: a Wireless 3.0.0 bump alone would merge itself before projection-tbt is listed. projection-tbt is signed with VysseCodes' author key, the Wireless mod's, so maps/authors.json only gets its repository (Open-HMG/hmgapi-projection-tbt, after the move). Co-Authored-By: Claude Opus 5.5 --- catalog/projection-tbt.json | 323 ++++++++++++++++++++++++++++ catalog/wireless-carplay-aa.json | 347 ++++++++++++++++++++++++++++++- maps/authors.json | 3 +- 3 files changed, 666 insertions(+), 7 deletions(-) create mode 100644 catalog/projection-tbt.json diff --git a/catalog/projection-tbt.json b/catalog/projection-tbt.json new file mode 100644 index 00000000..2f53e797 --- /dev/null +++ b/catalog/projection-tbt.json @@ -0,0 +1,323 @@ +{ + "id": "projection-tbt", + "name": "Phone Turn-by-Turn (CarPlay + Android Auto)", + "description": "Android Auto's and CarPlay's turn-by-turn directions on the cluster and HUD, wired or wireless. Until Wireless CarPlay + Android Auto 3.0 this was part of that mod: update Wireless to 3.0 first, then install this one.", + "authors": [ + "VysseCodes", + "AwsomeFox", + "Open-HMG contributors" + ], + "license": "AGPL-3.0", + "uuid": "7251ce71-a146-8a1e-958b-dbffc6af7359", + "version": "1.0.0", + "repo": "https://github.com/Open-HMG/hmgapi-projection-tbt", + "download": "https://github.com/Open-HMG/hmgapi-projection-tbt/releases/download/v1.0.0/projection-tbt-1.0.0.zip", + "sha256": "0000000000000000000000000000000000000000000000000000000000000000", + "hmgapi": ">=1.1.0", + "system": [ + { + "model": [ + "CVEV", + "NEEV", + "NEEV23", + "NEEV23SE", + "CEEV", + "NQ5HEV" + ], + "region": "USA", + "firmware": "260507" + }, + { + "model": [ + "NEEV", + "NEEV23", + "NEEV23SE" + ], + "region": "USA", + "firmware": "260903" + }, + { + "model": "NEEV", + "region": "CAN", + "firmware": "260903" + }, + { + "model": [ + "CVEV", + "NEEV" + ], + "region": "CAN", + "firmware": "260206" + }, + { + "model": "CEEV", + "region": "CAN", + "firmware": "260206" + }, + { + "model": "CEEV", + "region": "USA", + "firmware": "260903" + }, + { + "model": "CEEV", + "region": "CAN", + "firmware": "260903" + }, + { + "model": "CN7NPE", + "region": "USA", + "firmware": "260903" + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "USA", + "firmware": "260507" + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "CAN", + "firmware": "260206" + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "USA", + "firmware": "260903" + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "CAN", + "firmware": "260903" + }, + { + "model": [ + "CKPE", + "CKPE23", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEPEHEV", + "DEPEPHEV", + "DL3", + "DL322", + "MQ4", + "MQ422", + "MQ422HEV", + "MQ4HEV", + "MQ4PHEV", + "ON", + "ON22", + "SK3", + "SK322", + "SK3EV", + "SK3EV22", + "SP2", + "SP222", + "YGPE" + ], + "region": "USA", + "firmware": "260507" + }, + { + "model": [ + "CKPE", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEPEHEV", + "DEPEPHEV", + "DL322", + "DL3", + "MQ422", + "MQ422HEV", + "MQ4", + "MQ4HEV", + "MQ4PHEV", + "ON22", + "ON", + "SK322", + "SK3", + "SK3EV22", + "SK3EV", + "SP222", + "SP2", + "YGPE" + ], + "region": "CAN", + "firmware": "260206" + }, + { + "model": [ + "CKPE", + "CKPE22", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEEVPBV", + "DEPEHEV", + "DEPEPHEV", + "DL3", + "DL322", + "DL3HEV", + "DL3HEV22", + "HMPE2", + "JAPE", + "JAPE22", + "MQ4", + "MQ422", + "MQ422HEV", + "MQ4HEV", + "ON", + "SK3", + "SK321", + "SK3EV", + "SK3EV21", + "SK3EV22", + "SP2", + "SP221", + "SP222", + "TAM", + "TAM22", + "YGPE", + "YGPEHEV" + ], + "region": "KOR", + "firmware": "260902" + }, + { + "model": "CEEV", + "region": "USA", + "firmware": "260206" + }, + { + "model": "CN7PE", + "region": "USA", + "firmware": "260507" + }, + { + "model": [ + "BDPE", + "KA4", + "NQ5", + "NQ5HEV", + "NQ5PHEV", + "ONPE", + "SG2EV", + "SG2HEV", + "SG2PHEV", + "SK3EPE", + "SK3PE", + "SP2PE" + ], + "region": "CAN", + "firmware": "260206" + } + ] +} diff --git a/catalog/wireless-carplay-aa.json b/catalog/wireless-carplay-aa.json index 45e6d6b8..71bee251 100644 --- a/catalog/wireless-carplay-aa.json +++ b/catalog/wireless-carplay-aa.json @@ -1,23 +1,26 @@ { "id": "wireless-carplay-aa", "name": "Wireless CarPlay + Android Auto", - "description": "Wireless CarPlay and Android Auto on the head unit's hotspot, with turn-by-turn on the cluster and HUD.", + "description": "Wireless CarPlay and Android Auto on the head unit's hotspot. From 3.0, turn-by-turn on the cluster and HUD is its own mod, Phone Turn-by-Turn (projection-tbt): update this one first, then install that one to keep it.", "authors": [ "VysseCodes" ], "license": "AGPL-3.0", "uuid": "7251ce71-a146-8a1e-958b-dbffc6af7359", - "version": "2.1.0", + "version": "3.0.0", "repo": "https://github.com/Open-HMG/hmgapi-wireless-cp-aa", - "download": "https://github.com/Open-HMG/HMG-API/releases/download/v1.0.2/wireless-carplay-aa-2.1.0.zip", - "sha256": "07c0baee50362bb3b5ac7aafa6a46c39938479497ec28531c6f74ee3a2698446", - "hmgapi": ">=1.0.0", + "download": "https://github.com/Open-HMG/hmgapi-wireless-cp-aa/releases/download/v3.0.0/wireless-carplay-aa-3.0.0.zip", + "sha256": "0000000000000000000000000000000000000000000000000000000000000000", + "hmgapi": ">=1.1.0", "system": [ { "model": [ "CVEV", "NEEV", - "NEEV23" + "NEEV23", + "NEEV23SE", + "CEEV", + "NQ5HEV" ], "region": "USA", "firmware": "260507", @@ -25,6 +28,26 @@ "hmgapi.wifi" ] }, + { + "model": [ + "NEEV", + "NEEV23", + "NEEV23SE" + ], + "region": "USA", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "NEEV", + "region": "CAN", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, { "model": [ "CVEV", @@ -35,6 +58,318 @@ "features": [ "hmgapi.wifi" ] + }, + { + "model": "CEEV", + "region": "CAN", + "firmware": "260206", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "CEEV", + "region": "USA", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "CEEV", + "region": "CAN", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "CN7NPE", + "region": "USA", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "USA", + "firmware": "260507", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "CAN", + "firmware": "260206", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "USA", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "AEPEEV", + "AEPEHEV", + "AEPEPHEV", + "CN7", + "CN723", + "CN7HEV", + "CN7HEV23", + "DN8", + "DN822", + "DN822HEV", + "DN823", + "DN823HEV", + "DN8HEV", + "JSN", + "LX2", + "OSEV", + "OSPE", + "OSPE23", + "QX21", + "TM23", + "TMFL", + "TMHEV", + "TMHEV23", + "TMPHEV", + "TMPHEV23" + ], + "region": "CAN", + "firmware": "260903", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "CKPE", + "CKPE23", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEPEHEV", + "DEPEPHEV", + "DL3", + "DL322", + "MQ4", + "MQ422", + "MQ422HEV", + "MQ4HEV", + "MQ4PHEV", + "ON", + "ON22", + "SK3", + "SK322", + "SK3EV", + "SK3EV22", + "SP2", + "SP222", + "YGPE" + ], + "region": "USA", + "firmware": "260507", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "CKPE", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEPEHEV", + "DEPEPHEV", + "DL322", + "DL3", + "MQ422", + "MQ422HEV", + "MQ4", + "MQ4HEV", + "MQ4PHEV", + "ON22", + "ON", + "SK322", + "SK3", + "SK3EV22", + "SK3EV", + "SP222", + "SP2", + "YGPE" + ], + "region": "CAN", + "firmware": "260206", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "CKPE", + "CKPE22", + "DE20EV", + "DE22EV", + "DE22HEV", + "DE22PHEV", + "DEEVPBV", + "DEPEHEV", + "DEPEPHEV", + "DL3", + "DL322", + "DL3HEV", + "DL3HEV22", + "HMPE2", + "JAPE", + "JAPE22", + "MQ4", + "MQ422", + "MQ422HEV", + "MQ4HEV", + "ON", + "SK3", + "SK321", + "SK3EV", + "SK3EV21", + "SK3EV22", + "SP2", + "SP221", + "SP222", + "TAM", + "TAM22", + "YGPE", + "YGPEHEV" + ], + "region": "KOR", + "firmware": "260902", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "CEEV", + "region": "USA", + "firmware": "260206", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": "CN7PE", + "region": "USA", + "firmware": "260507", + "features": [ + "hmgapi.wifi" + ] + }, + { + "model": [ + "BDPE", + "KA4", + "NQ5", + "NQ5HEV", + "NQ5PHEV", + "ONPE", + "SG2EV", + "SG2HEV", + "SG2PHEV", + "SK3EPE", + "SK3PE", + "SP2PE" + ], + "region": "CAN", + "firmware": "260206", + "features": [ + "hmgapi.wifi" + ] } ] } diff --git a/maps/authors.json b/maps/authors.json index d0deef38..8e552557 100644 --- a/maps/authors.json +++ b/maps/authors.json @@ -3,10 +3,11 @@ "authors": { "7251ce71-a146-8a1e-958b-dbffc6af7359": { "name": "VysseCodes", - "projects": "HMG-API, its example mods, wireless CarPlay + Android Auto, ADB, adbd, NEMESIS in the app menu", + "projects": "HMG-API, its example mods, wireless CarPlay + Android Auto, phone turn-by-turn, ADB, adbd, NEMESIS in the app menu", "repos": [ "https://github.com/Open-HMG/HMG-API", "https://github.com/Open-HMG/hmgapi-wireless-cp-aa", + "https://github.com/Open-HMG/hmgapi-projection-tbt", "https://github.com/Open-HMG/hmgapi-adb", "https://github.com/Open-HMG/hmgapi-adbd", "https://github.com/Open-HMG/hmgapi-nemesis-shortcut" From fb6a1bf757ba182c206146a1cc05b14bf17aa532 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:12:38 -0500 Subject: [PATCH 15/69] Wiki and release checklist for turn-by-turn as its own mod Home lists phone turn-by-turn on its own; the NEMESIS packages table gets Phone Turn-by-Turn's conflicts and Wireless's enhanced.projection. docs/wireless-3-split.md is the order across egmp-aa-ev, Wireless, the turn-by-turn repository and HMG-API, and what owners are told where. Co-Authored-By: Claude Opus 5.5 --- docs/wireless-3-split.md | 140 +++++++++++++++++++++++++++++++++++++ wiki/Home.md | 6 +- wiki/Installing-HMG-API.md | 3 +- 3 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 docs/wireless-3-split.md diff --git a/docs/wireless-3-split.md b/docs/wireless-3-split.md new file mode 100644 index 00000000..8122ae7e --- /dev/null +++ b/docs/wireless-3-split.md @@ -0,0 +1,140 @@ +# Wireless 3.0 and Phone Turn-by-Turn: release checklist + +Turn-by-turn leaves the Wireless mod (`wireless-carplay-aa` 3.0) and becomes its own mod, +Phone Turn-by-Turn (`projection-tbt`). This page is the order the releases go out in, across +three repositories, and what owners are told. Rules are [releasing.md](releasing.md) and +[mod-repos.md](mod-repos.md). + +| Repository | What | Pull request | +|---|---|---| +| `AwsomeFox/egmp-aa-ev-hmg-api` | `egmp-aa-ev` asks for Wireless below 3.0 | (separate task) | +| `Open-HMG/hmgapi-wireless-cp-aa` | Wireless 3.0.0-beta.1 without turn-by-turn | #124, and the upgrade notes on top of it | +| `AwsomeFox/hmg-api-turn-by-turn` (moving to `Open-HMG/hmgapi-projection-tbt`) | release workflow, author key, upgrade notes | `ci/release-workflow` | +| `Open-HMG/HMG-API` | catalogue entries, `maps/authors.json`, wiki, then `tools/release-mods.txt` | this branch (`catalog/projection-tbt`) | + +## Why the order matters + +- `projection-tbt` declares `conflicts` with `wireless-carplay-aa <3.0.0-beta.1`: Wireless 2.x + still has the same turn-by-turn hooks. With both installed, HMG-API loads the first by id, + and `projection-tbt` sorts first: **installing it next to Wireless 2.x turns Wireless off**. + So the two ship together, and owners update Wireless first. +- The catalogue lists finals only (`catalog.py add` refuses a pre-release), and a HMG-API + pre-release can bundle a mod's pre-release only when the mod already has a catalogue entry + (`release-mods.txt` pins). `projection-tbt` has none until its 1.0.0. A HMG-API pre-release + that bundled Wireless 3.0-beta would leave owners without turn-by-turn and no way to get it + from that download. So **no HMG-API release bundles Wireless 3.x until `projection-tbt` 1.0.0 + is in the catalogue**; `release-mods.txt` stays on Wireless 2.2.x until then. +- A catalogue PR that only bumps one entry merges itself (`catalog-automerge.yml`). A Wireless + 3.0.0 bump on its own would go live before `projection-tbt` is listed, so **both entries go + in one PR** (two files: not a bump, so a maintainer merges it). + +## Decided here + +- **Author key: VysseCodes' (`7251ce71-…`), the Wireless mod's.** The key is per author, not + per mod; it's already on every HMG-API release's trusted list (a new key would show the + unknown-author warning until a HMG-API release carries it, and forever on units that don't + update); and it can never change once a release is out, so a personal key would tie every + future update to whoever holds it. The cost is a fifth `release` environment with `MOD_KEY`. + A repository's admins can read its environment secrets through a workflow, so the key only + goes in a repository VysseCodes controls: **the turn-by-turn repository moves to Open-HMG + before its first tag.** +- **Its address after the move: `https://github.com/Open-HMG/hmgapi-projection-tbt`** (the + `hmgapi-` convention). That's the address in `maps/authors.json` and the prepared entry + here; the release workflow refuses a tag unless `mod.json`'s `repo` is the repository it + runs in. If the name is different, change it in both. + +## Checklist + +### 0. Before any tag + +- [ ] Transfer `AwsomeFox/hmg-api-turn-by-turn` to Open-HMG as `hmgapi-projection-tbt` + (GitHub redirects the old links). +- [ ] In that repository: `projection-tbt/mod.json` `"repo"` set to the new address; README, + NOTICE and `docs/` links; `.github/CODEOWNERS` (its `@Open-HMG/maintainers` team only + works inside Open-HMG). +- [ ] VysseCodes: a `release` environment (deployment tags `v*` only, as in the Wireless repo) + with `MOD_KEY`, the same secret as the Wireless repo's. +- [ ] Tag ruleset as the other mod repos ("Protect release tags"). +- [ ] Merge `ci/release-workflow` (release workflow, `.github/mod-key.pub`, upgrade notes). +- [ ] Wireless repo: the README's links to the turn-by-turn repository point at the new address. + +### 1. `egmp-aa-ev` first (separate task) + +- [ ] `hmgapi-mod/mod.json`: `"requires": ["wireless-carplay-aa >=2.1.0 <3.0.0"]`, released + and published **before Wireless 3.0.0-beta.1 is published**, so an owner updating + Wireless is told `egmp-aa-ev` doesn't work with it, instead of finding out on the road. +- [ ] Its README: stay on Wireless 2.x until an `egmp-aa-ev` release supports 3.0. + +### 2. The betas, together + +- [ ] Wireless: merge #124 and the upgrade-notes PR on top of it; release PR with + `.github/release-notes/v3.0.0-beta.1.md`; tag `v3.0.0-beta.1`. +- [ ] Turn-by-turn: release PR (`1.0.0-beta.1` is already `mod.json`'s version) with + `.github/release-notes/v1.0.0-beta.1.md` (fill in "What's new" from `git log`); tag + `v1.0.0-beta.1`. +- [ ] Check both drafts off-car (every file in `SHA256SUMS`, versions, signature by + `7251ce71-…`). +- [ ] Publish both at the same time, Wireless first. Their notes link each other and say + "update Wireless first". +- [ ] `tools/release-mods.txt` here: **unchanged** (Wireless 2.2.x). + +### 3. On cars before the finals + +- [ ] Update from Wireless 2.2.x: Wireless 3.0 first, then `projection-tbt`; CarPlay and + Android Auto connect, turns on the cluster and HUD. +- [ ] Wrong order on purpose: `projection-tbt` next to 2.2.x shows the conflict and Wireless + comes back once it's 3.0. +- [ ] `projection-tbt` alone, wired phone. Wireless 3.0 alone: the car's navigation keeps the cluster. +- [ ] CarPlay after the Bluetooth-to-Wi-Fi handover: route guidance keeps coming (the two mods' + agreement, Wireless `docs/tbt-contract.md`). +- [ ] The HMG-API app installing both from one stick: which goes first, and what the owner + sees in between (not checked yet). + +### 4. The finals + +- [ ] Wireless `3.0.0` and `projection-tbt` `1.0.0`: `"hmgapi"` floor a final (`">=1.1.0"`; + `check-points.py` refuses a pre-release floor), release notes, tags, drafts checked on a + car, both published together. + +### 5. Catalogue (this branch) + +- [ ] Regenerate both entries from the published zips (the ones here are prepared from the + mod.json files, with a zero SHA-256 that `catalog.yml`'s download check refuses): + + ``` + curl -fLO https://github.com/Open-HMG/hmgapi-wireless-cp-aa/releases/download/v3.0.0/wireless-carplay-aa-3.0.0.zip + tools/catalog.py add wireless-carplay-aa-3.0.0.zip --download https://github.com/Open-HMG/hmgapi-wireless-cp-aa/releases/download/v3.0.0/wireless-carplay-aa-3.0.0.zip --repo https://github.com/Open-HMG/hmgapi-wireless-cp-aa + curl -fLO https://github.com/Open-HMG/hmgapi-projection-tbt/releases/download/v1.0.0/projection-tbt-1.0.0.zip + tools/catalog.py add projection-tbt-1.0.0.zip --download https://github.com/Open-HMG/hmgapi-projection-tbt/releases/download/v1.0.0/projection-tbt-1.0.0.zip --repo https://github.com/Open-HMG/hmgapi-projection-tbt + ``` + + (the same commands as the two release runs' summaries). +- [ ] If Wireless 2.2.0 entered the catalogue meanwhile (for HMG-API 1.1.0), rebase first; + `add` refuses a version older than the entry. +- [ ] Both entries in one PR, merged by a maintainer. The descriptions are the mods' own + (`mod.json`) and tell owners turn-by-turn is its own mod and to update Wireless first. + The wiki's Community mods page and the pages changed here (Home, the NEMESIS packages + table in Installing HMG-API) update on merge. + +### 6. Bundled in HMG-API + +- [ ] The next HMG-API release after step 5: `tools/release-mods.txt` lists + `wireless-carplay-aa` and `projection-tbt` by id (no pins). Its release notes: update + Wireless first, then install Phone Turn-by-Turn; `egmp-aa-ev` owners stay on 2.x. + +### 7. Afterwards + +- [ ] Both READMEs: drop "set up but not released" and the betas' wording. +- [ ] Wireless README "Install and connect": the version and HMG-API floor. +- [ ] `egmp-aa-ev`: a release that works with Wireless 3.0, then lift the cap. + +## What owners are told, and where + +| Where | Text | +|---|---| +| Wireless `mod.json` description (its catalogue entry, the Community mods page) | From 3.0, turn-by-turn is its own mod; update this one first, then install that one | +| `projection-tbt` `mod.json` description | Part of Wireless until 3.0; update Wireless to 3.0 first, then install this one | +| Wireless README, "Updating from 2.x" | the order, why (the conflict), settings set again, `egmp-aa-ev`, going back | +| Turn-by-turn README, "Updating from the Wireless mod 2.x" | the same, from this side; wired-only cars install it alone | +| Both first release notes | the order, what to test, going back (remove `projection-tbt` first) | +| Wiki: Home, Installing HMG-API (NEMESIS packages table) | turn-by-turn listed on its own; `projection-tbt`'s NEMESIS conflicts | diff --git a/wiki/Home.md b/wiki/Home.md index 33ed3e35..8862a22e 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -3,9 +3,9 @@ # HMG-API HMG-API is a mod manager for Hyundai, Kia and Genesis head units with navigation -(Gen5W). Mods add features to the head unit: wireless CarPlay and Android Auto with -turn-by-turn on the cluster and HUD, buttons that do more, pages in the side panel, -and more. You can install as many as you like; they don't overwrite each other, and +(Gen5W). Mods add features to the head unit: wireless CarPlay and Android Auto, your +phone's turn-by-turn on the cluster and HUD, buttons that do more, pages in the side +panel, and more. You can install as many as you like; they don't overwrite each other, and removing one puts back exactly what it changed. ![The HMG-API app](images/mods.png) diff --git a/wiki/Installing-HMG-API.md b/wiki/Installing-HMG-API.md index f13c5ca1..b736858a 100644 --- a/wiki/Installing-HMG-API.md +++ b/wiki/Installing-HMG-API.md @@ -51,7 +51,8 @@ other way round. Uninstall that package in NEMESIS Manager first: | Package | Can't be installed with | |---|---| | HMG-API | HMG Leafia Plus (`wireless.carplay.aa`), `carplay.session`, `voicehandler.vr-gates` (the last two until we know they don't clash) | -| Wireless CarPlay + Android Auto (mod) | NEMESIS's Wireless Projection (`wireless.projection`) and Projection TBT (`projection.tbt`) | +| Wireless CarPlay + Android Auto (mod) | NEMESIS's Wireless Projection (`wireless.projection`), Projection TBT (`projection.tbt`) and Enhanced Projection (`enhanced.projection`) | +| Phone Turn-by-Turn (mod) | NEMESIS's Projection TBT (`projection.tbt`) and Enhanced Projection (`enhanced.projection`) | | adb (mod) | NEMESIS's ADB over TCP (`adb.tcp`) | ## adb From c44f2773b765b494f1ae78154e3313fff9ffada3 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:15:04 -0500 Subject: [PATCH 16/69] Home Wi-Fi: the 127.x guard narrowed and kept; rules built with no gap HMGAPI_HOMELO lets in, for 127.x on wlan0, only the DNS server's answers (its address, port 53, established), and it is checked on every route_up instead of only when the lease changes: the stock firewall reloading flushes INPUT and can put its own jump first. route_localnet is on only while the guard is first in INPUT; a guard that can't go in is said and route_localnet stays off. The nat OUTPUT jump to HMGAPI_HOMEDNS is checked on every pass too. The network keeper builds the post-reroute DROP, the mark, masquerade, table 95's unreachable default and the fwmark rule before the IPv4 home REJECTs leave, and fills the cellular chain before OUTPUT jumps to it. mods_ok also checks the DROP inside HMGAPI_HOMECELL. wifi.sh down, net.sh down and the uninstaller take table 95's unreachable default out. The test's fake ip route replace/add now key routes as the kernel does (table, destination, metric; not the type), so a default via the gateway replaces the unreachable one. Tested off-car only (homewifi-test.sh with bash, net-test.sh, install/common/test.sh). Not yet checked on a car with the stock whitelist firewall (US Ioniq 6). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++- core/runtime/homewifi-test.sh | 59 +++++++++++++++++-- core/runtime/java/hmgapi/engine/HomeWifi.java | 53 ++++++++++++----- core/runtime/java/hmgapi/engine/Network.java | 36 +++++++---- install/common/uninstall.sh | 3 + 5 files changed, 126 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00d17d9b..9e52c652 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,11 +19,18 @@ (`mangle POSTROUTING`, `HMGAPI_HOMECELL`: nothing marked for home Wi-Fi leaves on `rmnet`), and table 95 holds an unreachable default while home Wi-Fi is down, so marked traffic never falls through to mobile data. IPv6, and everything with home Wi-Fi off, stays refused as before. + The keeper builds the home Wi-Fi rules (the post-reroute block, the mark, masquerade, table 95 + and the fwmark rule) before the IPv4 home REJECTs leave, and fills the cellular chain before + OUTPUT jumps to it; its check also looks for the DROP inside `HMGAPI_HOMECELL`. Home Wi-Fi off + and the uninstaller take table 95's unreachable default out. - **Mods' services can look names up on home Wi-Fi** (Ioniq 5 US 260507). Their resolver (`ANDROID_DNS_MODE=local`) has no servers in the service's process and asks 127.0.0.1; HMG-API's redirect to home Wi-Fi's DNS server kept that source address, so no query left the unit. While home Wi-Fi is up, `route_localnet` is on for `wlan0` (the queries are - masqueraded) and only the answers may come back in for 127.x (`HMGAPI_HOMELO`). + masqueraded) and, for 127.x on `wlan0`, only the DNS server's answers (its address, port 53) + get in (`HMGAPI_HOMELO`). The guard is checked on every pass, not only when the lease changes, + and put back first in INPUT after the stock firewall reloads; `route_localnet` is on only + while it's there. ## 1.1.0-rc.10 (2026-11-25) diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index bf17441e..1f85ea96 100644 --- a/core/runtime/homewifi-test.sh +++ b/core/runtime/homewifi-test.sh @@ -87,6 +87,7 @@ d=$FW/$v/$t; mkdir -p "$d" stock() { case $1 in INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING) return 0 ;; esac; return 1; } op=$1 c=$2; shift 2 f=$d/$c +case $op in -A|-I|-D|-F|-N|-X) echo "ipt$v $t $op $c $*" >> "$FW/order.log" ;; esac if ! stock "$c" && [ "$op" != -N ] && [ ! -f "$f" ]; then echo "iptables: No chain/target/match by that name." >&2; exit 1; fi case $op in -S) if stock "$c"; then echo "-P $c ACCEPT"; else echo "-N $c"; fi @@ -108,20 +109,30 @@ cat > "$F/bin/ip" <<'S' v=4; case $1 in -4) shift ;; -6) v=6; shift ;; esac o=$1 c=$2; shift 2 f=$FW/ip$v.$o; touch "$f" +rkey() { # " " of a route line + set -- $1; case $1 in unicast|unreachable|blackhole|prohibit|throw|local) shift ;; esac + dst=$1; [ "$dst" = default ] && dst=0.0.0.0/0; case $dst in */*) ;; *) dst=$dst/32 ;; esac + m=0 tb=main; while [ $# -gt 0 ]; do case $1 in metric|priority) m=$2 ;; table) tb=$2 ;; esac; shift; done + echo "$tb $dst $m" +} case $o.$c in route.show) if [ "$1" = dev ]; then grep -- " dev $2 .*table main\$" "$f" | sed 's/ table main$//' || true elif [ "$1" = table ]; then grep -- " table $2\$" "$f" | sed "s/ table $2\$//" || true; else grep -- " table main\$" "$f" || true; fi ;; - route.replace) n=$#; if [ "${@:$((n-1)):1}" = table ]; then tb=${!n}; set -- "${@:1:$((n-2))}"; else tb=main; fi - grep -v -- "^$1 .*table $tb\$" "$f" > "$f.new"; mv "$f.new" "$f"; echo "$* table $tb" >> "$f" ;; - route.add) n=$#; if [ "${@:$((n-1)):1}" = table ]; then tb=${!n}; set -- "${@:1:$((n-2))}"; else tb=main; fi - echo "$* table $tb" >> "$f" ;; + route.replace|route.add) n=$#; if [ "${@:$((n-1)):1}" = table ]; then tb=${!n}; set -- "${@:1:$((n-2))}"; else tb=main; fi + # as the kernel: a route is its table, destination and metric; its type (unreachable, ...) and + # the rest don't count. replace swaps the one with that key; add fails if there is one + k=$(rkey "$* table $tb") + while IFS= read -r l; do [ "$(rkey "$l")" = "$k" ] && found=1 || echo "$l"; done < "$f" > "$f.new" + if [ $c = add ] && [ -n "$found" ]; then rm "$f.new"; echo "RTNETLINK answers: File exists" >&2; exit 2; fi + echo "ip $c $* table $tb" >> "$FW/order.log" + mv "$f.new" "$f"; echo "$* table $tb" >> "$f" ;; route.del) grep -q -e "^$1 .*dev $3 .*table main\$" -e "^$1 dev $3 .*table main\$" "$f" || exit 2 awk -v r="$1" -v d="$3" '!x && $1 == r && index($0, " dev " d " ") { x = 1; next } { print }' "$f" > "$f.new"; mv "$f.new" "$f" ;; route.flush) grep -v -- " table $2\$" "$f" > "$f.new"; mv "$f.new" "$f" ;; route.get) [ "$2" = oif ] && grep -q "^10\.1\." <<< "$1" && echo "$1 dev $3" ;; addr.flush) : ;; rule.show) echo "0: from all lookup local"; cat "$f" ;; - rule.add) p=$2; shift 2; printf '%s:\t%s\n' "$p" "$*" >> "$f" ;; + rule.add) p=$2; shift 2; printf '%s:\t%s\n' "$p" "$*" >> "$f"; echo "ip rule add $p $*" >> "$FW/order.log" ;; rule.del) grep -q "^$2:" "$f" || exit 2; grep -v "^$2:" "$f" > "$f.new"; mv "$f.new" "$f" ;; esac S @@ -147,7 +158,14 @@ ipt() { PATH=$F/bin:$PATH iptables "$@"; } printf 'com.example.dl 10071 0 /data/data/com.example.dl default 3003\ncom.example.quiet 10072 0 /data/data/com.example.quiet default 3003\n' > "$F/packages.list" printf 'com.example.dl dl\ncom.example.quiet quiet\n' > "$D/state/apps.txt" +: > "$F/fw/order.log" log=$(keeper once) +# the order it's built in: no moment with the IPv4 home REJECTs gone and nothing else in their place +at() { grep -n -m1 -F -- "$1" "$F/fw/order.log" | cut -d: -f1; } +cell=$(at "ipt4 filter -I OUTPUT 1 -j HMGAPI_CELL") +check "built first: the post-reroute block, the mark, masquerade, table 95, the fwmark rule" yes "$(for l in "ipt4 mangle -A HMGAPI_HOMECELL -o rmnet+" "ipt4 mangle -I POSTROUTING 1 -j HMGAPI_HOMECELL" "ipt4 mangle -I OUTPUT 1 -j HMGAPI_HOME" "ipt4 nat -I POSTROUTING 1 -j HMGAPI_HOMEOUT" "ip add unreachable default table 95" "ip rule add 900 fwmark"; do a=$(at "$l"); [ -n "$a" ] && [ "$a" -lt "$cell" ] || { echo "no: $l"; exit; }; done; echo yes)" +check "... the cellular chain filled before OUTPUT jumps to it" yes "$([ "$(at "ipt4 filter -A HMGAPI_CELL -o rmnet+ -m owner --uid-owner 10072")" -lt "$cell" ] && echo yes || echo no)" +check "... marks before the jump to them" yes "$([ "$(at "ipt4 mangle -A HMGAPI_HOME -m owner --uid-owner 10071")" -lt "$(at "ipt4 mangle -I OUTPUT 1 -j HMGAPI_HOME")" ] && echo yes || echo no)" has "mods kept off cellular" "mods kept off cellular: 2 app(s) and every mod service, home Wi-Fi routing in" "$log" check "the cellular chain first in OUTPUT" "-A OUTPUT -j HMGAPI_CELL" "$(ipt -S OUTPUT | grep -m1 '^-A')" check "its IPv4 rules: the plain group and the app that didn't ask (home ones: after the reroute)" "-o rmnet+ -m owner --gid-owner 2950 -j REJECT @@ -162,6 +180,9 @@ has "marked traffic to table 95" "900: fwmark 0x2951 table 95" "$(cat "$F/fw/ip4 check "both mods' apps look names up through wlan0, never cellular DNS" "resolver setifaceforuidrange wlan0 10071 10071 resolver setifaceforuidrange wlan0 10072 10072" "$(cat "$F/fw/ndc.log")" check "all there: a check is quiet" "" "$(keeper once)" +ipt -t mangle -F HMGAPI_HOMECELL # the jump left, the DROP in it gone +has "the post-reroute DROP gone (its jump still there): put back" "mods' cellular block put back" "$(keeper once)" +check "... the DROP again" "-o rmnet+ -m mark --mark 0x2951 -j DROP" "$(cat "$F/fw/4/mangle/HMGAPI_HOMECELL")" ipt -I OUTPUT 1 -o rmnet+ -j ACCEPT # the stock firewall puts an accept first has "moved: put back first" "mods' cellular block put back" "$(keeper once)" check "... first again" "-A OUTPUT -j HMGAPI_CELL" "$(ipt -S OUTPUT | grep -m1 '^-A')" @@ -177,8 +198,10 @@ check "home Wi-Fi off: no marks" no "$([ -f "$F/fw/4/mangle/HMGAPI_HOME" ] && ec hasnt "... no routing rule" "900:" "$(cat "$F/fw/ip4.rule")" check "... still off cellular: all four refused in OUTPUT again" 4 "$(grep -c REJECT "$F/fw/4/filter/HMGAPI_CELL")" check "... no post-reroute block (nothing is marked)" no "$([ -f "$F/fw/4/mangle/HMGAPI_HOMECELL" ] && echo yes || echo no)" +FW=$F/fw PATH=$F/bin:$PATH ip route replace unreachable default table 95 keeper down >/dev/null hasnt "down: the cellular chain gone" "HMGAPI_CELL" "$(ipt -S OUTPUT)" +check "... table 95 empty (the uninstaller; wifi.sh's, in case it couldn't)" "" "$(grep 'table 95' "$F/fw/ip4.route" || true)" : > "$D/settings/allow/home_wifi" eng publish-state @@ -332,9 +355,32 @@ has "wlan0's DNS servers for the mods" "resolver setifdns wlan0 10.10.10.100" " has "a DNS server off the subnet: through the gateway" "10.10.10.100/32 via 10.4.0.1 dev wlan0 metric 1000" "$(cat "$F/fw/ip4.route")" check "mods' services' DNS to the home router's" "-m owner --gid-owner 2951 -p udp --dport 53 -j DNAT --to-destination 10.10.10.100 -m owner --gid-owner 2951 -p tcp --dport 53 -j DNAT --to-destination 10.10.10.100" "$(cat "$F/fw/4/nat/HMGAPI_HOMEDNS")" -has "services' lookups (their resolver asks 127.0.0.1) may come back in through wlan0, answers only" "-i wlan0 -d 127.0.0.0/8 -m state --state ESTABLISHED,RELATED -j RETURN +check "services' lookups (their resolver asks 127.0.0.1) may come back in through wlan0: the DNS server's answers only" "-i wlan0 -s 10.10.10.100/32 -d 127.0.0.0/8 -p udp --sport 53 -m state --state ESTABLISHED -j RETURN +-i wlan0 -s 10.10.10.100/32 -d 127.0.0.0/8 -p tcp --sport 53 -m state --state ESTABLISHED -j RETURN -i wlan0 -d 127.0.0.0/8 -j DROP" "$(cat "$F/fw/4/filter/HMGAPI_HOMELO")" check "... first in INPUT" "-j HMGAPI_HOMELO" "$(head -1 "$F/fw/4/filter/INPUT")" +check "... route_localnet on, behind it" 1 "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet")" +check "table 95: Wi-Fi's default replaced the unreachable one (one default, as the kernel keeps)" "default via 10.4.0.1 dev wlan0" "$(FW=$F/fw PATH=$F/bin:$PATH ip route show table 95 | grep default)" +# the stock firewall restarts (iptrules: INPUT flushed, its whitelist jump back), the lease the same +: > "$F/fw/4/filter/INPUT"; ipt -N WLIST_IN 2>/dev/null || true; ipt -A INPUT -j WLIST_IN +log=$(wk) +has "the stock firewall reloaded, the lease unchanged: the guard put back" "home Wi-Fi's 127.x guard put back" "$log" +check "... first in INPUT again" "-j HMGAPI_HOMELO" "$(head -1 "$F/fw/4/filter/INPUT")" +check "... the stock jump kept, after it" "-j WLIST_IN" "$(sed -n 2p "$F/fw/4/filter/INPUT")" +check "... route_localnet still on" 1 "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet")" +ipt -I INPUT 1 -j WLIST_IN # the stock jump put first, ours still there +wk >/dev/null +check "not first any more: moved back first" "-j HMGAPI_HOMELO" "$(head -1 "$F/fw/4/filter/INPUT")" +check "... once" 1 "$(grep -c HMGAPI_HOMELO "$F/fw/4/filter/INPUT")" +check "all in place: the next pass is quiet" "" "$(wk)" +ipt -F INPUT; ipt -N HMGAPI_BROKEN 2>/dev/null; printf '#!/bin/bash\ncase "$*" in *"-I INPUT 1 -j HMGAPI_HOMELO"*) exit 1 ;; esac\nexec "$(dirname "$0")/iptables.real" "$@"\n' > "$F/bin/iptables.wrap" +mv "$F/bin/iptables" "$F/bin/iptables.real"; mv "$F/bin/iptables.wrap" "$F/bin/iptables"; chmod +x "$F/bin/iptables" +log=$(wk) +has "the guard can't go in: said" "home Wi-Fi's 127.x guard can't be put in" "$log" +check "... route_localnet off" 0 "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet")" +mv "$F/bin/iptables.real" "$F/bin/iptables" +wk >/dev/null +check "... and on once it can" 1 "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet")" has "what it saw, for the app" "2437 -61 [WPA2-PSK-CCMP][ESS] Willows" "$(verb seen)" hasnt "the key never in the log" "secret" "$log" FW=$F/fw PATH=$F/bin:$PATH ip route replace default via 10.4.0.1 dev wlan0 # Android puts it back (a renewal) @@ -430,6 +476,7 @@ wk >/dev/null verb down >/dev/null check "down while parked: the hotspot back" 2 "$(cat "$F/fw/ap")" check "... the client off" no "$([ -f "$F/fw/client" ] && echo yes || echo no)" +check "... table 95's unreachable default out too (home Wi-Fi off, the uninstaller)" "" "$(grep 'table 95' "$F/fw/ip4.route" || true)" # ---- the projection AP ("wifi": {"projection": true}): the engine rm -f "$D/settings/allow/home_wifi" "$D/settings/hmgapi.json" diff --git a/core/runtime/java/hmgapi/engine/HomeWifi.java b/core/runtime/java/hmgapi/engine/HomeWifi.java index 5eb4dc39..408a2be5 100644 --- a/core/runtime/java/hmgapi/engine/HomeWifi.java +++ b/core/runtime/java/hmgapi/engine/HomeWifi.java @@ -308,28 +308,51 @@ static List describe(Engine e, Map> json, Se " ip route replace $d/32 via $gw dev $I metric 1000 && echo $d/32 >> $W/dnsroutes", " done", " iptables -t nat -N HMGAPI_HOMEDNS 2>/dev/null; iptables -t nat -F HMGAPI_HOMEDNS", - " iptables -t nat -C OUTPUT -j HMGAPI_HOMEDNS 2>/dev/null || iptables -t nat -I OUTPUT 1 -j HMGAPI_HOMEDNS", " for p in udp tcp; do iptables -t nat -A HMGAPI_HOMEDNS -m owner --gid-owner " + HOME_GID + " -p $p --dport 53 -j DNAT --to-destination $d1; done", - " # a service's resolver (ANDROID_DNS_MODE=local) has no servers in its process on these units, so", - " # it asks 127.0.0.1:53: the DNAT above sends that on to $d1 with the source still 127.0.0.1,", - " # which the kernel only routes out of (and back in through) wlan0 with route_localnet. Masqueraded", - " # (HMGAPI_HOMEOUT: marked), so nothing leaves as 127.0.0.1; only the answers to those queries may", - " # come in for 127.x on wlan0 (HMGAPI_HOMELO), nothing a home network sends on its own", - " echo 1 > $X/proc/sys/net/ipv4/conf/$I/route_localnet 2>/dev/null", - " iptables -N HMGAPI_HOMELO 2>/dev/null; iptables -F HMGAPI_HOMELO", - " iptables -C INPUT -j HMGAPI_HOMELO 2>/dev/null || iptables -I INPUT 1 -j HMGAPI_HOMELO", - " iptables -A HMGAPI_HOMELO -i $I -d 127.0.0.0/8 -m state --state ESTABLISHED,RELATED -j RETURN", - " iptables -A HMGAPI_HOMELO -i $I -d 127.0.0.0/8 -j DROP", + " 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\"", " 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", + " iptables -t nat -C OUTPUT -j HMGAPI_HOMEDNS 2>/dev/null || iptables -t nat -I OUTPUT 1 -j HMGAPI_HOMEDNS", + " if lo_guard $d1; then echo 1 > $LOCALNET 2>/dev/null; else echo 0 > $LOCALNET 2>/dev/null; fi", + "}", + "# A service's resolver (ANDROID_DNS_MODE=local) has no servers in its process on these units, so it", + "# asks 127.0.0.1:53: HMGAPI_HOMEDNS's DNAT sends that on to the DNS server with the source still", + "# 127.0.0.1, which the kernel only routes out of (and back in through) wlan0 with route_localnet.", + "# Masqueraded (HMGAPI_HOMEOUT: marked), so nothing leaves as 127.0.0.1. route_localnet is on only", + "# while HMGAPI_HOMELO is first in INPUT: for 127.x on wlan0, only the DNS server's answers (source", + "# $1, port 53; the DNAT is undone after filter INPUT, so they still carry its address) get past it,", + "# nothing else a home network sends. $1: the DNS server. Built again when missing or not first.", + "LOCALNET=$X/proc/sys/net/ipv4/conf/$I/route_localnet", + "lo_rules() { # $1 the server, $2 -C (check) or -A (add)", + " for p in udp tcp; do iptables $2 HMGAPI_HOMELO -i $I -s $1/32 -d 127.0.0.0/8 -p $p --sport 53 -m state --state ESTABLISHED -j RETURN 2>/dev/null || return 1; done", + " iptables $2 HMGAPI_HOMELO -i $I -d 127.0.0.0/8 -j DROP 2>/dev/null", + "}", + "lo_first() { [ \"$(iptables -S INPUT 2>/dev/null | while read -r a b rest; do [ \"$a\" = -A ] && { echo \"$rest\"; break; }; done)\" = '-j HMGAPI_HOMELO' ]; }", + "lo_guard() {", + " lo_rules $1 -C && lo_first && return 0", + " echo 0 > $LOCALNET 2>/dev/null # while it's rebuilt", + " again=; iptables -S HMGAPI_HOMELO >/dev/null 2>&1 && [ -f $W/lo.$1 ] && again=1", + " iptables -N HMGAPI_HOMELO 2>/dev/null; iptables -F HMGAPI_HOMELO", + " lo_rules $1 -A", + " for _ in 1 2 3 4; do iptables -D INPUT -j HMGAPI_HOMELO 2>/dev/null || break; done", + " iptables -I INPUT 1 -j HMGAPI_HOMELO", + " if lo_rules $1 -C && lo_first; then", + " rm -f $W/lo.*; : > $W/lo.$1", + " [ -n \"$again\" ] && say \"home Wi-Fi's 127.x guard put back (moved or removed since: the stock firewall reloaded?)\"", + " return 0", + " fi", + " say \"home Wi-Fi's 127.x guard can't be put in: mods' services' lookups stay off (route_localnet off)\"", + " return 1", "}", "route_down() {", " ip route flush table $T 2>/dev/null", " no_route", - " echo 0 > $X/proc/sys/net/ipv4/conf/$I/route_localnet 2>/dev/null", + " echo 0 > $LOCALNET 2>/dev/null", " for _ in 1 2 3 4; do iptables -D INPUT -j HMGAPI_HOMELO 2>/dev/null || break; done", - " iptables -F HMGAPI_HOMELO 2>/dev/null; iptables -X HMGAPI_HOMELO 2>/dev/null", + " iptables -F HMGAPI_HOMELO 2>/dev/null; iptables -X HMGAPI_HOMELO 2>/dev/null; rm -f $W/lo.*", " iptables -t nat -F HMGAPI_HOMEDNS 2>/dev/null", " for r in $(cat $W/dnsroutes 2>/dev/null); do ip route del $r dev $I 2>/dev/null; done", " rm -f $W/dnsroutes $W/lease", @@ -463,7 +486,9 @@ static List describe(Engine e, Map> json, Se " fi", " status waiting", "}", - "down() { client_mode && client_off \"home Wi-Fi off\"; route_down; status off; }", + "# home Wi-Fi off, the uninstaller, the service stopped: table 95's unreachable default out too (the", + "# network keeper's fwmark rule goes with home Wi-Fi; until then, marked traffic is still dropped on rmnet)", + "down() { client_mode && client_off \"home Wi-Fi off\"; route_down; ip route flush table $T 2>/dev/null; status off; }", "umask 077", "case $1 in", " down) down; exit 0 ;;", diff --git a/core/runtime/java/hmgapi/engine/Network.java b/core/runtime/java/hmgapi/engine/Network.java index 6598539b..11efe563 100644 --- a/core/runtime/java/hmgapi/engine/Network.java +++ b/core/runtime/java/hmgapi/engine/Network.java @@ -693,10 +693,29 @@ static List describe(String id, Ask a, boolean allowed) { "# (mangle POSTROUTING, HMGAPI_HOMECELL: anything marked for home Wi-Fi never leaves on rmnet), and", "# table 95 is never empty (wifi.sh: an unreachable default while home Wi-Fi is down). IPv6 isn't", "# routed to home Wi-Fi, so it stays refused in OUTPUT; so does everything with home Wi-Fi off.", + "# Built in an order with no gap: home Wi-Fi's mark, its post-reroute block, masquerade, table 95's", + "# unreachable default (if wifi.sh hasn't put one yet) and the fwmark rule first, then the cellular", + "# chain without the IPv4 home REJECTs, filled before OUTPUT jumps to it.", "mods_up() {", " home=; grep -q '^homewifi' \"$MA\" && home=1", + " if [ -n \"$home\" ]; then", + " iptables -t mangle -N HMGAPI_HOMECELL 2>/dev/null; iptables -t mangle -F HMGAPI_HOMECELL", + " iptables -t mangle -A HMGAPI_HOMECELL -o rmnet+ -m mark --mark " + HomeWifi.MARK + " -j DROP", + " iptables -t mangle -I POSTROUTING 1 -j HMGAPI_HOMECELL", + " iptables -t mangle -N HMGAPI_HOME 2>/dev/null; iptables -t mangle -F HMGAPI_HOME", + " iptables -t mangle -A HMGAPI_HOME -m owner --gid-owner " + HomeWifi.HOME_GID + " -j MARK --set-mark " + HomeWifi.MARK, + " while read -r mode u; do", + " [ \"$mode\" = home ] && iptables -t mangle -A HMGAPI_HOME -m owner --uid-owner $u -j MARK --set-mark " + HomeWifi.MARK, + " done < \"$MA\"", + " iptables -t mangle -I OUTPUT 1 -j HMGAPI_HOME", + " iptables -t nat -N HMGAPI_HOMEOUT 2>/dev/null; iptables -t nat -F HMGAPI_HOMEOUT", + " iptables -t nat -A HMGAPI_HOMEOUT -o " + HomeWifi.IFACE + " -m mark --mark " + HomeWifi.MARK + " -j MASQUERADE", + " iptables -t nat -I POSTROUTING 1 -j HMGAPI_HOMEOUT", + " [ -n \"$(ip route show table " + HomeWifi.TABLE + " 2>/dev/null)\" ] || ip route add unreachable default table " + HomeWifi.TABLE + " 2>/dev/null", + " ip rule add priority " + HomeWifi.PRIORITY + " fwmark " + HomeWifi.MARK + " table " + HomeWifi.TABLE, + " fi", " for v in 4 6; do", - " ipt $v -N HMGAPI_CELL 2>/dev/null; ipt $v -F HMGAPI_CELL; ipt $v -I OUTPUT 1 -j HMGAPI_CELL", + " ipt $v -N HMGAPI_CELL 2>/dev/null; ipt $v -F HMGAPI_CELL", " ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --gid-owner " + HomeWifi.SERVICE_GID + " -j REJECT", " [ -n \"$home\" ] && [ $v = 4 ] || ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --gid-owner " + HomeWifi.HOME_GID + " -j REJECT", " done", @@ -706,18 +725,8 @@ static List describe(String id, Ask a, boolean allowed) { " home) for v in 4 6; do [ -n \"$home\" ] && [ $v = 4 ] || ipt $v -A HMGAPI_CELL -o rmnet+ -m owner --uid-owner $u -j REJECT; done ;;", " esac", " done < \"$MA\"", + " for v in 4 6; do ipt $v -I OUTPUT 1 -j HMGAPI_CELL; done", " mods_dns", - " [ -n \"$home\" ] || return 0", - " iptables -t mangle -N HMGAPI_HOME 2>/dev/null; iptables -t mangle -F HMGAPI_HOME; iptables -t mangle -I OUTPUT 1 -j HMGAPI_HOME", - " iptables -t mangle -A HMGAPI_HOME -m owner --gid-owner " + HomeWifi.HOME_GID + " -j MARK --set-mark " + HomeWifi.MARK, - " while read -r mode u; do", - " [ \"$mode\" = home ] && iptables -t mangle -A HMGAPI_HOME -m owner --uid-owner $u -j MARK --set-mark " + HomeWifi.MARK, - " done < \"$MA\"", - " iptables -t mangle -N HMGAPI_HOMECELL 2>/dev/null; iptables -t mangle -F HMGAPI_HOMECELL; iptables -t mangle -I POSTROUTING 1 -j HMGAPI_HOMECELL", - " iptables -t mangle -A HMGAPI_HOMECELL -o rmnet+ -m mark --mark " + HomeWifi.MARK + " -j DROP", - " iptables -t nat -N HMGAPI_HOMEOUT 2>/dev/null; iptables -t nat -F HMGAPI_HOMEOUT; iptables -t nat -I POSTROUTING 1 -j HMGAPI_HOMEOUT", - " iptables -t nat -A HMGAPI_HOMEOUT -o " + HomeWifi.IFACE + " -m mark --mark " + HomeWifi.MARK + " -j MASQUERADE", - " ip rule add priority " + HomeWifi.PRIORITY + " fwmark " + HomeWifi.MARK + " table " + HomeWifi.TABLE, "}", "# in place, first in OUTPUT (nothing ahead of it may accept a mod's packet for cellular), all its rules there", "mods_ok() {", @@ -731,6 +740,7 @@ static List describe(String id, Ask a, boolean allowed) { " done", " grep -q '^homewifi' \"$MA\" || return 0", " iptables -t mangle -C OUTPUT -j HMGAPI_HOME 2>/dev/null && iptables -t mangle -C POSTROUTING -j HMGAPI_HOMECELL 2>/dev/null \\", + " && iptables -t mangle -C HMGAPI_HOMECELL -o rmnet+ -m mark --mark " + HomeWifi.MARK + " -j DROP 2>/dev/null \\", " && iptables -t nat -C POSTROUTING -j HMGAPI_HOMEOUT 2>/dev/null || return 1", " out=$(ip rule show 2>/dev/null); case $out in *\"" + HomeWifi.PRIORITY + ":\"*) ;; *) return 1 ;; esac", "}", @@ -749,7 +759,7 @@ static List describe(String id, Ask a, boolean allowed) { " tick=$((tick + 1)); [ $((tick % 6)) = 0 ] && mods_dns # netd forgets it when it restarts", "}", "tick=0", - "down() { fw_down; others_down; mods_down; rm -f \"$A\"; }", + "down() { fw_down; others_down; mods_down; ip route flush table " + HomeWifi.TABLE + " 2>/dev/null; rm -f \"$A\"; } # table 95: wifi.sh's, in case it couldn't", "keep() {", " case $(getprop init.svc.iptrules) in running|restarting) return ;; esac # the stock firewall loading", " mods_keep", diff --git a/install/common/uninstall.sh b/install/common/uninstall.sh index 4b9ac981..f33a5b2a 100644 --- a/install/common/uninstall.sh +++ b/install/common/uninstall.sh @@ -136,6 +136,9 @@ if [ -f "$D/state/services.txt" ]; then log "mods' services stopped" fi # mods' network rules, routes and settings out (the keeper does it when stopped; again in case it couldn't) +if [ -z "$ROOT" ] && [ -f "$D/state/wifi.sh" ]; then + sh "$D/state/wifi.sh" down >/dev/null 2>&1 && log "home Wi-Fi off, its routes out" +fi if [ -z "$ROOT" ] && [ -f "$D/state/net.sh" ]; then sh "$D/state/net.sh" down >/dev/null 2>&1 && log "mods' network rules out" fi From c7da49b90a2b2c1193948e2146d8507801c02780 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:20:21 -0500 Subject: [PATCH 17/69] projection-tbt entry and checklist: settings are taken over from Wireless 2.x The prepared entry takes the mod's current mod.json description (install-order warning), and the checklist no longer says owners set their turn-by-turn settings again: projection-tbt takes them over from Wireless 2.x once (WirelessImport), now a test item before the finals. Co-Authored-By: Claude Opus 5.5 --- catalog/projection-tbt.json | 2 +- docs/wireless-3-split.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/catalog/projection-tbt.json b/catalog/projection-tbt.json index 2f53e797..b7f7e151 100644 --- a/catalog/projection-tbt.json +++ b/catalog/projection-tbt.json @@ -1,7 +1,7 @@ { "id": "projection-tbt", "name": "Phone Turn-by-Turn (CarPlay + Android Auto)", - "description": "Android Auto's and CarPlay's turn-by-turn directions on the cluster and HUD, wired or wireless. Until Wireless CarPlay + Android Auto 3.0 this was part of that mod: update Wireless to 3.0 first, then install this one.", + "description": "Android Auto's and CarPlay's turn-by-turn directions on the cluster and HUD, wired or wireless. Part of the Wireless CarPlay + Android Auto mod until its 3.0: with that mod, update it to 3.0 first (next to 2.x this mod turns it off).", "authors": [ "VysseCodes", "AwsomeFox", diff --git a/docs/wireless-3-split.md b/docs/wireless-3-split.md index 8122ae7e..072c3a1c 100644 --- a/docs/wireless-3-split.md +++ b/docs/wireless-3-split.md @@ -85,6 +85,8 @@ three repositories, and what owners are told. Rules are [releasing.md](releasing - [ ] Wrong order on purpose: `projection-tbt` next to 2.2.x shows the conflict and Wireless comes back once it's 3.0. - [ ] `projection-tbt` alone, wired phone. Wireless 3.0 alone: the car's navigation keeps the cluster. +- [ ] Turn-by-turn settings changed in Wireless 2.x are the same in `projection-tbt` after its + first start (its one-time take-over, `WirelessImport`). - [ ] CarPlay after the Bluetooth-to-Wi-Fi handover: route guidance keeps coming (the two mods' agreement, Wireless `docs/tbt-contract.md`). - [ ] The HMG-API app installing both from one stick: which goes first, and what the owner @@ -133,8 +135,8 @@ three repositories, and what owners are told. Rules are [releasing.md](releasing | Where | Text | |---|---| | Wireless `mod.json` description (its catalogue entry, the Community mods page) | From 3.0, turn-by-turn is its own mod; update this one first, then install that one | -| `projection-tbt` `mod.json` description | Part of Wireless until 3.0; update Wireless to 3.0 first, then install this one | -| Wireless README, "Updating from 2.x" | the order, why (the conflict), settings set again, `egmp-aa-ev`, going back | +| `projection-tbt` `mod.json` description | Part of Wireless until 3.0; update Wireless to 3.0 first (next to 2.x it turns Wireless off) | +| Wireless README, "Updating from 2.x" | the order, why (the conflict), settings taken over by `projection-tbt` once, `egmp-aa-ev`, going back | | Turn-by-turn README, "Updating from the Wireless mod 2.x" | the same, from this side; wired-only cars install it alone | | Both first release notes | the order, what to test, going back (remove `projection-tbt` first) | | Wiki: Home, Installing HMG-API (NEMESIS packages table) | turn-by-turn listed on its own; `projection-tbt`'s NEMESIS conflicts | From 30f848910454f3d65b90a324d6f8dbf6764f8902 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:23:22 -0500 Subject: [PATCH 18/69] Boot guard: count late crashes and hangs, fail closed, explain and reset The zygote wrapper's watcher reset both counts once the zygote had been up 120 s, so a mod that crashed Android later (a phone connecting, CarPlay starting) restarted it forever with hooks on, and a hang was never counted. - starts goes back to 0 only once Android booted: a system_server and a com.android.launcher3 child of that zygote, the launcher up 30 s, and sys.boot_completed 1. hook/boot is no longer reset within a kernel boot, so three restarts in one boot turn hooks off whenever they happen. - No system_server after 120 s: the zygote hung before it (a mod's zygoteInit); the watcher kills it so the restart counts. - A limit reached writes hook/tripped; hooks stay off until reset. - Counters fail closed: a read or write error, or a count that isn't a number, means no hooks. Writes go to a .tmp file, fsync, rename. - engine boot-guard [reset]: the app shows "Hooks off: boot guard", why, and Reset and restart; the problem log uses it too. - Settings text, Troubleshooting, the problem log, CLAUDE.md and the core README give the real limits. - core/zygote/test.sh: late crashes, hangs, a crash-looping launcher, boot never completed, write and read errors, tripped staying off. Tested off-car only (macOS: tools/test-all.sh --fast; the ARM tests need Linux). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 23 ++ CLAUDE.md | 2 +- core/README.md | 4 +- core/app/java/hmgapi/app/MainActivity.java | 78 ++++- core/app/java/hmgapi/app/SettingsTab.java | 5 +- core/hmgapid/hmgapid.c | 6 +- .../runtime/java/hmgapi/engine/BootGuard.java | 94 +++++ core/runtime/java/hmgapi/engine/Engine.java | 5 +- .../java/hmgapi/engine/ProblemLog.java | 6 +- core/runtime/problem-test.sh | 23 +- core/zygote/test.sh | 160 +++++++-- core/zygote/zygote.c | 322 ++++++++++++++---- install/common/install.sh | 2 +- wiki/Troubleshooting.md | 28 +- 14 files changed, 637 insertions(+), 121 deletions(-) create mode 100644 core/runtime/java/hmgapi/engine/BootGuard.java diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..eee20c5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## Unreleased + +- **The boot guard now catches late crashes and hangs, and fails closed.** Its watcher used + to reset both counts once the zygote had been up 120 s, so a mod crashing Android later + (a phone connecting, CarPlay starting) restarted it again and again with hooks on every + time, and a hang (a mod's `zygoteInit`, a home screen that crash-loops) was never counted. + Now a start counts as good only once Android booted: a `system_server` and a launcher + (`com.android.launcher3`) forked by that zygote, the launcher up 30 s, and + `sys.boot_completed` 1. Only then does `hook/starts` go back to 0; `hook/boot` (every start + in one kernel boot) is never reset within that boot. A zygote with no `system_server` after + 120 s (a normal one forks it within 3 s) is stopped, so that restart counts. When a limit + is reached the wrapper writes `hook/tripped`, and hooks stay off through restarts until the + owner resets the guard. The counters fail closed: a read or write error, or a count that + isn't a number, means no hooks for that start (it used to mean hooks on, start 1), and each + count is written to a `.tmp` file, fsynced and renamed over the old one. +- **The app says why its hooks are off.** "Hooks not running" becomes "Hooks off: boot + guard" when the guard tripped; tapping it says which limit was reached and offers **Reset + and restart** (before, only a reinstall or adb reset it). New engine command + `boot-guard [reset]`, also in the problem log. The Settings text, Troubleshooting page and + problem log now give the real limits (three restarts in one boot, at any time, or six + starts in a row that don't reach the home screen), not "three failed starts in a row". + Tested off-car only. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/CLAUDE.md b/CLAUDE.md index 9d4f13ff..174a48d9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,7 @@ Owners get to decide for their own units. Follow these by default. If the user a | Path | What | |---|---| | `core/hmgapid` | root daemon + client, static ARM (no libc). Ops per caller uid (root/shell: all incl. `sh`, `remount`; `hmgapi.app`: HMG-API ops; others: `ping`). Abstract socket `@hmgapid`. | -| `core/zygote` | `app_process` wrapper (installed as `/system/bin/app_process`, stock kept as `app_process.hmgapi-stock`): `LD_PRELOAD` for the zygote when `/data/hmgapi/hook/enable`, boot guard (`hook/starts`: starts in a row that didn't last 120 s, off at 6; `hook/boot`: the kernel's `boot_id` and its count, off at 3, so restarts within 120 s don't count as crashes; the watcher resets both after 120 s). | +| `core/zygote` | `app_process` wrapper (installed as `/system/bin/app_process`, stock kept as `app_process.hmgapi-stock`): `LD_PRELOAD` for the zygote when `/data/hmgapi/hook/enable`, boot guard (`hook/starts`: starts in a row that didn't boot, off at 6; `hook/boot`: the kernel's `boot_id` and every start in it, off at 3, never reset within a kernel boot; `hook/tripped`: written when a limit is reached, hooks off until the owner resets it, `engine boot-guard reset` or the app; counters fail closed, written via `.tmp` + fsync + rename). A watcher resets `starts` only once Android booted: a `system_server` and a `com.android.launcher3` child of that zygote, the launcher up 30 s and `sys.boot_completed` 1; no `system_server` after 120 s (hung before it, a mod's `zygoteInit`) and it kills the zygote, so the restart counts. | | `core/loader` | `libhmgapi_hook.so`: interposes `JNI_CreateJavaVM`, loads `/system/framework/hmgapi-hook.jar` before `ZygoteInit.main`, Dalvik method hooks (Xposed-style, offsets checked on the EV6 libdvm). | | `core/runtime` | `hmgapi-hook.jar`: `Bridge`, `Hooks`, `MethodHook`, `ModEntry`/`ModContext`/`LoadedApp` (mod API), `Mods` (loader), launcher/editor hooks (`HMG-API`), ★ choices (`StarKey`). | | `core/app` | `hmgapi.app`: status + mod list (from `HmgApiStatus.json`, set by the hooks). | diff --git a/core/README.md b/core/README.md index ea9d8d64..70578ba3 100644 --- a/core/README.md +++ b/core/README.md @@ -3,7 +3,7 @@ Feasibility test for HMG-API's hook runtime (Xposed-style method hooks on Dalvik 4.4), in three reversible steps: 1. **Wrapper** (done, EV6 US 2026-10-27): `zygote.c` is installed as `/system/bin/app_process` and runs the stock binary (`app_process.hmgapi-stock`) with the same arguments. It writes a `hmgapi-hook:` line to the kernel log on every pass. Stock ARM `app_process` re-execs itself once (`NO_ADDR_COMPAT_LAYOUT_FIXUP=1`), so the zygote passes through twice; only the first pass counts. -2. **Loader** (done, EV6 US 2026-10-27): `loader.c` → `libhmgapi_hook.so`, preloaded into the zygote (only with `/data/hmgapi/hook/enable`), so it is mapped in every app. For now it only logs `HMG-API: loaded in `. Boot guard: the wrapper counts zygote starts in `/data/hmgapi/hook/starts` and stops preloading at 3; a watcher it double-forks resets the count once that zygote has been up for 120 s. `/data/hmgapi/hook/disable` turns it off without touching `/system`. +2. **Loader** (done, EV6 US 2026-10-27): `loader.c` → `libhmgapi_hook.so`, preloaded into the zygote (only with `/data/hmgapi/hook/enable`), so it is mapped in every app. For now it only logs `HMG-API: loaded in `. Boot guard: the wrapper counts zygote starts in `/data/hmgapi/hook/starts` (in a row, off at 6) and `hook/boot` (in one kernel boot, off at 3), and once off stays off until reset (`hook/tripped`, `engine boot-guard reset`); a watcher it double-forks resets `starts` once Android booted (the launcher up 30 s, boot completed) and stops a zygote that never forks `system_server`. `zygote.c`'s header has the details. `/data/hmgapi/hook/disable` turns it off without touching `/system`. 3. **Method hooks** (done, EV6 US 2026-10-27): `loader.c` interposes `JNI_CreateJavaVM`, swaps the zygote's `CallStaticVoidMethodV` once, and before `ZygoteInit.main` loads `/system/framework/hmgapi-hook.jar` (`java/`) and runs `Bridge.init()`. Hooks work like Xposed on Dalvik: the method becomes native, the original `Method` is kept as a copy. Java API shaped like Xposed (`MethodHook`, `Hooks.findAndHookMethod`). First hooks: `ActivityThread.handleBindApplication` (every app start) and, in the launcher, a log-only hook on `com.android.launcher3.view.a.g.load()`. - `SelfTest` (12 checks: all argument types, results, skip, exceptions, constructors, 2 hooks, 2000 calls with GC) runs in a one-off `app_process`, away from the zygote: `LD_PRELOAD= HMGAPI_SELFTEST= CLASSPATH= app_process /system/bin hmgapi.hook.SelfTest`, as root (it writes the jar's Dalvik cache). - The zygote unsets `LD_PRELOAD` once Dalvik is up (after the stock re-exec), so programs that apps start don't load the library. @@ -19,7 +19,7 @@ Feasibility test for HMG-API's hook runtime (Xposed-style method hooks on Dalvik ./test.sh ``` -Runs the wrapper under qemu-arm: argument passthrough, preload switch, boot guard, disable file, exec failure. +Runs the wrapper under qemu-arm: argument passthrough, preload switch, boot guard (late crashes, hangs, a launcher that crash-loops, write and read errors), disable file, exec failure. ## Safety diff --git a/core/app/java/hmgapi/app/MainActivity.java b/core/app/java/hmgapi/app/MainActivity.java index cc499f09..d6e4cd07 100644 --- a/core/app/java/hmgapi/app/MainActivity.java +++ b/core/app/java/hmgapi/app/MainActivity.java @@ -187,7 +187,7 @@ static String subtitle() { void refreshStatus() { final int run = ++statusRun; // an older check finishing later doesn't add its pill too pills.removeAllViews(); - hooksPill(); + hooksPill(run); if (restartNeeded()) Ui.pill(pills, "Restart needed", Ui.WARN); if (planning) return; // back from Updates: plan() asks already (two at once only wait on each other) new Ui.Job() { @@ -206,17 +206,89 @@ void done(Boolean changed, Exception e) { }.start(this); } - private void hooksPill() { + private void hooksPill(int run) { try { JSONObject map = new JSONObject(HmgApiStatus.json).optJSONObject("map"); if (map == null || !map.optBoolean("on")) Ui.pill(pills, "Hooks off for this car", Ui.WARN); else Ui.pill(pills, "Hooks on" + (map.optBoolean("checked_here") || "verified".equals(map.optString("status")) ? " (map checked)" : ""), Ui.ACCENT); } catch (Exception e) { - Ui.pill(pills, "Hooks not running", Ui.ERROR); + whyNotRunning(run, Ui.pill(pills, "Hooks not running", Ui.ERROR)); } } + /** + * Hooks not running: the boot guard says whether it turned them off and why (engine + * boot-guard). Tapping the pill shows that, with a reset (then a restart) when it tripped. + */ + private void whyNotRunning(final int run, final TextView pill) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("engine", "boot-guard"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (run != statusRun || e != null || r.code != 0) return; + final String out = r.output.trim(); + final boolean tripped = out.contains("boot guard: tripped"); + TextView p = pill; + if (tripped) { + pills.removeView(pill); + p = Ui.pill(pills, "Hooks off: boot guard", Ui.ERROR); + } + p.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + bootGuard(out, tripped); + } + }); + } + }.start(this); + } + + private void bootGuard(String out, boolean tripped) { + String why = null; + StringBuilder counts = new StringBuilder(); + for (String l : out.split("\n")) { + if (l.startsWith("why: ")) why = l.substring(5); + else if (l.startsWith("starts ") || l.startsWith("hook/disable")) counts.append(l).append('\n'); + } + AlertDialog.Builder d = new AlertDialog.Builder(this).setTitle(tripped ? "HMG-API's boot guard turned its hooks off" : "Hooks not running"); + if (tripped) { + d.setMessage((why != null ? why + "\n\n" : "") + + "Mods with code don't run until you reset it. Turn off or remove the mod you added or changed last, " + + "then reset: hooks are back on after the restart. If Android fails again, the guard turns them off again.\n\n" + + counts.toString().trim()) + .setNegativeButton("Not now", null) + .setPositiveButton("Reset and restart", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface di, int which) { + resetBootGuard(); + } + }); + } else { + d.setMessage("The boot guard didn't turn them off.\n\n" + counts.toString().trim()).setPositiveButton("OK", null); + } + d.show(); + } + + private void resetBootGuard() { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("engine", "boot-guard", "reset"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e == null && r.code == 0) restart(); + else message("Couldn't reset the boot guard", e != null ? Hmgapid.unreachable(e) : r.output.trim()); + } + }.start(this); + } + /** the boot this process runs in (to the 10 s): a restart flag is only for the boot it was set in */ static long boot() { return (System.currentTimeMillis() - SystemClock.elapsedRealtime()) / 10000; diff --git a/core/app/java/hmgapi/app/SettingsTab.java b/core/app/java/hmgapi/app/SettingsTab.java index 773fff2a..29c966f0 100644 --- a/core/app/java/hmgapi/app/SettingsTab.java +++ b/core/app/java/hmgapi/app/SettingsTab.java @@ -309,8 +309,9 @@ public void run() { } }); owner("Maps not checked on a car yet", "For a car HMG-API is new on: hooks run with a map nobody has checked on this car. " - + "If Android fails to start three times during one boot with its hooks, or the head unit restarts six times in a row " - + "within two minutes of starting, HMG-API's boot guard turns its hooks off. Takes effect at the next restart.", + + "If Android has to start again three times in one boot with its hooks (it crashed or hung, at any time), or six " + + "starts in a row don't get to the home screen, HMG-API's boot guard turns its hooks off until you reset it " + + "(tap \"Hooks off: boot guard\" at the top). Takes effect at the next restart.", "Try unchecked maps", "testing_maps", false, new Runnable() { @Override public void run() { diff --git a/core/hmgapid/hmgapid.c b/core/hmgapid/hmgapid.c index 1ea04bf3..a9a759d3 100644 --- a/core/hmgapid/hmgapid.c +++ b/core/hmgapid/hmgapid.c @@ -642,10 +642,12 @@ 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, "boot-guard"))) { 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" + " | boot-guard [reset]\n"); return 2; } a[n++] = APP_PROCESS; diff --git a/core/runtime/java/hmgapi/engine/BootGuard.java b/core/runtime/java/hmgapi/engine/BootGuard.java new file mode 100644 index 00000000..36af7ba3 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/BootGuard.java @@ -0,0 +1,94 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * The zygote wrapper's boot guard (core/zygote/zygote.c), told to people: the app when its + * hooks aren't running, the problem log, and the owner's reset. + * + * engine boot-guard its state, one "key: value" per line + * engine boot-guard reset hooks on again from the next start (the app then restarts) + * + * The wrapper's files in /data/hmgapi/hook: starts (starts in a row that didn't boot), boot + * (" ") and tripped ("boot|row ", + * written when a limit was reached; hooks stay off until it's gone). The limits are + * zygote.c's MAXSTARTS and MAXBOOTS. + */ +final class BootGuard { + static final int MAXSTARTS = 3, MAXBOOTS = 6; + + private BootGuard() { + } + + static int run(Engine e, String[] args) throws IOException { + String sub = args.length > 1 ? args[1] : ""; + if ("reset".equals(sub)) { + reset(e); + e.out.add("reset: hooks on again from the next restart"); + } else if (!"".equals(sub)) { + e.out.add("usage: engine boot-guard [reset]"); + return 2; + } + e.out.addAll(describe(e)); + return 0; + } + + /** what the owner's reset does (as a reinstall): counts from 0, not tripped */ + static void reset(Engine e) throws IOException { + File hook = new File(e.data, "hook"); + Engine.write(new File(hook, "starts"), "0\n"); + new File(hook, "boot").delete(); + File t = new File(hook, "tripped"); + if (t.exists() && !t.delete()) throw new IOException("can't remove " + t); + } + + /** "boot guard: tripped|ok", then why (tripped only) and the counts */ + static List describe(Engine e) { + File hook = new File(e.data, "hook"); + List l = new ArrayList(); + String tripped = text(new File(hook, "tripped")); + String starts = text(new File(hook, "starts")); + int row = number(starts); + String why = null; + if (tripped != null) { + if (tripped.startsWith("boot ")) { + why = "Android had to start again " + MAXSTARTS + " times in one boot with HMG-API's hooks (it crashed or hung each time), " + + "so HMG-API turned its hooks off."; + } else if (tripped.startsWith("row ")) { + why = MAXBOOTS + " starts in a row with HMG-API's hooks didn't get to the home screen, so HMG-API turned its hooks off."; + } else { + why = "HMG-API's boot guard turned its hooks off (" + tripped.trim() + ")."; + } + } else if (row >= MAXBOOTS) { + why = MAXBOOTS + " starts in a row with HMG-API's hooks didn't get to the home screen, so HMG-API turns its hooks off."; + } + l.add("boot guard: " + (why != null ? "tripped" : "ok")); + if (why != null) l.add("why: " + why); + l.add("starts in a row that didn't boot: " + (starts == null ? "none" : starts.trim()) + " (off at " + MAXBOOTS + ")"); + String boot = text(new File(hook, "boot")), id = text(new File(e.root + "/proc/sys/kernel/random/boot_id")); + int inBoot = 0; + if (boot != null && id != null && boot.startsWith(id.trim() + " ")) inBoot = number(boot.substring(id.trim().length() + 1)); + l.add("starts this boot: " + inBoot + " (the " + (MAXSTARTS + 1) + "th runs without hooks)"); + if (tripped != null) l.add("tripped: " + tripped.trim()); + if (new File(hook, "disable").exists()) l.add("hook/disable: yes (hooks switched off by hand)"); + return l; + } + + private static String text(File f) { + try { + return f.isFile() ? Engine.read(f) : null; + } catch (IOException x) { + return null; + } + } + + private static int number(String s) { + if (s == null) return -1; + int i = 0, v = 0; + while (i < s.length() && Character.isDigit(s.charAt(i)) && v < 100000000) v = v * 10 + (s.charAt(i++) - '0'); + return i == 0 ? -1 : v; + } +} diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..c01e1368 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -146,7 +146,7 @@ static String ownsWhy(String types) { static java.io.RandomAccessFile lockFile; // held open (the lock goes with the process) 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; + if ("status".equals(cmd) || "map".equals(cmd) || "problem".equals(cmd) || "boot-guard".equals(cmd) || "1".equals(env(LOCKED_ENV, null))) 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(); @@ -374,6 +374,7 @@ int run(String[] args) throws Exception { if ("map-car".equals(cmd)) return MapProbe.run(this, args); 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 ("boot-guard".equals(cmd)) return BootGuard.run(this, args); if ("usb-scan".equals(cmd)) return UsbUpdates.scan(this); if ("publish-state".equals(cmd)) return LiveState.publish(this); if ("apps".equals(cmd)) return ModApps.sync(this); @@ -437,7 +438,7 @@ int run(String[] args) throws Exception { if (!map.runnable) out.add("hooks are off on this car (" + map.reason + "): mods apply without their hooks"); } if (!restoreAll && !"plan".equals(cmd) && !"apply".equals(cmd)) { - 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"); + 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] | boot-guard [reset] | usb-scan | update-hmgapi | publish-state | apps"); return 2; } Plan p = plan(restoreAll, force); diff --git a/core/runtime/java/hmgapi/engine/ProblemLog.java b/core/runtime/java/hmgapi/engine/ProblemLog.java index de0f0624..4b40ded6 100644 --- a/core/runtime/java/hmgapi/engine/ProblemLog.java +++ b/core/runtime/java/hmgapi/engine/ProblemLog.java @@ -314,11 +314,7 @@ static void hmgapiState(Engine e, StringBuilder s, String dmesg) { s.append("hook/enable: ").append(new File(hook, "enable").exists() ? "yes" : "no") .append(", hook/disable: ").append(new File(hook, "disable").exists() ? "yes (hooks switched off)" : "no") .append(", hook/starts: ").append(starts).append('\n'); - try { - if (Integer.parseInt(starts) >= 3) s.append("boot guard: hooks off (the zygote failed to start 3 times in a row with them; a reinstall of HMG-API resets it)\n"); - } catch (NumberFormatException ignored) { - // no number: nothing to say - } + for (String l : BootGuard.describe(e)) s.append(l).append('\n'); s.append("hook library: ").append(new File(e.root + "/system/lib/libhmgapi_hook.so").isFile() ? "there" : "absent").append('\n'); int n = 0; for (String l : dmesg.split("\n")) { diff --git a/core/runtime/problem-test.sh b/core/runtime/problem-test.sh index b7b83728..82b23781 100755 --- a/core/runtime/problem-test.sh +++ b/core/runtime/problem-test.sh @@ -123,7 +123,7 @@ printf 'Process: com.daudio.app.dipo\n\njava.lang.IllegalStateException: older\n printf 'Process: com.android.settings\nSubject: Input dispatching timed out\n' > "$R/data/system/dropbox/system_app_anr@1795114600000.txt" cp "$R/data/tombstones/tombstone_00" "$R/data/system/dropbox/system_app_native_crash@1795114500000.txt" printf 'unrelated' > "$R/data/system/dropbox/event_data@1795114400000.txt" -printf '3\n' > "$D/hook/starts"; : > "$D/hook/enable" +printf '3\n' > "$D/hook/starts"; printf 'boot 3 3\n' > "$D/hook/tripped"; : > "$D/hook/enable" cat > "$R/system/bin/dmesg" <<'X' #!/bin/sh echo "<6>[ 10.1] hmgapi-hook: zygote pid 120, hooks on, start 3" @@ -140,7 +140,8 @@ has "collect only: said so" "kept: no log lines (collected only)" "$out" f=$(cat "$D"/public/reports/problem-*.txt) hasnt "collect only: no log section" "== Log (" "$f" has "state: boot guard" "hook/starts: 3" "$f" -has "state: explained" "boot guard: hooks off" "$f" +has "state: explained" "boot guard: tripped" "$f" +has "state: why" "Android had to start again 3 times in one boot" "$f" has "state: HMG-API's kernel lines" "hooks off (boot guard, starts=3)" "$f" has "mods: the files it adds, absent here" "adds /system/lib/libleafiaaac.so absent" "$f" has "reports: counted by type" "system_server_crash=1" "$f" @@ -163,6 +164,24 @@ has "default: HMG-API's kernel lines" "hmgapi-hook: zygote pid 340" "$f" hasnt "default: no crash reports" "WifiApService" "$f" hasnt "default: no other kernel lines" "wlan0: associated" "$f" has "default: said so" "crash reports: not included" "$f" + +# engine boot-guard: what the app shows when its hooks aren't running, and the owner's reset +eng() { HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1; } +mkdir -p "$R/proc/sys/kernel/random"; echo 5e1d0c34-aaaa-4bbb-8ccc-000000000009 > "$R/proc/sys/kernel/random/boot_id" +echo "5e1d0c34-aaaa-4bbb-8ccc-000000000009 4" > "$D/hook/boot" +out=$(eng boot-guard) +has "boot-guard: tripped" "boot guard: tripped" "$out" +has "boot-guard: why, for the owner" "why: Android had to start again 3 times in one boot" "$out" +has "boot-guard: this boot's starts (by the current boot_id)" "starts this boot: 4" "$out" +printf 'row 6 0\n' > "$D/hook/tripped" +has "boot-guard: the other limit" "6 starts in a row with HMG-API's hooks didn't get to the home screen" "$(eng boot-guard)" +out=$(eng boot-guard reset) +has "boot-guard reset: said" "reset: hooks on again from the next restart" "$out" +has "... ok now" "boot guard: ok" "$out" +check "... starts 0, boot and tripped gone" "0 no no" "$(cat "$D/hook/starts") $([ -e "$D/hook/boot" ] && echo yes || echo no) $([ -e "$D/hook/tripped" ] && echo yes || echo no)" +printf '7\n' > "$D/hook/starts" +has "boot-guard: 6 in a row not yet tripped by the wrapper counts as tripped" "boot guard: tripped" "$(eng boot-guard)" +rm -rf "$R/proc" rm -rf "$R/data/system/dropbox" "$D/hook" "$R/system/bin/dmesg" # without --crash-dumps: none diff --git a/core/zygote/test.sh b/core/zygote/test.sh index 1fe28632..01415ee6 100755 --- a/core/zygote/test.sh +++ b/core/zygote/test.sh @@ -1,29 +1,54 @@ #!/bin/sh # Off-car test of the zygote wrapper under qemu-arm (binfmt): argument passthrough, -# the preload switch and the boot guard. +# the preload switch and the boot guard (counting, its watcher, failing closed). set -e cd "$(dirname "$0")" T=$(mktemp -d) trap 'rm -rf "$T"' EXIT -cat > "$T/stock" <<'S' +# The stock app_process stand-in. As the "zygote" (the wrapper execs it, so it keeps the +# wrapper's pid, which the watcher watches) it can fork the children the watcher looks for: +# SS=s a system_server after s seconds (none: unset) +# LA=s then a launcher after s more seconds, living LALIVE seconds (default 30) +# LALOOP=n then n launchers in turn, each living 0.3 s (a home screen that crash-loops) +# STAY=s the zygote lives s seconds, then exits (crashes) +cat > "$T/stock" </dev/null 2>&1 & + if [ -n "\$LA" ]; then (sleep "\$SS"; sleep "\$LA"; exec "$T/launcher" "\${LALIVE:-30}") /dev/null 2>&1 & fi + if [ -n "\$LALOOP" ]; then sleep "\$SS"; i=0; while [ \$i -lt "\$LALOOP" ]; do "$T/launcher" 0.3; i=\$((i + 1)); done; fi +fi +[ -n "\$STAY" ] && sleep "\$STAY" exit 0 S chmod +x "$T/stock" +# system_server and the launcher: a native program named by its path (its cmdline), a child +# of the stand-in; getprop answers what $T/boot_completed holds +printf '#include \n#include \nint main(int c, char **v) { double s = c > 1 ? atof(v[1]) : 1; struct timespec t = { (time_t)s, (long)((s - (long)s) * 1e9) }; nanosleep(&t, 0); return 0; }\n' > "$T/nap.c" +cc -O2 -o "$T/system_server" "$T/nap.c" +cp "$T/system_server" "$T/launcher" +printf '#!/bin/sh\ncat %s/boot_completed 2>/dev/null || echo\n' "$T" > "$T/getprop"; chmod +x "$T/getprop" +echo 1 > "$T/boot_completed" : > "$T/lib.so" mkdir -p "$T/hook" echo 5e1d0c34-aaaa-4bbb-8ccc-000000000001 > "$T/boot_id" # one kernel boot, until a test changes it . ../../tools/env.sh -clang $ARM_STATIC -DGUARD_DELAY=1 -DSTOCK="\"$T/stock\"" -DKMSG="\"$T/kmsg\"" -DHOOKDIR="\"$T/hook\"" -DHOOKLIB="\"$T/lib.so\"" -DHMGAPID="\"$T/hmgapid\"" -DBOOTID="\"$T/boot_id\"" \ +# the watcher's times, in ms: poll 0.2 s, booted after the launcher's 0.6 s, hung with no +# system_server at 1 s, given up at 3 s +clang $ARM_STATIC -DPOLL_MS=200 -DUP_MS=600 -DHANG_MS=1000 -DGIVEUP_MS=3000 \ + -DSTOCK="\"$T/stock\"" -DKMSG="\"$T/kmsg\"" -DHOOKDIR="\"$T/hook\"" -DHOOKLIB="\"$T/lib.so\"" -DHMGAPID="\"$T/hmgapid\"" -DBOOTID="\"$T/boot_id\"" \ + -DGETPROP="\"$T/getprop\"" -DSYSTEM_SERVER="\"$T/system_server\"" -DLAUNCHER="\"$T/launcher\"" \ -o "$T/wrap" zygote.c fail=0 check() { # name, expected-substring, actual case "$3" in *"$2"*) echo "ok $1" ;; *) echo "FAIL $1: wanted '$2' in: $3"; fail=1 ;; esac } run() { : > "$T/kmsg"; LD_PRELOAD=old.so "$T/wrap" "$@" 2>/dev/null; } +fresh() { rm -f "$T/hook/starts" "$T/hook/boot" "$T/hook/tripped" "$T/hook"/*.tmp "$T/hook/starts.w"; echo 0 > "$T/hook/starts"; } +there() { [ -e "$1" ] && echo yes || echo no; } +id() { echo "5e1d0c34-aaaa-4bbb-8ccc-00000000000$1" > "$T/boot_id"; } out=$(run -Xzygote /system/bin --zygote --start-system-server) check "passes arguments" "ARGS:-Xzygote /system/bin --zygote --start-system-server" "$out" @@ -35,6 +60,7 @@ out=$(run --zygote) check "enabled: preload set" "PRELOAD:$T/lib.so" "$out" check "start counter" "1" "$(cat "$T/hook/starts")" check "log says on" "hooks on, start 1" "$(cat "$T/kmsg")" +check "counters written through .tmp, none left" "no no" "$(there "$T/hook/starts.tmp") $(there "$T/hook/boot.tmp")" : > "$T/kmsg"; out=$(NO_ADDR_COMPAT_LAYOUT_FIXUP=1 LD_PRELOAD="$T/lib.so" "$T/wrap" --zygote 2>/dev/null) check "re-exec: preload kept" "PRELOAD:$T/lib.so" "$out" @@ -50,61 +76,139 @@ check "... and logs it" ", hmgapid, exec" "$(cat "$T/kmsg")" NO_ADDR_COMPAT_LAYOUT_FIXUP=1 "$T/wrap" --zygote >/dev/null 2>&1; "$T/wrap" /system/bin com.android.commands.am.Am >/dev/null 2>&1; sleep 0.3 check "re-exec and plain app_process don't" "" "$(cat "$T/hmgapid.ran")" rm "$T/hmgapid" "$T/hmgapid.ran" -echo 1 > "$T/hook/starts"; echo "$(cat "$T/boot_id") 1" > "$T/hook/boot" # one earlier start, in this boot out=$(run /system/bin com.android.commands.am.Am) check "not zygote: no preload" "PRELOAD:old.so" "$out" +fresh; echo 1 > "$T/hook/starts"; echo "$(cat "$T/boot_id") 1" > "$T/hook/boot" # one earlier start, in this boot run --zygote >/dev/null; run --zygote >/dev/null out=$(run --zygote) check "boot guard after 3 starts" "PRELOAD:old.so" "$out" check "log says boot guard" "boot guard, starts=3" "$(cat "$T/kmsg")" +check "... and it trips: which limit, the counts" "boot 3 3" "$(cat "$T/hook/tripped" 2>/dev/null)" -echo 0 > "$T/hook/starts"; rm -f "$T/hook/boot"; touch "$T/hook/disable" +fresh; touch "$T/hook/disable" out=$(run --zygote) check "disable file" "PRELOAD:old.so" "$out" rm "$T/hook/disable"; rm "$T/lib.so" out=$(run --zygote) check "missing lib" "hooks off (no $T/lib.so)" "$(cat "$T/kmsg")" - -# boot guard reset by the watcher: zygote alive past GUARD_DELAY -> starts=0 : > "$T/lib.so" -echo 0 > "$T/hook/starts"; rm -f "$T/hook/boot" -: > "$T/kmsg"; STAY=3 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1 & + +# ---- the watcher: a start counts until Android booted (system_server, the launcher up +# UP_MS, sys.boot_completed 1); hook/boot stays for the whole kernel boot +fresh +: > "$T/kmsg"; SS=0.1 LA=0.1 STAY=3 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1 & zp=$! sleep 0.4 check "watcher: counted" "1" "$(cat "$T/hook/starts")" -sleep 1.4 -check "watcher: reset while zygote alive" "0" "$(cat "$T/hook/starts")" +sleep 1.6 +check "watcher: reset once Android booted" "0" "$(cat "$T/hook/starts")" wait $zp -check "watcher: logged" "boot guard reset" "$(cat "$T/kmsg")" -check "watcher: this boot's count gone too" no "$([ -e "$T/hook/boot" ] && echo yes || echo no)" -echo 0 > "$T/hook/starts" +check "watcher: logged" "booted ($T/launcher up 0 s, boot completed)" "$(sed 's/up [0-9]* s/up 0 s/' "$T/kmsg")" +check "watcher: this boot's count kept" "$(cat "$T/boot_id") 1" "$(cat "$T/hook/boot" 2>/dev/null)" -# the boot guard tells a crash loop (one kernel boot) from restarts (a new boot_id each) -id() { echo "5e1d0c34-aaaa-4bbb-8ccc-00000000000$1" > "$T/boot_id"; } -echo 0 > "$T/hook/starts"; rm -f "$T/hook/boot"; id 1 +# the review's late crash: Android booted each time, then died (STAY), in one kernel boot +fresh +for n in 1 2 3; do + SS=0.1 LA=0.1 STAY=2 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; sleep 0.3 +done +check "late crashes: each booted, so the row count is back to 0" "0" "$(cat "$T/hook/starts")" +out=$(run --zygote) +check "late crashes: 3 starts in one boot, the 4th has no hooks" "PRELOAD:old.so" "$out" +check "... logged" "boot guard, starts=0, this boot 3" "$(cat "$T/kmsg")" +check "... tripped" "boot 0 3" "$(cat "$T/hook/tripped" 2>/dev/null)" + +# tripped stays: a new kernel boot doesn't lift it, and nothing more is counted +id 2; out=$(run --zygote) +check "tripped: still off in a new boot" "PRELOAD:old.so" "$out" +check "... logged" "hooks off (boot guard tripped earlier" "$(cat "$T/kmsg")" +check "... not counted" "5e1d0c34-aaaa-4bbb-8ccc-000000000001 4" "$(cat "$T/hook/boot")" +fresh; out=$(run --zygote) +check "reset (starts 0, no boot, no tripped): on again" "PRELOAD:$T/lib.so" "$out" +id 1 + +# not booted: no reset, the start stays counted +fresh; echo 0 > "$T/boot_completed" +SS=0.1 LA=0.1 STAY=1.8 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; sleep 0.3 +check "boot never completed: still counted" "1" "$(cat "$T/hook/starts")" +echo 1 > "$T/boot_completed" +fresh +SS=0.1 LALOOP=5 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; sleep 0.3 +check "launcher crash-looping (never up 0.6 s): still counted" "1" "$(cat "$T/hook/starts")" +fresh +SS=0.1 LA=0.1 LALIVE=0.3 STAY=1.8 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; sleep 0.3 +check "launcher died before it was up 0.6 s: still counted" "1" "$(cat "$T/hook/starts")" +fresh +: > "$T/kmsg"; SS=0.1 STAY=4.5 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; sleep 0.3 +check "no launcher at all: given up at GIVEUP_MS, still counted" "1" "$(cat "$T/hook/starts")" +check "... logged" "not booted in 3 s, counted as a failed start" "$(cat "$T/kmsg")" +fresh +: > "$T/kmsg"; STAY= LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1 +sleep 1 +check "watcher: no reset after zygote died" "1" "$(cat "$T/hook/starts")" + +# a hang before system_server (a mod's zygoteInit): stopped at HANG_MS, so it counts in this boot +fresh +: > "$T/kmsg"; s=$(date +%s) +set +e; STAY=6 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; rc=$?; set -e +check "hang: the watcher stops the zygote (SIGKILL)" "137" "$rc" +check "... soon after HANG_MS, not when it would have ended" "yes" "$([ $(($(date +%s) - s)) -lt 4 ] && echo yes || echo no)" +check "... logged" "has no $T/system_server after 1 s (hung before it" "$(cat "$T/kmsg")" +check "... counted" "1" "$(cat "$T/hook/starts")" +for n in 2 3; do set +e; STAY=6 LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1; set -e; done +out=$(run --zygote) +check "3 hangs in one boot: the 4th start has no hooks (Android starts)" "PRELOAD:old.so" "$out" +check "... tripped" "boot 3 3" "$(cat "$T/hook/tripped" 2>/dev/null)" + +# ---- the boot guard tells a crash loop (one kernel boot) from restarts (a new boot_id each) +fresh; id 1 run --zygote >/dev/null; run --zygote >/dev/null; run --zygote >/dev/null out=$(run --zygote) check "crash loop in one boot: off after 3" "PRELOAD:old.so" "$out" check "... logged with this boot's count" "boot guard, starts=3, this boot 3" "$(cat "$T/kmsg")" check "... this boot's count kept" "5e1d0c34-aaaa-4bbb-8ccc-000000000001 4" "$(cat "$T/hook/boot")" -echo 0 > "$T/hook/starts"; rm -f "$T/hook/boot" +fresh for n in 1 2 3 4 5 6; do id $n; out=$(run --zygote); done check "6 short restarts (6 boots): hooks still on" "PRELOAD:$T/lib.so" "$out" check "... logged as the first start of its boot" "hooks on, start 6 (this boot 1)" "$(cat "$T/kmsg")" id 7; out=$(run --zygote) -check "the 7th in a row: off (a restart loop)" "PRELOAD:old.so" "$out" +check "the 7th in a row: off (a restart loop, or 6 boots that hung)" "PRELOAD:old.so" "$out" check "... logged" "boot guard, starts=6, this boot 0" "$(cat "$T/kmsg")" -echo 0 > "$T/hook/starts"; rm -f "$T/hook/boot" "$T/boot_id" +check "... tripped" "row 6 0" "$(cat "$T/hook/tripped" 2>/dev/null)" +fresh; rm -f "$T/boot_id" run --zygote >/dev/null; run --zygote >/dev/null; run --zygote >/dev/null out=$(run --zygote) check "no boot_id: every start counts, off after 3 as before" "PRELOAD:old.so" "$out" -check "... no boot file written" no "$([ -e "$T/hook/boot" ] && echo yes || echo no)" -echo 0 > "$T/hook/starts" -: > "$T/kmsg"; STAY= LD_PRELOAD=old.so "$T/wrap" --zygote >/dev/null 2>&1 -sleep 2 -check "watcher: no reset after zygote died" "1" "$(cat "$T/hook/starts")" +check "... no boot file written" no "$(there "$T/hook/boot")" +id 1 + +# ---- fail closed: a counter that can't be read or written in full means no hooks +for f in starts.tmp boot.tmp; do + fresh; ln -s /dev/full "$T/hook/$f" + out=$(run --zygote) + check "write error ($f on a full disk): no hooks" "PRELOAD:old.so" "$out" + check "... logged" "hooks off (can't read or write the boot guard's counters)" "$(cat "$T/kmsg")" +done +check "... the half-written temp file removed" no "$(there "$T/hook/boot.tmp")" +fresh; ln -sf /dev/full "$T/hook/starts"; ln -sf /dev/full "$T/hook/boot" +n=0; on=0 +while [ $n -lt 10 ]; do out=$(run --zygote); case "$out" in *"PRELOAD:$T/lib.so"*) on=$((on + 1)) ;; esac; n=$((n + 1)); done +check "the review's case (counters on /dev/full, 10 starts): hooks on none" "0" "$on" +fresh; rm "$T/hook/starts"; mkdir "$T/hook/starts" +out=$(run --zygote) +check "starts unreadable (a directory): no hooks" "PRELOAD:old.so" "$out" +rmdir "$T/hook/starts"; fresh; printf 'x\n' > "$T/hook/starts" +out=$(run --zygote) +check "starts not a number: no hooks" "PRELOAD:old.so" "$out" +fresh; : > "$T/hook/starts" +out=$(run --zygote) +check "starts empty: no hooks" "PRELOAD:old.so" "$out" +fresh; rm "$T/hook/starts" +out=$(run --zygote) +check "starts absent: from 0, hooks on" "PRELOAD:$T/lib.so" "$out" +check "... written with a newline" "1" "$(cat "$T/hook/starts")" +fresh rm "$T/stock" : > "$T/kmsg"; set +e; "$T/wrap" --zygote 2>/dev/null; rc=$?; set -e diff --git a/core/zygote/zygote.c b/core/zygote/zygote.c index cd4f071d..78acc6b3 100644 --- a/core/zygote/zygote.c +++ b/core/zygote/zygote.c @@ -7,19 +7,34 @@ * /data/hmgapi/hook/enable exists (step 2 creates it) * /data/hmgapi/hook/disable is absent (manual off switch) * /system/lib/libhmgapi_hook.so exists + * /data/hmgapi/hook/tripped is absent (the boot guard hasn't turned them off) * boot guard: fewer than MAXSTARTS (3) earlier starts in this kernel boot, and - * fewer than MAXBOOTS (6) in a row overall, that didn't last GUARD_DELAY - * Boot guard: /data/hmgapi/hook/starts counts the starts in a row that didn't last, - * across restarts; /data/hmgapi/hook/boot holds the kernel's boot_id and the count - * within that boot. A crash loop from a hook happens within one boot (on 4.4 a - * system_server crash kills the zygote and init starts it again), so 3 there turn - * the hooks off. A head unit restarted or switched off within GUARD_DELAY of - * starting (installs, applies, the car turned off) is a new boot: those count - * only toward MAXBOOTS, which still stops a loop of full restarts. With no - * boot_id, every start counts as the same boot (MAXSTARTS overall, as before). - * Reset: with hooks on, a watcher (double-forked, so init adopts it and the - * zygote never sees it exit) waits GUARD_DELAY seconds and, if this zygote pid is - * still alive, writes 0 to starts and removes boot: the start worked. + * fewer than MAXBOOTS (6) earlier starts in a row that didn't boot + * Boot guard: /data/hmgapi/hook/starts counts the starts in a row that didn't boot + * (reach the home screen), across restarts; /data/hmgapi/hook/boot holds the + * kernel's boot_id and every start within that boot, booted or not. On 4.4 a + * system_server crash kills the zygote and init starts it again in the same boot, + * so a crash loop from a hook, early or late (a phone connecting, CarPlay + * starting, an hour into a drive), shows there: the 4th start in one boot runs + * without hooks. A QuickBoot suspend and wake is the same boot with no new start. + * A head unit restarted or switched off before it booted (installs, applies, the + * car turned off) is a new boot: those count only toward MAXBOOTS, which still + * stops a loop of full restarts, and a boot that hangs. With no boot_id, every + * start counts as the same boot (MAXSTARTS overall). + * When either limit is reached the wrapper writes hook/tripped ("boot S B" or + * "row S B": which limit, the two counts) and from then on starts without hooks, + * counting nothing, until the owner resets it (the app, a reinstall, or removing + * hook/tripped, hook/boot and writing 0 to hook/starts). + * Fails closed: a counter that can't be read or written in full (to a .tmp file, + * fsync, rename) means no hooks for this start. + * Booted: with hooks on, a watcher (double-forked, so init adopts it and the zygote + * never sees it exit) polls every POLL_MS. Once this zygote has a system_server + * child, a launcher child (LAUNCHER) that has been up UP_MS, and + * sys.boot_completed is 1 (getprop), the start booted: it writes 0 to starts and + * exits. hook/boot stays: it goes only with a new kernel boot. No system_server + * after HANG_MS means the zygote hung before forking it (a mod's zygoteInit): the + * watcher kills the zygote, init starts it again, and that start counts. Not booted + * after GIVEUP_MS: the watcher exits and the start stays counted. * Stock ARM app_process re-execs /system/bin/app_process once with * NO_ADDR_COMPAT_LAYOUT_FIXUP=1 (ADDR_COMPAT_LAYOUT personality), so the zygote * passes through here twice per start. Only the first pass counts and sets the @@ -55,20 +70,45 @@ typedef unsigned long ul; #ifndef BOOTID #define BOOTID "/proc/sys/kernel/random/boot_id" #endif +#ifndef GETPROP +#define GETPROP "/system/bin/getprop" +#endif +#ifndef PROC +#define PROC "/proc" +#endif +#ifndef SYSTEM_SERVER +#define SYSTEM_SERVER "system_server" +#endif +#ifndef LAUNCHER +#define LAUNCHER "com.android.launcher3" /* every Gen5W build mapped so far (maps/base/launcher.json) */ +#endif #define MAXSTARTS 3 /* in one kernel boot */ #define MAXBOOTS 6 /* in a row, across restarts */ -#ifndef GUARD_DELAY -#define GUARD_DELAY 120 +/* the watcher's times, counted in its polls (so a busy unit only makes them longer) */ +#ifndef POLL_MS +#define POLL_MS 2000 +#endif +#ifndef UP_MS +#define UP_MS 30000 /* the launcher up this long (and the boot completed): booted */ +#endif +#ifndef HANG_MS +#define HANG_MS 120000 /* no system_server by then: hung (a normal start forks it within ~3 s) */ +#endif +#ifndef GIVEUP_MS +#define GIVEUP_MS 1800000 /* not booted in 30 minutes: stop watching, the start stays counted */ #endif #define MAXENV 256 -static long sys3(long n, long a, long b, long c) +/* EABI system call numbers only (CLAUDE.md): the head units answer -ENOSYS to OABI ones */ +static long sys4(long n, long a, long b, long c, long d) { register long r7 asm("r7") = n; register long r0 asm("r0") = a; register long r1 asm("r1") = b; register long r2 asm("r2") = c; - asm volatile("svc 0" : "+r"(r0) : "r"(r7), "r"(r1), "r"(r2) : "memory"); + register long r3 asm("r3") = d; + asm volatile("svc 0" : "+r"(r0) : "r"(r7), "r"(r1), "r"(r2), "r"(r3) : "memory"); return r0; } +static long sys3(long n, long a, long b, long c) { return sys4(n, a, b, c, 0); } static long xopen(const char *p, int fl, int m) { return sys3(5, (long)p, fl, m); } static long xread(int fd, void *b, ul n) { return sys3(3, fd, (long)b, n); } static long xwrite(int fd, const void *b, ul n) { return sys3(4, fd, (long)b, n); } @@ -77,11 +117,18 @@ static long xexecve(const char *p, char **av, char **ev) { return sys3(11, (long static long xfork(void) { return sys3(2, 0, 0, 0); } static long xgetpid(void) { return sys3(20, 0, 0, 0); } static void xexit(int c) { sys3(1, c, 0, 0); for (;;) ; } -static void xsleep(long s) { long ts[2] = { s, 0 }; sys3(162, (long)ts, 0, 0); } +static void xsleep_ms(long ms) { long ts[2] = { ms / 1000, (ms % 1000) * 1000000 }; sys3(162, (long)ts, 0, 0); } static void xunlink(const char *p) { sys3(10, (long)p, 0, 0); } +static long xrename(const char *a, const char *b) { return sys3(38, (long)a, (long)b, 0); } +static long xfsync(int fd) { return sys3(118, fd, 0, 0); } +static long xclose_rc(int fd) { return sys3(6, fd, 0, 0); } +static void xwait(long pid) { sys4(114, pid, 0, 0, 0); } /* wait4(pid, NULL, 0, NULL) */ +static void xkill(long pid, int sig) { sys3(37, pid, sig, 0); } #define O_RDONLY 0 #define O_WRONLY 1 #define O_WR 0x241 /* O_WRONLY|O_CREAT|O_TRUNC */ +#define O_DIRECTORY 0x4000 /* ARM */ +#define ENOENT 2 static ul slen(const char *s) { ul n = 0; while (s[n]) n++; return n; } static int seq(const char *a, const char *b) { while (*a && *a == *b) a++, b++; return *a == *b; } @@ -106,17 +153,20 @@ static void flush(void) lpos = 0; } -/* the number at the start of a file, or 0 (absent, empty, not a number) */ -static long readnum(const char *path, char *buf, ul size, long *len) +/* A counter file: its number (0 when the file is absent), or -1 when it can't be read + or doesn't start with a number: fail closed. len gets the bytes read. */ +static long readcount(const char *path, char *buf, ul size, long *len) { - long fd = xopen(path, O_RDONLY, 0), n = 0, v = 0, i; - if (fd >= 0) { - n = xread(fd, buf, size); - xclose(fd); - if (n < 0) n = 0; - } - if (len) *len = n; - for (i = 0; i < n && buf[i] >= '0' && buf[i] <= '9'; i++) v = v * 10 + (buf[i] - '0'); + long fd = xopen(path, O_RDONLY, 0), n, v = 0, i; + *len = 0; + if (fd == -ENOENT) return 0; + if (fd < 0) return -1; + n = xread(fd, buf, size); + xclose(fd); + if (n <= 0) return -1; + *len = n; + if (buf[0] < '0' || buf[0] > '9') return -1; + for (i = 0; i < n && buf[i] >= '0' && buf[i] <= '9' && v < 100000000; i++) v = v * 10 + (buf[i] - '0'); return v; } static void putnum(char *t, int *k, long v) @@ -126,15 +176,31 @@ static void putnum(char *t, int *k, long v) while (i) t[(*k)++] = d[--i]; } +/* Writes n bytes to path, whole or not at all: to tmp, fsync, then rename over path + (a power cut leaves the old file or the new one, never a short one). 0, or -1. */ +static int put_file(const char *path, const char *tmp, const char *s, long n) +{ + long fd = xopen(tmp, O_WR, 0600), r; + if (fd < 0) return -1; + r = xwrite(fd, s, n); + if (r == n && xfsync(fd) < 0) r = -1; + if (xclose_rc(fd) < 0) r = -1; + if (r != n || xrename(tmp, path) < 0) { xunlink(tmp); return -1; } + fd = xopen(HOOKDIR, O_RDONLY | O_DIRECTORY, 0); /* the rename itself to disk: best effort */ + if (fd >= 0) { xfsync(fd); xclose(fd); } + return 0; +} + /* Bumps both counters (in a row: starts; this boot: boot). Returns the in-a-row count - before this start, or -1 when it can't be written; *inboot gets this boot's count - before this start (the in-a-row one when there's no boot_id). */ + before this start, or -1 when a counter can't be read or written in full; *inboot gets + this boot's count before this start (the in-a-row one when there's no boot_id). */ static long bump_starts(long *inboot) { static char b[16], id[48], saved[96]; long fd, v, idn = 0, sn = 0, i, k; int same, w; - v = readnum(HOOKDIR "/starts", b, sizeof b, 0); + v = readcount(HOOKDIR "/starts", b, sizeof b, &sn); + if (v < 0) return -1; fd = xopen(BOOTID, O_RDONLY, 0); if (fd >= 0) { idn = xread(fd, id, sizeof id - 1); @@ -142,72 +208,194 @@ static long bump_starts(long *inboot) if (idn < 0) idn = 0; while (idn > 0 && (id[idn - 1] == '\n' || id[idn - 1] == ' ')) idn--; } + sn = 0; fd = xopen(HOOKDIR "/boot", O_RDONLY, 0); if (fd >= 0) { sn = xread(fd, saved, sizeof saved - 1); xclose(fd); - if (sn < 0) sn = 0; - } + if (sn < 0) return -1; + } else if (fd != -ENOENT) return -1; saved[sn] = 0; /* hook/boot: " " */ same = idn > 0 && sn > idn && saved[idn] == ' '; for (i = 0; same && i < idn; i++) if (saved[i] != id[i]) same = 0; if (idn == 0) *inboot = v; - else if (same) { *inboot = 0; for (k = idn + 1; k < sn && saved[k] >= '0' && saved[k] <= '9'; k++) *inboot = *inboot * 10 + (saved[k] - '0'); } + else if (same) { *inboot = 0; for (k = idn + 1; k < sn && saved[k] >= '0' && saved[k] <= '9' && *inboot < 100000000; k++) *inboot = *inboot * 10 + (saved[k] - '0'); } else *inboot = 0; - fd = xopen(HOOKDIR "/starts", O_WR, 0600); - if (fd < 0) return -1; - { char t[12]; int n = 0; putnum(t, &n, v + 1); xwrite(fd, t, n); } - xclose(fd); + { char t[16]; int n = 0; putnum(t, &n, v + 1); t[n++] = '\n'; + if (put_file(HOOKDIR "/starts", HOOKDIR "/starts.tmp", t, n) < 0) return -1; } if (idn > 0) { - fd = xopen(HOOKDIR "/boot", O_WR, 0600); - if (fd >= 0) { - w = 0; - for (i = 0; i < idn && w < (int)sizeof saved - 14; i++) saved[w++] = id[i]; - saved[w++] = ' '; - putnum(saved, &w, *inboot + 1); - saved[w++] = '\n'; - xwrite(fd, saved, w); - xclose(fd); - } + w = 0; + for (i = 0; i < idn && w < (int)sizeof saved - 14; i++) saved[w++] = id[i]; + saved[w++] = ' '; + putnum(saved, &w, *inboot + 1); + saved[w++] = '\n'; + if (put_file(HOOKDIR "/boot", HOOKDIR "/boot.tmp", saved, w) < 0) return -1; } return v; } -static int alive(long pid) + +/* the guard tripped: "boot|row ", kept until the owner resets it */ +static void trip(const char *why, long starts, long inboot) +{ + char t[40]; int n = 0; + while (*why) t[n++] = *why++; + t[n++] = ' '; putnum(t, &n, starts); t[n++] = ' '; putnum(t, &n, inboot); t[n++] = '\n'; + if (put_file(HOOKDIR "/tripped", HOOKDIR "/tripped.tmp", t, n) < 0) put(" (can't write tripped)"); +} + +static int procpath(char *p, long pid, const char *what) { - char p[24] = "/proc/", c; - int i = 6, k = 0; char t[12]; long fd, n; + const char *s = PROC "/"; + int i = 0, k = 0; char t[12]; + while (*s) p[i++] = *s++; do t[k++] = '0' + pid % 10; while ((pid /= 10) && k < 11); while (k) p[i++] = t[--k]; + p[i++] = '/'; + while (*what) p[i++] = *what++; p[i] = 0; - { const char *s = "/cmdline"; while (*s) p[i++] = *s++; p[i] = 0; } + return i; +} +static int alive(long pid) +{ + char p[64], c; + long fd, n; + procpath(p, pid, "cmdline"); fd = xopen(p, O_RDONLY, 0); if (fd < 0) return 0; n = xread(fd, &c, 1); /* a zombie has an empty cmdline */ xclose(fd); return n == 1; } +/* pid's parent (from /proc//stat, after the name's last ')'), or -1 */ +static long ppid_of(long pid) +{ + static char b[256]; + char p[64]; + long fd, n, i, j, v = 0; + procpath(p, pid, "stat"); + fd = xopen(p, O_RDONLY, 0); + if (fd < 0) return -1; + n = xread(fd, b, sizeof b - 1); + xclose(fd); + if (n <= 0) return -1; + for (i = n - 1; i > 0 && b[i] != ')'; i--) ; + if (i == 0) return -1; + for (j = i + 1; j < n && b[j] == ' '; j++) ; /* ") S ppid" */ + for (; j < n && b[j] != ' '; j++) ; + for (; j < n && b[j] == ' '; j++) ; + if (j >= n || b[j] < '0' || b[j] > '9') return -1; + for (; j < n && b[j] >= '0' && b[j] <= '9'; j++) v = v * 10 + (b[j] - '0'); + return v; +} +/* pid is a child of parent named name (its cmdline's first string) */ +static int child_named(long pid, long parent, const char *name) +{ + static char b[128]; + char p[64]; + long fd, n; + if (ppid_of(pid) != parent) return 0; + procpath(p, pid, "cmdline"); + fd = xopen(p, O_RDONLY, 0); + if (fd < 0) return 0; + n = xread(fd, b, sizeof b - 1); + xclose(fd); + if (n <= 0) return 0; + b[n] = 0; + return seq(b, name); +} +/* a child of parent named name, or 0 */ +static long find_child(long parent, const char *name) +{ + static char d[4096]; + long fd = xopen(PROC, O_RDONLY | O_DIRECTORY, 0), n, off, pid, found = 0; + if (fd < 0) return 0; + while (!found && (n = sys3(217, fd, (long)d, sizeof d)) > 0) { /* getdents64 */ + for (off = 0; off < n && !found; off += *(unsigned short *)(d + off + 16)) { + const char *nm = d + off + 19; + pid = 0; + while (*nm >= '0' && *nm <= '9') pid = pid * 10 + (*nm++ - '0'); + if (*nm || pid <= 0) continue; + if (child_named(pid, parent, name)) found = pid; + } + } + xclose(fd); + return found; +} +/* sys.boot_completed is 1 (getprop's answer: no libc here to read the property area) */ +static int boot_completed(char **ev) +{ + static char *av[] = { GETPROP, "sys.boot_completed", 0 }; + int p[2]; + char c[4]; + long pid, n = 0; + if (sys3(42, (long)p, 0, 0) < 0) return 0; /* pipe */ + pid = xfork(); + if (pid == 0) { + sys3(63, p[1], 1, 0); /* dup2 to stdout */ + xclose(p[0]); xclose(p[1]); + xexecve(GETPROP, av, ev); + xexit(127); + } + xclose(p[1]); + if (pid > 0) n = xread(p[0], c, sizeof c); + xclose(p[0]); + if (pid > 0) xwait(pid); + return n >= 1 && c[0] == '1' && (n == 1 || c[1] == '\n'); +} + +static void reset_starts(void) +{ + if (put_file(HOOKDIR "/starts", HOOKDIR "/starts.w", "0\n", 2) < 0) put(", can't write starts"); +} /* Double fork: the middle child exits at once and is reaped here, before the - exec, so the zygote never gets a SIGCHLD for it. */ -static void start_watcher(void) + exec, so the zygote never gets a SIGCHLD for it. The watcher's own children + (getprop) are its own to reap. */ +static void start_watcher(char **ev) { long zpid = xgetpid(), pid = xfork(); if (pid == 0) { if (xfork() == 0) { - long fd; + long t, ss = 0, la = 0, since = 0, fd; sys3(66, 0, 0, 0); /* setsid */ - xsleep(GUARD_DELAY); - if (!alive(zpid)) xexit(0); - fd = xopen(HOOKDIR "/starts", O_WR, 0600); - if (fd >= 0) { xwrite(fd, "0", 1); xclose(fd); } - xunlink(HOOKDIR "/boot"); - put("<6>hmgapi-hook: zygote "); putn(zpid); put(" up "); putn(GUARD_DELAY); - put(" s, boot guard reset"); flush(); + /* none of the zygote's fds (its socket from init, a caller's pipe): /dev/null on 0-2 */ + for (fd = 3; fd < 1024; fd++) xclose(fd); + fd = xopen("/dev/null", 2, 0); /* O_RDWR */ + if (fd >= 0) { sys3(63, fd, 0, 0); sys3(63, fd, 1, 0); sys3(63, fd, 2, 0); if (fd > 2) xclose(fd); } + for (t = POLL_MS; ; t += POLL_MS) { + xsleep_ms(POLL_MS); + if (!alive(zpid)) xexit(0); /* it died: this start stays counted */ + if (t > GIVEUP_MS) { + put("<4>hmgapi-hook: zygote "); putn(zpid); put(" not booted in "); putn(GIVEUP_MS / 1000); + put(" s, counted as a failed start"); flush(); + xexit(0); + } + if (!ss) ss = find_child(zpid, SYSTEM_SERVER); + if (!ss) { + if (t < HANG_MS) continue; + put("<3>hmgapi-hook: zygote "); putn(zpid); put(" has no " SYSTEM_SERVER " after "); putn(t / 1000); + put(" s (hung before it: a mod's zygoteInit?), stopping it; the next start counts"); flush(); + xkill(zpid, 9); + xexit(0); + } + if (la && !child_named(la, zpid, LAUNCHER)) la = 0; /* it died: from 0 again */ + if (!la) { + la = find_child(zpid, LAUNCHER); + since = t; + continue; + } + if (t - since < UP_MS || !boot_completed(ev)) continue; + put("<6>hmgapi-hook: zygote "); putn(zpid); put(" booted ("); put(LAUNCHER); put(" up "); + putn((t - since) / 1000); put(" s, boot completed) at "); putn(t / 1000); put(" s, starts reset"); + reset_starts(); + flush(); + xexit(0); + } } xexit(0); } - if (pid > 0) sys3(114, pid, 0, 0); /* wait4(pid, NULL, 0, NULL) */ + if (pid > 0) xwait(pid); } /* hmgapid daemon, double-forked like the watcher (it detaches by itself too) */ @@ -222,7 +410,7 @@ static void start_hmgapid(char **ev) } xexit(0); } - if (pid > 0) sys3(114, pid, 0, 0); + if (pid > 0) xwait(pid); } static char *env[MAXENV]; @@ -244,11 +432,13 @@ int main(int argc, char **argv, char **envp) else if (zygote && exists(HOOKDIR "/enable")) { if (exists(HOOKDIR "/disable")) put(", hooks off (disable file)"); else if (!exists(HOOKLIB)) put(", hooks off (no " HOOKLIB ")"); + else if (exists(HOOKDIR "/tripped")) put(", hooks off (boot guard tripped earlier: hook/tripped)"); else { starts = bump_starts(&inboot); - if (starts < 0) put(", hooks off (can't write starts)"); + if (starts < 0) put(", hooks off (can't read or write the boot guard's counters)"); else if (inboot >= MAXSTARTS || starts >= MAXBOOTS) { put(", hooks off (boot guard, starts="); putn(starts); put(", this boot "); putn(inboot); put(")"); + trip(inboot >= MAXSTARTS ? "boot" : "row", starts, inboot); } else { use = 1; put(", hooks on, start "); putn(starts + 1); put(" (this boot "); putn(inboot + 1); put(")"); } } @@ -256,13 +446,13 @@ int main(int argc, char **argv, char **envp) for (i = 0; envp[i] && n < MAXENV - 2; i++) if (!(use && spre(envp[i], "LD_PRELOAD="))) env[n++] = envp[i]; - if (use) env[n++] = preload; env[n] = 0; if (zygote && !reexec && exists(HMGAPID)) put(", hmgapid"); put(", exec " STOCK); flush(); - if (use) start_watcher(); + if (use) start_watcher(env); /* getprop gets the environment without the preload */ + if (use) { env[n++] = preload; env[n] = 0; } if (zygote && !reexec && exists(HMGAPID)) start_hmgapid(envp); rc = xexecve(STOCK, argv, env); put("<3>hmgapi-hook: exec " STOCK " failed, errno "); diff --git a/install/common/install.sh b/install/common/install.sh index bc889914..02f623be 100644 --- a/install/common/install.sh +++ b/install/common/install.sh @@ -287,7 +287,7 @@ REMOUNTED= # hooks on at the next restart (the zygote wrapper's boot guard counts from 0) echo 0 > "$D/hook/starts" -rm -f "$D/hook/boot" "$D/hook/disable" +rm -f "$D/hook/boot" "$D/hook/tripped" "$D/hook/disable" : > "$D/hook/enable" # what's installed, for uninstall.sh and the app diff --git a/wiki/Troubleshooting.md b/wiki/Troubleshooting.md index c3fe9aef..e3b1b160 100644 --- a/wiki/Troubleshooting.md +++ b/wiki/Troubleshooting.md @@ -45,17 +45,31 @@ The first time a mod uses a car command, HMG-API asks you on screen. If you said ## The head unit restarted over and over -When Android fails to start three times during one boot with HMG-API's hooks (a -hook crashing the system), or the head unit restarts six times in a row less than -two minutes after starting, HMG-API turns its hooks off by itself so the head unit -starts normally, and the app says the hooks aren't running. Turn off or remove the -mod you added last, then reset the counter and restart: reinstall HMG-API from the -app (Check USB updates, Reinstall HMG-API), or over adb: +HMG-API's boot guard turns its hooks off by itself, so the head unit starts +normally without them, when either happens: + +- Android has to start again three times in one boot of the head unit with + HMG-API's hooks: it crashed or hung each time. Any time counts, not only while + it starts: a phone connecting, CarPlay starting, an hour into a drive. +- Six starts in a row with the hooks don't get to the home screen (the head unit + restarted or was switched off before, or it hung on a black screen). + +A start counts as good once the home screen has been up for 30 seconds. A hang +before Android gets going (no system server after two minutes) is stopped and +counts as a failed start. + +The hooks then stay off, through restarts, until you reset the guard. The app +says "Hooks off: boot guard" at the top; tap it to see which limit was reached. +Turn off or remove the mod you added or changed last, then tap **Reset and +restart**. Reinstalling HMG-API resets it too, or over adb: ``` -adb shell "hmgapid sh 'echo 0 > /data/hmgapi/hook/starts; rm -f /data/hmgapi/hook/boot'" +adb shell hmgapid engine boot-guard reset ``` +and restart the head unit. If Android fails again, the guard turns the hooks off +again; a [Car Report](Car-Report) helps find which mod. + ## A mod isn't doing anything - Is it switched on, and did you **Apply changes**? From e5c9543fae83170f094a2e58293a787f4242c7ef Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:28:17 -0500 Subject: [PATCH 19/69] Engine: journal settings, props and binds; checked backups; room checks Recover now puts back the settings, live props and binds an apply or trial changed, not only its files: a trial's persist.* prop stayed set after "trial undone", and the next apply took it for stock. Stock backups are copied beside, checked against the stock md5, then renamed, as install.sh's backup() does. An app's odex backup has its md5 recorded, and every backup is checked before a restore or rebuild; a NEMESIS copy with the recorded md5 stands in for a damaged one, else the engine stops and names it. The journal's saved copies are checked the same way. An apply checks room on /system and /data before writing anything; recover removes a cut-off copy, and on a full /system the file, before its saved copy goes back. A damaged journal, or a saved copy that's gone, is set aside (state/journal.bad.json) instead of failing at every start. build.prop and live props refuse dalvik.* and persist.sys.dalvik.* without overrides.allow_critical; CRITICAL takes framework-res.apk, libz, libcrypto, the ICU files, libgui, libEGL, lib/hw and lib/egl, and the boot daemons Android waits for. update-hmgapi refuses while a journal is pending. The Dalvik cache clean-up touches only the app's own entry, priv-app included. Tests: core/runtime/journal-test.sh, plus safety-test.sh and usb-test.sh. Off-car only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 31 ++ core/runtime/java/hmgapi/engine/Engine.java | 513 +++++++++++++++--- .../java/hmgapi/engine/UsbUpdates.java | 16 + core/runtime/journal-test.sh | 255 +++++++++ core/runtime/safety-test.sh | 32 ++ core/runtime/usb-test.sh | 6 + tools/test-all.sh | 4 +- tools/test-select.py | 4 +- 8 files changed, 790 insertions(+), 71 deletions(-) create mode 100644 core/runtime/journal-test.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..33b9898f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## Unreleased + +- **An undone trial or a cut-off apply puts settings, live props and binds back too.** The + journal kept only files and the state, so a trial's `persist.*` prop (or one set by an apply + cut off after its settings) stayed set after "trial undone", the next apply took it for stock, + and `engine restore` left it set. `binds.txt` wasn't rolled back either. The journal now keeps + each one's value before, and `engine recover` writes them back. +- **Stock backups are checked before every use.** They're taken as the installer takes its + own: copied beside, checked against the stock md5, then renamed, so a cut-off copy never sits + under the backup's name. An app's odex backup has its md5 recorded now. A restore, uninstall or + rebuild never writes a backup that isn't the recorded md5 (a short odex under a stock apk with + no `classes.dex` crashed that app at every launch): a NEMESIS copy with that md5 stands in, or + the engine stops and names the backup and the md5 it should have. +- **Room is checked before an apply** writes anything, on `/system` and `/data`. If `/system` + filled up anyway, `engine recover` removes the cut-off copy first and, when there's still no + room, the file before its saved copy goes back, instead of failing at every start. +- **A damaged journal, or a saved copy that's gone, no longer blocks everything.** `engine + recover` sets the journal aside (`state/journal.bad.json`) and says so; `engine status` and + `engine keep` say what's wrong instead of failing. +- **More is refused unless `hmgapi.json overrides.allow_critical` lists it** (with a warning): + `dalvik.*` and `persist.sys.dalvik.*` keys in `build.prop` and as live props + (`"prop:"`, e.g. the runtime switch `persist.sys.dalvik.vm.lib`), `framework-res.apk`, + `libz`, `libcrypto`, `libssl`, the ICU libraries and data file, `libgui`, `libui`, `libEGL`, + `libGLESv2`, `libhardware`, `libsqlite`, `libexpat`, everything in `/system/lib/hw/` and + `/system/lib/egl/`, and `netd`, `mediaserver`, `logwrapper` and `e2fsck`. +- **HMG-API doesn't update itself while an apply is unfinished or a trial is in place** + (`engine update-hmgapi`, `--force` included): `engine keep` or `engine recover` first. +- **A rebuilt app's Dalvik cache entry is the only one touched.** The clean-up also deleted + other apps' entries whose names ended the same way, and the entry filled after a restore was + always named `system@app@`, wrong for an app in `/system/priv-app`. Tested off-car only. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..f4f09a9f 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -42,10 +42,12 @@ * src, else puts stock back (nothing on disk changes; a restart clears it). * * Safety (the unit must always boot): /system/build.prop only takes "props" - * changes, never to ro.* keys, and every edit must keep every other line; - * boot-critical files (see CRITICAL) are refused unless hmgapi.json - * overrides.allow_critical lists the path; files HMG-API's installer owns are - * always refused. Live properties ("prop") are persist.* only: they live in + * changes, never to ro.*, dalvik.* or persist.sys.dalvik.* keys (CRITICAL_PROPS), + * and every edit must keep every other line; boot-critical files (see critical()) + * are refused unless hmgapi.json overrides.allow_critical lists the path + * ("/system/build.prop:" for a key, "prop:" for a live property); files + * HMG-API's installer owns are always refused. Live properties ("prop") are + * persist.* only (not persist.sys.dalvik.*: the runtime switch): they live in * /data/property, and removing that file undoes them. A prop's "value" "" means * unset. "mirror": a live (non-persist) property set to the same value, for init * triggers such as sys.usb.config; "restart": services restarted after the @@ -337,10 +339,8 @@ String bindRefused(String src, String target, String svc) { if (!target.matches("/(sbin|system/bin)/[A-Za-z0-9._-]+")) return "target must be in /sbin or /system/bin"; if (!svc.matches("[a-z0-9_]+")) return "service must be an init service name"; for (String x : HMGAPI_OWNED) if (x.equals(target) || x.equals(src)) return target + " belongs to HMG-API's own install"; - for (String x : CRITICAL) { - if (x.equals(target) && !allowedCritical(target)) { - return "the unit needs " + target + " to boot (hmgapi.json overrides.allow_critical lists it to allow, at your own risk)"; - } + if (critical(target) && !allowedCritical(target)) { + return "the unit needs " + target + " to boot (hmgapi.json overrides.allow_critical lists it to allow, at your own risk)"; } if ("/sbin/ueventd".equals(target) || "/sbin/healthd".equals(target) || target.equals("/init")) return target + " can't be swapped"; return null; @@ -461,9 +461,9 @@ 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); - LiveState.publish(this); - return 0; + int rc = apply(p, trial); + if (rc == 0) LiveState.publish(this); + return rc; } // ------------------------------------------------------------------ mods @@ -912,10 +912,11 @@ static final class Target { boolean exists; // result exists String result; // md5 of the result, or "absent" String stock; // md5 of the stock original, or "absent" - File baseline; // where the stock bytes come from (null = absent) + File baseline; // where the stock bytes come from (null = absent); restore: what's written back boolean newBackup; // baseline must be backed up at apply boolean app; // rebuilt app: odex regenerated - File odexSrc; // app: the stock odex its delta was built from (backed up at apply) + File odexSrc; // app: the stock odex its delta was built from (backed up at apply); restore: what's written back + String odexStock; // app: that odex's md5 (recorded in files.json "odex"; null in an older engine's records) Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock } @@ -1029,6 +1030,14 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { + " ro.* can't change, and build.prop edits aren't used for properties)"); continue; } + if (criticalProp(key) != null) { + if (!allowedCritical("prop:" + key)) { + problems.add(m.id + ": prop " + key + ": " + criticalProp(key) + ", so it's refused (hmgapi.json" + + " overrides.allow_critical \"prop:" + key + "\" allows it, at your own risk)"); + continue; + } + out.add("WARNING: prop " + key + " can keep the unit from booting; setting it because overrides.allow_critical lists it"); + } } if ("setting".equals(ch.type) && c.get("add") instanceof List) { // a list setting (enabled_input_methods "a:b"): every mod's entries on top of the stock value @@ -1116,10 +1125,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { List skipped = new ArrayList(); for (Target t : p.targets.values()) { if (t.restore) { - Map f = (Map) files.get(t.path); - t.stock = (String) f.get("stock"); - t.result = t.stock; - t.app = Boolean.TRUE.equals(f.get("app")); + restoreFrom(t, (Map) files.get(t.path)); continue; } int before = problems.size(); @@ -1151,14 +1157,89 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { else { // owned before, can't be built now: back to stock Target t = p.targets.get(path); t.restore = true; - t.stock = (String) f.get("stock"); - t.result = t.stock; - t.app = Boolean.TRUE.equals(f.get("app")); + restoreFrom(t, f); } } return p; } + /** + * A file going back to stock: where its stock bytes (and an app's stock odex) come from. + * Each backup is checked against the md5 recorded when it was taken; a damaged one is + * never written back (a short odex under a stock apk with no classes.dex: the app + * crashes at every launch). A NEMESIS copy with the recorded md5 stands in, else the + * plan stops, saying which backup and what it should be. + */ + void restoreFrom(Target t, Map f) throws IOException { + t.stock = (String) f.get("stock"); + t.result = t.stock; + t.app = Boolean.TRUE.equals(f.get("app")); + if (!"absent".equals(t.stock)) { + t.baseline = stockCopy(t.path, t.stock); + if (t.baseline == null) return; + } + if (t.app) { + String odex = t.path.replaceAll("\\.apk$", ".odex"); + t.odexStock = (String) f.get("odex"); + t.odexSrc = t.odexStock != null ? stockCopy(odex, t.odexStock) : wholeOdex(odex); + } + } + + /** + * HMG-API's backup of a stock file if it has the md5 recorded for it, else a NEMESIS copy + * that does (noted; a rebuild backs it up again); null, with the problem, if neither. + */ + File stockCopy(String path, String md5) throws IOException { + File b = backup(path); + String have = md5(b); + if (have.equals(md5)) return b; + File nem = nemesisStock(path, Collections.singleton(md5)); + if (nem != null) { + out.add("note " + path + ": HMG-API's stock backup is " + ("absent".equals(have) ? "missing" : "damaged (" + have + ")") + + "; using the stock copy NEMESIS kept (" + nem.getParentFile().getName() + "), which has the recorded md5 " + md5); + return nem; + } + problems.add(path + ": HMG-API's stock backup " + b.getPath().substring(root.length()) + " is " + + ("absent".equals(have) ? "missing" : "damaged (md5 " + have + ")") + ", not the stock file recorded (md5 " + md5 + + "), so it can't be put back. Copy the stock file (md5 " + md5 + ") there, then try again"); + return null; + } + + /** + * An app's odex backup from before HMG-API recorded its md5: a Dalvik odex ("dey\n" and + * its header's opt section) must be as long as its header says; a short one (a cut-off + * copy) is refused. Anything else can't be told apart, so it's used as before. + */ + File wholeOdex(String odex) throws IOException { + File b = backup(odex); + if (!b.isFile()) { + problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + + " is missing, so the stock app (which has no code of its own) can't be put back. Copy the stock odex there, then try again"); + return null; + } + byte[] h = new byte[40]; + InputStream in = new FileInputStream(b); + int n; + try { + n = in.read(h); + } finally { + in.close(); + } + if (n == 40 && h[0] == 'd' && h[1] == 'e' && h[2] == 'y' && h[3] == '\n') { + long optOff = le32(h, 24), optLen = le32(h, 28); + if (b.length() < optOff + optLen) { + problems.add(odex + ": HMG-API's backup of the stock odex " + b.getPath().substring(root.length()) + " is cut short (" + + b.length() + " bytes, its header says " + (optOff + optLen) + "), so it can't be put back. Copy the stock odex there, then try again"); + return null; + } + } + return b; + } + + static long le32(byte[] b, int at) { + return (b[at] & 0xffL) | (b[at + 1] & 0xffL) << 8 | (b[at + 2] & 0xffL) << 16 | (b[at + 3] & 0xffL) << 24; + } + /** live md5s taken as found this plan (Plan.rebased), for build() */ Map rebaseAccept = new TreeMap(); @@ -1232,13 +1313,46 @@ static boolean backupName(String n, String path) { /** Files the unit can't boot (or HMG-API can't run) without. */ static final String[] CRITICAL = { + // the shell, the linker, the daemons init starts at boot that Android waits for (system_server + // hangs without netd or mediaserver's audio), and what init's mount_all runs on /data "/system/bin/linker", "/system/bin/sh", "/system/bin/mksh", "/system/bin/toolbox", "/system/bin/servicemanager", "/system/bin/vold", "/system/bin/surfaceflinger", "/system/bin/dexopt", "/system/bin/installd", + "/system/bin/netd", "/system/bin/mediaserver", "/system/bin/logwrapper", "/system/bin/e2fsck", + // what the zygote, system_server and surfaceflinger load "/system/lib/libc.so", "/system/lib/libdl.so", "/system/lib/libm.so", "/system/lib/libstdc++.so", "/system/lib/liblog.so", "/system/lib/libcutils.so", "/system/lib/libutils.so", "/system/lib/libbinder.so", "/system/lib/libdvm.so", "/system/lib/libandroid_runtime.so", "/system/lib/libnativehelper.so", "/system/lib/libselinux.so", + "/system/lib/libz.so", "/system/lib/libcrypto.so", "/system/lib/libssl.so", "/system/lib/libicuuc.so", + "/system/lib/libicui18n.so", "/system/usr/icu/icudt51l.dat", "/system/lib/libgui.so", "/system/lib/libui.so", + "/system/lib/libEGL.so", "/system/lib/libGLESv2.so", "/system/lib/libhardware.so", "/system/lib/libsqlite.so", + "/system/lib/libexpat.so", + "/system/framework/framework-res.apk", "/system/etc/init.sh", "/system/etc/mkshrc", }; + /** Folders whose every file is boot-critical: the hardware modules and the GPU's EGL drivers. */ + static final String[] CRITICAL_DIRS = { "/system/lib/hw/", "/system/lib/egl/" }; + /** Property prefixes a mod can't set (build.prop keys, live props) without overrides.allow_critical. */ + static final String[] CRITICAL_PROPS = { "ro.", "dalvik.", "persist.sys.dalvik." }; + + /** Whether the unit needs this file to boot (CRITICAL, CRITICAL_DIRS, the boot class path). */ + static boolean critical(String path) { + for (String x : CRITICAL) if (x.equals(path)) return true; + for (String d : CRITICAL_DIRS) if (path.startsWith(d)) return true; + for (String j : BOOT_JARS) { + if (path.equals("/system/framework/" + j + ".jar") || path.equals("/system/framework/" + j + ".odex")) return true; + } + return false; + } + + /** Why a property can keep the unit from booting, or null if it can't. */ + static String criticalProp(String key) { + if (key.startsWith("ro.")) return "ro.* properties set how the firmware identifies and boots itself"; + if (key.startsWith("dalvik.") || key.startsWith("persist.sys.dalvik.")) { + return "dalvik.* and persist.sys.dalvik.* properties set how Dalvik starts (persist.sys.dalvik.vm.lib picks the runtime;" + + " a wrong one and no app starts)"; + } + return null; + } /** Boot class path jars (and their odex): Dalvik won't start without them intact. */ static final String[] BOOT_JARS = { "core", "conscrypt", "okhttp", "core-junit", "bouncycastle", "ext", "framework", "framework2", "telephony-common", "voip-common", "mms-common", "android.policy", "services", "apache-xml", @@ -1284,11 +1398,12 @@ String guard(Target t) { if (set instanceof Map) keys.addAll(((Map) set).keySet()); if (rm instanceof List) for (Object k : (List) rm) keys.add(String.valueOf(k)); for (String k : keys) { - if (k.startsWith("ro.") && !allowedCritical(t.path + ":" + k)) { - return t.path + ": " + ch.mod.id + " changes " + k + "; ro.* properties set how the firmware identifies and" - + " boots itself, so they're refused (hmgapi.json overrides.allow_critical \"" + t.path + ":" + k - + "\" allows it, at your own risk)"; + String why = criticalProp(k); + if (why != null && !allowedCritical(t.path + ":" + k)) { + return t.path + ": " + ch.mod.id + " changes " + k + "; " + why + ", so they're refused" + + " (hmgapi.json overrides.allow_critical \"" + t.path + ":" + k + "\" allows it, at your own risk)"; } + if (why != null) out.add("WARNING: " + t.path + ": " + k + " can keep the unit from booting; changing it because overrides.allow_critical lists it"); if (!k.matches("[A-Za-z0-9._-]+")) return t.path + ": " + ch.mod.id + ": \"" + k + "\" isn't a property name"; } if (set instanceof Map) { @@ -1300,11 +1415,7 @@ String guard(Target t) { } return null; } - boolean critical = false; - for (String x : CRITICAL) critical |= x.equals(t.path); - for (String j : BOOT_JARS) { - critical |= t.path.equals("/system/framework/" + j + ".jar") || t.path.equals("/system/framework/" + j + ".odex"); - } + boolean critical = critical(t.path); if (critical && !allowedCritical(t.path)) { return t.path + ": the unit needs this file to boot, so mods can't change it (hmgapi.json overrides.allow_critical" + " lists paths allowed anyway, at your own risk)"; @@ -1342,7 +1453,12 @@ void build(Target t, Map owned) throws Exception { } if (owned != null) { t.stock = (String) owned.get("stock"); - t.baseline = "absent".equals(t.stock) ? null : backup(t.path); + if (!"absent".equals(t.stock)) { + // rebuilt from the backup only if it's still the stock file recorded (a NEMESIS copy that is stands in) + t.baseline = stockCopy(t.path, t.stock); + if (t.baseline == null) return; + t.newBackup = !t.baseline.equals(backup(t.path)); + } } else { String m = md5(live); if ("absent".equals(m)) { @@ -1490,21 +1606,28 @@ else if (!m.equals(addMd5)) { // (lpatch only builds from the exact stock bytes, so trying each is safe) String odexPath = t.path.replaceAll("\\.apk$", ".odex"); List odexes = new ArrayList(); - if (owned != null) odexes.add(backup(odexPath)); - else { + String bad = null; + if (owned != null) { + // the live odex is HMG-API's dexopt output now, never stock. A backup that isn't the + // recorded md5 is left out; NEMESIS's copies stand in (backed up again at apply) + String rec = (String) owned.get("odex"), have = md5(backup(odexPath)); + if (rec == null || rec.equals(have)) odexes.add(backup(odexPath)); + else bad = "HMG-API's backup of the stock odex is " + ("absent".equals(have) ? "missing" : "damaged (" + have + ")") + + ", recorded " + rec; + } else { odexes.add(sys(odexPath)); odexes.add(new File(stockDir, odexPath)); - odexes.addAll(nemesisCopies(odexPath)); } + odexes.addAll(nemesisCopies(odexPath)); File dex = new File(stageDir, t.path.replace('/', '_') + ".dex"); - String why = "no stock odex found"; + String why = bad != null ? bad + ", and no NEMESIS copy fits" : "no stock odex found"; t.odexSrc = null; for (String d : ch.srcs("delta")) { for (File odex : odexes) { if (!odex.isFile()) continue; Run r = exec(lpatch, "delta", d, odex.getPath(), dex.getPath()); if (r.code == 0 && dex.isFile()) { t.odexSrc = odex; break; } - why = r.text.trim(); + if (bad == null) why = r.text.trim(); } if (t.odexSrc != null) break; } @@ -1512,6 +1635,7 @@ else if (!m.equals(addMd5)) { problems.add(t.path + ": " + ch.mod.id + "'s app delta doesn't fit this app's stock odex: " + why); return; } + t.odexStock = md5(t.odexSrc); // lpatch built from it, so these are the stock bytes: recorded with the backup File next = new File(work.getPath() + ".a"); Run r = exec(lpatch, "zipadd", work.getPath(), dex.getPath(), next.getPath()); if (r.code != 0 || !next.isFile()) { @@ -1828,7 +1952,7 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply @SuppressWarnings("unchecked") - void apply(Plan p, boolean trial) throws Exception { + int apply(Plan p, boolean trial) throws Exception { Map files = (Map) p.state.get("files"); Map st = (Map) p.state.get("settings"); List changed = new ArrayList(); @@ -1836,8 +1960,14 @@ void apply(Plan p, boolean trial) throws Exception { // --force: also a file whose result is unchanged but which was deleted or changed outside HMG-API (#103) if (t.restore || !t.result.equals(p.owned(t.path)) || (p.force && !t.result.equals(md5(sys(t.path))))) changed.add(t); } + String full = room(changed); + if (full != null) { + out.add("nothing changed: " + full); + return 3; + } - // journal: what each file was before, so a lost apply or a trial can be rolled back + // journal: what each file was before, so a lost apply or a trial can be rolled back. Each saved + // copy is checked against the live file and its md5 kept, so recover never writes a short one back rm(prevDir); prevDir.mkdirs(); List entries = new ArrayList(); @@ -1848,17 +1978,32 @@ void apply(Plan p, boolean trial) throws Exception { File live = sys(path); if (live.isFile()) { File prev = new File(prevDir, path.replace('/', '_')); - copy(live, prev); + e.put("md5", checkedCopy(live, prev, md5(live))); e.put("prev", prev.getPath()); e.put("mode", mode(live)); } entries.add(e); } } + // settings, live props and binds as they are now: recover writes them back too (a trial's + // persist.* prop, or an apply cut off after the settings but before the state, stayed set and + // was then taken as stock by the next apply) + Map wasSet = new LinkedHashMap(); + Map before = new LinkedHashMap(); + for (Map.Entry e : p.settings.entrySet()) { + Map s = (Map) st.get(e.getKey()); + if (s != null && String.valueOf(e.getValue()[0]).equals(String.valueOf(s.get("value")))) continue; // not written + journalSetting(wasSet, before, e.getKey(), (Map) e.getValue()[2], s); + } + for (String k : p.settingsRestore) journalSetting(wasSet, before, k, null, (Map) st.get(k)); + File bindsFile = new File(stateDir, "binds.txt"), bindsFailed = new File(stateDir, "binds.failed"); Map j = new LinkedHashMap(); j.put("trial", trial); j.put("committed", false); j.put("entries", entries); + j.put("settings", wasSet); + j.put("binds", bindsFile.isFile() ? read(bindsFile) : null); + j.put("binds_failed", bindsFailed.isFile() ? read(bindsFailed) : null); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below write(journalFile, Json.write(j)); @@ -1867,13 +2012,15 @@ void apply(Plan p, boolean trial) throws Exception { rm(backup(path)); if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); } - // stock backups, once + // stock backups, as install.sh's backup() takes them: copied beside, checked against the stock md5, + // then renamed, so a cut-off copy never sits under the backup's name. Taken once, and again only + // when the one there isn't the stock file (a damaged one, replaced from a NEMESIS copy) for (Target t : changed) { - if (!t.newBackup) continue; - copy(t.baseline, backup(t.path)); - if (t.app) { - String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (t.odexSrc != null && t.odexSrc.isFile() && !backup(odex).isFile()) copy(t.odexSrc, backup(odex)); + if (t.restore) continue; + if (t.newBackup) checkedCopy(t.baseline, backup(t.path), t.stock); + if (t.app && t.odexSrc != null && t.odexStock != null) { + File ob = backup(t.path.replaceAll("\\.apk$", ".odex")); + if (!t.odexStock.equals(md5(ob))) checkedCopy(t.odexSrc, ob, t.odexStock); } } @@ -1895,7 +2042,7 @@ void apply(Plan p, boolean trial) throws Exception { String was; if (s == null) { s = new LinkedHashMap(); - s.put("stock", settingGet(k)); + s.put("stock", before.get(k)); // read once, for the journal st.put(k, s); was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); } else { @@ -1922,15 +2069,17 @@ void apply(Plan p, boolean trial) throws Exception { if (!back.equals(String.valueOf(s.get("value")))) after(s, back); out.add("set " + k + " back to " + s.get("stock")); } + cut("settings"); // binds: hmgapid does them after the output is printed (restarting a service like adbd // may cut the link that asked); a new list clears earlier failures String bt = bindsText(p.binds); if (!bt.equals(currentBinds())) { - write(new File(stateDir, "binds.txt"), bt); - new File(stateDir, "binds.failed").delete(); + write(bindsFile, bt); + bindsFailed.delete(); bindsChanged = true; } + cut("binds"); // state for (Target t : changed) { @@ -1943,6 +2092,7 @@ void apply(Plan p, boolean trial) throws Exception { f.put("result", t.result); f.put("mods", new ArrayList(t.mods)); if (t.app) f.put("app", true); + if (t.app && t.odexStock != null) f.put("odex", t.odexStock); files.put(t.path, f); } write(stateFile, Json.write(p.state)); @@ -1959,6 +2109,106 @@ void apply(Plan p, boolean trial) throws Exception { for (Target t : changed) needs.add(restart(t.path)); if (!p.settings.isEmpty() || !p.settingsRestore.isEmpty()) needs.add("settings applied now"); out.add("done: " + changed.size() + " file(s); " + needs); + return 0; + } + + /** a setting, live prop or list setting's value before this apply, with what undoing it needs (mirror, restart) */ + void journalSetting(Map was, Map before, String k, Map c, Map s) + throws Exception { + String v = settingGet(k); + before.put(k, v); + Map e = new LinkedHashMap(); + e.put("value", v); + for (String x : new String[] { "mirror", "restart" }) { + Object o = c != null && c.get(x) != null ? c.get(x) : s != null ? s.get(x) : null; + if (o != null) e.put(x, o); + } + was.put(k, e); + } + + /** + * Off-car tests only (HMGAPI_TEST_CUT=): the engine stops dead here, as when the + * unit loses power mid-apply, so recover can be tested on what that leaves. + */ + void cut(String point) { + if (host && point.equals(env("HMGAPI_TEST_CUT", null))) { + System.out.flush(); + Runtime.getRuntime().halt(137); + } + } + + /** + * Room for this apply, checked before anything is written. On /system: each new file is + * written beside the old one, then renamed over it. An app's old apk and odex are freed + * then (the app is stopped while its files change), so only the growth counts, plus the + * largest old one while both are there; any other file counts whole (a running process + * may still map the old one until the restart). On /data: the journal's copies, new + * backups and the Dalvik cache. A /system that filled mid-apply left a half-done apply + * that recover couldn't put back either. null, or why not. + */ + String room(List changed) throws IOException { + long sys = 0, both = 0, dat = 0; + for (Target t : changed) { + File src = t.restore ? t.baseline : t.exists ? t.stage : null; + long nw = src == null ? 0 : src.length(), old = sys(t.path).length(); + for (String path : withOdex(t)) dat += sys(path).length(); // the journal's copies + if (t.newBackup && t.baseline != null) dat += t.baseline.length(); + if (t.app) { + long odex = t.odexSrc != null ? t.odexSrc.length() : 0, oldOdex = sys(t.path.replaceAll("\\.apk$", ".odex")).length(); + File dex = new File(stageDir, t.path.replace('/', '_') + ".dex"); + long est = t.restore ? odex : Math.max(odex, dex.length() + dex.length() / 4); // dexopt's odex: about the dex and a quarter + sys += Math.max(0, nw - old) + Math.max(0, est - oldOdex); + both = Math.max(both, Math.max(old, oldOdex)); + dat += est + odex; // the Dalvik cache copy, and the odex backup + } else { + sys += nw; + } + } + if (sys == 0 && dat == 0) return null; + long sysFree = free("system", sys(SYSTEM)), datFree = free("data", data); + long sysNeed = sys + both + SYSTEM_SPARE, datNeed = dat + DATA_SPARE; + if (sysFree < sysNeed) return "not enough room on /system: this apply needs about " + mb(sysNeed) + ", " + mb(sysFree) + " free"; + if (datFree < datNeed) return "not enough room on /data: this apply needs about " + mb(datNeed) + ", " + mb(datFree) + + " free (HMG-API keeps a copy of each file it changes, and its stock backup)"; + return null; + } + + static final String SYSTEM = "/system"; + static final long SYSTEM_SPARE = 512 * 1024, DATA_SPARE = 16 * 1024 * 1024; + + static String mb(long n) { + return String.format(java.util.Locale.US, "%.1f MB", n / 1048576.0); + } + + /** + * Free bytes on the filesystem holding f, as root sees it on /system (root may use its + * reserved blocks; the engine runs as root) and as apps do on /data (Android needs its + * reserve there). Off-car tests: HMGAPI_TEST_FREE="system= data=". + */ + long free(String which, File f) { + if (host) { + for (String kv : env("HMGAPI_TEST_FREE", "").split(" ")) if (kv.startsWith(which + "=")) return Long.parseLong(kv.substring(which.length() + 1)); + } + while (f != null && !f.exists()) f = f.getParentFile(); + if (f == null) return Long.MAX_VALUE; + return "system".equals(which) ? f.getFreeSpace() : f.getUsableSpace(); + } + + /** + * Copied beside dst, checked against the md5 it must have, then renamed onto dst: a copy + * that fails or is cut off never leaves a short file under dst's name. Returns the md5. + */ + static String checkedCopy(File src, File dst, String want) throws IOException { + File tmp = new File(dst.getPath() + ".hmgapi-new"); + try { + copy(src, tmp); + String got = md5(tmp); + if (!got.equals(want)) throw new IOException("copy of " + src + " to " + dst + " came out " + got + ", not " + want); + if (!tmp.renameTo(dst)) throw new IOException("rename onto " + dst); + return got; + } finally { + tmp.delete(); + } } List withOdex(Target t) { @@ -1974,11 +2224,11 @@ void swap(Target t) throws Exception { if ("absent".equals(t.stock)) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); } else { - put(backup(t.path), dst, "644"); + put(t.baseline, dst, "644"); // checked against its recorded md5 in the plan (restoreFrom) } if (t.app) { String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (backup(odex).isFile()) put(backup(odex), sys(odex), "644"); + if (t.odexSrc != null) put(t.odexSrc, sys(odex), "644"); dalvik(t.path, sys(odex), false); } out.add("restored " + t.path); @@ -1998,23 +2248,37 @@ void swap(Target t) throws Exception { out.add("wrote " + t.path); } - /** dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. */ + /** + * The Dalvik cache entry of an app on /system: its path without the leading /, each / + * an @, then @classes.dex (system@app@X.apk@classes.dex, system@priv-app@X.apk@classes.dex). + */ + static String dalvikName(String apkPath) { + return apkPath.substring(1).replace('/', '@') + "@classes.dex"; + } + + /** + * dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. Only this + * app's own entry goes (a *X.apk* glob also took MyX.apk's). Off the unit: no dexopt, and + * the cache under HMGAPI_ROOT when the test made one. + */ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { - if (host) return; - String apk = new File(apkPath).getName(); - exec("/system/bin/sh", "-c", "rm -f /data/dalvik-cache/*" + apk + "* /cache/dalvik-cache/*" + apk + "*"); - if (dexopt) { + String name = dalvikName(apkPath); + File cache = new File(root + "/data/dalvik-cache/" + name); + cache.delete(); + new File(root + "/cache/dalvik-cache/" + name).delete(); + if (dexopt && !host) { Run r = exec("/system/bin/dexopt", "--preopt", sys(apkPath).getPath(), odex.getPath(), "m=y,u=n"); if (r.code != 0 || !odex.isFile()) throw new IOException("dexopt " + apkPath + ": " + r.text); exec("/system/bin/chmod", "644", odex.getPath()); exec("/system/bin/chown", "1000:1000", odex.getPath()); } - if (odex.isFile()) { - File cache = new File("/data/dalvik-cache/system@app@" + apk + "@classes.dex"); + if (odex.isFile() && cache.getParentFile().isDirectory()) { File tmp = new File(cache.getPath() + ".tmp"); copy(odex, tmp); - exec("/system/bin/chmod", "644", tmp.getPath()); - exec("/system/bin/chown", "1000:1000", tmp.getPath()); + if (!host) { + exec("/system/bin/chmod", "644", tmp.getPath()); + exec("/system/bin/chown", "1000:1000", tmp.getPath()); + } if (!tmp.renameTo(cache)) tmp.delete(); } } @@ -2088,13 +2352,49 @@ int status() throws Exception { Set on = new LinkedHashSet(); adbTcpWarning(LiveState.mods(this, on), on); if (journalFile.exists()) { - Map j = Json.object(read(journalFile)); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial apply in place: `engine keep` keeps it, the next start undoes it" + Map j = journal(); + out.add(j == null ? "an apply didn't finish, and its journal (state/journal.json) is damaged: the next start sets it aside (`engine recover`)" + : Boolean.TRUE.equals(j.get("trial")) && Boolean.TRUE.equals(j.get("committed")) + ? "trial apply in place: `engine keep` keeps it, the next start undoes it" : "an apply didn't finish: the next start rolls it back (`engine recover`)"); } return bad == 0 ? 0 : 4; } + /** the journal, or null if it can't be read or isn't whole (entries, each with a path, and the state) */ + @SuppressWarnings("unchecked") + Map journal() { + try { + Map j = Json.object(read(journalFile)); + if (!(j.get("entries") instanceof List) || !(j.get("state") instanceof Map)) return null; + for (Object o : (List) j.get("entries")) { + if (!(o instanceof Map) || !(((Map) o).get("path") instanceof String)) return null; + String path = (String) ((Map) o).get("path"); + if (!systemPath(path)) return null; + } + if (j.get("settings") != null && !(j.get("settings") instanceof Map)) return null; + return j; + } catch (Exception e) { + return null; + } + } + + /** + * A journal that can't be used, set aside (state/journal.bad.json, its saved copies in + * state/prev.bad/) so apply, restore and uninstall aren't refused for good. What it would + * have put back stays as it is: `engine status` shows what isn't HMG-API's result. + */ + void setAside(String why) { + File bad = new File(stateDir, "journal.bad.json"), prevBad = new File(stateDir, "prev.bad"); + bad.delete(); + rm(prevBad); + boolean moved = journalFile.renameTo(bad); + if (!moved) journalFile.delete(); + if (prevDir.exists() && !prevDir.renameTo(prevBad)) rm(prevDir); + out.add("journal " + why + "; set aside as state/" + (moved ? bad.getName() : "(deleted: couldn't be moved)") + + (prevBad.exists() ? ", its saved copies in state/" + prevBad.getName() + "/" : "")); + } + /** * The car's ADB TCP switch (persist.service.adb.tcp.enable=1: Engineering Mode, or * NEMESIS's Enable ADB) also runs `ifconfig eth0 192.168.0.123` (init.daudio.rc), @@ -2123,7 +2423,11 @@ int keep() throws Exception { out.add("no trial to keep"); return 0; } - Map j = Json.object(read(journalFile)); + Map j = journal(); + if (j == null) { + out.add("the last apply's journal (state/journal.json) is damaged; `engine recover` sets it aside"); + return 1; + } if (!Boolean.TRUE.equals(j.get("trial")) || !Boolean.TRUE.equals(j.get("committed"))) { out.add("the last apply didn't finish; it can only be rolled back (`engine recover`)"); return 1; @@ -2140,32 +2444,107 @@ int recover() throws Exception { out.add("nothing to recover"); return 0; } - Map j = Json.object(read(journalFile)); + Map j = journal(); + if (j == null) { + // no way to tell what it would put back; kept as it is, it refuses every apply, restore and uninstall + setAside("state/journal.json is damaged (an apply was cut off while writing it?), so nothing could be put back from it"); + out.add("the files and settings that apply changed stay as they are; `engine status` shows them, and `engine apply`" + + " (or apply --force) builds them again"); + return 0; + } + // each saved copy checked before any is written: one that's gone or isn't what was saved is skipped, + // not written back, and not tried again at every start + List lost = new ArrayList(); + for (Object o : (List) j.get("entries")) { + Map e = (Map) o; + Object prev = e.get("prev"); + if (prev == null) continue; + File pf = new File(String.valueOf(prev)); + String have = md5(pf); + if ("absent".equals(have) || (e.get("md5") != null && !have.equals(e.get("md5")))) lost.add((String) e.get("path")); + } remount("rw"); try { for (Object o : (List) j.get("entries")) { Map e = (Map) o; String path = (String) e.get("path"); File dst = sys(path); + new File(dst.getPath() + ".hmgapi-new").delete(); // a cut-off apply's half-written copy: its room back first + if (lost.contains(path)) { + out.add("can't put back " + path + ": its saved copy is " + ("absent".equals(md5(new File(String.valueOf(e.get("prev"))))) + ? "gone" : "damaged") + "; left as it is"); + continue; + } Object prev = e.get("prev"); if (prev == null) { if (dst.exists()) dst.delete(); } else { - put(new File((String) prev), dst, e.get("mode") == null ? "644" : String.valueOf(e.get("mode"))); + putBack(new File((String) prev), dst, e.get("mode") == null ? "644" : String.valueOf(e.get("mode"))); } - if (path.endsWith(".odex") && !host) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); + if (path.endsWith(".odex")) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); out.add("rolled back " + path); } } finally { remount("ro"); } + recoverSettings(j); + if (j.containsKey("binds")) { + File bf = new File(stateDir, "binds.txt"), ff = new File(stateDir, "binds.failed"); + String was = (String) j.get("binds"), now = bf.isFile() ? read(bf) : null; + if (!eq(was, now)) { + if (was == null) bf.delete(); + else write(bf, was); + bindsChanged = true; + out.add("rolled back binds"); + } + String wasFailed = (String) j.get("binds_failed"); + if (wasFailed == null) ff.delete(); + else write(ff, wasFailed); + } write(stateFile, Json.write(j.get("state"))); - journalFile.delete(); - rm(prevDir); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); + if (lost.isEmpty()) { + journalFile.delete(); + rm(prevDir); + } else { + setAside(lost.size() + " file(s) couldn't be put back"); + out.add("`engine status` shows them (CHANGED); `engine apply --force` builds them again"); + } + out.add(Boolean.TRUE.equals(j.get("trial")) && Boolean.TRUE.equals(j.get("committed")) ? "trial undone" : "unfinished apply rolled back"); return 0; } + /** the settings and live props an apply changed, back to what the journal says they were */ + @SuppressWarnings("unchecked") + void recoverSettings(Map j) throws Exception { + Object so = j.get("settings"); + if (!(so instanceof Map)) return; // a journal from an older engine: files only + for (Map.Entry e : ((Map) so).entrySet()) { + String k = e.getKey(); + if (!(e.getValue() instanceof Map)) continue; + Map s = (Map) e.getValue(); + String was = s.get("value") == null ? null : String.valueOf(s.get("value")); + String now = settingGet(k); + if (eq(was == null || was.isEmpty() ? null : was, now == null || now.isEmpty() ? null : now)) continue; + settingPut(k, was); + after(s, was == null ? "" : was); + out.add("rolled back setting " + k + " = " + (was == null ? "(unset)" : was)); + } + } + + /** + * put() for recover. A /system that filled up mid-apply may have no room for the copy + * beside the file (put writes there, then renames): then the file goes first and its + * saved copy takes its place. The saved copy and the journal stay until recover finishes, + * so a cut here is put right at the next start. + */ + void putBack(File src, File dst, String mode) throws Exception { + if (dst.isFile() && free("system", dst.getParentFile()) < src.length() + SYSTEM_SPARE) { + if (!dst.delete()) throw new IOException("delete " + dst); + out.add("room /system is short of room: " + dst.getPath().substring(root.length()) + " removed before its saved copy goes back"); + } + put(src, dst, mode); + } + /** * A firmware update put /system back to stock under HMG-API (install.sh finds its wrapper * gone): every file HMG-API changed that isn't its result any more is the new firmware's diff --git a/core/runtime/java/hmgapi/engine/UsbUpdates.java b/core/runtime/java/hmgapi/engine/UsbUpdates.java index a1531edd..f950e6b9 100644 --- a/core/runtime/java/hmgapi/engine/UsbUpdates.java +++ b/core/runtime/java/hmgapi/engine/UsbUpdates.java @@ -159,7 +159,23 @@ static String installedVersion(Engine e) { return Engine.HMGAPI_VERSION; } + /** + * Why HMG-API can't update itself now, or null: never while an apply is unfinished or a + * trial is in place. The new installer would build on files and records that the next + * start rolls back (and its engine on a journal it may not read the same way). The + * catalogue's update asks this before it downloads. + */ + static String pendingWhy(Engine e) { + if (!e.journalFile.exists()) return null; + return "an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first, then update HMG-API"; + } + static int updateHmgApi(Engine e, String path, boolean force) throws Exception { + String pending = pendingWhy(e); + if (pending != null) { // --force is for an older release, not this + e.out.add("refused: " + pending); + return 1; + } File zip = new File(path); if (!zip.isFile()) { e.out.add("no release at " + path); diff --git a/core/runtime/journal-test.sh b/core/runtime/journal-test.sh new file mode 100644 index 00000000..ad9a9b77 --- /dev/null +++ b/core/runtime/journal-test.sh @@ -0,0 +1,255 @@ +#!/bin/sh +# Off-car test of the engine's journal and backups: recover puts back settings, live props +# and binds as well as files (a trial, an apply cut off part-way); stock backups are taken +# checked and used only when they're still the stock file; room is checked before an +# apply; a damaged journal or saved copy is set aside instead of failing every start; the +# Dalvik cache entries touched are only the app's own. +# Needs a JDK, python3 with bsdiff4, and out/lpatch-host (./build.sh lpatch). +set -e +cd "$(dirname "$0")/../.." +REPO=$PWD +[ -x out/lpatch-host ] || { echo "run ./build.sh lpatch first"; exit 1; } +CP=$(mktemp -d) +sh tools/engine-classes.sh "$CP" +T=$(mktemp -d) +trap 'rm -rf "$T" "$CP"' EXIT +R=$T/root +D=$R/data/hmgapi +fail=0 +check() { if [ "$2" = "$3" ]; then echo "ok $1"; else echo "FAIL $1: wanted [$2], got [$3]"; fail=1; fi; } +hasnt() { case "$3" in *"$2"*) echo "FAIL $1: [$2] in [$3]"; fail=1 ;; *) echo "ok $1" ;; esac; } +has() { case "$3" in *"$2"*) echo "ok $1" ;; *) echo "FAIL $1: wanted [$2] in [$3]"; fail=1 ;; esac; } +md5() { [ -f "$1" ] && md5sum "$1" | cut -d' ' -f1 || echo absent; } +yes_no() { if [ -e "$1" ]; then echo yes; else echo no; fi; } +eng() { set +e; out=$(HMGAPI_ROOT=$R HMGAPI_HOST=1 HMGAPI_TEST_ANY_CAR=1 HMGAPI_PRODUCT=CVEV.USA.0000.V015 HMGAPI_ONEBIN=cvev_us \ + HMGAPI_LPATCH=$REPO/out/lpatch-host java -cp "$CP" hmgapi.engine.Engine "$@" 2>&1); rc=$?; set -e; } +rec() { python3 -c 'import json,sys; s=json.load(open(sys.argv[1])); print(eval(sys.argv[2]))' "$@"; } + +# ---- a fake head unit: a library, an app in /system/app and one in /system/priv-app +mkdir -p $R/system/lib $R/system/app $R/system/priv-app $R/system/etc/permissions $D/mods $D/settings $R/data/dalvik-cache +printf 'ro.build.product=CVEV.USA.0000.V015\npersist.ium.support=none\n' > $R/system/build.prop +python3 - "$T" "$R" <<'PY' +import sys, random, zipfile +T, R = sys.argv[1], sys.argv[2] +random.seed(5) +stock = bytearray(random.getrandbits(8) for _ in range(65536)) +open(R + "/system/lib/libtest.so", "wb").write(stock) +a = bytearray(stock); a[0x1000:0x1004] = b"\x01\x02\x03\x04"; open(T + "/lib.a", "wb").write(a) +b = bytearray(stock); b[0x3000:0x3004] = b"\x05\x06\x07\x08"; open(T + "/lib.b", "wb").write(b) +for d, n in (("app", "Test"), ("priv-app", "Priv")): + with zipfile.ZipFile(R + "/system/%s/%s.apk" % (d, n), "w") as z: + z.writestr("AndroidManifest.xml", b"manifest " + n.encode()) +odex = bytes(random.getrandbits(8) for _ in range(8192)) +open(R + "/system/app/Test.odex", "wb").write(odex) +open(R + "/system/priv-app/Priv.odex", "wb").write(odex) # the same bytes, so one delta fits both +open(T + "/classes.dex", "wb").write(b"dex\n035\0" + bytes(random.getrandbits(8) for _ in range(4096))) +PY +STOCK_LIB=$(md5 $R/system/lib/libtest.so); STOCK_APK=$(md5 $R/system/app/Test.apk); STOCK_ODEX=$(md5 $R/system/app/Test.odex) +STOCK_PRIV=$(md5 $R/system/priv-app/Priv.apk); cp $R/system/lib/libtest.so $T/lib.stock +mkdir -p $T/m +python3 tools/mkrecipe.py ra /system/lib/libtest.so $R/system/lib/libtest.so $T/lib.a > $T/m/ra.recipe +python3 tools/mkrecipe.py rb /system/lib/libtest.so $R/system/lib/libtest.so $T/lib.b > $T/m/rb.recipe +python3 tools/mkdelta.py $R/system/app/Test.odex $T/classes.dex $T/m/Test.lpd > /dev/null +mod() { # mod + d=$D/mods/$1; rm -rf $d; mkdir -p $d/patches/ev6 $d/files + printf '{"id": "%s", "version": "1.0.0"}\n' "$1" > $d/mod.json + printf '{"cars": {"CVEV.USA.": "ev6"}, "changes": [%s]}\n' "$2" > $d/patches.json + printf 'libtest.so %s\nTest.apk %s\nTest.odex %s\nPriv.apk %s\nPriv.odex %s\n' $STOCK_LIB $STOCK_APK $STOCK_ODEX $STOCK_PRIV $STOCK_ODEX > $d/patches/ev6/stock + cp $T/m/* $d/; echo bin > $d/files/x +} +APPS='{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "ra.recipe"}, + {"type": "app", "path": "/system/app/Test.apk", "delta": "Test.lpd"}, + {"type": "app", "path": "/system/priv-app/Priv.apk", "delta": "Test.lpd"}' + +# ---- Dalvik cache: only the app's own entry, by its real name (priv-app too) +echo old > $R/data/dalvik-cache/system@app@Test.apk@classes.dex +echo other > $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex +echo old > $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex +mod base "$APPS" +eng apply +check "apply: two apps and a library" 0 $rc +check "the app's own cache entry dropped" absent "$(md5 $R/data/dalvik-cache/system@app@Test.apk@classes.dex)" +check "... the priv-app's by its own name" absent "$(md5 $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex)" +check "... an app whose name ends the same way untouched" other "$(cat $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex)" +check "odex backup taken" "$STOCK_ODEX" "$(md5 $D/stock/system/app/Test.odex)" +check "... its md5 recorded" "$STOCK_ODEX" "$(rec $D/state/files.json 's["files"]["/system/app/Test.apk"].get("odex")')" +check "no half-written backup left" "" "$(find $D/stock -name '*.hmgapi-new')" +eng restore +check "restore" 0 $rc +check "... the stock odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" +check "... its cache entry filled from it" "$STOCK_ODEX" "$(md5 $R/data/dalvik-cache/system@app@Test.apk@classes.dex)" +check "... the priv-app's entry under system@priv-app@" "$STOCK_ODEX" "$(md5 $R/data/dalvik-cache/system@priv-app@Priv.apk@classes.dex)" +check "... no system@app@ entry made for the priv-app" absent "$(md5 $R/data/dalvik-cache/system@app@Priv.apk@classes.dex)" +check "... the other app's entry still untouched" other "$(cat $R/data/dalvik-cache/system@app@MyTest.apk@classes.dex)" + +# ---- a trial's settings, live props and binds: undone by recover with its files +printf 'global/foo=1\n' > $R/settings.txt +mod base "$APPS" +eng apply +BEFORE_LIB=$(md5 $R/system/lib/libtest.so) +mod tx '{"type": "prop", "key": "persist.test.x", "value": "1"}, + {"type": "setting", "namespace": "global", "key": "foo", "value": "2"}, + {"type": "bind", "src": "files/x", "target": "/sbin/adbd", "service": "adbd"}, + {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +rm -f $R/actions.log +eng apply --trial +check "trial apply" 0 $rc +has "... the prop set" "prop/persist.test.x=1" "$(cat $R/settings.txt)" +has "... the setting set" "global/foo=2" "$(cat $R/settings.txt)" +check "... the bind listed" "/data/hmgapi/mods/tx/files/x /sbin/adbd adbd" "$(cat $D/state/binds.txt)" +eng status +has "status: a trial in place" "trial apply in place" "$out" +rm -f $R/actions.log +eng recover +check "recover" 0 $rc +has "... says the trial is undone" "trial undone" "$out" +check "... the library back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +hasnt "... the trial's prop unset again" "persist.test.x" "$(cat $R/settings.txt)" +has "... the setting back to its old value" "global/foo=1" "$(cat $R/settings.txt)" +check "... binds as before the trial" "" "$(cat $D/state/binds.txt 2>/dev/null)" +has "... hmgapid told to undo the bind" "binds" "$(cat $R/actions.log 2>/dev/null)" +has "... and said so" "rolled back setting prop/persist.test.x = (unset)" "$out" +eng apply +check "the next apply" 0 $rc +check "... records the prop's stock as unset (not the trial's 1)" None "$(rec $D/state/files.json 's["settings"]["prop/persist.test.x"]["stock"]')" +check "... and the setting's as 1" 1 "$(rec $D/state/files.json 's["settings"]["global/foo"]["stock"]')" +rm -r $D/mods/tx +eng apply +hasnt "the mod off: its prop unset" "persist.test.x" "$(cat $R/settings.txt)" +has "... the setting stock" "global/foo=1" "$(cat $R/settings.txt)" + +# ---- an apply cut off after its settings, before its state: recover puts them back +mod cut '{"type": "prop", "key": "persist.cut.y", "value": "1"}, {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +BEFORE_LIB=$(md5 $R/system/lib/libtest.so); BEFORE_STATE=$(md5 $D/state/files.json) +export HMGAPI_TEST_CUT=settings; eng apply; unset HMGAPI_TEST_CUT +check "cut off (power lost)" 137 $rc +has "... the prop was set" "prop/persist.cut.y=1" "$(cat $R/settings.txt)" +check "... the journal left" yes "$(yes_no $D/state/journal.json)" +eng status +has "status: an apply didn't finish" "an apply didn't finish" "$out" +eng apply +check "another apply waits for recover" 1 $rc +eng recover +check "recover" 0 $rc +has "... an unfinished apply, not a trial" "unfinished apply rolled back" "$out" +hasnt "... the prop unset" "persist.cut.y" "$(cat $R/settings.txt)" +check "... the library back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +check "... the state as before" "$BEFORE_STATE" "$(md5 $D/state/files.json)" +mod cut '{"type": "bind", "src": "files/x", "target": "/sbin/adbd", "service": "adbd"}' +export HMGAPI_TEST_CUT=binds; eng apply; unset HMGAPI_TEST_CUT +check "cut off after the binds" 137 $rc +eng recover +check "... binds as before" "" "$(cat $D/state/binds.txt 2>/dev/null)" +rm -r $D/mods/cut + +# ---- room: checked before anything is written +mod rb '{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +BEFORE_LIB=$(md5 $R/system/lib/libtest.so) +export HMGAPI_TEST_FREE="system=1000"; eng apply; unset HMGAPI_TEST_FREE +check "/system full: refused" 3 $rc +has "... saying how much it needs" "not enough room on /system: this apply needs about" "$out" +check "... nothing written" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +check "... no journal" no "$(yes_no $D/state/journal.json)" +export HMGAPI_TEST_FREE="data=1000"; eng apply; unset HMGAPI_TEST_FREE +check "/data full: refused" 3 $rc +has "... saying so" "not enough room on /data" "$out" +# a /system that filled up mid-apply: recover makes room (a cut-off copy, then the file itself) +eng apply --trial +check "a trial" 0 $rc +echo half > $R/system/lib/libtest.so.hmgapi-new +export HMGAPI_TEST_FREE="system=0"; eng recover; unset HMGAPI_TEST_FREE +check "recover with /system full" 0 $rc +check "... the cut-off copy beside the file removed" absent "$(md5 $R/system/lib/libtest.so.hmgapi-new)" +check "... the file put back" "$BEFORE_LIB" "$(md5 $R/system/lib/libtest.so)" +has "... saying why it went first" "/system is short of room" "$out" +check "... no journal left" no "$(yes_no $D/state/journal.json)" +rm -r $D/mods/rb + +# ---- a damaged journal, a saved copy that's gone: set aside, not failing at every start +echo '{"trial": true, "entr' > $D/state/journal.json +eng status +has "status: the journal is damaged" "its journal (state/journal.json) is damaged" "$out" +eng keep +has "keep: says recover sets it aside" "damaged; \`engine recover\` sets it aside" "$out" +eng restore +check "restore waits for recover" 1 $rc +eng recover +check "recover with a damaged journal" 0 $rc +has "... set aside" "set aside as state/journal.bad.json" "$out" +hasnt "... claims nothing rolled back (the boot step restarts on that)" "rolled back" "$out" +check "... the journal gone" no "$(yes_no $D/state/journal.json)" +check "... kept to look at" yes "$(yes_no $D/state/journal.bad.json)" +eng apply +check "apply works again" 0 $rc +mod tx '{"type": "prop", "key": "persist.test.z", "value": "1"}, {"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +eng apply --trial +rm $D/state/prev/_system_lib_libtest.so +eng recover +check "recover with a saved copy gone" 0 $rc +has "... that file named" "can't put back /system/lib/libtest.so: its saved copy is gone" "$out" +hasnt "... the rest still put back (the prop)" "persist.test.z" "$(cat $R/settings.txt)" +check "... the journal set aside, not tried again at every start" no "$(yes_no $D/state/journal.json)" +eng recover +has "... a second recover has nothing to do" "nothing to recover" "$out" +eng apply +has "... the next apply says the file isn't HMG-API's result" "/system/lib/libtest.so: changed outside HMG-API" "$out" +eng apply --force +check "... --force builds it again" 0 $rc +rm -r $D/mods/tx +eng apply --trial +printf 'x' >> "$(ls $D/state/prev/* | head -n 1)" +eng recover +has "a saved copy that isn't what was saved: not written back" "its saved copy is damaged" "$out" +eng apply --force >/dev/null + +# ---- backups: checked against the recorded md5 before every use +eng restore +check "restore to stock" 0 $rc +check "... library stock" "$STOCK_LIB" "$(md5 $R/system/lib/libtest.so)" +mod base "$APPS" +eng apply +check "apply again" 0 $rc +head -c 4000 $T/classes.dex > $D/stock/system/app/Test.odex # a cut-off odex backup +APK_NOW=$(md5 $R/system/app/Test.apk) +eng restore +check "a damaged odex backup: restore refused" 3 $rc +has "... saying which and what it should be" "HMG-API's stock backup /data/hmgapi/stock/system/app/Test.odex is damaged" "$out" +check "... the app left as it is (not a stock apk with a short odex)" "$APK_NOW" "$(md5 $R/system/app/Test.apk)" +# the priv-app's odex backup has the same stock bytes as Test.odex's +mkdir -p $R/data/nemesis/backup/pkg; cp $D/stock/system/priv-app/Priv.odex $R/data/nemesis/backup/pkg/Test.odex +eng restore +check "... a NEMESIS copy with the recorded md5 stands in" 0 $rc +has "... noted" "using the stock copy NEMESIS kept (pkg)" "$out" +check "... the stock odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" +rm -r $R/data/nemesis +eng apply +head -c 30000 $R/system/lib/libtest.so > $D/stock/system/lib/libtest.so # a cut-off backup of the library +mod rb '{"type": "recipe", "path": "/system/lib/libtest.so", "recipe": "rb.recipe"}' +eng plan +check "a damaged backup: no rebuild from it" 3 $rc +has "... saying so" "HMG-API's stock backup /data/hmgapi/stock/system/lib/libtest.so is damaged" "$out" +mkdir -p $R/data/nemesis/backup/pkg; cp $T/lib.stock $R/data/nemesis/backup/pkg/libtest.so +eng apply +check "... rebuilt from a NEMESIS copy with the recorded md5" 0 $rc +check "... the backup taken again, whole" "$STOCK_LIB" "$(md5 $D/stock/system/lib/libtest.so)" +rm -r $R/data/nemesis $D/mods/rb +eng apply +# an app's rebuild with a damaged odex backup: a NEMESIS copy that fits is used, and backed up again +mkdir -p $R/data/nemesis/backup/pkg; cp $D/stock/system/app/Test.odex $R/data/nemesis/backup/pkg/Test.odex +printf 'x' >> $D/stock/system/app/Test.odex +rm $R/system/app/Test.apk # so --force writes the app again +eng apply --force +check "app rebuilt with its odex backup damaged" 0 $rc +check "... the odex backup is stock again" "$STOCK_ODEX" "$(md5 $D/stock/system/app/Test.odex)" +rm -r $R/data/nemesis +# a record from before the odex md5 was kept: a cut-short Dalvik odex is still caught by its header +python3 - $D/state/files.json $D/stock/system/app/Test.odex <<'PY' +import json, struct, sys +s = json.load(open(sys.argv[1])); del s["files"]["/system/app/Test.apk"]["odex"]; json.dump(s, open(sys.argv[1], "w")) +open(sys.argv[2], "wb").write(b"dey\n036\0" + struct.pack("<8I", 40, 1000, 1040, 10, 1050, 90000, 0, 0) + b"\0" * 1000) +PY +eng restore +check "an older record, odex shorter than its header says: refused" 3 $rc +has "... saying so" "is cut short" "$out" + +exit $fail diff --git a/core/runtime/safety-test.sh b/core/runtime/safety-test.sh index cc8defb7..52ea1dcc 100644 --- a/core/runtime/safety-test.sh +++ b/core/runtime/safety-test.sh @@ -78,6 +78,16 @@ printf '{"overrides": {"allow_critical": ["/system/build.prop:ro.build.version.r mod a '{"type": "props", "path": "/system/build.prop", "set": {"ro.build.version.release": "4.4.4"}, "stock": "any"}' eng plan; check "ro.* key allowed by override" 0 $rc rm $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "props", "path": "/system/build.prop", "set": {"dalvik.vm.heapsize": "512m"}, "stock": "any"}' +eng plan; has "dalvik.* key refused" "dalvik.vm.heapsize; dalvik.* and persist.sys.dalvik.* properties set how Dalvik starts" "$out"; check "... refusal exit" 3 $rc +mod a '{"type": "props", "path": "/system/build.prop", "set": {"persist.sys.dalvik.vm.lib": "libart.so"}, "stock": "any"}' +eng plan; has "persist.sys.dalvik.* key in build.prop refused (the runtime switch)" "changes persist.sys.dalvik.vm.lib" "$out" +printf '{"overrides": {"allow_critical": ["/system/build.prop:dalvik.vm.heapsize"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "props", "path": "/system/build.prop", "set": {"dalvik.vm.heapsize": "512m"}, "stock": "any"}' +eng plan; check "dalvik.* key allowed by override" 0 $rc +has "... with a warning" "WARNING: /system/build.prop: dalvik.vm.heapsize can keep the unit from booting" "$out" +rm $R/data/hmgapi/settings/hmgapi.json +check "build.prop still untouched" "$STOCK_PROP" "$(md5 $R/system/build.prop)" # ---- boot-critical and HMG-API's own files mod a '{"type": "add", "path": "/system/lib/libc.so", "src": "a.xml", "stock": "any"}' @@ -89,10 +99,29 @@ eng plan; has "HMG-API's own files refused even with overrides" "belongs to HMG- rm $R/data/hmgapi/settings/hmgapi.json mod a '{"type": "add", "path": "/system/framework/framework.jar", "src": "a.xml"}' eng plan; has "boot class path jar refused" "framework.jar: the unit needs this file to boot" "$out" +for p in /system/framework/framework-res.apk /system/lib/libz.so /system/lib/libcrypto.so /system/lib/libicuuc.so \ + /system/usr/icu/icudt51l.dat /system/lib/libgui.so /system/lib/libEGL.so /system/lib/hw/gralloc.tcc803x.so \ + /system/lib/egl/libGLES_mali.so /system/bin/netd /system/bin/mediaserver; do + mod a '{"type": "add", "path": "'$p'", "src": "a.xml", "stock": "any"}' + eng plan; has "boot-critical: $p refused" "$p: the unit needs this file to boot" "$out" +done +printf '{"overrides": {"allow_critical": ["/system/lib/hw/gralloc.tcc803x.so"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "add", "path": "/system/lib/hw/gralloc.tcc803x.so", "src": "a.xml", "stock": "any"}' +eng plan; has "a hardware module allowed by override, with a warning" "WARNING: /system/lib/hw/gralloc.tcc803x.so is boot-critical" "$out" +rm $R/data/hmgapi/settings/hmgapi.json +mod a '{"type": "add", "path": "/system/lib/hwx/x.so", "src": "a.xml", "stock": "any"}' +eng plan; check "a folder that only starts like hw/ isn't critical" 0 $rc # ---- live props mod a '{"type": "prop", "key": "ro.secure", "value": "0"}' eng plan; has "non-persist prop refused" "only persist.* properties can be set" "$out" +mod a '{"type": "prop", "key": "persist.sys.dalvik.vm.lib", "value": "libart.so"}' +eng plan; has "the runtime switch refused" "prop persist.sys.dalvik.vm.lib: dalvik.* and persist.sys.dalvik.* properties" "$out" +has "... naming the override" "overrides.allow_critical \"prop:persist.sys.dalvik.vm.lib\"" "$out"; check "... refusal exit" 3 $rc +printf '{"overrides": {"allow_critical": ["prop:persist.sys.dalvik.vm.lib"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +eng plan; check "... allowed by override" 0 $rc +has "... with a warning" "WARNING: prop persist.sys.dalvik.vm.lib can keep the unit from booting" "$out" +rm $R/data/hmgapi/settings/hmgapi.json printf 'prop/persist.sys.iap2.wifi=f\n' > $R/settings.txt mod a '{"type": "prop", "key": "persist.sys.iap2.wifi", "value": "t"}, {"type": "prop", "key": "persist.iap2.iden.wireless", "value": "t"}' eng apply; has "persist prop set live" "prop/persist.sys.iap2.wifi=t" "$(cat $R/settings.txt)" @@ -123,6 +152,9 @@ has "hmgapid told to do it" "binds" "$(cat $R/actions.log 2>/dev/null)" mod a '{"type": "bind", "src": "files/x", "target": "/system/bin/linker", "service": "x"}' mkdir -p $R/data/hmgapi/mods/a/files; echo bin > $R/data/hmgapi/mods/a/files/x eng plan; has "bind over a boot-critical binary refused" "the unit needs /system/bin/linker to boot" "$out" +mod a '{"type": "bind", "src": "files/x", "target": "/system/bin/netd", "service": "netd"}' +mkdir -p $R/data/hmgapi/mods/a/files; echo bin > $R/data/hmgapi/mods/a/files/x +eng plan; has "bind over a boot daemon refused" "the unit needs /system/bin/netd to boot" "$out" mod a '{"type": "add", "path": "/system/etc/permissions/b.xml", "src": "a.xml"}' eng apply; has "binds dropped with the mod: unbind planned" "binds" "$(cat $R/actions.log)" check "binds.txt empty again" "" "$(cat $R/data/hmgapi/state/binds.txt)" diff --git a/core/runtime/usb-test.sh b/core/runtime/usb-test.sh index 0502dc94..7a6fb1d3 100755 --- a/core/runtime/usb-test.sh +++ b/core/runtime/usb-test.sh @@ -64,6 +64,12 @@ has "update in place" '"version": "2.0.0"' "$(cat $R/data/hmgapi/mods/beta/mod.j eng update-hmgapi $U/HMGAPI/updates/hmgapi-fake.zip; check "fake release not run" 3 $rc check "its installer didn't run" no "$([ -e $R/installed-9.9.9 ] && echo yes || echo no)" +echo '{"trial": true, "committed": true, "entries": [], "state": {}}' > $R/data/hmgapi/state/journal.json +eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip; check "a trial in place: no self-update" 1 $rc +has "... saying what to do first" "refused: an earlier apply isn't finished or is a trial: run \`engine keep\` (trial) or \`engine recover\` first" "$out" +eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip --force; check "... --force doesn't step around it" 1 $rc +check "... its installer didn't run" no "$([ -e $R/installed-9.9.9 ] && echo yes || echo no)" +rm $R/data/hmgapi/state/journal.json eng update-hmgapi $U/HMGAPI/updates/hmgapi-9.9.9.zip; check "genuine release runs its installer" 0 $rc has "installer output passed on" "fake installer ran" "$out" check "installer ran" yes "$([ -e $R/installed-9.9.9 ] && echo yes)" diff --git a/tools/test-all.sh b/tools/test-all.sh index 0d50eb41..64d76673 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/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/journal-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/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/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/journal-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/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" diff --git a/tools/test-select.py b/tools/test-select.py index 37887ed8..346b20c7 100755 --- a/tools/test-select.py +++ b/tools/test-select.py @@ -15,7 +15,7 @@ RUNTIME = ['core/runtime/*-test.sh'] # the tests that compile hmgapi.engine (tools/engine-classes.sh): the rest of core/runtime's # Java (hook, vehicle) is only compiled by the build and the SDK, and its own tests -ENGINE = ['core/runtime/engine-test.sh', 'core/runtime/signing-test.sh', 'core/runtime/system-test.sh', 'core/runtime/safety-test.sh', +ENGINE = ['core/runtime/engine-test.sh', 'core/runtime/signing-test.sh', 'core/runtime/system-test.sh', 'core/runtime/safety-test.sh', 'core/runtime/journal-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/live-test.sh', 'core/runtime/native-test.sh', 'core/runtime/runtime-test.sh', 'core/runtime/net-test.sh', 'core/runtime/homewifi-test.sh', 'core/runtime/overlap-test.sh', 'core/runtime/scriptcheck-test.sh', 'install/nemesis/mod-test.sh', 'install/nemesis/sync-test.sh', @@ -54,7 +54,7 @@ (['install/*'], INSTALL + ['core/runtime/packages-test.sh']), (['tools/zygote-orders.py'], ['install/common/orders-test.sh']), (['install/nemesis/mod/*', 'install/nemesis/bin/open.sh'], SDK), - (['tools/mkdelta.py', 'tools/mkrecipe.py', 'tools/mkmemrecipe.py'], ['core/runtime/engine-test.sh', 'core/runtime/safety-test.sh', 'tools/lpatch/test.sh']), + (['tools/mkdelta.py', 'tools/mkrecipe.py', 'tools/mkmemrecipe.py'], ['core/runtime/engine-test.sh', 'core/runtime/safety-test.sh', 'core/runtime/journal-test.sh', 'tools/lpatch/test.sh']), (['tools/mkinstallers.sh', 'tools/mkrelease.sh', 'tools/mkmodpkg.sh', 'tools/mknemesismod.sh', 'tools/nemesis-version.py', 'tools/nemesis-meta.py', 'tools/release-mods.txt'], INSTALL + ['core/runtime/signing-test.sh', 'core/runtime/usb-test.sh'] + SDK + MODS), # the mod SDK and the reusable mod workflow (['tools/build-mod.sh', 'tools/check-points.py', 'tools/sdk/*', 'tools/sdk-test.sh', 'tools/mkrecipe.py', 'tools/mkdelta.py', 'tools/mkmemrecipe.py', 'tools/mkicon.sh', 'tools/mod-draft.py', 'tools/check-scripts.sh', '.github/workflows/mod.yml'], SDK), From f1e44222443e67a4e5cc712f3bd9c1a26ad58a98 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:28:47 -0500 Subject: [PATCH 20/69] 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 4a2606a76711ccb344d89f8ee1ecee178b91bac5 Mon Sep 17 00:00:00 2001 From: anthonyanderson Date: Fri, 27 Nov 2026 09:29:28 -0500 Subject: [PATCH 21/69] Engine: roll back a failed apply at once, journal held apps, keep file modes A failed apply (rename, dexopt, remount, copy, settings, state write) now puts every file and setting back in the same run, last changed first, deletes its temp files and starts the apps it stopped. Only a power cut, a killed engine or a failed rollback leaves the journal for recover. Apps stopped (pm disable) while their files change are written to the journal and state/held.txt before they're stopped. recover starts them again, and boot.sh runs engine release-held once Android is up (not while an unfinished apply is waiting). Android itself, persistent apps, OTAClient and apps already off are never stopped. Each file's mode, owner and SELinux label are read before HMG-API first writes it (FileMeta, files.json stockMeta, journal entries) and put back on apply, rollback and restore. A change under /system/bin or /system/xbin must give a "mode". Tests: engine, safety, overlap and boot.sh, with a fake pm and failure injection (HMGAPI_TEST_FAIL, off the unit only). Tested off-car only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 + core/runtime/engine-test.sh | 159 +++++ core/runtime/java/hmgapi/engine/Engine.java | 586 ++++++++++++++---- core/runtime/java/hmgapi/engine/FileMeta.java | 191 ++++++ core/runtime/overlap-test.sh | 7 + core/runtime/safety-test.sh | 21 + docs/mod-reference.md | 5 + install/common/boot.sh | 8 + install/common/test.sh | 7 + install/common/uninstall.sh | 3 +- 10 files changed, 878 insertions(+), 134 deletions(-) create mode 100644 core/runtime/java/hmgapi/engine/FileMeta.java diff --git a/CHANGELOG.md b/CHANGELOG.md index c4168555..f4a9dd7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## Unreleased + +- **A failed apply is rolled back at once.** When a rename, a dexopt, a remount or a copy + failed part-way, /system stayed half-applied (one library new, the next stock, an app's + odex deleted) until the next start, and every other engine command was refused. Now the + same run puts every file and setting back, last changed first, deletes its temp files + (`*.hmgapi-new`, `stage/`), and starts the apps it stopped. Only a power cut, a killed + engine or a rollback that fails too leaves the journal for the next start (`engine recover`). +- **Apps stopped during an apply always come back.** The apps whose files change (GPM, + DiPO, iAP2, navigation, BtSettings) are `pm disable`d for the swap, and Android keeps them + off across restarts. The list lived only in memory, so a power cut (the driver's door, the + battery saver) or a killed engine left them off for good. It's now written to the journal + and `state/held.txt` before any is stopped; `engine recover` starts them again, and at boot, + once Android is up, `engine release-held` does (only with no unfinished apply left, so they + never run on half-changed files). Android itself (`framework-res.apk`), persistent apps + (`packages.xml`), OTAClient and apps that were off already are never stopped. +- **File modes, owners and SELinux labels are kept.** Every file was written, restored and + rolled back as 644 root:root, whatever it was: uninstalling a mod that patched a binary in + `/system/bin` put the stock one back unable to run. Each file's own mode, owner and label + are now read before HMG-API first writes it and put back on restore and rollback; a change + with no `"mode"` keeps them. A change under `/system/bin` or `/system/xbin` with no `"mode"` + is refused. Files recorded by an earlier HMG-API get Android's defaults on restore (755 + root:shell in `/system/bin` and `/system/xbin`, 644 root:root elsewhere). + Tested off-car only. + ## 1.1.0-rc.10 (2026-11-25) - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` diff --git a/core/runtime/engine-test.sh b/core/runtime/engine-test.sh index 89634abd..1aac477b 100644 --- a/core/runtime/engine-test.sh +++ b/core/runtime/engine-test.sh @@ -433,4 +433,163 @@ for i in 1 2 3; do done echo "ok three plans at once on a fresh mod, three rounds" check "... the feature file written once, no .tmp left" "android.hardware.wifi.xml" "$(ls -A $R/data/hmgapi/mods/wa/.features)" + +# ---- a failed apply: rolled back in the same run; a cut-off one: by recover. Apps held while +# their files change are journaled first and always started again; modes, owners, labels kept. +# Off the unit, owners and labels live in $R/meta.txt (FileMeta), the mode is the file's own. +rm -rf $R/data/hmgapi/mods/* $R/data/hmgapi/state $R/data/hmgapi/stock +check "app stock before" "$STOCK_APK $STOCK_ODEX" "$(md5 $R/system/app/Test.apk) $(md5 $R/system/app/Test.odex)" +mkdir -p $R/system/bin $R/system/framework $R/data/system +mode() { python3 -c 'import os, sys; print(oct(os.stat(sys.argv[1]).st_mode & 0o7777)[2:])' "$1"; } +own() { m=$(mode $R$1); o=$(grep "^$1 " $R/meta.txt 2>/dev/null | sed "s#^$1 ##"); echo "$m ${o:-0 0 -}"; } +for f in lib/a.so lib/z.so bin/netd framework/framework-res.apk app/Pers.apk app/Off.apk; do + head -c 4096 /dev/urandom > $R/system/$f; head -c 4096 /dev/urandom > $T/m/$(basename $f).new +done +chmod 640 $R/system/lib/a.so; chmod 644 $R/system/lib/z.so; chmod 755 $R/system/bin/netd +printf '%s\n' "/system/lib/a.so 1000 1000 u:object_r:system_file:s0" "/system/bin/netd 0 2000 u:object_r:netd_exec:s0" > $R/meta.txt +cp -p $R/meta.txt $T/meta.stock +OWN_A=$(own /system/lib/a.so); OWN_Z=$(own /system/lib/z.so); OWN_N=$(own /system/bin/netd) +check "stock modes and owners set up" "640 1000 1000 u:object_r:system_file:s0|644 0 0 -|755 0 2000 u:object_r:netd_exec:s0" "$OWN_A|$OWN_Z|$OWN_N" +sums() { for f in lib/a.so lib/z.so bin/netd app/Test.apk app/Test.odex framework/framework-res.apk app/Pers.apk app/Off.apk; do md5 $R/system/$f; done | tr '\n' ' '; } +STOCK_ALL=$(sums) +# a package manager: Test.apk's app runs, Off.apk's is off already, Pers.apk's is persistent, framework-res is android +cat > $T/pm <> $T/pm.calls +case "\$1 \$2" in + "list packages") if [ "\$3" = -f ]; then cat $T/pm.pkgs; else sed 's/^/package:/' $T/pm.off; fi ;; + "disable "*) echo "\$2" >> $T/pm.off; echo "Package \$2 new state: disabled" ;; + "enable "*) grep -vx "\$2" $T/pm.off > $T/pm.off.n || true; mv $T/pm.off.n $T/pm.off; echo "Package \$2 new state: enabled" ;; +esac +EOF +chmod +x $T/pm +printf 'package:%s\n' /system/app/Test.apk=com.test.app /system/app/Off.apk=com.test.off /system/app/Pers.apk=com.test.pers \ + /system/framework/framework-res.apk=android > $T/pm.pkgs +cat > $R/data/system/packages.xml <<'X' + + + + + + + +X +pmreset() { echo com.test.off > $T/pm.off; rm -f $T/pm.calls; } +# engf ": ...": eng with those steps failing (Engine.testFail); exported and unset again, since +# sh keeps a variable put before a function call +engf() { HMGAPI_TEST_FAIL=$1; export HMGAPI_TEST_FAIL; shift; eng "$@"; unset HMGAPI_TEST_FAIL; } +pmreset +export HMGAPI_PM=$T/pm HMGAPI_PROPS="sys.boot_completed=1" +mod rb 1.0.0 '' ' + {"type": "add", "path": "/system/lib/a.so", "src": "a.so.new", "stock": "any"}, + {"type": "add", "path": "/system/lib/z.so", "src": "z.so.new", "stock": "any"}, + {"type": "add", "path": "/system/bin/netd", "src": "netd.new", "stock": "any", "mode": "755"}, + {"type": "app", "path": "/system/app/Test.apk", "delta": "Test.lpd"}, + {"type": "add", "path": "/system/framework/framework-res.apk", "src": "framework-res.apk.new", "stock": "any"}, + {"type": "add", "path": "/system/app/Pers.apk", "src": "Pers.apk.new", "stock": "any"}, + {"type": "add", "path": "/system/app/Off.apk", "src": "Off.apk.new", "stock": "any"}' +cp $T/m/*.new $T/m/Test.lpd $R/data/hmgapi/mods/rb/ +J=$R/data/hmgapi/state/journal.json; HELD=$R/data/hmgapi/state/held.txt +left() { find $R/system -name '*.hmgapi-new' | tr '\n' ' '; } +allstock() { # allstock : every file, mode, owner and label as before, nothing left over, apps as before + check "$1: every file as it was" "$STOCK_ALL" "$(sums)" + check "$1: modes, owners, labels as they were" "$OWN_A|$OWN_Z|$OWN_N" "$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" + check "$1: no journal, no prev/, no held list, no temp files" "no no no " "$([ -f $J ] && echo yes || echo no) $([ -d $R/data/hmgapi/state/prev ] && echo yes || echo no) $([ -f $HELD ] && echo yes || echo no) $(left)" + check "$1: the app it held started again; the one off before still off" "com.test.off" "$(cat $T/pm.off)" +} + +engf "swap:/system/lib/z.so" apply +check "a swap failing part-way (a.so written, z.so not): the apply fails" 1 $rc +has "... saying why" "apply failed: java.io.IOException: test: swap fails at /system/lib/z.so" "$out" +has "... rolled back in the same run, last written first" "rolled back /system/lib/a.so" "$out" +has "... all of it" "rolled back: every file is as it was before this apply" "$out" +allstock "swap failure" +has "... the app was stopped first, then started again" "disable com.test.app|" "$(tr '\n' '|' < $T/pm.calls)" +hasnt "... Android itself (framework-res.apk) never stopped" "disable android" "$(cat $T/pm.calls)" +hasnt "... nor a persistent app" "disable com.test.pers" "$(cat $T/pm.calls)" +hasnt "... nor one that was off already (or started)" "com.test.off" "$(grep -v '^list' $T/pm.calls)" +has "... said" "note com.test.pers keeps running while /system/app/Pers.apk changes (persistent)" "$out" +check "... no record of the failed apply" "" "$(grep -o 'a\.so' $R/data/hmgapi/state/files.json 2>/dev/null || true)" +eng plan +check "... other commands aren't refused after it" 0 $rc + +pmreset +engf "dexopt:/system/app/Test.apk" apply +check "dexopt failing (the odex deleted already): the apply fails" 1 $rc +allstock "dexopt failure" +check "... the odex back" "$STOCK_ODEX" "$(md5 $R/system/app/Test.odex)" + +pmreset +engf "put:/system/lib/z.so" apply +check "a copy failing: the apply fails" 1 $rc +allstock "copy failure (its temp file deleted)" + +pmreset +engf "remount:rw" apply +check "remount rw failing: the apply fails" 1 $rc +allstock "remount failure" +hasnt "... nothing had changed, so nothing rolled back" "rolled back /system" "$out" + +# a power cut (or a killed engine) in the middle: a.so new, z.so stock, the app off +pmreset +engf "halt:/system/lib/z.so" apply +check "cut off mid-swap: the journal stays" yes "$([ -f $J ] && echo yes)" +check "... a.so new, z.so stock" "$(md5 $T/m/a.so.new) $(md5 $R/data/hmgapi/state/prev/_system_lib_z.so)" "$(md5 $R/system/lib/a.so) $(md5 $R/system/lib/z.so)" +check "... the held app journaled before it was stopped, and still off" "com.test.app|com.test.app" "$(cat $HELD)|$(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1]))["held"]))' $J)" +has "... (off in the package manager)" "com.test.app" "$(cat $T/pm.off)" +eng plan +check "... other commands wait for recover" 1 $rc +eng status +has "... status names the held app" "held [com.test.app]" "$out" +export HMGAPI_PROPS="" # recover at boot runs before Android is up +eng recover +check "recover before Android is up" 0 $rc +has "... rolled back" "unfinished apply rolled back" "$out" +check "... files, modes, owners back" "$STOCK_ALL|$OWN_A|$OWN_Z|$OWN_N" "$(sums)|$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" +has "... the app left for boot.sh" "start again once Android is up (boot.sh: engine release-held)" "$out" +check "... still in held.txt" "com.test.app" "$(cat $HELD)" +eng release-held +check "release-held with Android not up: waits" 1 $rc +export HMGAPI_PROPS="sys.boot_completed=1" +eng release-held +check "release-held once Android is up" 0 $rc +allstock "power cut, then recover and release-held" + +# the rollback fails too: the journal stays, the apps stay off with their files half-changed, recover finishes later +pmreset +engf "swap:/system/lib/z.so rollback:/system/lib/a.so" apply +check "a rollback that fails too: the apply fails" 1 $rc +has "... said" "NOT rolled back: [/system/lib/a.so (test: rollback fails at /system/lib/a.so)]" "$out" +check "... the journal kept" yes "$([ -f $J ] && echo yes)" +has "... the app stays off" "com.test.app" "$(cat $T/pm.off)" +eng release-held +check "... release-held won't start it over half-changed files" 1 $rc +eng recover +check "... recover finishes it" 0 $rc +allstock "failed rollback, then recover" + +# a good apply: modes and owners kept, a mod's mode used, stock ones recorded; restore puts them back +pmreset +eng apply +check "apply" 0 $rc +check "a file with no mode keeps its stock mode, owner and label" "$OWN_A" "$(own /system/lib/a.so)" +check "netd: the mod's mode, the stock owner and label" "$OWN_N" "$(own /system/bin/netd)" +check "the held app started again" "com.test.off" "$(cat $T/pm.off)" +check "no held list left" no "$([ -f $HELD ] && echo yes || echo no)" +check "stock modes recorded" "640 1000 1000 u:object_r:system_file:s0" "$(python3 -c 'import json, sys; m = json.load(open(sys.argv[1]))["files"]["/system/lib/a.so"]["stockMeta"]["/system/lib/a.so"]; print(m["mode"], m["uid"], m["gid"], m["context"])' $R/data/hmgapi/state/files.json)" +eng restore +check "restore" 0 $rc +check "restore: files, modes, owners, labels stock" "$STOCK_ALL|$OWN_A|$OWN_Z|$OWN_N" "$(sums)|$(own /system/lib/a.so)|$(own /system/lib/z.so)|$(own /system/bin/netd)" +# a record from before modes were kept, and netd as that HMG-API wrote it (644 0:0): restore uses /system/bin's 755 0:2000 +eng apply +python3 - $R/data/hmgapi/state/files.json <<'PY' +import json, sys +s = json.load(open(sys.argv[1])) +for f in s["files"].values(): f.pop("stockMeta", None) +json.dump(s, open(sys.argv[1], "w")) +PY +chmod 644 $R/system/bin/netd; sed -i.bak '/^\/system\/bin\/netd /d' $R/meta.txt +eng restore +check "restore of an old record: /system/bin's defaults" "755 0 2000 -" "$(own /system/bin/netd)" +unset HMGAPI_PM HMGAPI_PROPS exit $fail diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..f55e3fc5 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -26,7 +26,8 @@ * engine keep keep a trial apply * engine restore every file and setting HMG-API changed back to stock * engine status files HMG-API owns: stock, mods, expected and live md5 - * engine recover at start (hmgapid): roll back an unfinished or trial apply + * engine recover at start (hmgapid): roll back an unfinished or trial apply, start the apps it held + * engine release-held at start, once Android is up: start apps an apply left stopped (state/held.txt) * * Mods: /data/hmgapi/mods//patches.json (see the wiki's patch engine page). * The goal: mods work side by side and never overwrite each other. HMG-API @@ -423,6 +424,7 @@ int run(String[] args) throws Exception { } if ("nemesis-sync".equals(cmd)) return NemesisSync.run(this); if ("recover".equals(cmd)) return recover(); + if ("release-held".equals(cmd)) return releaseHeld(); if ("keep".equals(cmd)) return keep(); if ("firmware-reset".equals(cmd)) return firmwareReset(); if (journalFile.exists() && !"keep".equals(cmd)) { @@ -437,7 +439,7 @@ int run(String[] args) throws Exception { if (!map.runnable) out.add("hooks are off on this car (" + map.reason + "): mods apply without their hooks"); } if (!restoreAll && !"plan".equals(cmd) && !"apply".equals(cmd)) { - 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"); + out.add("usage: engine plan | apply [--trial] | keep | restore | status | recover | release-held | 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); @@ -918,6 +920,7 @@ static final class Target { File odexSrc; // app: the stock odex its delta was built from (backed up at apply) Set mods = new LinkedHashSet(); boolean restore; // no mod wants it any more: back to stock + Map stockMeta; // path (and an app's odex) -> FileMeta's map, as before HMG-API's first write } final class Plan { @@ -1120,6 +1123,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { t.stock = (String) f.get("stock"); t.result = t.stock; t.app = Boolean.TRUE.equals(f.get("app")); + t.stockMeta = f.get("stockMeta") instanceof Map ? (Map) f.get("stockMeta") : null; continue; } int before = problems.size(); @@ -1154,6 +1158,7 @@ Plan plan(boolean restoreAll, boolean force) throws Exception { t.stock = (String) f.get("stock"); t.result = t.stock; t.app = Boolean.TRUE.equals(f.get("app")); + t.stockMeta = f.get("stockMeta") instanceof Map ? (Map) f.get("stockMeta") : null; } } return p; @@ -1273,6 +1278,11 @@ String guard(Target t) { return t.path + ": " + ch.mod.id + ": mode " + ms + " (only plain modes like 644 or 755: no setuid, setgid or sticky bits)"; } } + // a binary written without its mode doesn't run, and an uninstall putting back a stock one that + // doesn't run can keep the unit from booting: say it, every time + if ((t.path.startsWith("/system/bin/") || t.path.startsWith("/system/xbin/")) && modeOf(t) == null && !t.changes.isEmpty()) { + return t.path + ": " + t.changes.get(0).mod.id + ": a change in /system/bin or /system/xbin needs a \"mode\" (\"755\" for a program)"; + } if (t.path.equals("/system/build.prop")) { for (Ch ch : t.changes) { if (!"props".equals(ch.type)) { @@ -1313,6 +1323,12 @@ String guard(Target t) { return null; } + /** the "mode" a target's changes give it (the first that gives one), or null */ + static String modeOf(Target t) { + for (Ch ch : t.changes) if (ch.c.get("mode") != null) return String.valueOf(ch.c.get("mode")); + return null; + } + @SuppressWarnings("unchecked") boolean allowedCritical(String what) { Object o = hmgapi.get("overrides"); @@ -1343,6 +1359,7 @@ void build(Target t, Map owned) throws Exception { if (owned != null) { t.stock = (String) owned.get("stock"); t.baseline = "absent".equals(t.stock) ? null : backup(t.path); + t.stockMeta = owned.get("stockMeta") instanceof Map ? (Map) owned.get("stockMeta") : null; } else { String m = md5(live); if ("absent".equals(m)) { @@ -1827,6 +1844,14 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply + /** + * One transaction. The journal (what each file was, its bytes in prev/, its mode, owner and + * label) goes down before anything changes, the apps holding changed files are written into + * it before they're stopped, and any failure (a rename, a dexopt, a remount, a full disk) + * puts every file and setting back in this same run, last changed first, then starts the + * apps again. Only a cut-off run (a power cut, a killed engine) or a rollback that fails + * too leaves the journal for the next start (boot.sh: engine recover). + */ @SuppressWarnings("unchecked") void apply(Plan p, boolean trial) throws Exception { Map files = (Map) p.state.get("files"); @@ -1842,6 +1867,9 @@ void apply(Plan p, boolean trial) throws Exception { prevDir.mkdirs(); List entries = new ArrayList(); for (Target t : changed) { + // a file HMG-API hasn't written yet: its mode, owner and label as found are its stock ones (restore puts them back) + boolean first = !t.restore && t.stockMeta == null && p.owned(t.path) == null; + Map sm = new LinkedHashMap(); for (String path : withOdex(t)) { Map e = new LinkedHashMap(); e.put("path", path); @@ -1850,109 +1878,168 @@ void apply(Plan p, boolean trial) throws Exception { File prev = new File(prevDir, path.replace('/', '_')); copy(live, prev); e.put("prev", prev.getPath()); - e.put("mode", mode(live)); + Map meta = FileMeta.read(this, live).toMap(); + e.putAll(meta); + if (first) sm.put(path, meta); } entries.add(e); } + if (!sm.isEmpty()) t.stockMeta = sm; } Map j = new LinkedHashMap(); j.put("trial", trial); j.put("committed", false); j.put("entries", entries); + j.put("held", new ArrayList()); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below write(journalFile, Json.write(j)); - // files taken as found (changed outside HMG-API): their old backups no longer say what was there - for (String path : p.rebased.keySet()) { - rm(backup(path)); - if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); - } - // stock backups, once - for (Target t : changed) { - if (!t.newBackup) continue; - copy(t.baseline, backup(t.path)); - if (t.app) { - String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (t.odexSrc != null && t.odexSrc.isFile() && !backup(odex).isFile()) copy(t.odexSrc, backup(odex)); + Set held = new LinkedHashSet(); + List settingsUndo = new ArrayList(); // {key, live value before}, in the order set + String bindsBefore = currentBinds(); + boolean rw = false, keepHeld = false; + try { + // files taken as found (changed outside HMG-API): their old backups no longer say what was there + for (String path : p.rebased.keySet()) { + rm(backup(path)); + if (path.endsWith(".apk")) rm(backup(path.replaceAll("\\.apk$", ".odex"))); + } + // stock backups, once + for (Target t : changed) { + if (!t.newBackup) continue; + copy(t.baseline, backup(t.path)); + if (t.app) { + String odex = t.path.replaceAll("\\.apk$", ".odex"); + if (t.odexSrc != null && t.odexSrc.isFile() && !backup(odex).isFile()) copy(t.odexSrc, backup(odex)); + } } - } - Set held = hold(changed); - try { + held = hold(changed, j); remount("rw"); + rw = true; for (Target t : changed) swap(t); - } finally { + rw = false; remount("ro"); - release(held); - } - // settings - for (Map.Entry e : p.settings.entrySet()) { - String k = e.getKey(); - String v = String.valueOf(e.getValue()[0]); - Map s = (Map) st.get(k); - if (s != null && v.equals(String.valueOf(s.get("value")))) continue; - String was; - if (s == null) { - s = new LinkedHashMap(); - s.put("stock", settingGet(k)); - st.put(k, s); - was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + // settings + for (Map.Entry e : p.settings.entrySet()) { + String k = e.getKey(); + String v = String.valueOf(e.getValue()[0]); + Map s = (Map) st.get(k); + if (s != null && v.equals(String.valueOf(s.get("value")))) continue; + String was; + if (s == null) { + s = new LinkedHashMap(); + s.put("stock", settingGet(k)); + st.put(k, s); + was = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + } else { + was = String.valueOf(s.get("value")); + } + boolean live = !v.equals(was); // mirror/restart only when the value really changes + // already the wanted value: only take it over. Setting it again isn't harmless: + // init re-runs its triggers (persist.sys.usb.config re-enumerated USB and dropped adb) + if (live) { + settingsUndo.add(new String[] { k, settingGet(k) }); + settingPut(k, v); + } + s.put("value", v); + s.put("mod", e.getValue()[1]); + Map c = (Map) e.getValue()[2]; + if (c != null && c.get("mirror") != null) s.put("mirror", c.get("mirror")); + else s.remove("mirror"); + if (c != null && c.get("restart") != null) s.put("restart", c.get("restart")); + else s.remove("restart"); + if (live) after(s, v); + out.add("set " + k + " = " + (v.isEmpty() ? "(unset)" : v)); + } + for (String k : p.settingsRestore) { + Map s = (Map) st.remove(k); + settingsUndo.add(new String[] { k, settingGet(k) }); + settingPut(k, s.get("stock") == null ? null : String.valueOf(s.get("stock"))); + String back = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); + if (!back.equals(String.valueOf(s.get("value")))) after(s, back); + out.add("set " + k + " back to " + s.get("stock")); + } + + // binds: hmgapid does them after the output is printed (restarting a service like adbd + // may cut the link that asked); a new list clears earlier failures + String bt = bindsText(p.binds); + if (!bt.equals(bindsBefore)) { + write(new File(stateDir, "binds.txt"), bt); + new File(stateDir, "binds.failed").delete(); + bindsChanged = true; + } + + // state + for (Target t : changed) { + if (t.restore) { + files.remove(t.path); + continue; + } + Map f = new LinkedHashMap(); + f.put("stock", t.stock); + f.put("result", t.result); + f.put("mods", new ArrayList(t.mods)); + if (t.app) f.put("app", true); + if (t.stockMeta != null) f.put("stockMeta", t.stockMeta); + files.put(t.path, f); + } + write(stateFile, Json.write(p.state)); + if (trial) { + j.put("committed", true); + write(journalFile, Json.write(j)); + out.add("trial: undone at the next start unless you run `engine keep`"); } else { - was = String.valueOf(s.get("value")); - } - boolean live = !v.equals(was); // mirror/restart only when the value really changes - // already the wanted value: only take it over. Setting it again isn't harmless: - // init re-runs its triggers (persist.sys.usb.config re-enumerated USB and dropped adb) - if (live) settingPut(k, v); - s.put("value", v); - s.put("mod", e.getValue()[1]); - Map c = (Map) e.getValue()[2]; - if (c != null && c.get("mirror") != null) s.put("mirror", c.get("mirror")); - else s.remove("mirror"); - if (c != null && c.get("restart") != null) s.put("restart", c.get("restart")); - else s.remove("restart"); - if (live) after(s, v); - out.add("set " + k + " = " + (v.isEmpty() ? "(unset)" : v)); - } - for (String k : p.settingsRestore) { - Map s = (Map) st.remove(k); - settingPut(k, s.get("stock") == null ? null : String.valueOf(s.get("stock"))); - String back = s.get("stock") == null ? "" : String.valueOf(s.get("stock")); - if (!back.equals(String.valueOf(s.get("value")))) after(s, back); - out.add("set " + k + " back to " + s.get("stock")); - } - - // binds: hmgapid does them after the output is printed (restarting a service like adbd - // may cut the link that asked); a new list clears earlier failures - String bt = bindsText(p.binds); - if (!bt.equals(currentBinds())) { - write(new File(stateDir, "binds.txt"), bt); - new File(stateDir, "binds.failed").delete(); - bindsChanged = true; - } - - // state - for (Target t : changed) { - if (t.restore) { - files.remove(t.path); - continue; + journalFile.delete(); + rm(prevDir); + } + } catch (Throwable failure) { + out.add("apply failed: " + failure); + // settings and binds as they were, nothing left to run after the output + for (int i = settingsUndo.size() - 1; i >= 0; i--) { + try { + settingPut(settingsUndo.get(i)[0], settingsUndo.get(i)[1]); + } catch (Exception x) { + out.add("WARNING: couldn't put " + settingsUndo.get(i)[0] + " back to " + settingsUndo.get(i)[1] + ": " + x); + } + } + mirrors.clear(); + restarts.clear(); + if (bindsChanged) { + write(new File(stateDir, "binds.txt"), bindsBefore); + bindsChanged = false; + } + if (rw) { + rw = false; + try { + remount("ro"); + } catch (Exception ignored) { + // the rollback remounts for itself + } + } + List left = rollback(j); + if (left.isEmpty()) { + journalFile.delete(); + rm(prevDir); + out.add("rolled back: every file is as it was before this apply"); + } else { + keepHeld = true; + out.add("NOT rolled back: " + left); + out.add("the next start tries again (`engine recover`); " + (held.isEmpty() ? "" : held + " stay off until then; ") + + "other engine commands wait for it"); + } + rm(stageDir); + throw failure; + } finally { + if (rw) remount("ro"); + if (!keepHeld && !held.isEmpty()) { + List still = new ArrayList(release(held)); + if (journalFile.exists()) { // a trial waiting: what recover would still turn on + j.put("held", still); + write(journalFile, Json.write(j)); + } } - Map f = new LinkedHashMap(); - f.put("stock", t.stock); - f.put("result", t.result); - f.put("mods", new ArrayList(t.mods)); - if (t.app) f.put("app", true); - files.put(t.path, f); - } - write(stateFile, Json.write(p.state)); - if (trial) { - j.put("committed", true); - write(journalFile, Json.write(j)); - out.add("trial: undone at the next start unless you run `engine keep`"); - } else { - journalFile.delete(); - rm(prevDir); } rm(stageDir); Set needs = new LinkedHashSet(); @@ -1961,6 +2048,92 @@ void apply(Plan p, boolean trial) throws Exception { out.add("done: " + changed.size() + " file(s); " + needs); } + /** + * Puts the journaled files back as they were, last changed first, with their modes, owners + * and labels, and the state with them. A file already as it was is left alone, so a run + * cut off before the swap writes nothing. Returns what couldn't be put back (then the + * journal must stay). + */ + @SuppressWarnings("unchecked") + List rollback(Map j) throws Exception { + List entries = new ArrayList((List) j.get("entries")); + Collections.reverse(entries); + List> todo = new ArrayList>(); + Set apks = new LinkedHashSet(); + for (Object o : entries) { + Map e = (Map) o; + String path = (String) e.get("path"); + File dst = sys(path), prev = e.get("prev") == null ? null : new File((String) e.get("prev")); + boolean same = prev == null ? !dst.exists() + : dst.isFile() && md5(dst).equals(md5(prev)) && FileMeta.read(this, dst).same(journalMeta(e, path)); + if (!same) { + todo.add(e); + if (path.endsWith(".apk")) apks.add(path); + } + } + // an app's odex as it was, but its apk not: its dalvik-cache copy needs filling again + for (Object o : entries) { + Map e = (Map) o; + String path = (String) e.get("path"); + if (path.endsWith(".odex") && apks.contains(path.replaceAll("\\.odex$", ".apk")) && !todo.contains(e)) todo.add(e); + } + List left = new ArrayList(); + if (!todo.isEmpty()) { + try { + remount("rw"); + } catch (Exception x) { + for (Map e : todo) left.add(e.get("path") + " (" + x.getMessage() + ")"); + return left; + } + try { + for (Map e : todo) { + String path = (String) e.get("path"); + File dst = sys(path); + try { + testFail("rollback", path); + if (e.get("prev") == null) { + if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); + } else { + put(new File((String) e.get("prev")), dst, journalMeta(e, path)); + } + if (path.endsWith(".odex")) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); + out.add("rolled back " + path); + } catch (Exception x) { + left.add(path + " (" + x.getMessage() + ")"); + } + } + } finally { + remount("ro"); + } + } + if (left.isEmpty()) write(stateFile, Json.write(j.get("state"))); + return left; + } + + /** a journal entry's mode, owner and label (a journal from before they were read: the /system defaults) */ + static FileMeta journalMeta(Map e, String path) { + FileMeta m = FileMeta.from(e); + return m != null ? m : FileMeta.defaults(path); + } + + /** the stock mode, owner and label of path (an app's apk or odex), as recorded before HMG-API's first write */ + static FileMeta stockMeta(Target t, String path) { + FileMeta m = t.stockMeta == null ? null : FileMeta.from(t.stockMeta.get(path)); + return m != null ? m : FileMeta.defaults(path); // recorded by an HMG-API before this: the /system defaults + } + + /** what a built file is written with: its stock owner and label (else the live file's, else the defaults), the mod's mode if it gives one */ + FileMeta targetMeta(Target t) throws IOException { + FileMeta m = t.stockMeta == null ? null : FileMeta.from(t.stockMeta.get(t.path)); + File live = sys(t.path); + if (m == null) m = live.isFile() ? FileMeta.read(this, live) : FileMeta.defaults(t.path); + m = m.copy(); + String mode = modeOf(t); + if (mode != null) m.mode = Integer.parseInt(mode, 8); + return m; + } + List withOdex(Target t) { List l = new ArrayList(); l.add(t.path); @@ -1969,16 +2142,18 @@ List withOdex(Target t) { } void swap(Target t) throws Exception { + testFail("swap", t.path); File dst = sys(t.path); if (t.restore) { if ("absent".equals(t.stock)) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); } else { - put(backup(t.path), dst, "644"); + put(backup(t.path), dst, stockMeta(t, t.path)); } if (t.app) { String odex = t.path.replaceAll("\\.apk$", ".odex"); - if (backup(odex).isFile()) put(backup(odex), sys(odex), "644"); + if (backup(odex).isFile()) put(backup(odex), sys(odex), stockMeta(t, odex)); dalvik(t.path, sys(odex), false); } out.add("restored " + t.path); @@ -1986,13 +2161,13 @@ void swap(Target t) throws Exception { } if (!t.exists) { if (dst.exists() && !dst.delete()) throw new IOException("delete " + dst); + FileMeta.gone(this, dst); return; } - put(t.stage, dst, t.changes.isEmpty() || t.changes.get(0).c.get("mode") == null ? "644" - : String.valueOf(t.changes.get(0).c.get("mode"))); + put(t.stage, dst, targetMeta(t)); if (t.app) { File odex = sys(t.path.replaceAll("\\.apk$", ".odex")); - odex.delete(); + odex.delete(); // dexopt --preopt opens its output O_EXCL; the journal has the old one dalvik(t.path, odex, true); } out.add("wrote " + t.path); @@ -2000,6 +2175,7 @@ void swap(Target t) throws Exception { /** dexopt a rebuilt app and fill its Dalvik cache entry, as the 1.x package did. */ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { + if (dexopt) testFail("dexopt", apkPath); if (host) return; String apk = new File(apkPath).getName(); exec("/system/bin/sh", "-c", "rm -f /data/dalvik-cache/*" + apk + "* /cache/dalvik-cache/*" + apk + "*"); @@ -2019,48 +2195,178 @@ void dalvik(String apkPath, File odex, boolean dexopt) throws Exception { } } - /** Write next to the target and rename, so a reader never sees half a file. */ - void put(File src, File dst, String mode) throws Exception { + /** + * Write next to the target with its mode, owner and label, then rename, so a reader never + * sees half a file or one that can't run. Nothing is left behind when it fails. + */ + void put(File src, File dst, FileMeta meta) throws Exception { File tmp = new File(dst.getPath() + ".hmgapi-new"); dst.getParentFile().mkdirs(); - copy(src, tmp); - if (!host) { - exec("/system/bin/chmod", mode, tmp.getPath()); - exec("/system/bin/chown", "0:0", tmp.getPath()); - } - if (!md5(tmp).equals(md5(src))) { + try { + testFail("put", devicePath(dst)); + copy(src, tmp); + FileMeta.set(this, tmp, meta); + if (!md5(tmp).equals(md5(src))) throw new IOException("copy to " + dst + " came out different"); + if (!tmp.renameTo(dst)) throw new IOException("rename onto " + dst); + FileMeta.moved(this, tmp, dst); + } catch (Exception e) { tmp.delete(); - throw new IOException("copy to " + dst + " came out different"); + FileMeta.gone(this, tmp); + throw e; } - if (!tmp.renameTo(dst)) { - tmp.delete(); - throw new IOException("rename onto " + dst); + } + + /** + * Off the unit only, for the tests: HMGAPI_TEST_FAIL=": ..." makes that step fail + * there (swap, put, dexopt, rollback); "halt:" ends the engine at once in swap, + * as a power cut would (no rollback, no finally). + */ + void testFail(String step, String path) throws IOException { + if (!host) return; + for (String s : env("HMGAPI_TEST_FAIL", "").split(" ")) { + if ("swap".equals(step) && s.equals("halt:" + path)) { + System.out.flush(); + Runtime.getRuntime().halt(9); + } + if (s.equals(step + ":" + path)) throw new IOException("test: " + step + " fails at " + path); } } - Set hold(List changed) throws Exception { + /** f's path on the unit (without HMGAPI_ROOT) */ + String devicePath(File f) { + String p = f.getPath(); + return !root.isEmpty() && p.startsWith(root) ? p.substring(root.length()) : p; + } + + // ------------------------------------------------------------------ apps held while their files change + + /** The package manager, or null where there's none (off the unit, unless a test gives one). */ + String pm() { return env("HMGAPI_PM", host ? null : "/system/bin/pm"); } + + /** never stopped: Android itself, and what HMG-API's USB install path needs */ + static final String[] NEVER_HOLD = { "android", "com.hkmc.system.app.OTAClient" }; + static final int FLAG_PERSISTENT = 1 << 3; // ApplicationInfo.FLAG_PERSISTENT + + /** + * Stops (pm disable) the apps whose apk changes, so none runs on a half-changed file (DiPO + * and iAP2 crash-looped, SIGBUS). Android keeps an app disabled across restarts, so the + * list goes into the journal and state/held.txt first: a power cut or a killed engine + * before release leaves it for recover and boot.sh. Never Android itself, a persistent + * app (Android starts those on its own; off, it may not come up at all), OTAClient, or an + * app that was off already (it stays off). + */ + Set hold(List changed, Map j) throws Exception { Set held = new LinkedHashSet(); - if (host || !"1".equals(getprop("sys.boot_completed"))) return held; + String pm = pm(); + if (pm == null || !"1".equals(getprop("sys.boot_completed"))) return held; Map pkgs = new LinkedHashMap(); - for (String l : exec("/system/bin/pm", "list", "packages", "-f").text.split("\n")) { + for (String l : exec(pm, "list", "packages", "-f").text.split("\n")) { l = l.trim(); int eq = l.lastIndexOf('='); if (l.startsWith("package:") && eq > 0) pkgs.put(l.substring(8, eq), l.substring(eq + 1)); } + Set off = new LinkedHashSet(); + for (String l : exec(pm, "list", "packages", "-d").text.split("\n")) if (l.trim().startsWith("package:")) off.add(l.trim().substring(8)); + Map flags = packageFlags(); for (Target t : changed) { String pkg = pkgs.get(t.path); - if (pkg != null && exec("/system/bin/pm", "disable", pkg).code == 0) held.add(pkg); - } - if (!held.isEmpty()) out.add("stopped " + held + " while their files change"); + if (pkg == null || off.contains(pkg)) continue; + String why = null; + for (String n : NEVER_HOLD) if (n.equals(pkg)) why = "never stopped"; + if (why == null && t.path.startsWith("/system/framework/")) why = "part of Android itself"; + if (why == null && flags.get(pkg) == null) why = "not in packages.xml, so it can't be told whether it's persistent"; + if (why == null && (flags.get(pkg) & FLAG_PERSISTENT) != 0) why = "persistent"; + if (why != null) out.add("note " + pkg + " keeps running while " + t.path + " changes (" + why + ")"); + else held.add(pkg); + } + if (held.isEmpty()) return held; + j.put("held", new ArrayList(held)); + write(journalFile, Json.write(j)); + Set all = readHeld(); + all.addAll(held); + writeHeld(all); + for (String pkg : held) exec(pm, "disable", pkg); + out.add("stopped " + held + " while their files change"); return held; } - void release(Set held) throws Exception { - for (String pkg : held) exec("/system/bin/pm", "enable", pkg); + /** Starts held apps again (pm enable). Returns those it couldn't; they stay in held.txt for the next try. */ + List release(Set held) throws Exception { + List left = new ArrayList(); + String pm = pm(); + Set done = new LinkedHashSet(); + for (String pkg : held) { + Run r = pm == null ? null : exec(pm, "enable", pkg); + if (r != null && r.code == 0 && r.text.contains("new state")) done.add(pkg); + else left.add(pkg); + } + Set all = readHeld(); + all.removeAll(done); + writeHeld(all); + if (!done.isEmpty()) out.add("started " + done + " again"); + if (!left.isEmpty()) out.add("WARNING: couldn't start " + left + " again; the next start tries again (state/held.txt)"); + return left; + } + + /** Held apps left over (a cut-off apply, or a release that failed): started again once Android is up and no apply is waiting. */ + @SuppressWarnings("unchecked") + int releaseHeld() throws Exception { + Set held = readHeld(); + if (held.isEmpty()) { + out.add("no apps held"); + return 0; + } + if (journalFile.exists() && !Boolean.TRUE.equals(Json.object(read(journalFile)).get("committed"))) { + out.add("held " + held + " stay off: an apply didn't finish, and their files are as it left them; `engine recover` puts them back and starts them"); + return 1; + } + if (!"1".equals(getprop("sys.boot_completed"))) { + out.add("held " + held + ": Android isn't up yet"); + return 1; + } + return release(held).isEmpty() ? 0 : 1; + } + + File heldFile() { return new File(stateDir, "held.txt"); } + + Set readHeld() throws IOException { + Set s = new LinkedHashSet(); + if (!heldFile().isFile()) return s; + for (String l : read(heldFile()).split("\n")) if (l.trim().matches("[A-Za-z0-9_.]+")) s.add(l.trim()); + return s; + } + + void writeHeld(Set s) throws IOException { + if (s.isEmpty()) { + heldFile().delete(); + return; + } + StringBuilder b = new StringBuilder(); + for (String p : s) b.append(p).append('\n'); + write(heldFile(), b.toString()); + } + + /** Each package's ApplicationInfo flags, from /data/system/packages.xml (what PackageManager wrote at its last scan). */ + Map packageFlags() { + Map m = new LinkedHashMap(); + try { + java.util.regex.Matcher pk = java.util.regex.Pattern.compile("]*>").matcher(read(new File(root + "/data/system/packages.xml"))); + while (pk.find()) { + java.util.regex.Matcher n = java.util.regex.Pattern.compile("\\sname=\"([^\"]+)\"").matcher(pk.group()); + java.util.regex.Matcher f = java.util.regex.Pattern.compile("\\sflags=\"(-?[0-9]+)\"").matcher(pk.group()); + if (n.find() && f.find()) m.put(n.group(1), Long.parseLong(f.group(1))); + } + } catch (Exception e) { + // unreadable: no app counts as known, so none is held + } + return m; } void remount(String mode) throws Exception { - if (host) return; + if (host) { + if ("rw".equals(mode)) testFail("remount", "rw"); + return; + } Run r = exec(env("HMGAPI_HMGAPID", "/system/bin/hmgapid"), "remount", mode); if (r.code != 0 && "rw".equals(mode)) throw new IOException("remount rw: " + r.text); } @@ -2092,6 +2398,8 @@ int status() throws Exception { out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial apply in place: `engine keep` keeps it, the next start undoes it" : "an apply didn't finish: the next start rolls it back (`engine recover`)"); } + Set held = readHeld(); + if (!held.isEmpty()) out.add("held " + held + " stopped (pm disable) by an apply that didn't start them again; `engine recover` starts them"); return bad == 0 ? 0 : 4; } @@ -2134,35 +2442,48 @@ int keep() throws Exception { return 0; } + /** + * An apply cut off (a power cut, a killed engine) or a waiting trial: every journaled file + * back as it was (bytes, mode, owner, label), then the apps it held started again. The + * output says "rolled back" or "trial undone" only when files changed (boot.sh restarts + * the unit on those words). Left over held apps alone: started again too. + */ @SuppressWarnings("unchecked") int recover() throws Exception { if (!journalFile.exists()) { out.add("nothing to recover"); - return 0; + return startHeld(readHeld()); } Map j = Json.object(read(journalFile)); - remount("rw"); - try { - for (Object o : (List) j.get("entries")) { - Map e = (Map) o; - String path = (String) e.get("path"); - File dst = sys(path); - Object prev = e.get("prev"); - if (prev == null) { - if (dst.exists()) dst.delete(); - } else { - put(new File((String) prev), dst, e.get("mode") == null ? "644" : String.valueOf(e.get("mode"))); - } - if (path.endsWith(".odex") && !host) dalvik(path.replaceAll("\\.odex$", ".apk"), dst, false); - out.add("rolled back " + path); - } - } finally { - remount("ro"); + int before = out.size(); + List left = rollback(j); + if (!left.isEmpty()) { + out.add("recover didn't finish, the journal stays: couldn't put back " + left); + Set held = readHeld(); + if (j.get("held") instanceof List) for (Object o : (List) j.get("held")) held.add(String.valueOf(o)); + writeHeld(held); + if (!held.isEmpty()) out.add("held " + held + " stay off until it does"); + return 1; } - write(stateFile, Json.write(j.get("state"))); + boolean any = out.size() > before; journalFile.delete(); rm(prevDir); - out.add(Boolean.TRUE.equals(j.get("trial")) ? "trial undone" : "unfinished apply rolled back"); + if (Boolean.TRUE.equals(j.get("trial"))) out.add(any ? "trial undone" : "trial dropped: its files were as before it already"); + else out.add(any ? "unfinished apply rolled back" : "unfinished apply dropped: no file had changed yet"); + Set held = readHeld(); + if (j.get("held") instanceof List) for (Object o : (List) j.get("held")) held.add(String.valueOf(o)); + return startHeld(held); + } + + /** held apps started again now if Android is up, else left in held.txt for boot.sh (engine release-held) */ + int startHeld(Set held) throws Exception { + if (held.isEmpty()) return 0; + writeHeld(held); + if (!"1".equals(getprop("sys.boot_completed"))) { + out.add("held " + held + " start again once Android is up (boot.sh: engine release-held)"); + return 0; + } + release(held); return 0; } @@ -2220,7 +2541,6 @@ Map loadState() throws IOException { File backup(String path) { return new File(stockDir, path); } - String mode(File f) { return "644"; } String settingGet(String k) throws Exception { if (host) return hostSettings().get(k); diff --git a/core/runtime/java/hmgapi/engine/FileMeta.java b/core/runtime/java/hmgapi/engine/FileMeta.java new file mode 100644 index 00000000..ea69cfb3 --- /dev/null +++ b/core/runtime/java/hmgapi/engine/FileMeta.java @@ -0,0 +1,191 @@ +package hmgapi.engine; + +import java.io.File; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TreeMap; + +/** + * A /system file's mode, owner, group and SELinux label. Read before HMG-API first writes a + * file (files.json "stockMeta" per path, and each journal entry) and put back with its bytes + * on apply, rollback and restore: a stock /system/bin binary put back as 644 doesn't run, and + * one put back as 0:0 instead of 0:2000, or with another label, may not either. + * + * On the unit: libcore's stat and android.os.SELinux (both in every 4.4 app_process), toolbox + * as the fallback. Off the unit (HMGAPI_HOST=1) the mode is the desktop file's own (chmod), + * and owners and labels, which a desktop user can't set, live in {@code /meta.txt}, one + * "