"""Fetch pinned upstream addons for personal installation; never mirror them.""" import hashlib import json import os from pathlib import Path, PurePosixPath import re import shutil import stat import urllib.parse import urllib.request import zipfile def digest(path): h = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): h.update(block) return h.hexdigest() def no_links(path): path = Path(path).absolute() if any(p.is_symlink() for p in (path, *path.parents)): raise ValueError('Use a real folder, not a symbolic link: ' + str(path)) def safe_relative(value): if not isinstance(value, str) or not value or '\\' in value or ':' in value: raise ValueError('Unsafe archive/package path') rel = PurePosixPath(value.rstrip('/')) if rel.is_absolute() or not rel.parts or any(p in ('', '.', '..') for p in value.rstrip('/').split('/')): raise ValueError('Unsafe archive/package path: ' + value) for part in rel.parts: if part.endswith((' ', '.')) or re.search(r'[\x00-\x1f<>"|?*]', part): raise ValueError('Unsupported Windows filename: ' + value) if re.fullmatch(r'(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', part, re.I): raise ValueError('Reserved Windows filename: ' + value) return Path(*rel.parts) def selected(bundle, voices): if voices not in ('none', 'en', 'enru'): raise ValueError('Voice packs must be none, en, or enru') lock = json.loads((Path(bundle) / 'dependencies.lock.json').read_text()) if lock.get('format') != 1 or lock.get('interface') != 16001: raise ValueError('Unsupported dependency lock') groups = {'base'} | ({'en'} if voices != 'none' else set()) | ({'ru'} if voices == 'enru' else set()) packages = [p for p in lock['packages'] if p['group'] in groups] folders = set() for p in packages: if not re.fullmatch(r'[A-Za-z0-9_]+', p['id']) or not re.fullmatch(r'[0-9a-f]{64}', p['sha256']): raise ValueError('Invalid dependency identity') if urllib.parse.urlsplit(p['url']).scheme != 'https' or not 0 < p['bytes'] <= 2_000_000_000: raise ValueError('Invalid dependency URL or size') for name in p['folders']: if not re.fullmatch(r'[A-Za-z0-9_]+', name) or name in folders or name == 'RuenUI': raise ValueError('Invalid or duplicate addon folder') folders.add(name) return packages def compatible(folder): toc = Path(folder) / (Path(folder).name + '.toc') return toc.is_file() and bool(re.search(r'^## Interface:.*\b16001\b', toc.read_text(encoding='utf-8-sig'), re.M)) def download(package, cache): cache = Path(cache); no_links(cache); cache.mkdir(parents=True, exist_ok=True) target = cache / (package['id'] + '-' + package['sha256'][:12] + '.zip') no_links(target) if target.is_file() and target.stat().st_size == package['bytes'] and digest(target) == package['sha256']: return target # Keep one verified archive per package; other applications' files are untouched. for stale in cache.glob(package['id'] + '-*.zip'): if stale != target and re.fullmatch(re.escape(package['id']) + r'-[0-9a-f]{12}\.zip', stale.name): no_links(stale); stale.unlink() required = package['bytes'] + package['max_unpacked_bytes'] + 128 * 1024 * 1024 if shutil.disk_usage(cache).free < required: raise OSError('Not enough free space to download and unpack ' + package['id']) part = target.with_suffix('.part'); no_links(part) print('Downloading ' + package['id'] + ' (' + str(round(package['bytes'] / 1_000_000)) + ' MB)...', flush=True) try: request = urllib.request.Request(package['url'], headers={'User-Agent': 'RuenUI-Installer/1'}) with urllib.request.urlopen(request, timeout=60) as response, part.open('wb') as out: if urllib.parse.urlsplit(response.url).scheme != 'https': raise ValueError('Refusing a non-HTTPS download redirect') total = 0 while True: block = response.read(1024 * 1024) if not block: break total += len(block) if total > package['bytes']: raise ValueError('Download exceeds pinned size') out.write(block) if part.stat().st_size != package['bytes'] or digest(part) != package['sha256']: raise ValueError('Dependency checksum mismatch: ' + package['id']) os.replace(part, target) return target finally: if part.exists(): part.unlink() def extract(package, archive, stage): stage = Path(stage); no_links(stage); stage.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(archive) as z: entries = z.infolist(); total = 0; seen = set() if len(entries) > 100_000: raise ValueError('Archive has too many entries') for entry in entries: rel = safe_relative(entry.filename) key = rel.as_posix().casefold() if key in seen: raise ValueError('Duplicate archive filename: ' + entry.filename) seen.add(key) mode = entry.external_attr >> 16 if stat.S_ISLNK(mode): raise ValueError('Archive links are not allowed') total += entry.file_size if total > package['max_unpacked_bytes']: raise ValueError('Archive expands beyond its limit') if shutil.disk_usage(stage).free < total + 128 * 1024 * 1024: raise OSError('Not enough free space to unpack ' + package['id']) for entry in entries: rel = safe_relative(entry.filename) if rel.parts[0] not in package['folders']: continue target = stage / rel; no_links(target) if entry.is_dir(): target.mkdir(parents=True, exist_ok=True); continue target.parent.mkdir(parents=True, exist_ok=True) with z.open(entry) as src, target.open('wb') as dst: shutil.copyfileobj(src, dst) for folder in package['folders']: if not compatible(stage / folder): raise ValueError('Dependency is missing its Forever TOC: ' + folder) def prepare(bundle, game, stage, voices, cache): packages = selected(bundle, voices) sources = {'RuenUI': Path(bundle) / 'RuenUI'} enabled = ['RuenUI'] for package in packages: missing = [] for folder in package['folders']: target = Path(game) / 'Interface/AddOns' / folder; no_links(target) if target.exists(): if not compatible(target): raise ValueError('Existing ' + folder + ' is not marked compatible with Forever; update it from its author first.') print('Keeping existing ' + folder, flush=True) else: missing.append(folder) enabled.append(folder) if missing: extract(package, download(package, cache), stage) for folder in missing: sources[folder] = Path(stage) / folder return sources, enabled