"""Build the two soho card trees from Psion's own root filesystem tarball. python3 mksoho.py [tarball] card-soho/ Psion's soho image, unmodified -- the ARCHIVAL image card-soho-safe/ the same, with exactly three changes, each marked in the file: /etc/fstab NAND /home mount commented out /usr/bin/eject.sh will not stop hda when hda is the root disk /usr/bin/{flash_eraseall,flash_lock,flash_unlock,flashcp, nandwrite,nanddump} removed (kept in ../parked/soho-safe-removed-flash-tools/) Each tree gets root/, boot.fat, mknods.debugfs and metadata.debugfs; then PSION_CARD_DIR=card-soho scripts/mkimage.sh (PSION_IMAGE_NAME=...) PSION_CARD_DIR=card-soho-safe scripts/mkimage.sh builds the image. Two traps this script exists to avoid: * macOS cannot create device nodes, keep foreign owners or (unprivileged) keep setuid bits, so extraction loses them. They are taken instead from the tarball's own listing (tar tv --numeric-owner) by tarmeta2debugfs.py and written into the filesystem with debugfs when the image is built. * --exclude './dev/*' also drops ./dev itself, so the directory is recreated here. Without it every device node lands in / and X never starts. The trees are checked against the listing before anything is written out. """ import hashlib, os, shutil, stat, subprocess, sys, tarfile, filecmp, re HERE = os.path.dirname(os.path.abspath(__file__)) W = os.path.abspath(os.path.join(HERE, '..')) P = os.path.abspath(os.path.join(W, '..')) NAME = 'soho-image-netbook-pro-20050104074212.rootfs.tar.bz2' # the project keeps it in PSIONEX/; the PsionLX release in 3-PSION-SOURCES/soho-image/ TARBALL = sys.argv[1] if len(sys.argv) > 1 else next( (c for c in (os.path.join(P, 'PSIONEX', NAME), os.path.join(P, '3-PSION-SOURCES', 'soho-image', NAME)) if os.path.exists(c)), os.path.join(P, 'PSIONEX', NAME)) SHA256 = 'baa176ff06dcda9d58e86e17f76be3f19e63edbf791515cbea9111e22a0ae11d' LISTING = os.path.join(W, 'soho-analysis', 'soho-tarball-listing.txt') ORIG, SAFE = os.path.join(W, 'card-soho'), os.path.join(W, 'card-soho-safe') PARKED = os.path.join(P, 'parked', 'soho-safe-removed-flash-tools') \ if os.path.isdir(os.path.join(P, 'parked')) else os.path.join(W, 'removed-flash-tools') FLASH_TOOLS = ['flash_eraseall', 'flash_lock', 'flash_unlock', 'flashcp', 'nandwrite', 'nanddump'] FSTAB_OLD = '/dev/mtdblock1 /home jffs2 defaults 0 2\n' FSTAB_NEW = ('# PsionLX safe image (2026): Psion mounted /home from NAND partition 1 as JFFS2,\n' '# because this image was built for LX-partitioned internal flash. On a netBook Pro\n' '# whose NAND holds Windows CE that must never happen, so it is disabled and /home\n' '# stays on the card, in the "emergency" home directory soho-image.oe provides.\n' '#/dev/mtdblock1 /home jffs2 defaults 0 2\n') EJECT_OLD = '/etc/pcmcia/ide stop hda > /dev/null\n' EJECT_NEW = ('# PsionLX safe image (2026): on Psion\'s NAND-booted machine hda was only ever the\n' '# CF slot. Booted from a card, hda IS the root disk, and stopping it pulls the\n' '# filesystem out from under the running system. Only stop it when it is not root.\n' 'if ! grep -q \'^/dev/hda[0-9]* / \' /proc/mounts; then\n' ' /etc/pcmcia/ide stop hda > /dev/null\n' 'fi\n') def run(*cmd, **kw): r = subprocess.run(cmd, capture_output=True, text=True, **kw) if r.returncode != 0: sys.exit(f'{" ".join(cmd)} failed:\n{r.stderr}') return r.stdout def patch(root, rel, old, new): p = os.path.join(root, rel) s = open(p).read() if s.count(old) != 1: sys.exit(f'{rel}: expected Psion\'s line exactly once') open(p, 'w').write(s.replace(old, new)) def verify_listing(): """The listing is the source of every mode, owner and device node, so prove it describes this tarball exactly -- read with Python's tarfile, which behaves the same on every OS, unlike tar's own verbose output.""" rx = re.compile(r'^(\S{10})\s+\d+\s+(\d+)\s+(\d+)\s+(\S+)\s+\S+\s+\d+\s+\S+\s+(.*)$') want = {} for line in open(LISTING): m = rx.match(line.rstrip('\n')) if not m: sys.exit(f'{LISTING}: unreadable line: {line!r}') mode, uid, gid, size, name = m.groups() target = None if mode[0] == 'l': name, target = name.split(' -> ', 1) elif mode[0] == 'h' or ' link to ' in name: name, target = name.split(' link to ', 1) want[name.rstrip('/')] = (mode, int(uid), int(gid), size, target) TYPE = {tarfile.REGTYPE: stat.S_IFREG, tarfile.AREGTYPE: stat.S_IFREG, tarfile.DIRTYPE: stat.S_IFDIR, tarfile.SYMTYPE: stat.S_IFLNK, tarfile.CHRTYPE: stat.S_IFCHR, tarfile.BLKTYPE: stat.S_IFBLK} seen = 0 with tarfile.open(TARBALL, 'r:bz2') as tf: for m in tf: name = m.name if m.name.startswith('.') else './' + m.name name = name.rstrip('/') or '.' w = want.get(name) if w is None: sys.exit(f'{name} is in the tarball but not in {LISTING}') mode, uid, gid, size, target = w got = stat.filemode(TYPE.get(m.type, stat.S_IFREG) | m.mode) if m.ischr() or m.isblk(): gsize = f'{m.devmajor},{m.devminor}' elif m.isfile(): gsize = str(m.size) else: gsize = size # directories and links: tar's own block size, not checked if (got[1:] != mode[1:] or (mode[0] != 'h' and got[0] != mode[0]) or (m.uid, m.gid) != (uid, gid) or gsize != size or (target is not None and m.linkname not in (target, target.lstrip('./')))): sys.exit(f'{name}: listing says {mode} {uid}:{gid} {size} {target}, tarball has ' f'{got} {m.uid}:{m.gid} {gsize} {m.linkname}') seen += 1 if seen != len(want): sys.exit(f'{LISTING} has {len(want)} entries, the tarball {seen}') return seen def check_against_listing(root): """Every non-device entry in Psion's listing must exist with the same type, size and link target. Returns the number of entries checked.""" rx = re.compile(r'^(\S)\S{9}\s+\d+\s+\d+\s+\d+\s+(\S+)\s+\S+\s+\d+\s+\S+\s+(.*)$') n = 0 for line in open(LISTING): m = rx.match(line.rstrip('\n')) if not m: continue t, size, name = m.groups() if t in 'cb': continue target = None if t == 'l': name, target = name.split(' -> ', 1) rel = name[2:] if name.startswith('./') else name if rel in ('', '.'): continue p = os.path.join(root, rel.rstrip('/')) if t == 'd': ok = os.path.isdir(p) and not os.path.islink(p) elif t == 'l': ok = os.path.islink(p) and os.readlink(p) == target elif t == 'h': ok = os.path.isfile(p) else: ok = os.path.isfile(p) and not os.path.islink(p) and os.path.getsize(p) == int(size) if not ok: sys.exit(f'{root}: {rel} does not match Psion\'s listing') n += 1 return n def main(): h = hashlib.sha256() with open(TARBALL, 'rb') as f: for chunk in iter(lambda: f.read(1 << 20), b''): h.update(chunk) if h.hexdigest() != SHA256: sys.exit(f'{TARBALL}: sha256 does not match Psion\'s tarball') print(' tarball verified (sha256)') if not os.path.exists(LISTING): # bsdtar's format (macOS's tar; "bsdtar" from libarchive-tools on Linux), # which is what tarmeta2debugfs.py and the checks below read tar = shutil.which('bsdtar') or 'tar' os.makedirs(os.path.dirname(LISTING), exist_ok=True) open(LISTING, 'w').write(run(tar, 'tvjf', TARBALL, '--numeric-owner')) n = verify_listing() print(f' listing verified against the tarball: {n} entries, every type, mode, owner and size') # ---- the original for d in (ORIG, SAFE): if os.path.exists(d): shutil.rmtree(d) root = os.path.join(ORIG, 'root') os.makedirs(root) run('tar', 'xjf', TARBALL, '-C', root, '--exclude', './dev/*') os.makedirs(os.path.join(root, 'dev'), exist_ok=True) # the trap run(sys.executable, os.path.join(HERE, 'tarmeta2debugfs.py'), LISTING, ORIG) shutil.copy(os.path.join(W, 'bootimg', 'boot-original.fat'), os.path.join(ORIG, 'boot.fat')) n = check_against_listing(root) devs = sum(1 for l in open(os.path.join(ORIG, 'mknods.debugfs')) if l.startswith('mknod')) print(f' card-soho: {n} entries match Psion\'s listing, {devs} device nodes to create, ' f'boot partition = Psion\'s own kernel') # ---- the safe one sroot = os.path.join(SAFE, 'root') shutil.copytree(root, sroot, symlinks=True) patch(sroot, 'etc/fstab', FSTAB_OLD, FSTAB_NEW) patch(sroot, 'usr/bin/eject.sh', EJECT_OLD, EJECT_NEW) os.makedirs(PARKED, exist_ok=True) for t in FLASH_TOOLS: p = os.path.join(sroot, 'usr/bin', t) kept = os.path.join(PARKED, t) if os.path.exists(kept) and not filecmp.cmp(p, kept, shallow=False): sys.exit(f'{kept} exists and is not Psion\'s {t}') shutil.copy2(p, kept) os.remove(p) shutil.copy(os.path.join(ORIG, 'mknods.debugfs'), SAFE) gone = tuple(f'sif "/usr/bin/{t}" ' for t in FLASH_TOOLS) with open(os.path.join(ORIG, 'metadata.debugfs')) as src, \ open(os.path.join(SAFE, 'metadata.debugfs'), 'w') as dst: dst.writelines(l for l in src if not l.startswith(gone)) shutil.copy(os.path.join(W, 'bootimg', 'boot-safe.fat'), os.path.join(SAFE, 'boot.fat')) # the two trees must differ by exactly the three marked changes diffs, only = [], [] for dp, dns, fns in os.walk(root): for f in fns: a = os.path.join(dp, f) rel = os.path.relpath(a, root) b = os.path.join(sroot, rel) if not os.path.lexists(b): only.append(rel) elif not os.path.islink(a) and not filecmp.cmp(a, b, shallow=False): diffs.append(rel) if sorted(diffs) != ['etc/fstab', 'usr/bin/eject.sh'] or \ sorted(only) != sorted(f'usr/bin/{t}' for t in FLASH_TOOLS): sys.exit(f'card-soho-safe differs unexpectedly: changed {diffs}, removed {only}') print(' card-soho-safe: differs from Psion\'s only in /etc/fstab, /usr/bin/eject.sh and ' 'the six flash tools; boot partition = hardened kernel') if __name__ == '__main__': main()