Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: frigate-glance writes its config through the provider first, and checks the app read it (#3016)

NickLD5159c4917d69
diff --git a/addons/frigate-glance/README.md b/addons/frigate-glance/README.md
index d5c5ef3a4..f66a3dc7e 100644
--- a/addons/frigate-glance/README.md
+++ b/addons/frigate-glance/README.md
@@ -35,8 +35,8 @@ further by camera and object.
| Start at boot (`RECEIVE_BOOT_COMPLETED`) | To reconnect after a reboot. On TCL sets `install.sh` also allows the `APP_AUTO_START` app-op, without which TCL's firmware blocks it. |
Two components only the ADB shell can use (they need `WRITE_SECURE_SETTINGS`, as the launcher's
-ThemeProvider): `ConfigProvider` takes `config.json` on firmware that locks the shell out of `Android/data`,
-and `TestCardReceiver` shows a test card over whatever is playing.
+ThemeProvider): `ConfigProvider` takes `install.sh`'s `config.json`, so the file belongs to the add-on rather
+than the shell, and `TestCardReceiver` shows a test card over whatever is playing.
## Setup
@@ -50,8 +50,8 @@ and `TestCardReceiver` shows a test card over whatever is playing.
```
It builds the add-on, installs it, grants the overlay and auto-start, pushes the config, turns on the key
- service next to any the launcher uses, and prints `MQTT: ok` and `Frigate: ok` (or what went wrong), then
- shows a test card. The pushed file is deleted on the TV once the add-on has read it.
+ service next to any the launcher uses, and prints `Config: read by the app`, `MQTT: ok` and `Frigate: ok`
+ (or what went wrong), then shows a test card. The pushed file is deleted on the TV once the add-on has read it.
3. Press Home and answer **Show card** when the launcher asks about the add-on's card. Open it for the
settings, in five sections: **Overview** (snooze, connection status), **Cameras** (which cameras, and
whether cameras added later count), **Alerts** (alerts only or detections too, which objects), **Card**
diff --git a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java
index 261678e42..2676fde38 100644
--- a/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java
+++ b/addons/frigate-glance/app/src/main/java/io/github/nickld/frigateglance/ConfigProvider.java
@@ -12,9 +12,10 @@ import java.io.File;
import java.io.FileNotFoundException;
/**
- * For firmware that locks the shell out of Android/data (TCL G07, Android 11): install.sh writes config.json
- * here with `content write`, as tools/theme.sh does for the launcher. Write-only, one file name, and only the
- * shell can call it (WRITE_SECURE_SETTINGS on the provider). The file is imported once it is closed.
+ * install.sh writes config.json here with `content write`, as tools/theme.sh does for the launcher, so the file
+ * belongs to the app: a copy the shell makes is the shell's, which the app cannot open on Android 14 (#3016), and
+ * some firmware locks the shell out of Android/data altogether (TCL G07, Android 11). Write-only, one file name,
+ * and only the shell can call it (WRITE_SECURE_SETTINGS on the provider). The file is imported once it is closed.
*/
public class ConfigProvider extends ContentProvider {
private static final String NAME = "config.json";
diff --git a/addons/frigate-glance/install.sh b/addons/frigate-glance/install.sh
index 46dec83d4..12d3173d4 100755
--- a/addons/frigate-glance/install.sh
+++ b/addons/frigate-glance/install.sh
@@ -48,12 +48,17 @@ case "$OUT" in *Success*) ;; *) echo "ERROR: pm install failed" >&2; exit 1 ;; e
# Display over other apps (TCL's Settings hide it) and TCL's auto-start, so the service reconnects after a reboot.
tv "appops set $PKG SYSTEM_ALERT_WINDOW allow; cmd appops set $PKG APP_AUTO_START allow 2>/dev/null; echo permissions granted"
-# The config goes into the app's files folder, or through its provider where the shell may not write there.
-# The log is cleared first: through the provider the service picks the config up, and logs its connection, at once.
+# The config goes in through the app's provider, so the file belongs to the app. On Android 14 the shell can cp
+# into Android/data as well, but that file is the shell's (uid 2000) and the app gets EACCES opening it (#3016),
+# as the launcher did with themes (#832). An earlier copy goes first: the provider cannot truncate a file the
+# shell owns. Android 8 and 9 have no `content write`, and a provider exception comes back as text, both with
+# exit status 0, so those messages count as failures, as in tools/theme.sh, and cp is the fallback. Only cp runs
+# mkdir: a folder the shell makes is one the provider then cannot write into.
+# The log is cleared first: through the provider the app imports the config, and logs it, at once.
tv "logcat -c" >/dev/null
STAGE=/data/local/tmp/fg-config.json
tv --push "$CONFIG" "$STAGE" >/dev/null
-OUT=$(tv "d=/sdcard/Android/data/$PKG/files; if { mkdir -p \$d 2>/dev/null && cp $STAGE \$d/config.json 2>/dev/null; } || content write --uri content://$PKG.config/config.json < $STAGE; then echo config pushed; else echo config not written; fi; rm -f $STAGE")
+OUT=$(tv "d=/sdcard/Android/data/$PKG/files; rm -f \$d/config.json 2>/dev/null; if { o=\$(content write --uri content://$PKG.config/config.json < $STAGE 2>&1) && case \"\$o\" in *'Unsupported operation'*|*'Error while accessing provider'*) false ;; esac; } || { mkdir -p \$d 2>/dev/null && cp $STAGE \$d/config.json 2>/dev/null; }; then echo config pushed; else echo config not written; fi; rm -f $STAGE")
echo "$OUT"
case "$OUT" in *"config pushed"*) ;; *) echo "ERROR: the config could not be written on the TV" >&2; exit 1 ;; esac
@@ -70,10 +75,19 @@ for _ in $(seq 1 10); do
LOG=$(tv "logcat -d -s FrigateGlance:*" | tr -d '\r')
case "$LOG" in *"mqtt connected"*|*"mqtt error"*) case "$LOG" in *"frigate ok"*|*"frigate error"*) break ;; esac ;; esac
done
+# Whether the app read the file: "config pushed" only means the shell wrote it. A rejected config's reason can
+# quote the config, passwords included, so only its first words are printed here.
+config=$(printf '%s\n' "$LOG" | grep -o 'config imported\|pushed config unreadable: .*\|pushed config rejected' | tail -n 1 || true)
mqtt=$(printf '%s\n' "$LOG" | grep -o 'mqtt connected\|mqtt error: .*' | tail -n 1 || true)
frigate=$(printf '%s\n' "$LOG" | grep -o 'frigate ok\|frigate error: .*' | tail -n 1 || true)
+case "$config" in
+ "config imported") echo "Config: read by the app" ;;
+ "pushed config rejected") echo "Config: rejected by the app (logcat -s FrigateGlance says why)" ;;
+ "") echo "Config: not read by the app within 20 s" ;;
+ *) echo "Config: ${config#pushed config }" ;;
+esac
case "$mqtt" in "mqtt connected") echo "MQTT: ok" ;; "") echo "MQTT: no answer within 20 s" ;; *) echo "MQTT: ${mqtt#mqtt error: }" ;; esac
case "$frigate" in "frigate ok") echo "Frigate: ok" ;; "") echo "Frigate: no answer within 20 s" ;; *) echo "Frigate: ${frigate#frigate error: }" ;; esac
-[ "$mqtt" = "mqtt connected" ] && [ "$frigate" = "frigate ok" ] || exit 1
+[ "$config" = "config imported" ] && [ "$mqtt" = "mqtt connected" ] && [ "$frigate" = "frigate ok" ] || exit 1
tv "am broadcast -n $PKG/.TestCardReceiver >/dev/null; echo test card shown"
echo "Installed. A test card is on the TV now; real ones follow Frigate's alerts."
diff --git a/tests/test_frigate_glance_install.py b/tests/test_frigate_glance_install.py
new file mode 100644
index 000000000..e4a970fec
--- /dev/null
+++ b/tests/test_frigate_glance_install.py
@@ -0,0 +1,258 @@
+"""Frigate Glance's install.sh must hand the config to the app in a form the app can read, and say so (#3016).
+
+On Android 14 the adb shell can cp into Android/data, but the file belongs to the shell (uid 2000) and the app
+gets EACCES opening it. The script used to try cp first, print "config pushed", and only fail later with
+"MQTT: no config". It now writes through the app's ConfigProvider first, as tools/theme.sh does since #842,
+and reads the app's log to report whether the app imported the file.
+
+These tests run the real install.sh against a stub tools/tv.py whose "TV shell" is /bin/sh on this machine.
+Stub `content`, `cp` and `mkdir` commands track which files and folders the shell owns, and a stub app reads
+the pushed file the way the real one does: it can open a file the shell owns only on Android 8 and 9, where
+sdcardfs hides the owner.
+"""
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+ADDON = ROOT / "addons" / "frigate-glance"
+PKG = "io.github.nickld.frigateglance"
+DEVICE_DIR = f"/sdcard/Android/data/{PKG}/files"
+SECRET = "hunter2-secret"
+
+FAKE_TV = r'''
+import os
+import shutil
+import subprocess
+import sys
+
+root = os.environ["FAKE_ROOT"]
+
+
+def local(text):
+ return (text.replace("/sdcard/Android/data/io.github.nickld.frigateglance/files", root + "/device/files")
+ .replace("/data/local/tmp/", root + "/tmp/"))
+
+
+if sys.argv[1] == "--push":
+ shutil.copyfile(sys.argv[2], local(sys.argv[3]))
+else:
+ env = {**os.environ, "PATH": root + "/bin" + os.pathsep + os.environ["PATH"]}
+ result = subprocess.run(["sh", "-c", local(" ".join(sys.argv[1:]))], capture_output=True, text=True, env=env)
+ sys.stdout.write(result.stdout)
+ sys.stderr.write(result.stderr)
+ # tv.py passes the shell's text through, not its exit status.
+'''
+
+# The app: what ConfigStore.importPushed() and GlanceService log, against the fake TV's files.
+FAKE_APP = r'''
+import json
+import os
+import sys
+
+root = os.environ["FAKE_ROOT"]
+pushed = os.path.join(root, "device", "files", "config.json")
+private = os.path.join(root, "private-config.json")
+owned = os.path.join(root, "shell-owned.txt")
+
+
+def log(level, message):
+ with open(os.path.join(root, "logcat.txt"), "a") as f:
+ f.write(f"11-02 10:00:00.000 4242 4242 {level} FrigateGlance: {message}\n")
+
+
+def shell_owns(path):
+ return os.path.exists(owned) and path in open(owned).read().splitlines()
+
+
+def import_pushed():
+ if not os.path.isfile(pushed):
+ return
+ if shell_owns(pushed) and os.environ.get("FAKE_ANDROID") != "9":
+ log("W", "pushed config unreadable: /storage/emulated/0/Android/data/io.github.nickld.frigateglance"
+ "/files/config.json: open failed: EACCES (Permission denied)")
+ return
+ text = open(pushed).read()
+ os.remove(pushed)
+ if os.environ.get("FAKE_REJECT"):
+ # GlanceConfig passes a parser's message through, and that can quote the config.
+ log("W", "pushed config rejected: bad value " + json.loads(text)["mqtt"])
+ return
+ open(private, "w").write(text)
+ log("I", "config imported")
+
+
+import_pushed()
+if sys.argv[1] == "start":
+ if os.path.exists(private):
+ log("I", "mqtt connected")
+ log("I", "frigate ok")
+ else:
+ log("W", "mqtt error: no config")
+'''
+
+# `content write` runs inside the app's process on a TV, so the file it creates is the app's. Android 8 and 9
+# have no write subcommand; a provider that throws prints its exception. Both exit 0, as on a TV.
+FAKE_CONTENT = r'''
+import os
+import subprocess
+import sys
+
+root = os.environ["FAKE_ROOT"]
+owned = os.path.join(root, "shell-owned.txt")
+mode = os.environ.get("FAKE_CONTENT", "ok")
+with open(os.path.join(root, "content.log"), "a") as f:
+ f.write(" ".join(sys.argv[1:]) + "\n")
+
+
+def shell_owns(path):
+ return os.path.exists(owned) and path in open(owned).read().splitlines()
+
+
+# A file or folder the shell removed is no longer the shell's: the provider creates it anew as the app.
+if os.path.exists(owned):
+ kept = [p for p in open(owned).read().splitlines() if os.path.exists(p)]
+ open(owned, "w").write("".join(p + "\n" for p in kept))
+if mode == "android9" and sys.argv[1] == "write":
+ print("usage: adb shell content [subcommand] [options]")
+ print("[ERROR] Unsupported operation: write")
+ sys.exit(0)
+folder = os.path.join(root, "device", "files")
+path = os.path.join(folder, "config.json")
+if mode == "error" or shell_owns(folder) or shell_owns(path):
+ print("Error while accessing provider:io.github.nickld.frigateglance.config")
+ print("java.io.FileNotFoundException: open failed: EACCES (Permission denied)")
+ sys.exit(0)
+os.makedirs(folder, exist_ok=True)
+with open(path, "wb") as f:
+ f.write(sys.stdin.buffer.read())
+# ConfigProvider imports the file as soon as it is closed.
+subprocess.run([sys.executable, os.path.join(root, "app.py"), "close"], check=True)
+'''
+
+
[email protected](os.name == "nt", "install.sh requires a POSIX shell")
+class FrigateGlanceInstallTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ addon = self.root / "addons" / "frigate-glance"
+ addon.mkdir(parents=True)
+ shutil.copy2(ADDON / "install.sh", addon / "install.sh")
+ (addon / "gradlew").write_text("#!/bin/sh\nexit 0\n")
+ (addon / "gradlew").chmod(0o755)
+ (addon / "local.properties").write_text("sdk.dir=/nowhere\n")
+ tools = self.root / "tools"
+ (tools / "venv" / "bin").mkdir(parents=True)
+ (tools / "venv" / "bin" / "python").symlink_to(sys.executable)
+ (tools / "b64push.py").write_text("pass\n")
+ (tools / "tv.py").write_text(FAKE_TV)
+ (self.root / "app.py").write_text(FAKE_APP)
+ (self.root / "content.py").write_text(FAKE_CONTENT)
+ (self.root / "tmp").mkdir()
+ (self.root / "device").mkdir()
+ self.files = self.root / "device" / "files"
+ self.owned = self.root / "shell-owned.txt"
+ py = sys.executable
+ stubs = {
+ "pm": "echo Success",
+ "appops": "exit 0",
+ "cmd": "exit 0",
+ "sleep": "exit 0",
+ "settings": '[ "$1" = get ] && echo null; exit 0',
+ "logcat": f'case "$1" in -c) : > "$FAKE_ROOT/logcat.txt" ;; -d) cat "$FAKE_ROOT/logcat.txt" ;; esac',
+ "am": f'[ "$1" = start ] && "{py}" "$FAKE_ROOT/app.py" start; exit 0',
+ "content": f'exec "{py}" "$FAKE_ROOT/content.py" "$@"',
+ # A folder or file the adb shell creates is the shell's.
+ "mkdir": '[ "$1" = -p ] && shift\nfor d in "$@"; do [ -d "$d" ] || echo "$d" >> "$FAKE_ROOT/shell-owned.txt"; '
+ '/bin/mkdir -p "$d" || exit 1; done',
+ "cp": 'for last; do :; done\n/bin/cp "$@" && echo "$last" >> "$FAKE_ROOT/shell-owned.txt"',
+ }
+ (self.root / "bin").mkdir()
+ for name, body in stubs.items():
+ path = self.root / "bin" / name
+ path.write_text("#!/bin/sh\n" + body + "\n")
+ path.chmod(0o755)
+ self.config = self.root / "config.json"
+ self.config.write_text(json.dumps({"mqtt": f"mqtt://glance:{SECRET}@broker.invalid:1883",
+ "frigateUrl": "http://frigate.invalid:5000"}))
+
+ def install(self, **env):
+ # The stubs go on the script's own PATH too, so its 2 s waits do not slow the failure cases.
+ full = {**os.environ, "TV_HOST": "192.0.2.10", "FAKE_ROOT": str(self.root),
+ "PATH": f"{self.root / 'bin'}{os.pathsep}{os.environ['PATH']}", **env}
+ result = subprocess.run(["bash", str(self.root / "addons" / "frigate-glance" / "install.sh"),
+ str(self.config)], cwd=self.root, env=full, capture_output=True, text=True,
+ timeout=120)
+ self.assertNotIn(SECRET, result.stdout + result.stderr, "install.sh promises never to print the config")
+ return result
+
+ def shell_owned(self):
+ return self.owned.read_text().splitlines() if self.owned.exists() else []
+
+ def test_android_14_config_goes_through_the_provider(self):
+ result = self.install()
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("Config: read by the app\nMQTT: ok\nFrigate: ok\n", result.stdout)
+ self.assertIn("Installed.", result.stdout)
+ self.assertEqual(self.shell_owned(), [], "neither cp nor mkdir has to run when the provider answers")
+ self.assertFalse((self.root / "tmp" / "fg-config.json").exists(), "the staged copy holds passwords")
+
+ def test_a_leftover_copy_from_the_old_script_is_removed_first(self):
+ """The provider cannot truncate a file the shell owns, so the stale copy has to go before it writes."""
+ self.files.mkdir()
+ (self.files / "config.json").write_text("{}")
+ self.owned.write_text(f"{self.files / 'config.json'}\n")
+ result = self.install()
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ self.assertIn("Config: read by the app", result.stdout)
+
+ def test_android_9_without_content_write_falls_back_to_cp(self):
+ """`content` exits 0 there, so only its message tells the script to run cp."""
+ result = self.install(FAKE_CONTENT="android9", FAKE_ANDROID="9")
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ calls = (self.root / "content.log").read_text().splitlines()
+ self.assertEqual(calls, [f"write --uri content://{PKG}.config/config.json"], "the provider is tried first")
+ self.assertIn(str(self.files / "config.json"), self.shell_owned(), "cp did the writing")
+ self.assertIn("Config: read by the app", result.stdout)
+
+ def test_a_copy_the_app_cannot_open_fails_at_the_config_line(self):
+ """The reported failure: the shell wrote the file, the app got EACCES, and the old script blamed MQTT."""
+ result = self.install(FAKE_CONTENT="error")
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Config: unreadable: ", result.stdout)
+ self.assertIn("EACCES (Permission denied)", result.stdout)
+ self.assertNotIn("Installed.", result.stdout)
+
+ def test_a_new_config_the_app_cannot_open_is_not_hidden_by_the_old_one(self):
+ """pm install -r keeps the app's data, so MQTT and Frigate can come up on the last config imported."""
+ (self.root / "private-config.json").write_text("{}")
+ result = self.install(FAKE_CONTENT="error")
+ self.assertIn("MQTT: ok", result.stdout)
+ self.assertIn("Config: unreadable: ", result.stdout)
+ self.assertNotEqual(result.returncode, 0, "the config just pushed never reached the app")
+ self.assertNotIn("Installed.", result.stdout)
+
+ def test_a_folder_the_old_script_made_is_reported_not_hidden(self):
+ """A files folder the shell made refuses the provider too; the script has to say the app never read it."""
+ self.files.mkdir()
+ self.owned.write_text(f"{self.files}\n")
+ result = self.install()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Config: unreadable: ", result.stdout)
+
+ def test_a_rejected_config_is_named_without_its_contents(self):
+ result = self.install(FAKE_REJECT="1")
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("Config: rejected by the app", result.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()