Files
WoW-Hybrid-gateway/ops/codec_input_bundle.py

68 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Verify or restore pinned codec source inputs. Never compiles or installs."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
import tarfile
import tempfile
ROOT = Path(__file__).resolve().parents[1]
DEFAULT = ROOT / 'base-inputs/codec-recovery-20261129.json'
def verify(pin=DEFAULT, output=None):
pin = Path(pin).resolve()
metadata = json.loads(pin.read_text())
archive = pin.parent / metadata['archive']
if archive.is_symlink() or hashlib.file_digest(archive.open('rb'), 'sha256').hexdigest() != metadata['sha256']:
raise ValueError('Codec input archive differs')
expected = metadata['files']
if len(expected) > 1024 or sum(row['bytes'] for row in expected.values()) > 512 * 1024 * 1024:
raise ValueError('Codec input inventory exceeds bound')
seen = set()
with tarfile.open(archive, 'r:gz') as bundle:
for member in bundle:
name = member.name
path = PurePosixPath(name)
if not member.isfile() or path.is_absolute() or '..' in path.parts or str(path) != name or name in seen or name not in expected:
raise ValueError('Unexpected codec input member')
row = expected[name]
if member.size != row['bytes'] or not 0 <= member.size <= 134217728:
raise ValueError('Codec input member size differs')
with bundle.extractfile(member) as source:
if hashlib.file_digest(source, 'sha256').hexdigest() != row['sha256']:
raise ValueError('Codec input member digest differs')
if output is not None:
target = Path(output) / name
target.parent.mkdir(parents=True, exist_ok=True)
with bundle.extractfile(member) as source, target.open('xb') as sink:
shutil.copyfileobj(source, sink)
seen.add(name)
if seen != set(expected):
raise ValueError('Codec input members missing')
return metadata
def restore(destination, pin=DEFAULT):
destination = Path(destination).absolute()
if destination.exists():
raise ValueError('Fresh restore destination required')
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.codec-inputs-', dir=destination.parent) as staging:
verify(pin, staging)
Path(staging).rename(destination)
return destination
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--pin', type=Path, default=DEFAULT)
parser.add_argument('--restore', type=Path)
args = parser.parse_args()
if args.restore:
print('Restored pinned codec inputs to', restore(args.restore, args.pin))
else:
metadata = verify(args.pin)
print('Verified', len(metadata['files']), 'pinned codec input files; no build or install.')
if __name__ == '__main__':
main()