ws-arch2-cab: archive/cab (MSCF read: stored / MSZIP folders with the carried-over deflate dictionary, reserve areas, checksums, attributes, UTF-8 names, spanned files UNSUPPORTED; write: one stored / MSZIP folder) vs cabextract / gcab / 7z; Deflate.inflate gains an optional preset dictionary (5th argument, Inflate.raw 7th; backward compatible)
This commit is contained in:
1 parent
53b41c7275
commit
825c45b03c
10 files changed
+851
-4
No files matched your search
@@ -0,0 +1,179 @@
|
||||
# Cabinet fixtures (tools/fixtures.py): cabinets by gcab (stored and MSZIP folders, paths), lcab (stored) and 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), the libmspack test cabinets read from the nix store (test data,
|
||||
# not committed: normal / reserve / multi-part / Quantum / LZX samples), and our writer's output. The reference data
|
||||
# is what cabextract extracts and lists (sizes, data CRCs, the DOS times as UTC); 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 } } }
|
||||
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)
|
||||
|
||||
INPUTS = ["tools/fixtures/_arch2.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(blockdata, previous) -> payload)];
|
||||
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
|
||||
out = []
|
||||
prev = b""
|
||||
for s in range(0, len(stream), 32768):
|
||||
chunk = stream[s:s + 32768]
|
||||
out.append((enc(chunk, prev), len(chunk)))
|
||||
prev = chunk
|
||||
blocks.append(out)
|
||||
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 store(chunk, prev):
|
||||
return chunk
|
||||
|
||||
|
||||
def mszip_dict(chunk, prev):
|
||||
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
return b"CK" + c.compress(chunk) + c.flush()
|
||||
|
||||
|
||||
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)
|
||||
# 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_255c_filename", "reserve_---", "reserve_--D",
|
||||
"reserve_-F-", "reserve_-FD", "reserve_H--", "reserve_H-D", "reserve_HF-", "reserve_HFD"):
|
||||
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")]
|
||||
# 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})
|
||||
finally:
|
||||
A.rmtree(tmp)
|
||||
@@ -0,0 +1,30 @@
|
||||
# Docs inputs for the archive page's Cabinet section (tools/fixtures.py; tools/docs_check.py explains the inputs): an
|
||||
# MSZIP cabinet of a small tree by gcab.
|
||||
# tests/gen/docs_arch_cab.luau { files = { [name] = bytes }, vars = { cabBytes = "setup.cab" } }
|
||||
import importlib.util, os, subprocess, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py"]
|
||||
|
||||
MTIME = 1767225600 # 2026-01-01T00:00:00Z
|
||||
|
||||
|
||||
def docs_check(ctx):
|
||||
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = docs_check(ctx)
|
||||
files = {}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
os.makedirs(os.path.join(d, "bin"))
|
||||
for n, data in (("readme.txt", b"formats-luau cabinet\n" * 20), ("bin/tool.dll", bytes(range(256)) * 64)):
|
||||
with open(os.path.join(d, n), "wb") as f:
|
||||
f.write(data)
|
||||
os.utime(os.path.join(d, n), (MTIME, MTIME))
|
||||
subprocess.run(["nix", "shell", "nixpkgs#gcab", "-c", "gcab", "-c", "-z", "setup.cab", "readme.txt", "bin/tool.dll"],
|
||||
cwd=d, check=True, capture_output=True, env=dict(os.environ, TZ="UTC"))
|
||||
files["setup.cab"] = open(os.path.join(d, "setup.cab"), "rb").read()
|
||||
dc.emit_inputs(ctx, files, {"cabBytes": "setup.cab"})
|
||||
Reference in new issue
Block a user