Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
770 lines
32 KiB
Python
770 lines
32 KiB
Python
"""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()
|