403 lines
19 KiB
Python
403 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Conservative interactive installer, embedded into the published shell and PowerShell launchers."""
|
|
import argparse
|
|
import configparser
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
import shutil
|
|
import signal
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from urllib.parse import quote
|
|
import xml.etree.ElementTree as ET
|
|
|
|
BASE_URL = 'https://assets.dandaedre.com/mtg/'
|
|
MAX_DOWNLOAD = 64 * 1024 * 1024
|
|
|
|
|
|
def say(message):
|
|
print(message, flush=True)
|
|
|
|
|
|
def prompt(message):
|
|
try:
|
|
if sys.platform == 'win32':
|
|
with open('CONIN$', 'r') as reader, open('CONOUT$', 'w') as writer:
|
|
writer.write(message + ' ')
|
|
writer.flush()
|
|
answer = reader.readline()
|
|
if not answer:
|
|
raise ValueError('No answer received; installation cancelled.')
|
|
return answer.strip()
|
|
# Separate streams work on non-seekable terminals, unlike text mode r+.
|
|
with open('/dev/tty', 'r') as reader, open('/dev/tty', 'w') as writer:
|
|
writer.write(message + ' ')
|
|
writer.flush()
|
|
answer = reader.readline()
|
|
except OSError as error:
|
|
raise ValueError('Interactive terminal required; no files installed. Run from a terminal.') from error
|
|
if not answer:
|
|
raise ValueError('No answer received; installation cancelled.')
|
|
return answer.strip()
|
|
|
|
|
|
def confirm(message):
|
|
if prompt(message + ' [y/N]').lower() not in ('y', 'yes'):
|
|
raise ValueError('Installation cancelled; approval was not given.')
|
|
|
|
|
|
def safe_path(path):
|
|
if not path.is_absolute() or path == Path(path.anchor) or path.resolve() != path:
|
|
raise ValueError(f'Unsafe path (must be absolute without symlinks or ..): {path}')
|
|
for part in (path, *path.parents):
|
|
if part.is_symlink() or (part.exists() and getattr(part.lstat(), 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT):
|
|
raise ValueError(f'Symlink paths are not supported: {part}')
|
|
if part != path and part.exists() and not part.is_dir():
|
|
raise ValueError(f'Parent path is not a directory: {part}')
|
|
return path
|
|
|
|
|
|
def discover(home, environment):
|
|
if sys.platform == 'win32':
|
|
candidates = []
|
|
for variable in ('LOCALAPPDATA', 'APPDATA'):
|
|
if environment.get(variable):
|
|
base = Path(environment[variable])
|
|
candidates.extend([base / 'Cockatrice/Cockatrice', base / 'Cockatrice'])
|
|
return list(dict.fromkeys(path for path in candidates
|
|
if (path / 'cards.xml').is_file() or (path / 'settings').is_dir()))
|
|
data = Path(environment.get('XDG_DATA_HOME') or home / '.local/share')
|
|
candidates = [data / 'Cockatrice/Cockatrice', home / '.local/share/Cockatrice/Cockatrice',
|
|
home / '.var/app/io.github.Cockatrice.cockatrice/data/Cockatrice/Cockatrice',
|
|
home / '.var/app/io.cockatrice.Cockatrice/data/Cockatrice/Cockatrice',
|
|
home / 'Library/Application Support/Cockatrice/Cockatrice',
|
|
home / 'Library/Application Support/Cockatrice']
|
|
legacy = data / 'Cockatrice'
|
|
if (legacy / 'cards.xml').is_file() or (legacy / 'settings').is_dir():
|
|
candidates.append(legacy)
|
|
return list(dict.fromkeys(path for path in candidates if path.exists() or path.is_symlink()))
|
|
|
|
|
|
def select_install(home, environment, explicit=None):
|
|
candidates = [explicit] if explicit else discover(home, environment)
|
|
if not candidates:
|
|
raise ValueError('No Cockatrice data directory found. Install and launch Cockatrice once, '
|
|
'then retry, or pass --data-dir /absolute/path/to/Cockatrice/data. '
|
|
'Cockatrice itself will not be installed by this script.')
|
|
if len(candidates) > 1:
|
|
say('Multiple possible Cockatrice installations found; no location will be guessed:')
|
|
for index, path in enumerate(candidates, 1):
|
|
say(f' {index}. {path}')
|
|
choice = prompt('Select the installation number, or press Enter to abort:')
|
|
if not choice.isdigit() or not 1 <= int(choice) <= len(candidates):
|
|
raise ValueError('Invalid selection; installation aborted.')
|
|
root = candidates[int(choice) - 1]
|
|
else:
|
|
root = candidates[0]
|
|
safe_path(root)
|
|
if not root.is_dir() or not ((root / 'cards.xml').is_file() or (root / 'settings').is_dir()):
|
|
raise ValueError(f'Not a recognized Cockatrice data directory: {root}. '
|
|
'Choose the folder containing cards.xml or settings/ (the parent of customsets/ and pics/). '
|
|
'For Flatpak use ~/.var/app/io.github.Cockatrice.cockatrice/data/Cockatrice/Cockatrice/, '
|
|
'not data/ or data/Cockatrice/. Launch Cockatrice once first.')
|
|
for marker in (root / 'cards.xml', root / 'settings'):
|
|
if marker.is_symlink():
|
|
raise ValueError(f'Symlinked installation marker is not supported: {marker}')
|
|
destinations = {'customsets': root / 'customsets', 'pics': root / 'pics'}
|
|
settings = root / 'settings/paths.ini'
|
|
if settings.exists() or settings.is_symlink():
|
|
safe_path(settings)
|
|
config = configparser.ConfigParser(interpolation=None, strict=True)
|
|
with settings.open() as stream:
|
|
config.read_file(stream)
|
|
for key in destinations:
|
|
value = config.get('paths', key, fallback='').strip()
|
|
if value:
|
|
destinations[key] = Path(value)
|
|
for kind, path in destinations.items():
|
|
safe_path(path)
|
|
if path.exists() and not path.is_dir():
|
|
raise ValueError(f'{kind} destination is not a directory: {path}')
|
|
ancestor = path
|
|
while not ancestor.exists():
|
|
ancestor = ancestor.parent
|
|
if not os.access(ancestor, os.W_OK | os.X_OK):
|
|
raise ValueError(f'Cannot write to {kind} destination: {path}')
|
|
if not path.exists():
|
|
confirm(f'Cockatrice data found at {root}, but {path} is missing. Create this folder?')
|
|
return root, destinations
|
|
|
|
|
|
def download(relative, target, limit):
|
|
url = BASE_URL + quote(relative, safe='/')
|
|
say(f'Downloading {url}\n temporary file: {target}')
|
|
command = ['curl.exe' if sys.platform == 'win32' else 'curl', '--fail', '--show-error', '--silent', '--proto', '=https',
|
|
'--connect-timeout', '15', '--max-time', '180', '--max-filesize', str(limit),
|
|
'--output', str(target), url]
|
|
result = subprocess.run(command, check=False)
|
|
if result.returncode:
|
|
raise ValueError(f'Download failed (curl exit {result.returncode}): {url}. Nothing installed.')
|
|
if not target.is_file() or not 0 < target.stat().st_size <= limit:
|
|
raise ValueError(f'Download is empty, missing, or too large: {url}')
|
|
|
|
|
|
def validate_manifest(data, destinations):
|
|
manifest = json.loads(data)
|
|
if not isinstance(manifest, dict) or manifest.get('version') != 1:
|
|
raise ValueError('Unsupported installer manifest')
|
|
entries = manifest.get('files')
|
|
if not isinstance(entries, list) or not entries or len(entries) > 10000:
|
|
raise ValueError('Manifest must contain 1 to 10000 files')
|
|
seen = set()
|
|
checked = []
|
|
for entry in entries:
|
|
if not isinstance(entry, dict):
|
|
raise ValueError('Invalid manifest file entry')
|
|
source, destination = entry.get('source'), entry.get('destination')
|
|
for value in (source, destination):
|
|
if not isinstance(value, str) or any(ord(c) < 32 for c in value) or '\\' in value:
|
|
raise ValueError('Invalid manifest path')
|
|
path = PurePosixPath(value)
|
|
if path.is_absolute() or '..' in path.parts or str(path) != value:
|
|
raise ValueError(f'Unsafe manifest path: {value}')
|
|
src, dest = PurePosixPath(source), PurePosixPath(destination)
|
|
if (len(src.parts) != 2 or src.parts[0] not in ('xml', 'cards') or
|
|
len(dest.parts) < 2 or dest.parts[0] not in destinations):
|
|
raise ValueError('Manifest contains unsupported source or destination')
|
|
if src.parts[0] == 'xml':
|
|
if dest.parts[0] != 'customsets' or len(dest.parts) != 2 or src.suffix != '.xml' or dest.suffix != '.xml':
|
|
raise ValueError('Invalid XML destination')
|
|
elif dest.parts[0] != 'pics' or len(dest.parts) != 3 or dest.suffix.lower() not in ('.png', '.jpg', '.jpeg', '.webp', '.gif'):
|
|
raise ValueError('Invalid artwork destination')
|
|
size, digest = entry.get('size'), entry.get('sha256')
|
|
if type(size) is not int or not 0 < size <= MAX_DOWNLOAD:
|
|
raise ValueError('Invalid download size')
|
|
if not isinstance(digest, str) or len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest):
|
|
raise ValueError('Invalid SHA-256 digest')
|
|
if sys.platform == 'win32':
|
|
for component in dest.parts:
|
|
if (PureWindowsPath(component).is_reserved() or component.endswith((' ', '.'))
|
|
or any(c in component for c in '<>:"|?*')):
|
|
raise ValueError(f'Unsafe Windows filename: {component}')
|
|
target = destinations[dest.parts[0]].joinpath(*dest.parts[1:])
|
|
safe_path(target)
|
|
if target in seen or (target.exists() and not target.is_file()):
|
|
raise ValueError(f'Duplicate or invalid destination: {target}')
|
|
parent = target.parent
|
|
while not parent.exists():
|
|
parent = parent.parent
|
|
if not os.access(parent, os.W_OK | os.X_OK):
|
|
raise ValueError(f'Destination parent is not writable: {parent}')
|
|
seen.add(target)
|
|
checked.append((entry, target))
|
|
if not any(e['source'].startswith('xml/') for e, _ in checked):
|
|
raise ValueError('Manifest has no XML files')
|
|
return sorted(checked, key=lambda item: item[0]['source'].startswith('xml/'))
|
|
|
|
|
|
def validate_download(path, entry):
|
|
data = path.read_bytes()
|
|
if len(data) != entry['size'] or hashlib.sha256(data).hexdigest() != entry['sha256']:
|
|
raise ValueError(f'Size/checksum mismatch: {entry["source"]}; nothing installed. Retry after CI publication finishes.')
|
|
if entry['source'].startswith('xml/'):
|
|
if b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
|
|
raise ValueError('XML entity declarations are not supported')
|
|
root = ET.fromstring(data)
|
|
if root.tag != 'cockatrice_carddatabase' or not root.findall('./sets/set/name') or not root.findall('./cards/card'):
|
|
raise ValueError(f'Invalid Cockatrice XML: {entry["source"]}')
|
|
elif not (data.startswith(b'\x89PNG\r\n\x1a\n') or data.startswith(b'\xff\xd8\xff') or
|
|
data.startswith((b'GIF87a', b'GIF89a')) or (data.startswith(b'RIFF') and data[8:12] == b'WEBP')):
|
|
raise ValueError(f'Invalid image signature: {entry["source"]}')
|
|
|
|
|
|
def atomic_copy(source, target):
|
|
safe_path(target)
|
|
temporary = None
|
|
try:
|
|
with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.cockatrice-token-', delete=False) as stream:
|
|
temporary = Path(stream.name)
|
|
with source.open('rb') as incoming:
|
|
shutil.copyfileobj(incoming, stream)
|
|
stream.flush()
|
|
if hasattr(os, 'fchmod'):
|
|
os.fchmod(stream.fileno(), 0o644)
|
|
os.fsync(stream.fileno())
|
|
if hashlib.sha256(temporary.read_bytes()).digest() != hashlib.sha256(source.read_bytes()).digest():
|
|
raise OSError(f'Copy verification failed before moving into place: {target}')
|
|
os.replace(temporary, target)
|
|
finally:
|
|
if temporary is not None and temporary.exists():
|
|
temporary.unlink()
|
|
|
|
|
|
def install_files(staged, workspace):
|
|
backups, changed, created = {}, [], []
|
|
try:
|
|
for index, (_, target) in enumerate(staged):
|
|
safe_path(target)
|
|
if target.exists():
|
|
backup = workspace / f'backup-{index}'
|
|
shutil.copy2(target, backup)
|
|
backups[target] = backup
|
|
else:
|
|
backups[target] = None
|
|
for source, target in staged:
|
|
absent = []
|
|
parent = target.parent
|
|
while not parent.exists():
|
|
absent.append(parent)
|
|
parent = parent.parent
|
|
for directory in reversed(absent):
|
|
directory.mkdir(mode=0o755)
|
|
created.append(directory)
|
|
say(f'Installing verified file: {source}\n destination: {target}')
|
|
# A same-directory temporary copy makes the final move atomic even
|
|
# when the download directory lives on a different filesystem.
|
|
atomic_copy(source, target)
|
|
changed.append(target)
|
|
except BaseException as error:
|
|
say(f'ERROR: Installation failed: {error}. Rolling back completed file replacements.')
|
|
failures = []
|
|
for target in reversed(changed):
|
|
try:
|
|
if backups[target] is None:
|
|
target.unlink()
|
|
else:
|
|
atomic_copy(backups[target], target)
|
|
shutil.copystat(backups[target], target)
|
|
say(f'Restored previous state: {target}')
|
|
except OSError as rollback_error:
|
|
failures.append(f'{target}: {rollback_error}')
|
|
for directory in reversed(created):
|
|
try:
|
|
directory.rmdir()
|
|
except OSError as cleanup_error:
|
|
failures.append(f'{directory}: {cleanup_error}')
|
|
if failures:
|
|
raise RuntimeError(f'ROLLBACK INCOMPLETE. Keep recovery files in {workspace}. ' + '; '.join(failures)) from error
|
|
raise ValueError(f'Installation failed; previous files restored. Reason: {error}') from error
|
|
|
|
|
|
def plan_updates(entries, force=False):
|
|
pending, unchanged = [], []
|
|
for entry, target in entries:
|
|
safe_path(target)
|
|
identical = (target.is_file() and target.stat().st_size == entry['size'] and
|
|
hashlib.sha256(target.read_bytes()).hexdigest() == entry['sha256'])
|
|
if identical and not force:
|
|
validate_download(target, entry)
|
|
unchanged.append(target)
|
|
else:
|
|
pending.append((entry, target))
|
|
return pending, unchanged
|
|
|
|
|
|
def run(args):
|
|
if sys.platform not in ('linux', 'darwin', 'win32'):
|
|
raise ValueError('This installer supports Linux, macOS and Windows only.')
|
|
if sys.platform == 'win32':
|
|
import ctypes
|
|
if ctypes.windll.shell32.IsUserAnAdmin():
|
|
raise ValueError('Run PowerShell as your normal user, not as Administrator.')
|
|
elif os.geteuid() == 0:
|
|
raise ValueError('Run as your normal user, without sudo/root, to avoid installing into the wrong home.')
|
|
if not shutil.which('curl.exe' if sys.platform == 'win32' else 'curl'):
|
|
raise ValueError('curl is required. Install curl and retry; nothing installed.')
|
|
say('Cockatrice custom tokens installer. Close Cockatrice before proceeding.')
|
|
root, destinations = select_install(Path.home(), os.environ, args.data_dir)
|
|
say(f'Cockatrice data: {root}\nXML destination: {destinations["customsets"]}\nArtwork destination: {destinations["pics"]}/<SET_CODE>/')
|
|
confirm('Use these locations and continue with Cockatrice closed?')
|
|
workspace = Path(tempfile.mkdtemp(prefix='cockatrice-tokens-'))
|
|
lock = root / '.custom-tokens-install.lock'
|
|
locked = False
|
|
preserve = False
|
|
try:
|
|
try:
|
|
lock.mkdir(mode=0o700)
|
|
locked = True
|
|
except FileExistsError as error:
|
|
raise ValueError(f'Another installation may be running: {lock}. Abort; inspect before removing a stale lock.') from error
|
|
manifest_path = workspace / 'manifest.json'
|
|
download('manifest.json', manifest_path, 2 * 1024 * 1024)
|
|
entries = validate_manifest(manifest_path.read_text(), destinations)
|
|
entries, unchanged = plan_updates(entries, force=getattr(args, 'force', False))
|
|
for target in unchanged:
|
|
say(f'Already up to date (unchanged): {target}')
|
|
if not entries:
|
|
say('SUCCESS: all published files are already up to date. No files downloaded or replaced (manifest checked).')
|
|
return
|
|
say(f'Update check: {len(entries)} files to install/replace; {len(unchanged)} already up to date.')
|
|
required = sum(entry['size'] for entry, _ in entries)
|
|
backups_size = sum(target.stat().st_size for _, target in entries if target.exists())
|
|
if shutil.disk_usage(workspace).free < required + backups_size:
|
|
raise ValueError(f'Not enough temporary disk space for downloads and backups: {workspace}')
|
|
for _, target in entries:
|
|
parent = target.parent
|
|
while not parent.exists():
|
|
parent = parent.parent
|
|
if shutil.disk_usage(parent).free < required:
|
|
raise ValueError(f'Not enough destination disk space: {parent}')
|
|
staged = []
|
|
for index, (entry, target) in enumerate(entries):
|
|
source = workspace / f'download-{index}'
|
|
download(entry['source'], source, entry['size'])
|
|
validate_download(source, entry)
|
|
staged.append((source, target))
|
|
say('All downloads passed size, SHA-256, and content checks. Installation plan:')
|
|
for _, target in staged:
|
|
say(f' {"Replace" if target.exists() else "Create"}: {target}')
|
|
confirm('Install these files now? Existing files listed above will be backed up during installation.')
|
|
try:
|
|
install_files(staged, workspace)
|
|
except RuntimeError:
|
|
preserve = True
|
|
raise
|
|
say('SUCCESS: custom XML and referenced artwork installed. Restart Cockatrice to load them.')
|
|
finally:
|
|
if locked:
|
|
lock.rmdir()
|
|
if preserve:
|
|
say(f'Recovery files preserved: {workspace}')
|
|
else:
|
|
shutil.rmtree(workspace)
|
|
say(f'Removed temporary download directory: {workspace}')
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="""Data directory example (Flatpak):
|
|
--data-dir /home/vky/.var/app/io.github.Cockatrice.cockatrice/data/Cockatrice/Cockatrice/
|
|
|
|
Choose the folder containing cards.xml or settings/, normally alongside decks/.
|
|
Its customsets/ and pics/ subfolders may be missing: creation requires confirmation
|
|
and happens only after all downloads validate and you approve installation.
|
|
Do NOT select the outer .../data/ or .../data/Cockatrice/ folders, or decks/ or
|
|
customsets/ itself. Configured customsets/pics paths in settings/paths.ini win.
|
|
""")
|
|
parser.add_argument('--data-dir', '--datadir', type=Path,
|
|
help='Existing absolute data root containing cards.xml or settings/; see example below')
|
|
parser.add_argument('--force', action='store_true',
|
|
help='Download and replace even files whose size and SHA-256 already match')
|
|
args = parser.parse_args()
|
|
|
|
def interrupted(number, frame):
|
|
raise KeyboardInterrupt(f'Interrupted by signal {number}')
|
|
|
|
for number in (signal.SIGTERM, getattr(signal, 'SIGHUP', signal.SIGTERM)):
|
|
signal.signal(number, interrupted)
|
|
try:
|
|
run(args)
|
|
except (OSError, ValueError, RuntimeError, configparser.Error, ET.ParseError, KeyboardInterrupt) as error:
|
|
print(f'ERROR: {error}', file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|