"""Ready pycdlib ISO assembly/readback for explicitly reviewed file trees. SPDX-License-Identifier: GPL-2.0-or-later No ISO parser or compressor is implemented here; pycdlib handles the format. """ from pathlib import Path import hashlib import io import json import re import pycdlib def sha(path): digest = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): digest.update(block) return digest.hexdigest() def json_file(path, value): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf8') def windows_text(path, body): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(body.replace('\r\n', '\n').replace('\n', '\r\n').encode('ascii')) def write_tree(tree, work, filename, volume, evidence): """New compact ISO, both namespaces read back, plus 256 KiB chunk hashes.""" def directory_name(rel): return '/' + '/'.join(re.sub('[^A-Z0-9_]', '_', item.upper()) for item in rel.split('/')) iso = pycdlib.PyCdlib() iso.new(interchange_level=3, joliet=3, rock_ridge='1.09', vol_ident=volume) for directory in sorted((p for p in tree.rglob('*') if p.is_dir()), key=lambda p: (len(p.parts), str(p))): relative = directory.relative_to(tree).as_posix() iso.add_directory(iso_path=directory_name(relative), joliet_path='/' + relative, rr_name=directory.name) inventory, aliases = [], set() for path in sorted(p for p in tree.rglob('*') if p.is_file()): relative = path.relative_to(tree).as_posix() stem, dot, extension = path.name.rpartition('.') name = re.sub('[^A-Z0-9_]', '_', (stem if dot else extension).upper()) if dot: name += '.' + re.sub('[^A-Z0-9_]', '_', extension.upper()) parent = path.parent.relative_to(tree).as_posix() primary = (directory_name(parent) if parent != '.' else '') + '/' + name + ';1' if primary in aliases: raise ValueError('ISO alias collision: ' + primary) aliases.add(primary) iso.add_file(str(path), iso_path=primary, joliet_path='/' + relative, rr_name=path.name) inventory.append({'path': '/' + relative, 'bytes': path.stat().st_size, 'sha256': sha(path), 'isoPath': primary}) temporary = work / (filename + '.iso') if temporary.exists(): raise ValueError('Refusing to replace existing ISO') iso.write(str(temporary)) iso.close() digest = sha(temporary) output = work / (filename + '-' + digest + '.iso') temporary.rename(output) reader = pycdlib.PyCdlib() reader.open(str(output)) actual = {directory.rstrip('/') + '/' + name for directory, _, names in reader.walk(joliet_path='/') for name in names} if actual != {row['path'] for row in inventory}: raise ValueError('Unexpected/missing output file') for row in inventory: for namespace, path in [('joliet_path', row['path']), ('iso_path', row['isoPath'])]: body = io.BytesIO() reader.get_file_from_iso_fp(body, **{namespace: path}) if len(body.getvalue()) != row['bytes'] or hashlib.sha256(body.getvalue()).hexdigest() != row['sha256']: raise ValueError('Readback mismatch: ' + row['path']) reader.close() chunks = [] with output.open('rb') as stream: offset = 0 for body in iter(lambda: stream.read(256 * 1024), b''): chunks.append({'offset': offset, 'bytes': len(body), 'sha256': hashlib.sha256(body).hexdigest()}) offset += len(body) json_file(evidence / 'output-inventory.json', inventory) json_file(evidence / 'iso-chunks.json', {'bytes': output.stat().st_size, 'sha256': digest, 'chunkBytes': 256 * 1024, 'chunks': chunks}) return {'localFile': str(output), 'filename': output.name, 'bytes': output.stat().st_size, 'sha256': digest, 'volume': volume, 'files': len(inventory)}