248 lines
12 KiB
Python
248 lines
12 KiB
Python
# Cabinet fixtures (tools/fixtures.py): cabinets by gcab (stored and MSZIP folders, paths), lcab (stored), our own
|
|
# minimal cabinet builder below (MSZIP blocks deflated with the previous block as the zlib dictionary, several
|
|
# folders, reserve areas, attributes, UTF-8 names; LZX and Quantum folders from the fixture compressors _lzx.py /
|
|
# _quantum.py, since no packaged tool writes them), the libmspack test cabinets read from the nix store (test data,
|
|
# not committed: normal / reserve / multi-part / mszip_lzx_qtm samples and the broken ones), and our writer's output.
|
|
# The reference data is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); every fixture
|
|
# LZX / Quantum cabinet must extract with cabextract to the original bytes, and cabextract, gcab and 7z must extract
|
|
# our writer's cabinets to the same bytes.
|
|
# tests/gen/cab.luau { cases = { { name, data, entries = { { name, size, crc, mtime } } } }, ours = { ok, log },
|
|
# spanned = { { name, data } }, bad = { { name, data } } }
|
|
import calendar, importlib.util, os, re, struct, subprocess, time, zlib
|
|
|
|
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
|
|
A = importlib.util.module_from_spec(_s)
|
|
_s.loader.exec_module(A)
|
|
_s = importlib.util.spec_from_file_location("_lzx", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_lzx.py"))
|
|
L = importlib.util.module_from_spec(_s)
|
|
_s.loader.exec_module(L)
|
|
_s = importlib.util.spec_from_file_location("_quantum", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_quantum.py"))
|
|
Q = importlib.util.module_from_spec(_s)
|
|
_s.loader.exec_module(Q)
|
|
|
|
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_lzx.py", "tools/fixtures/_quantum.py"]
|
|
ENV = dict(os.environ, TZ="UTC")
|
|
|
|
|
|
def checksum(data, seed=0):
|
|
"""the CFDATA checksum ([MS-CAB] 2.4)"""
|
|
s = seed
|
|
n = len(data) - len(data) % 4
|
|
for i in range(0, n, 4):
|
|
s ^= struct.unpack_from("<I", data, i)[0]
|
|
t = 0
|
|
for b in data[n:]:
|
|
t = (t << 8) | b
|
|
return s ^ t
|
|
|
|
|
|
def dos(t):
|
|
y, mo, d, h, mi, s = time.gmtime(t)[:6]
|
|
return ((y - 1980) << 9) | (mo << 5) | d, (h << 11) | (mi << 5) | (s // 2)
|
|
|
|
|
|
def build(folders, reserve=None):
|
|
"""a cabinet: folders = [(typeCompress, [(name, bytes, attribs, mtime)], encode(stream) -> [(payload, size)])];
|
|
reserve = (header bytes, folder size, data size)"""
|
|
hres, fres, dres = reserve or (b"", 0, 0)
|
|
flags = 4 if reserve else 0
|
|
head = 36 + (4 + len(hres) if reserve else 0)
|
|
nfiles = sum(len(f[1]) for f in folders)
|
|
files = b""
|
|
blocks = []
|
|
for fi, (typ, fl, enc) in enumerate(folders):
|
|
off = 0
|
|
stream = b""
|
|
for name, data, attr, mt in fl:
|
|
d, t = dos(mt)
|
|
files += struct.pack("<IIHHHH", len(data), off, fi, d, t, attr) + name + b"\0"
|
|
off += len(data)
|
|
stream += data
|
|
blocks.append(enc(stream))
|
|
coff = head + len(folders) * (8 + fres)
|
|
dat = coff + len(files)
|
|
folder_tab = b""
|
|
data = b""
|
|
for (typ, _, _), bl in zip(folders, blocks):
|
|
folder_tab += struct.pack("<IHH", dat + len(data), len(bl), typ) + b"\0" * fres
|
|
for payload, n in bl:
|
|
csum = checksum(struct.pack("<HH", len(payload), n), checksum(payload))
|
|
data += struct.pack("<IHH", csum, len(payload), n) + b"\x5a" * dres + payload
|
|
total = coff + len(files) + len(data)
|
|
hdr = b"MSCF" + struct.pack("<IIIIIBBHHHHH", 0, total, 0, coff, 0, 3, 1, len(folders), nfiles, flags, 0x1234, 0)
|
|
if reserve:
|
|
hdr += struct.pack("<HBB", len(hres), fres, dres) + hres
|
|
return hdr + folder_tab + files + data
|
|
|
|
|
|
def chunks(stream):
|
|
return [stream[s:s + 32768] for s in range(0, len(stream), 32768)]
|
|
|
|
|
|
def store(stream):
|
|
return [(c, len(c)) for c in chunks(stream)]
|
|
|
|
|
|
def mszip_dict(stream):
|
|
out, prev = [], b""
|
|
for chunk in chunks(stream):
|
|
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
|
|
out.append((b"CK" + c.compress(chunk) + c.flush(), len(chunk)))
|
|
prev = chunk
|
|
return out
|
|
|
|
|
|
def lzx(wbits, e8size=0, seed=1, plan=None):
|
|
def enc(stream):
|
|
data, frames = L.compress(stream, wbits, e8size, seed, plan)
|
|
out, p = [], 0
|
|
for i, n in enumerate(frames):
|
|
out.append((data[p:p + n], min(32768, len(stream) - i * 32768)))
|
|
p += n
|
|
assert p == len(data)
|
|
return out
|
|
return enc
|
|
|
|
|
|
def quantum(wbits):
|
|
def enc(stream):
|
|
frames = Q.compress(stream, wbits)
|
|
return [(f, min(32768, len(stream) - i * 32768)) for i, f in enumerate(frames)]
|
|
return enc
|
|
|
|
|
|
LIST = re.compile(r"^\s*(\d+) \| (\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d):(\d\d) \| (.*)$")
|
|
|
|
|
|
def reference(path, tmp, tag):
|
|
"""cabextract's listing (name -> mtime) and extraction (name -> size, crc)"""
|
|
listing = A.tool(["cabextract"], ["cabextract", "-l", path]).decode("utf-8", "replace")
|
|
times = {}
|
|
for line in listing.splitlines():
|
|
m = LIST.match(line)
|
|
if m:
|
|
d, mo, y, h, mi, s = (int(x) for x in m.group(2, 3, 4, 5, 6, 7))
|
|
times[m.group(8).replace("\\", "/")] = calendar.timegm((y, mo, d, h, mi, s))
|
|
out = os.path.join(tmp, "x-" + tag)
|
|
os.makedirs(out)
|
|
subprocess.run(["nix", "shell", "nixpkgs#cabextract", "-c", "cabextract", "-q", "-d", out, path], check=True,
|
|
capture_output=True, env=ENV)
|
|
ents = []
|
|
for n, c in sorted(A.read_tree(out).items()):
|
|
e = {"name": n, "size": os.path.getsize(os.path.join(out, n)), "crc": c}
|
|
if n in times:
|
|
e["mtime"] = times[n]
|
|
ents.append(e)
|
|
return ents
|
|
|
|
|
|
def mspack_cabs():
|
|
"""the libmspack source's test cabinets (nix store path of its tarball, unpacked into a temporary directory)"""
|
|
src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#libmspack.src"], check=True,
|
|
capture_output=True).stdout.decode().strip()
|
|
return src
|
|
|
|
|
|
def generate(ctx):
|
|
rng = ctx.rng(47)
|
|
tmp = A.tmpdir()
|
|
try:
|
|
work = os.path.join(tmp, "w")
|
|
text = b"the quick brown fox jumps over the lazy dog\n" * 3000
|
|
rand = rng.randbytes(70000)
|
|
A.tree(A.FILES + [("dir/sub/text.txt", text), ("dir/rand.bin", rand),
|
|
("dir/runs.bin", b"\0" * 50000 + b"\xff" * 30000)], work)
|
|
names = [n for n, _ in A.FILES] + ["dir/sub/text.txt", "dir/rand.bin", "dir/runs.bin"]
|
|
cases = []
|
|
|
|
def add(name, path):
|
|
cases.append({"name": name, "data": open(path, "rb").read(), "entries": reference(path, tmp, str(len(cases)))})
|
|
|
|
for z in ("", "-z"):
|
|
arc = os.path.join(tmp, "gcab%s.cab" % z)
|
|
A.tool(["gcab"], ["gcab", "-c"] + ([z] if z else []) + [arc] + names, cwd=work)
|
|
add("gcab " + (z or "store"), arc)
|
|
arc = os.path.join(tmp, "lcab.cab")
|
|
A.tool(["lcab"], ["lcab", "-r", "dir", "hello.txt", arc], cwd=work)
|
|
add("lcab", arc)
|
|
# our builder: MSZIP with the dictionary, two folders (stored + MSZIP), reserve areas, attributes, UTF-8
|
|
big = text + rand[:20000] + text[:50000]
|
|
cab1 = build([(1, [(b"a\\text.txt", big, 0x20, 1700000000), (b"b.bin", rand, 0x01, 1600000000)], mszip_dict)])
|
|
cab2 = build([(0, [(b"stored.txt", b"stored data " * 5000, 0x20, 1700000000)], store),
|
|
(1, [("naïve ☃.txt".encode(), text, 0x80 | 0x20, 1700000002), (b"empty", b"", 0x20, 1700000000)], mszip_dict)],
|
|
reserve=(b"HEADER-RESERVE", 6, 3))
|
|
for i, c in enumerate((cab1, cab2)):
|
|
p = os.path.join(tmp, "built%d.cab" % i)
|
|
open(p, "wb").write(c)
|
|
A.tool(["cabextract"], ["cabextract", "-t", p]) # checksums and data as cabextract reads them
|
|
add(("mszip with dictionary", "two folders, reserve, utf-8")[i], p)
|
|
# LZX (our fixture compressor, checked by cabextract): windows 2^15 .. 2^21, the three block types, E8
|
|
x86 = bytearray(rng.randbytes(90000))
|
|
for i in range(0, len(x86) - 5, 23):
|
|
x86[i] = 0xE8
|
|
x86 = bytes(x86) + text[:40000]
|
|
lzx_cases = [
|
|
("lzx 2^15 text", 15, 0, [(b"t.txt", text[:100000])], None),
|
|
("lzx 2^16 mixed", 16, 0, [(b"a.txt", text), (b"b.bin", rand[:30000]), (b"c.txt", text[:5000])], None),
|
|
("lzx 2^17 types", 17, 0, [(b"m.bin", big)], [(1, 40000), (2, 30001), (3, 7777), (2, 50000), (3, 4), (1, len(big) - 127782)]),
|
|
("lzx 2^21 e8", 21, 12000000, [(b"x86.exe", x86), (b"tail.txt", text[:3000])], None),
|
|
("lzx 2^18 e8 small", 18, 70000, [(b"s.bin", x86[:20000])], [(2, 20000)]),
|
|
]
|
|
for i, (label, wb, e8size, fl, plan) in enumerate(lzx_cases):
|
|
c = build([(3 | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], lzx(wb, e8size, 100 + i, plan))])
|
|
p = os.path.join(tmp, "lzx%d.cab" % i)
|
|
open(p, "wb").write(c)
|
|
ents = reference(p, tmp, "lzx%d" % i)
|
|
want = {n.decode(): zlib.crc32(d) for n, d in fl}
|
|
if {e["name"]: e["crc"] for e in ents} != want:
|
|
raise RuntimeError("cabextract does not extract the fixture LZX cabinet " + label)
|
|
cases.append({"name": label, "data": c, "entries": ents})
|
|
# Quantum (our fixture compressor, checked by cabextract): windows 2^10 .. 2^21, model rescaling and re-sorting
|
|
quantum_cases = [
|
|
("quantum 2^10 text", 10, [(b"q.txt", text[:20000])]),
|
|
("quantum 2^16 mixed", 16, [(b"a.txt", text[:60000]), (b"b.bin", rand[:20000]), (b"c.bin", x86[:30000])]),
|
|
("quantum 2^21 big", 21, [(b"big.bin", big)]),
|
|
]
|
|
for i, (label, wb, fl) in enumerate(quantum_cases):
|
|
c = build([(2 | (4 << 4) | (wb << 8), [(n, d, 0x20, 1700000000) for n, d in fl], quantum(wb))])
|
|
p = os.path.join(tmp, "qtm%d.cab" % i)
|
|
open(p, "wb").write(c)
|
|
ents = reference(p, tmp, "qtm%d" % i)
|
|
want = {n.decode(): zlib.crc32(d) for n, d in fl}
|
|
if {e["name"]: e["crc"] for e in ents} != want:
|
|
raise RuntimeError("cabextract does not extract the fixture Quantum cabinet " + label)
|
|
cases.append({"name": label, "data": c, "entries": ents})
|
|
# the libmspack test cabinets
|
|
ms = os.path.join(tmp, "ms")
|
|
os.makedirs(ms)
|
|
subprocess.run(["tar", "xzf", mspack_cabs(), "-C", ms, "--wildcards", "*/test/test_files/cabd/*.cab"], check=True)
|
|
cabd = os.path.join(ms, os.listdir(ms)[0], "test", "test_files", "cabd")
|
|
for n in ("normal_2files_1folder", "normal_2files_2folders", "normal_255c_filename", "reserve_---", "reserve_--D",
|
|
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD", "mszip_lzx_qtm"):
|
|
add("libmspack " + n, os.path.join(cabd, n + ".cab"))
|
|
spanned = [{"name": n, "data": open(os.path.join(cabd, n + ".cab"), "rb").read()}
|
|
for n in ("multi_basic_pt1", "multi_basic_pt2", "multi_basic_pt3")]
|
|
# broken cabinets cabextract fails on (crafted bad trees, loops, short headers / strings)
|
|
bad = [{"name": n, "data": open(os.path.join(cabd, n), "rb").read()} for n in sorted(os.listdir(cabd))
|
|
if n.endswith(".cab") and (n.startswith(("partial_", "bad_", "lzx-")) or (n.startswith("cve-") and "9732" not in n))]
|
|
# our writer, extracted by the reference tools
|
|
log, ok = [], True
|
|
for opts in ("compression=mszip", "compression=none", "compression=mszip,level=1"):
|
|
data = A.ours(ctx, "cab", opts)
|
|
p = os.path.join(tmp, "ours.cab")
|
|
open(p, "wb").write(data)
|
|
for tool, argv in (("cabextract", ["cabextract", "-q", "-d", "{o}", p]), ("gcab", ["gcab", "-x", "-C", "{o}", p]),
|
|
("p7zip", ["7z", "x", "-o{o}", p])):
|
|
out = os.path.join(tmp, "o-%s-%d" % (tool, len(log)))
|
|
os.makedirs(out)
|
|
r = subprocess.run(["nix", "shell", "nixpkgs#" + tool, "-c"] + [a.replace("{o}", out) for a in argv],
|
|
capture_output=True, env=ENV)
|
|
got = A.read_tree(out)
|
|
want = {n: zlib.crc32(d) for n, d in A.FILES}
|
|
good = r.returncode == 0 and got == want
|
|
ok = ok and good
|
|
log.append("%s %s: %s" % (opts, tool, "ok" if good else "FAILED %r" % (got,)))
|
|
ctx.emit("cab", {"cases": cases, "ours": {"ok": ok, "log": "; ".join(log)}, "spanned": spanned, "bad": bad})
|
|
finally:
|
|
A.rmtree(tmp)
|