# SPDX-License-Identifier: GPL-2.0-or-later """Ready: pycdlib ISO authoring + BeautifulSoup HTML edits + stdlib archive reads. 7-Zip/innoextract/unar supplied frozen original embedded files; no Windows EXE runs. No filesystem-format or installer-format parser is implemented here. """ from pathlib import Path from datetime import datetime, timezone from bs4 import BeautifulSoup import argparse, hashlib, io, json, os, shutil, tarfile, zipfile import pycdlib HERE = Path(__file__).resolve().parent def sha(path): h = hashlib.sha256() with path.open('rb') as f: for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block) return h.hexdigest() def main(): ap = argparse.ArgumentParser() ap.add_argument('--out-dir', required=True, type=Path) args = ap.parse_args() if args.out_dir.exists(): raise ValueError('Use a new output directory; previous runs are immutable.') config = json.loads((HERE / 'inputs.json').read_text()) embedded_path = HERE / config['embeddedManifest'] if sha(embedded_path) != config['embeddedManifestSha256']: raise ValueError('Frozen embedded-file manifest changed') embedded = {row['sourcePath']: row for row in json.loads(embedded_path.read_text())} for path, row in embedded.items(): source = Path(path) if path.startswith('/tmp/') else Path(config['workRoot']) / 'inspect' / path.lstrip('/') if source.stat().st_size != row['bytes'] or sha(source) != row['sha256']: raise ValueError('Original embedded bytes changed: ' + path) work = Path(config['workRoot']) original_path = Path(config['original']['file']) if sha(original_path) != config['original']['hashes']['sha256']: raise ValueError('Original ISO SHA mismatch') for row in config['sources']: if sha(Path(row['file'])) != row['sha256']: raise ValueError('Source SHA mismatch: ' + row['name']) args.out_dir.mkdir(parents=True) tree = args.out_dir / 'tree' tree.mkdir() archive = args.out_dir.parent / 'archive' archive.mkdir(exist_ok=True) archived = archive / 'gnuwinII_November_30_2004-original.iso' if not archived.exists(): os.link(original_path, archived) if sha(archived) != config['original']['hashes']['sha256']: raise ValueError('Archived original differs') inventory = json.loads(Path('/tmp/svits-gnuwin-original-20261021/main-directory.json').read_text())['files'] apps = set(config['apps']) original = pycdlib.PyCdlib() original.open(str(original_path)) retained, deleted, added, modified = [], [], [], [] image_names = {'title.png', 'logosmall.gif', 'gwicon.png', 'bullet.gif', 'bulletanim.gif', 'gnuwinCD.jpg', 'gnuwinCD-small.jpg', 'legal.jpg', 'faq.jpg', 'install.jpg'} languages = {'en', 'fr', 'de', 'it', 'es', 'pt', 'ct', 'hi', 'sv', 'hu'} # Keep the original interface structure and reviewed application descriptions. # All installers/archives are replaced by exact portable bytes below, not new applications. for row in inventory: p = row['path'] parts = Path(p).parts keep = p in {'/index.html', '/autorun.inf'} or p.startswith('/gpl/') if len(parts) > 2 and parts[1] == 'apps': keep = (parts[2] in apps and '/install/' not in p and '/doc/' not in p) or parts[2] in languages if len(parts) > 2 and parts[1] in languages: keep = p.endswith('.html') if p.startswith('/classes/'): keep = p.endswith('.html') if p.startswith('/images/'): name = parts[-1] keep = p.startswith('/images/border/') or name in image_names or name in {lang + suffix for lang in languages for suffix in ['.gif', '-small.gif']} if p.startswith('/glossaire/'): keep = p.endswith(('.html', '.gif', '.png')) if keep: target = tree / p.lstrip('/') target.parent.mkdir(parents=True, exist_ok=True) original.get_file_from_iso(str(target), joliet_path=p) retained.append({'originalPath': p, 'outputPath': p, 'bytes': target.stat().st_size, 'sha256': sha(target)}) else: reason = 'Outside this fully reviewed subset; omitted under owner cleanup instruction, not declared prohibited.' if p.startswith('/apps/vidomi/'): reason = 'Entire Vidomi package omitted: exact Product EULA is personal/nonredistributable except encoder.exe.' elif '/install/' in p and len(parts) > 2 and parts[2] in apps: reason = 'Original package omitted; reviewed byte-exact portable application parts retained separately.' deleted.append({'originalPath': p, 'bytes': row['bytes'], 'reason': reason}) original.close() targets = {} def portable(app, source, excluded=()): dest = tree / 'apps' / app / 'en' / 'install' / 'portable' for p in sorted(x for x in source.rglob('*') if x.is_file()): rel = p.relative_to(source) if any(rel.as_posix() == item or rel.parts[0] == item for item in excluded) or p.name.startswith('_extract'): continue target = dest / rel target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(p, target) added.append({'path': '/' + target.relative_to(tree).as_posix(), 'bytes': target.stat().st_size, 'sha256': sha(target), 'provenance': str(p), 'change': 'Exact embedded bytes; no binary patch'}) return dest up = work / 'unpacked/apps' portable('putty', up / 'putty/en/install/putty-0.55-installer.exe/app') targets['putty'] = 'putty.exe' portable('SciTE', up / 'SciTE/en/install/SciTE-1.57-en-fr-de-es-pt.exe/app') targets['SciTE'] = 'SciTE.exe' # Native README explicitly calls the compiled opening book optional. portable('gnuchess', up / 'gnuchess/en/install/GNUChessSetup.exe/app', {'GNUCHESS.DAT'}) targets['gnuchess'] = 'GNUCHESS.EXE' portable('gnuplot', up / 'gnuplot/en/install/GnuplotSetup.exe/app') targets['gnuplot'] = 'wgnupl32.exe' portable('gpg', up / 'gpg/en/install/gnupg-w32cli-1.2.3.zip') targets['gpg'] = 'gpg.exe' for version in ['nh340win.zip', 'nh342win3.zip']: portable('nethack2', up / ('nethack2/en/install/' + version)) if version == 'nh342win3.zip' else None targets['nethack2'] = 'NetHackW.exe' # Retain the older official release as its unchanged original archive too. nh340 = work / 'inspect/apps/nethack2/en/install/nh340win.zip' nhdest = tree / 'apps/nethack2/en/install/nh340win.zip' nhdest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(nh340, nhdest) added.append({'path': '/apps/nethack2/en/install/nh340win.zip', 'bytes': nhdest.stat().st_size, 'sha256': sha(nhdest), 'provenance': '/apps/nethack2/en/install/nh340win.zip', 'change': 'Unchanged original archive'}) portable('virtualdub', up / 'virtualdub/en/install/VirtualDub-1.5.10.zip') targets['virtualdub'] = 'VirtualDub.exe' # Vim permits unmodified parts. Omit optional diff/gettext and shell/IDE integration. vim = work / 'gvim-unar/gvim62/Register 0, 1' portable('vim', vim, {'lang', 'keymap', 'libintl.dll', 'diff.exe', 'install.exe', 'uninstal.exe', 'gvimext.dll', 'VisVim.dll'}) targets['vim'] = 'gvim.exe' openssl = tree / 'apps/openssl/en/install/portable' openssl.mkdir(parents=True, exist_ok=True) src = work / 'inspect/apps/openssl/en/install/openssl.exe' shutil.copy2(src, openssl / 'openssl.exe') added.append({'path': '/apps/openssl/en/install/portable/openssl.exe', 'bytes': src.stat().st_size, 'sha256': sha(src), 'provenance': '/apps/openssl/en/install/openssl.exe', 'change': 'Unchanged original PE'}) targets['openssl'] = 'openssl.exe' source_rows = [] for row in config['sources']: name = 'gnuwin-interface-2002-09-06.tar' if row['name'] == 'gnuwin2Source-2002-09-06.tar.gz' else row['name'] target = tree / 'sources' / name target.parent.mkdir(exist_ok=True) shutil.copy2(row['file'], target) source_rows.append({**row, 'outputPath': '/sources/' + name}) notices = tree / 'notices' notices.mkdir() copies = { 'PuTTY-LICENCE.txt': up / 'putty/en/install/putty-0.55-installer.exe/app/LICENCE', 'NetHack-license.txt': up / 'nethack2/en/install/nh342win3.zip/license', 'SciTE-License.txt': up / 'SciTE/en/install/SciTE-1.57-en-fr-de-es-pt.exe/app/License.txt', 'GNUChess-GPL.txt': up / 'gnuchess/en/install/GNUChessSetup.exe/app/DOC/COPYING.TXT', 'gnuplot-Copyright.txt': up / 'gnuplot/en/install/GnuplotSetup.exe/app/Copyright', 'GnuPG-GPL.txt': up / 'gpg/en/install/gnupg-w32cli-1.2.3.zip/COPYING', 'Vim-license.txt': vim / 'doc/uganda.txt', 'VirtualDub-GPL.txt': up / 'virtualdub/en/install/VirtualDub-1.5.10.zip/copying', } for name, path in copies.items(): shutil.copy2(path, notices / name) with tarfile.open(work / 'sources/openssl-0.9.7-git.tar.gz') as t: member = next(m for m in t.getmembers() if m.name.endswith('/LICENSE')) (notices / 'OpenSSL-LICENSE.txt').write_bytes(t.extractfile(member).read()) with tarfile.open(work / 'sources/libpng-1.0.5-git.tar.gz') as t: member = next(m for m in t.getmembers() if m.name.endswith('/png.h')) # The complete original header retains the exact libpng copyright/permission text. (notices / 'libpng-1.0.5-png.h').write_bytes(t.extractfile(member).read()) with tarfile.open(work / 'sources/zlib-1.1.3.tar.gz') as t: member = next(m for m in t.getmembers() if m.name.endswith('/zlib.h')) (notices / 'zlib-1.1.3-zlib.h').write_bytes(t.extractfile(member).read()) for page in sorted(tree.rglob('*.html')): # The historical multilingual pages use several declared encodings. # Let the ready HTML decoder read their actual bytes before UTF-8 output. soup = BeautifulSoup(page.read_bytes(), 'html.parser') for a in list(soup.find_all('a', href=True)): # Removing an omitted
  • also decomposes its other links, which # remain in this snapshot of the original tree. if a.attrs is None: continue href = a['href'] # urljoin supplies standard relative-path resolution; no custom HTML parser. from urllib.parse import urljoin, urlsplit resolved = urlsplit(urljoin('https://disc.invalid/' + page.relative_to(tree).as_posix(), href)) pp = Path(resolved.path).parts if resolved.hostname == 'disc.invalid' and len(pp) > 2 and pp[1] == 'apps': app = pp[2] if app not in apps and app not in languages: parent = a.find_parent('li') (parent or a).decompose() continue if app in apps and ('/install/' in resolved.path or resolved.path.endswith('/install')): a['href'] = os.path.relpath(tree / 'apps' / app / 'en/install/portable' / targets[app], page.parent).replace(os.sep, '/') # Keep the native menu hierarchy, but do not leave links to omitted # articles, docs or historical missing pages. No replacement app is added. for el in list(soup.find_all(['a', 'img', 'link', 'script', 'body', 'td'])): if el.attrs is None: continue for attr in ['href', 'src', 'background']: href = el.get(attr) if not href or href.startswith(('#', 'mailto:', 'javascript:')): continue resolved = urlsplit(urljoin('https://disc.invalid/' + page.relative_to(tree).as_posix(), href)) if resolved.hostname != 'disc.invalid': continue if resolved.path == '/gnuwin2Source-2002-09-06.tar.gz': el[attr] = os.path.relpath(tree / 'sources/gnuwin-interface-2002-09-06.tar', page.parent).replace(os.sep, '/') continue from urllib.parse import unquote destination = tree / unquote(resolved.path).lstrip('/') if destination.exists(): continue if el.name == 'a': el.unwrap() break if el.name in ['img', 'link', 'script']: el.decompose() break del el[attr] if soup.body: notice = soup.new_tag('p') notice['style'] = 'background:#fff2ba;color:#172a35;padding:8px;border:1px solid #b5a36a' notice.string = f'MODIFIED COPY, 22 October 2026: unofficial cleaned GNUWin II selection; {len(apps)} reviewed applications. Original November 30, 2004 collection by GNU Generation/EPFL. See README.TXT and sources/.' soup.body.insert(0, notice) page.write_text(str(soup), encoding='utf8') modified.append({'path': '/' + page.relative_to(tree).as_posix(), 'change': 'Marked modified; omitted-application links removed; retained install links point to exact portable bytes'}) autorun = tree / 'autorun.inf' autorun.write_text('[autorun]\r\nopen=explorer .\\index.html\r\nshell\\verb\\command=explorer .\\index.html\r\nshell\\verb=Cleaned GNUWin II selection\r\n', encoding='ascii') modified.append({'path': '/autorun.inf', 'change': 'Native Explorer index entry retained; missing icon reference removed; modified-copy label'}) readme = ('CLEANED GNUWIN II WINDOWS SELECTION (2004)\n' 'Modified copy, 22 October 2026. Not an official GNUWin/EPFL release.\n' 'Original collection/interface copyright2004 GNU Generation and GNUWin Team; GPL.\n' 'Original ISO archived unmodified. Only reviewed original application bytes retained.\n\n' 'Open index.html for the original multilingual interface.\n' 'For games and saving files, copy the portable application folder to C: first.\n' 'No application EXE/DLL has been patched or replaced with a newer release.\n\n' + '\n'.join(app + ': apps/' + app + '/en/install/portable/' + exe for app, exe in targets.items()) + '\n\nSources are supplied on this same CD in sources/; original notices in notices/.\n' 'GNUChess source is also in its portable/SRC; optional compiled opening book is omitted.\n' 'Vim is the original6.2 build160/patchlevel0, not patch160. Optional gettext/diff and shell integration are omitted.\n' 'OpenSSL actual retained binary is0.9.7, not the old menu label0.9.7c.\n' 'This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/).\n' 'This product includes cryptographic software written by Eric Young (eay@cryptsoft.com).\n' 'This product includes software written by Tim Hudson (tjh@cryptsoft.com).\n' 'Omitted software with incomplete proof is not declared prohibited.\n' 'See deletion/retention manifests and sources. No warranty.\n') (tree / 'README.TXT').write_text(readme, encoding='utf8', newline='\r\n') for name, data in [('deleted-manifest.json', deleted), ('retained-original.json', retained), ('retained-embedded.json', added), ('modified-interface.json', modified), ('source-files.json', source_rows)]: (args.out_dir / name).write_text(json.dumps(data, indent=2) + '\n') if name in ['deleted-manifest.json', 'source-files.json']: shutil.copy2(args.out_dir / name, tree / name) modifications = tree / 'modifications' modifications.mkdir() for name in ['build.py', 'inputs.json', 'embedded-inputs.json', 'requirements.txt', 'clearance-and-modifications.json']: shutil.copy2(HERE / name, modifications / name) iso = pycdlib.PyCdlib() iso.new(interchange_level=3, joliet=3, rock_ridge='1.09', vol_ident='GNUWIN2_CLEANED') dirs = {Path('.'): ''} for i, directory in enumerate(sorted((p for p in tree.rglob('*') if p.is_dir()), key=lambda p: (len(p.parts), str(p))), 1): rel = directory.relative_to(tree) ident = dirs[rel.parent] + '/D' + str(i).zfill(7) dirs[rel] = ident iso.add_directory(iso_path=ident, joliet_path='/' + rel.as_posix(), rr_name=directory.name) output_inventory = [] for i, p in enumerate(sorted(p for p in tree.rglob('*') if p.is_file()), 1): rel = p.relative_to(tree) ident = dirs[rel.parent] + '/F' + str(i).zfill(7) + ';1' iso.add_file(str(p), iso_path=ident, joliet_path='/' + rel.as_posix(), rr_name=p.name) output_inventory.append({'path': '/' + rel.as_posix(), 'bytes': p.stat().st_size, 'sha256': sha(p)}) output = args.out_dir / 'GNUWinII-main-cleaned.iso' iso.write(str(output)) iso.close() verify = pycdlib.PyCdlib() verify.open(str(output)) for row in output_inventory: body = io.BytesIO() verify.get_file_from_iso_fp(body, joliet_path=row['path']) if hashlib.sha256(body.getvalue()).hexdigest() != row['sha256']: raise ValueError('Readback failed: ' + row['path']) verify.close() (args.out_dir / 'output-inventory.json').write_text(json.dumps(output_inventory, indent=2) + '\n') proof = {'created': datetime.now(timezone.utc).isoformat(), 'status': 'bytes verified; source/clearance peer review and guest gate pending', 'title': config['title'], 'original': config['original'], 'originalArchive': str(archived), 'output': {'file': str(output), 'bytes': output.stat().st_size, 'sha256': sha(output)}, 'applications': sorted(apps), 'sourceArchives': len(source_rows), 'sourceBytes': sum(r['bytes'] for r in source_rows), 'allOutputFilesReadBack': len(output_inventory), 'originalDeletedFiles': len(deleted), 'nativeGuestTest': False, 'providerConfigured': False, 'shelfInsertEnabled': False, 'noWindowsGuestBytes': True, 'noRuntimeChange': True} (args.out_dir / 'ready-artifact.json').write_text(json.dumps(proof, indent=2) + '\n') print(json.dumps(proof, indent=2)) if __name__ == '__main__': main()