diff --git a/install.ps1 b/install.ps1 index 4a8ffac23..226f320bc 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "8e7ea94c5c9ded4ba5033ab33ab2f633df8632e8221dcc14de9b8ffe7d29065a" + $defaultInstallSha256 = "31f3475b2205fe40694d232961957a4322dea518d476210b55d2a9e5da10d602" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index 55d5960fb..107991d02 100644 --- a/install.py +++ b/install.py @@ -1827,6 +1827,19 @@ def _replace_with_copy(src: Path, dest: Path) -> None: raise +def read_local_json(path: Path, limit: int) -> object: + """A JSON file of limit bytes at most. OSError when it cannot be read, + ValueError saying why when it is too large or not JSON.""" + with open(path, "rb") as handle: + raw = handle.read(limit + 1) + if len(raw) > limit: + raise ValueError(f"it exceeds {limit} bytes") + try: + return json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"not JSON ({exc})") from exc + + def write_atomically(path: Path, data: bytes) -> None: """Write data at path through a scratch file beside it, removed when the write fails; a scratch that cannot be removed is named in the error.""" @@ -7379,9 +7392,8 @@ def _network_allowed(what: str) -> None: def local_manifest_platform(path: Path) -> str | None: """The platform a saved file list names, None when it names none.""" try: - with open(path, "rb") as handle: - data = json.loads(handle.read(MAX_MANIFEST_BYTES).decode("utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError): + data = read_local_json(path, MAX_MANIFEST_BYTES) + except (OSError, ValueError): return None plat = data.get("platform") if isinstance(data, dict) else None return plat if plat in AVAILABLE_PLATFORMS else None @@ -7444,19 +7456,10 @@ NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs def read_local_manifest(path: Path, plat: str) -> dict: """A file list saved on disk, checked as a downloaded one is.""" try: - with open(path, "rb") as handle: - raw = handle.read(MAX_MANIFEST_BYTES + 1) + return _validate_manifest(read_local_json(path, MAX_MANIFEST_BYTES), plat) except OSError as exc: print(f" Cannot read the file list {path}: {exc.strerror or exc}.", file=sys.stderr) sys.exit(1) - try: - if len(raw) > MAX_MANIFEST_BYTES: - raise ValueError(f"it exceeds {MAX_MANIFEST_BYTES} bytes") - try: - data = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ValueError(f"not JSON ({exc})") from exc - return _validate_manifest(data, plat) except ValueError as exc: EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat, message=f"the file list is not valid: {exc}") @@ -7807,12 +7810,16 @@ def local_targets(plat: str) -> "dict | None": if LOCAL.manifest is None: return None beside = LOCAL.manifest.parent / "targets" / f"{plat}.json" - raw = _read_capped(beside, MAX_TARGETS_BYTES) - if raw is None: + if not _is_file(beside): return None try: - return _validate_targets(json.loads(raw.decode("utf-8"))) - except (UnicodeDecodeError, ValueError) as exc: + return _validate_targets(read_local_json(beside, MAX_TARGETS_BYTES)) + except OSError as exc: + # Read as absent, the offline run asked for the file already there. + print(f" Error: the target list {beside} cannot be read: {exc.strerror or exc}", + file=sys.stderr) + sys.exit(1) + except ValueError as exc: print(f" Error: the target list {beside} is not valid: {exc}", file=sys.stderr) sys.exit(1) @@ -7828,16 +7835,17 @@ def fetch_standalone(plat: str, manifest: dict) -> dict: where = str(beside) if beside is not None and _is_file(beside) else url try: if where != url: - raw = _read_capped(Path(where), MAX_STANDALONE_BYTES) - data = json.loads((raw or b"").decode("utf-8")) + data = read_local_json(Path(where), MAX_STANDALONE_BYTES) else: data = _fetch_json(url, MAX_STANDALONE_BYTES, "standalone layout") return _check_standalone_layouts(data, manifest, plat) except urllib.error.HTTPError as exc: problem = f"HTTP {exc.code}" except (urllib.error.URLError, OSError) as exc: - problem = str(exc) if isinstance(exc, _Offline) else network_words(exc)[1] - except (UnicodeDecodeError, ValueError) as exc: + problem = (str(exc) if isinstance(exc, _Offline) + else exc.strerror or str(exc) if where != url + else network_words(exc)[1]) + except ValueError as exc: problem = f"not valid: {exc}" EVENTS.emit("error", stage="manifest", reason="unavailable", platform=plat, message=f"--standalone needs {where}: {problem}") diff --git a/install.sh b/install.sh index e7a98c417..a93a43c4f 100755 --- a/install.sh +++ b/install.sh @@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins # curl or wget stop on a cut transfer before the hash is read: the site's # build rewrites this line there (scripts/sitebootstrap.py). MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." -DEFAULT_INSTALL_SHA256="8e7ea94c5c9ded4ba5033ab33ab2f633df8632e8221dcc14de9b8ffe7d29065a" +DEFAULT_INSTALL_SHA256="31f3475b2205fe40694d232961957a4322dea518d476210b55d2a9e5da10d602" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. MAX_INSTALLER_BYTES=8388608 diff --git a/install/launchers/index.json b/install/launchers/index.json index fad6fa672..8487e69a0 100644 --- a/install/launchers/index.json +++ b/install/launchers/index.json @@ -27,8 +27,8 @@ { "dest": "roms/ports/retrobios/install.py", "repo_path": "install.py", - "size": 1448645, - "sha256": "8e7ea94c5c9ded4ba5033ab33ab2f633df8632e8221dcc14de9b8ffe7d29065a", + "size": 1448904, + "sha256": "31f3475b2205fe40694d232961957a4322dea518d476210b55d2a9e5da10d602", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1502270, - "sha256": "0246007dae205b51c288a17a6a0ecae978097d57bdeb9cda46a25123018cff2f" + "size": 1502529, + "sha256": "f4e3bc9d84ef9fd0f40266370f2f0edce67d2ba90e516c2802b018d80d365a47" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1448645, - "sha256": "8e7ea94c5c9ded4ba5033ab33ab2f633df8632e8221dcc14de9b8ffe7d29065a", + "size": 1448904, + "sha256": "31f3475b2205fe40694d232961957a4322dea518d476210b55d2a9e5da10d602", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1448645, - "sha256": "8e7ea94c5c9ded4ba5033ab33ab2f633df8632e8221dcc14de9b8ffe7d29065a", + "size": 1448904, + "sha256": "31f3475b2205fe40694d232961957a4322dea518d476210b55d2a9e5da10d602", "executable": false }, { diff --git a/installer/host_fs.py b/installer/host_fs.py index 7659ffed2..79dd2d099 100644 --- a/installer/host_fs.py +++ b/installer/host_fs.py @@ -2,6 +2,7 @@ from __future__ import annotations import errno +import json import os import re import shutil @@ -239,6 +240,19 @@ def _replace_with_copy(src: Path, dest: Path) -> None: raise +def read_local_json(path: Path, limit: int) -> object: + """A JSON file of limit bytes at most. OSError when it cannot be read, + ValueError saying why when it is too large or not JSON.""" + with open(path, "rb") as handle: + raw = handle.read(limit + 1) + if len(raw) > limit: + raise ValueError(f"it exceeds {limit} bytes") + try: + return json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"not JSON ({exc})") from exc + + def write_atomically(path: Path, data: bytes) -> None: """Write data at path through a scratch file beside it, removed when the write fails; a scratch that cannot be removed is named in the error.""" diff --git a/installer/network.py b/installer/network.py index 4891ccebb..b8253bba9 100644 --- a/installer/network.py +++ b/installer/network.py @@ -16,7 +16,7 @@ from pathlib import Path from typing import Any, NoReturn from installer.events import EVENTS -from installer.host_fs import _is_file +from installer.host_fs import _is_file, read_local_json from installer.manifest import _check_standalone_layouts, _validate_manifest, _validate_targets from installer.offline import LOCAL, _Offline, _network_allowed, offline_named, offline_undo, offline_words from installer.platforms import TARGET_PLATFORMS, display_name @@ -86,19 +86,10 @@ NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs def read_local_manifest(path: Path, plat: str) -> dict: """A file list saved on disk, checked as a downloaded one is.""" try: - with open(path, "rb") as handle: - raw = handle.read(MAX_MANIFEST_BYTES + 1) + return _validate_manifest(read_local_json(path, MAX_MANIFEST_BYTES), plat) except OSError as exc: print(f" Cannot read the file list {path}: {exc.strerror or exc}.", file=sys.stderr) sys.exit(1) - try: - if len(raw) > MAX_MANIFEST_BYTES: - raise ValueError(f"it exceeds {MAX_MANIFEST_BYTES} bytes") - try: - data = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ValueError(f"not JSON ({exc})") from exc - return _validate_manifest(data, plat) except ValueError as exc: EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat, message=f"the file list is not valid: {exc}") @@ -449,12 +440,16 @@ def local_targets(plat: str) -> "dict | None": if LOCAL.manifest is None: return None beside = LOCAL.manifest.parent / "targets" / f"{plat}.json" - raw = _read_capped(beside, MAX_TARGETS_BYTES) - if raw is None: + if not _is_file(beside): return None try: - return _validate_targets(json.loads(raw.decode("utf-8"))) - except (UnicodeDecodeError, ValueError) as exc: + return _validate_targets(read_local_json(beside, MAX_TARGETS_BYTES)) + except OSError as exc: + # Read as absent, the offline run asked for the file already there. + print(f" Error: the target list {beside} cannot be read: {exc.strerror or exc}", + file=sys.stderr) + sys.exit(1) + except ValueError as exc: print(f" Error: the target list {beside} is not valid: {exc}", file=sys.stderr) sys.exit(1) @@ -470,16 +465,17 @@ def fetch_standalone(plat: str, manifest: dict) -> dict: where = str(beside) if beside is not None and _is_file(beside) else url try: if where != url: - raw = _read_capped(Path(where), MAX_STANDALONE_BYTES) - data = json.loads((raw or b"").decode("utf-8")) + data = read_local_json(Path(where), MAX_STANDALONE_BYTES) else: data = _fetch_json(url, MAX_STANDALONE_BYTES, "standalone layout") return _check_standalone_layouts(data, manifest, plat) except urllib.error.HTTPError as exc: problem = f"HTTP {exc.code}" except (urllib.error.URLError, OSError) as exc: - problem = str(exc) if isinstance(exc, _Offline) else network_words(exc)[1] - except (UnicodeDecodeError, ValueError) as exc: + problem = (str(exc) if isinstance(exc, _Offline) + else exc.strerror or str(exc) if where != url + else network_words(exc)[1]) + except ValueError as exc: problem = f"not valid: {exc}" EVENTS.emit("error", stage="manifest", reason="unavailable", platform=plat, message=f"--standalone needs {where}: {problem}") diff --git a/installer/offline.py b/installer/offline.py index 101cf9482..d5bfd5875 100644 --- a/installer/offline.py +++ b/installer/offline.py @@ -1,12 +1,12 @@ """The offline mode and the local sources a run reads in place of the network.""" from __future__ import annotations -import json import os import weakref from pathlib import Path from typing import TYPE_CHECKING +from installer.host_fs import read_local_json from installer.invocation import OFFLINE_VARIABLE, offline_requested from installer.platforms import AVAILABLE_PLATFORMS from installer.remote import MAX_MANIFEST_BYTES @@ -107,9 +107,8 @@ def _network_allowed(what: str) -> None: def local_manifest_platform(path: Path) -> str | None: """The platform a saved file list names, None when it names none.""" try: - with open(path, "rb") as handle: - data = json.loads(handle.read(MAX_MANIFEST_BYTES).decode("utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError): + data = read_local_json(path, MAX_MANIFEST_BYTES) + except (OSError, ValueError): return None plat = data.get("platform") if isinstance(data, dict) else None return plat if plat in AVAILABLE_PLATFORMS else None diff --git a/tests/test_install_offline.py b/tests/test_install_offline.py index 4ad692eea..288f173c9 100644 --- a/tests/test_install_offline.py +++ b/tests/test_install_offline.py @@ -1154,5 +1154,46 @@ class OfflineAndPackLeaveOut(Scratch): self.assertIn("Enter) install what is found in", out.getvalue()) + +class LocalFilesSayWhyTheyCannotBeUsed(unittest.TestCase): + """An oversized layout beside --manifest was "not valid: Expecting + value", and an unreadable target list read as absent, so the offline + run asked for the file already there.""" + + def setUp(self): + self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) + self.addCleanup(shutil.rmtree, self.root, True) + listing = self.root / "retroarch.json" + listing.write_text("{}") + patcher = unittest.mock.patch.object(install.LOCAL, "manifest", listing) + patcher.start() + self.addCleanup(patcher.stop) + + def _said(self, call) -> str: + with contextlib.redirect_stderr(io.StringIO()) as err, \ + self.assertRaises(SystemExit) as stop: + call() + self.assertEqual(stop.exception.code, 1) + return err.getvalue() + + def test_an_oversized_standalone_layout(self): + (self.root / "standalone").mkdir() + (self.root / "standalone" / "retroarch.json").write_bytes( + b" " * (install.MAX_STANDALONE_BYTES + 1)) + said = self._said(lambda: install.fetch_standalone("retroarch", {})) + self.assertIn(f"it exceeds {install.MAX_STANDALONE_BYTES} bytes", said) + + @unittest.skipIf(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + "a mode of 000 closes the file to this user on POSIX only") + def test_an_unreadable_target_list(self): + (self.root / "targets").mkdir() + boards = self.root / "targets" / "retroarch.json" + boards.write_text("{}") + boards.chmod(0) + self.addCleanup(boards.chmod, 0o644) + said = self._said(lambda: install.local_targets("retroarch")) + self.assertIn(f"the target list {boards} cannot be read", said) + + if __name__ == "__main__": unittest.main()