From 825c45b03cebba405f7ae08e7c4fe2cb315cf32e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:37:25 -0500 Subject: [PATCH] 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) --- docs/FORMATS.md | 1 + docs/guide/archive.md | 20 + src/Formats/Registry.luau | 12 + src/Formats/archive/cab/Sum.luau | 42 ++ src/Formats/archive/cab/init.luau | 412 ++++++++++++++++++ .../codecs/compress/Deflate/Inflate.luau | 13 +- src/Formats/codecs/compress/Deflate/init.luau | 17 +- tests/archive/cab.luau | 129 ++++++ tools/fixtures/cab.py | 179 ++++++++ tools/fixtures/docs_arch_cab.py | 30 ++ 10 files changed, 851 insertions(+), 4 deletions(-) create mode 100644 src/Formats/archive/cab/Sum.luau create mode 100644 src/Formats/archive/cab/init.luau create mode 100644 tests/archive/cab.luau create mode 100644 tools/fixtures/cab.py create mode 100644 tools/fixtures/docs_arch_cab.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5d4e73a..a89ec21 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -70,6 +70,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | binhex | .hqx .hcx | yes | yes | forks: true | `tests/archive/binhex.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | +| archive | cab | .cab | yes | yes | methods: "store", "mszip" | `tests/archive/cab.luau` | | archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` | | archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` | | archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` | diff --git a/docs/guide/archive.md b/docs/guide/archive.md index edda82c..d711803 100644 --- a/docs/guide/archive.md +++ b/docs/guide/archive.md @@ -272,6 +272,25 @@ assert(by["bin"].dir and by["bin/run.sh"].mode == 493 and by["run"].link == "bin assert(F.archive.load(isoBytes, { prefer = "joliet" }).meta.iso.tree == "joliet") ``` +## Microsoft Cabinet + +Cabinet files (`.cab`) read with stored, MSZIP, LZX and Quantum folders; each data block's checksum is checked when +a file of its folder is read. Entries carry the MS-DOS `attributes` (`readonly`, `executable`), `utf8` (the name flag) +and `folder`; DOS times are local times without a zone, read as UTC. Files continued from or into another cabinet of +a set read as `UNSUPPORTED`. Writing makes one folder, MSZIP (default, `level`) or stored (`compression = "none"`): + +```luau +local cab = assert(F.archive.load(cabBytes)) +assert(cab.format == "cab" and cab.meta.folders[1].method == "mszip") +local by = {} +for _, e in cab:list() do + by[e.name] = e +end +assert(by["bin/tool.dll"].size == 16384 and by["readme.txt"].mtime == 1767225600) +local out = assert(F.save(cab, nil, { format = "cab", compression = "none" })) +assert(F.archive.load(out):list()[1].method == "store") +``` + ## Formats | Format | Read | Write | Notes | @@ -290,6 +309,7 @@ assert(F.archive.load(isoBytes, { prefer = "joliet" }).meta.iso.tree == "joliet" | compress (`.Z`, `.taz`) | yes | yes | single stream; 9..16-bit LZW | | LZ4 (`.lz4`) | yes | yes | single stream; frames, legacy frames, XXH32 checks; no dictionaries | | ISO 9660 (`.iso`) | yes | - | Joliet, Rock Ridge, El Torito, multi-extent; no UDF | +| Cabinet (`.cab`) | yes | yes | stored / MSZIP / LZX / Quantum (read), stored / MSZIP (write); no spanned files | Full capability list: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 5d312e4..6e81c47 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -794,6 +794,18 @@ local list: { Entry } = { return require("@formats/archive/bz2") end, }, + { + name = "cab", + category = "archive", + path = "archive/cab", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip" } }, + load = function() + return require("@formats/archive/cab") + end, + }, { name = "cpio", category = "archive", diff --git a/src/Formats/archive/cab/Sum.luau b/src/Formats/archive/cab/Sum.luau new file mode 100644 index 0000000..c57c2c3 --- /dev/null +++ b/src/Formats/archive/cab/Sum.luau @@ -0,0 +1,42 @@ +--!strict +--!native +--!optimize 2 +-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3 +-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format +-- description ([MS-CAB] 2.4, CFDATA.csum). + +local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len +local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift + +local Sum = {} + +-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum) +function Sum.of(buf: buffer, off: number, len: number, seed: number): number + if off < 0 or len <= 0 or off + len > blen(buf) then + return seed + end + local s = seed + local p = off + local stop = off + len - len % 4 + while p < stop do + s = bxor(s, readu32(buf, p)) + p += 4 + end + local rem = len % 4 + local tail = 0 + if rem == 3 then + tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2)) + elseif rem == 2 then + tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1)) + elseif rem == 1 then + tail = readu8(buf, p) + end + return bxor(s, tail) +end + +-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData) +function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number + return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536) +end + +return Sum diff --git a/src/Formats/archive/cab/init.luau b/src/Formats/archive/cab/init.luau new file mode 100644 index 0000000..cb30c8e --- /dev/null +++ b/src/Formats/archive/cab/init.luau @@ -0,0 +1,412 @@ +--!strict +-- archive/cab: Microsoft Cabinet files (MSCF 1.3) read into an Archive: the header with its reserve areas and +-- cabinet set fields, folders (CFFOLDER) compressed with none, MSZIP (each CFDATA block "CK" + raw deflate whose +-- dictionary carries over from the block before), LZX (codecs/compress/Lzx, windows 2^15..2^21) or Quantum +-- (codecs/compress/Quantum, windows 2^10..2^21), the files (CFFILE) with their MS-DOS attributes, DOS times (local +-- time without a zone, read as UTC) and the UTF-8 name flag; every data block's checksum is verified (Err.CHECKSUM) +-- when a file of its folder is read. A folder is decompressed once per read and kept for the next file of the same +-- folder. Writes one folder, stored or MSZIP (independent 32 KB deflate blocks), from any Archive. Written from the +-- Microsoft Cabinet format specification ([MS-CAB]). Not supported: files continued from / to another cabinet of a +-- set (Err.UNSUPPORTED for those entries, and for the first folder of a cabinet continued from a previous one), +-- signed / self-extracting stubs before the header. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Deflate = require("@formats/codecs/compress/Deflate") +local Archive = require("@formats/containers/Archive") +local Sum = require("@formats/archive/cab/Sum") + +-- ------------------------------------------------------------------------------------------------ contract +local Cab = { + name = "cab", + category = "archive", + extensions = { "cab" }, + mime = { "application/vnd.ms-cab-compressed" }, + deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "containers/Archive" }, + caps = { decode = true, encode = true, methods = { "store", "mszip" } }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a folder that decompresses to more than this (default 2^30) + maxEntries: number?, -- default 65535 + verify: boolean?, -- check the data block checksums (default true) +} +export type EncodeOptions = { + compression: ("mszip" | "none")?, -- default "mszip" + level: number?, -- deflate level 0..9 (default 6) + setId: number?, -- the cabinet set id (default 0) +} + +-- ------------------------------------------------------------------------------------------------ constants +local FLAG_PREV, FLAG_NEXT, FLAG_RESERVE = 0x0001, 0x0002, 0x0004 +local ATTR_UTF8 = 0x80 +local METHOD = { [0] = "store", "mszip", "quantum", "lzx" } +local BLOCK = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function Cab.sniff(r: Bytes.Reader): number + if r:peek(8) == "MSCF\0\0\0\0" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Folder = { + dataAt: number, -- offset of the first CFDATA (relative to the reader) + blocks: number, + type: number, -- typeCompress + index: number, +} +type Block = { at: number, len: number, size: number } + +-- the CFDATA blocks of a folder (checksums checked), their total output and whether the folder runs into the next +-- cabinet (a block with cbUncomp 0) +local function blocks(r: Bytes.Reader, f: Folder, dataReserve: number, verify: boolean, maxBytes: number): ({ Block }?, any, boolean?) + local list: { Block } = {} + local p = f.dataAt + local total = 0 + for i = 1, f.blocks do + local h = r:sub(p, 8) + local csum, cbData, cbUncomp = h:u32le(), h:u16le(), h:u16le() + if h.err then + return nil, Err.new(Err.TRUNCATED, "data block header past the end", r.base + p) + end + local at = p + 8 + dataReserve + if at + cbData > r:size() then + return nil, Err.new(Err.TRUNCATED, "data block past the end", r.base + p) + end + if cbUncomp == 0 then + return list, total, true + end + if verify and csum ~= 0 and Sum.block(r.buf, r.base + at, cbData, cbUncomp) ~= csum then + return nil, Err.new(Err.CHECKSUM, "data block " .. i .. " checksum mismatch", r.base + p) + end + total += cbUncomp + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "folder larger than maxBytes") + end + table.insert(list, { at = r.base + at, len = cbData, size = cbUncomp }) + p = at + cbData + end + return list, total, false +end + +-- the decompressed data of a folder's blocks +local function inflateFolder(buf: buffer, list: { Block }, total: number, typ: number): (buffer?, Err.Err?) + local method = bit32.band(typ, 15) + local out = buffer.create(total) + if method == 0 then + local o = 0 + for _, b in list do + if b.len ~= b.size then + return nil, Err.new(Err.CORRUPT, "stored block with different sizes", b.at) + end + buffer.copy(out, o, buf, b.at, b.len) + o += b.len + end + return out, nil + elseif method == 1 then + local o = 0 + for _, b in list do + if b.len < 2 or buffer.readu16(buf, b.at) ~= 0x4B43 then + return nil, Err.new(Err.CORRUPT, "MSZIP block without its CK signature", b.at) + end + local dict: buffer? = nil + if o > 0 then + local d = math.min(o, BLOCK) + dict = buffer.create(d) + buffer.copy(dict :: buffer, 0, out, o - d, d) + end + local part, err = Deflate.inflate(buf, b.at + 2, b.len - 2, b.size, dict) + if not part then + return nil, err + end + buffer.copy(out, o, part, 0, b.size) + o += b.size + end + return out, nil + end + return nil, Err.new(Err.UNSUPPORTED, "compression type " .. method) +end + +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Cab.encode(archive, opts) +end + +function Cab.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local maxBytes = o.maxBytes or 2 ^ 30 + local maxEntries = o.maxEntries or 65535 + local verify = o.verify ~= false + if not r:match("MSCF") then + return nil, Err.new(Err.CORRUPT, "no MSCF signature", r.base) + end + r:skip(4) + local cbCabinet = r:u32le() + r:skip(4) + local coffFiles = r:u32le() + r:skip(4) + local minor, major = r:u8(), r:u8() + local cFolders, cFiles, flags = r:u16le(), r:u16le(), r:u16le() + local setId, iCabinet = r:u16le(), r:u16le() + local headerReserve, folderReserve, dataReserve = 0, 0, 0 + if bit32.band(flags, FLAG_RESERVE) ~= 0 then + headerReserve, folderReserve, dataReserve = r:u16le(), r:u8(), r:u8() + end + local a = Archive.new("cab", encode) + local meta: any = a.meta + if headerReserve > 0 then + meta.reserve = r:bytes(headerReserve) + end + if bit32.band(flags, FLAG_PREV) ~= 0 then + meta.prevCabinet, meta.prevDisk = r:cstring(256), r:cstring(256) + end + if bit32.band(flags, FLAG_NEXT) ~= 0 then + meta.nextCabinet, meta.nextDisk = r:cstring(256), r:cstring(256) + end + if r.err then + return nil, r.err + end + if major ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, "cabinet version " .. major .. "." .. minor) + end + meta.setId, meta.cabinet = setId, iCabinet + meta.source = { + format = "cab", + version = major .. "." .. minor, + size = cbCabinet, + flags = flags, + reserve = { header = headerReserve, folder = folderReserve, data = dataReserve }, + } + -- folders + local folders: { Folder } = {} + local methods = {} + for i = 1, cFolders do + local dataAt, nblocks, typ = r:u32le(), r:u16le(), r:u16le() + r:skip(folderReserve) + if r.err then + return nil, r.err + end + folders[i] = { dataAt = dataAt, blocks = nblocks, type = typ, index = i } + local m = METHOD[bit32.band(typ, 15)] + methods[i] = { + method = m or ("type " .. bit32.band(typ, 15)), + window = if m == "lzx" or m == "quantum" then bit32.band(bit32.rshift(typ, 8), 31) else nil, + level = if m == "quantum" then bit32.band(bit32.rshift(typ, 4), 15) else nil, + blocks = nblocks, + } + end + meta.folders = methods + if cFiles > maxEntries then + return nil, Err.new(Err.LIMIT, "more than maxEntries files") + end + -- the folder cache: the last decompressed folder + local cachedIndex, cachedData, cachedRuns = 0, nil :: buffer?, false + local function folderData(f: Folder): (buffer?, Err.Err?, boolean?) + if cachedIndex == f.index then + return cachedData, nil, cachedRuns + end + local list, total, runs = blocks(r, f, dataReserve, verify, maxBytes) + if not list then + return nil, total, false + end + local data, err = inflateFolder(r.buf, list, total, f.type) + if not data then + return nil, err, false + end + cachedIndex, cachedData, cachedRuns = f.index, data, runs == true + return data, nil, runs + end + -- files + local fr = r:sub(coffFiles) + for _ = 1, cFiles do + local size, offset, iFolder = fr:u32le(), fr:u32le(), fr:u16le() + local date, time, attribs = fr:u16le(), fr:u16le(), fr:u16le() + local raw = fr:cstring(65536) + if fr.err then + return nil, fr.err + end + local name = string.gsub(raw, "\\", "/") + local spanned: string? = nil + local folder: Folder? + if iFolder == 0xFFFD or iFolder == 0xFFFF then + spanned = "a file continued from the previous cabinet" + folder = folders[1] + elseif iFolder == 0xFFFE then + spanned = "a file continued in the next cabinet" + folder = folders[#folders] + else + folder = folders[iFolder + 1] + if iFolder == 0 and bit32.band(flags, FLAG_PREV) ~= 0 then + spanned = "a folder continued from the previous cabinet" + end + end + if not folder then + return nil, Err.new(Err.CORRUPT, "file " .. name .. " in a missing folder " .. iFolder) + end + local fo = folder :: Folder + if size > maxBytes then + return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes") + end + local e: any = { + name = name, + size = size, + method = METHOD[bit32.band(fo.type, 15)] or "unknown", + mtime = Archive.fromDos(date * 65536 + time), + dir = false, + attributes = bit32.band(attribs, 0xFF7F), + utf8 = bit32.band(attribs, ATTR_UTF8) ~= 0, + folder = fo.index, + offset = offset, + readonly = bit32.band(attribs, 0x01) ~= 0, + executable = bit32.band(attribs, 0x40) ~= 0, + } + if spanned then + e.spanned = true + end + if size > 0 or spanned then + e.load = function(): (buffer?, Err.Err?) + if spanned then + return nil, Err.new(Err.UNSUPPORTED, spanned :: string) + end + local data, err, runs = folderData(fo) + if not data then + return nil, err + end + if offset + size > buffer.len(data) then + if runs then + return nil, Err.new(Err.UNSUPPORTED, "a file continued in the next cabinet") + end + return nil, Err.new(Err.CORRUPT, "file past the end of its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, data, offset, size) + return out, nil + end + end + Archive.put(a, e) + end + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- encode(archive, opts?) -> a cabinet with one folder holding every file (directories are implied by the names) +function Cab.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local compression = o.compression or "mszip" + if compression ~= "mszip" and compression ~= "none" then + return nil, Err.new(Err.ARG, "compression must be \"mszip\" or \"none\"") + end + local level = o.level or 6 + if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then + return nil, Err.new(Err.ARG, "level must be 0..9") + end + local files, ferr = Archive.files(archive) + if not files then + return nil, ferr + end + if #files > 65535 then + return nil, Err.new(Err.ARG, "more than 65535 files") + end + local total = 0 + for _, f in files do + total += buffer.len(f.data) + end + if total > 0x7FFF8000 then + return nil, Err.new(Err.ARG, "more than 2 GB of data") + end + -- the folder data, in 32 KB blocks + local folder = buffer.create(total) + local p = 0 + for _, f in files do + buffer.copy(folder, p, f.data, 0, buffer.len(f.data)) + p += buffer.len(f.data) + end + local data = Bytes.writer(total // 2 + 64) + local nblocks = 0 + local s = 0 + while s < total do + local n = math.min(BLOCK, total - s) + local chunk = buffer.create(n) + buffer.copy(chunk, 0, folder, s, n) + local payload: buffer + if compression == "mszip" then + local z, zerr = Deflate.compress(chunk, { level = level }) + if not z then + return nil, zerr + end + payload = buffer.create(buffer.len(z) + 2) + buffer.writeu16(payload, 0, 0x4B43) + buffer.copy(payload, 2, z, 0, buffer.len(z)) + else + payload = chunk + end + local len = buffer.len(payload) + data:u32le(Sum.block(payload, 0, len, n)) + data:u16le(len) + data:u16le(n) + data:bytes(payload) + nblocks += 1 + s += n + end + local blob = data:finish() + -- names and the file table + local table_ = Bytes.writer(64 + #files * 32) + local offset = 0 + for _, f in files do + local e: any = f.entry + local name = string.gsub(f.name, "/", "\\") + local attribs = if type(e.attributes) == "number" then bit32.band(e.attributes, 0x7F) else 0x20 + if string.find(name, "[\128-\255]") then + attribs = bit32.bor(attribs, ATTR_UTF8) + end + local stamp = Archive.toDos(e.mtime) + table_:u32le(buffer.len(f.data)) + table_:u32le(offset) + table_:u16le(0) + table_:u16le(stamp // 65536) + table_:u16le(stamp % 65536) + table_:u16le(attribs) + table_:cstring(name) + offset += buffer.len(f.data) + end + local fileTable = table_:finish() + local nfolders = if #files > 0 then 1 else 0 + local coffFiles = 36 + 8 * nfolders + local dataAt = coffFiles + buffer.len(fileTable) + local size = dataAt + buffer.len(blob) + local w = Bytes.writer(size) + w:string("MSCF") + w:u32le(0) + w:u32le(size) + w:u32le(0) + w:u32le(coffFiles) + w:u32le(0) + w:u8(3) + w:u8(1) + w:u16le(nfolders) + w:u16le(#files) + w:u16le(0) + w:u16le(o.setId or 0) + w:u16le(0) + if nfolders == 1 then + w:u32le(dataAt) + w:u16le(nblocks) + w:u16le(if compression == "mszip" then 1 else 0) + end + w:bytes(fileTable) + w:bytes(blob) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty cab Archive: a:add(name, data, { mtime }); a:write({ compression = "none" | "mszip" }) +function Cab.new(): any + local a = Archive.new("cab", encode) + a.meta.source = { format = "cab" } + return a +end + +return Cab diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau index 456464f..5927590 100644 --- a/src/Formats/codecs/compress/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -64,10 +64,19 @@ end -- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in -- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and -- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). +-- dict: a preset dictionary (the data before the stream, e.g. MSZIP's previous block): out starts with a copy of it, +-- distances may reach into it, and outLen includes it (cap does not). -- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?) - local out = bcreate(cap) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?, dict: buffer?): (buffer?, any, number?) local op = 0 + if dict then + op = blen(dict) + cap += op + end + local out = bcreate(cap) + if dict then + bcopy(out, 0, dict, 0, op) + end local pos = start local bitbuf, bitcnt, over = 0, 0, 0 local lt, dt = bcreate(LITCAP * 4), bcreate(DISTCAP * 4) :: buffer diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index fd25c71..b4c5319 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -6,6 +6,7 @@ -- local Deflate = require("@formats/codecs/compress/Deflate") -- local out, err = Deflate.inflate(buf) -- raw deflate -> buffer, consumedEnd | nil, Err -- local out, err = Deflate.inflate(buf, off, len, size) -- a range, with the exact output size if known +-- local out, err = Deflate.inflate(buf, off, len, size, dict) -- with a preset dictionary (MSZIP blocks) -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 -- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members -- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip @@ -43,7 +44,9 @@ end -- inflate(buf, offset?, length?, expectedSize?) -> buffer, consumedEnd | nil, Err. Raw deflate. -- expectedSize: the exact uncompressed size when known (a zip entry): the output is allocated once, and a stream -- that inflates to a different size is an error. consumedEnd is the input offset just past the final block. -function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?): (buffer?, any) +-- dict: a preset dictionary (up to 32 KB of data before the stream, as MSZIP's previous block): back references may +-- reach into it; the result holds only the new bytes. +function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, expectedSize: number?, dict: buffer?): (buffer?, any) local b, o, l, aerr = args("Deflate.inflate", buf, offset, length) if not b then return nil, aerr @@ -58,10 +61,20 @@ function Deflate.inflate(buf: buffer | string, offset: number?, length: number?, else cap = math.max(1024, l * 4) end - local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact) + if dict ~= nil and type(dict) ~= "buffer" then + return nil, Err.new(Err.ARG, "Deflate.inflate: dict must be a buffer") + end + local out, n, consumed = Inflate.raw(b, o, o + l, cap :: number, exact, false, dict) if not out then return nil, inflateErr(tostring(n), o) end + if dict then + local d = buffer.len(dict) + n -= d + local res = buffer.create(n) + buffer.copy(res, 0, out, d, n) + out = res + end if exact and n ~= expectedSize then return nil, Err.new(Err.CORRUPT, string.format("inflate: output is %d bytes, expected %d", n, expectedSize :: number)) end diff --git a/tests/archive/cab.luau b/tests/archive/cab.luau new file mode 100644 index 0000000..e818db3 --- /dev/null +++ b/tests/archive/cab.luau @@ -0,0 +1,129 @@ +-- archive/cab tests: cabinets by gcab (stored / MSZIP), lcab, a builder of MSZIP blocks that use the previous block as +-- their dictionary (several folders, reserve areas, attributes, UTF-8 names) and libmspack's test cabinets give the +-- files cabextract extracts (names, sizes, data CRCs, DOS times read as UTC); cabextract / gcab / 7z extract our +-- writer's output (fixture step) and it round-trips; spanned files are UNSUPPORTED; checksum, truncation and +-- signature errors; Deflate's preset dictionary; the fuzz pass. Fixtures: tools/fixtures/cab.py. +local T = require("@tests/T") +local F = require("@formats") +local Cab = require("@formats/archive/cab") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Deflate = require("@formats/codecs/compress/Deflate") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/cab") + +local t = T.suite("cab") +t:eq(Cab.name, "cab", "name") + +local function load(s: string, opts: any?): (any, Err.Err?) + return Cab.decode(Bytes.reader(buffer.fromstring(s)), opts) +end + +local samples = {} +local methods = {} +for _, c in Fx.cases do + local a, err = load(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name) + for _, e in a:list() do + methods[e.method] = true + end + end + t:eq(F.detect(c.data), "cab", c.name .. ": detect") + table.insert(samples, string.sub(c.data, 1, 4000)) +end +t:check(methods.store and methods.mszip, "covers store and mszip") + +-- attributes, UTF-8 names, reserve areas (the builder's two-folder cabinet) +local two = assert(load(Fx.cases[5].data)) +local naive = two._byName["na\u{ef}ve \u{2603}.txt"] +t:check(naive and naive.utf8 and naive.attributes == 0x20, "utf-8 name and attributes") +t:eq(two.meta.source.reserve.data, 3, "data reserve") +t:eq(buffer.tostring(two.meta.reserve), "HEADER-RESERVE", "header reserve") +t:eq(#two.meta.folders, 2, "two folders") +t:check(assert(load(Fx.cases[4].data))._byName["b.bin"].readonly, "read-only attribute") + +-- our writer +t:check(Fx.ours.ok, "reference tools extract our cabinets: " .. Fx.ours.log) +E.roundTrip(t, Cab, nil, "round trip mszip") +E.roundTrip(t, Cab, { compression = "none" }, "round trip store") +local big = Cab.new() +big:add("dir/big.bin", E.content(200000, 3), { mtime = 1700000000 }) +big:add("x.txt", "x") +local bigData = assert(big:write()) +local back = assert(Cab.decode(Bytes.reader(bigData))) +t:eq(buffer.tostring(assert(back:read("dir/big.bin"))), buffer.tostring(E.content(200000, 3)), "200 KB through 7 blocks") +t:eq(back:list()[1].mtime, 1700000000, "mtime") +t:eq(select(2, Cab.encode(big, { compression = "lzx" :: any })).code, Err.ARG, "bad compression") + +-- spanned cabinets: files continued from / to another cabinet are UNSUPPORTED, the others read +for _, c in Fx.spanned do + local a, err = load(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + local unsupported = 0 + for _, e in a:list() do + local b, rerr = a:read(e.name) + if not b then + t:eq(rerr.code, Err.UNSUPPORTED, c.name .. ": " .. e.name) + unsupported += 1 + end + end + t:check(unsupported > 0, c.name .. ": has spanned files") + end +end + +-- Deflate's preset dictionary +local dictText = string.rep("abcdefgh", 100) +local z = assert(Deflate.compress(dictText .. dictText)) +local plain = assert(Deflate.inflate(z, nil, nil, 1600, buffer.fromstring("unused prefix"))) +t:eq(buffer.tostring(plain), dictText .. dictText, "inflate with an unused dictionary") + +-- errors +local data = Fx.cases[2].data -- gcab -z +local function code(s: string): string? + local a, e = load(s) + if not a then + return e and e.code + end + for _, en in a:list() do + local b, rerr = a:read(en.name) + if not b then + return rerr and rerr.code + end + end + return nil +end +t:eq(code(data), nil, "intact") +t:eq(code("MSCF\0\0\0\0" .. string.rep("\0", 10)), Err.TRUNCATED, "short header") +t:eq(code("PK\3\4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"), Err.CORRUPT, "not a cabinet") +t:eq(code(string.sub(data, 1, #data - 100)), Err.TRUNCATED, "cut") +local mid = #data - 200 +local flipped = string.sub(data, 1, mid - 1) .. string.char(bit32.bxor(string.byte(data, mid), 0x08)) .. string.sub(data, mid + 1) +t:eq(code(flipped), Err.CHECKSUM, "flipped data byte") +local a2 = assert(load(flipped, { verify = false })) +local failed = 0 +for _, e in a2:list() do + if not a2:read(e.name) then + failed += 1 + end +end +t:note("flipped byte without verify: %d entries fail", failed) + +t:fuzz("decode", function(b: buffer) + local r = Cab.decode(Bytes.reader(b)) + if r then + for _, e in r:list() do + r:read(e.name) + end + end + local r2 = Cab.decode(Bytes.reader(b), { verify = false }) + if r2 then + for _, e in r2:list() do + r2:read(e.name) + end + end + return r +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/fixtures/cab.py b/tools/fixtures/cab.py new file mode 100644 index 0000000..cf86ebe --- /dev/null +++ b/tools/fixtures/cab.py @@ -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(" 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(" 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) diff --git a/tools/fixtures/docs_arch_cab.py b/tools/fixtures/docs_arch_cab.py new file mode 100644 index 0000000..79ca4b0 --- /dev/null +++ b/tools/fixtures/docs_arch_cab.py @@ -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"})