"""Owner-facing, versioned installer; first SDK Open belongs to fixed prepare. Invoke through the release's local Ubuntu terminal. The OS password is never accepted by this script or sent to Mission Core. No arbitrary commands/URLs. """ import base64 import hashlib import http.client import json import os import pwd import re import socket import struct import subprocess import sys import time import uuid from contextlib import suppress from datetime import UTC, datetime, timedelta from pathlib import Path STAGING = Path("/var/tmp/mission-core-x4-installs") INSTANCES = Path("/run/mission-core-x4-instances") PREPARE = Path("/usr/lib/mission-core-node/insta360/prepare.py") MAINTENANCE = Path("/var/lib/mission-core-insta360/maintenance") SERVICES = ( "mission-core-node.service", "mission-core-k1.service", "mission-core-realsense.service", ) def private(path): path.mkdir(mode=0o700, exist_ok=True) info = path.lstat() if path.is_symlink() or not path.is_dir() or info.st_uid != 0 or info.st_mode & 0o077: raise RuntimeError("Installer staging is not root-owned and private") def request(path, operation=None, *, video=False, archive_route=None): timeout = 2 if video else 55 if operation else 3 client = http.client.HTTPConnection("driver", timeout=timeout) client.sock = socket.socket(socket.AF_UNIX) client.sock.settimeout(timeout) try: client.sock.connect(str(path)) if operation is None: client.request("GET", "/snapshot") else: client.request( "POST", archive_route or ("/sdk-video" if video else "/operation"), json.dumps(operation), {"Content-Type": "application/json"}, ) response = client.getresponse() limit = 4 * 1024**2 + 1028 if video else 65536 content = response.read(limit + 1) if response.status != 200 or len(content) > limit: raise RuntimeError("Camera status is unavailable") return content if video else json.loads(content) finally: client.close() # Executed only AFTER dropping supplementary groups, GID and UID. A fixed # owner-private destination, O_EXCL, bounded bytes and hash verification avoid # root writes into an operator-controlled tree. No evidence is removed. OWNER_ORIGINAL_EXPORT = r""" import hashlib, json, os, pathlib, pwd, re, sys if os.geteuid() == 0: raise RuntimeError("Original export must be unprivileged") ident, size_text, expected = sys.argv[1:] size = int(size_text) if (not re.fullmatch(r"file_[0-9a-f]{32}", ident) or not 0 < size <= 8 * 1024**3 or not re.fullmatch(r"[0-9a-f]{64}", expected)): raise ValueError("Invalid original export") os.umask(0o077) root = (pathlib.Path(pwd.getpwuid(os.geteuid()).pw_dir) / ".local/share/mission-core/qualifications/x4-originals") root.mkdir(mode=0o700, parents=True, exist_ok=True) path = root / (ident + ".insv") digest, count = hashlib.sha256(), 0 with path.open("xb") as stream: while count < size: chunk = sys.stdin.buffer.read(min(1024**2, size - count)) if not chunk: raise RuntimeError("Original export interrupted; partial retained") stream.write(chunk) digest.update(chunk) count += len(chunk) stream.flush() os.fsync(stream.fileno()) if digest.hexdigest() != expected: raise RuntimeError("Original export hash mismatch; evidence retained") print(json.dumps({"path": str(path), "bytes": count, "sha256": digest.hexdigest()})) """ def verify_original(path, camera, source): """Optional installed file-access acceptance; SDK stays in the USB worker.""" if ( not isinstance(source, str) or len(source) > 1024 or not re.fullmatch(r"/DCIM/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_.-]+\.insv", source) ): raise ValueError("Invalid camera original qualification input") uid = int(os.environ.get("SUDO_UID", "0")) if uid <= 0: raise RuntimeError("Original qualification needs an authenticated local owner") account = pwd.getpwuid(uid) ident = "file_" + uuid.uuid4().hex context = {"session_id": camera["session_id"], "id": ident} result = request(path, dict(context, source=source), archive_route="/archive/start") deadline = time.monotonic() + 360 while result.get("state") == "running" and time.monotonic() < deadline: time.sleep(1) result = request(path, context, archive_route="/archive/status") if ( result.get("state") != "complete" or type(result.get("bytes")) is not int or not 0 < result["bytes"] <= 8 * 1024**3 or not re.fullmatch(r"[0-9a-f]{64}", result.get("sha256", "")) ): raise RuntimeError("Original transfer incomplete; camera and partial file retained") child = subprocess.Popen( [ "/usr/bin/python3", "-I", "-c", OWNER_ORIGINAL_EXPORT, ident, str(result["bytes"]), result["sha256"], ], user=uid, group=account.pw_gid, extra_groups=[], env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"}, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) try: offset = 0 while offset < result["bytes"]: chunk = request( path, dict(context, offset=offset), video=True, archive_route="/archive/read" ) if len(chunk) != min(1024**2, result["bytes"] - offset): raise RuntimeError("Original export chunk is incomplete") child.stdin.write(chunk) offset += len(chunk) child.stdin.close() child.wait(timeout=30) if child.returncode != 0: raise RuntimeError("Owner original export failed; partial retained") exported = json.loads(child.stdout.read(4097)) if exported.get("sha256") != result["sha256"] or exported.get("bytes") != result["bytes"]: raise RuntimeError("Exported original differs from the worker's receipt") return {"state": "complete", "id": ident, **exported} finally: if not child.stdin.closed: child.stdin.close() child.wait(timeout=30) child.stdout.close() child.stderr.close() def camera_command(camera, action): now = datetime.now(UTC) operation = "op_" + uuid.uuid4().hex return { "api_version": "missioncore.nodedc/plugin-sdk/v0alpha2", "kind": "OperationRequest", "operation_id": operation, "idempotency_key": operation, "session": {"device_id": camera["id"], "session_id": camera["session_id"]}, "action_id": action, "requested_at": now.isoformat(), "deadline_at": (now + timedelta(seconds=60)).isoformat(), "parameters": {}, } def admit_package_plan(raw, version): """The owner permits only this Mission Core package, no OS changes.""" for line in raw.decode(errors="strict").splitlines(): fields = line.split() if ( fields and fields[0] in ("Inst", "Conf", "Remv", "Purg") and ( len(fields) < 3 or fields[0] in ("Remv", "Purg") or fields[1] != "mission-core-insta360-x4" or "(" + version + " " not in line ) ): raise RuntimeError("APT предлагает изменения вне обновления X4. Установка отменена.") def stitch_packet(raw, revision, cursor, generation): if len(raw) < 5: raise ValueError("Truncated SDK packet") size = struct.unpack("!I", raw[:4])[0] if not 0 < size <= 1024 or len(raw) <= 4 + size: raise ValueError("Invalid SDK envelope") header, data = json.loads(raw[4 : 4 + size]), raw[4 + size :] if not isinstance(header, dict) or any( type(header.get(key)) is not int or header[key] < 0 for key in ( "cursor", "generation", "timestamp", "stream_index", "stream_type", "codec", "calibration_revision", "bytes", ) ): raise ValueError("Invalid SDK metadata") if ( header["calibration_revision"] != revision or header["stream_index"] not in (0, 1) or not 0 <= header["stream_type"] <= 255 or header["codec"] not in (0, 1) or header["bytes"] != len(data) or not 0 < len(data) <= 4 * 1024**2 or header["timestamp"] <= 0 or header.get("gap") is not False or header["cursor"] <= cursor or (cursor and header["cursor"] != cursor + 1) or (generation is not None and header["generation"] != generation) ): raise ValueError("SDK stream changed or lost packets") return header, data def capture_stitch_input(path, camera): """Bounded private original-packet evidence, never a second USB owner. No MediaSDK is loaded as root. The optional sample is for a later isolated, unprivileged qualification. It does not claim stitched or stabilized output. """ result = request(path, camera_command(camera, "details")) status = result.get("result", {}) if result.get("state") != "complete" or status.get("recording") != 0: raise RuntimeError("Stitch input requires confirmed idle recording state") if status.get("preview") not in (0, 1): raise RuntimeError("Preview state is unknown") owned = status["preview"] == 0 if owned and request(path, camera_command(camera, "preview.start")).get("state") != "complete": raise RuntimeError("Preview start was not acknowledged") try: details = request(path, camera_command(camera, "details")) calibration = details.get("result", {}).get("preview_calibration") if details.get("state") != "complete" or not isinstance(calibration, dict): raise RuntimeError("Factory calibration is unavailable") revision = calibration.get("revision") if type(revision) is not int or revision <= 0: raise RuntimeError("A versioned original-packet bridge is required") cursor, generation, total = 0, None, 0 packets = [] start = time.monotonic() while len(packets) < 128 and time.monotonic() - start < 12: raw = request(path, {"session_id": camera["session_id"], "cursor": cursor}, video=True) if not raw: continue header, data = stitch_packet(raw, revision, cursor, generation) if total + len(data) > 8 * 1024**2: break total += len(data) packets.append({"header": header, "data": base64.b64encode(data).decode("ascii")}) cursor, generation = header["cursor"], header["generation"] after = request(path, camera_command(camera, "details")) if ( after.get("state") != "complete" or after.get("result", {}).get("preview_calibration") != calibration or len(packets) < 8 ): raise RuntimeError("No consistent bounded SDK input was captured") return { "schema": "missioncore.insta360.stitch-input/v1", "scope": "original-callback-sample-not-stitched-output", "captured_at": datetime.now(UTC).isoformat(), "monotonic_started": start, "duration_seconds": time.monotonic() - start, "device_id": camera["id"], "session_id": camera["session_id"], "calibration": calibration, "generation": generation, "gyro_exposure_forwarded": False, "packets": packets, } finally: if owned: stopped = request(path, camera_command(camera, "preview.stop")) if stopped.get("state") != "complete": raise RuntimeError("Qualification preview stop was not acknowledged") def pause_previews(run, report, publish): """Pause preview after OS authentication, then use the installed safety gate. Never stop a recording. The existing exclusive lifecycle lock + maintenance marker close the interval in which a viewer could restart acquisition. The broker's operator preview intent is retained for recovery after the upgrade. """ if not PREPARE.exists(): return False if MAINTENANCE.exists(): raise RuntimeError("Предыдущее обновление X4 не завершено. Нужна проверка его отчёта.") report["preview_pause"] = {"operations": [], "state": "running"} publish() for attempt in range(3): paths = sorted(INSTANCES.glob("instax4_*/driver.sock")) cameras = [] for path in paths: if not re.fullmatch(r"instax4_[0-9a-f]{32}", path.parent.name): raise RuntimeError("Некорректная привязка X4.") camera = request(path) if camera.get("id") != path.parent.name or not camera.get("online"): raise RuntimeError("Состояние X4 неизвестно. Обновление не начато.") # Read actual SDK status, not a possibly stale inventory snapshot. status = request(path, camera_command(camera, "details")) if status.get("state") != "complete" or status.get("result", {}).get("recording") != 0: raise RuntimeError( "Запись X4 активна или её состояние неизвестно. Обновление не начато." ) if status["result"].get("preview") not in (0, 1): raise RuntimeError("Состояние просмотра X4 неизвестно. Обновление не начато.") cameras.append((path, camera, status["result"]["preview"])) for path, camera, preview in cameras: if preview == 0: continue command = camera_command(camera, "preview.stop") result = request(path, command) report["preview_pause"]["operations"].append({"request": command, "result": result}) publish() if result.get("state") != "complete": raise RuntimeError("Остановка просмотра X4 не подтверждена. Обновление не начато.") # STOP invalidates cached status; allow the worker's normal poll to # refresh it. The installed quiesce gate checks all instances again. deadline = time.monotonic() + 10 while cameras and time.monotonic() < deadline: if all(request(path).get("preparation_safe") is True for path, _, _ in cameras): break time.sleep(0.25) try: run( "quiesce-" + str(attempt + 1), ["/usr/bin/python3", "-I", str(PREPARE), "--quiesce"] ) except RuntimeError: # A viewer may have restarted in the small pre-gate interval. # Retry only before the gate was acquired; no unknown outcome replay. if MAINTENANCE.exists() or attempt == 2: raise else: report["preview_pause"]["state"] = "complete" publish() return True return False def main(): if os.geteuid() or sys.argv[1:]: raise RuntimeError("Запустите установщик в локальном окне Ubuntu через sudo.") os.umask(0o077) source = Path(__file__).resolve().parent manifest = json.loads((source / "release.json").read_text()) if manifest["schema"] != "missioncore.insta360.owner-release/v1": raise ValueError("Unsupported release") version = manifest["version"] revision = manifest["runtime_revision"] if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version) or not re.fullmatch( r"[0-9a-f]{24}", revision ): raise ValueError("Invalid release version") if manifest["qualification_profile"] != "sdk-status-and-image-verification": raise ValueError("Unsupported qualification profile") if type(manifest.get("capture_stitch_input", False)) is not bool: raise ValueError("Invalid stitch input qualification profile") if manifest.get("verify_original") is not None and not isinstance( manifest["verify_original"], str ): raise ValueError("Invalid original qualification profile") package = "mission-core-insta360-x4_" + version + "_amd64.deb" admitted = manifest["files"] if set(admitted) != {package, "install_release.py", "install"}: raise ValueError("Unexpected installer contents") for name, expected in admitted.items(): data = (source / name).read_bytes() if len(data) != expected["bytes"] or hashlib.sha256(data).hexdigest() != expected["sha256"]: raise ValueError("Установщик повреждён. Контрольная сумма не совпала.") private(STAGING) identifier = uuid.uuid4().hex folder = STAGING / identifier private(folder) # Snapshot the exact admitted bytes to root-only staging before APT, so # it never consumes a mutable package from the operator's Downloads path. data = (source / package).read_bytes() if hashlib.sha256(data).hexdigest() != admitted[package]["sha256"]: raise ValueError("Package changed before staging") (folder / package).write_bytes(data) report = { "schema": "missioncore.insta360.install-run/v1", "session_id": identifier, "started_at": datetime.now(UTC).isoformat(), "monotonic_started": time.monotonic(), "release_sha256": hashlib.sha256((source / "release.json").read_bytes()).hexdigest(), "package_sha256": admitted[package]["sha256"], "state": "running", "scope": "install-profile-SDK-status-and-bounded-image-verification", "steps": [], } env = { "PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C.UTF-8", "DEBIAN_FRONTEND": "noninteractive", } def publish(): (folder / "report.json").write_text(json.dumps(report, indent=2) + "\n") def run(step, command, timeout=180): report["steps"].append( {"id": step, "state": "running", "started_at": datetime.now(UTC).isoformat()} ) publish() result = subprocess.run(command, env=env, capture_output=True, timeout=timeout) (folder / (step + ".stdout")).write_bytes(result.stdout) (folder / (step + ".stderr")).write_bytes(result.stderr) report["steps"][-1].update( state="complete" if result.returncode == 0 else "error", exit_code=result.returncode ) publish() if result.returncode: # The owner terminal log is private. Preserve the concrete cause # there instead of requiring privileged access to a hidden report. report["steps"][-1]["diagnostic_tail"] = ( result.stdout[-4096:] + result.stderr[-4096:] ).decode(errors="replace") publish() raise RuntimeError("Не завершён этап установки: " + step) return result.stdout quiesced = False publish() try: # These remain private to the authenticated owner; the terminal wrapper # saves stdout with umask 077. No camera identifiers enter public logs. previous = sorted(STAGING.glob("*/report.json"), key=lambda p: p.stat().st_mtime) for path in previous[-6:]: if path.parent != folder: print("MISSION_CORE_X4_PREVIOUS " + path.read_text().replace("\n", ""), flush=True) baseline = run( "baseline", [ "/usr/bin/systemctl", "show", *SERVICES, "-p", "Id", "-p", "ActiveState", "-p", "NRestarts", ], ) report["existing_services"] = baseline.decode().splitlines() plan = run( "apt-plan", ["/usr/bin/apt-get", "--simulate", "--no-remove", "install", str(folder / package)], ) admit_package_plan(plan, version) quiesced = pause_previews(run, report, publish) run( "package", ["/usr/bin/apt-get", "install", "-y", "--no-remove", str(folder / package)], timeout=None, ) installed_version = ( run( "installed-version", ["/usr/bin/dpkg-query", "-W", "-f=${Version}", "mission-core-insta360-x4"], ) .decode() .strip() ) if installed_version != version: raise RuntimeError("Установленная версия X4 не совпала с проверенным пакетом.") # This is the identical installed model job started by Node's local or # paired remote prepare command. No SDK demo, root SDK or manual grant. preparation = Path("/var/lib/mission-core-insta360/preparation.json") prepared = json.loads(preparation.read_text()) if preparation.exists() else {} active = Path("/var/lib/mission-core-insta360/active.path") # An upgrade's postinst already executes this same fixed preparation. # Do not race its asynchronously connecting workers with a second run. if not ( prepared.get("state") == "complete" and prepared.get("revision") == revision and active.exists() and active.read_text().strip() == revision ): run( "prepare", ["/usr/bin/systemctl", "start", "mission-core-node-insta360-x4-prepare.service"], ) deadline = time.monotonic() + 50 while True: values = [] for path in Path("/run/mission-core-x4-instances").glob("instax4_*/driver.sock"): if not re.fullmatch(r"instax4_[0-9a-f]{32}", path.parent.name): continue with suppress(OSError, ValueError, RuntimeError, http.client.HTTPException): values.append(request(path)) if values and all(item.get("prepared") and item.get("online") for item in values): break if time.monotonic() >= deadline: report["camera_status"] = values raise RuntimeError( "Пакет установлен, но подключение X4 не подтверждено. " "Проверьте питание и USB-режим камеры." ) time.sleep(1) report["camera_status"] = values if len(values) != 1: raise RuntimeError("Для этой аппаратной проверки требуется ровно одна X4.") camera = values[0] if not re.fullmatch(r"instax4_[0-9a-f]{32}", camera["id"]): raise RuntimeError("Camera identity is invalid") now = datetime.now(UTC) operation = "op_" + uuid.uuid4().hex command = { "api_version": "missioncore.nodedc/plugin-sdk/v0alpha2", "kind": "OperationRequest", "operation_id": operation, "idempotency_key": operation, "session": {"device_id": camera["id"], "session_id": camera["session_id"]}, "action_id": "verify", "requested_at": now.isoformat(), "deadline_at": (now + timedelta(seconds=60)).isoformat(), "parameters": {}, } report["image_verification"] = {"request": command, "state": "running"} publish() result = request( Path("/run/mission-core-x4-instances") / camera["id"] / "driver.sock", command ) report["image_verification"].update(state=result.get("state"), result=result) publish() if ( result.get("state") != "complete" or result.get("result", {}).get("verified") is not True ): raise RuntimeError("SDK подключён, но проверка изображения не завершилась успешно.") if manifest.get("capture_stitch_input", False): try: sample = capture_stitch_input(INSTANCES / camera["id"] / "driver.sock", camera) raw = json.dumps(sample, separators=(",", ":")).encode() (folder / "stitch-input.private.json").write_bytes(raw) report["stitch_input"] = { "state": "complete", "bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), "packets": len(sample["packets"]), "real_stitched_frame_verified": False, } # The local terminal wrapper tees to a private owner-readable # log. No writes to user-selected paths or permission widening. print("MISSION_CORE_X4_STITCH_INPUT " + raw.decode(), flush=True) except Exception as sample_error: report["stitch_input"] = {"state": "error", "error": str(sample_error)[:300]} publish() if manifest.get("verify_original"): try: report["original_verification"] = verify_original( INSTANCES / camera["id"] / "driver.sock", camera, manifest["verify_original"] ) except Exception as original_error: report["original_verification"] = { "state": "error", "error": str(original_error)[:300], } publish() after = run( "existing-services-after", [ "/usr/bin/systemctl", "show", *SERVICES, "-p", "Id", "-p", "ActiveState", "-p", "NRestarts", ], ) report["existing_services_unchanged"] = after == baseline report["state"] = "complete" print("Пакет X4 установлен. SDK подключился; получение изображения подтверждено.") print("WebRTC и команды записи остаются отдельными проверками.") except Exception as error: report["state"] = "error" report["error"] = str(error)[:300] # APT can fail before changing the package. Recover through the same # installed preparation workflow only when dpkg confirms a configured # package. Never erase a maintenance marker by hand or repair dpkg here. if quiesced and MAINTENANCE.exists(): installed = subprocess.run( ["/usr/bin/dpkg-query", "-W", "-f=${Status}", "mission-core-insta360-x4"], capture_output=True, text=True, timeout=10, ) if installed.returncode == 0 and installed.stdout.strip() == "install ok installed": try: run("recover-preparation", ["/usr/bin/python3", "-I", str(PREPARE)]) except Exception as recovery_error: report["recovery_error"] = str(recovery_error)[:300] raise finally: report["finished_at"] = datetime.now(UTC).isoformat() report["duration_seconds"] = time.monotonic() - report["monotonic_started"] publish() # Owner direction: retain the installer payload and evidence. Do not # perform cleanup or remove package copies as part of this update. print("MISSION_CORE_X4_RESULT " + json.dumps(report, ensure_ascii=False), flush=True) print("Отчёт установки:", folder / "report.json") if __name__ == "__main__": try: main() except Exception as error: print(str(error), file=sys.stderr) sys.exit(1)