Files

196 lines
9.5 KiB
Python

# iso fixtures (tools/fixtures.py): ISO 9660 images of one tree built by xorriso (nixpkgs#xorriso: plain and Joliet
# with -rockridge off, then the mkisofs emulation -R, -J -R, an El Torito no-emulation boot image) and genisoimage (nixpkgs#cdrkit, -J -R: deep directories
# relocated to rr_moved, long names and symlink targets in CE continuation areas), plus a multi-extent file and an
# interleaved file crafted here by splitting / editing a directory record. Expected listings: the source tree (os.lstat)
# for Rock Ridge images, pycdlib (a second reader, run through nix python) for the plain and Joliet name sets.
# tests/gen/iso.luau { images = { { name, data (or same = the index of the image with the same data), tree, entries = { { name, dir, size?, crc?, mode?, link?, mtime? } } } },
# boot = { data, lba, sectors, catalog }, multi = { data, name, size, crc }, interleaved = data }
import json, os, shutil, stat, struct, subprocess, tempfile, zlib
MTIME = 1650000000
DUMP = r"""
import json, sys, io, zlib, pycdlib
path, kind = sys.argv[1], sys.argv[2]
iso = pycdlib.PyCdlib()
iso.open(path)
out = []
key = {"joliet": "joliet_path", "iso9660": "iso_path"}[kind]
for d, dirs, files in iso.walk(**{key: "/"}):
base = d.rstrip("/")
for n in dirs:
out.append({"name": (base + "/" + n).lstrip("/"), "dir": True})
for n in files:
p = base + "/" + n
b = io.BytesIO()
iso.get_file_from_iso_fp(b, **{key: p})
name = p.lstrip("/")
if ";" in name:
name = name[:name.rindex(";")]
if kind == "iso9660" and name.endswith("."):
name = name[:-1]
out.append({"name": name, "dir": False, "size": len(b.getvalue()), "crc": zlib.crc32(b.getvalue())})
iso.close()
sys.stdout.write(json.dumps(out))
"""
def sh(pkg, argv, cwd):
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c"] + argv, cwd=cwd, capture_output=True, check=True).stdout
def tree_entries(root, skip_deep=False):
out = []
for dirpath, dirs, files in os.walk(root):
dirs.sort()
for n in sorted(dirs + files):
p = os.path.join(dirpath, n)
rel = os.path.relpath(p, root)
st = os.lstat(p)
e = {"name": rel, "dir": stat.S_ISDIR(st.st_mode), "mode": stat.S_IMODE(st.st_mode), "mtime": MTIME}
if stat.S_ISLNK(st.st_mode):
e["link"] = os.readlink(p)
elif stat.S_ISREG(st.st_mode):
with open(p, "rb") as f:
d = f.read()
e["size"], e["crc"] = len(d), zlib.crc32(d)
out.append(e)
return out
def split_record(data, name, at_bytes):
"""a multi-extent copy: the directory record of name split into two records (the first flagged 0x80)"""
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
root_len = struct.unpack_from("<I", img, 16 * 2048 + 156 + 10)[0]
p, e = root_lba * 2048, root_lba * 2048 + root_len
while p < e:
ln = img[p]
if ln == 0:
p = (p // 2048 + 1) * 2048
continue
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
rec = bytearray(img[p:p + ln])
size = struct.unpack_from("<I", rec, 10)[0]
lba = struct.unpack_from("<I", rec, 2)[0]
a, b2 = bytearray(rec), bytearray(rec)
struct.pack_into("<I", a, 10, at_bytes)
struct.pack_into(">I", a, 14, at_bytes)
a[25] |= 0x80
struct.pack_into("<I", b2, 2, lba + at_bytes // 2048)
struct.pack_into(">I", b2, 6, lba + at_bytes // 2048)
struct.pack_into("<I", b2, 10, size - at_bytes)
struct.pack_into(">I", b2, 14, size - at_bytes)
sector_end = (p // 2048 + 1) * 2048
used = sector_end
q = p + ln
while q < sector_end and img[q] != 0:
q += img[q]
assert q + ln <= sector_end, "no room in the directory sector"
img[p:q + ln] = a + b2 + img[p + ln:q]
return bytes(img), size
p += ln
raise Exception("record not found")
def set_interleave(data, name):
img = bytearray(data)
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
p = root_lba * 2048
while img[p]:
nl = img[p + 32]
if bytes(img[p + 33:p + 33 + nl]) == name:
img[p + 26], img[p + 27] = 1, 1
return bytes(img)
p += img[p]
raise Exception("record not found")
def generate(ctx):
rng = ctx.rng(29)
tmp = tempfile.mkdtemp()
try:
root = os.path.join(tmp, "tree")
files = [
("hello.txt", b"hello, iso\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(5000)),
("big.bin", rng.randbytes(40000)),
("A File With Spaces And A Name Longer Than Sixty-Four Characters For Joliet.txt", b"long joliet\n"),
("unicodé/naïve.txt", "ünïcödé".encode()),
("run.sh", b"#!/bin/sh\necho hi\n"),
]
for n, d in files:
p = os.path.join(root, n)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(d)
os.chmod(os.path.join(root, "run.sh"), 0o755)
os.symlink("hello.txt", os.path.join(root, "link"))
os.makedirs(os.path.join(root, "emptydir"))
for dirpath, dirs, fs in os.walk(root):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
base_entries = tree_entries(root)
# a second tree with what only Rock Ridge holds: deep directories, a 200-byte name, a long symlink target
root2 = os.path.join(tmp, "tree2")
shutil.copytree(root, root2, symlinks=True)
deep = os.path.join(root2, *["d%d" % i for i in range(1, 11)])
os.makedirs(deep)
with open(os.path.join(deep, "deep.txt"), "wb") as f:
f.write(b"ten levels down\n")
with open(os.path.join(root2, "n" * 200), "wb") as f:
f.write(b"a 200-byte name\n")
os.symlink("/" + "/".join(["target-component-%02d" % i for i in range(16)]), os.path.join(root2, "longlink"))
for dirpath, dirs, fs in os.walk(root2):
for n in dirs + fs:
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
rr_entries = tree_entries(root2)
images = []
def dump(path, kind):
return json.loads(ctx.python(["pycdlib"], DUMP.replace("sys.argv[1], sys.argv[2]", repr(path) + ", " + repr(kind))))
def xorriso(name, args, src, tree, entries=None):
out = os.path.join(tmp, name + ".iso")
if args and args[0] == "native": # xorriso's own commands (mkisofs emulation always writes Rock Ridge)
sh("xorriso", ["xorriso", "-outdev", out, "-padding", "0"] + args[1:] + ["-map", src, "/"], tmp)
else:
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-o", out] + args + [src], tmp)
if entries is None:
entries = dump(out, tree)
images.append({"name": name, "data": open(out, "rb").read(), "tree": tree, "entries": entries})
return out
plain = xorriso("xorriso-plain", ["native", "-rockridge", "off"], root, "iso9660")
xorriso("xorriso-J", ["native", "-rockridge", "off", "-joliet", "on"], root, "joliet")
xorriso("xorriso-R", ["-R"], root, "rockridge", base_entries)
xorriso("xorriso-JR", ["-J", "-R"], root2, "rockridge", rr_entries)
out = os.path.join(tmp, "geniso.iso")
sh("cdrkit", ["genisoimage", "-quiet", "-no-pad", "-J", "-R", "-o", out, root2], tmp)
images.append({"name": "genisoimage-JR", "data": open(out, "rb").read(), "tree": "rockridge", "entries": rr_entries})
# Joliet from the -J -R image too (prefer = "joliet")
images.append({"name": "genisoimage-JR-joliet", "same": len(images), "tree": "joliet", "entries": dump(out, "joliet")})
# El Torito
bootdir = os.path.join(tmp, "boot")
shutil.copytree(root, bootdir, symlinks=True)
with open(os.path.join(bootdir, "boot.img"), "wb") as f:
f.write(b"\xfa\xeb\xfe" + bytes(2045))
out = os.path.join(tmp, "boot.iso")
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-R", "-o", out, "-b", "boot.img", "-c", "boot.cat", "-no-emul-boot",
"-boot-load-size", "4", bootdir], tmp)
bdata = open(out, "rb").read()
info = subprocess.run(["nix", "shell", "nixpkgs#xorriso", "-c", "xorriso", "-indev", out, "-report_el_torito", "plain"],
capture_output=True, text=True).stdout
# "El Torito boot img : 1 BIOS y none 0x0000 0x00 4 LBA"
row = [l for l in info.split("\n") if l.startswith("El Torito boot img")][0].split()
cat = [l for l in info.split("\n") if l.startswith("El Torito catalog")][0].split()
boot = {"data": bdata, "sectors": int(row[-2]), "lba": int(row[-1]), "bootable": row[7] == "y", "catalog": int(cat[4])}
multi, msize = split_record(open(plain, "rb").read(), b"BIG.BIN;1", 2048 * 8)
mcrc = zlib.crc32(dict(files)["big.bin"])
interleaved = set_interleave(open(plain, "rb").read(), b"HELLO.TXT;1")
finally:
shutil.rmtree(tmp)
ctx.emit("iso", {"images": images, "boot": boot, "multi": {"data": multi, "name": "BIG.BIN", "size": msize, "crc": mcrc},
"interleaved": interleaved})