feat(video): recover camera previews and reduce encoding and playout cost

Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:01 +03:00
parent e06ff9a214
commit fa8bde584f
94 changed files with 8892 additions and 375 deletions
+3 -3
View File
@@ -16,7 +16,7 @@ sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from debian import package # noqa: E402
from fetch_sdk import verify # noqa: E402
VERSION = "0.1.3-10"
VERSION = "0.1.3-30"
WHEELS = {
"aiohappyeyeballs",
"aiohttp",
@@ -74,7 +74,7 @@ def runtime_payload():
if provenance["sdk_lock_sha256"] != digest((PACKAGING / "sdk-lock.json").read_bytes()):
raise ValueError("Native adapter SDK input changed")
binary = (native / "libmissioncore_x4.so").read_bytes()
if digest(binary) != provenance["binary"]["sha256"] or provenance["abi"] != 1:
if digest(binary) != provenance["binary"]["sha256"] or provenance["abi"] != 2:
raise ValueError("Native adapter provenance mismatch")
files = {"lib/libmissioncore_x4.so": binary}
for item in lock["files"]:
@@ -206,7 +206,7 @@ Architecture: amd64
Maintainer: NODE.DC local build <noreply@example.invalid>
Section: admin
Priority: optional
Depends: mission-core-node (>= 0.8.16), mission-core-node (<< 0.9.0),
Depends: mission-core-node (>= 0.8.49-71), mission-core-node (<< 0.9.0),
systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), adduser, udev, polkitd,
libc6 (>= 2.35), libstdc++6 (>= 12), libgcc-s1, zlib1g,
bluez (>= 5.72), python3-dbus, python3-gi
@@ -0,0 +1,315 @@
"""Build the bounded MediaSDK initialization qualification, without vendor execution."""
import argparse
import base64
import hashlib
import json
import struct
import subprocess
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
HEADERS = {
"ins_realtime_stitcher.h": "b156c45b24b69abb9f82435c8e5472ca8c371414f31c50162a7781c69d426e82",
"ins_stitcher.h": "ccdffcdb9387495ef34548a9ff5d14009dae2333d5cfc53b5e7f0500e19d7a94",
"ins_common.h": "9cdfbcd875f599eb6ebfa6cc36538828017c1ab314e3f059b060d3a83e922ced",
}
ENTRY = """import hashlib,json,sys,zipfile
from pathlib import Path
with zipfile.ZipFile(sys.argv[0]) as z:
raw=z.read("manifest.json")
m=json.loads(raw)
source=z.read("media_qualification.py")
ident=hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name!="mission-core-x4-media-qualify-"+ident+".pyz":
raise RuntimeError("Qualification artifact identity mismatch")
if hashlib.sha256(source).hexdigest()!=m["files"]["media_qualification.py"]:
raise RuntimeError("Qualification source checksum mismatch")
exec(compile(source,"media_qualification.py","exec"),{"__name__":"__main__"})
"""
def recorded_input(raw):
"""Serialize the exact admitted callback sample, without rewriting NALs."""
if not 0 < len(raw) <= 12 * 1024**2:
raise ValueError("Recorded input exceeds the sample bound")
sample = json.loads(raw)
if sample.get("schema") != "missioncore.insta360.stitch-input/v1":
raise ValueError("Unknown callback sample")
calibration = sample["calibration"]
revision = calibration["revision"]
if type(revision) is not int or revision <= 0:
raise ValueError("Missing calibration revision")
output = bytearray(b"MCX4P002")
def number(value, code="I", minimum=0, maximum=16384):
if type(value) is not int or not minimum <= value <= maximum:
raise ValueError("Invalid captured metadata number")
output.extend(struct.pack("<" + code, value))
def text(value, maximum, empty=False):
if not isinstance(value, str):
raise ValueError("Invalid captured metadata string")
encoded = value.encode()
if len(encoded) > maximum or (not encoded and not empty) or b"\0" in encoded:
raise ValueError("Invalid captured metadata string")
number(len(encoded), maximum=maximum)
output.extend(encoded)
text(calibration["camera_name"], 128)
offsets = calibration["offsets"]
if not isinstance(offsets, list) or not any(offsets):
raise ValueError("Missing factory calibration")
number(len(offsets), minimum=1, maximum=4)
for offset in offsets:
text(offset, 8192, empty=True)
crop = calibration["crop"]
for key in ("source_width", "source_height", "width", "height"):
number(crop[key], minimum=1)
for key in ("x", "y"):
number(crop[key], code="i")
codec = calibration["encode_type"]
number(codec, maximum=1)
packets = sample["packets"]
number(len(packets), minimum=8, maximum=128)
total, cursor = 0, None
timestamps = {}
for packet in packets:
header = packet["header"]
if (
header["calibration_revision"] != revision
or header["generation"] != sample["generation"]
or header["codec"] != codec
or header.get("gap") is not False
or type(header["cursor"]) is not int
or header["cursor"] < 1
or (cursor is not None and header["cursor"] != cursor + 1)
):
raise ValueError("Callback generation, revision or continuity changed")
timestamp, index = header["timestamp"], header["stream_index"]
number(timestamp, code="q", minimum=1, maximum=2**63 - 1)
number(header["stream_type"], maximum=255)
number(index, maximum=1)
if timestamp < timestamps.get(index, 0):
raise ValueError("Invalid callback timestamp order")
timestamps[index], cursor = timestamp, header["cursor"]
data = base64.b64decode(packet["data"], validate=True)
if type(header["bytes"]) is not int or header["bytes"] != len(data):
raise ValueError("Callback payload length changed")
number(len(data), minimum=1, maximum=4 * 1024**2)
total += len(data)
if total > 8 * 1024**2:
raise ValueError("Recorded payload exceeds bound")
output.extend(data)
return bytes(output)
def build(
headers,
compatibility_deb,
synthetic_input=None,
software_rendering=False,
recorded_camera_input=None,
original_receipt=None,
original_seconds=95,
live_input=False,
replay_artifact=None,
stitch_type="dynamic",
):
origins = (
synthetic_input,
recorded_camera_input,
original_receipt,
live_input,
replay_artifact,
)
if sum(bool(x) for x in origins) > 1:
raise ValueError("Choose exactly one rendering input origin")
render = any(origins)
if stitch_type not in ("dynamic", "template") or (
stitch_type != "dynamic" and not replay_artifact
):
raise ValueError("Alternate stitch type is limited to retained callback replay")
if live_input and not software_rendering:
raise ValueError("Live qualification requires the verified software rendering profile")
if type(original_seconds) is not int or not 0 <= original_seconds <= 240:
raise ValueError("Original sample time must be between 0 and 240 seconds")
if software_rendering and not render:
raise ValueError("Software rendering requires a rendering input")
mode = (
"live-render"
if live_input
else "original-render"
if original_receipt
else "recorded-render"
if recorded_camera_input or replay_artifact
else "synthetic-render"
if render
else "initialization"
)
files = {
"media_qualification.py": (ROOT / "packaging/media_qualification.py").read_bytes(),
"media_probe.cpp": (
ROOT
/ "native"
/ (
"media_original_probe.cpp"
if original_receipt
else "media_frame_probe.cpp"
if render
else "media_probe.cpp"
)
).read_bytes(),
"profile.json": json.dumps(
{
"mode": mode,
"egl_platform": "surfaceless" if render else None,
"software_rendering": software_rendering,
**({"stitch_type": stitch_type} if replay_artifact else {}),
**({"original_seconds": original_seconds} if original_receipt else {}),
}
).encode(),
}
if live_input:
for name in ("media_live_source.py", "media_live_qualification.py", "install_release.py"):
files[name] = (ROOT / "packaging" / name).read_bytes()
if original_receipt:
original = json.loads(original_receipt.read_text())
if (
original.get("state") != "complete"
or type(original.get("bytes")) is not int
or not 0 < original["bytes"] <= 8 * 1024**3
or not isinstance(original.get("sha256"), str)
or len(original["sha256"]) != 64
):
raise ValueError("A verified original receipt is required")
files["original.json"] = json.dumps(
{key: original[key] for key in ("path", "bytes", "sha256")}
).encode()
if recorded_camera_input:
files["input.bin"] = recorded_input(recorded_camera_input.read_bytes())
if replay_artifact:
with zipfile.ZipFile(replay_artifact) as previous:
raw = previous.read("manifest.json")
ident = hashlib.sha256(raw).hexdigest()[:24]
manifest = json.loads(raw)
if (
replay_artifact.name != f"mission-core-x4-media-qualify-{ident}.pyz"
or json.loads(previous.read("profile.json"))["mode"] != "recorded-render"
):
raise ValueError("Replay input is not a retained recorded-source artifact")
for name in ("profile.json", "input.bin"):
if hashlib.sha256(previous.read(name)).hexdigest() != manifest["files"][name]:
raise ValueError("Retained replay artifact changed")
data = previous.read("input.bin")
if not data.startswith(b"MCX4P002") or len(data) > 8 * 1024**2 + 65536:
raise ValueError("Invalid retained callback input")
files["input.bin"] = data
files["source-provenance.json"] = json.dumps(
{
"artifact_sha256": hashlib.sha256(replay_artifact.read_bytes()).hexdigest(),
"input_sha256": hashlib.sha256(data).hexdigest(),
"scope": "Unchanged prior camera callback sample; no new live capture",
}
).encode()
if synthetic_input:
content = synthetic_input.read_bytes()
if not content.startswith(b"MCX4P001") or not 0 < len(content) <= 8 * 1024**2:
raise ValueError("Invalid bounded synthetic rendering input")
files["input.bin"] = content
package_sha = "298a778a6a579a556f6bb4e32512cd76e0483b57b4a379ee85397f62fe21f225"
if hashlib.sha256(compatibility_deb.read_bytes()).hexdigest() != package_sha:
raise ValueError("Unexpected Ubuntu libtiff5 compatibility package")
# The operator Mac's libarchive tar reads ar and zstd. No maintainer scripts
# or package manager run, on either the build host or the qualification host.
payload = subprocess.run(
["/usr/bin/tar", "-xOf", str(compatibility_deb), "data.tar.zst"],
capture_output=True,
check=True,
timeout=20,
).stdout
for target, source in {
"compat/libtiff.so.5": "./usr/lib/x86_64-linux-gnu/libtiff.so.5.7.0",
"compat/LICENSE.libtiff5": "./usr/share/doc/libtiff5/copyright",
}.items():
content = subprocess.run(
["/usr/bin/tar", "-xOf", "-", source],
input=payload,
capture_output=True,
check=True,
timeout=20,
).stdout
if not 0 < len(content) < 1024 * 1024:
raise ValueError("Unexpected compatibility payload size")
files[target] = content
for name, expected in HEADERS.items():
data = (headers / name).read_bytes()
if hashlib.sha256(data).hexdigest() != expected:
raise ValueError("MediaSDK header differs from the approved archive")
files["include/" + name] = data
manifest = {
"schema": "missioncore.insta360.media-qualification-artifact/v1",
"scope": "bounded-live-stream-read-only"
if live_input
else "bounded-" + mode + "-no-camera-access",
"vendor_version": "3.1.5",
"system_changes": False,
"compatibility_package": {
"name": "libtiff5",
"version": "4.3.0-6ubuntu0.13",
"architecture": "amd64",
"sha256": package_sha,
"source": "https://packages.ubuntu.com/jammy-updates/amd64/libtiff5/download",
"scope": "private-qualification-only-not-installed",
},
"files": {n: hashlib.sha256(d).hexdigest() for n, d in files.items()},
}
raw = json.dumps(manifest, sort_keys=True).encode()
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / f"mission-core-x4-media-qualify-{ident}.pyz"
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED) as z:
for name, data in {"__main__.py": ENTRY.encode(), "manifest.json": raw, **files}.items():
info = zipfile.ZipInfo(name, date_time=(2026, 10, 14, 0, 0, 0))
info.external_attr = 0o600 << 16
info.compress_type = zipfile.ZIP_DEFLATED
z.writestr(info, data)
output.chmod(0o600)
return {
"artifact": str(output),
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"id": ident,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--headers", type=Path, required=True)
parser.add_argument("--compatibility-deb", type=Path, required=True)
inputs = parser.add_mutually_exclusive_group()
inputs.add_argument("--synthetic-input", type=Path)
inputs.add_argument("--recorded-camera-input", type=Path)
inputs.add_argument("--original-receipt", type=Path)
inputs.add_argument("--live-input", action="store_true")
inputs.add_argument("--replay-artifact", type=Path)
parser.add_argument("--stitch-type", choices=("dynamic", "template"), default="dynamic")
parser.add_argument("--software-rendering", action="store_true")
parser.add_argument("--original-seconds", type=int, default=95)
args = parser.parse_args()
print(
json.dumps(
build(
args.headers,
args.compatibility_deb,
args.synthetic_input,
args.software_rendering,
args.recorded_camera_input,
args.original_receipt,
args.original_seconds,
args.live_input,
args.replay_artifact,
args.stitch_type,
)
)
)
@@ -10,7 +10,6 @@ import hashlib
import json
import os
import platform
import shutil
import subprocess
import tempfile
from pathlib import Path
@@ -63,7 +62,7 @@ def build(sdk, destination):
raise ValueError("Built adapter does not depend on the admitted SDK")
report = {
"schema": "missioncore.insta360.native-build/v1",
"abi": 1,
"abi": 2,
"sdk_lock_sha256": hashlib.sha256(LOCK.read_bytes()).hexdigest(),
"source": {
p.name: hashlib.sha256(p.read_bytes()).hexdigest()
@@ -87,8 +86,8 @@ def build(sdk, destination):
os.rename(stage, destination)
return report
finally:
if stage.exists():
shutil.rmtree(stage)
# Owner direction: preserve failed build staging and its evidence.
pass
if __name__ == "__main__":
@@ -0,0 +1,97 @@
"""Small, verified unprivileged owner-wrapper build using a qualified board .deb.
Avoid transporting the same 58 MB package twice across the operator link.
This creates build artifacts only, never installs or executes a vendor SDK.
"""
import argparse
import hashlib
import json
import sys
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
ENTRY = """import hashlib,json,os,platform,subprocess,sys,zipfile
from pathlib import Path
if os.geteuid()==0 or platform.system()!="Linux":
raise RuntimeError("Use the unprivileged Ubuntu build account")
os.umask(0o077)
with zipfile.ZipFile(sys.argv[0]) as z:
raw=z.read("manifest.json"); manifest=json.loads(raw)
ident=hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name!="mission-core-x4-owner-build-"+ident+".pyz":
raise ValueError("Build identity changed")
files={n:z.read(n) for n in manifest["files"]}
if any(hashlib.sha256(data).hexdigest()!=manifest["files"][name] for name,data in files.items()):
raise ValueError("Build source changed")
expected=manifest["qualified"]
source=Path(expected["file"])
if (source.is_symlink() or source.stat().st_uid!=os.geteuid()
or source.stat().st_size!=expected["bytes"]):
raise ValueError("Qualified package changed")
with source.open("rb") as f:
if hashlib.file_digest(f,"sha256").hexdigest()!=expected["sha256"]:
raise ValueError("Qualified package hash changed")
root=Path("/var/tmp")/("mission-core-x4-owner-build-"+ident)
root.mkdir(mode=0o700)
(root/"packaging").mkdir(mode=0o700)
(root/"build").mkdir(mode=0o700)
for name,data in files.items():
with (root/"packaging"/name).open("xb") as f:f.write(data)
os.link(source,root/"build"/source.name)
(root/"build/package-result.json").write_text(json.dumps(expected))
command=["/usr/bin/python3","-I",str(root/"packaging/build_owner_release.py"),
"--qualified",str(root/"build")]
if manifest.get("original"):
command.extend(["--verify-original",manifest["original"]])
subprocess.run(command,check=True)
"""
def build(report, original=None):
files = {
name: (ROOT / "packaging" / name).read_bytes()
for name in (
"install",
"install_release.py",
"owner_release_entry.py",
"build_owner_release.py",
)
}
manifest = {
"schema": "missioncore.insta360.owner-wrapper-build/v1",
"qualified": json.loads(report.read_text()),
"original": original,
"files": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()},
}
raw = json.dumps(manifest, sort_keys=True).encode()
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-x4-owner-build-" + ident + ".pyz")
required = sum(map(len, files.values())) + len(raw) + len(ENTRY) + 2 * 1024**2
with (
publish_input(output, required_bytes=required) as staged,
zipfile.ZipFile(staged, "x", compression=zipfile.ZIP_DEFLATED) as z,
):
for name, data in {"__main__.py": ENTRY.encode(), "manifest.json": raw, **files}.items():
z.writestr(name, data)
output.chmod(0o600)
print(
json.dumps(
{
"artifact": str(output), "retention": input_hold(output),
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--qualified-report", type=Path, required=True)
parser.add_argument("--verify-original")
args = parser.parse_args()
build(args.qualified_report, args.verify_original)
@@ -10,7 +10,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def build(qualified):
def build(qualified, capture_stitch_input=False, verify_original=None):
expected = json.loads((qualified / "package-result.json").read_text())
version = expected["version"]
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version):
@@ -35,6 +35,8 @@ def build(qualified):
"version": version,
"runtime_revision": expected["revision"],
"qualification_profile": "sdk-status-and-image-verification",
"capture_stitch_input": capture_stitch_input,
"verify_original": verify_original,
"qualification": "Ubuntu native build, cold imports, static closure, synthetic tests",
"hardware_qualified": False,
"clean_image_qualified": False,
@@ -64,4 +66,10 @@ def build(qualified):
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--qualified", type=Path, required=True)
print(json.dumps(build(parser.parse_args().qualified)))
parser.add_argument("--capture-stitch-input", action="store_true")
parser.add_argument(
"--verify-original",
help="Exact camera-listed .insv for private installed file-access acceptance",
)
args = parser.parse_args()
print(json.dumps(build(args.qualified, args.capture_stitch_input, args.verify_original)))
@@ -1,5 +1,6 @@
"""Snapshot package inputs for compilation/qualification only on the Ubuntu Mini."""
import argparse
import hashlib
import json
import sys
@@ -11,9 +12,11 @@ from build_deb import VERSION # noqa: E402
from fetch_sdk import ROOT, verify # noqa: E402
REPOSITORY = ROOT.parents[1]
sys.path.insert(0, str(REPOSITORY / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
def build():
def build(native=None):
sdk = json.loads((ROOT / "packaging/sdk-lock.json").read_text())
verify(ROOT / "build/sdk", sdk)
paths = list((ROOT / "packaging").glob("*.py"))
@@ -34,7 +37,8 @@ def build():
paths += list((REPOSITORY / "packages/plugin-sdk/python/missioncore_plugin_sdk").rglob("*.py"))
paths += [REPOSITORY / "scripts/packaging/debian.py"]
paths += [REPOSITORY / "apps/node-agent/packaging/insta360_profile.py"]
paths += [REPOSITORY / "apps/node-agent/packaging/install_owner_release.py"]
paths += [REPOSITORY / "apps/node-agent/packaging" / name for name in (
"install_owner_release.py", "can_maintenance.py", "vesc_hall_recovery.py")]
paths += [
REPOSITORY / name
for name in (
@@ -47,6 +51,11 @@ def build():
files = {
path.relative_to(REPOSITORY).as_posix(): path.read_bytes() for path in sorted(set(paths))
}
if native is not None:
for name in ("libmissioncore_x4.so", "provenance.json"):
files[(ROOT / "build/native" / name).relative_to(REPOSITORY).as_posix()] = (
native / name
).read_bytes()
entrypoint = (ROOT / "packaging/native_build_entry.py").read_bytes()
manifest = {
"schema": "missioncore.insta360.build-source/v1",
@@ -62,7 +71,12 @@ def build():
raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n"
ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-x4-package-build-" + ident + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive:
required = sum(map(len, files.values())) + len(raw) + len(entrypoint) + 2 * 1024**2
with (
publish_input(output, required_bytes=required) as staged,
staged.open("xb") as stream,
zipfile.ZipFile(stream, "w") as archive,
):
for name, data in {
"__main__.py": entrypoint,
"source.json": raw,
@@ -75,6 +89,7 @@ def build():
output.chmod(0o600)
return {
"artifact": str(output),
"retention": input_hold(output),
"source_id": ident,
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
@@ -82,4 +97,8 @@ def build():
if __name__ == "__main__":
print(json.dumps(build()))
parser = argparse.ArgumentParser()
parser.add_argument(
"--native", type=Path, help="Qualified versioned output; retain older native builds"
)
print(json.dumps(build(parser.parse_args().native)))
@@ -3,11 +3,15 @@
import hashlib
import json
import sys
import zipfile
from pathlib import Path
from fetch_sdk import LOCK, ROOT, verify
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
def build():
lock = json.loads(LOCK.read_text())
@@ -40,8 +44,10 @@ def build():
output = ROOT / "build" / ("mission-core-x4-build-" + ident + ".pyz")
entries = {"__main__.py": entrypoint, "source.json": content}
entries.update({"source/" + name: data for name, data in files.items()})
required = sum(map(len, entries.values())) + 2 * 1024**2
with (
output.open("xb") as stream,
publish_input(output, required_bytes=required) as staged,
staged.open("xb") as stream,
zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive,
):
for name, data in entries.items():
@@ -52,6 +58,7 @@ def build():
output.chmod(0o600)
return {
"artifact": str(output),
"retention": input_hold(output),
"bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"source_id": ident,
@@ -4,7 +4,6 @@ import hashlib
import importlib
import io
import json
import shutil
import subprocess
import sys
import tarfile
@@ -93,4 +92,5 @@ try:
if not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful():
raise RuntimeError("Package qualification tests failed")
finally:
shutil.rmtree(stage)
# Owner direction: retain qualification artifacts; no automatic cleanup.
pass
+389 -10
View File
@@ -4,12 +4,15 @@ 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
@@ -19,6 +22,9 @@ 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",
@@ -33,8 +39,8 @@ def private(path):
raise RuntimeError("Installer staging is not root-owned and private")
def request(path, operation=None):
timeout = 55 if operation else 3
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)
@@ -44,17 +50,322 @@ def request(path, operation=None):
client.request("GET", "/snapshot")
else:
client.request(
"POST", "/operation", json.dumps(operation), {"Content-Type": "application/json"}
"POST",
archive_route or ("/sdk-video" if video else "/operation"),
json.dumps(operation),
{"Content-Type": "application/json"},
)
response = client.getresponse()
content = response.read(65537)
if response.status != 200 or len(content) > 65536:
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 json.loads(content)
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.")
@@ -71,6 +382,12 @@ def main():
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"}:
@@ -122,9 +439,16 @@ def main():
)
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
@@ -148,15 +472,27 @@ def main():
],
)
report["existing_services"] = baseline.decode().splitlines()
run(
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")
@@ -222,6 +558,35 @@ def main():
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",
[
@@ -243,14 +608,28 @@ def main():
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()
# Retain bounded private evidence and remove only the installer-owned
# temporary package copy. Runtime/journals remain owned by the .deb.
(folder / package).unlink()
# 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")
@@ -0,0 +1,223 @@
"""One bounded live qualification; vendor SDK remains unprivileged and isolated."""
import getpass
import json
import os
import resource
import signal
import struct
import subprocess
import sys
import time
from pathlib import Path
from install_release import stitch_packet
from media_live_source import read_message, write_all
from media_qualification import digest, restrict_process, stamp, verify_runtime
def calibration_bytes(calibration):
raw = bytearray(b"MCX4L001")
def integer(value, minimum=0, maximum=16384, code="I"):
if type(value) is not int or not minimum <= value <= maximum:
raise ValueError("Invalid calibration number")
raw.extend(struct.pack("<" + code, value))
def text(value, limit, empty=False):
if not isinstance(value, str):
raise ValueError("Invalid calibration text")
data = value.encode()
if len(data) > limit or (not data and not empty) or b"\0" in data:
raise ValueError("Invalid calibration text")
integer(len(data), maximum=limit)
raw.extend(data)
text(calibration["camera_name"], 128)
offsets = calibration["offsets"]
if not isinstance(offsets, list) or not any(offsets):
raise ValueError("Missing factory calibration")
integer(len(offsets), minimum=1, maximum=4)
for offset in offsets:
text(offset, 8192, True)
for field in ("source_width", "source_height", "width", "height"):
integer(calibration["crop"][field], minimum=1)
for field in ("x", "y"):
integer(calibration["crop"][field], code="i")
integer(calibration["encode_type"], maximum=1)
return bytes(raw)
def execute_live(root, device, session):
if os.geteuid() == 0:
raise RuntimeError("Vendor qualification must never run as root")
verify_runtime(root)
if digest(root / "probe") != json.loads((root / "binary.json").read_text())["sha256"]:
raise ValueError("Qualification binary changed")
profile = json.loads((root / "profile.json").read_text())
if profile != {
"mode": "live-render",
"egl_platform": "surfaceless",
"software_rendering": True,
}:
raise ValueError("Unqualified live rendering profile")
work = root / "live-run"
work.mkdir(mode=0o700)
(work / "logs").mkdir(mode=0o700)
report = {
"started": stamp(),
"scope": "20s-live-original-stream-960x480-cpu",
"system_changes": False,
"camera_lifecycle_changes": False,
"latency_scope": (
"reader receipt to SDK output; excludes USB/worker backlog, encoding and network"
),
}
source = renderer = None
initial_usage = resource.getrusage(resource.RUSAGE_CHILDREN)
with (
(work / "source.log").open("xb", buffering=0) as source_log,
(work / "stdout.log").open("xb", buffering=0) as stdout,
(work / "stderr.log").open("xb", buffering=0) as stderr,
):
try:
password = getpass.getpass("Ubuntu password for the authorized read-only live sample: ")
source = subprocess.Popen(
[
"/usr/bin/sudo",
"-k",
"-S",
"-p",
"",
"/usr/bin/python3",
"-I",
str(Path(sys.argv[0]).resolve()),
"source-live",
"--device-id",
device,
"--session-id",
session,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=source_log,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
bufsize=0,
)
source.stdin.write((password + "\n").encode())
password = ""
header = json.loads(read_message(source.stdout, time.monotonic() + 10, 65536))
if header["session"] != session:
raise ValueError("Live reader returned a different session")
calibration = header["calibration"]
native_header = calibration_bytes(calibration)
(work / "calibration.private.json").write_text(json.dumps(calibration))
renderer = subprocess.Popen(
[str(root / "probe"), str(work / "logs"), "-", str(root / "sdk/bin/models") + "/"],
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr,
start_new_session=True,
cwd=work,
bufsize=0,
preexec_fn=lambda: restrict_process(root, work, True),
env={
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8",
"OMP_NUM_THREADS": "2",
"OPENBLAS_NUM_THREADS": "2",
"LP_NUM_THREADS": "2",
"TMPDIR": str(work),
"XDG_CACHE_HOME": str(work),
"EGL_PLATFORM": "surfaceless",
"LIBGL_ALWAYS_SOFTWARE": "true",
"GALLIUM_DRIVER": "llvmpipe",
},
)
os.set_blocking(renderer.stdin.fileno(), False)
write_all(renderer.stdin, native_header, time.monotonic() + 2)
deadline = time.monotonic() + 12
while b'"phase":"live_ready"' not in (work / "stdout.log").read_bytes():
if renderer.poll() is not None or time.monotonic() > deadline:
raise RuntimeError("SDK did not become ready within the bound")
time.sleep(0.1)
source.stdin.write(b"START\n")
source.stdin.close()
report["stream_started"] = stamp()
deadline = time.monotonic() + 26
cursor, generation, packets, size = 0, None, 0, 0
while True:
raw = read_message(source.stdout, deadline)
if not raw:
break
if len(raw) < 13:
raise ValueError("Truncated live packet")
received = struct.unpack("<Q", raw[:8])[0]
header, data = stitch_packet(raw[8:], calibration["revision"], cursor, generation)
if header["codec"] != calibration["encode_type"]:
raise ValueError("Source codec changed")
cursor, generation = header["cursor"], header["generation"]
packets += 1
size += len(data)
if packets > 900 or size > 32 * 1024**2:
raise ValueError("Live sample exceeds bounds")
payload = (
struct.pack(
"<IqIIQ",
len(data),
header["timestamp"],
header["stream_type"],
header["stream_index"],
received,
)
+ data
)
write_all(renderer.stdin, payload, min(deadline, time.monotonic() + 2))
report.update(
stream_finished=stamp(), packets=packets, bytes=size, generation=generation
)
write_all(renderer.stdin, struct.pack("<I", 0), time.monotonic() + 2)
renderer.stdin.close()
report["source_exit_code"] = source.wait(timeout=5)
report["renderer_exit_code"] = renderer.wait(timeout=12)
except Exception as error:
report["error"] = type(error).__name__ + ": " + str(error)
finally:
if source is not None:
if not source.stdin.closed:
source.stdin.close()
source.stdout.close()
try:
report["source_exit_code"] = source.wait(timeout=5)
except subprocess.TimeoutExpired:
# The root reader has a fixed 48s alarm and cannot touch the
# camera lifecycle. Closing its pipes makes writes fail.
report["source_exit_code"] = source.wait(timeout=50)
if renderer is not None:
if not renderer.stdin.closed:
renderer.stdin.close()
try:
report["renderer_exit_code"] = renderer.wait(timeout=3)
except subprocess.TimeoutExpired:
os.killpg(renderer.pid, signal.SIGKILL)
renderer.wait()
report["renderer_killed_at_deadline"] = True
report["renderer_exit_code"] = renderer.returncode
report["finished"] = stamp()
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
report["child_usage"] = {
"user_seconds": usage.ru_utime - initial_usage.ru_utime,
"system_seconds": usage.ru_stime - initial_usage.ru_stime,
"max_rss_kib": usage.ru_maxrss,
}
report["artifacts"] = {
str(p.relative_to(work)): digest(p) for p in work.rglob("*") if p.is_file()
}
(root / "live-run.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report), flush=True)
if (
report.get("error")
or report.get("source_exit_code") != 0
or report.get("renderer_exit_code") != 0
):
raise RuntimeError("Live qualification failed; evidence retained")
@@ -0,0 +1,202 @@
"""Bounded read-only access to the installed X4 original-packet bridge.
This helper never imports a vendor library, starts preview, opens USB, writes a
file, or changes host configuration. Its only privileged capability is reading
one already-running, explicitly identified camera session for 20 seconds.
"""
import http.client
import json
import os
import re
import select
import signal
import socket
import struct
import sys
import time
from pathlib import Path
from install_release import camera_command, stitch_packet
DURATION = 20
MAX_BYTES = 32 * 1024**2
MAX_PACKETS = 900
WARMUP = 2
def independent_packet(data, codec):
"""Begin only at an original IDR with its original codec parameter sets."""
kinds = set()
for marker in re.finditer(b"\x00\x00(?:\x00)?\x01", data):
if marker.end() < len(data):
kinds.add(data[marker.end()] & 31 if codec == 0 else (data[marker.end()] >> 1) & 63)
return (
{5, 7, 8} <= kinds
if codec == 0
else {32, 33, 34} <= kinds and bool(kinds & {16, 17, 18, 19, 20, 21})
)
def read_exact(stream, size, deadline):
result = bytearray()
while len(result) < size:
remaining = deadline - time.monotonic()
if remaining <= 0 or not select.select([stream], [], [], remaining)[0]:
raise TimeoutError("Live qualification pipe deadline")
chunk = os.read(stream.fileno(), size - len(result))
if not chunk:
raise EOFError("Live qualification pipe ended early")
result.extend(chunk)
return bytes(result)
def read_message(stream, deadline, limit=4 * 1024**2 + 1040):
size = struct.unpack("!I", read_exact(stream, 4, deadline))[0]
if size > limit:
raise ValueError("Live qualification envelope exceeds bound")
return read_exact(stream, size, deadline) if size else b""
def write_all(stream, data, deadline):
view = memoryview(data)
while view:
remaining = deadline - time.monotonic()
if remaining <= 0 or not select.select([], [stream], [], remaining)[1]:
raise TimeoutError("Live qualification consumer is not keeping up")
try:
count = os.write(stream.fileno(), view[:65536])
except BlockingIOError:
continue
if count <= 0:
raise BrokenPipeError("Live qualification consumer closed")
view = view[count:]
def emit_message(stream, raw):
write_all(stream, struct.pack("!I", len(raw)) + raw, time.monotonic() + 2)
def request(path, camera, *, cursor=None):
client = http.client.HTTPConnection("driver", timeout=3)
client.sock = socket.socket(socket.AF_UNIX)
client.sock.settimeout(3)
try:
client.sock.connect(str(path))
if camera is None:
client.request("GET", "/snapshot")
else:
body = (
camera_command(camera, "details")
if cursor is None
else {"session_id": camera["session_id"], "cursor": cursor}
)
client.request(
"POST",
"/operation" if cursor is None else "/sdk-video",
json.dumps(body),
{"Content-Type": "application/json"},
)
response = client.getresponse()
limit = 65536 if cursor is None else 4 * 1024**2 + 1028
raw = response.read(limit + 1)
if response.status != 200 or len(raw) > limit:
raise RuntimeError("Installed camera bridge is unavailable")
return json.loads(raw) if cursor is None else raw
finally:
client.close()
def active_details(path, camera):
result = request(path, camera)
details = result.get("result", {})
if (
result.get("state") != "complete"
or details.get("preview") != 1
or details.get("recording") != 0
):
raise RuntimeError("An already-active preview and idle recording are required")
calibration = details.get("preview_calibration")
if (
not isinstance(calibration, dict)
or type(calibration.get("revision")) is not int
or calibration["revision"] <= 0
):
raise ValueError("Versioned factory calibration is required")
return calibration
def source(device, session, output, control):
if not re.fullmatch(r"instax4_[0-9a-f]{32}", device) or not re.fullmatch(
r"x4_[0-9a-f]{32}", session
):
raise ValueError("Invalid exact camera identity")
path = Path("/run/mission-core-x4-instances") / device / "driver.sock"
camera = request(path, None)
if (
camera.get("id") != device
or camera.get("session_id") != session
or camera.get("online") is not True
):
raise RuntimeError("The requested camera session changed")
calibration = active_details(path, camera)
emit_message(output, json.dumps({"calibration": calibration, "session": session}).encode())
# The unprivileged renderer must acknowledge initialization before reading
# camera packets. stdin contains only this token after sudo consumes auth.
if read_exact(control, 6, time.monotonic() + 15) != b"START\n":
raise ValueError("Missing explicit renderer readiness")
started = time.monotonic()
cursor, generation, size, count = 0, None, 0, 0
forwarded, discarded = 0, 0
forwarding = WARMUP == 0
while time.monotonic() - started < DURATION:
raw = request(path, camera, cursor=cursor)
received = time.monotonic_ns()
if not raw:
continue
header, data = stitch_packet(raw, calibration["revision"], cursor, generation)
if header["codec"] != calibration["encode_type"]:
raise ValueError("Source codec changed")
size += len(data)
count += 1
if size > MAX_BYTES or count > MAX_PACKETS:
raise ValueError("Live sample exceeds its byte/packet bound")
cursor, generation = header["cursor"], header["generation"]
if not forwarding:
# The driver's bounded late-join queue can contain two seconds of
# prior data. Drain it continuously, then wait for a new complete
# keyframe; do not inject a burst of old frames into SDK playback.
if time.monotonic() - started < WARMUP or not independent_packet(data, header["codec"]):
discarded += 1
continue
forwarding = True
emit_message(output, struct.pack("<Q", received) + raw)
forwarded += 1
if forwarded < 8:
raise RuntimeError("No continuous independently decodable live input")
if active_details(path, camera) != calibration:
raise ValueError("Factory calibration changed during the sample")
emit_message(output, b"")
return {
"packets": count,
"forwarded_packets": forwarded,
"startup_discarded_packets": discarded,
"bytes": size,
"generation": generation,
"seconds": time.monotonic() - started,
"preview_preserved": True,
}
def main(device, session):
if os.geteuid() != 0:
raise RuntimeError("The installed bridge requires explicitly authorized access")
# Also bounds setup, blocked pipes and a lost SSH caller. No cleanup removes
# files or sends a camera command; this reader owns no camera lifecycle.
signal.alarm(48)
os.set_blocking(sys.stdout.fileno(), False)
try:
result = source(device, session, sys.stdout.buffer, sys.stdin.buffer)
print(json.dumps({"source_complete": True, **result}), file=sys.stderr, flush=True)
finally:
signal.alarm(0)
@@ -0,0 +1,769 @@
"""Versioned, unprivileged MediaSDK qualification on the existing Ubuntu Mini.
Stage, compile and execute are distinct commands. Compilation never runs SDK
code. Execution has no network, USB, host sockets or writable host OS paths.
This profile establishes library initialization only, never stitched-frame or
real-time quality acceptance. Missing system dependencies are reported, not
installed. All files belong to the bounded qualification directory.
"""
import argparse
import concurrent.futures
import ctypes
import fcntl
import hashlib
import json
import os
import platform
import pwd
import re
import resource
import shutil
import signal
import struct
import subprocess
import sys
import tarfile
import time
import urllib.request
import zipfile
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
SCHEMA = "missioncore.insta360.media-qualification/v1"
ARCHIVE_BYTES = 2039751710
ARCHIVE_SHA = "c22890a9d51164599324429a68d62cec0278e4a4a17f0c126cbfb0a20073a2f0"
ARCHIVE_URL = "https://wassets.insta360.com/common/8f722c654d8a43f88944337be023922c/Linux_CameraSDK-2.1.8_MediaSDK-3.1.5.zip"
MEMBER = "Linux_CameraSDK-2.1.8_MediaSDK-3.1.5/MediaSDK-3.1.5-20260819-linux64.tar_1787191716602.gz"
PREFIX = "opt/MediaSDK-3.1.5-linux/"
MAX_EXPANDED = 13 * 1024**3
def digest(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def stamp():
return {"utc": datetime.now(UTC).isoformat(), "monotonic": time.monotonic()}
def relative(name):
name = name.removeprefix("./")
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts or "\\" in name or path.as_posix() != name:
raise ValueError("Unsafe vendor archive entry")
if not name.startswith(PREFIX):
raise ValueError("Vendor entry outside the declared runtime")
result = name[len(PREFIX) :]
if not result or not result.startswith(("lib/", "bin/")):
raise ValueError("Unexpected vendor runtime entry")
return result
def download_range(root, start, end):
"""Bound concurrency and verify the server actually honored the byte range."""
target = root / f"{start}-{end}.part"
receipt = target.with_suffix(".json")
if target.exists() and receipt.exists():
saved = json.loads(receipt.read_text())
if target.stat().st_size == end - start + 1 and digest(target) == saved["sha256"]:
return target
raise ValueError("Previously completed download part changed")
partial = target.with_suffix(".partial")
for attempt in range(3):
try:
request = urllib.request.Request(
ARCHIVE_URL,
headers={"Range": f"bytes={start}-{end}", "Accept-Encoding": "identity"},
)
# This is an incomplete, artifact-owned transfer, never accepted evidence.
if partial.is_symlink():
raise ValueError("Unexpected download symlink")
with (
urllib.request.urlopen(request, timeout=30) as response,
partial.open("wb") as output,
):
if (
response.url != ARCHIVE_URL
or response.status != 206
or response.headers.get("Content-Range")
!= f"bytes {start}-{end}/{ARCHIVE_BYTES}"
):
raise ValueError("Vendor returned a different archive range")
size = 0
while chunk := response.read(min(1024 * 1024, end - start + 2 - size)):
size += len(chunk)
if size > end - start + 1:
raise ValueError("Vendor range is oversized")
output.write(chunk)
if size != end - start + 1:
raise ValueError("Vendor range is incomplete")
partial.rename(target)
receipt.write_text(json.dumps({"sha256": digest(target)}))
return target
except (OSError, TimeoutError):
if attempt == 2:
raise
raise RuntimeError("Download retries exhausted")
def source_archive(root, prefix=None):
target = root / "vendor.zip"
if target.exists():
if (
target.is_symlink()
or target.stat().st_size != ARCHIVE_BYTES
or digest(target) != ARCHIVE_SHA
):
raise ValueError("Existing vendor archive differs from the approved download")
return target
parts = root / "download"
parts.mkdir(mode=0o700, exist_ok=True)
start = prefix.stat().st_size if prefix else 0
if not 0 <= start < ARCHIVE_BYTES:
raise ValueError("Invalid source prefix size")
ranges = [
(pos, min(ARCHIVE_BYTES - 1, pos + 8 * 1024**2 - 1))
for pos in range(start, ARCHIVE_BYTES, 8 * 1024**2)
]
completed, updated = start, time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
pending = {pool.submit(download_range, parts, a, b): (a, b) for a, b in ranges}
for future in concurrent.futures.as_completed(pending):
future.result()
a, b = pending[future]
completed += b - a + 1
if time.monotonic() - updated >= 20:
print(
json.dumps({"phase": "download", "bytes": completed, "total": ARCHIVE_BYTES}),
flush=True,
)
updated = time.monotonic()
partial = root / "vendor.zip.partial"
if partial.is_symlink():
raise ValueError("Unexpected archive symlink")
with partial.open("wb") as output:
inputs = ([prefix] if prefix else []) + [parts / f"{a}-{b}.part" for a, b in ranges]
for item in inputs:
with item.open("rb") as source:
shutil.copyfileobj(source, output, 1024 * 1024)
if partial.stat().st_size != ARCHIVE_BYTES or digest(partial) != ARCHIVE_SHA:
raise ValueError("Vendor archive checksum mismatch")
partial.rename(target)
# Completed bytes have been verified as exactly the approved vendor archive.
for item in parts.iterdir():
item.unlink()
parts.rmdir()
return target
def extract_runtime(archive, target):
if target.exists():
raise ValueError("Do not replace a qualification runtime")
target.mkdir(mode=0o700)
rows, links, total, names = [], [], 0, set()
with (
zipfile.ZipFile(archive) as zipped,
zipped.open(MEMBER) as stream,
tarfile.open(fileobj=stream, mode="r|gz") as outer,
):
package = next(
item
for item in outer
if item.isfile() and item.name.endswith("/MediaSDK-3.1.5-linux-amd64.deb")
)
deb = outer.extractfile(package)
if deb.read(8) != b"!<arch>\n":
raise ValueError("Invalid vendor Debian archive")
while header := deb.read(60):
if len(header) != 60 or header[58:] != b"`\n":
raise ValueError("Invalid Debian member")
size = int(header[48:58])
if not 0 <= size <= ARCHIVE_BYTES:
raise ValueError("Oversized Debian member")
if header[:16].decode().strip().rstrip("/") == "data.tar.gz":
with tarfile.open(fileobj=deb, mode="r|gz") as payload:
for item in payload:
if item.isdir():
continue
name = relative(item.name)
if name in names or len(names) >= 512:
raise ValueError("Duplicate or excessive vendor entries")
names.add(name)
if item.issym() or item.islnk():
if item.islnk():
link = relative(item.linkname)
else:
raw = PurePosixPath(item.linkname)
if raw.is_absolute() or ".." in raw.parts or "\\" in item.linkname:
raise ValueError("Unsafe vendor link")
link = (PurePosixPath(name).parent / raw).as_posix()
links.append((name, link))
continue
if not item.isfile() or not 0 <= item.size <= 3 * 1024**3:
raise ValueError("Unsupported vendor entry")
total += item.size
if total > MAX_EXPANDED:
raise ValueError("Expanded vendor payload exceeds the profile")
dest = target / name
dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
checksum = hashlib.sha256()
with payload.extractfile(item) as source, dest.open("xb") as output:
while chunk := source.read(1024 * 1024):
checksum.update(chunk)
output.write(chunk)
dest.chmod(0o600)
rows.append(
{"path": name, "bytes": item.size, "sha256": checksum.hexdigest()}
)
break
remaining = size + size % 2
while remaining:
chunk = deb.read(min(remaining, 1024 * 1024))
if not chunk:
raise ValueError("Truncated Debian member")
remaining -= len(chunk)
else:
raise ValueError("Vendor payload missing")
# Resolve only links to packaged regular files; no host paths or link cycles.
pending = links[:]
while pending:
next_pending = []
for name, link in pending:
source, dest = target / link, target / name
if not source.is_file():
next_pending.append((name, link))
continue
dest.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
os.link(source, dest)
rows.append({"path": name, "hardlink": link})
if len(next_pending) == len(pending):
raise ValueError("Unresolved vendor link")
pending = next_pending
return rows
def verify_runtime(root):
manifest = json.loads((root / "runtime.json").read_text())
if manifest.get("archive_sha256") != ARCHIVE_SHA:
raise ValueError("Unexpected runtime source")
for item in manifest["files"]:
path = root / "sdk" / item["path"]
if path.is_symlink() or not path.is_file():
raise ValueError("Runtime file missing or substituted")
if "sha256" in item and (
path.stat().st_size != item["bytes"] or digest(path) != item["sha256"]
):
raise ValueError("Runtime checksum changed")
if "hardlink" in item and not path.samefile(root / "sdk" / item["hardlink"]):
raise ValueError("Runtime link changed")
def compile_probe(root):
verify_runtime(root)
output = root / "probe"
if output.exists():
raise ValueError("Do not overwrite a compiled qualification")
subprocess.run(
[
"/usr/bin/g++",
"-std=c++17",
"-pthread",
"-O1",
"-Wall",
"-Wextra",
"-Werror",
"-I",
str(root / "include"),
str(root / "media_probe.cpp"),
"-L",
str(root / "sdk/lib"),
"-Wl,--allow-shlib-undefined",
"-Wl,--disable-new-dtags,-rpath," + str(root / "sdk/lib") + ":" + str(root / "compat"),
"-lMediaSDK",
"-o",
str(output),
],
check=True,
timeout=120,
env={"PATH": "/usr/bin:/bin", "LANG": "C.UTF-8"},
)
(root / "binary.json").write_text(
json.dumps(
{
"sha256": digest(output),
"scope": json.loads((root / "profile.json").read_text())["mode"],
**stamp(),
}
)
)
def limit_child():
os.nice(10)
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_AS, (8 * 1024**3, 8 * 1024**3))
resource.setrlimit(resource.RLIMIT_CPU, (60, 60))
resource.setrlimit(resource.RLIMIT_FSIZE, (16 * 1024**2, 16 * 1024**2))
def network_filter():
"""x86_64 seccomp: no network/Unix sockets or io_uring escape path.
Forbid socket syscalls before vendor code runs. Landlock independently
constrains filesystem/device access and cross-domain signals.
"""
instructions = [
(0x20, 0, 0, 4), # architecture
(0x15, 1, 0, 0xC000003E),
(0x06, 0, 0, 0x80000000), # kill non-x86_64
(0x20, 0, 0, 0), # syscall number
(0x35, 0, 1, 0x40000000),
(0x06, 0, 0, 0x80000000), # kill x32 ABI
]
for number in [*range(41, 56), 288, 299, 307, 425, 426, 427]:
instructions += [(0x15, 0, 1, number), (0x06, 0, 0, 0x00050001)]
instructions += [(0x06, 0, 0, 0x7FFF0000)]
return b"".join(struct.pack("HBBI", *row) for row in instructions)
def restrict_process(root, work, software_rendering=False):
"""Add kernel-enforced restrictions without modifying host policy or namespaces."""
limit_child()
libc = ctypes.CDLL(None, use_errno=True)
libc.syscall.restype = ctypes.c_long
def check(result):
if result < 0:
raise OSError(ctypes.get_errno(), "Cannot enforce qualification isolation")
return result
if check(libc.syscall(444, 0, 0, 1)) < 6:
raise RuntimeError("Qualification requires Landlock ABI 6 or newer")
class Ruleset(ctypes.Structure):
_fields_ = [
("fs", ctypes.c_uint64),
("network", ctypes.c_uint64),
("scoped", ctypes.c_uint64),
]
class Rule(ctypes.Structure):
_pack_ = 1
_fields_ = [("access", ctypes.c_uint64), ("parent", ctypes.c_int)]
attr = Ruleset(0xFFFF, 0, 3)
ruleset = check(libc.syscall(444, ctypes.byref(attr), ctypes.sizeof(attr), 0))
read = 1 | 4 | 8
writable = 2 | 4 | 8 | 16 | 32 | 128 | 256 | 4096 | 8192 | 16384
paths = [
(p, read)
for p in (
"/usr",
"/lib",
"/lib64",
"/etc/ld.so.cache",
"/etc/vulkan",
"/etc/drirc",
"/etc/localtime",
"/sys",
"/proc/cpuinfo",
"/proc/meminfo",
"/proc/self",
str(root / "sdk"),
str(root / "compat"),
str(root / "probe"),
str(root / "input.bin"),
str(root / "original.insv"),
)
]
paths += [
(str(work), writable),
("/dev/null", 2 | 4 | 32768),
("/dev/urandom", 4),
("/dev/random", 4),
]
if not software_rendering:
paths.append(("/dev/dri", 2 | 4 | 8 | 32768))
try:
for name, rights in paths:
path = Path(name)
if not path.exists():
continue
if not path.is_dir():
rights &= 1 | 2 | 4 | 16384 | 32768
fd = os.open(name, os.O_PATH | os.O_CLOEXEC)
try:
entry = Rule(rights, fd)
check(libc.syscall(445, ruleset, 1, ctypes.byref(entry), 0))
finally:
os.close(fd)
check(libc.prctl(38, 1, 0, 0, 0)) # PR_SET_NO_NEW_PRIVS
check(libc.syscall(446, ruleset, 0))
finally:
os.close(ruleset)
class Filter(ctypes.Structure):
_fields_ = [("length", ctypes.c_ushort), ("instructions", ctypes.c_void_p)]
code = network_filter()
buffer = ctypes.create_string_buffer(code)
program = Filter(len(code) // 8, ctypes.cast(buffer, ctypes.c_void_p))
check(libc.prctl(22, 2, ctypes.byref(program), 0, 0)) # PR_SET_SECCOMP, FILTER
def execute_probe(root, environment_only=False, debug=False, attempt=1):
if type(attempt) is not int or not 1 <= attempt <= 3 or (environment_only and attempt != 1):
raise ValueError("Invalid bounded qualification attempt")
profile = {} if environment_only else json.loads((root / "profile.json").read_text())
if type(profile.get("software_rendering", False)) is not bool:
raise ValueError("Invalid software-rendering profile")
mode = "environment" if environment_only else profile["mode"]
if mode not in (
"environment",
"initialization",
"synthetic-render",
"recorded-render",
"original-render",
):
raise ValueError("Unknown qualification profile")
if not environment_only:
verify_runtime(root)
binary = json.loads((root / "binary.json").read_text())
if digest(root / "probe") != binary["sha256"]:
raise ValueError("Qualification binary changed")
name = "environment" if environment_only else "debug" if debug else "run"
if attempt != 1:
name += "-" + str(attempt)
work = root / name
work.mkdir(mode=0o700)
(work / "logs").mkdir(mode=0o700)
if environment_only:
script = """import errno,json,os,socket,sys
for family in (socket.AF_INET,socket.AF_INET6,socket.AF_UNIX):
try: socket.socket(family,socket.SOCK_STREAM)
except OSError as error: assert error.errno==errno.EPERM
else: raise RuntimeError('Socket isolation failed')
try: open(sys.argv[1],'xb')
except OSError as error: assert error.errno==errno.EACCES
else: raise RuntimeError('Filesystem isolation failed')
for path in ('/home','/run','/dev/bus/usb'):
try: os.listdir(path)
except OSError as error: assert error.errno in (errno.EACCES,errno.ENOENT)
else: raise RuntimeError('Private/device directory isolation failed')
with open('write-check','xb') as output: output.write(b'owned sandbox data')
os.unlink('write-check')
assert os.geteuid()!=0
print(json.dumps({'network_blocked':True,'host_writes_blocked':True,'usb_blocked':True,'private_paths_blocked':True,'work_writable':True,'unprivileged':True}))
"""
command = ["/usr/bin/python3", "-c", script, str(root / "deny-write-probe")]
else:
command = [str(root / "probe"), str(work / "logs")]
if mode in ("synthetic-render", "recorded-render"):
command += [str(root / "input.bin"), str(root / "sdk/bin/models") + "/"]
if "stitch_type" in profile:
if profile["stitch_type"] not in ("dynamic", "template"):
raise ValueError("Invalid recorded-source stitch type")
command += [profile["stitch_type"]]
elif mode == "original-render":
original = json.loads((root / "original.json").read_text())
if (root / "original.insv").stat().st_size != original["bytes"] or digest(
root / "original.insv"
) != original["sha256"]:
raise ValueError("Original changed after verified export")
seconds = profile["original_seconds"]
if type(seconds) is not int or not 0 <= seconds <= 240:
raise ValueError("Invalid original sample time")
command += [
str(root / "original.insv"),
str(root / "sdk/bin/models") + "/",
str(seconds),
]
if debug:
if shutil.which("gdb") != "/usr/bin/gdb":
raise RuntimeError("The bounded diagnostic requires an already installed gdb")
# GDB traces only its own child. The child applies the exact sandbox
# before exec/loading any vendor code; no SDK runs in the debugger.
launcher = """import ctypes,hashlib,json,os,sys,zipfile
from pathlib import Path
with zipfile.ZipFile(sys.argv[1]) as z:
source=z.read('media_qualification.py');m=json.loads(z.read('manifest.json'))
assert hashlib.sha256(source).hexdigest()==m['files']['media_qualification.py']
ns={'__name__':'diagnostic_tracee'};exec(compile(source,'media_qualification.py','exec'),ns)
root,work=Path(sys.argv[2]),Path(sys.argv[3])
profile=json.loads((root/'profile.json').read_text())
assert ctypes.CDLL(None).prctl(1,9)==0
ns['restrict_process'](root,work,profile.get('software_rendering',False))
os.execve(sys.argv[4],sys.argv[4:],dict(os.environ))
"""
launcher_file = work / "tracee.py"
launcher_file.write_text(launcher)
command = [
"/usr/bin/gdb",
"--nx",
"--nh",
"--batch",
"-ex",
"set debuginfod enabled off",
"-ex",
"set auto-load off",
"-ex",
"set startup-with-shell off",
"-ex",
"set disable-randomization off",
"-ex",
"set pagination off",
"-ex",
"set confirm off",
"-ex",
"run",
"-ex",
"info program",
"-ex",
"thread apply all bt 16",
"--args",
"/usr/bin/python3",
"-I",
str(launcher_file),
str(Path(sys.argv[0]).resolve()),
str(root),
str(work),
*command,
]
report = {
"schema": SCHEMA,
"started": stamp(),
"scope": "isolation-only-no-sdk" if environment_only else mode + "-no-camera",
"real_camera_frame_verified": False,
"debugger_only": debug,
"attempt": attempt,
}
with (work / "stdout.log").open("xb") as stdout, (work / "stderr.log").open("xb") as stderr:
process = subprocess.Popen(
command,
stdout=stdout,
stderr=stderr,
start_new_session=True,
preexec_fn=None
if debug
else lambda: restrict_process(root, work, profile.get("software_rendering", False)),
cwd=work,
env={
"PATH": "/usr/bin:/bin",
"LANG": "C.UTF-8",
"OMP_NUM_THREADS": "2",
"OPENBLAS_NUM_THREADS": "2",
"LP_NUM_THREADS": "2",
"TMPDIR": str(work),
"XDG_CACHE_HOME": str(work),
"DEBUGINFOD_URLS": "",
# This versioned profile runs without the operator's display
# session. Mesa must create its offscreen context directly.
**(
{"EGL_PLATFORM": "surfaceless", "EGL_LOG_LEVEL": "debug"}
if mode in ("synthetic-render", "recorded-render", "original-render")
else {}
),
**(
{"LIBGL_ALWAYS_SOFTWARE": "true", "GALLIUM_DRIVER": "llvmpipe"}
if profile.get("software_rendering")
else {}
),
},
)
try:
report["debugger_exit_code" if debug else "exit_code"] = process.wait(
timeout=70 if debug else 45
)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
report["timeout"] = True
report["finished"] = stamp()
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
report["child_usage"] = {
"user_seconds": usage.ru_utime,
"system_seconds": usage.ru_stime,
"max_rss_kib": usage.ru_maxrss,
}
report["stdout"] = (work / "stdout.log").read_text(errors="replace")[-8192:]
report["stderr"] = (work / "stderr.log").read_text(errors="replace")[-8192:]
(root / (name + ".json")).write_text(json.dumps(report, indent=2))
print(json.dumps(report), flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"command",
choices=("stage", "compile", "run", "environment", "debug", "run-live", "source-live"),
)
parser.add_argument("--device-id")
parser.add_argument("--session-id")
parser.add_argument("--download-prefix", type=Path)
parser.add_argument("--reuse-stage", type=Path)
parser.add_argument("--attempt", type=int, choices=(1, 2, 3), default=1)
args = parser.parse_args()
if args.attempt != 1 and args.command not in ("run", "debug"):
raise ValueError("Repeated attempts apply only to isolated probe execution")
if (
platform.system() != "Linux"
or platform.machine() != "x86_64"
or (os.geteuid() == 0 and args.command != "source-live")
):
raise RuntimeError("Qualification requires the unprivileged Ubuntu x86_64 operator")
if not Path("/etc/os-release").read_text().startswith('PRETTY_NAME="Ubuntu 24.04'):
raise RuntimeError("This exploratory profile is scoped to the current Ubuntu 24.04 Mini")
with zipfile.ZipFile(sys.argv[0]) as artifact:
raw = artifact.read("manifest.json")
manifest = json.loads(raw)
ident = hashlib.sha256(raw).hexdigest()[:24]
if Path(sys.argv[0]).name != f"mission-core-x4-media-qualify-{ident}.pyz":
raise ValueError("Qualification artifact identity mismatch")
files = {name: artifact.read(name) for name in manifest["files"]}
if any(
hashlib.sha256(data).hexdigest() != manifest["files"][name]
for name, data in files.items()
):
raise ValueError("Qualification source checksum mismatch")
live = args.command in ("source-live", "run-live")
if live:
if (
json.loads(files["profile.json"])["mode"] != "live-render"
or not isinstance(args.device_id, str)
or not re.fullmatch(r"instax4_[0-9a-f]{32}", args.device_id)
or not isinstance(args.session_id, str)
or not re.fullmatch(r"x4_[0-9a-f]{32}", args.session_id)
):
raise ValueError("Live qualification needs an exact admitted camera/session")
elif args.device_id is not None or args.session_id is not None:
raise ValueError("Camera identities only apply to live qualification")
if args.command == "source-live":
from media_live_source import main as source_main
source_main(args.device_id, args.session_id)
return
root = Path("/var/tmp") / ("mission-core-x4-media-" + ident)
if root.is_symlink():
raise ValueError("Qualification staging cannot be a symlink")
root.mkdir(mode=0o700, exist_ok=True)
if root.stat().st_uid != os.geteuid() or root.stat().st_mode & 0o077:
raise ValueError("Qualification staging ownership changed")
lock = (root / "qualification.lock").open("a")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
if args.download_prefix:
expected = Path(
"/var/tmp/mission-core-x4-media-b47176f7987d48427af11997/vendor.zip.partial"
)
if args.command != "stage" or args.download_prefix != expected or expected.is_symlink():
raise ValueError("Only the inspected previous transfer may be resumed")
parent = expected.parent
if (
parent.is_symlink()
or parent.stat().st_uid != os.geteuid()
or parent.stat().st_mode & 0o077
):
raise ValueError("Unsafe previous transfer directory")
old = b"/var/tmp/mission-core-x4-media-qualify-b47176f7987d48427af11997.pyz"
for proc in Path("/proc").glob("[0-9]*/cmdline"):
try:
if old in proc.read_bytes().split(b"\0"):
raise ValueError("Previous transfer is still running")
except (FileNotFoundError, PermissionError):
continue
if args.reuse_stage and args.command != "stage":
raise ValueError("Runtime reuse is a staging operation")
if args.command == "stage":
if shutil.disk_usage(root).free < 16 * 1024**3:
raise RuntimeError("Insufficient free space for the bounded SDK qualification")
for name, data in files.items():
if name.startswith(("include/", "compat/")) or name in (
"media_probe.cpp",
"profile.json",
"input.bin",
"original.json",
):
target = root / name
target.parent.mkdir(mode=0o700, exist_ok=True)
target.write_bytes(data)
if "original.json" in files:
original = json.loads(files["original.json"])
source = Path(original["path"])
owner_root = (
Path(pwd.getpwuid(os.geteuid()).pw_dir)
/ ".local/share/mission-core/qualifications/x4-originals"
)
if (
source.parent != owner_root
or source.is_symlink()
or not re.fullmatch(r"file_[0-9a-f]{32}\.insv", source.name)
or source.stat().st_uid != os.geteuid()
or source.stat().st_mode & 0o077
or source.stat().st_size != original["bytes"]
or not 0 < original["bytes"] <= 8 * 1024**3
or digest(source) != original["sha256"]
):
raise ValueError("Original is not the verified owner-private export")
os.link(source, root / "original.insv")
if args.reuse_stage:
source = args.reuse_stage
expected = Path("/var/tmp/mission-core-x4-media-4c930fafc280d49210dd2d4d")
if (
source != expected
or source.is_symlink()
or source.stat().st_uid != os.geteuid()
or source.stat().st_mode & 0o077
):
raise ValueError("Unexpected prior SDK qualification stage")
verify_runtime(source)
if digest(source / "vendor.zip") != ARCHIVE_SHA:
raise ValueError("Prior archive checksum changed")
(root / "sdk").mkdir(mode=0o700)
previous = json.loads((source / "runtime.json").read_text())
for item in previous["files"]:
target = root / "sdk" / item["path"]
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
os.link(source / "sdk" / item["path"], target)
os.link(source / "vendor.zip", root / "vendor.zip")
(root / "runtime.json").write_text(json.dumps(previous, indent=2))
archive = source_archive(root, args.download_prefix)
if not (root / "runtime.json").exists():
rows = extract_runtime(archive, root / "sdk")
(root / "runtime.json").write_text(
json.dumps({"archive_sha256": ARCHIVE_SHA, "files": rows, **stamp()}, indent=2)
)
verify_runtime(root)
print(json.dumps({"phase": "staged", "root": str(root), **stamp()}), flush=True)
elif args.command == "compile":
for name, data in files.items():
if (
name.startswith(("include/", "compat/"))
or name in ("media_probe.cpp", "profile.json", "input.bin", "original.json")
) and (root / name).read_bytes() != data:
raise ValueError("Staged qualification source changed")
compile_probe(root)
print(json.dumps({"phase": "compiled", "root": str(root), **stamp()}), flush=True)
else:
if args.command in ("run", "debug", "run-live"):
for name, data in files.items():
if (
name.startswith("compat/")
or name in ("profile.json", "input.bin", "original.json")
) and (root / name).read_bytes() != data:
raise ValueError("Compatibility dependency changed")
if args.command == "run-live":
from media_live_qualification import execute_live
execute_live(root, args.device_id, args.session_id)
else:
execute_probe(
root,
environment_only=args.command == "environment",
debug=args.command == "debug",
attempt=args.attempt,
)
if __name__ == "__main__":
main()
@@ -11,6 +11,8 @@ import tempfile
import zipfile
from pathlib import Path
NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb', 'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb')
PROFILES = {
"missioncore.insta360.owner-release/v1": (
"mission-core-insta360-x4",
@@ -83,6 +85,9 @@ def main():
package = package_id + "_" + version + "_amd64.deb"
if hashlib.sha256(archive.read("__main__.py")).hexdigest() != manifest["entrypoint_sha256"]:
raise ValueError("Release entry point changed")
dependencies = manifest.get("dependencies", [])
if dependencies and (manifest["schema"] != "missioncore.node.owner-release/v1" or dependencies != list(NODE_DEPENDENCIES)):
raise ValueError("Unexpected release dependencies")
allowed = {
"release.json",
"__main__.py",
@@ -90,6 +95,7 @@ def main():
"install_release.py",
package,
}
allowed.update(dependencies)
if set(archive.namelist()) != allowed or len(archive.namelist()) != len(allowed):
raise ValueError("Invalid release contents")
if set(manifest["files"]) != allowed - {"release.json", "__main__.py"}:
@@ -117,6 +123,7 @@ def main():
"--simulate",
"--no-remove",
"install",
*[str(folder / name) for name in dependencies],
str(folder / package),
],
capture_output=True,
+52 -33
View File
@@ -91,6 +91,57 @@ def bindings():
return {ident: value for ident, value in found.items() if ident not in duplicates}
def reconcile(known, startup=False):
observed = bindings()
current = {
ident: {
"port": item.port,
"bus": item.bus,
"address": item.address,
"revision": active().name,
}
for ident, item in observed.items()
}
changed = False
for ident in list(known):
if current.get(ident) != known[ident]:
systemctl("stop", PREFIX + ident + ".service")
path = UNITS / (PREFIX + ident + ".service")
if path.exists():
trusted(path).unlink()
del known[ident]
changed = True
additions = [ident for ident in current if ident not in known]
for ident in additions:
item = observed[ident]
try:
if read_binding(item.port) != item:
continue
except (OSError, ValueError):
# Enumeration and revalidation are separate sysfs reads.
continue
write(UNITS / (PREFIX + ident + ".service"), unit(item))
known[ident] = current[ident]
changed = True
if changed:
write(CONTROL / "bindings.json", json.dumps(known, sort_keys=True).encode())
systemctl("daemon-reload")
for ident in list(current) if startup else additions:
if ident in known:
try:
systemctl("start", PREFIX + ident + ".service")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
# A disappearing BindPaths node can fail unit setup. Keep supervising
# other cameras; retry this one only after its USB binding changes.
# A timed-out start may still succeed, so never replay it blindly.
print(
f"X4 worker start on USB {observed[ident].port} failed "
f"({type(exc).__name__}); waiting for a new USB binding",
file=sys.stderr,
flush=True,
)
def main():
if os.geteuid() or len(sys.argv) != 1:
raise RuntimeError("Use the fixed installed supervisor unit")
@@ -116,39 +167,7 @@ def main():
raise RuntimeError("Invalid previous camera binding")
known[ident] = info
while not stopping:
observed = bindings()
current = {
ident: {
"port": item.port,
"bus": item.bus,
"address": item.address,
"revision": active().name,
}
for ident, item in observed.items()
}
changed = False
for ident in list(known):
if current.get(ident) != known[ident]:
systemctl("stop", PREFIX + ident + ".service")
path = UNITS / (PREFIX + ident + ".service")
if path.exists():
trusted(path).unlink()
del known[ident]
changed = True
additions = [ident for ident in current if ident not in known]
for ident in additions:
item = observed[ident]
if read_binding(item.port) != item:
continue
write(UNITS / (PREFIX + ident + ".service"), unit(item))
known[ident] = current[ident]
changed = True
if changed:
write(record, json.dumps(known, sort_keys=True).encode())
systemctl("daemon-reload")
for ident in list(current) if startup else additions:
if ident in known:
systemctl("start", PREFIX + ident + ".service")
reconcile(known, startup=startup)
startup = False
time.sleep(1)
@@ -0,0 +1,297 @@
"""Installer acquisition race checks; no OS, camera or package changes."""
import hashlib
import importlib.util
import io
import json
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
spec = importlib.util.spec_from_file_location(
"x4_installer", Path(__file__).with_name("install_release.py")
)
owner = importlib.util.module_from_spec(spec)
spec.loader.exec_module(owner)
CAMERA = {
"id": "instax4_" + "a" * 32,
"session_id": "x4_session",
"online": True,
"preparation_safe": True,
}
PATH = Path("/run/mission-core-x4-instances") / CAMERA["id"] / "driver.sock"
class OriginalExportTests(unittest.TestCase):
def test_invalid_source_and_missing_owner_stop_before_download(self):
with patch.object(owner, "request") as request:
for source in ("/etc/passwd", "https://camera/file.insv"):
with self.assertRaises(ValueError):
owner.verify_original(PATH, CAMERA, source)
with (
patch.dict(owner.os.environ, {"SUDO_UID": "0"}),
self.assertRaises(RuntimeError),
):
owner.verify_original(PATH, CAMERA, "/DCIM/test.insv")
request.assert_not_called()
def test_export_drops_all_privileges_and_confirms_owner_hash(self):
digest = hashlib.sha256(b"original").hexdigest()
result = {"state": "complete", "bytes": 8, "sha256": digest}
child = Mock(returncode=0)
child.stdin.closed = False
child.stdout = io.BytesIO(json.dumps(dict(result, path="/owner/private.insv")).encode())
child.stderr = io.BytesIO()
with (
patch.dict(owner.os.environ, {"SUDO_UID": "1000"}),
patch.object(owner.pwd, "getpwuid", return_value=Mock(pw_gid=1000)),
patch.object(owner, "request", side_effect=[result, b"original"]),
patch.object(owner.subprocess, "Popen", return_value=child) as process,
):
value = owner.verify_original(PATH, CAMERA, "/DCIM/test.insv")
self.assertEqual(value["sha256"], digest)
self.assertEqual(process.call_args.kwargs["user"], 1000)
self.assertEqual(process.call_args.kwargs["group"], 1000)
self.assertEqual(process.call_args.kwargs["extra_groups"], [])
child.stdin.write.assert_called_once_with(b"original")
compile(owner.OWNER_ORIGINAL_EXPORT, "owner-original-export", "exec")
class PauseTests(unittest.TestCase):
def setUp(self):
self.prepare = patch.object(owner, "PREPARE", Mock())
self.marker = patch.object(owner, "MAINTENANCE", Mock())
self.instances = patch.object(owner, "INSTANCES", Mock())
self.prepare.start().exists.return_value = True
self.marker.start().exists.return_value = False
self.instances.start().glob.return_value = [PATH]
self.addCleanup(patch.stopall)
self.report = {}
self.actions = []
def request(self, path, command=None):
if command is None:
return dict(CAMERA)
self.actions.append(command["action_id"])
if command["action_id"] == "details":
return {"state": "complete", "result": {"recording": 0, "preview": 1}}
return {"state": "complete"}
def test_preview_is_paused_after_authentication_and_gate_is_acquired(self):
run = Mock()
with patch.object(owner, "request", side_effect=self.request):
self.assertTrue(owner.pause_previews(run, self.report, Mock()))
self.assertEqual(self.actions, ["details", "preview.stop"])
self.assertEqual(run.call_args.args[1][-1], "--quiesce")
self.assertEqual(self.report["preview_pause"]["state"], "complete")
def test_recording_or_unknown_recording_blocks_before_any_stop(self):
for recording in (1, None):
run = Mock()
with patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": recording, "preview": 1}},
],
) as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(run, {}, Mock())
self.assertEqual(request.call_count, 2)
run.assert_not_called()
def test_all_cameras_are_checked_before_first_pause(self):
second = dict(CAMERA, id="instax4_" + "b" * 32)
owner.INSTANCES.glob.return_value = [
PATH,
PATH.parent.parent / second["id"] / "driver.sock",
]
with patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": 0, "preview": 1}},
second,
{"state": "complete", "result": {"recording": 1}},
],
) as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(Mock(), {}, Mock())
actions = [
call.args[1]["action_id"] for call in request.call_args_list if len(call.args) > 1
]
self.assertEqual(actions, ["details", "details"])
def test_unknown_stop_result_is_not_retried(self):
run = Mock()
with (
patch.object(
owner,
"request",
side_effect=[
CAMERA,
{"state": "complete", "result": {"recording": 0, "preview": 1}},
{"state": "unknown"},
],
),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, self.report, Mock())
run.assert_not_called()
def test_viewer_restart_before_gate_rechecks_camera_and_has_bounded_retry(self):
run = Mock(side_effect=[RuntimeError("busy"), None])
with patch.object(owner, "request", side_effect=self.request):
self.assertTrue(owner.pause_previews(run, self.report, Mock()))
self.assertEqual(self.actions, ["details", "preview.stop"] * 2)
run = Mock(side_effect=RuntimeError("busy"))
with (
patch.object(owner, "request", side_effect=self.request),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, {}, Mock())
self.assertEqual(run.call_count, 3)
def test_existing_maintenance_is_not_overwritten(self):
owner.MAINTENANCE.exists.return_value = True
with patch.object(owner, "request") as request:
with self.assertRaises(RuntimeError):
owner.pause_previews(Mock(), {}, Mock())
request.assert_not_called()
def test_no_driver_is_a_clean_host_noop(self):
owner.PREPARE.exists.return_value = False
run = Mock()
self.assertFalse(owner.pause_previews(run, {}, Mock()))
run.assert_not_called()
def test_gate_with_unknown_outcome_is_not_retried(self):
run = Mock(side_effect=RuntimeError("lost reply"))
owner.MAINTENANCE.exists.side_effect = [False, True]
with (
patch.object(owner, "request", side_effect=self.request),
self.assertRaises(RuntimeError),
):
owner.pause_previews(run, {}, Mock())
self.assertEqual(run.call_count, 1)
class StitchSampleTests(unittest.TestCase):
@staticmethod
def packet(cursor=1, **changes):
header = dict(
cursor=cursor,
generation=2,
timestamp=1234,
stream_index=0,
stream_type=0x20,
codec=0,
calibration_revision=4,
bytes=3,
gap=False,
)
header.update(changes)
raw = owner.json.dumps(header).encode()
return owner.struct.pack("!I", len(raw)) + raw + b"raw"
def test_original_bytes_and_vendor_marker_survive(self):
header, data = owner.stitch_packet(self.packet(), 4, 0, None)
self.assertEqual(data, b"raw")
self.assertEqual(header["stream_type"], 0x20)
self.assertEqual(header["codec"], 0)
def test_revision_generation_cursor_gaps_and_types_fail_closed(self):
for changes in (
{"calibration_revision": 5},
{"generation": 3},
{"gap": True},
{"cursor": 8},
{"stream_type": 256},
{"bytes": 2},
{"timestamp": True},
):
with self.assertRaises(ValueError):
owner.stitch_packet(
self.packet(cursor=2, **changes)
if "cursor" not in changes
else self.packet(**changes),
4,
1,
2,
)
def test_capture_failure_stops_only_its_preview(self):
actions = []
def request(path, command=None, **kwargs):
action = command["action_id"]
actions.append(action)
if action == "details":
return {"state": "complete", "result": {"recording": 0, "preview": 0}}
return {"state": "complete"}
with patch.object(owner, "request", side_effect=request), self.assertRaises(RuntimeError):
owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(actions, ["details", "preview.start", "details", "preview.stop"])
def test_capture_preserves_existing_preview_on_failure(self):
actions = []
def request(path, command=None, **kwargs):
actions.append(command["action_id"])
return {"state": "complete", "result": {"recording": 0, "preview": 1}}
with patch.object(owner, "request", side_effect=request), self.assertRaises(RuntimeError):
owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(actions, ["details", "details"])
def test_capture_records_exact_consistent_packets_and_restores_idle(self):
calibration = {"revision": 4, "offsets": ["factory"]}
actions, counter = [], 0
def request(path, command=None, **kwargs):
nonlocal counter
if kwargs.get("video"):
counter += 1
return self.packet(counter)
action = command["action_id"]
actions.append(action)
return {
"state": "complete",
"result": {"recording": 0, "preview": 0, "preview_calibration": calibration},
}
with patch.object(owner, "request", side_effect=request):
sample = owner.capture_stitch_input(PATH, CAMERA)
self.assertEqual(len(sample["packets"]), 128)
self.assertEqual(sample["calibration"], calibration)
self.assertEqual(owner.base64.b64decode(sample["packets"][0]["data"]), b"raw")
self.assertFalse(sample["gyro_exposure_forwarded"])
self.assertEqual(actions[-1], "preview.stop")
class ExactPackagePlanTests(unittest.TestCase):
def test_only_requested_upgrade_or_already_installed_is_admitted(self):
owner.admit_package_plan(
b"Inst mission-core-insta360-x4 [0.1.3-11] (0.1.3-12 local-deb [amd64])\n"
b"Conf mission-core-insta360-x4 (0.1.3-12 local-deb [amd64])",
"0.1.3-12",
)
owner.admit_package_plan(b"0 upgraded, 0 newly installed, 0 to remove", "0.1.3-12")
def test_unrelated_install_configure_remove_and_wrong_version_fail(self):
for text in (
"Inst unrelated (1 local [amd64])",
"Conf unrelated (1 local [amd64])",
"Remv unrelated [1]",
"Purg mission-core-insta360-x4 [0.1.3-11]",
"Inst mission-core-insta360-x4 [0.1.3-11] (0.1.3-13 local-deb [amd64])",
):
with self.assertRaises(RuntimeError):
owner.admit_package_plan(text.encode(), "0.1.3-12")
if __name__ == "__main__":
unittest.main()