diff --git a/.github/workflows/catalog-update.yml b/.github/workflows/catalog-update.yml new file mode 100644 index 00000000..ce559d78 --- /dev/null +++ b/.github/workflows/catalog-update.yml @@ -0,0 +1,95 @@ +# Opens a catalogue pull request for each entry whose repo has a newer final release +# (tools/catalog.py updates): the entry written again from that release's zip, as add +# does. A bump of one entry is merged by the Catalogue auto-merge once the Catalogue +# check passes; anything else (a changed name, a new repo for the key) waits for a +# maintainer. Head units read the catalogue from main, so a merged bump reaches owners +# on their next catalogue check: no HMG-API release is needed. +# +# Hourly, from main. One branch per version (catalog-update/-): a version +# whose branch exists, open or closed by a maintainer, isn't opened again; a newer +# version closes the older one's pull request. The pull request is the Open-HMG +# catalogue app's (vars.CATALOG_APP_CLIENT_ID, secrets.CATALOG_APP_PRIVATE_KEY), so the +# Catalogue check runs on it: one opened with GITHUB_TOKEN starts no workflows. +name: Catalogue updates + +on: + schedule: + - cron: "17 * * * *" + workflow_dispatch: + +permissions: {} + +concurrency: + group: catalog-update + cancel-in-progress: false + +jobs: + update: + if: github.repository == 'Open-HMG/HMG-API' + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: "17" + + - name: Newer releases + id: updates + env: + GH_TOKEN: ${{ github.token }} + run: | + python3 tools/catalog.py updates > "$RUNNER_TEMP/updates.txt" + cat "$RUNNER_TEMP/updates.txt" + { echo '```'; cat "$RUNNER_TEMP/updates.txt"; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + if [ -s "$RUNNER_TEMP/updates.txt" ]; then echo "any=1" >> "$GITHUB_OUTPUT"; fi + + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: app + if: steps.updates.outputs.any + with: + client-id: ${{ vars.CATALOG_APP_CLIENT_ID }} + private-key: ${{ secrets.CATALOG_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: A pull request for each + if: steps.app.outputs.token + env: + GH_TOKEN: ${{ github.token }} + APP_TOKEN: ${{ steps.app.outputs.token }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + while read -r id old new url <&3; do # fd 3: nothing in the loop can eat the list + case "$id $old $new" in *[!a-z0-9.\ -]*) echo "odd line: $id $old $new"; continue ;; esac + git checkout -q -f origin/main && git clean -fdq catalog maps # nothing left over from the mod before + branch="catalog-update/$id-$new" + if git ls-remote --exit-code --heads origin "$branch" > /dev/null; then echo "$id $new: $branch is there already"; continue; fi + git checkout -q -B "$branch" origin/main + if ! python3 tools/catalog.py updates --apply "$id"; then echo "$id $new: not written"; continue; fi + git add -A catalog maps + git commit -qm "Catalogue: $id $new" -m "From $url (tools/catalog.py updates)." + git push -q "https://x-access-token:${APP_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "HEAD:refs/heads/$branch" + # this mod's older version PRs: catalog-update/- exactly (not -2's) + GH_TOKEN=$APP_TOKEN gh pr list --repo "$GITHUB_REPOSITORY" --state open --base main --json number,headRefName \ + --jq '.[] | "\(.number) \(.headRefName)"' | while read -r n ref; do + [ "$ref" != "$branch" ] || continue + v=${ref#catalog-update/$id-} + [ "$v" != "$ref" ] || continue + case "$v" in *[!0-9.]*|.*|*.|*..*) continue ;; *.*.*) ;; *) continue ;; esac + GH_TOKEN=$APP_TOKEN gh pr close "$n" --repo "$GITHUB_REPOSITORY" --delete-branch --comment "Replaced by $id $new." + done + printf '%s\n' "$id $old to $new, from its own repo's release: $url" "" \ + "Opened by the Catalogue updates workflow (\`tools/catalog.py updates\`). If it only bumps the version, the Catalogue auto-merge merges it once the Catalogue check passes; otherwise it waits for a maintainer." \ + > "$RUNNER_TEMP/body.md" + GH_TOKEN=$APP_TOKEN gh pr create --repo "$GITHUB_REPOSITORY" --base main --head "$branch" \ + --title "Catalogue: $id $new" --body-file "$RUNNER_TEMP/body.md" + done 3< "$RUNNER_TEMP/updates.txt" 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 fdf81877..30702160 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,289 @@ ## 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. +- **The boot hook keeps the boot scripts' other lines as they are.** Putting HMG-API's block + into NEMESIS's `install-recovery.sh` and the stock `qb_runtime.sh` (every install, and + `hook-check.sh` at boot) wrote each line again with `echo`, which expands backslashes in the + unit's mksh as in dash: `\\` became `\`, and a `\c` ended the output there, so a line like + `V="x\cY"; echo ok` lost its closing quote and joined the next one, and the script stopped + running. Lines are now written with mksh's `print -r` (in a shell without it, as the + off-car tests' dash, with `echo` and every backslash doubled), checked on a test line when + the script starts, and the new file is checked before it goes in: without the block it must + be the file as it was, or the file is left alone. Tested off-car only (dash and macOS `sh`; + CI also runs the checks in mksh), not yet on a car. +- **An update checks the stock copy by md5.** A new install checks `app_process` against + `stock.txt`, but an update only checked that `app_process.hmgapi-stock` started like a + binary, so a copy cut short, zero-filled or otherwise damaged passed, and the next start had + no zygote. The catalogue's `engine update hmgapi` runs the same installer. Now a stock copy + that isn't a known build comes back from the stock backup when that is one, and with no + stock backup the update is refused with nothing changed, as a new install is + (`HMGAPI_FORCE=1` stays for maintainers). Tested off-car only. +- **The zygote wrapper falls back to the stock backup.** When the stock copy won't run (lost + or damaged on `/system`), the wrapper runs the install's backup of the stock binary, + `/data/hmgapi/stock/system/bin/app_process` (made executable first, and only if it starts + like an ELF binary), so Android still starts and an install or uninstall can put `/system` + right. Where SELinux refuses an exec from `/data` (an Enforcing unit) it exits as before. + Not yet tested on a car. +- **Hooks stay off on a Dalvik other than the EV6's.** The hook runtime's struct offsets come + from the EV6's libdvm. Before the first hook it now reads them back from Bridge's own + methods (class, name, shorty, flags, argument count, native function), the primitive types + and an array's length; on a mismatch it logs which one and leaves hooks off, so the unit runs + stock instead of crashing each app as it starts. Not yet tested on a car. +- **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) goes back to 0 only once that start has stayed up an hour after booting + (QuickBoot keeps one kernel boot for weeks, and crashes days apart mustn't add up; a crash + loop never stays up that long). 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. +- **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. +- **Restarts, applies and installs only start with the car in P.** A restart takes the reverse + camera's picture away for about a minute (Android shows it on these units), and on 2026-11-27 a + NEMESIS install (no HMG-API) cut off by a shift into reverse left a unit that didn't start. + `hmgapid reboot` (every restart: the app's buttons, the boot steps), `engine apply` and + `engine restore` when they change files on `/system` (and so may stop system apps for the + swap), `engine update-hmgapi`, and `install.sh`/`uninstall.sh` (every install route) read + `gear.park` first. Not in P: refused (exit 75), nothing changed, no override. No reading (the + car's map has no gear point, or the vehicle service isn't up yet): `hmgapid reboot` and the + engine refuse (exit 76) unless told `--gear-unknown-ok`, which the app passes once the owner + says the car is in P; the USB, NEMESIS and adb routes, with no one to ask, warn and go on. The + app tells the owner to stay in P until it's done, as does the USB installer's toast. +- **HMG-API's vehicle service always runs**, not only while a mod reads the car, so every car + with a gear point in its map gives the reading the checks above need. +- **The restart after a boot-time rollback waits for the car to be parked**, in the background + (the boot never waits): HMG-API's parked state, or in P with the car off (in P for two minutes + when the power status can't be read). Until then the app shows Restart needed; with no gear + reading for 10 minutes there's no restart, and the app's Restart asks the owner. +- **A cut-off install or apply leaves less behind.** `install.sh`, `uninstall.sh` and the USB + installer ignore a closed output pipe and hang-ups (a screen that closed under them, an adb + that dropped), and sync each file before renaming it into place, so a reset right after never + leaves an empty `app_process`. The engine writes down the apps it stops (`state/held.txt`) + before `pm disable`, which lasts across restarts; an apply cut off before it turned them on + again has them turned on by the next start's `engine recover`. The USB installer's restart + waits while the car isn't in P. Tested off-car only: what shifting into reverse does to a + running install on a car is still to be checked (`docs/car-test.md`). +- **No mod reaches the car's safety functions** (the review of 2026-11-26). The rear + camera, the 360 view (AVM/SVM), the parking guide lines (PGS) and the emergency calls + (SOS, eCall) are built in as off limits (`hmgapi.engine.Protected`), with no owner + override. No mod loads in their app processes (`com.hkmc.system.app.rearcamera`, + `com.hkmc.telematics.ECall`, `com.hkmc.telematics.service`, and names that look like + a camera or eCall app), at boot or live. The hooks mods put on in the zygote pass + through there, and HMG-API adds nothing of its own. No mod may hook the camera and + telematics classes that run in `system_server` (`com.hkmc.pgs.*`, `PgsService`, + `TMUService`, `com.hkmc.tmu.*`, their MICOM protocols), declared or not. A mod that + declares `framework.pgs_service*`, `framework.car_services.pgs` or `framework.tmu*` isn't + loaded. Names are from the US Ioniq 5 260507's stock files and logs. +- **Direct hooks are reported.** A mod's `Bridge.hookMethod`/`Hooks.findAndHookMethod` + call outside its declared points still works outside the protected processes and + classes (egmp-aa-ev 0.8.4 uses one as a fallback). It's logged once per process + (`undeclared hook:`), and the Car Report has a `protection` section listing these, the + refused hooks and the protected processes it saw start. +- **Guide lines a mod changed go back after a restart or the mod's removal.** The + `guide_lines` command keeps their stock state in `state/guide-lines.stock` before the + first change. The vehicle service puts it back at its start (retrying until the + camera service answers) and keeps running while the file is there, and the uninstall + puts it back too. Before, the state lived only in memory, so a restart while a mod + held the lines off left them off. +- **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. +- **A cut-off install leaves less behind.** `install.sh`, `uninstall.sh` and the USB installer + ignore a closed output pipe and hang-ups (a screen that closed under them, an adb that + dropped), and sync each file before renaming it into place, so a reset right after never + leaves an empty `app_process`. The USB installer's restart waits while the car isn't in P. + Tested off-car only: what shifting into reverse does to a running install on a car is still + to be checked (`docs/car-test.md`). - **A root service can read its own settings** (`HmgApi.settings()`, `saveSettings()`): the daemon sees such a service as root, so the client names its mod (`HMGAPI_MOD`). +- **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`. +- **A mod can move to a new author key** without owners removing it: the old key signs + `key-handover.json` (`Signing handover`), and an update by the new key goes in only when + those steps lead from the installed key to it. The catalogue takes the new key the same way + (`"key_from"`), always through a maintainer. So each mod can have its own key. +- **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 zip's `mod.json`) are met + by what's installed, or by the catalogue's version, installed first; a required mod that's + turned off is turned on. Loops, conflicts, a requirement newer than the catalogue's or not + in it, an unreadable range, and a mod for a newer HMG-API are refused before anything is + downloaded or installed. The result is checked as a whole: every mod that will be on keeps + what it requires (an update that breaks another mod's range is refused), and conflicts count + whichever side lists them. Every mod zip is downloaded and checked (SHA-256, signature, + author key, HMG-API, car) before the first install. When a mod zip requires more than the + plan said, nothing is installed and the new plan is shown for a second OK. Removing a mod + others require says which won't load. +- **A first install from the catalogue needs a known author.** The catalogue isn't signed, so + 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/`. +- **Updates.** Mods tab → Updates (with how many) lists installed mods with a newer catalogue + version, and a newer HMG-API release (on a pre-release, only that version's next ones), with + its release notes, Update and Update all (each mod that can go; the ones that can't are listed + with why). "Install anyway" is per mod and says for what: not listed for this head unit, or an + author who isn't on the trusted list. A mod's row in the list says "update x.y.z". HMG-API checks by itself each time + home Wi-Fi comes up, at most every 6 hours (owner switch `no_update_check` turns that off), and + can also download and stage the mods' plain updates then (`auto_stage_updates`, off by + default): they wait aside until the owner 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 + 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, 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". +- **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`, nor + the home group's or the home apps' traffic by owner, so the block holds if the mark rule is lost), + 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 DROPs inside `HMGAPI_HOMECELL`. (Repairing + the rules still takes them out for a moment, as before.) 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, 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. +- **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 mods + over home Wi-Fi, each with its SHA-256. Each socket has home Wi-Fi's mark and is bound to + `wlan0`, or the call fails (never an unmarked socket on the main table's mobile data, even + before the fwmark rule is in), with 20 s send and receive timeouts (connect, the handshake, + each read). The DNS server comes from home Wi-Fi's lease (there only while its route is up, + not a leftover `dhcp.wlan0.dns1`), asked on the same kind of socket. An answer the server + didn't end with a TLS close counts only when its Content-Length or last chunk says it is + whole; chunk sizes are hex digits only (a negative one passed the cap), and a broken body + leaves no `.part`. Each call has its own answer file, opened `O_EXCL` and `O_NOFOLLOW`. ## 1.1.0-rc.10 (2026-11-25) +- **Safe mode: every mod off at once, nothing removed** (review of 2026-11-26). While + `/data/hmgapi/SAFE` is there, the runtime loads no mod's hooks, hmgapid runs no mod's + service (boot-start ones included, even before the engine has run), the mods' apps are + turned off and their network rules come out, except a rule to adbd's port, so adb over the + hotspot stays reachable. HMG-API, its own hooks and its app stay on. The mods' file changes + stay. On and off: `hmgapid engine safe on|off` (root, adb, the app), Settings → Safe mode, + or the file by hand; the top bar says "Safe mode: mods off". Before, the only switch was + `hook/disable`, which turns off hooks only (HMG-API's own too) and was documented only in + `core/README.md`; mods' services, apps and network rules kept running. +- **The boot guard turns safe mode on.** Its first trip (3 failed starts in one boot, or 6 + in a row) writes `SAFE` and starts the count again, so HMG-API's own hooks (its tile, its ★ + choice, the update block) get one more try without any mod; a trip in safe mode turns the + hooks off as before. `engine safe off` resets the counters. +- **Service logs stay capped while the service runs.** hmgapid read a service's log size only + when it started it, so a service that kept running wrote forever (a looping `echo` under the + real hmgapid: 885 MB in 8 s). Output now comes through a pipe hmgapid reads: 256 KB, then + `.1`, and at most 256 KB kept a minute (a line says how much was left out). HMG-API's own log + (LogKeeper) is capped the same way, and keeps each mod's lines to 300 a minute so a mod + logging on a hot path can't push HMG-API's own lines out. +- **Mods' services run at a lower priority**: nice 10 and the lowest best-effort I/O class, + unless the service asks for `"priority": "normal"` in `mod.json`. HMG-API's own services + are unchanged. A service gets only fds 0-2. +- **Recovery without the screen** in the wiki: Troubleshooting's "Stuck on the boot animation, + no home screen, or an app keeps crashing" (adb first, safe mode, `hook/disable`, `/data` + full, back to stock) and Uninstalling's no-screen route over adb. A USB stick can't trigger + any of it: Android mounts it, after the point where such a unit is stuck. + Tested off-car only, not on a car: the engine's safe mode, network and priority checks + (`core/runtime/safe-test.sh`) and `tools/test-all.sh --fast`; hmgapid's and the zygote + wrapper's new checks run under qemu-arm (`core/hmgapid/test.sh`, `core/zygote/test.sh`). + - **No owner-facing way to force an unknown `app_process`, for now.** An empty `HMGAPI/FORCE` file on the USB stick no longer forces the USB install or the NEMESIS package, and the refusals no longer say how to force: an `app_process` not in `stock.txt` is refused with @@ -622,6 +900,42 @@ NEMESIS in the app menu. isn't loaded, and the app shows why. This also keeps such a mod from winning a conflict it then can't use. +### 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. +- **`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`. +### For mod authors + +- **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). 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) The second release candidate: fixes from a review of rc.1, nothing new in HMG-API itself. diff --git a/CLAUDE.md b/CLAUDE.md index 9d4f13ff..58aab360 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ HMG-API (1.1.0-rc.10) is a mod manager for Hyundai/Kia/Genesis **Gen5W** head un ## Recommendations (warn, then follow the user) -Owners get to decide for their own units. Follow these by default. If the user asks to go against one, say the risk in a line or two, then do what they asked. HMG-API does the same for its users: a warning plus an override, never a silent block. For now one exception: an `app_process` not in `install/common/stock.txt` is refused with no owner-facing override (no stick file, no message names one); `HMGAPI_FORCE=1` over adb stays for maintainers. +Owners get to decide for their own units. Follow these by default. If the user asks to go against one, say the risk in a line or two, then do what they asked. HMG-API does the same for its users: a warning plus an override, never a silent block. Three exceptions. For now: an `app_process` not in `install/common/stock.txt` is refused with no owner-facing override (no stick file, no message names one); `HMGAPI_FORCE=1` over adb stays for maintainers. And a restart, an apply or restore that changes `/system`, or an install or update while `gear.park` says the car isn't in P is refused (exit 75), saying to shift to P; with no gear reading it's the usual warning plus override (`--gear-unknown-ok`; the installers, with no one to ask, warn and go on). A restart takes the reverse camera's picture away for about a minute, and a shift into reverse can cut an install off (`hmgapi.engine.Gear`, `hmgapid reboot`, `lib.sh` `gear_gate`). New steps of that kind go through the same check. Always: the car's safety functions (rear camera, 360 view, guide lines, SOS/eCall) are off limits to every mod with no override at all (`hmgapi.engine.Protected`: no mod in their processes, no mod hook on their classes or points). - Only firmware from 2026 onward (`26xxxx`) is supported for now; maps target each car's newest for its region: US 260507 (some models are on 260903: `maps/hyundai/neev23/usa/260903`), Canada 260206. Each region has its own builds, so maps (`maps////`, `car.json` `products`) and a mod's `"system"` match the full region, e.g. `CVEV.USA.`. Don't port pre-2026 firmware by default; ask the owner to update the head unit. With no map for the car, mods still install, points it can't find stay off, and a car missing from a mod's `"system"` is a warning with an override. - Don't flash MICOM, the bootloader or modem firmware, or firmware meant for another car: these can brick the unit or the car beyond what a USB stick can fix. @@ -32,9 +32,9 @@ 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/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/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`. Runs mods' services (logs capped through a pipe while they run, nice 10 unless `"priority": "normal"`). | +| `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. When the stock copy won't exec, it runs the install's backup, `/data/hmgapi/stock/system/bin/app_process` (made 700 first, ELF only). The first trip turns safe mode on instead (`/data/hmgapi/SAFE`: no mod loads and none of their services run; HMG-API's own hooks get one more try) and starts the counts again; a trip in safe mode, or with no way to write `SAFE`, is the trip above. | +| `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, and read back from Bridge's own methods before the first hook: a different layout logs why and leaves hooks off). | | `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). | | `core/client` | `hmgapi-client.jar`: for mods' own apps and services (bundled in their APKs). | @@ -44,6 +44,8 @@ Owners get to decide for their own units. Follow these by default. If the user a | `tools/sdk`, `./build.sh sdk` | the mod SDK (`hmgapi-mod-sdk-.zip`, a release asset from 1.1.0-beta.1): what a mod repo builds, tests and packages with; `.github/workflows/mod.yml` is their reusable CI. | | `tools/` | `lpatch`, `mkrecipe.py`, `mkdelta.py`, `mkicon.sh` (stock-style tile pictures; `mkicon-hmgapi.sh` makes HMG-API's own from the logo), `env.sh`, `test-all.sh`; `map-car.py` (partial maps), `maplib.py` (the repo keeps `maps/base/` + each build's differences in `car.json`; `build.sh` expands them into the per-app files the unit reads), `test-hooks.py` (points × cars, `maps/coverage.json`), `probe-test.py` (on-car mapper vs map-car.py); `cars.py` (stock trees in `$HMGAPI_CARS`, default `~/hmg-cars`: `list`, `test --report`; `docs/car-trees.md`). | +Safe mode: `/data/hmgapi/SAFE` (`hmgapid engine safe on|off`, Settings → Safe mode, the boot guard): no mod's hooks, services, apps or network rules (except a rule to adbd's port), nothing removed; `hmgapi.engine.Safe`. A USB stick can't help a unit stuck before Android: on 4.4, vold mounts a stick only when Android's MountService asks (AOSP behaviour, not timed on a car yet), so with no screen it's adb or the boot guard. + ## Gotchas learned the hard way - **Deodex with `baksmali x -a 18`**, against the car's own framework dir with the full BOOTCLASSPATH order (core, conscrypt, okhttp, core-junit, bouncycastle, ext, framework, framework2, telephony-common, voip-common, mms-common, android.policy, services, apache-xml, webviewchromium, automotive) plus every other framework odex. `-a 19` silently mis-maps instance fields (KitKat libcore Object fields) and skips classes. diff --git a/build.sh b/build.sh index 8736fa21..008aa4da 100755 --- a/build.sh +++ b/build.sh @@ -34,6 +34,17 @@ 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 + # 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 + 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 \ + -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 +106,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 +131,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" } @@ -140,9 +151,13 @@ 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); + # 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 + 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/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,7 +166,13 @@ 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: expanded, + # every build's full per-app files, as the unit reads them (tools/maplib.py) + python3 tools/maplib.py expand "$S/maps" || exit 1 + 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" @@ -166,11 +187,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/catalog/projection-tbt.json b/catalog/projection-tbt.json new file mode 100644 index 00000000..7dbb491f --- /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. 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", + "Open-HMG contributors" + ], + "license": "AGPL-3.0", + "uuid": "e5b72fe0-5b85-8d49-9a2f-cd175f08e9cb", + "version": "1.0.0", + "repo": "https://github.com/Open-HMG/projection-tbt", + "download": "https://github.com/Open-HMG/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/core/README.md b/core/README.md index ea9d8d64..15c882dd 100644 --- a/core/README.md +++ b/core/README.md @@ -3,7 +3,8 @@ 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; back to 0 once a start stays up an hour after booting), 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`. + - **Safe mode** (`/data/hmgapi/SAFE`; `hmgapid engine safe on|off`, the app's Settings → Safe mode, the file by hand): every mod off, nothing removed. The runtime loads no mod (`Mods`, state `safe`), hmgapid runs only HMG-API's own services (it reads the file itself, so boot-start ones stay off before the engine runs), and the engine publishes every mod as off: their apps turned off, their network rules out except one that lets TCP through to adbd's port (`persist.adb.tcp.port`), so adb stays reachable. The mods' file changes stay. `safe off` also resets the boot guard. `hmgapi.engine.Safe`. 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 +20,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, and the safe mode its first trip turns on), disable file, exec failure. ## Safety diff --git a/core/app/java/hmgapi/app/CatalogFlow.java b/core/app/java/hmgapi/app/CatalogFlow.java new file mode 100644 index 00000000..791e0678 --- /dev/null +++ b/core/app/java/hmgapi/app/CatalogFlow.java @@ -0,0 +1,339 @@ +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.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * 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). The owner's "Install anyway" is per mod and per + * reason (not listed for this head unit: --any-car=; an author key that isn't on the trusted + * list: --any-author=). Update all plans each mod on its own (update --all): the ones that can't + * go now are listed, the rest go. When a mod zip turns out to need more than the plan said, the + * engine stops (exit 5) and the new plan is shown for a second OK. 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() {} + + /** the engine's exit when the mod zips need more steps than the plan the owner saw */ + static final int PLAN_CHANGED = 5; + + abstract static class Done { + abstract void installed(String output); + + abstract void failed(String output); + + /** + * No answer in time (the install goes on by itself in the engine). The screen should hand back + * RESULT_OK all the same: the main screen's plan waits for the engine, then shows what changed. + */ + void lost(String message) { + failed(message); + } + } + + /** what the owner said yes to, per mod */ + static final class Choice { + final Set anyCar = new LinkedHashSet(), anyAuthor = new LinkedHashSet(); + + void args(List c) { + if (!anyCar.isEmpty()) c.add("--any-car=" + join(anyCar)); + if (!anyAuthor.isEmpty()) c.add("--any-author=" + join(anyAuthor)); + } + } + + static String join(Iterable s) { + StringBuilder b = new StringBuilder(); + for (String x : s) b.append(b.length() > 0 ? "," : "").append(x); + return b.toString(); + } + + /** 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(Activity a, List ids, boolean update, Done done) { + plan(a, ids, update, false, new Choice(), done); + } + + /** Update all: each installed mod with an update, planned on its own */ + static void startAll(Activity a, Done done) { + plan(a, new ArrayList(), true, true, new Choice(), done); + } + + private static void plan(final Activity a, final List ids, final boolean update, final boolean all, final Choice ch, 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")); + if (all) c.add("--all"); + else c.addAll(ids); + if (update) c.add("--update"); + ch.args(c); + return Hmgapid.call(180000, 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, all, ch, null, done); + } + }.start(a); + } + + /** the yes-or-no's in a plan: its own, and (update all) the left-out mods' */ + private static List overrides(JSONObject p) { + List out = new ArrayList(); + JSONArray o = p.optJSONArray("overrides"); + for (int i = 0; o != null && i < o.length(); i++) out.add(o.optJSONObject(i)); + JSONArray sk = p.optJSONArray("skipped"); + for (int i = 0; sk != null && i < sk.length(); i++) { + JSONArray so = sk.optJSONObject(i).optJSONArray("overrides"); + for (int k = 0; so != null && k < so.length(); k++) out.add(so.optJSONObject(k)); + } + return out; + } + + private static void confirm(final Activity a, final JSONObject p, final List ids, final boolean update, final boolean all, + final Choice ch, String intro, final Done done) { + StringBuilder msg = new StringBuilder(intro == null ? "" : intro + "\n\n"); + 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.optBoolean("turn_on")) line += ", and turn it on"; + if (s.has("for")) line += " (needed by " + s.optString("for") + ")"; + if (s.optBoolean("any_car")) line += " (not listed for this head unit: your choice)"; + msg.append("• ").append(line).append('\n'); + if ("install".equals(act) && !s.optBoolean("trusted", true)) untrusted = true; + } + final List ov = overrides(p); + JSONArray probs = p.optJSONArray("problems"); + JSONArray skipped = p.optJSONArray("skipped"); + 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'); + AlertDialog.Builder d = new AlertDialog.Builder(a).setTitle(update ? "Can't update it" : "Can't install it").setMessage(b.toString().trim()); + d.setPositiveButton("OK", null); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.show(); + return; + } + if (skipped != null && skipped.length() > 0) { + msg.append(n > 0 ? "\nNot updated now:\n" : "None of them can be updated now:\n"); + for (int i = 0; i < skipped.length(); i++) { + JSONObject s = skipped.optJSONObject(i); + msg.append("• ").append(s.optString("id")).append(": ").append(s.optString("why")).append('\n'); + } + } + if (n == 0) { + String t = msg.length() > 0 ? msg.toString().trim() + : notes != null && notes.length() > 0 ? notes.optString(0) : "Nothing to install: it's installed already."; + AlertDialog.Builder d = new AlertDialog.Builder(a).setMessage(t).setPositiveButton("OK", null); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.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, all before the first one is installed. Nothing changes on the head unit until you apply."); + if (untrusted) { + msg.append("\n\nYou chose to install mods by authors who aren't on HMG-API's trusted author list. A mod's code runs inside " + + "the head unit's apps."); + } + // what goes: the plan's own list (update all: the mods it kept), so a later check can't add any + final List go = new ArrayList(); + JSONArray w = p.optJSONArray("wanted"); + for (int i = 0; w != null && i < w.length(); i++) go.add(w.optString(i)); + if (go.isEmpty()) go.addAll(ids); + AlertDialog.Builder d = 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 x, int which) { + run(a, go, update, ch, done); + } + }); + if (!ov.isEmpty()) anyway(a, d, ov, ids, update, all, ch, done); + d.show(); + } + + /** + * "Install anyway…": the owner picks, mod by mod, what to say yes to (each with its reason), after + * a warning that says what each kind of yes means. Then the plan again with those. + */ + private static void anyway(final Activity a, AlertDialog.Builder d, final List ov, final List ids, final boolean update, + final boolean all, final Choice ch, final Done done) { + d.setNeutralButton(update ? "Update anyway…" : "Install anyway…", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int which) { + final String[] items = new String[ov.size()]; + final boolean[] picked = new boolean[ov.size()]; + boolean car = false, author = false; + for (int i = 0; i < ov.size(); i++) { + JSONObject o = ov.get(i); + boolean isCar = "car".equals(o.optString("kind")); + car |= isCar; + author |= !isCar; + items[i] = o.optString("id") + ": " + (isCar ? "not listed for this head unit (" + o.optString("why") + ")" : o.optString("why")); + } + StringBuilder warn = new StringBuilder(); + if (car) warn.append("Not listed for this head unit: its author didn't list this car, so it may not work here. HMG-API keeps " + + "a backup of every file it changes, and removing the mod puts them back. "); + if (author) warn.append("An author who isn't on the trusted list: the catalogue isn't signed, so HMG-API can't tell this key " + + "is really the author's. A mod's code runs inside the head unit's apps: say yes only if you know and trust its author. "); + new AlertDialog.Builder(a).setTitle("Which ones, at your own risk?") + .setMultiChoiceItems(items, picked, new DialogInterface.OnMultiChoiceClickListener() { + @Override + public void onClick(DialogInterface y, int i, boolean on) { + picked[i] = on; + } + }) + .setNegativeButton("Cancel", null) + .setPositiveButton("Next", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface y, int ww) { + Choice next = new Choice(); + next.anyCar.addAll(ch.anyCar); + next.anyAuthor.addAll(ch.anyAuthor); + boolean any = false; + for (int i = 0; i < ov.size(); i++) { + if (!picked[i]) continue; + any = true; + String id = ov.get(i).optString("id"); + if ("car".equals(ov.get(i).optString("kind"))) next.anyCar.add(id); + else next.anyAuthor.add(id); + } + if (any) plan(a, ids, update, all, next, done); + } + }).show(); + new AlertDialog.Builder(a).setTitle("At your own risk").setMessage(warn.toString().trim()) + .setPositiveButton("I understand", null).show(); + } + }); + } + + private static void run(final Activity a, final List ids, final boolean update, final Choice ch, 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); + ch.args(c); + return Hmgapid.call(1800000, c.toArray(new String[0])); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + wait.dismiss(); + if (e != null) { + done.lost("No answer from HMG-API in time (" + e.getMessage() + "). The download and install go on by themselves: " + + "back on the main screen, HMG-API waits for them, then shows what changed."); + } else if (r.code == PLAN_CHANGED) { + JSONObject q; + try { + q = json(r.output); + } catch (Exception x) { + done.failed(MainActivity.readable(r.output)); + return; + } + confirm(a, q, ids, update, false, ch, "The downloaded mod zips need more than the catalogue said, so nothing was " + + "installed yet. This is what it takes now:", done); + } 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); + } + + /** an install or update done (staged, not applied): what it did, and applying it now (the main screen's plan, then its OK) */ + static void applyNow(final MainActivity a, String title, String text) { + new AlertDialog.Builder(a).setTitle(title) + .setMessage(text + "\n\nNothing on the head unit changes until the changes are applied.") + .setNegativeButton("Later", null) + .setPositiveButton("Apply now", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + a.plan(); + } + }).show(); + } +} diff --git a/core/app/java/hmgapi/app/CatalogTab.java b/core/app/java/hmgapi/app/CatalogTab.java new file mode 100644 index 00000000..6b0653df --- /dev/null +++ b/core/app/java/hmgapi/app/CatalogTab.java @@ -0,0 +1,158 @@ +package hmgapi.app; + +import android.app.AlertDialog; +import android.graphics.Color; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.Arrays; + +/** + * Get mods: HMG-API's mod catalogue (engine catalog, kept from the last check; "Check now" + * fetches it again over home Wi-Fi). Each mod with what installing it would do here; Install + * takes the mods it requires too (CatalogFlow), then offers to apply. A tab of the main screen. + */ +final class CatalogTab { + final MainActivity a; + + CatalogTab(MainActivity a) { + this.a = a; + } + + private LinearLayout rows; + private TextView message, when; + private Button connect; + + View view() { + LinearLayout root = Ui.column(a); + root.setBackgroundColor(Ui.BG); + LinearLayout list = Ui.scrolling(root, 1, LinearLayout.LayoutParams.MATCH_PARENT); + list.setPadding(Ui.dp(a, 32), Ui.dp(a, 16), Ui.dp(a, 32), Ui.dp(a, 24)); + Ui.text(list, "Get mods", 30, true, Ui.GREEN); + Ui.text(list, "HMG-API's mod catalogue: mods the HMG-API project lists, each from its author's own GitHub release. " + + "Mods they need are installed with them. Checked and downloaded over home Wi-Fi only.", 16, false, Color.GRAY); + when = Ui.text(list, "", 15, false, Color.GRAY); + message = Ui.text(list, "", 18, false, Ui.WARN); + LinearLayout buttons = Ui.row(a); + 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(a, new Runnable() { + @Override + public void run() { + load(true); + } + }); + } + }); + connect.setVisibility(View.GONE); + list.addView(buttons); + rows = new LinearLayout(a); + rows.setOrientation(LinearLayout.VERTICAL); + list.addView(rows); + load(false); + return root; + } + + private void load(final boolean refresh) { + message.setText(refresh ? "Checking the catalogue…" : "Loading…"); + new Ui.Job() { + @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(a); + } + + 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" + + ("new".equals(st) ? ": installing it needs your yes" : "")), 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) + + (m.optBoolean("any_car") ? " (you chose to use it here)" : ""), + 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(a, Arrays.asList(m.optString("id")), update, new CatalogFlow.Done() { + @Override + public void installed(String output) { + CatalogFlow.applyNow(a, "Installed", MainActivity.readable(output)); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(a).setTitle("Not installed").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + void lost(String message) { + new AlertDialog.Builder(a).setTitle("Still installing").setMessage(message) + .setPositiveButton("OK", null).show(); + } + }); + } + }); + if (!online && !"same".equals(st)) b.setEnabled(false); + } +} diff --git a/core/app/java/hmgapi/app/LogsTab.java b/core/app/java/hmgapi/app/LogsTab.java index dfe28b08..4b1df750 100644 --- a/core/app/java/hmgapi/app/LogsTab.java +++ b/core/app/java/hmgapi/app/LogsTab.java @@ -35,7 +35,7 @@ View view() { @Override public void onClick(View v) { problem = true; - a.show(3); + a.show(MainActivity.LOGS); } }); Ui.button(bar, "Refresh", new View.OnClickListener() { diff --git a/core/app/java/hmgapi/app/MainActivity.java b/core/app/java/hmgapi/app/MainActivity.java index cc499f09..8a710ed6 100644 --- a/core/app/java/hmgapi/app/MainActivity.java +++ b/core/app/java/hmgapi/app/MainActivity.java @@ -24,7 +24,8 @@ * by category), Car Report, Logs. */ public class MainActivity extends Activity { - static final String[] TABS = { "Mods", "Settings", "Car Report", "Logs" }; + static final String[] TABS = { "Installed mods", "Catalogue", "Updates", "Settings", "Car Report", "Logs" }; + static final int MODS = 0, CATALOGUE = 1, UPDATES_TAB = 2, SETTINGS = 3, REPORT = 4, LOGS = 5; private LinearLayout pills; private FrameLayout content; private final TextView[] tabs = new TextView[TABS.length]; @@ -77,7 +78,7 @@ public void onClick(View v) { Ui.button(actions, "Restart unit", new View.OnClickListener() { @Override public void onClick(View v) { - confirmRestart(); + Park.confirmRestart(MainActivity.this); } }); top.addView(actions); @@ -90,7 +91,7 @@ public void onClick(View v) { final int n = i; LinearLayout t = Ui.column(this); tabs[i] = new TextView(this); - tabs[i].setText(TABS[i]); + tabs[i].setText(i == UPDATES_TAB ? updatesLabel() : TABS[i]); Ui.size(tabs[i], 21); tabs[i].setPadding(Ui.dp(this, 4), Ui.dp(this, 6), Ui.dp(this, 4), Ui.dp(this, 8)); t.addView(tabs[i]); @@ -166,11 +167,23 @@ void show(int n) { marks[i].setVisibility(i == n ? View.VISIBLE : View.INVISIBLE); } content.removeAllViews(); - View v = n == 0 ? new ModsTab(this).view() : n == 1 ? new SettingsTab(this).view() - : n == 2 ? new ReportTab(this).view() : new LogsTab(this).view(); + tabs[UPDATES_TAB].setText(updatesLabel()); + View v = n == MODS ? new ModsTab(this).view() : n == CATALOGUE ? new CatalogTab(this).view() + : n == UPDATES_TAB ? new UpdatesTab(this).view() : n == SETTINGS ? new SettingsTab(this).view() + : n == REPORT ? new ReportTab(this).view() : new LogsTab(this).view(); content.addView(v); } + /** "Updates (n)" when the last check found any (public/updates.json, written by the engine) */ + static String updatesLabel() { + try { + int n = new org.json.JSONObject(UsbFolders.read(new java.io.File("/data/hmgapi/public/updates.json"))).optInt("count"); + return n > 0 ? "Updates (" + n + ")" : "Updates"; + } catch (Exception e) { + return "Updates"; + } + } + /** "1.0.0 · Kia EV6 (usa 260507)" from the hook runtime's status */ static String subtitle() { try { @@ -187,7 +200,8 @@ 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 (safeMode()) Ui.pill(pills, "Safe mode: mods off", Ui.WARN); 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,15 +220,101 @@ 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 public state (state.json, written by the engine), or an empty one */ + static JSONObject publicState() { + try { + return new JSONObject(SettingsTab.read(new java.io.File("/data/hmgapi/public/state.json"))); + } catch (Exception e) { + return new JSONObject(); + } + } + + /** safe mode on (hmgapi.engine.Safe): every mod off */ + static boolean safeMode() { + return publicState().optBoolean("safe"); } /** the boot this process runs in (to the 10 s): a restart flag is only for the boot it was set in */ @@ -223,6 +323,8 @@ static long boot() { } boolean restartNeeded() { + // boot.sh rolled a cut-off apply back and waits for the car to be parked to restart, or left it to the owner + if (new java.io.File("/data/hmgapi/public/restart-needed").isFile()) return true; return getSharedPreferences("hmgapi", MODE_PRIVATE).getLong("restart_boot", -1) == boot(); } @@ -239,6 +341,7 @@ void needRestart() { @Override protected void onActivityResult(int request, int result, Intent data) { + if (request == UPDATES && current == MODS) show(MODS); // the Mods tab again: new mods, versions, the updates count if (request == UPDATES && result == RESULT_OK) plan(); // mods were installed: apply them (plan first) } @@ -273,25 +376,38 @@ void done(Hmgapid.Result r, Exception e) { : "Everything is applied."); return; } - new AlertDialog.Builder(MainActivity.this).setTitle("Apply these changes?").setMessage(shown) + final boolean files = filesChange(r.output); + new AlertDialog.Builder(MainActivity.this).setTitle("Apply these changes?") + .setMessage(files ? shown + "\n\nThis changes system files, so it only starts with the car in P. " + Park.STAY : shown) .setNegativeButton("Cancel", null) .setPositiveButton("Apply", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { - apply(); + if (!files) { + apply(false); + return; + } + Park.then(MainActivity.this, APPLYING, new Park.Go() { + @Override + public void go(boolean unknownOk) { + apply(unknownOk); + } + }); } }).show(); } }.start(this); } - private void apply() { + static final String APPLYING = "Applying changes to system files"; + + private void apply(final boolean unknownOk) { final AlertDialog wait = new AlertDialog.Builder(this) .setMessage("Applying… (rebuilding apps can take a few minutes; leave the head unit on)").setCancelable(false).show(); new Ui.Job() { @Override Hmgapid.Result work() throws Exception { - return Hmgapid.call(900000, "engine", "apply"); + return Hmgapid.call(900000, Park.with(unknownOk, "engine", "apply")); } @Override @@ -301,6 +417,13 @@ void done(Hmgapid.Result r, Exception e) { message("Lost contact while applying", e.getMessage() + ". The apply finishes on its own; open HMG-API again to check."); return; } + // the car left P since the check (or gives no reading): nothing was changed + if (Park.refused(MainActivity.this, r, APPLYING, new Park.Go() { + @Override + public void go(boolean ok) { + apply(ok); + } + })) return; boolean restart = restartNeeded() || r.output.contains("restart the head unit"); if (r.output.contains("restart the head unit")) needRestart(); AlertDialog.Builder d = new AlertDialog.Builder(MainActivity.this) @@ -327,6 +450,14 @@ void message(String title, String text) { new AlertDialog.Builder(this).setTitle(title).setMessage(text).setPositiveButton("OK", null).show(); } + /** Does an engine plan change files on /system (only in P: hmgapi.engine.Gear)? */ + static boolean filesChange(String out) { + for (String l : out.split("\n")) { + if (l.startsWith("change ") || l.startsWith("update ") || l.startsWith("restore ")) return true; + } + return false; + } + /** Does an engine plan change anything? */ static boolean changes(String out) { for (String l : out.split("\n")) { @@ -347,32 +478,7 @@ static String readable(String out) { return b.toString().trim(); } - private void confirmRestart() { - new AlertDialog.Builder(this) - .setTitle("Restart the head unit?") - .setMessage("The screen goes dark for about a minute. Don't use this while driving with navigation or a call active.") - .setNegativeButton("Cancel", null) - .setPositiveButton("Restart", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface d, int which) { - restart(); - } - }) - .show(); - } - void restart() { - new Ui.Job() { - @Override - Hmgapid.Result work() throws Exception { - return Hmgapid.call("reboot"); - } - - @Override - void done(Hmgapid.Result r, Exception e) { - if (e == null && r.code == 0) return; - message("Couldn't restart", e != null ? "hmgapid isn't running (" + e.getMessage() + ")" : r.output.trim()); - } - }.start(this); + Park.restart(this); } } diff --git a/core/app/java/hmgapi/app/ModsTab.java b/core/app/java/hmgapi/app/ModsTab.java index 9baaa9f2..732bebec 100644 --- a/core/app/java/hmgapi/app/ModsTab.java +++ b/core/app/java/hmgapi/app/ModsTab.java @@ -26,14 +26,20 @@ 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 or the mod's releases (public/updates.json), or null + String updateRepo; // the update is from this repo's releases (not the catalogue), or null + String source = "", repo, choice, withdrawn; // where its updates come from (catalogue, releases, off); a maintainer's withdrawal + boolean listed; + List requires = new ArrayList(); boolean enabled, hasCode; List services = new ArrayList(); int color() { - if (!enabled) return Ui.OFF; + if (!enabled || "safe".equals(state)) return Ui.OFF; if ("conflict".equals(state)) return Ui.WARN; if ("error".equals(state) || "unsupported".equals(state)) return Ui.ERROR; return Ui.ACCENT; @@ -41,6 +47,7 @@ int color() { String label() { if (!enabled) return "Off"; + if ("safe".equals(state) || MainActivity.safeMode()) return "On, held by safe mode"; if ("conflict".equals(state)) return "Conflict"; if ("error".equals(state)) return "Error"; if ("unsupported".equals(state)) return "Not for this car"; @@ -80,6 +87,16 @@ 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"); + JSONObject srcs = up == null ? null : up.optJSONObject("sources"); + JSONArray wds = up == null ? null : up.optJSONArray("withdrawn"); for (String line : Hmgapid.call("mods").output.split("\n")) { String[] w = line.split("\t"); if (w.length < 2) continue; @@ -96,6 +113,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 +132,23 @@ 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"))) continue; + m.update = u.optString("version"); + if ("release".equals(u.optString("source"))) m.updateRepo = u.optString("repo").replace("https://github.com/", ""); + } + JSONObject src = srcs == null ? null : srcs.optJSONObject(m.id); + if (src != null) { + m.source = src.optString("source"); + m.repo = src.has("repo") ? src.optString("repo") : null; + m.choice = src.has("choice") ? src.optString("choice") : null; + m.listed = src.optBoolean("listed"); + } + for (int i = 0; wds != null && i < wds.length(); i++) { + JSONObject wo = wds.getJSONObject(i); + if (m.id.equals(wo.optString("id")) && m.version.equals(wo.optString("version"))) m.withdrawn = wo.optString("why"); + } out.add(m); } return out; @@ -123,8 +163,8 @@ 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); + Ui.text(list, " No mods installed. Get some in the Catalogue tab (over home Wi-Fi), or put mod zips 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; @@ -143,7 +183,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() { @@ -207,7 +248,7 @@ void done(Hmgapid.Result r, Exception e) { Ui.button(detail, "Make a Car Report", new View.OnClickListener() { @Override public void onClick(View v) { - a.show(2); + a.show(MainActivity.REPORT); } }); } @@ -215,6 +256,43 @@ 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.withdrawn != null) { + TextView box = Ui.text(detail, "Withdrawn\nHMG-API's maintainers withdrew " + m.name + " " + m.version + ": " + m.withdrawn + + ". Update it, or turn it off until there's a fixed version.", 17, false, Ui.TEXT); + box.setBackground(Ui.box(a, 0xff3a3320, Ui.WARN, 10)); + int p = Ui.dp(a, 14); + box.setPadding(p, p, p, p); + } + if (m.update != null) { + Ui.text(detail, m.updateRepo != null ? "Version " + m.update + " is in " + m.updateRepo + "'s releases (signed by the same author; " + + "not reviewed for the catalogue)." : "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, 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); + } + + @Override + void lost(String message) { + a.message("Still updating", message); + a.plan(); // waits for the engine, then shows what changed + } + }); + } + }); + } + if (!m.requires.isEmpty()) Ui.text(detail, "Needs " + join(m.requires.toArray(new String[0])).replace(" · ", ", "), 15, false, Ui.GREY); + if (m.listed || m.repo != null) updatesFrom(m); Ui.line(detail); Ui.text(detail, "Settings", 21, true, Ui.GREEN); @@ -265,6 +343,45 @@ public void onClick(View v) { }); } + /** where the mod's updates come from: the catalogue, its own GitHub releases, or nowhere (engine update-source) */ + void updatesFrom(final Mod m) { + Ui.line(detail); + Ui.text(detail, "Updates", 21, true, Ui.GREEN); + String repo = m.repo == null ? null : m.repo.replace("https://github.com/", ""); + Ui.text(detail, "catalogue".equals(m.source) ? "From HMG-API's catalogue." + (repo != null ? " Its own releases (" + repo + ") can be followed instead, " + + "for example to test a new version before it's listed." : "") + : "releases".equals(m.source) ? "From " + repo + "'s releases on GitHub" + (m.listed ? ", instead of the catalogue." : ": it isn't in " + + "the catalogue.") + " Only a release signed with the same author key as the installed version is offered." + : "Off: HMG-API doesn't check for updates of " + m.name + ".", 16, false, Ui.GREY); + LinearLayout row = Ui.row(a); + if (m.listed && !"catalogue".equals(m.source)) source(row, m, "From the catalogue", "catalogue"); + if (repo != null && !"releases".equals(m.source)) source(row, m, "From its releases", "releases"); + if (!"off".equals(m.source)) source(row, m, "Don't check", "off"); + if (m.choice != null) source(row, m, "Default", "default"); + detail.addView(row); + } + + private void source(LinearLayout row, final Mod m, String label, final String to) { + Ui.button(row, label, new View.OnClickListener() { + @Override + public void onClick(View v) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call("engine", "update-source", m.id, to); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e != null || r.code != 0) a.message("Not changed", e != null ? e.getMessage() : MainActivity.readable(r.output)); + else android.widget.Toast.makeText(a, MainActivity.readable(r.output).trim(), android.widget.Toast.LENGTH_LONG).show(); + load(); + } + }.start(a); + } + }); + } + static String join(String... parts) { StringBuilder s = new StringBuilder(); for (String p : parts) if (p != null && !p.isEmpty()) s.append(s.length() > 0 ? " · " : "").append(p); @@ -281,9 +398,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() { diff --git a/core/app/java/hmgapi/app/Park.java b/core/app/java/hmgapi/app/Park.java new file mode 100644 index 00000000..d113e30a --- /dev/null +++ b/core/app/java/hmgapi/app/Park.java @@ -0,0 +1,157 @@ +package hmgapi.app; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; + +/** + * Steps that only start with the car in P: a restart (it takes the reverse camera's picture + * away for about a minute), and anything that changes /system or stops system apps for a + * while (an apply, an install, an HMG-API update), which a shift into reverse can cut off half + * done. The gear comes from HMG-API's vehicle reading (hmgapid `vehicle gear.park`). Not in P: + * the owner is told to shift to P, and nothing starts. No reading on this car: the warning + * plus override (the owner says the car is in P, and the step runs with --gear-unknown-ok). + * hmgapid's reboot and the engine check again (hmgapi.engine.Gear: exit codes 75 and 76), so + * a shift between the check here and the step still stops it. + */ +final class Park { + private Park() {} + + static final int NOT_PARKED = 75; + static final int UNKNOWN = 76; + static final String OVERRIDE = "--gear-unknown-ok"; + static final String STAY = "Keep the car in P until it's done."; + + interface Go { + /** the step itself; unknownOk: add OVERRIDE (no gear reading, the owner said go on) */ + void go(boolean unknownOk); + } + + /** what: the step, for the messages ("Restarting the head unit") */ + static void then(final Activity a, final String what, final Go go) { + new Ui.Job() { + @Override + Integer work() throws Exception { + Hmgapid.Result r = Hmgapid.call("vehicle", "gear.park"); + return r.code == 0 ? parse(r.output) : -1; + } + + @Override + void done(Integer g, Exception e) { + int v = e != null || g == null ? -1 : g; + if (v == 1) go.go(false); + else if (v == 0) notParked(a, what); + else unknown(a, what, go); + } + }.start(a); + } + + /** hmgapid's answer, "gear.park 1" ("-" when the car didn't answer): 1, 0, or -1 */ + static int parse(String out) { + for (String l : out.split("\n")) { + l = l.trim(); + if (l.equals("gear.park 1")) return 1; + if (l.equals("gear.park 0")) return 0; + } + return -1; + } + + static void notParked(Activity a, String what) { + new AlertDialog.Builder(a).setTitle("Shift to P first") + .setMessage(what + " only starts with the car in P: shifting into reverse while it runs can cut it off " + + "half done, and a restart takes the reverse camera's picture away for about a minute. Nothing was changed.") + .setPositiveButton("OK", null).show(); + } + + static void unknown(Activity a, final String what, final Go go) { + new AlertDialog.Builder(a).setTitle("Is the car in P?") + .setMessage("HMG-API can't read the gear on this car, so it can't check that it's in P. " + what + + " should only run in P: shifting into reverse while it runs can cut it off half done, and a " + + "restart takes the reverse camera's picture away for about a minute.\n\nPut the car in P. " + STAY) + .setNegativeButton("Cancel", null) + .setPositiveButton("It's in P: go on", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + go.go(true); + } + }).show(); + } + + /** + * An op the engine or hmgapid refused for the gear (75, 76): said here, true. For 76 the + * owner may go on: retry runs the step again with OVERRIDE. + */ + static boolean refused(Activity a, Hmgapid.Result r, String what, Go retry) { + if (r == null) return false; + if (r.code == NOT_PARKED) { + notParked(a, what); + return true; + } + if (r.code == UNKNOWN) { + unknown(a, what, retry); + return true; + } + return false; + } + + /** a command with OVERRIDE added when asked */ + static String[] with(boolean unknownOk, String... cmd) { + if (!unknownOk) return cmd; + String[] c = new String[cmd.length + 1]; + System.arraycopy(cmd, 0, c, 0, cmd.length); + c[cmd.length] = OVERRIDE; + return c; + } + + /** Restart the head unit: asked first, then only in P (every restart button: Main, Updates) */ + static void confirmRestart(final Activity a) { + new AlertDialog.Builder(a) + .setTitle("Restart the head unit?") + .setMessage("The screen goes dark for about a minute, and the reverse camera's picture with it, so this " + + "only runs with the car in P. Don't use it with navigation or a call active.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Restart", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface d, int which) { + restart(a); + } + }) + .show(); + } + + /** the restart itself, after the owner's yes: the gear, then hmgapid reboot */ + static void restart(final Activity a) { + then(a, RESTART, new Go() { + @Override + public void go(boolean unknownOk) { + restartNow(a, unknownOk); + } + }); + } + + static final String RESTART = "Restarting the head unit"; + + /** hmgapid reboot, which checks the gear again (a shift since the check here: said, nothing done) */ + static void restartNow(final Activity a, final boolean unknownOk) { + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call(with(unknownOk, "reboot")); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + if (e == null && r.code == 0) return; + if (e == null && refused(a, r, RESTART, new Go() { + @Override + public void go(boolean ok) { + restartNow(a, ok); + } + })) return; + new AlertDialog.Builder(a).setTitle("Couldn't restart") + .setMessage(e != null ? "hmgapid isn't running (" + e.getMessage() + ")" : r.output.trim()) + .setPositiveButton("OK", null).show(); + } + }.start(a); + } +} diff --git a/core/app/java/hmgapi/app/ProblemPage.java b/core/app/java/hmgapi/app/ProblemPage.java index 482ad77f..5b7efaaa 100644 --- a/core/app/java/hmgapi/app/ProblemPage.java +++ b/core/app/java/hmgapi/app/ProblemPage.java @@ -41,7 +41,7 @@ View view() { @Override public void onClick(View v) { LogsTab.problem = false; - a.show(3); + a.show(MainActivity.LOGS); } }); Ui.text(list, "Record a problem", 28, true, Ui.TEXT); @@ -119,10 +119,10 @@ void done(String r, Exception e) { recording = false; result = r; error = e == null ? null : String.valueOf(e.getMessage()); - if (LogsTab.problem && a.current == 3) a.show(3); // redraw, if the page is still open + if (LogsTab.problem && a.current == MainActivity.LOGS) a.show(MainActivity.LOGS); // redraw, if the page is still open } }.start(a); - a.show(3); + a.show(MainActivity.LOGS); } void stop(final Button go) { diff --git a/core/app/java/hmgapi/app/SettingsTab.java b/core/app/java/hmgapi/app/SettingsTab.java index 773fff2a..755dd9b3 100644 --- a/core/app/java/hmgapi/app/SettingsTab.java +++ b/core/app/java/hmgapi/app/SettingsTab.java @@ -2,7 +2,6 @@ import android.app.AlertDialog; import android.content.DialogInterface; -import android.content.Intent; import android.view.View; import android.widget.LinearLayout; import android.widget.Switch; @@ -16,12 +15,13 @@ /** * HMG-API's own settings, by category: Vehicle (the owner's switches for mods' - * commands), Updates, Phone projection (what mods set), Hook map (this car's map, - * checks, mapping it from its own files), About. The switches are kept by hmgapid - * (allow ). + * commands), Home Wi-Fi, Phone projection (what mods set), Hook map (this car's map, + * checks, mapping it from its own files), Safe mode (every mod off: engine safe), About. Updates + * (the catalogue's, USB, the car's own over-the-air ones) are the Updates tab's. The switches are + * kept by hmgapid (allow ). */ final class SettingsTab { - static final String[] CATS = { "Vehicle", "Updates", "Home Wi-Fi", "Phone projection", "Hook map", "About" }; + static final String[] CATS = { "Vehicle", "Home Wi-Fi", "Phone projection", "Hook map", "Safe mode", "About" }; final MainActivity a; LinearLayout cats, page; static int current; // the category shown last, kept while the app runs @@ -46,6 +46,7 @@ View view() { } void show(int n) { + if (n < 0 || n >= CATS.length) n = 0; current = n; cats.removeAllViews(); for (int i = 0; i < CATS.length; i++) { @@ -62,11 +63,12 @@ public void onClick(View v) { } page.removeAllViews(); Ui.text(page, CATS[n], 28, true, Ui.TEXT); - if (n == 0) vehicle(); - else if (n == 1) updates(); - else if (n == 2) homeWifi(); - else if (n == 3) projection(); - else if (n == 4) hookMap(); + String c = CATS[n]; + if ("Vehicle".equals(c)) vehicle(); + else if ("Home Wi-Fi".equals(c)) homeWifi(); + else if ("Phone projection".equals(c)) projection(); + else if ("Hook map".equals(c)) hookMap(); + else if ("Safe mode".equals(c)) safeMode(); else about(); } @@ -183,30 +185,6 @@ void homeWifi() { new HomeWifiPage(a, page).show(this); } - void updates() { - if (!hooksOn()) { - Ui.text(page, "HMG-API's hooks aren't running on this car (see Hook map), so it isn't blocking over-the-air updates: " - + "the car can download and install them. The car's own switch is what counts until the hooks run: Settings > " - + "General > Install Infotainment System Updates Automatically.", 16, true, Ui.TEXT); - } - owner("Over-the-air updates", "Off (the default): HMG-API blocks the car's own update downloads, so an update can't " - + "replace what HMG-API and your mods depend on. USB and dealer updates still work. Takes effect at the next restart.", - "Allow over-the-air updates", "ota_updates", false, new Runnable() { - @Override - public void run() { - a.needRestart(); - } - }); - Ui.text(page, "Updates from USB", 21, true, Ui.TEXT); - Ui.text(page, "HMG-API releases and mod packages (zips) in HMGAPI/updates/ on a USB stick.", 16, false, Ui.GREY); - Ui.button(page, "Check the USB stick", new View.OnClickListener() { - @Override - public void onClick(View v) { - a.startActivityForResult(new Intent(a, UpdatesActivity.class), MainActivity.UPDATES); - } - }); - } - void projection() { Ui.text(page, "What mods change in Android Auto and CarPlay (set in each mod's settings). Changes take effect the " + "next time the phone connects after a restart.", 16, false, Ui.GREY); @@ -309,8 +287,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() { @@ -319,6 +298,46 @@ public void run() { }); } + /** safe mode: every mod off, HMG-API and this app on (hmgapid engine safe on|off) */ + void safeMode() { + JSONObject st = MainActivity.publicState(); + boolean on = st.optBoolean("safe"); + if (on && st.optString("safe_why").startsWith("boot guard")) { + Ui.text(page, "HMG-API turned safe mode on by itself: Android failed to start several times in a row. Turn off or " + + "remove the mod you added or changed last (Mods), then turn safe mode off and restart.", 17, true, Ui.WARN); + } + Ui.text(page, "Turns every mod off at once without removing anything: no mod's hooks (from the next restart), services, " + + "apps or network rules (adb stays reachable). HMG-API and this app stay on, so you can turn it off here. Use it when something goes " + + "wrong after adding or changing a mod, to see whether a mod is the cause. The mods' changes to system files stay " + + "as they are: turning a mod off and applying, or uninstalling, puts those back.", 16, false, Ui.GREY); + Ui.text(page, "HMG-API also turns it on by itself if Android keeps failing to start with mods. Without the screen, over adb: " + + "adb shell \"hmgapid engine safe on\" (or off).", 16, false, Ui.GREY); + final Switch sw = Ui.switchRow(page, "Safe mode (all mods off)"); + sw.setChecked(on); + sw.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(android.widget.CompoundButton b, final boolean checked) { + sw.setEnabled(false); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return Hmgapid.call(120000, "engine", "safe", checked ? "on" : "off"); + } + + @Override + void done(Hmgapid.Result r, Exception e) { + boolean ok = e == null && r.code == 0; + a.message(ok ? (checked ? "Safe mode on" : "Safe mode off") : "Didn't work", e != null ? Hmgapid.unreachable(e) : r.output.trim()); + if (ok && r.output.contains("restart the head unit")) a.needRestart(); + else a.refreshStatus(); + show(current); + } + }.start(a); + } + }); + Ui.line(page); + } + void run(String waiting, final String... cmd) { final AlertDialog wait = new AlertDialog.Builder(a).setMessage(waiting).setCancelable(false).show(); new Ui.Job() { diff --git a/core/app/java/hmgapi/app/UpdatesActivity.java b/core/app/java/hmgapi/app/UpdatesActivity.java index de25e9e2..6713bedc 100644 --- a/core/app/java/hmgapi/app/UpdatesActivity.java +++ b/core/app/java/hmgapi/app/UpdatesActivity.java @@ -159,8 +159,20 @@ public void onClick(DialogInterface d, int which) { }).show(); } + static final String INSTALLING = "Installing a mod"; + + /** a mod's install leads to an apply (Apply changes), so it starts only in P too (Park) */ private void install(final JSONObject p, final String uuid, final boolean anyCar) { - message.setText("Installing " + p.optString("name") + "…"); + Park.then(this, INSTALLING, new Park.Go() { + @Override + public void go(boolean unknownOk) { + installNow(p, uuid, anyCar); + } + }); + } + + private void installNow(final JSONObject p, final String uuid, final boolean anyCar) { + message.setText("Installing " + p.optString("name") + "… " + Park.STAY); new Ui.Job() { @Override Hmgapid.Result work() throws Exception { @@ -187,22 +199,30 @@ private void confirmHmgApi(final JSONObject p) { new AlertDialog.Builder(this) .setTitle("Update HMG-API to " + p.optString("version") + "?") .setMessage("HMG-API's installer runs (it takes a minute; leave the head unit on), then the head unit " - + "needs a restart. Your mods and settings stay.") + + "needs a restart. Your mods and settings stay.\n\nIt changes system files, so it only starts with " + + "the car in P. " + Park.STAY) .setNegativeButton("Cancel", null) .setPositiveButton("Update", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface d, int which) { - updateHmgApi(p); + Park.then(UpdatesActivity.this, UPDATING, new Park.Go() { + @Override + public void go(boolean unknownOk) { + updateHmgApi(p, unknownOk); + } + }); } }).show(); } - private void updateHmgApi(final JSONObject p) { - message.setText("Updating HMG-API…"); + static final String UPDATING = "Updating HMG-API"; + + private void updateHmgApi(final JSONObject p, final boolean unknownOk) { + message.setText("Updating HMG-API… " + Park.STAY); new Ui.Job() { @Override Hmgapid.Result work() throws Exception { - return Hmgapid.call(900000, "engine", "update-hmgapi", p.optString("file")); + return Hmgapid.call(900000, Park.with(unknownOk, "engine", "update-hmgapi", p.optString("file"))); } @Override @@ -212,21 +232,22 @@ void done(Hmgapid.Result r, Exception e) { + "own; restart the head unit once it's done."); return; } + if (Park.refused(UpdatesActivity.this, r, UPDATING, new Park.Go() { + @Override + public void go(boolean ok) { + updateHmgApi(p, ok); + } + })) { + message.setText("Not updated yet: the car must be in P."); + return; + } AlertDialog.Builder d = new AlertDialog.Builder(UpdatesActivity.this) .setTitle(r.code == 0 ? "HMG-API updated" : "Not updated").setMessage(r.output.trim()); if (r.code == 0) { d.setNegativeButton("Later", null).setPositiveButton("Restart now", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface x, int which) { - new Ui.Job() { - @Override - Hmgapid.Result work() throws Exception { - return Hmgapid.call("reboot"); - } - - @Override - void done(Hmgapid.Result rr, Exception ee) {} - }.start(UpdatesActivity.this); + Park.restart(UpdatesActivity.this); // only in P } }); } else { diff --git a/core/app/java/hmgapi/app/UpdatesTab.java b/core/app/java/hmgapi/app/UpdatesTab.java new file mode 100644 index 00000000..4b18b468 --- /dev/null +++ b/core/app/java/hmgapi/app/UpdatesTab.java @@ -0,0 +1,355 @@ +package hmgapi.app; + +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.graphics.Color; +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 when home Wi-Fi comes up, at most every 6 hours; + * "Check now" checks again). An update takes any new mods it requires (CatalogFlow); Update all + * plans each mod on its own, so one that can't go doesn't hold back the rest. HMG-API's own runs + * its installer, then the head unit restarts. Mod updates are applied from here (Apply now) or with + * Apply changes; ones the automatic check downloaded ("staged") wait aside until then. A tab of the + * main screen. + */ +final class UpdatesTab { + final MainActivity a; + + UpdatesTab(MainActivity a) { + this.a = a; + } + + private LinearLayout rows; + private TextView message, when; + private Button connect, all; + + View view() { + LinearLayout root = Ui.column(a); + root.setBackgroundColor(Ui.BG); + LinearLayout list = Ui.scrolling(root, 1, LinearLayout.LayoutParams.MATCH_PARENT); + list.setPadding(Ui.dp(a, 32), Ui.dp(a, 16), Ui.dp(a, 32), Ui.dp(a, 24)); + Ui.text(list, "Updates", 30, true, Ui.GREEN); + Ui.text(list, "Newer versions of your mods from HMG-API's catalogue (or, for a mod it doesn't list, from the mod's own releases " + + "on GitHub), 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(a); + 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(a, 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(a); + 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(a, check, "no_update_check", true, null); + Switch stage = Ui.switchRow(list, "Also download mod updates then: they wait until you apply"); + Ui.allowSwitch(a, stage, "auto_stage_updates", false, null); + Ui.text(list, "Only plain updates are downloaded by themselves: one that needs another mod installed or turned on waits for your " + + "Update. Nothing downloaded runs before you apply. HMG-API itself is only ever updated when you tap its Update.", 15, false, Color.GRAY); + + Ui.line(list); + Ui.text(list, "Updates from USB", 21, true, Ui.GREEN); + Ui.text(list, "HMG-API releases and mod zips in HMGAPI/updates/ on a USB stick: for a car with no home Wi-Fi, " + + "or a mod that isn't in the catalogue.", 15, false, Color.GRAY); + Ui.button(list, "Check the USB stick", new View.OnClickListener() { + @Override + public void onClick(View v) { + a.startActivityForResult(new android.content.Intent(a, UpdatesActivity.class), MainActivity.UPDATES); + } + }); + + Ui.line(list); + Ui.text(list, "The car's own updates", 21, true, Ui.GREEN); + if (!SettingsTab.hooksOn()) { + Ui.text(list, "HMG-API's hooks aren't running on this car (Settings > Hook map), so it isn't blocking over-the-air updates: " + + "the car can download and install them. The car's own switch is what counts until the hooks run: Settings > " + + "General > Install Infotainment System Updates Automatically.", 15, true, Ui.TEXT); + } + Ui.text(list, "Off (the default): HMG-API blocks the car's own over-the-air update downloads, so an update can't replace what " + + "HMG-API and your mods depend on. USB and dealer updates still work. Takes effect at the next restart.", 15, false, Color.GRAY); + Switch ota = Ui.switchRow(list, "Allow over-the-air updates"); + Ui.allowSwitch(a, ota, "ota_updates", false, new Runnable() { + @Override + public void run() { + a.needRestart(); + } + }); + load(false); + return root; + } + + 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).")); + JSONArray wd = d.optJSONArray("withdrawn"); + for (int i = 0; wd != null && i < wd.length(); i++) { + JSONObject w = wd.optJSONObject(i); + Ui.gap(rows, 14); + Ui.text(rows, "Withdrawn: " + w.optString("id") + " " + w.optString("version"), 20, true, Ui.WARN); + Ui.text(rows, "HMG-API's maintainers withdrew this version: " + w.optString("why") + ". Update it if there's a newer one " + + "below, or turn it off in Installed mods.", 15, false, Color.GRAY); + } + if (d.has("hmgapi")) hmgapiRow(d.optJSONObject("hmgapi"), online); + int count = 0; + for (int i = 0; mods != null && i < mods.length(); i++) { + row(mods.optJSONObject(i), online); + count++; + } + all.setVisibility(count > 1 ? View.VISIBLE : View.GONE); + all.setEnabled(online); + all.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + update(null); // each mod planned on its own (update --all) + } + }); + } + }.start(a); + } + + 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") + (m.optBoolean("prerelease") ? " (pre-release)" : ""), + 16, false, Ui.GREEN); + if (m.optString("description").length() > 0) Ui.text(rows, m.optString("description"), 15, false, Color.GRAY); + if ("release".equals(m.optString("source"))) { + Ui.text(rows, "From " + m.optString("repo").replace("https://github.com/", "") + "'s releases on GitHub: signed by the same author as " + + "the installed version, but not reviewed for HMG-API's catalogue.", 15, false, Ui.WARN); + } + if (m.optBoolean("staged")) Ui.text(rows, "Downloaded by the automatic check: it goes in when you apply", 15, false, 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 or updated with it if needed)", 15, false, Color.GRAY); + } + LinearLayout buttons = Ui.row(a); + Button b = Ui.button(buttons, "Update", new View.OnClickListener() { + @Override + public void onClick(View v) { + update(Arrays.asList(m.optString("id"))); + } + }); + b.setEnabled(online); + if (m.optString("notes").length() > 0 || m.optString("page").length() > 0) { + Ui.button(buttons, "Release notes", new View.OnClickListener() { + @Override + public void onClick(View v) { + notes(m.optString("name", m.optString("id")), m); + } + }); + } + rows.addView(buttons); + } + + /** ids null: update all */ + private void update(List ids) { + CatalogFlow.Done done = new CatalogFlow.Done() { + @Override + public void installed(String output) { + CatalogFlow.applyNow(a, "Updated", MainActivity.readable(output)); + load(false); + } + + @Override + public void failed(String output) { + new AlertDialog.Builder(a).setTitle("Not updated").setMessage(output) + .setPositiveButton("OK", null).show(); + load(false); + } + + @Override + void lost(String message) { + new AlertDialog.Builder(a).setTitle("Still updating").setMessage(message) + .setPositiveButton("OK", null).show(); + } + }; + if (ids == null) CatalogFlow.startAll(a, done); + else CatalogFlow.start(a, ids, true, done); + } + + 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); + if (h.optString("notes").length() > 0 || h.optString("page").length() > 0) { + Ui.button(rows, "Release notes", new View.OnClickListener() { + @Override + public void onClick(View v) { + notes("HMG-API", h); + } + }); + } + Button b = Ui.button(rows, "Update HMG-API", true, new View.OnClickListener() { + @Override + public void onClick(View v) { + new AlertDialog.Builder(a) + .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(false); + } + }).show(); + } + }); + b.setEnabled(online); + } + + /** the release's notes (the engine keeps them from GitHub: the head unit may have no browser), and its page */ + private void notes(String what, JSONObject h) { + final String page = h.optString("page"); + String text = h.optString("notes").length() > 0 ? h.optString("notes").replace("\r", "") : "No notes with this release."; + android.widget.ScrollView sv = new android.widget.ScrollView(a); + TextView t = new TextView(a); + t.setText(text + (page.length() > 0 ? "\n\n" + page : "")); + t.setTextIsSelectable(true); + Ui.size(t, 16); + int pad = Ui.dp(a, 16); + t.setPadding(pad, pad, pad, pad); + sv.addView(t); + AlertDialog.Builder d = new AlertDialog.Builder(a).setTitle(what + " " + h.optString("version")).setView(sv) + .setPositiveButton("OK", null); + final android.content.Intent open = new android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(page)); + if (page.startsWith("https://") && open.resolveActivity(a.getPackageManager()) != null) { + d.setNeutralButton("Open the page", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + try { + a.startActivity(open); + } catch (Exception ignored) { + // no browser after all: the link is in the text + } + } + }); + } + d.show(); + } + + /** force: the owner's "Update anyway" after mods that wouldn't take the new version were named */ + private void updateHmgApi(final boolean force) { + final AlertDialog wait = new AlertDialog.Builder(a) + .setMessage("Downloading and installing HMG-API… (leave the head unit on)").setCancelable(false).show(); + new Ui.Job() { + @Override + Hmgapid.Result work() throws Exception { + return force ? Hmgapid.call(900000, "engine", "update", "hmgapi", "--force") : 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(a) + .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(a); + } + }); + } else if (!force && r.output.contains("engine update hmgapi --force")) { // mods that wouldn't load with it: the owner decides + d.setNegativeButton("Cancel", null).setNeutralButton("Update anyway", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface x, int w) { + new AlertDialog.Builder(a).setTitle("Update anyway?") + .setMessage("The mods named won't load with the new HMG-API, and applying changes stops until you update or " + + "turn them off.") + .setNegativeButton("Cancel", null) + .setPositiveButton("Update anyway", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface y, int ww) { + updateHmgApi(true); + } + }).show(); + } + }); + } else { + d.setPositiveButton("OK", null); + } + d.show(); + message.setText(r.code == 0 ? "HMG-API updated: restart the head unit." : "Not updated."); + } + }.start(a); + } +} diff --git a/core/fetch/fetch.c b/core/fetch/fetch.c new file mode 100644 index 00000000..7a695312 --- /dev/null +++ b/core/fetch/fetch.c @@ -0,0 +1,357 @@ +/* libhmgapi_fetch.so: one HTTPS request, or one DNS query, for HMG-API's engine (hmgapi.engine.NativeFetch): + * the catalogue, mod zips and HMG-API releases, over home Wi-Fi only (Catalog). + * + * Android 4.4's Java TLS shares no cipher suite with GitHub, but the unit's own libssl.so + * (OpenSSL 1.0.1) has TLS 1.2 with ECDHE and AES-GCM. This opens a TCP connection, does the + * 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 DNS query (Java's + * bytes, DnsLookup) goes out the same way, over UDP, so it is held to home Wi-Fi too. + * + * 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 mod zip must have the SHA-256 its catalogue entry names, and the engine checks its signature + * (the installed mod's author key; HMG-API's release key for HMG-API itself) and refuses a + * downgrade. A hostile network can make a check find nothing, not get code installed. + * + * Every socket carries home Wi-Fi's mark (SO_MARK 0x2951: table 95, HomeWifi) and is bound to + * wlan0 (SO_BINDTODEVICE), or isn't used at all: a socket that can't have both is an error. The + * mark makes its route table 95's (home Wi-Fi, or the unreachable default while home Wi-Fi is + * down); the binding holds it to wlan0 even before the network keeper has added the fwmark rule + * (priority 900), when the mark alone would leave it on the main table's mobile data. Root only + * (the engine is). Each socket has send and receive timeouts (connect, the handshake and every + * read and write), so a network that goes away mid-answer (route_down) ends the call. + * + * How the answer ended matters: a TLS close (close_notify) is a whole answer; anything else + * (the connection dropped, a read error, a timeout) is E_CUT with what came written to the file, + * which Java takes only if the HTTP framing says it is whole (Http). + * + * 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. + * No static buffers, but OpenSSL 1.0.1 (the unit's) isn't thread-safe without locking callbacks, + * which this doesn't install: NativeFetch serializes every call (fetch and dns hold one lock). + * First written as a mod (an update-check proof of concept), run on an Ioniq 5 US 260507. + */ +#ifdef HOST +#include +#include +#include +#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; +}; +struct timeval { long tv_sec, tv_usec; }; /* 32-bit ARM: two 32-bit longs */ +_Static_assert(sizeof(struct timeval) == 8, "ARM timeval"); +#define AF_INET 2 +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 +#define AI_NUMERICHOST 4 +#define SOL_SOCKET 1 +#define SO_RCVTIMEO 20 +#define SO_SNDTIMEO 21 +#define SO_BINDTODEVICE 25 +#define SO_MARK 36 +#define O_WRONLY 01 +#define O_CREAT 0100 +#define O_EXCL 0200 +#define O_NOFOLLOW 0100000 /* ARM's value (x86's is 0400000) */ +#define LIBC_SYM(name) dlsym(libc_h, #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 + +/* error codes (negative), so Java can say which step failed (NativeFetch.why) */ +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, E_ROUTE = -12, E_CUT = -13, E_SOCKET = -14 }; + +#define SSL_CTRL_OPTIONS 32 +#define SSL_CTRL_SET_TLSEXT_HOSTNAME 55 +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L +#define SSL_ERROR_ZERO_RETURN 6 +#define HOME_MARK 0x2951 +#define HOME_IFACE "wlan0" +#define BUF 16384 + +/* the C library's functions this needs, looked up once per call */ +struct libc { + int (*getaddrinfo)(const char *, const char *, const struct addrinfo *, struct addrinfo **); + void (*freeaddrinfo)(struct addrinfo *); + int (*socket)(int, int, int); + int (*connect)(int, const struct sockaddr *, sock_len); + int (*setsockopt)(int, int, int, const void *, sock_len); + int (*close)(int); + int (*open)(const char *, int, ...); + long (*write)(int, const void *, unsigned long); + long (*read)(int, void *, unsigned long); + void *(*malloc)(unsigned long); + void (*free)(void *); +}; + +static int libc_load(struct libc *c, const char *c_lib) { +#ifndef HOST + void *libc_h = dlopen(c_lib, RTLD_NOW); + if (!libc_h) return E_LIB; +#else + (void) c_lib; +#endif + c->getaddrinfo = LIBC_SYM(getaddrinfo); + c->freeaddrinfo = LIBC_SYM(freeaddrinfo); + c->socket = LIBC_SYM(socket); + c->connect = LIBC_SYM(connect); + c->setsockopt = LIBC_SYM(setsockopt); + c->close = LIBC_SYM(close); + c->open = LIBC_SYM(open); + c->write = LIBC_SYM(write); + c->read = LIBC_SYM(read); + c->malloc = LIBC_SYM(malloc); + c->free = LIBC_SYM(free); + if (!c->getaddrinfo || !c->freeaddrinfo || !c->socket || !c->connect || !c->setsockopt || !c->close || !c->open + || !c->write || !c->read || !c->malloc || !c->free) return E_SYM; + return 0; +} + +/* a socket for a: timeouts set, and (on the unit) home Wi-Fi's mark and wlan0, or none at all */ +static int home_socket(struct libc *c, const struct addrinfo *a, int timeout_ms) { + int fd = c->socket(a->ai_family, a->ai_socktype, a->ai_protocol); + if (fd < 0) return E_SOCKET; + struct timeval tv; + memset(&tv, 0, sizeof tv); + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + if (c->setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv) != 0 + || c->setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv) != 0) { /* SO_SNDTIMEO bounds connect too */ + c->close(fd); + return E_SOCKET; + } +#ifndef HOST + unsigned int mark = HOME_MARK; + static const char iface[] = HOME_IFACE; + if (c->setsockopt(fd, SOL_SOCKET, SO_MARK, &mark, sizeof mark) != 0 + || c->setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, iface, sizeof iface) != 0) { + c->close(fd); + return E_ROUTE; + } +#endif + return fd; +} + +/* connected to the first of addr:port that answers; or a negative error */ +static int home_connect(struct libc *c, const char *addr, const char *port, int type, int timeout_ms) { + 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 = type; + hints.ai_flags = AI_NUMERICHOST; /* an address (DnsLookup's): never the system resolver, which uses mobile data */ + if (c->getaddrinfo(addr, port, &hints, &res) != 0 || !res) return E_RESOLVE; + int fd = E_CONNECT; + for (a = res; a; a = a->ai_next) { + fd = home_socket(c, a, timeout_ms); + if (fd < 0) break; /* no socket held to home Wi-Fi: no connection */ + if (c->connect(fd, a->ai_addr, a->ai_addrlen) == 0) break; + c->close(fd); + fd = E_CONNECT; + } + c->freeaddrinfo(res); + return fd; +} + +/* the answer's file: new, ours (O_EXCL), never through a link */ +static int open_new(struct libc *c, const char *path) { + return c->open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0600); +} + +static int write_all(struct libc *c, int fd, const char *p, int n) { + int w = 0; + while (w < n) { + long k = c->write(fd, p + w, (unsigned long) (n - w)); + if (k <= 0) return -1; + w += (int) k; + } + return 0; +} + +/* host is "name@address": the name goes in the TLS server name, the connection goes to the + * address (Java's own lookup, DnsLookup: the unit's resolver would ask the car's carrier DNS) */ +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, int timeout_ms) { + char host[256]; + 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] != '@' || !host_arg[hn + 1]) return E_ARGS; + const char *addr = host_arg + hn + 1; + struct libc c; + int rc = libc_load(&c, c_lib); + if (rc) return rc; + void *ssl_h = dlopen(ssl_lib, RTLD_NOW); + if (!ssl_h) return E_LIB; + + /* 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_get_error)(const void *, int) = dlsym(ssl_h, "SSL_get_error"); + 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 || !p_get_error) return E_SYM; + + int fd = home_connect(&c, addr, port, SOCK_STREAM, timeout_ms); + if (fd < 0) return fd; + void *ctx = 0, *ssl = 0; + int out = -1, clean = 0; + char *buf = 0; + 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; + } + buf = c.malloc(BUF); + if (!buf) { rc = E_CTX; goto done; } + out = open_new(&c, out_path); + if (out < 0) { rc = E_FILE; goto done; } + int total = 0; + for (;;) { + int n = p_ssl_read(ssl, buf, BUF); + if (n <= 0) { + /* the server's TLS close (Connection: close) ends a whole answer; a dropped connection, + * a read error or a timeout doesn't: Java decides from the HTTP framing (E_CUT) */ + clean = p_get_error(ssl, n) == SSL_ERROR_ZERO_RETURN; + break; + } + if (n > max_bytes - total) { rc = E_TOO_BIG; goto done; } + if (write_all(&c, out, buf, n)) { rc = E_FILE; goto done; } + total += n; + } + rc = total == 0 ? E_READ : clean ? total : E_CUT; +done: + if (out >= 0) c.close(out); + if (buf) c.free(buf); + if (ssl) { if (clean && p_shutdown) p_shutdown(ssl); p_free(ssl); } /* no shutdown after an error (OpenSSL) */ + if (ctx) p_ctx_free(ctx); + c.close(fd); + return rc; +} + +/* one UDP query to server:port (DnsLookup's bytes) on a socket held to home Wi-Fi; the answer to out_path */ +static int dns(const char *c_lib, const char *server, const char *port, const char *query, int query_len, + const char *out_path, int timeout_ms) { + struct libc c; + int rc = libc_load(&c, c_lib); + if (rc) return rc; + int fd = home_connect(&c, server, port, SOCK_DGRAM, timeout_ms); + if (fd < 0) return fd; + char *buf = c.malloc(1500); + int out = -1; + if (!buf) { rc = E_CTX; goto done; } + if (c.write(fd, query, (unsigned long) query_len) != query_len) { rc = E_SEND; goto done; } + long n = c.read(fd, buf, 1500); + if (n <= 0) { rc = E_READ; goto done; } + out = open_new(&c, out_path); + if (out < 0 || write_all(&c, out, buf, (int) n)) { rc = E_FILE; goto done; } + rc = (int) n; +done: + if (out >= 0) c.close(out); + if (buf) c.free(buf); + c.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, jint timeout_ms) { + (void) cls; + if (!ssl_lib || !c_lib || !host || !port || !request || !out_path || max_bytes <= 0 || timeout_ms <= 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, (int) timeout_ms) : 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; +} + +JNIEXPORT jint JNICALL Java_hmgapi_engine_NativeFetch_dns(JNIEnv *env, jclass cls, jstring c_lib, jstring server, + jstring port, jbyteArray query, jstring out_path, jint timeout_ms) { + (void) cls; + if (!c_lib || !server || !port || !query || !out_path || timeout_ms <= 0) return E_ARGS; + const char *c = (*env)->GetStringUTFChars(env, c_lib, 0), *sv = (*env)->GetStringUTFChars(env, server, 0); + const char *p = (*env)->GetStringUTFChars(env, port, 0), *o = (*env)->GetStringUTFChars(env, out_path, 0); + jsize len = (*env)->GetArrayLength(env, query); + jbyte *q = (*env)->GetByteArrayElements(env, query, 0); + int rc = (c && sv && p && o && q) ? dns(c, sv, p, (const char *) q, (int) len, o, (int) timeout_ms) : E_ARGS; + if (q) (*env)->ReleaseByteArrayElements(env, query, q, JNI_ABORT); + if (o) (*env)->ReleaseStringUTFChars(env, out_path, o); + if (p) (*env)->ReleaseStringUTFChars(env, port, p); + if (sv) (*env)->ReleaseStringUTFChars(env, server, sv); + if (c) (*env)->ReleaseStringUTFChars(env, c_lib, c); + return rc; +} diff --git a/core/hmgapid/README.md b/core/hmgapid/README.md index 65f899e6..b07729cd 100644 --- a/core/hmgapid/README.md +++ b/core/hmgapid/README.md @@ -11,12 +11,16 @@ hmgapid [args...] # any user: asks the daemon, prints its output, exits | Caller (SO_PEERCRED) | Ops | |---|---| | root (0), shell (2000: adb) | everything: `sh `, `remount rw\|ro`, plus the HMG-API ops | -| the `hmgapi.app` uid (from `/data/system/packages.list`) | `mods`, `enable `, `disable `, `setting-get `, `setting-set `, `log`, `reboot`, `allow`, `park-rule`, `services [mod]`, `service-restart\|stop\|start `, `service-log `, `usb [mod]`, `vehicle …` | +| the `hmgapi.app` uid (from `/data/system/packages.list`) | `mods`, `enable `, `disable `, `setting-get `, `setting-set `, `log`, `reboot [--gear-unknown-ok]` (only in P: 75 not in P; 76 no gear reading, unless told to go on), `allow`, `park-rule`, `services [mod]`, `service-restart\|stop\|start `, `service-log `, `usb [mod]`, `vehicle …` | | an enabled mod's app (its `apps`, `state/apps.txt`) or service (by session) | its own mod only: `whoami`, `setting-get`, `setting-set `, `services`, `service-restart\|stop\|start `, `service-log `, `usb`, `vehicle …` (the readings its mod.json lists) | | anyone else | `ping`, `version` | **Services.** The daemon runs the enabled mods' services (`state/services.txt`, written by the engine from `mod.json`): as root, system or the mod's app uid, each in its own session, with its own folder (`run//`) and log (`logs//.log`), started at boot or once `sys.boot_completed` is 1, restarted with backoff, stopped (TERM, then KILL) when the mod is turned off. It also runs `engine apps` once Android is up and whenever `state/apps.txt` changes. +A service's output comes to the daemon through a pipe, so its log is capped while it runs: 256 KB, then `.1`, and at most 256 KB of output kept a minute (the rest left out, with a line saying so and how much; before, the log was only checked when the service started, and a looping `echo` wrote 885 MB in 8 s). HMG-API's own log (`hmgapi log`, LogKeeper) is one of these services, and LogKeeper keeps each mod's lines to 300 a minute, so HMG-API's own lines stay. A mod's service runs at nice 10 with the lowest best-effort I/O priority (`setpriority`, `ioprio_set`) unless its `mod.json` asks for `"priority": "normal"` (`state/service-priority.txt`); HMG-API's own run at normal priority. Only fds 0-2 reach a service. + +**Safe mode.** While `/data/hmgapi/SAFE` is there (`engine safe on`, the app's switch, the zygote wrapper's boot guard, or the file by hand), the daemon keeps only HMG-API's own lines of `services.txt`: every mod's service stops, boot-start ones included, and none starts, even right after a restart before the engine has run. When the file comes or goes it has the engine publish the state again (every mod off: apps, network rules, the public state) and runs `engine apps`. `engine` is open to root, shell and the HMG-API app, so `hmgapid engine safe on|off` works from adb and from the app. + **Boot.** `hmgapid boot` is the boot hook's only line (`install-recovery.sh`, `qb_runtime.sh`) and what HMG-API's NEMESIS service runs. It returns at once, so the boot script goes straight on to NEMESIS's start. A detached child (own session, none of the caller's fds) starts the daemon if none runs (the zygote wrapper usually started it already) and, if it's the first call this boot, runs `/data/hmgapi/boot.sh` (HMG-API's boot steps: binds, the app's installer, `hook-check.sh`, the NEMESIS sync, `engine recover`; output in `boot.log`). The lock is `/dev/.hmgapi-boot`, made with `O_EXCL` on tmpfs (gone at every boot). So whichever trigger comes first runs the boot steps, and the others do nothing. Abstract socket `@hmgapid` (no file permissions involved; the bind is also the single-instance lock). Request `LFD1` + argc + length-prefixed args; response frames `O` (output, streamed) and `X` (exit code). Log: `/data/hmgapi/hmgapid.log`. diff --git a/core/hmgapid/hmgapid.c b/core/hmgapid/hmgapid.c index 1ea04bf3..f9f998c1 100644 --- a/core/hmgapid/hmgapid.c +++ b/core/hmgapid/hmgapid.c @@ -15,7 +15,7 @@ * anyone else ping, version * * HMG-API ops: mods, enable , disable , setting-get , - * setting-set , log, reboot, engine , log, reboot [--gear-unknown-ok] (only in P), engine (the patch engine, run as root with app_process and the * runtime jar). Root ops: sh , remount rw|ro. * @@ -52,6 +52,23 @@ typedef long sl; #ifndef ROOTDIR #define ROOTDIR "/data/hmgapi" #endif +/* Safe mode while this file is there: no mod's service runs (HMG-API's own do), and the + * engine publishes every mod as off (no apps, no network rules); the zygote wrapper and the + * runtime load no mod's hooks. `engine safe on|off`, or the file by hand. */ +#define SAFEFILE ROOTDIR "/SAFE" +/* A service's log: LOG_MAX, then .1, checked as its output comes in; at most LOG_RATE bytes + * of it kept in each LOG_WINDOW seconds, the rest left out (a loop that logs must not fill + * /data or wear the flash). */ +#ifndef LOG_MAX +#define LOG_MAX (256 * 1024) +#endif +#ifndef LOG_RATE +#define LOG_RATE (256 * 1024) +#endif +#ifndef LOG_WINDOW +#define LOG_WINDOW 60 +#endif +#define MOD_NICE 10 /* mods' services: nice 10 and the lowest best-effort I/O priority, unless the mod asks for normal */ #ifndef SH #define SH "/system/bin/sh" #endif @@ -168,6 +185,8 @@ static long clock_sec(int clk) #define x_setresuid(a, b, c) S3(208, a, b, c) #define x_setresgid(a, b, c) S3(210, a, b, c) #define x_chown(p, u, g) S3(212, p, u, g) +#define x_setpriority(w, who, v) S3(97, w, who, v) /* EABI 97 */ +#define x_ioprio_set(w, who, v) S3(314, w, who, v) /* EABI 314 */ #define x_fchmod(fd, m) S2(94, fd, m) #define x_fchown(fd, u, g) S3(207, fd, u, g) /* fchown32 */ #define MS_BIND 4096 @@ -642,10 +661,18 @@ 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"))) { - say(fd, "usage: engine plan | apply [--trial] [--force] | keep | restore | status | recover | install | remove " + || seq(sub, "map-car") || seq(sub, "report") || seq(sub, "problem") || seq(sub, "nemesis-sync") + || seq(sub, "boot-guard") || seq(sub, "safe") + || seq(sub, "catalog") || seq(sub, "catalog-plan") || seq(sub, "catalog-install") || seq(sub, "updates") + || seq(sub, "update") || seq(sub, "update-check") || seq(sub, "update-source"))) { + say(fd, "usage: engine plan | apply [--trial] [--force] [--gear-unknown-ok] | keep | restore | status | recover | install | remove " + " | safe [on | off]" " | 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]" + " | catalog [--refresh] | catalog-plan ... [--update] | catalog-install ... [--any-car[=,...]]" + " [--any-author=,...] | updates [--refresh] | update ... | --all | hmgapi [--force] | update-check" + " | update-source catalogue | releases | off | default\n"); return 2; } a[n++] = APP_PROCESS; @@ -959,12 +986,17 @@ static int op_binds(int fd) * ROOTDIR/state/services.status what runs now: * ROOTDIR/state/ctl/ requests from ops (workers are forked: they can't touch this * table): "restart|stop|start " - * ROOTDIR/logs//.log its output (256 KB, then .1) + * ROOTDIR/logs//.log its output, through a pipe the daemon reads: LOG_MAX, + * then .1, while it runs; more than LOG_RATE in LOG_WINDOW s is left out (one line says so) * ROOTDIR/run/// its own folder (HMGAPI_DATA, ANDROID_DATA for its * dalvik-cache), owned by its user + * ROOTDIR/state/service-priority.txt " normal": runs at normal priority; every + * other mod's service gets nice MOD_NICE and the lowest best-effort I/O class * A mod turned off is dropped from services.txt by the engine: stopped here (TERM, * then KILL after 5 s); turned on: started. A service that keeps exiting within a - * minute is started again after 1, 2, 4 ... 300 s, and given up after 10 tries. */ + * minute is started again after 1, 2, 4 ... 300 s, and given up after 10 tries. + * Safe mode (SAFEFILE): only HMG-API's own lines count, so every mod's service stops, + * boot-start ones included. */ #define MAX_SVC 32 #define SVC_LINE 512 #define SVC_FIELDS 24 @@ -974,11 +1006,14 @@ struct svc { char line[SVC_LINE], buf[SVC_LINE]; char *f[SVC_FIELDS + 1]; int nf, state, fails, gone, stopping; + int outfd, logfd; /* its output pipe (read end) and log, -1 when closed */ sl pid; long next, started, kill_at; + long logsize, win_start, win_bytes; + unsigned long long dropped; /* left out in this window */ }; static struct svc svcs[MAX_SVC]; -static int nsvc, android_up, status_dirty; +static int nsvc, android_up, status_dirty, safe_mode; static long last_android_check; static char svc_text[16384], apps_synced[8192]; static int apps_sync_pending = 1; @@ -1041,6 +1076,116 @@ static void svc_log(const char *what, struct svc *v, sl n) logline(what, l.b, n, 0); } +/* ---- a service's log, written here from its output pipe */ +static void svc_logpath(struct svc *v, char *p, ul cap) +{ + path3(p, cap, ROOTDIR "/logs/", v->f[0], "/"); + path3(p, cap, p, v->f[1], ".log"); +} + +static void svc_log_open(struct svc *v, int fresh) +{ + char p[256], old[260]; + unsigned long long st[16]; + long long big = 0; + svc_logpath(v, p, sizeof p); + if (!fresh) { + /* far past the cap: grown before logs were capped while running (one release's looping + * service: 885 MB in 8 s). Emptied, not kept as .1, so /data gets the room back now. */ + path3(old, sizeof old, p, ".1", ""); + if (x_stat64(old, st) == 0 && (long long)st[6] > 2LL * LOG_MAX) x_unlink(old); + if (x_stat64(p, st) == 0 && (long long)st[6] > 2LL * LOG_MAX) { big = (long long)st[6]; fresh = 1; } + } + v->logfd = (int)x_open(p, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC | (fresh ? O_TRUNC : 0), 0600); + v->logsize = 0; + if (v->logfd >= 0 && !fresh && x_stat64(p, st) == 0) v->logsize = (long)st[6]; /* st_size at 48 */ + if (v->logfd >= 0 && big) { + line_t l; l.n = 0; l.b[0] = 0; + lput(&l, "[hmgapid] this log was "); lnum(&l, (sl)(big >> 20)); lput(&l, " MB: emptied\n"); + if (wall(v->logfd, l.b, l.n) == 0) v->logsize = (long)l.n; + } +} + +/* into the log, never past LOG_MAX: a full log becomes .1 (the old .1 goes) */ +static void svc_log_put(struct svc *v, const char *b, ul n) +{ + while (n > 0) { + ul k; + if (v->logfd < 0) svc_log_open(v, 0); + if (v->logfd < 0) return; + if (v->logsize >= LOG_MAX) { + char p[256], old[260]; + svc_logpath(v, p, sizeof p); + path3(old, sizeof old, p, ".1", ""); + x_close(v->logfd); + x_rename(p, old); + svc_log_open(v, 1); + continue; + } + k = (ul)(LOG_MAX - v->logsize); + if (k > n) k = n; + if (wall(v->logfd, b, k)) return; + v->logsize += (long)k; + b += k; + n -= k; + } +} + +/* a new window: say how much the last one left out */ +static void svc_log_window(struct svc *v, long now, int force) +{ + if (!force && now - v->win_start < LOG_WINDOW) return; + if (v->dropped) { + line_t l; l.n = 0; l.b[0] = 0; + lput(&l, "[hmgapid] "); lnum(&l, (sl)((v->dropped + 1023) / 1024)); lput(&l, " KB of output left out\n"); + svc_log_put(v, l.b, l.n); + svc_log("service output left out (KB)", v, (sl)((v->dropped + 1023) / 1024)); + } + v->win_start = now; + v->win_bytes = 0; + v->dropped = 0; +} + +static void svc_log_out(struct svc *v, const char *b, ul n, long now) +{ + svc_log_window(v, now, 0); + if (!v->dropped && v->win_bytes < LOG_RATE) { /* what fits in this window's budget */ + ul room = (ul)(LOG_RATE - v->win_bytes), k = n < room ? n : room; + v->win_bytes += (long)k; + svc_log_put(v, b, k); + b += k; + n -= k; + } + if (n == 0) return; + if (!v->dropped) { + line_t l; l.n = 0; l.b[0] = 0; + lput(&l, "\n[hmgapid] more than "); lnum(&l, LOG_RATE / 1024); lput(&l, " KB of output in "); lnum(&l, LOG_WINDOW); + lput(&l, " s: the rest is left out until the next "); lnum(&l, LOG_WINDOW); lput(&l, " s\n"); + svc_log_put(v, l.b, l.n); + } + v->dropped += n; +} + +static void svc_out_close(struct svc *v, long now) +{ + if (v->outfd >= 0) x_close(v->outfd); + v->outfd = -1; + svc_log_window(v, now, 1); + if (v->logfd >= 0) x_close(v->logfd); + v->logfd = -1; +} + +/* its pipe is readable: what's there into the log; at EOF (it and everything it started + * have closed it) the pipe and the log are closed */ +static void svc_read(struct svc *v, long now) +{ + static char b[65536]; + sl n = x_read(v->outfd, b, sizeof b); + if (n == -EINTR || n == -11 /* EAGAIN */) return; + if (n <= 0) { svc_out_close(v, now); return; } + svc_log_out(v, b, (ul)n, now); +} + static void write_status(void) { static char st[8192]; @@ -1120,14 +1265,26 @@ static int svc_gid(const char *mod, int uid) return MOD_GID; } +/* a service's nice value: HMG-API's own 0; a mod's MOD_NICE unless the engine's + * state/service-priority.txt has " normal" (its mod.json asked) */ +static int svc_nice(const char *mod, const char *name) +{ + static char b[4096]; + char want[96]; + if (seq(mod, "hmgapi")) return 0; + path3(want, sizeof want, mod, " ", name); + path3(want, sizeof want, want, " normal", ""); + if (read_small(ROOTDIR "/state/service-priority.txt", b, sizeof b) < 0) return MOD_NICE; + return has_line(b, want) ? 0 : MOD_NICE; +} + static void svc_start(struct svc *v, long now) { - char path[256], dir[256], data[256], cache[256], logp[256], old[260], envb[6][300]; + char path[256], dir[256], data[256], cache[256], logp[256], envb[6][300]; static char *envp[110]; char *argv[SVC_FIELDS + 6]; u32 gids[20]; - int ng, uid, egid, ne = 0, na = 0, i, go[2]; - unsigned long long st[16]; + int ng, uid, egid, ne = 0, na = 0, i, go[2], op[2], nice; sl pid, lf; const char *mod = v->f[0], *name = v->f[1], *kind = v->f[5], *rel = v->f[6], *cls = v->f[7]; uid = svc_user(v->f[2], gids, &ng); @@ -1154,11 +1311,12 @@ static void svc_start(struct svc *v, long now) mkdir_owned(logp, 0700, -1, -1); path3(logp, sizeof logp, logp, "/", name); path3(logp, sizeof logp, logp, ".log", ""); - if (x_stat64(logp, st) == 0 && (long long)st[6] > 256 * 1024) { /* st_size at 48 */ - path3(old, sizeof old, logp, ".1", ""); - x_rename(logp, old); - } - lf = x_open(logp, O_WRONLY | O_CREAT | O_APPEND, 0600); + if (v->outfd >= 0) svc_out_close(v, now); /* the last run's pipe, still held by something it started */ + /* its output through a pipe this daemon reads (svc_read: the log stays capped while it runs); + * no pipe: straight into the log, as before */ + if (x_pipe(op) < 0) { op[0] = -1; lf = x_open(logp, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0600); } + else lf = op[1]; + nice = svc_nice(mod, name); envp[ne++] = "PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"; envp[ne++] = "LD_LIBRARY_PATH=/vendor/lib:/system/lib"; @@ -1192,7 +1350,13 @@ static void svc_start(struct svc *v, long now) if (x_pipe(go) < 0) { go[0] = go[1] = -1; } pid = x_fork(); - if (pid < 0) { if (lf >= 0) x_close(lf); if (go[0] >= 0) { x_close(go[0]); x_close(go[1]); } v->next = now + 5; return; } + if (pid < 0) { + if (lf >= 0) x_close(lf); + if (op[0] >= 0) x_close(op[0]); + if (go[0] >= 0) { x_close(go[0]); x_close(go[1]); } + v->next = now + 5; + return; + } if (pid == 0) { sl nul = x_open("/dev/null", O_RDONLY, 0); char c; @@ -1204,6 +1368,11 @@ static void svc_start(struct svc *v, long now) } if (nul >= 0) x_dup2(nul, 0); if (lf >= 0) { x_dup2(lf, 1); x_dup2(lf, 2); } + for (i = 3; i < 1024; i++) x_close(i); /* only 0-2: not the other services' pipes, nor the daemon's socket */ + if (nice) { /* lower first: a mod's loop must not starve the car's own processes */ + x_setpriority(0 /* PRIO_PROCESS */, 0, nice); + x_ioprio_set(1 /* IOPRIO_WHO_PROCESS */, 0, (2 << 13) | 7); /* best effort, level 7; errors ignored */ + } x_chdir(data); if (x_geteuid() == 0) { /* off-car tests run unprivileged: no switch */ /* A mod's service runs with MOD_GID or HOME_GID as its effective group (svc_gid): the @@ -1218,6 +1387,10 @@ static void svc_start(struct svc *v, long now) x_exit(127); } if (lf >= 0) x_close(lf); + v->outfd = op[0]; + v->win_start = now; + v->win_bytes = 0; + v->dropped = 0; v->pid = pid; v->state = S_RUN; v->started = now; @@ -1300,6 +1473,19 @@ static void svc_reload(long now) char *p; int i; if (read_small(ROOTDIR "/state/services.txt", want, sizeof want) < 0) want[0] = 0; + if (safe_mode) { /* HMG-API's own lines only */ + static char kept[16384]; + kept[0] = 0; + for (p = want; *p; ) { + char *e = p; + ul n; + while (*e && *e != '\n') e++; + n = (ul)(e - p); + if (n && n < SVC_LINE && spre(p, "hmgapi ")) { mcpy(line, p, n); line[n] = 0; apnd(kept, sizeof kept, line); } + p = *e ? e + 1 : e; + } + mcpy(want, kept, slen(kept) + 1); + } if (seq(want, svc_text)) return; mcpy(svc_text, want, slen(want) + 1); for (i = 0; i < nsvc; i++) { /* no longer wanted (or changed): stop */ @@ -1321,6 +1507,7 @@ static void svc_reload(long now) if (!dup && nsvc < MAX_SVC) { struct svc *v = &svcs[nsvc]; mset(v, 0, sizeof *v); + v->outfd = v->logfd = -1; mcpy(v->line, line, n + 1); svc_parse(v); if (svc_valid(v) && !svc_find(v->f[0], v->f[1])) { @@ -1406,6 +1593,12 @@ static void svc_tick(void) logline("Android is up", 0, -1, 0); } } + if (exists(SAFEFILE) != safe_mode) { /* turned on or off (the engine, or the file by hand) */ + safe_mode = !safe_mode; + logline(safe_mode ? "safe mode on: mods' services stop" : "safe mode off: mods' services start", 0, -1, 0); + publish_state(); /* the engine writes the state for it: apps, network rules, the public state */ + apps_sync_pending = 1; /* mods' apps off (or on again) once Android is up */ + } svc_reload(now); svc_ctl(now); /* the mods' apps, when the list changes (or first after Android is up) */ @@ -1420,7 +1613,14 @@ static void svc_tick(void) for (i = 0; i < nsvc; i++) { struct svc *v = &svcs[i]; if (v->pid > 0 && v->kill_at && now >= v->kill_at) { x_kill(-v->pid, SIGKILL); x_kill(v->pid, SIGKILL); v->kill_at = 0; } + if (v->outfd >= 0) svc_log_window(v, now, 0); /* what a quiet minute left out gets said */ if (v->gone && v->pid == 0) { /* drop it */ + if (v->outfd >= 0) { /* what's in its pipe first */ + struct { int fd; short ev, rev; } q = { v->outfd, POLLIN, 0 }; + int k; + for (k = 0; k < 16 && v->outfd >= 0 && x_poll(&q, 1, 0) > 0; k++) svc_read(v, now); + } + svc_out_close(v, now); --nsvc; if (i != nsvc) mcpy(&svcs[i], &svcs[nsvc], sizeof svcs[i]); svc_parse(&svcs[i]); /* field pointers point into its own buf: rebuild after the copy */ @@ -1570,6 +1770,52 @@ static int op_vehicle(int fd, const char *mod, int argc, char **argv) return n < 0 ? 1 : 0; } +/* The gear, for a restart (as hmgapi.engine.Gear): 1 in P, 0 not in P, -1 no reading (the + vehicle service isn't up yet, or the car didn't answer: "-"). */ +static int gear_park(void) +{ + static char buf[256]; + static const char req[] = "read gear.park\n"; + struct sun a; + int alen = sockaddr_of(&a, VEHICLE_SOCK); + sl s, n; + ul got = 0; + struct { sl sec, usec; } tv = { 3, 0 }; + s = x_socket(1, 1 | 02000000, 0); + if (s < 0) return -1; + x_setsockopt((int)s, 1 /* SOL_SOCKET */, 20 /* SO_RCVTIMEO */, &tv, sizeof tv); + if (x_connect(s, &a, alen) < 0 || wall((int)s, req, sizeof req - 1)) { x_close(s); return -1; } + while (got < sizeof buf - 1 && (n = x_read((int)s, buf + got, sizeof buf - 1 - got)) > 0) { + got += (ul)n; + if (buf[got - 1] == '\n') break; /* one line; the service's close may not reach us (#145) */ + } + x_close(s); + buf[got] = 0; + if (seq(buf, "gear.park 1\n")) return 1; + if (seq(buf, "gear.park 0\n")) return 0; + return -1; +} + +/* A restart only in P: it takes the reverse camera's picture away for about a minute (Android + shows it on these units), and a driver may be about to reverse. Not in P: refused (75), no + override. No reading: refused (76) unless the caller says to go on, after asking the owner + (the HMG-API app) or deciding it can't (boot.sh waits instead). */ +static int op_reboot(int fd, int unknown_ok) +{ + char *a[] = { REBOOT, 0 }; + int g = gear_park(); + if (g == 0) { + say(fd, "not restarting: the car isn't in P (a restart takes the reverse camera's picture away for about a minute). Shift to P first.\n"); + return 75; + } + if (g < 0 && !unknown_ok) { + say(fd, "not restarting: the gear can't be read, so hmgapid can't check that the car is in P. With the car in P: reboot --gear-unknown-ok\n"); + return 76; + } + say(fd, "restarting\n"); + return run(fd, a); +} + /* A vehicle command (hmgapi.engine.Vehicle.COMMANDS) through HMG-API's vehicle service, which applies its guard. A mod only the ones it declared (state/commands.txt: " "); mod 0 (root, HMG-API's app): any, as "-". */ @@ -1644,7 +1890,7 @@ static int op_micom_watch(int fd, int argc, char **argv) path3(want, sizeof want, want, i > 1 ? " " : "", argv[i]); } if (write_small(ROOTDIR "/state/micom-watch.txt", want) < 0) { say(fd, "can't save it\n"); return 1; } - publish_state(); // the vehicle service runs while the watch is on + publish_state(); // the vehicle service (always running) picks the watch up say(fd, want); say(fd, "\n"); return 0; @@ -1718,8 +1964,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; } @@ -1830,11 +2078,8 @@ static int handle(int fd, int whoami, int argc, char **argv) if (seq(op, "park-rule") && argc <= 2) return op_park_rule(fd, argc, argv); if (seq(op, "micom-watch") && argc <= 9) return op_micom_watch(fd, argc, argv); if (seq(op, "micom-log") && argc == 1) return op_svc_log(fd, "hmgapi", "micom"); - if (seq(op, "reboot") && argc == 1) { - char *a[] = { REBOOT, 0 }; - say(fd, "restarting\n"); - return run(fd, a); - } + if (seq(op, "reboot") && argc == 1) return op_reboot(fd, 0); + if (seq(op, "reboot") && argc == 2 && seq(argv[1], "--gear-unknown-ok")) return op_reboot(fd, 1); if (whoami != WHO_ROOT) { say(fd, "not allowed\n"); return 13; } if (seq(op, "whoami") && argc == 1) { say(fd, g_mod[0] ? g_mod : "root"); say(fd, "\n"); return 0; } @@ -1969,7 +2214,9 @@ static int daemon_main(void) x_close(ready[0]); for (;;) { - struct { int fd; short ev, rev; } p = { (int)s, POLLIN, 0 }; + static struct { int fd; short ev, rev; } p[MAX_SVC + 1]; + static int of[MAX_SVC + 1]; + int np = 1, i; sl c; for (;;) { /* children: services and op workers */ int st = 0; @@ -1978,7 +2225,16 @@ static int daemon_main(void) if (!svc_exited(k, st, x_time()) && workers > 0) workers--; } svc_tick(); - if (x_poll(&p, 1, 1000) <= 0) continue; + /* the socket, and every service's output pipe */ + p[0].fd = (int)s; p[0].ev = POLLIN; p[0].rev = 0; + for (i = 0; i < nsvc; i++) { + if (svcs[i].outfd < 0) continue; + p[np].fd = svcs[i].outfd; p[np].ev = POLLIN; p[np].rev = 0; + of[np++] = i; + } + if (x_poll(p, np, 1000) <= 0) continue; + for (i = 1; i < np; i++) if (p[i].rev) svc_read(&svcs[of[i]], x_time()); + if (!(p[0].rev & POLLIN)) continue; c = x_accept(s); if (c < 0) continue; if (workers >= MAX_WORKERS) { done((int)c, 75); x_close(c); continue; } /* busy */ @@ -2118,7 +2374,7 @@ int main(int argc, char **argv, char **envp) if (argc < 2) { out(2, "usage: hmgapid daemon | hmgapid boot | hmgapid [args...]\n" "ops: ping, version, mods, enable , disable , setting-get ,\n" - " setting-set , mod-file mod.json|settings.json, log, reboot, engine ,\n" + " setting-set , mod-file mod.json|settings.json, log, reboot [--gear-unknown-ok], engine ,\n" " services [mod], service-restart|service-stop|service-start , service-log ,\n" " usb [mod], sh , remount rw|ro, binds\n" "a mod's own app: whoami, setting-get, setting-set , services, service-restart|stop|start ,\n" diff --git a/core/hmgapid/test.sh b/core/hmgapid/test.sh index 4a237744..1f131f86 100755 --- a/core/hmgapid/test.sh +++ b/core/hmgapid/test.sh @@ -18,7 +18,7 @@ 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; } -# build +# build [more -D flags] build() { mkdir -p "$T/$1/root/mods" printf '%s\n' "$3" > "$T/$1/packages.list" @@ -28,7 +28,7 @@ build() { chmod +x "$T/$1/logcat" "$T/$1/app_process" "$T/$1/getprop" OUT="$T/$1" sh build.sh -DNOCAPCHECK -DROOTDIR="\"$T/$1/root\"" -DSH="\"/bin/sh\"" -DLOGCAT="\"$T/$1/logcat\"" \ -DREBOOT="\"/bin/true\"" -DAPP_PROCESS="\"$T/$1/app_process\"" -DPACKAGES_LIST="\"$T/$1/packages.list\"" -DGETPROP="\"$T/$1/getprop\"" -DUSBROOT="\"$T/$1/usb\"" -DBOOTMARK="\"$T/$1/bootmark\"" -DSOCK_NAME="\"hmgapid-test-$1-$$\"" -DVEHICLE_SOCK="\"hmgapi-vehicle-test-$$\"" \ - -DSHELL_UID="$2" >/dev/null + -DSHELL_UID="$2" $4 >/dev/null } run() { b=$1; shift; "$T/$b/hmgapid" "$@" 2>&1; } code() { b=$1; shift; set +e; "$T/$b/hmgapid" "$@" >/dev/null 2>&1; c=$?; set -e; echo $c; } @@ -115,6 +115,7 @@ has "log runs logcat" "fake logcat -d -v time -s HMG-API:V" "$(run root log)" check "unknown op" "2" "$(code root frobnicate)" check "engine runs app_process" "app_process /system/bin hmgapi.engine.Engine apply --trial CLASSPATH=/system/framework/hmgapi-hook.jar ROOT=/system KEEP=yes PRELOAD=none" "$(run root engine apply --trial)" check "engine refuses other subcommands" "2" "$(code root engine rm -rf)" +has "engine safe: passed to the engine" "hmgapi.engine.Engine safe on" "$(run root engine safe on)" check "root dir mode (traverse only for apps)" "drwx--x--x" "$(ls -ld "$T/root/root" | cut -c1-10)" has "log file" "(root) disable -> 0" "$(cat "$T/root/root/hmgapid.log")" @@ -123,8 +124,13 @@ check "app: mods" "0" "$(code app mods)" check "app: setting-set" "0" "$(code app setting-set x '{}')" check "app: sh refused" "13" "$(code app sh 'echo no')" check "app: remount refused" "13" "$(code app remount rw)" -check "app: reboot allowed" "0" "$(code app reboot)" +# a restart only in P (op_reboot): no vehicle service here, so no gear reading +check "app: reboot with no gear reading refused" "76" "$(code app reboot)" +has "... and says how to go on" "reboot --gear-unknown-ok" "$(run app reboot)" +check "app: reboot --gear-unknown-ok allowed" "0" "$(code app reboot --gear-unknown-ok)" +check "app: reboot with another argument refused (not an op it may use)" "13" "$(code app reboot --now)" check "app: engine allowed" "0" "$(code app engine status)" +check "app: safe mode switch allowed" "0" "$(code app engine safe off)" # --- anyone else check "other: ping" "ok" "$(run other ping)" @@ -230,6 +236,74 @@ check "app may list services" 0 "$(code app services)" check "other may not" 13 "$(code other services)" check "bad names refused" 2 "$(code root service-restart ../x loop)" +# --- service logs while the service runs, priority, safe mode: a daemon of its own with small +# limits (a looping echo under hmgapid wrote 885 MB in 8 s when the log was only checked at start) +build logs "$ME" "" "-DLOG_MAX=16384 -DLOG_RATE=16384 -DLOG_WINDOW=3" # rate = cap, as on the unit +L=$T/logs/root +mkdir -p "$L/mods/spam/bin" "$L/state" +printf 'while :; do echo 0123456789012345678901234567890123456789; done\n' > "$L/mods/spam/bin/spam.sh" +printf 'i=0; while [ $i -lt 100 ]; do echo line $i; i=$((i+1)); done; exec '"$SLEEP"' 60\n' > "$L/mods/spam/bin/quiet.sh" +printf 'i=0; while [ $i -lt 1000 ]; do echo 0123456789012345678901234567890123456789; i=$((i+1)); done; exec '"$SLEEP"' 60\n' > "$L/mods/spam/bin/burst.sh" +printf 'exec '"$SLEEP"' 60\n' > "$L/state/net.sh" +printf 'spam quiet normal\n' > "$L/state/service-priority.txt" +cat > "$L/state/services.txt" < "$L/logs/spam/quiet.log"; head -c 3145728 /dev/zero > "$L/logs/spam/quiet.log.1" +lst() { run logs services "$1" | awk -v n="$2" '$2 == n { print $3 }'; } +lpid() { run logs services "$1" | awk -v n="$2" '$2 == n { print $4 }'; } +nice_of() { [ -n "$1" ] && awk '{ print $19 }' "/proc/$1/stat" 2>/dev/null; } +check "logs daemon starts" "hmgapid: started" "$(KEEPME=yes LD_PRELOAD= "$T/logs/hmgapid" daemon)" +waitfor '[ "$(lst spam spam)" = running ]' || true +sleep 4 +check "a service logging in a loop keeps running" running "$(lst spam spam)" +size=$(cat "$L/logs/spam/spam.log" "$L/logs/spam/spam.log.1" 2>/dev/null | wc -c | tr -d ' ') +check "... its log stays capped while it runs (log + .1)" yes "$([ "$size" -gt 0 ] && [ "$size" -le $((2 * 16384 + 512)) ] && echo yes || echo "no ($size bytes)")" +check "... rotated to .1" yes "$([ -s "$L/logs/spam/spam.log.1" ] && echo yes || echo no)" +# a burst (40 KB at once, then quiet): what's left out is said, and how much once its window ends +has "a burst: says what it leaves out" "the rest is left out until the next 3 s" "$(cat "$L/logs/spam/burst.log" 2>/dev/null)" +waitfor 'grep -q "KB of output left out" "$L/logs/spam/burst.log"' || true +has "... and how much, once the window ends" "KB of output left out" "$(cat "$L/logs/spam/burst.log" 2>/dev/null)" +check "... still running" running "$(lst spam burst)" +has "... in hmgapid's log too" "service output left out (KB)" "$(cat "$L/hmgapid.log")" +has "a quiet service's log is whole" "line 99" "$(run logs service-log spam quiet)" +has "... an old oversized log emptied, saying so" "[hmgapid] this log was 3 MB: emptied" "$(head -1 "$L/logs/spam/quiet.log")" +check "... and its oversized .1 gone" no "$([ -e "$L/logs/spam/quiet.log.1" ] && echo yes || echo no)" +check "a mod's service: nice 10" 10 "$(nice_of "$(lpid spam spam)")" +check "... unless it asked for normal" 0 "$(nice_of "$(lpid spam quiet)")" +check "HMG-API's own: normal" 0 "$(nice_of "$(lpid hmgapi net)")" +# safe mode: the file (as `engine safe on` writes it, or by hand) +spid=$(lpid spam spam) +echo owner > "$L/SAFE" +waitfor '[ -z "$(lst spam spam)" ]' || true +check "safe mode: a mod's service stops" "" "$(lst spam spam)$(lst spam burst)" +check "... all of them" "" "$(lst spam quiet)" +check "... its processes end" no "$(kill -0 "$spid" 2>/dev/null && echo yes || echo no)" +check "... HMG-API's own keep running" running "$(lst hmgapi net)" +has "... logged" "safe mode on" "$(cat "$L/hmgapid.log")" +waitfor 'grep -q publish-state "$T/logs/engine.log"' || true +has "... the engine publishes the state for it" "hmgapi.engine.Engine publish-state" "$(cat "$T/logs/engine.log" 2>/dev/null)" +printf 'spam late root boot yes script bin/quiet.sh -\n' >> "$L/state/services.txt" +sleep 2 +check "... a new boot-start service doesn't start" "" "$(lst spam late)" +pkill -f "$T/logs/" 2>/dev/null || true +sleep 1 +check "a daemon started in safe mode" "hmgapid: started" "$(KEEPME=yes LD_PRELOAD= "$T/logs/hmgapid" daemon)" +waitfor '[ "$(lst hmgapi net)" = running ]' || true +sleep 1 +check "... starts no mod's boot service" "" "$(run logs services spam)" +check "... but HMG-API's own" running "$(lst hmgapi net)" +rm "$L/SAFE" +waitfor '[ "$(lst spam late)" = running ]' || true +check "safe mode off: mods' services start again" "running running" "$(lst spam late) $(lst spam quiet)" +has "... logged" "safe mode off" "$(cat "$L/hmgapid.log")" +pkill -f "$T/logs/" 2>/dev/null || true + # --- a mod's own app (its uid is an app an enabled mod declared) check "mod app: whoami" demo "$(run mod whoami)" check "mod app: own settings" 0 "$(code mod setting-set '{"x": 2}')" @@ -246,18 +320,19 @@ cp "$T/mod/root/state/usb.txt" "$S/state/usb.txt" check "root: every mod's" "demo /storage/usb1/Dashcam other /storage/usb0/Other" "$(run root usb | sort | tr '\n' ' ' | sed 's/ $//')" # --- vehicle readings: relayed to HMG-API's vehicle service, only what the mod declared check "vehicle: service not running" 69 "$(code root vehicle speed)" -python3 - "hmgapi-vehicle-test-$$" "$T/vehicle.req" <<'PY' & -import socket, sys +python3 - "hmgapi-vehicle-test-$$" "$T/vehicle.req" "$T/gear" <<'PY' & +import os, socket, sys s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.bind("\0" + sys.argv[1]); s.listen(4); s.settimeout(30) held = [] -for _ in range(6): +for _ in range(9): try: c, _ = s.accept() except socket.timeout: break line = c.makefile().readline() open(sys.argv[2], "a").write(line) if line.startswith("do "): c.sendall(("ok %s\n" % line.strip()).encode()); c.close(); continue - c.sendall("".join("%s 42\n" % n for n in line.split()[1:]).encode()) + gear = open(sys.argv[3]).read().strip() if os.path.exists(sys.argv[3]) else "42" + c.sendall("".join("%s %s\n" % (n, gear if n == "gear.park" else "42") for n in line.split()[1:]).encode()) if "speed.held" in line: held.append(c); continue # the car's service: its close never reached hmgapid (#145) c.close() PY @@ -271,6 +346,12 @@ check "vehicle: bad name refused" 2 "$(code mod vehicle 'speed;x')" check "vehicle: root reads any" "hv.soc 42" "$(run root vehicle hv.soc)" check "vehicle: a whole answer with the connection left open is still ok (#145)" "0 speed.held 42" "$(set +e; o=$(run root vehicle speed.held); echo "$? $o")" check "vehicle: other app refused" 13 "$(code other vehicle speed)" +# the restart's gear check, through the same service +echo 1 > "$T/gear" +check "reboot: in P, restarts" "0 restarting" "$(set +e; o=$(run app reboot); echo "$? $o")" +echo 0 > "$T/gear" +check "reboot: not in P, refused" 75 "$(code app reboot)" +check "reboot: not in P, refused even with the override" 75 "$(code app reboot --gear-unknown-ok)" printf 'demo charge_door\n' > "$T/mod/root/state/commands.txt" check "vehicle-do: a declared command passed on with the mod" "ok do demo charge_door open" "$(run mod vehicle-do charge_door open)" check "vehicle-do: undeclared refused" 13 "$(code mod vehicle-do wheel_heat on)" @@ -306,7 +387,7 @@ check "park-rule: a mod's app can't" 13 "$(code mod park-rule closed)" check "park-rule: the HMG-API app can" closed "$(run app park-rule closed)" check "park-rule: back to door" door "$(run root park-rule door)" kill $VP 2>/dev/null || true; wait $VP 2>/dev/null || true -check "vehicle: nothing reached the service for refused asks" 5 "$(wc -l < "$T/vehicle.req" | tr -d ' ')" +check "vehicle: nothing reached the service for refused asks (5, and the 3 restarts' gear)" 8 "$(wc -l < "$T/vehicle.req" | tr -d ' ')" : > "$T/mod/root/state/apps.txt" check "mod turned off: its app is anyone again" 13 "$(code mod whoami)" diff --git a/core/loader/loader.c b/core/loader/loader.c index 8ac40f56..7fa29679 100644 --- a/core/loader/loader.c +++ b/core/loader/loader.c @@ -62,10 +62,12 @@ int cacheflush(long start, long end, long flags); /* ---- Dalvik 4.4 layouts (offsets checked on the EV6 libdvm) ---- */ #define ACC_STATIC 0x0008 #define ACC_NATIVE 0x0100 +#define M_CLASS(m) (*(void **)(m)) #define M_ACCESS(m) (*(u4 *)((char *)(m) + 0x04)) #define M_REGS(m) (*(u2 *)((char *)(m) + 0x0a)) #define M_OUTS(m) (*(u2 *)((char *)(m) + 0x0c)) #define M_INS(m) (*(u2 *)((char *)(m) + 0x0e)) +#define M_NAME(m) (*(const char **)((char *)(m) + 0x10)) #define M_SHORTY(m) (*(const char **)((char *)(m) + 0x1c)) #define M_INSNS(m) (*(void **)((char *)(m) + 0x20)) #define M_NATIVE(m) (*(void **)((char *)(m) + 0x28)) @@ -74,6 +76,8 @@ int cacheflush(long start, long end, long flags); #define CLASS_PRIM(c) (*(int *)((char *)(c) + 0x44)) #define PRIM_NOT 0 #define PRIM_VOID 1 +#define PRIM_INT 6 +#define ARRAY_LEN(a) (*(u4 *)((char *)(a) + 0x08)) #define ARRAY_DATA(a) ((void **)((char *)(a) + 0x10)) typedef union { int i; long long j; float f; double d; void *l; } JValue; @@ -313,6 +317,47 @@ static int failed(JNIEnv *env, const char *what) return 1; } +static int streq(const char *a, const char *b) +{ + if (!a || !b) return 0; + while (*a && *a == *b) a++, b++; + return *a == *b; +} + +/* + * The offsets above are the EV6 libdvm's (AOSP 4.4), with no check that this unit's libdvm is + * that build. A libdvm laid out otherwise would have the hooks write the wrong words of every + * hooked Method: in the zygote the boot guard catches the crash, but in an app it would crash + * as each one starts, which nothing catches. So before the first hook, the layout is read back + * from Bridge's own methods, which libdvm found by name, where nothing can be wrong but the + * offsets: the declaring class, name, shorty, flags and argument count of each, the 0x28 + * nativeFunc that dvmSetNativeFunc (libdvm's own code) just wrote, the primitive type of int, + * void and Bridge, and an array's length. 0, with the reason logged: no hooks. + */ +static const char *layout_bad(void *bc, void *orig, void *handle, void *self) +{ + void *a; + u4 len; + if (M_CLASS(handle) != bc || M_CLASS(orig) != bc) return "Method.clazz (0x00)"; + if (!streq(M_NAME(handle), "handleHookedMethod") || !streq(M_NAME(orig), "invokeOriginalMethodNative")) + return "Method.name (0x10)"; + /* (Member, int, Object, Object, Object[]) Object; (Member, int, Class[], Class, Object, Object[]) Object */ + if (!streq(M_SHORTY(handle), "LLILLL") || !streq(M_SHORTY(orig), "LLILLLL")) return "Method.shorty (0x1c)"; + if ((M_ACCESS(handle) & (ACC_STATIC | ACC_NATIVE)) != ACC_STATIC + || (M_ACCESS(orig) & (ACC_STATIC | ACC_NATIVE)) != (ACC_STATIC | ACC_NATIVE)) return "Method.accessFlags (0x04)"; + if (M_INS(handle) != 5 || M_INS(orig) != 6 || M_REGS(handle) < M_INS(handle)) return "Method.insSize/registersSize (0x0a, 0x0e)"; + if (!M_INSNS(handle)) return "Method.insns (0x20)"; + if (M_NATIVE(orig) != (void *)invokeOriginal) return "Method.nativeFunc (0x28)"; + if (CLASS_PRIM(dvm.findPrim('I')) != PRIM_INT || CLASS_PRIM(dvm.findPrim('V')) != PRIM_VOID || CLASS_PRIM(bc) != PRIM_NOT) + return "ClassObject.primitiveType (0x44)"; + a = dvm.allocArray(gObjectArrayClass, 3, 0); + if (!a) return "an Object[3] (no memory)"; + len = ARRAY_LEN(a); + dvm.release(a, self); + if (len != 3) return "ArrayObject.length (0x08)"; + return 0; +} + static int load_dvm(void) { void *h = dlopen("libdvm.so", 0); @@ -359,6 +404,14 @@ static void start_bridge(JNIEnv *env, const char *jar, const char *entry) gObjectArrayClass = dvm.findArrayClass("[Ljava/lang/Object;", 0); if (!m || !gHandleHooked || !gObjectArrayClass) { LOGE("init: bridge methods not found"); return; } dvm.setNativeFunc(m, invokeOriginal, 0); + { + const char *bad = layout_bad(bc, m, gHandleHooked, self); + if (bad) { + /* Bridge.init never runs, so nothing is hooked: the unit runs stock */ + LOGE("init: this libdvm's layout isn't the one HMG-API was built for (%s doesn't match), so hooks are off. Please send this line to the HMG-API maintainers with your car and its head unit software version", bad); + return; + } + } m = GetStaticMethodID(env, bridge, entry, "()V"); if (failed(env, entry) || !m) return; diff --git a/core/runtime/catalog-test.sh b/core/runtime/catalog-test.sh new file mode 100644 index 00000000..0cd1e554 --- /dev/null +++ b/core/runtime/catalog-test.sh @@ -0,0 +1,701 @@ +#!/bin/sh +# Off-car test of the catalogue and updates (Catalog): the catalogue fetched (index.json, or GitHub's +# folder listing; a bad index, an entry that doesn't come), what each mod would do here, dependencies +# (requires installed first, a required mod that's off turned on, requires only the zip names and +# a second OK for them, loops, conflicts either way, the result as a whole, unreadable ranges, what +# isn't in the catalogue), trust (a first install's key must be on the unit's list, or the owner's yes +# per mod), every download checked before the first install (SHA-256, the zip being what the entry +# says, the author key), the owner's any-car choice per mod, updates (mods and HMG-API's own release, +# its pre-releases, mods it would leave behind), the automatic check (every 6 hours, staging only pure +# updates aside until apply), mods outside the catalogue updated from their own GitHub releases (by +# the installed key only; SHA-256 when given; withdrawn versions; the owner's choice of source; the +# API limit), and a removal's warning. +# GitHub is played by files (HMGAPI_TEST_WEB: NativeFetch.Web). +set -e +cd "$(dirname "$0")/../.." +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 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"; } +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 mod zip, served from a release (through GitHub's +# redirect to its asset host), and its catalogue entry (extras for the entry: $ENTRY; its author key: $EUUID, else the trusted one) +pkg() { + rm -rf $T/m; mkdir -p $T/m + 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" "${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 + (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 zip requires more than its entry says (an older entry): learned, installed first +pkg helper 1.0.0 +pkg extra 1.0.0 ', "requires": ["helper"]'; listing +eng catalog --refresh +eng catalog-install extra +check "install extra: the plan the owner saw missed a step, so stopped for a second OK" 5 $rc +has "... said why" "the mod zips require more than the catalogue says" "$out" +check "... the new plan handed back" "helper install extra|extra install None" "$(j '"|".join(s["id"]+" "+s["action"]+" "+str(s.get("for")) for s in d["steps"])')" +check "... nothing installed" "none none" "$(installed helper) $(installed extra)" +eng catalog-plan extra +check "... the next plan has it (learned from the zip)" "helper extra" "$(j '" ".join(s["id"] for s in d["steps"])')" +eng catalog-install extra +check "install extra again" 0 $rc +has "... helper, which only the zip names, installed" "installing helper 1.0.0 (extra needs it)" "$out" +check "... both" "1.0.0 1.0.0" "$(installed helper) $(installed extra)" + +# ---- what can't be met: nothing installed +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" "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 +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 +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)" +check "... its record gone: the apply is final" no "$([ -f $D/state/staged-swap.json ] && echo yes || echo no)" + +# staged updates are part of the apply: a cut-off apply or an undone trial puts them back, like the /system files +pkg helper 1.2.0; listing; eng catalog --refresh +GAP=0 eng update-check +check "helper 1.2.0 staged" 1.2.0 "$(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +# cut off between moving 1.1.0 aside and putting 1.2.0 in: only the record and previous/ are there +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +eng apply +check "an apply cut off in its staged updates: the next one waits for recover" 1 $rc +eng recover +check "... recover: the old version back, the update staged again" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +check "... its record gone" no "$([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +# cut off after both moves, before the journal was written (the apply was still planning) +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +eng recover +check "cut off before its journal: recover puts the old version back" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +has "... and says so (boot.sh restarts on it)" "rolled back the staged update of helper" "$out" +# a trial that's undone: its journal and the staged update's record go back together +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": True, "committed": True, "entries": [], "state": st}, open(os.path.join(d, "journal.json"), "w")) +J +eng keep +check "a trial kept: the staged update stays in" "0 1.2.0 no" "$rc $(installed helper) $([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +rm -rf "$D/mods/helper"; mv "$D/previous/helper" "$D/mods/helper"; pkg helper 1.2.0; listing; eng catalog --refresh; GAP=0 eng update-check +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper"; echo '{"ids": ["helper"]}' > "$D/state/staged-swap.json" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": True, "committed": True, "entries": [], "state": st}, open(os.path.join(d, "journal.json"), "w")) +J +eng recover +check "a trial undone: the staged update goes back with it" "1.1.0 1.2.0 no" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])") $([ -f $D/state/staged-swap.json ] && echo yes || echo no)" +has "... trial undone" "trial undone" "$out" +# from the journal on, it carries the staged updates (no record of their own): cut off mid-apply +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper" +python3 - "$D/state" <<'J' +import json, os, sys +d = sys.argv[1]; st = json.load(open(os.path.join(d, "files.json"))) if os.path.exists(os.path.join(d, "files.json")) else {"files": {}, "settings": {}} +json.dump({"trial": False, "committed": False, "entries": [], "state": st, "staged": ["helper"]}, open(os.path.join(d, "journal.json"), "w")) +J +eng recover +check "cut off mid-apply, the staged update only on the journal: recover puts it back" "1.1.0 1.2.0" "$(installed helper) $(python3 -c "import json; print(json.load(open('$D/pending/helper/mod.json'))['version'])")" +has "... says so" "rolled back the staged update of helper" "$out" +# the journal deleted (the apply is final): nothing left to put back, even before the run's own clean-up +rm -rf "$D/previous/helper"; mv "$D/mods/helper" "$D/previous/helper"; mv "$D/pending/helper" "$D/mods/helper" +eng recover +check "an apply that finished (no journal, no record): recover leaves the update in" "nothing to recover 1.2.0" "$out $(installed helper)" +mv "$D/mods/helper" "$D/pending/helper"; mv "$D/previous/helper" "$D/mods/helper" + +# withdrawn after it was staged: dropped at the apply, not put in +echo '{"withdrawn": [{"id": "helper", "versions": "1.2.0", "why": "breaks the cluster"}]}' > "$CAT/withdrawn.json" +eng catalog --refresh +eng apply +check "a staged update withdrawn since: not put in" "0 1.1.0 no" "$rc $(installed helper) $([ -d $D/pending/helper ] && echo yes || echo no)" +has "... said why" "dropped the staged helper 1.2.0: HMG-API's maintainers withdrew it since (breaks the cluster)" "$out" +rm "$CAT/withdrawn.json"; pkg helper 1.1.0; listing; eng catalog --refresh +rm "$D/settings/allow/auto_stage_updates" + +# ---- HMG-API's own release +cat > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" <<'J' +[{"tag_name": "v9.0.0", "draft": true, "prerelease": false, "assets": []}, + {"tag_name": "v1.1.0", "draft": false, "prerelease": false, "html_url": "https://github.com/Open-HMG/HMG-API/releases/tag/v1.1.0", "body": "What's new in 1.1.0", + "assets": [{"name": "hmgapi-1.1.0-update.zip", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/hmgapi-1.1.0-update.zip"}, + {"name": "SHA256SUMS", "browser_download_url": "https://github.com/Open-HMG/HMG-API/releases/download/v1.1.0/SHA256SUMS"}]}, + {"tag_name": "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"]')" +check "... with its release notes, for the app" "What's new in 1.1.0" "$(j 'd["hmgapi"]["notes"]')" +eng update hmgapi +has "a release that isn't its SHA256SUMS: refused" "refused HMG-API 1.1.0: the download's SHA-256 is" "$out" +echo '[{"tag_name": "v1.0.2", "draft": false, "prerelease": false, "assets": []}]' > "$W/api.github.com/repos/Open-HMG/HMG-API/releases_per_page=15" +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 mod zip checked before the first one goes in +pkg dep 1.0.0 +ENTRY=', "requires": ["dep"]'; pkg top 1.0.0 ', "requires": ["dep"]' $T/other.key +listing; eng catalog --refresh +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")) +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" +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" +rm "$W/raw.githubusercontent.com.down" + +# ---- mods outside the catalogue: updates from their own GitHub releases (mod.json "repo") +rm -f "$CAT/index.json"; listing +# rpkg [key]: a signed mod zip as a release asset; sets $ZSHA, $ZSIZE +rpkg() { + rm -rf $T/m; mkdir -p $T/m + printf '{"id": "%s", "name": "%s mod", "version": "%s", "hmgapi": ">=1.0.0", "repo": "https://github.com/%s"%s}\n' "$2" "$2" "$3" "$1" "$4" > $T/m/mod.json + sig sign $T/m ${5:-$T/author.key} > /dev/null + z=$W/objects.githubusercontent.com/r/$1/$2-$3.zip; mkdir -p "$(dirname "$z")" "$W/github.com/$1/releases/download/v$3" + (cd $T/m && rm -f "$z" && zip -q -r -X "$z" .) + echo "https://objects.githubusercontent.com/r/$1/$2-$3.zip" > "$W/github.com/$1/releases/download/v$3/$2-$3.zip.redirect" + ZSHA=$(python3 -c "import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest())" "$z") + ZSIZE=$(wc -c < "$z" | tr -d ' ') +} +# rel : one release's JSON +rel() { printf '{"tag_name": "%s", "draft": false, "prerelease": %s, "html_url": "https://github.com/%s/releases/tag/%s", "body": "notes for %s", "assets": [%s]}' "$2" "$3" "$1" "$2" "$2" "$4"; } +asset() { printf '{"name": "%s", "browser_download_url": "https://github.com/%s/releases/download/%s/%s", "size": %s%s}' "$3" "$1" "$2" "$3" "$4" "$5"; } +releases() { r=$1; shift; mkdir -p "$W/api.github.com/repos/$r"; (IFS=,; echo "[$*]") > "$W/api.github.com/repos/$r/releases_per_page=10"; } +u() { printf '%s' "$out" | python3 -c "import json,sys; t=sys.stdin.read(); d=json.loads(t[t.index('{'):]); m=[x for x in d['mods'] if x['id']==sys.argv[1]]; print(eval(sys.argv[2]) if m else None)" "$1" "$2"; } + +rpkg dev/side side 1.0.0 '' +eng install $W/objects.githubusercontent.com/r/dev/side/side-1.0.0.zip +check "an unlisted mod with a repo, installed by hand" 1.0.0 "$(installed side)" +rpkg dev/side side 1.1.0 ''; S11=$ZSHA; A11=$(asset dev/side v1.1.0 side-1.1.0.zip $ZSIZE ", \"digest\": \"sha256:$ZSHA\"") +rpkg dev/side side 1.2.0-beta.1 ''; A12=$(asset dev/side v1.2.0-beta.1 side-1.2.0-beta.1.zip $ZSIZE '') +releases dev/side "$(printf '{"tag_name": "v2.0.0", "draft": true, "prerelease": false, "assets": []}')" "$(rel dev/side v1.2.0-beta.1 true "$A12")" \ + "$(rel dev/side v1.1.0 false "$A11,$(asset dev/side v1.1.0 other-1.1.0.zip 10 '')")" "$(rel dev/side v0.9.0 false '')" +: > $W/requests.log +eng updates --refresh +check "its releases: the newest final, not the draft or the beta" 1.1.0 "$(u side 'm[0]["version"]')" +check "... said where from" "release https://github.com/dev/side" "$(u side 'm[0]["source"]+" "+m[0]["repo"]')" +check "... with the release's notes" "notes for v1.1.0" "$(u side 'm[0]["notes"]')" +check "... its source: releases" releases "$(j 'd["sources"]["side"]["source"]')" +check "... one API call for its repo" 1 "$(grep -c 'api.github.com/repos/dev/side/releases?per_page=10' $W/requests.log)" +hasnt "... none for mods with no repo" "repos/test/" "$(cat $W/requests.log)" +check "... the release's SHA-256 kept (its digest)" "$S11" "$(python3 -c "import json,sys; print([m for m in json.load(open(sys.argv[1]))['mods'] if m['id']=='side'][0]['sha256'])" $D/catalog/releases.json)" +eng catalog +hasnt "... not in the Catalogue tab" '"side"' "$out" +eng update side +check "update from its release" 0 $rc +has "... checked against the release's SHA-256" "downloaded side 1.1.0 from its release (SHA-256 as the release's)" "$out" +check "... installed" 1.1.0 "$(installed side)" + +# a release whose zip isn't what its digest says; one with no SHA-256 at all (the signature decides) +rpkg dev/side side 1.3.0 '' +releases dev/side "$(rel dev/side v1.3.0 false "$(asset dev/side v1.3.0 side-1.3.0.zip $ZSIZE ", \"digest\": \"sha256:$(printf '%064d' 0)\"")")" +eng updates --refresh +eng update side +check "a digest that doesn't match: refused" 1 $rc +has "... why" "the download's SHA-256 is $ZSHA, its release says" "$out" +releases dev/side "$(rel dev/side v1.3.0 false "$(asset dev/side v1.3.0 side-1.3.0.zip $ZSIZE '')")" +eng updates --refresh +eng update side +check "no SHA-256 given: the signature decides" "0 1.3.0" "$rc $(installed side)" +has "... said so" "no SHA-256 given: its signature decides" "$out" + +# SHA256SUMS in the release, a zip by another key (as a key change), a zip that isn't the tag's version +rpkg dev/side side 1.4.0 '' $T/other.key +printf '%s side-1.4.0.zip\n' "$ZSHA" > "$W/github.com/dev/side/releases/download/v1.4.0/SHA256SUMS" +releases dev/side "$(rel dev/side v1.4.0 false "$(asset dev/side v1.4.0 side-1.4.0.zip $ZSIZE ''),$(asset dev/side v1.4.0 SHA256SUMS 80 '')")" +eng updates --refresh +check "SHA256SUMS: its SHA-256 used" "$ZSHA" "$(python3 -c "import json,sys; print([m for m in json.load(open(sys.argv[1]))['mods'] if m['id']=='side'][0]['sha256'])" $D/catalog/releases.json)" +eng update side +check "a release by another author key (a key change): refused" "3 1.3.0" "$rc $(installed side)" +has "... why" "signed by a different author (uuid $O, installed mod has $U)" "$out" +rpkg dev/side side 1.6.0 '' +mkdir -p $W/github.com/dev/side/releases/download/v1.5.0; mv $W/github.com/dev/side/releases/download/v1.6.0/side-1.6.0.zip.redirect $W/github.com/dev/side/releases/download/v1.5.0/side-1.5.0.zip.redirect +releases dev/side "$(rel dev/side v1.5.0 false "$(asset dev/side v1.5.0 side-1.5.0.zip $ZSIZE '')")" +eng updates --refresh +eng update side +check "a zip that isn't the release's version: refused" 1 $rc +has "... why" "the zip is side 1.6.0" "$out" + +# too large, no matching zip, a download from elsewhere: not offered, with a note +releases dev/side "$(rel dev/side v1.7.0 false "$(asset dev/side v1.7.0 side-1.7.0.zip 99999999999 '')")" +eng catalog --refresh +has "a zip larger than HMG-API takes: noted" "side 1.7.0: its zip is 99999999999 bytes" "$(j '" ".join(d.get("notes", []))')" +releases dev/side "$(rel dev/side v1.7.0 false "$(asset dev/side v1.7.0 notes.txt 10 '')")" +eng catalog --refresh +has "no zip for it: noted" "side 1.7.0: its release has no side-....zip asset" "$(j '" ".join(d.get("notes", []))')" +releases dev/side "$(rel dev/side v1.7.0 false '{"name": "side-1.7.0.zip", "browser_download_url": "https://example.com/side-1.7.0.zip", "size": 10}')" +eng updates --refresh +check "a zip from outside its repo's releases: not offered" None "$(u side 'm[0]["version"]')" + +# withdrawn by a maintainer: skipped for the newest one that isn't +rpkg dev/side side 1.7.0 ''; A17=$(asset dev/side v1.7.0 side-1.7.0.zip $ZSIZE '') +rpkg dev/side side 1.8.0 ''; A18=$(asset dev/side v1.8.0 side-1.8.0.zip $ZSIZE '') +releases dev/side "$(rel dev/side v1.8.0 false "$A18")" "$(rel dev/side v1.7.0 false "$A17")" +echo '{"withdrawn": [{"id": "side", "versions": ">=1.8.0", "why": "breaks the camera"}, {"id": "base", "versions": "2.0.0", "why": "test"}]}' > "$CAT/withdrawn.json" +listing +eng catalog --refresh +hasnt "withdrawn.json isn't taken for an entry" "withdrawn: left out" "$out" +eng updates +check "a withdrawn release: the one before it offered" 1.7.0 "$(u side 'm[0]["version"]')" +check "... an installed version that's withdrawn: said" "base 2.0.0 test" "$(j '" ".join(w["id"]+" "+w["version"]+" "+w["why"] for w in d.get("withdrawn", []))')" +eng catalog +check "... and in the Catalogue tab" test "$(j '[m for m in d["mods"] if m["id"]=="base"][0].get("withdrawn")')" +rm "$CAT/withdrawn.json"; listing + +# staged by the automatic check, like a catalogue update +: > "$D/settings/allow/auto_stage_updates" +GAP=0 eng update-check +has "staged from its release" "staged: side 1.3.0 -> 1.8.0" "$(cat $D/logs/hmgapi/updates.log)" +check "... in pending/" 1.8.0 "$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['version'])" $D/pending/side/mod.json)" +rm -rf "$D/pending/side" "$D/settings/allow/auto_stage_updates" + +# the owner's choice: off, then back; a listed mod from its releases instead +eng update-source side off +has "updates off" "side: updates from nowhere" "$out" +eng updates +check "... not offered" None "$(u side 'm[0]["version"]')" +eng update side +has "... updating it says why not" "side's updates are turned off" "$out" +eng update-source side default +has "... default again: its releases" "side: updates from dev/side's releases" "$out" +eng update-source base releases +check "releases for a mod with no repo: refused" 1 $rc +has "... why" "names no GitHub repo" "$out" +eng update-source side catalogue +has "the catalogue for a mod it doesn't list: refused" "side isn't in the catalogue" "$out" +eng update-source nosuch off +has "a mod that isn't installed: refused" "nosuch isn't installed" "$out" +ENTRY=; pkg both 1.0.0 ', "repo": "https://github.com/dev/both"'; listing +eng catalog --refresh +eng catalog-install both +check "a listed mod with a repo" 1.0.0 "$(installed both)" +rpkg dev/both both 1.1.0 ''; releases dev/both "$(rel dev/both v1.1.0 false "$(asset dev/both v1.1.0 both-1.1.0.zip $ZSIZE '')")" +: > $W/requests.log +eng updates --refresh +check "... from the catalogue: no update, its releases not asked" "None 0" "$(u both 'm[0]["version"]') $(grep -c 'repos/dev/both' $W/requests.log || true)" +eng update-source both releases +eng updates --refresh +check "... its releases, chosen: offered" "1.1.0 release" "$(u both 'm[0]["version"]+" "+m[0]["source"]')" +eng update-source both default + +# a beta tester stays on that mod's betas +rpkg dev/beta beta 2.0.0-beta.1 '' +eng install $W/objects.githubusercontent.com/r/dev/beta/beta-2.0.0-beta.1.zip +rpkg dev/beta beta 2.0.0-beta.2 ''; releases dev/beta "$(rel dev/beta v2.0.0-beta.2 true "$(asset dev/beta v2.0.0-beta.2 beta-2.0.0-beta.2.zip $ZSIZE '')")" +eng updates --refresh +check "a beta installed: its next beta offered" 2.0.0-beta.2 "$(u beta 'm[0]["version"]')" + +# a repo moved to another owner (GitHub's API follows it): its downloads are the new repo's +rm -rf "$W/objects.githubusercontent.com/r/org"; mkdir -p "$W/objects.githubusercontent.com/r/org/beta" "$W/github.com/org/beta/releases/download/v2.0.0-beta.3" +rpkg dev/beta beta 2.0.0-beta.3 '' +mv $W/github.com/dev/beta/releases/download/v2.0.0-beta.3/beta-2.0.0-beta.3.zip.redirect $W/github.com/org/beta/releases/download/v2.0.0-beta.3/ +releases dev/beta "$(rel org/beta v2.0.0-beta.3 true "$(asset org/beta v2.0.0-beta.3 beta-2.0.0-beta.3.zip $ZSIZE '')")" +eng updates --refresh +check "a moved repo: offered, from where it is now" "2.0.0-beta.3 https://github.com/org/beta" "$(u beta 'm[0]["version"]+" "+m[0]["repo"]')" +releases dev/beta "$(rel dev/beta v2.0.0-beta.3 true "$(asset org/beta v2.0.0-beta.3 beta-2.0.0-beta.3.zip $ZSIZE '')")" +eng updates --refresh +check "... a download from another repo than its release's: not offered" None "$(u beta 'm[0]["version"]')" +releases dev/beta "$(rel dev/beta v2.0.0-beta.2 true "$(asset dev/beta v2.0.0-beta.2 beta-2.0.0-beta.2.zip 100 '')")" +eng updates --refresh + +# GitHub's API limit: said, the last answer kept +echo 403 > "$W/api.github.com/repos/dev/beta/releases_per_page=10.status" +echo 403 > "$W/api.github.com/repos/dev/side/releases_per_page=10.status" +eng catalog --refresh +has "the API limit: said" "GitHub's API limit (60 an hour) is reached" "$(j '" ".join(d.get("notes", []))')" +eng updates +check "... the last answers kept" "2.0.0-beta.2 1.8.0" "$(u beta 'm[0]["version"]') $(u side 'm[0]["version"]')" +rm "$W/api.github.com/repos/dev/beta/releases_per_page=10.status" "$W/api.github.com/repos/dev/side/releases_per_page=10.status" +eng remove beta; eng remove side; eng remove both + +# ---- removing a mod others require: warned +eng remove base +has "a removal others need: warned" "app requires base: it won't load until base is installed again" "$out" + +[ $fail = 0 ] && echo "all catalogue checks passed" +exit $fail diff --git a/core/runtime/engine-test.sh b/core/runtime/engine-test.sh index 89634abd..bd0b3ea9 100644 --- a/core/runtime/engine-test.sh +++ b/core/runtime/engine-test.sh @@ -136,6 +136,53 @@ check "disable modb" 0 $rc check "library without modb" "$(md5 $T/lib.a)" "$(md5 $R/system/lib/libtest.so)" check "modb's prop gone" "" "$(grep persist.modb $R/system/build.prop || true)" +# ---- only in P (Gear): a change to /system starts only with the car in P; no reading: the owner's go-ahead +printf '#!/bin/sh\n[ "$*" = "vehicle gear.park" ] || exit 0\ncat "%s/gear.out"\ncase "$(cat "%s/gear.out")" in gear.park*) exit 0 ;; esac\nexit 69\n' "$T" "$T" > $T/hmgapid +chmod +x $T/hmgapid +export HMGAPI_HMGAPID=$T/hmgapid +rm $R/data/hmgapi/mods/modb/.disabled +LIB_NOW=$(md5 $R/system/lib/libtest.so) +echo "gear.park 0" > $T/gear.out +eng apply +check "not in P: apply refused" 75 $rc +has "... saying why" "refused: the car isn't in P, and the apply only starts in P" "$out" +check "... nothing changed" "$LIB_NOW" "$(md5 $R/system/lib/libtest.so)" +check "... no journal" no "$([ -e $R/data/hmgapi/state/journal.json ] && echo yes || echo no)" +eng apply --gear-unknown-ok +check "not in P: refused even with the override" 75 $rc +eng plan +check "a plan needs no P" 0 $rc +echo "the vehicle service isn't running (yet)" > $T/gear.out +eng apply +check "no gear reading: apply refused" 76 $rc +has "... naming the owner's go-ahead" "then go on anyway (--gear-unknown-ok)" "$out" +check "... nothing changed" "$LIB_NOW" "$(md5 $R/system/lib/libtest.so)" +echo "gear.park -" > $T/gear.out +eng apply +check "the car didn't answer: refused the same" 76 $rc +eng apply --gear-unknown-ok +check "no gear reading, with the owner's go-ahead: applied" 0 $rc +has "... with the warning" "warning: the gear can't be read on this car" "$out" +check "... modb back in" "$(md5 $T/lib.ab)" "$(md5 $R/system/lib/libtest.so)" +touch $R/data/hmgapi/mods/modb/.disabled +echo "gear.park 1" > $T/gear.out +eng apply +check "in P: applied" 0 $rc +has "... the owner told to stay in P" "keep the car in P until the apply is done" "$out" +check "... modb out again" "$(md5 $T/lib.a)" "$(md5 $R/system/lib/libtest.so)" +echo "gear.park 0" > $T/gear.out +eng apply +check "nothing to change on /system: no gear needed" "0" "$rc" +# apps an apply stopped while their files changed (pm disable lasts across restarts): an apply +# cut off before it let them go leaves the list; recover keeps it while Android isn't up, for +# boot.sh's release-held (the held-apps checks further down start them with a package manager) +printf 'dev.example.gpm\ndev.example.dipo\n' > $R/data/hmgapi/state/held.txt +eng recover +has "recover: the apps a cut-off apply stopped, Android not up: left for boot.sh" "start again once Android is up (boot.sh: engine release-held)" "$out" +check "... still listed" "dev.example.gpm dev.example.dipo" "$(echo $(cat $R/data/hmgapi/state/held.txt))" +rm -f $R/data/hmgapi/state/held.txt +unset HMGAPI_HMGAPID + # ---- trial: undone by recover, or kept echo '{"extra": true}' > $R/data/hmgapi/settings/moda.json BP_BEFORE=$(md5 $R/system/build.prop) @@ -433,4 +480,167 @@ 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) +# netd and framework-res.apk are boot-critical (refused without the owner's override): these checks +# are about modes, owners and held apps on real paths, so the override lets them change +printf '{"overrides": {"allow_critical": ["/system/bin/netd", "/system/framework/framework-res.apk"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +# 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 +rm -f $R/data/hmgapi/settings/hmgapi.json exit $fail diff --git a/core/runtime/fetch-test.sh b/core/runtime/fetch-test.sh new file mode 100644 index 00000000..0356883f --- /dev/null +++ b/core/runtime/fetch-test.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Off-car test of the engine's HTTPS pieces (Http, NativeFetch.Web, Sha256, DnsLookup), then the +# library itself (core/fetch/fetch.c) built for this computer (-DHOST: no SO_MARK or wlan0 here) +# against a local TLS server, when there's a C compiler, the JDK's jni.h and an OpenSSL 1.1+/3 +# libssl (HMGAPI_TEST_SSL, or Homebrew's or the system's); skipped otherwise. +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 core/runtime/test/hmgapi/engine/FetchNativeTest.java 2>/dev/null +java -cp "$CP" hmgapi.engine.FetchTest + +JH=$(java -XshowSettings:properties -version 2>&1 | sed -n 's/^ *java.home = //p') +SSL=${HMGAPI_TEST_SSL:-} +for s in /opt/homebrew/opt/openssl@3/lib/libssl.dylib /usr/local/opt/openssl@3/lib/libssl.dylib /usr/lib/x86_64-linux-gnu/libssl.so.3 /usr/lib/aarch64-linux-gnu/libssl.so.3 /usr/lib64/libssl.so.3; do + [ -n "$SSL" ] || { [ -f "$s" ] && SSL=$s; } +done +case $(uname) in Darwin) OS=darwin EXT=dylib ;; *) OS=linux EXT=so ;; esac +if ! command -v cc >/dev/null || [ ! -f "$JH/include/jni.h" ] || [ -z "$SSL" ] || ! command -v keytool >/dev/null; then + echo "skip the library on this computer: needs cc, the JDK's jni.h, keytool and an OpenSSL 1.1+/3 libssl (HMGAPI_TEST_SSL)" + exit 0 +fi +cc -DHOST -shared -fPIC -Wall -Werror -I"$JH/include" -I"$JH/include/$OS" -o "$CP/libhmgapi_fetch.$EXT" core/fetch/fetch.c +keytool -genkeypair -alias t -keyalg EC -groupname secp256r1 -dname CN=localhost -validity 2 -storetype PKCS12 \ + -keystore "$CP/ks.p12" -storepass fetchtest -keypass fetchtest >/dev/null 2>&1 +java -cp "$CP" hmgapi.engine.FetchNativeTest "$CP/libhmgapi_fetch.$EXT" "$SSL" "$CP/ks.p12" fetchtest diff --git a/core/runtime/homewifi-test.sh b/core/runtime/homewifi-test.sh index a7e7d4ea..f4feb423 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 @@ -83,6 +87,8 @@ 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 +[ "$op $c" = "-F HMGAPI_HOMELO" ] && [ -n "$LOCALNET_FILE" ] && { cat "$LOCALNET_FILE" 2>/dev/null || echo none; } >> "$FW/lo-at-flush" 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 @@ -104,17 +110,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; else grep -- " table ${3:-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.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|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 @@ -140,14 +159,23 @@ 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 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: by the mark, and by owner without it" "-o rmnet+ -m mark --mark 0x2951 -j DROP +-o rmnet+ -m owner --gid-owner 2951 -j DROP +-o rmnet+ -m owner --uid-owner 10071 -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")" @@ -155,27 +183,37 @@ 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 DROPs again" 3 "$(grep -c DROP "$F/fw/4/mangle/HMGAPI_HOMECELL")" +ipt -t mangle -D HMGAPI_HOMECELL -o rmnet+ -m owner --uid-owner 10071 -j DROP # one owner DROP gone +has "an owner DROP gone: put back" "mods' cellular block put back" "$(keeper once)" +has "... it's there again" "--uid-owner 10071 -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')" 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)" +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 # ---- 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' @@ -209,6 +247,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" + [ -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" @@ -255,7 +296,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 +311,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" +# 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)" @@ -288,6 +352,10 @@ 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")" +has "... after wifi.json says up (the engine reads it to know it's online)" '"state": "up"' "$(cat "$X/data/hmgapi/wifi/update-check.pub")" +mkdir -p "$X/proc/sys/net/ipv4/conf/wlan0"; wk >/dev/null +check "... not again while still up" 1 "$(grep -c . "$X/data/hmgapi/wifi/update-check.test")" check "status: up, signal, channel, no network name" '{"state": "up", "rssi": -61, "freq": 2437}' "$(pub)" 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")" @@ -297,6 +365,38 @@ 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")" +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)" +export LOCALNET_FILE=$X/proc/sys/net/ipv4/conf/wlan0/route_localnet; : > "$F/fw/lo-at-flush" +was=$(cat "$F/fw/props/dhcp.wlan0.dns1"); printf 10.10.10.101 > "$F/fw/props/dhcp.wlan0.dns1" +wk >/dev/null +check "a new DNS server: route_localnet off before the old guard is flushed (each flush)" "0 0" "$(echo $(cat "$F/fw/lo-at-flush"))" +check "... the guard for the new server, and route_localnet on behind it" "1 -s 10.10.10.101/32" "$(cat "$X/proc/sys/net/ipv4/conf/wlan0/route_localnet") $(grep -o -m1 -- '-s 10.10.10.101/32' "$F/fw/4/filter/HMGAPI_HOMELO")" +printf '%s' "$was" > "$F/fw/props/dhcp.wlan0.dns1"; wk >/dev/null; unset LOCALNET_FILE +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) @@ -311,7 +411,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 @@ -390,6 +492,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" @@ -399,7 +502,7 @@ eng publish-state check "publish with a projection ask runs" 0 $rc check "the keeper's asks: the projection AP for aa, no home Wi-Fi" "projection aa" "$(cat "$D/state/wifi.txt")" has "the keeper runs without home Wi-Fi, from boot" "hmgapi wifi root boot yes script /data/hmgapi/state/wifi.sh" "$(cat "$D/state/services.txt")" -hasnt "... no vehicle service for it" "hmgapi vehicle " "$(cat "$D/state/services.txt")" +has "... the vehicle service runs anyway (the gear check)" "hmgapi vehicle " "$(cat "$D/state/services.txt")" eng plan has "the plan: the projection AP" "wifi the projection AP up from boot, once each boot, unless a Wi-Fi client is on [aa]" "$out" has "the plan: the hotspot feature comes with it (the chip powered)" "com.hkmc.software.wifihotspot" "$out" diff --git a/core/runtime/hooks-test.sh b/core/runtime/hooks-test.sh index 7da24a9b..17a8fbec 100755 --- a/core/runtime/hooks-test.sh +++ b/core/runtime/hooks-test.sh @@ -1,6 +1,7 @@ #!/bin/sh # Off-car test of hook plans (hmgapi.engine.HookPlan through `engine plan`): load -# order, declared modes, and conflicts when two mods replace the same hook point. +# order, declared modes, and conflicts when two mods replace the same hook point; the +# safety functions no mod touches (hmgapi.engine.Protected) and the Car Report's account of them. # (The runtime guard and ordering are in the on-car self-test.) set -e cd "$(dirname "$0")/../.." @@ -63,6 +64,37 @@ rm $R/data/hmgapi/mods/wire/.disabled eng plan; hasnt "the first turned off: the other loads" "won't load" "$out" rm -r $R/data/hmgapi/mods/* +# safety functions (engine.Protected): the cameras, guide lines and telematics, no mod, built in +eng plan; has "plan lists the protected processes" "safety process com.hkmc.system.app.rearcamera: the rear camera, 360 view (AVM/SVM) and parking guide lines (no mod, built in)" "$out" +has "... and classes" "safety class com.hkmc.micom.PgsService: the camera and guide line service (system_server) (no mod, built in)" "$out" +mod lines '{"framework.pgs_service.request_guide_lines": "observe"}' +mod fine '{"launcher.menu_list.load": "observe"}' +eng plan; has "a mod declaring the guide line point won't load" "hooks lines won't load: hook point framework.pgs_service.request_guide_lines reaches the parking guide lines and cameras (use the vehicle commands guide_lines and rear_camera): a safety function, no mod hooks it (built in, no override)" "$out" +hasnt "... the other one loads" "fine won't load" "$out" +printf '{"overrides": {"ignore_system": ["lines"]}}\n' > $R/data/hmgapi/settings/hmgapi.json +eng plan; has "... no owner override changes that" "hooks lines won't load: hook point framework.pgs_service.request_guide_lines" "$out" +rm $R/data/hmgapi/settings/hmgapi.json +rm -r $R/data/hmgapi/mods/* +# the Car Report: what the runtime logged (a protected process started, a refused hook, an undeclared one) +mkdir -p $R/data/hmgapi/logs/hmgapi +cat > $R/data/hmgapi/logs/hmgapi/log.log <<'L' +11-27 10:00:01.000 I/HMG-API( 1163): protected: com.hkmc.system.app.rearcamera runs the rear camera, 360 view (AVM/SVM) and parking guide lines: no mod loads here, mods' hooks pass through, HMG-API adds nothing (built in, no override) +11-27 10:00:02.000 W/HMG-API( 624): protected: refused cam's hook on com.hkmc.micom.PgsService.requestGuideLineState in system_server: the camera and guide line service (system_server) is a safety function; no mod hooks it (built in, no override) +11-27 10:00:03.000 W/HMG-API( 2900): undeclared hook: egmp-aa-ev hooked X.shutdown in com.google.android.projection.sink directly, not through a hook point it declared in mod.json +11-27 10:05:03.000 W/HMG-API( 3100): undeclared hook: egmp-aa-ev hooked X.shutdown in com.google.android.projection.sink directly, not through a hook point it declared in mod.json +L +eng report; check "report" 0 $rc +has "report: the safety summary" "safety: 1 protected process(es) started with no mod, 1 mod hook(s) refused, 1 direct hook(s) outside declared points" "$out" +md=$(cat $R/data/hmgapi/public/reports/*.md) +has "report: protected processes seen" "Protected processes that started here, with no mod loaded: \`com.hkmc.system.app.rearcamera\`" "$md" +has "report: the refused hook" " - refused cam's hook on com.hkmc.micom.PgsService.requestGuideLineState in system_server" "$md" +has "report: the undeclared hook, once" "Direct hooks outside a mod's declared points: 1 + - egmp-aa-ev hooked X.shutdown in com.google.android.projection.sink directly" "$md" +has "report json: the rules" '"process com.hkmc.system.app.rearcamera: the rear camera' "$(cat $R/data/hmgapi/public/reports/*.json)" +rm -r $R/data/hmgapi/logs $R/data/hmgapi/public +javac --release 8 -Xlint:-options -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/ProtectedTest.java +java -cp "$CP" hmgapi.engine.ProtectedTest core/hookpoints || fail=1 + # the mod loader's own decisions (hook.Mods: boot and live loads), on a mods folder javac --release 8 -Xlint:-options -nowarn -cp "$CP" -d "$CP" core/runtime/test/hmgapi/engine/HookPlanTest.java mkdir -p $T/loader; java -cp "$CP" hmgapi.engine.HookPlanTest $T/loader || fail=1 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/Catalog.java b/core/runtime/java/hmgapi/engine/Catalog.java new file mode 100644 index 00000000..243532ba --- /dev/null +++ b/core/runtime/java/hmgapi/engine/Catalog.java @@ -0,0 +1,1739 @@ +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.HashSet; +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 ... [--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 [--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 + * engine update-source catalogue | releases | off | default + * where an installed mod's updates come from (the owner's choice) + * overrides, the owner's own choice, per mod: --any-car=,... (not listed for this head unit), + * --any-author=,... (a first install by an author key that isn't on this unit's trusted list); + * --any-car alone: every mod in the batch + * + * 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: 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. + * + * Mods outside the catalogue: their own GitHub releases (Releases), when their mod.json names the + * repo. Each installed mod has one update source (source()): the catalogue, its releases, or none. + * A maintainer can stop a version on both: catalog/withdrawn.json (withdrawn()). + * + * Dependencies: a mod's "requires" come from its entry (catalog.py copies them) and from the + * downloaded zip's mod.json (kept in learned.json, so the next plan has them); each is met by + * what's installed, or by the catalogue's version, installed first. A required mod that's turned off + * is turned on. After planning, every mod that will be on is checked against the result: its + * requires met, and no conflicts either way. When a mod zip requires more than the plan the owner + * saw, nothing is installed and the new plan is handed back (exit 5) for a second OK. + * + * The automatic check stages only pure updates (nothing else installed or turned on, signed with the + * 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, and one per repo of mods updated from their releases) */ + static final long CHECK_GAP_S = 6 * 3600; + /** catalog-install / update: the mod zips require more than the plan said; the new plan is in the output */ + static final int PLAN_CHANGED = 5; + static final String FROM_CATALOGUE = "catalogue", FROM_RELEASES = "releases", FROM_NONE = "off"; + + final Engine e; + final File dir, cacheFile, updatesFile, learnedFile; + 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"); + 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, all = false, update = "update".equals(cmd), force = false; + Overrides ov = new Overrides(); + for (int i = 1; i < args.length; 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: " + a); + 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 ("update-source".equals(cmd)) return c.setSource(args); + // planning and installing: the catalogue as it is now, when home Wi-Fi is up + String stale = null; + if (c.cache == null || (c.offline() == null && c.stale())) { + String err = c.refresh(); + 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(force); + } + if (update && all) { + for (Object o : (List) c.updates().get("mods")) ids.add(String.valueOf(((Map) o).get("id"))); + if (ids.isEmpty() && "update".equals(cmd)) { + e.out.add("every installed mod is up to date with the catalogue"); + return 0; + } + } + 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 = 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; + } + 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); + } + + 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 + + @SuppressWarnings("unchecked") + void load() { + try { + if (cacheFile.isFile()) cache = Json.object(Engine.read(cacheFile)); + } catch (Exception x) { + cache = null; // unreadable: fetched again + } + } + + /** 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() { + 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; + } + + /** hmgapi.json "catalog": {"prereleases": true}: every pre-release offered */ + @SuppressWarnings("unchecked") + boolean prereleases() { + Object c = e.hmgapi.get("catalog"); + 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() { + 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"; + } + } + + /** 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 { + 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(); + 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; + 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); + } 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; + 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; + String name = String.valueOf(((Map) o).get("name")); + if (!name.matches(ID + "\\.json") || "index.json".equals(name) || "withdrawn.json".equals(name)) continue; + if (mods.size() >= MAX_ENTRIES) break; + File ef = new File(tmp, name); + Http.Result er = http.get(base + name, ef, MAX_ENTRY); + 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"; + } + } + 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; + } + 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); + // what maintainers withdrew: a 404 is none; anything else keeps the last check's + File wf = new File(tmp, "withdrawn.json"); + Http.Result wr = http.get(base + "withdrawn.json", wf, MAX_JSON); + Object wd = null; + if (wr.ok()) { + try { + Object w = Json.parse(Engine.read(wf)); + wd = w instanceof Map ? ((Map) w).get("withdrawn") : w; + } catch (Exception x) { + wd = null; + } + if (!(wd instanceof List)) notes.add("the catalogue's withdrawn.json isn't a list: the last check's kept"); + } else if (wr.status == 404) { + wd = new ArrayList(); + } else { + notes.add("the catalogue's withdrawn.json: " + wr + " (the last check's kept)"); + } + if (!(wd instanceof List) && cache != null && cache.get("withdrawn") instanceof List) wd = cache.get("withdrawn"); + if (wd instanceof List) c.put("withdrawn", wd); + cache = c; // the new catalogue first: which mods it lists decides their source + Set listed = new HashSet(); + for (Object o : mods) listed.add(String.valueOf(((Map) o).get("id"))); + List fromReleases = new ArrayList(); + for (String id : installed().keySet()) { + Releases.Mod m = Releases.mod(e, id); + if (m != null && FROM_RELEASES.equals(source(id, m, listed))) fromReleases.add(m); + } + Releases.check(this, http, tmp, fromReleases, notes); + if (!notes.isEmpty()) c.put("notes", notes); + writeWhole(cacheFile, Json.write(c), false); + 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 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 { + 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()); + for (Object o : (List) list) { + if (!(o instanceof Map)) continue; + Map rel = (Map) o; + if (Boolean.TRUE.equals(rel.get("draft"))) continue; + String tag = String.valueOf(rel.get("tag_name")); + if (!tag.matches("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"); + 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"))); + String body = rel.get("body") instanceof String ? ((String) rel.get("body")).trim() : ""; // the release notes, for the app + if (body.length() > 6000) body = body.substring(0, 6000) + "\n…"; + if (!body.isEmpty()) best.put("notes", body); + else best.remove("notes"); + bv = v; + } + if (best == null) return null; + 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; + Object requires, conflicts; + } + + @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 { + Map j = Json.object(Engine.read(mj)); + Inst i = new Inst(); + 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 + } + } + return m; + } + + /** the catalogue's own entries, as listed (the Catalogue tab) */ + @SuppressWarnings("unchecked") + Map> listed() { + Map> m = new LinkedHashMap>(); + if (cache == null || !(cache.get("mods") instanceof List)) return m; + for (Object o : (List) cache.get("mods")) m.put(String.valueOf(((Map) o).get("id")), (Map) o); + return m; + } + + /** + * What planning and updates go by: the catalogue's entries, none that's withdrawn, with each mod whose + * update source is its releases taking its release entry instead (by the installed key; none if no + * newer release was found). + */ + Map> entries() { + Map> m = listed(); + for (String id : new ArrayList(m.keySet())) { + if (withdrawn(id, String.valueOf(m.get(id).get("version"))) != null) m.remove(id); + } + Map> rel = Releases.entries(this); + Set ids = listed().keySet(); + for (String id : installed().keySet()) { + Releases.Mod mod = Releases.mod(e, id); + if (mod == null || !FROM_RELEASES.equals(source(id, mod, ids))) continue; + m.remove(id); + Map en = rel.get(id); + if (en != null && mod.uuid != null && mod.uuid.equalsIgnoreCase(String.valueOf(en.get("uuid"))) + && withdrawn(id, String.valueOf(en.get("version"))) == null) m.put(id, en); + } + return m; + } + + /** why a maintainer withdrew id's version (catalog/withdrawn.json: [{"id", "versions": range, "why"}]), or null */ + @SuppressWarnings("unchecked") + String withdrawn(String id, String version) { + Object l = cache == null ? null : cache.get("withdrawn"); + for (Object o : l instanceof List ? (List) l : new ArrayList()) { + if (!(o instanceof Map)) continue; + Map w = (Map) o; + if (!id.equals(w.get("id"))) continue; + Object r = w.get("versions"); + if (r != null && !sat(version, String.valueOf(r))) continue; + return w.get("why") instanceof String ? (String) w.get("why") : "withdrawn by HMG-API's maintainers"; + } + return null; + } + + // ---- where each installed mod's updates come from + + /** the owner's choices: hmgapi.json "catalog": {"update_source": {"": "catalogue" | "releases" | "off"}} */ + @SuppressWarnings("unchecked") + Map choices() { + Object c = e.hmgapi.get("catalog"); + Object u = c instanceof Map ? ((Map) c).get("update_source") : null; + return u instanceof Map ? (Map) u : new LinkedHashMap(); + } + + /** + * id's update source: the owner's choice, else the catalogue when it lists the mod, else its releases + * when its mod.json names a GitHub repo, else none. A choice that can't be met (the catalogue for a + * mod it doesn't list, releases with no GitHub repo) is none. + */ + String source(String id, Releases.Mod m, Set listed) { + Object ch = choices().get(id); + String s = ch instanceof String ? (String) ch : listed.contains(id) ? FROM_CATALOGUE : FROM_RELEASES; + if (FROM_CATALOGUE.equals(s)) return listed.contains(id) ? FROM_CATALOGUE : FROM_NONE; + if (FROM_RELEASES.equals(s)) return m != null && m.repo != null ? FROM_RELEASES : FROM_NONE; + return FROM_NONE; + } + + /** each installed mod's update source, for the app: {id: {"source", "choice"?, "repo"?, "listed"}} */ + Map sources() { + Map out = new TreeMap(); + Set ids = listed().keySet(); + Map ch = choices(); + for (String id : installed().keySet()) { + Releases.Mod m = Releases.mod(e, id); + Map x = new LinkedHashMap(); + x.put("source", source(id, m, ids)); + if (ch.get(id) instanceof String) x.put("choice", ch.get(id)); + if (m != null && m.repo != null) x.put("repo", m.repo); + x.put("listed", ids.contains(id)); + out.put(id, x); + } + return out; + } + + /** engine update-source catalogue | releases | off | default: the owner's choice, kept in hmgapi.json */ + @SuppressWarnings("unchecked") + int setSource(String[] args) throws IOException { + if (args.length != 3 || !args[1].matches(ID) || !Arrays.asList(FROM_CATALOGUE, FROM_RELEASES, FROM_NONE, "default").contains(args[2])) { + e.out.add("usage: engine update-source catalogue | releases | off | default"); + return 2; + } + String id = args[1], to = args[2]; + Map inst = installed(); + if (!inst.containsKey(id)) { + e.out.add(id + " isn't installed"); + return 1; + } + Releases.Mod m = Releases.mod(e, id); + if (FROM_RELEASES.equals(to) && (m == null || m.repo == null)) { + e.out.add(id + "'s mod.json names no GitHub repo (\"repo\": \"https://github.com//\"), so it has no releases to check"); + return 1; + } + if (FROM_CATALOGUE.equals(to) && !listed().containsKey(id)) { + e.out.add(id + " isn't in the catalogue" + (cache == null ? " (it hasn't been checked yet)" : "")); + return 1; + } + Object c = e.hmgapi.get("catalog"); + Map cat = c instanceof Map ? (Map) c : new LinkedHashMap(); + Map ch = new TreeMap(choices()); + for (String k : new ArrayList(ch.keySet())) if (!inst.containsKey(k)) ch.remove(k); // removed mods' choices go + if ("default".equals(to)) ch.remove(id); + else ch.put(id, to); + if (ch.isEmpty()) cat.remove("update_source"); + else cat.put("update_source", ch); + e.hmgapi.put("catalog", cat); + File lj = new File(e.data, "settings/hmgapi.json"); + lj.getParentFile().mkdirs(); + Engine.write(lj, Json.write(e.hmgapi)); + String now = source(id, m, listed().keySet()); + e.out.add(id + ": updates from " + (FROM_CATALOGUE.equals(now) ? "the catalogue" : FROM_RELEASES.equals(now) ? m.repo + "'s releases" : "nowhere (not checked)") + + (FROM_RELEASES.equals(now) ? " (checked at the next refresh)" : "")); + if (cache != null) writeUpdates(); + return 0; + } + + /** a dependency list (requires or conflicts), optional ones left out (only NEMESIS's package builder honours them) */ + @SuppressWarnings("unchecked") + static List deps(Object list) { + 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; + } + + /** 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) { + 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, 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; + 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 : listed().values()) { + Map m = new LinkedHashMap(); + String id = String.valueOf(en.get("id")); + for (String k : new String[] {"id", "name", "version", "description", "authors", "license", "repo", "uuid"}) { + 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); + 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); + m.put("trusted", Packages.trustedAuthor(e, String.valueOf(en.get("uuid"))) != null); + String wd = withdrawn(id, String.valueOf(en.get("version"))); + if (wd != null) m.put("withdrawn", wd); + out.add(m); + } + rep.put("mods", out); + 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(); + Map src = sources(); + for (Map.Entry i : installed().entrySet()) { + Map en = cat.get(i.getKey()); + if (en == null || !"update".equals(status(i.getValue().version, String.valueOf(en.get("version"))))) continue; + Object s = src.get(i.getKey()); + if (s instanceof Map && FROM_NONE.equals(((Map) s).get("source"))) continue; // the owner turned its updates off + String unfit = unfit(en); + if (unfit != null && !unfit.startsWith("car: ")) continue; // not for this HMG-API: not offered + Map m = new LinkedHashMap(); + 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); + if (String.valueOf(en.get("version")).equals(stagedVersion(e, i.getKey()))) m.put("staged", true); + if ("release".equals(en.get("source"))) { // from the mod's own releases: said so, with its notes + m.put("source", "release"); + for (String k : new String[] {"repo", "page", "notes", "prerelease"}) if (en.get(k) != null) m.put(k, en.get(k)); + } + list.add(m); + } + List wd = new ArrayList(); // what's installed that a maintainer withdrew + for (Map.Entry i : installed().entrySet()) { + String why = withdrawn(i.getKey(), i.getValue().version); + if (why == null) continue; + Map w = new LinkedHashMap(); + w.put("id", i.getKey()); + w.put("version", i.getValue().version); + w.put("why", why); + wd.add(w); + } + if (!wd.isEmpty()) rep.put("withdrawn", wd); + rep.put("sources", src); + Map h = hmgapiOffer(); + if (h != null) rep.put("hmgapi", h); + } + 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)"); after any install or removal too */ + void writeUpdates() throws IOException { + String text = Json.write(updates()); + 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 zips 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 zip's requires and conflicts for its entry (this exact download); true if the plan didn't know one */ + @SuppressWarnings("unchecked") + boolean learn(Plan p, Step s, Map mj) throws IOException { + boolean more = false; + 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' zips 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) + + static final class Step { + final String id, action, version, installed, because; + final Map entry; + /** 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; + this.action = action; + this.version = version; + this.installed = installed; + 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(); + final Map learned = learned(); + final Set visiting = new LinkedHashSet(); + 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; + } + + /** a dependency list from an entry or a mod zip: an unreadable one (bad id or range) is a problem */ + List checked(Object list, String owner, String what, List into) { + for (Version.Dep d : deps(list)) { + String bad = !d.id.matches(ID) ? "\"" + d.id + "\" isn't a mod id" : d.range == null ? null : Version.rangeError(d.range); + 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; + 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)); + } + 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) { + Releases.Mod m = i == null ? null : Releases.mod(e, id); + String src = m == null ? null : source(id, m, listed().keySet()); + problem(FROM_RELEASES.equals(src) ? id + ": no newer release in " + m.repo + "'s releases (as last checked)" + : FROM_NONE.equals(src) && i != null && choices().get(id) != null ? id + "'s updates are turned off (update-source)" + : id + " isn't in the catalogue"); + return; + } + String st = status(i == null ? null : i.version, String.valueOf(en.get("version"))); + 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) { + problem(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) { + Inst i = inst.get(d.id); + Step p = planned(d.id); + 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; + } + 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) { + problem(who + " needs " + d + (i != null ? " (" + i.version + " is installed)" : "") + ", which isn't in the catalogue"); + return; + } + 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"))))) { + 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); + 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)) { + 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); + 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); + } + + /** + * 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 zips' + * 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) { + 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(); + 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.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, Overrides ov) { + Plan p = new Plan(ov); + p.update = update; + for (String id : ids) p.want(id, update); + 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 mod zip into dl, checks its SHA-256 and that it is what the entry says, unzips it; null, or why not */ + @SuppressWarnings("unchecked") + String fetch(Http http, File dl, Step s, Map> pkgs) throws Exception { + File z = new File(dl, s.id + "-" + s.version + ".zip"); + 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; + boolean rel = "release".equals(s.entry.get("source")); + String sha = Sha256.hex(z), want = s.entry.get("sha256") == null ? null : String.valueOf(s.entry.get("sha256")); + if (want == null && !rel) return "refused " + s.id + " " + s.version + ": its catalogue entry has no SHA-256"; + if (want != null && !sha.equals(want)) { + return "refused " + s.id + " " + s.version + ": the download's SHA-256 is " + sha + ", " + (rel ? "its release says " : "the catalogue says ") + want; + } + File u = new File(dl, s.id + "-" + s.version); + Map mj = null; + try { + 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 zip is " + (mj == null ? "not a mod" : mj.get("id") + " " + mj.get("version")); + } + pkgs.put(s.id, mj); + e.out.add("downloaded " + s.id + " " + s.version + (!rel ? " (SHA-256 as the catalogue's)" : want != null ? " from its release (SHA-256 as the release's)" + : " from its release (no SHA-256 given: its signature decides)")); + 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; + } + if (p.steps.isEmpty()) { + for (String n : p.notes) e.out.add(n); + e.out.add("nothing to install"); + return p.skipped.isEmpty() ? 0 : 1; + } + 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; + 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; + } + more |= learn(p, s, pkgs.get(s.id)); + } + // a mod zip can require more than its entry says (an entry from before catalog.py copied requires): + // its own mod.json is the truth. If that changes what this takes, the owner sees the new plan first. + if (more) { + Plan q = p.skipped.isEmpty() ? plan(p.wanted, p.update, p.ov) : planEach(p.wanted, p.ov); + if (!q.problems.isEmpty() || !q.sameAs().equals(p.sameAs())) { + e.out.add(q.problems.isEmpty() ? "the mod zips require more than the catalogue says, so this takes more steps:" + + " nothing was installed. Check the new plan and install again" : "can't, with what the mod zips require:"); + for (String x : q.problems) e.out.add("can't: " + x); + if (q.problems.isEmpty()) e.out.add("(nothing was installed)"); + e.out.add(Json.write(q.toJson())); + return q.problems.isEmpty() ? PLAN_CHANGED : 1; + } + } + 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 mod zip checked as its install will check it (signature, author key, HMG-API, car), before the first goes in + for (Step s : p.steps) { + if ("enable".equals(s.action)) continue; + Packages.Verdict v = Packages.check(e, s.dir, String.valueOf(s.entry.get("uuid")), false, p.ov.car(s.id)); + 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) { + 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.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); + 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 zip'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 */ } + } + } + + /** 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(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; + } + 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 = 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; + } + 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); + } + } + + // ---- 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 (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(); + 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"); + 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 : 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 keys an entry's mod was handed over from ("key_from", catalog.py add writes it from the zip's + * key-handover.json): a hint only, since the catalogue isn't signed. The install checks the handover itself. + */ + @SuppressWarnings("unchecked") + static Set keyFrom(Map en) { + Set out = new HashSet(); + Object k = en == null ? null : en.get("key_from"); + if (k instanceof List) for (Object o : (List) k) out.add(String.valueOf(o).toLowerCase()); + return out; + } + + /** + * 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"))) || keyFrom(s.entry).contains(have.toLowerCase()))) { + 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 mod zip 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). + */ + /** + * The staged updates an apply put in mods/ (each one's previous version in previous/), kept in + * state/staged-swap.json from before the first is moved until the apply's journal is written, which + * then carries them ("staged"): a cut-off apply or a trial that's undone puts them back (engine + * recover), as it does the /system files, and deleting the journal makes them final with those. + */ + static File swapFile(Engine e) { + return new File(e.stateDir, "staged-swap.json"); + } + + @SuppressWarnings("unchecked") + static List swapped(Engine e) { + List ids = new ArrayList(); + try { + if (!swapFile(e).isFile()) return ids; + Object l = Json.object(Engine.read(swapFile(e))).get("ids"); + for (Object o : l instanceof List ? (List) l : new ArrayList()) if (String.valueOf(o).matches(ID)) ids.add(String.valueOf(o)); + } catch (Exception x) { + // unreadable: as if none (mods/ and previous/ stay as they are) + } + return ids; + } + + static void recordSwap(Engine e, List ids) throws IOException { + Map m = new LinkedHashMap(); + m.put("ids", ids); + writeWhole(swapFile(e), Json.write(m), false); + } + + /** the apply that took them is final (not a trial, or a trial kept): nothing to put back any more */ + static void stagedDone(Engine e) { + swapFile(e).delete(); + } + + /** + * engine recover: staged updates a cut-off apply or an undone trial left in mods/ go back to pending/: + * those its journal names (fromJournal), and any still only on their own record (cut off before the journal) + */ + static void stagedRecover(Engine e, List fromJournal) { + List ids = swapped(e); + for (String id : fromJournal) if (id.matches(ID) && !ids.contains(id)) ids.add(id); + if (ids.isEmpty()) { + swapFile(e).delete(); + return; + } + stagedBack(e, ids); + for (String id : ids) e.out.add("rolled back the staged update of " + id + " (its previous version is installed again)"); + } + + static List stagedIn(Engine e) throws Exception { + List done = new ArrayList(); + Catalog c = new Catalog(e); + c.load(); + File[] ps = new File(e.data, "pending").listFiles(); + if (ps != null) Arrays.sort(ps); + for (File p : ps == null ? new File[0] : ps) { + 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 if (c.withdrawn(id, want) != null) why = "HMG-API's maintainers withdrew it since (" + c.withdrawn(id, want) + ")"; + else { + Packages.Verdict v = Packages.check(e, p, Packages.installedUuid(inst), false, false); + if (v.code != 0) why = v.reason; + } + 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(); + done.add(id); + recordSwap(e, done); // before the move: a cut-off apply finds it and puts it back + boolean off = new File(inst, ".disabled").exists(); + if (!inst.renameTo(prev)) throw new IOException("can't move the installed " + id + " aside"); + if (!p.renameTo(inst)) { + 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 + ")"); + } + if (done.isEmpty()) swapFile(e).delete(); + 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); + if (!prev.isDirectory() && !inst.isDirectory() && pend.isDirectory()) continue; // cut off before its move: still staged + if (!prev.isDirectory() && inst.isDirectory() && pend.isDirectory()) continue; // cut off before its move: the old one is still in mods/ + if (prev.isDirectory() && !inst.isDirectory() && pend.isDirectory()) { // cut off between the moves: the old one back + if (!prev.renameTo(inst)) e.out.add("couldn't put " + id + "'s previous version back: it's in /data/hmgapi/previous/" + id); + continue; + } + Engine.rm(pend); + if (!prev.isDirectory() || !inst.renameTo(pend) || !prev.renameTo(inst)) { + e.out.add("couldn't put " + id + "'s previous version back: the staged one stays installed"); + continue; + } + new File(pend, ".disabled").delete(); + } + if (!ids.isEmpty()) e.out.add("the staged updates (" + join(ids, ", ") + ") stay staged until an apply goes through"); + swapFile(e).delete(); + } +} diff --git a/core/runtime/java/hmgapi/engine/DnsLookup.java b/core/runtime/java/hmgapi/engine/DnsLookup.java new file mode 100644 index 00000000..643f914a --- /dev/null +++ b/core/runtime/java/hmgapi/engine/DnsLookup.java @@ -0,0 +1,110 @@ +package hmgapi.engine; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +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, 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. The server is the one in + * wifi.sh's lease (/data/hmgapi/wifi/lease, " "), which is there only while home + * Wi-Fi's route is up (dhcp.wlan0.dns1 can be left from an earlier join), and the query goes + * through an Asker: on the unit the fetch library's socket, marked for home Wi-Fi and bound to + * wlan0, so it goes out on home Wi-Fi or not at all. + */ +final class DnsLookup { + private DnsLookup() {} + + static final int TRIES = 3, TIMEOUT_MS = 3000; + static final String LEASE = "/data/hmgapi/wifi/lease"; + + /** one query's exchange: the answer's bytes, or an IOException */ + interface Asker { + byte[] ask(String server, byte[] query) throws IOException; + } + + /** the server: home Wi-Fi's DNS from wifi.sh's lease (its gateway when the lease has none); null while home Wi-Fi's route isn't up */ + static String server(String root) { + String[] f; + try { + f = Engine.read(new File(root + LEASE)).trim().split("\\s+"); + } catch (IOException x) { + return null; + } + for (int i = f.length - 1; i >= 0; i--) { + if (f[i].matches("\\d{1,3}(\\.\\d{1,3}){3}")) return f[i]; + } + return null; + } + + /** host's A records (dotted), first answer first; empty if none */ + static List lookup(String server, String host, Asker asker) 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); + try { + byte[] r = asker.ask(server, q); + return answers(r, r.length, id); + } catch (IOException e) { + last = e; + } + } + 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); + } +} diff --git a/core/runtime/java/hmgapi/engine/Engine.java b/core/runtime/java/hmgapi/engine/Engine.java index 1a5de4e8..35804bb1 100644 --- a/core/runtime/java/hmgapi/engine/Engine.java +++ b/core/runtime/java/hmgapi/engine/Engine.java @@ -23,10 +23,13 @@ * * engine plan what would change, conflicts, restarts (writes nothing) * engine apply [--trial] build and install; --trial: undone at the next start unless kept + * (a change to /system only starts in P: Gear; --gear-unknown-ok + * when the car gives no gear reading) * 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 @@ -42,10 +45,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 @@ -68,6 +73,7 @@ public final class Engine { public static final String HMGAPI_API = HMGAPI_VERSION.replaceFirst("-.*$", ""); final String root = env("HMGAPI_ROOT", ""); final boolean host = "1".equals(env("HMGAPI_HOST", "")); + boolean gearUnknownOk; // --gear-unknown-ok: the owner's go-ahead when the car gives no gear reading (Gear) final String lpatch = env("HMGAPI_LPATCH", "/system/bin/lpatch"); /** How the enabled mods' hooks fit together (the same rules the zygote's loader uses). */ HookPlan hookPlan() { @@ -146,10 +152,18 @@ 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; + // 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; + return lock(cmd, Long.parseLong(env("HMGAPI_LOCK_WAIT", "900"))); + } + + /** the lock, waiting at most waitSeconds (0: only if it's free now) */ + boolean lock(String cmd, long waitSeconds) throws IOException, InterruptedException { + if (locked || "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(); + long wait = waitSeconds * 1000000000L, start = System.nanoTime(); while (true) { java.nio.channels.FileLock l; try { @@ -337,10 +351,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; @@ -358,9 +370,11 @@ int run(String[] args) throws Exception { for (int i = 1; i < args.length; i++) { if ("--trial".equals(args[i])) trial = true; else if ("--force".equals(args[i])) force = true; + else if (Gear.OVERRIDE.equals(args[i])) gearUnknownOk = true; } stateDir.mkdirs(); - if (!lock(cmd)) return 4; + boolean safeCmd = "safe".equals(cmd); // never waits for another run (an apply can take minutes): Safe.run + if (!safeCmd && !lock(cmd)) return 4; File lj = new File(data, "settings/hmgapi.json"); if (lj.isFile()) hmgapi = Json.object(read(lj)); product = env("HMGAPI_PRODUCT", null); @@ -368,13 +382,17 @@ int run(String[] args) throws Exception { onebin = env("HMGAPI_ONEBIN", null); if (onebin == null) onebin = getprop("ro.mobis.onebindir"); facts = new SystemCheck.Facts(root, (Map) hmgapi.get("car")); + if (safeCmd) return Safe.run(this, args); if ("status".equals(cmd)) return status(); if ("verify-map".equals(cmd)) return MapCheck.run(this); 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 ("catalog".equals(cmd) || "catalog-plan".equals(cmd) || "catalog-install".equals(cmd) || "updates".equals(cmd) + || "update".equals(cmd) || "update-check".equals(cmd) || "update-source".equals(cmd)) return Catalog.run(this, args); if ("publish-state".equals(cmd)) return LiveState.publish(this); if ("apps".equals(cmd)) return ModApps.sync(this); if ("probe".equals(cmd)) { // a mod's install-time probe again (its answer is kept until then) @@ -385,7 +403,7 @@ int run(String[] args) throws Exception { } if ("update-hmgapi".equals(cmd)) { if (args.length < 2) { - out.add("usage: engine update-hmgapi [--force]"); + out.add("usage: engine update-hmgapi [--force] [--gear-unknown-ok]"); return 2; } return UsbUpdates.updateHmgApi(this, args[1], force); @@ -395,7 +413,7 @@ int run(String[] args) throws Exception { return 0; } if ("install".equals(cmd) || "remove".equals(cmd)) { - if (journalFile.exists()) { + if (journalFile.exists() || Catalog.swapFile(this).exists()) { out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); return 1; } @@ -408,6 +426,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; @@ -423,9 +444,10 @@ 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)) { + if ((journalFile.exists() || Catalog.swapFile(this).exists()) && !"keep".equals(cmd)) { out.add("an earlier apply isn't finished or is a trial: run `engine keep` (trial) or `engine recover` first"); return 1; } @@ -435,15 +457,27 @@ int run(String[] args) throws Exception { if (!restoreAll) { CarMap map = CarMap.load(root, facts, hmgapi); if (!map.runnable) out.add("hooks are off on this car (" + map.reason + "): mods apply without their hooks"); + if (Safe.on(data)) out.add("safe mode is on (" + Safe.describe(data) + "): the mods' files change as planned, but none of them runs until it's off"); } 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] [--gear-unknown-ok] | keep | restore | status | recover | release-held | firmware-reset | install | remove | safe [on | off] | 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); + // updates the automatic check staged (pending/): in place right before an apply plans, never earlier + List staged = "apply".equals(cmd) ? Catalog.stagedIn(this) : new ArrayList(); + stagedNow = staged; + if ("plan".equals(cmd)) Catalog.stagedReport(this); + Plan p; + try { + p = plan(restoreAll, force); + } catch (Exception x) { + Catalog.stagedBack(this, staged); + throw x; + } p.report(this); if (!restoreAll) { out.addAll(hookPlan().report()); + if ("plan".equals(cmd)) for (String s : Protected.describe()) out.add("safety " + s + " (no mod, built in)"); Set on = new LinkedHashSet(); Map> all = LiveState.mods(this, on); out.addAll(ModRuntime.describe(this, all, on)); @@ -453,17 +487,41 @@ 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; if (p.isEmpty()) { out.add("nothing to do"); + if ("apply".equals(cmd)) Catalog.stagedDone(this); // the staged updates changed no /system file: they're in for good if ("apply".equals(cmd)) LiveState.publish(this); // a switch with no file change still reaches running apps return 0; } - apply(p, trial); + // files on /system change (and apps may be held): only in P (Gear) + if (p.filesChange()) { + int g = Gear.check(this, restoreAll ? "the restore" : "the apply", gearUnknownOk); + if (g != 0) { + Catalog.stagedBack(this, staged); // not applied: the staged updates wait in pending/ again + return g; + } + } + // a staged update stays in mods/ only if the apply that takes it goes through: its code loads + // from there at boot, and must never run on the /system files of the version before it + int rc; + try { + rc = apply(p, trial); + } catch (Throwable x) { + Catalog.stagedBack(this, staged); + throw x; + } + if (rc != 0) { + Catalog.stagedBack(this, staged); + return rc; + } + // a trial's staged updates stay on the record with it: `engine keep` keeps them, undoing the trial puts them back + if (!trial) Catalog.stagedDone(this); LiveState.publish(this); - return 0; + return rc; } // ------------------------------------------------------------------ mods @@ -912,12 +970,14 @@ 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 + Map stockMeta; // path (and an app's odex) -> FileMeta's map, as before HMG-API's first write } final class Plan { @@ -930,6 +990,14 @@ final class Plan { Map rebasedFrom = new TreeMap(); // path -> what HMG-API had written (merges: checked after build) boolean force; // --force: owned files that aren't what HMG-API wrote are written again + /** what apply() writes on /system: a file that changes or goes back to stock */ + boolean filesChange() throws IOException { + for (Target t : targets.values()) { + if (t.restore || !t.result.equals(owned(t.path)) || (force && !t.result.equals(md5(sys(t.path))))) return true; + } + return false; + } + boolean isEmpty() throws IOException { if (!rebased.isEmpty()) return false; for (Target t : targets.values()) if (t.restore || t.result == null || !t.result.equals(owned(t.path))) return false; @@ -1029,6 +1097,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 +1192,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 +1224,90 @@ 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")); + t.stockMeta = f.get("stockMeta") instanceof Map ? (Map) f.get("stockMeta") : null; // mode, owner, label (FileMeta) + 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 +1381,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", @@ -1273,6 +1455,18 @@ 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)"; } } + // boot-critical first: of the reasons a change is refused, the one that matters most + 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)"; + } + if (critical) out.add("WARNING: " + t.path + " is boot-critical; changing it because overrides.allow_critical lists it"); + // 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)) { @@ -1284,11 +1478,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,16 +1495,12 @@ 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"); - } - 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)"; - } - if (critical) out.add("WARNING: " + t.path + " is boot-critical; changing it because overrides.allow_critical lists it"); + 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; } @@ -1342,7 +1533,13 @@ 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)); + } + t.stockMeta = owned.get("stockMeta") instanceof Map ? (Map) owned.get("stockMeta") : null; } else { String m = md5(live); if ("absent".equals(m)) { @@ -1490,21 +1687,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 +1716,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()) { @@ -1827,8 +2032,19 @@ File find(File dir, String path, Set accepted, int depth) { // ------------------------------------------------------------------ apply + /** the staged updates this apply put in place (Catalog.stagedIn): its journal carries them */ + List stagedNow = new ArrayList(); + + /** + * 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 { + 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,129 +2052,422 @@ 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(); 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); 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)); + 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; + } + // 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("held", new ArrayList()); j.put("state", Json.parse(Json.write(p.state))); // a copy: p.state changes below + // the staged updates go on the journal: from here, deleting it makes them final with the /system + // files in one step, and a recover puts them back with those files; their own record only covered + // the moments before this + j.put("staged", new ArrayList(stagedNow)); write(journalFile, Json.write(j)); + Catalog.swapFile(this).delete(); - // files taken as found (changed outside HMG-API): their old backups no longer say what was there - for (String path : p.rebased.keySet()) { - 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, 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.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); + } } - } - 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", before.get(k)); // read once, for the journal + 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")); + } + 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(bindsBefore)) { + write(bindsFile, bt); + bindsFailed.delete(); + bindsChanged = true; + } + cut("binds"); + + // 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.app && t.odexStock != null) f.put("odex", t.odexStock); + 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(bindsFile, bindsBefore); + String wasFailed = (String) j.get("binds_failed"); + if (wasFailed == null) bindsFailed.delete(); + else write(bindsFailed, wasFailed); + bindsChanged = false; + } + if (rw) { + rw = false; + try { + remount("ro"); + } catch (Exception ignored) { + // the rollback remounts for itself + } + } + List lostNow = new ArrayList(); + List left = rollback(j, lostNow); + left.addAll(lostNow); // a saved copy that's gone in the same run: say it, and leave the journal for recover + 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(); 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(); + } + } + + /** + * 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, List lost) 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")); + new File(dst.getPath() + ".hmgapi-new").delete(); // a cut-off apply's half-written copy: its room back first + if (prev != null) { // the saved copy checked before it's written back (its md5 was kept when it was taken) + String have = md5(prev); + if ("absent".equals(have) || (e.get("md5") != null && !have.equals(e.get("md5")))) { + lost.add(path); + out.add("can't put back " + path + ": its saved copy is " + ("absent".equals(have) ? "gone" : "damaged") + "; left as it is"); + continue; + } + } + 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 { + putBack(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) { @@ -1969,16 +2478,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(t.baseline, dst, stockMeta(t, t.path)); // 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), stockMeta(t, odex)); dalvik(t.path, sys(odex), false); } out.add("restored " + t.path); @@ -1986,81 +2497,226 @@ 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); } - /** 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) { + if (dexopt) testFail("dexopt", apkPath); + 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(); } } - /** 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); } @@ -2087,14 +2743,53 @@ int status() throws Exception { } Set on = new LinkedHashSet(); adbTcpWarning(LiveState.mods(this, on), on); + if (Safe.on(data)) out.add("safe mode on (" + Safe.describe(data) + "): " + Safe.WHAT); 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`)"); } + 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; } + /** 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,49 +2818,135 @@ 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; } journalFile.delete(); rm(prevDir); + Catalog.stagedDone(this); out.add("kept"); 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()) { + if (Catalog.swapFile(this).exists()) { // cut off after staged updates went in, before its journal: those go back + Catalog.stagedRecover(this, new ArrayList()); + return startHeld(readHeld()); + } out.add("nothing to recover"); - return 0; + return startHeld(readHeld()); + } + 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 startHeld(readHeld()); + } + int before = out.size(); + // a saved copy that's gone or isn't what was saved is skipped, not written back, and not tried + // again at every start (lost); a file that couldn't be written is tried again (left) + List lost = new ArrayList(); + List left = rollback(j, lost); + 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; } - 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"); + 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); + } + List staged = new ArrayList(); // the mod code that went in with it goes too + if (j.get("staged") instanceof List) for (Object o : (List) j.get("staged")) staged.add(String.valueOf(o)); + Catalog.stagedRecover(this, staged); + boolean any = out.size() > before; + 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"); + } + 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; } - 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"); + release(held); 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, FileMeta meta) 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, meta); + } + /** * 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 @@ -2220,7 +3001,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 + * "