#!/usr/bin/env python3 """Fetch exactly the reviewed vendor release into a portable local catalog.""" import argparse import hashlib import os import tempfile import time import urllib.request from pathlib import Path from k1link.fleet.netbird.assets import LOCK, directory, verify def publish(root: Path, identifiers: list[str]) -> None: folder = directory(root) folder.mkdir(parents=True, exist_ok=True, mode=0o700) for row in LOCK["items"]: if identifiers and row["id"] not in identifiers: continue try: verify(root, row["id"]) print(row["id"], "already verified", flush=True) continue except (OSError, ValueError): pass fd, temporary = tempfile.mkstemp(prefix=".download-", dir=folder) try: digest, count, deadline = hashlib.sha256(), 0, time.monotonic() + 600 with ( os.fdopen(fd, "wb") as output, urllib.request.urlopen( urllib.request.Request( row["source_url"], headers={"User-Agent": "MissionCoreRelease"} ), timeout=30, ) as source, ): while chunk := source.read(256 * 1024): count += len(chunk) if count > row["bytes"] or time.monotonic() > deadline: raise ValueError("Download size/time limit") digest.update(chunk) output.write(chunk) output.flush() os.fsync(output.fileno()) if count != row["bytes"] or digest.hexdigest() != row["sha256"]: raise ValueError("Vendor checksum mismatch") os.replace(temporary, folder / row["filename"]) verify(root, row["id"]) print(row["id"], count, "verified", flush=True) finally: Path(temporary).unlink(missing_ok=True) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--fleet-root", required=True, type=Path) parser.add_argument( "--client", action="append", choices=[r["id"] for r in LOCK["items"]], default=[] ) arguments = parser.parse_args() publish(arguments.fleet_root, arguments.client)