diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 91830ba..0ad1d19 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | png | .png .apng | yes | yes | animation: false, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | +| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | Codecs (layer 1, shared by formats; not loadable on their own): diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index a10375f..d0b35a8 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/png") end, }, + { + name = "7z", + category = "archive", + path = "archive/7z", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, + load = function() + return require("@formats/archive/7z") + end, + }, { name = "xz", category = "archive", diff --git a/src/Formats/archive/7z/Header.luau b/src/Formats/archive/7z/Header.luau new file mode 100644 index 0000000..c85accc --- /dev/null +++ b/src/Formats/archive/7z/Header.luau @@ -0,0 +1,542 @@ +--!strict +-- archive/7z/Header: the 7z header parser (7zFormat.txt from the LZMA SDK / 7-Zip, Igor Pavlov, public domain): +-- streams info (pack info, folders with their coders and bind pairs, substreams), files info (names, empty streams / +-- files, anti items, times, attributes). Not --!native: a parse failure raises an Err value that parse() catches and +-- returns; any other error is a bug and propagates (the tests' fuzz pass sees it). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local Header = {} + +export type Coder = { id: string, numIn: number, numOut: number, props: buffer } +export type Folder = { + coders: { Coder }, + bindPairs: { { inIndex: number, outIndex: number } }, + packed: { number }, -- in-stream index of each packed stream + unpackSizes: { number }, -- per out stream + crc: number?, + firstPack: number, -- index of the folder's first pack stream (0-based) + numSub: number, -- substreams (files) in the folder +} +export type Streams = { + packPos: number, + packSizes: { number }, + folders: { Folder }, + subSizes: { number }, -- every substream, folder by folder + subCrcs: { [number]: number }, -- 1-based substream index -> CRC +} +export type File = { + name: string, + emptyStream: boolean, + emptyFile: boolean, + anti: boolean, + mtime: number?, + attributes: number?, +} +export type Parsed = { streams: Streams?, files: { File }, encoded: Streams? } + +local K = { + End = 0x00, + Header = 0x01, + ArchiveProperties = 0x02, + AdditionalStreamsInfo = 0x03, + MainStreamsInfo = 0x04, + FilesInfo = 0x05, + PackInfo = 0x06, + UnPackInfo = 0x07, + SubStreamsInfo = 0x08, + Size = 0x09, + CRC = 0x0A, + Folder = 0x0B, + CodersUnPackSize = 0x0C, + NumUnPackStream = 0x0D, + EmptyStream = 0x0E, + EmptyFile = 0x0F, + Anti = 0x10, + Name = 0x11, + MTime = 0x14, + WinAttributes = 0x15, + EncodedHeader = 0x17, + Dummy = 0x19, +} +Header.K = K + +local Fail = {} + +local function bad(r: Bytes.Reader, msg: string, code: string?): never + error(setmetatable({ err = Err.new(code or Err.CORRUPT, msg, r.pos) }, Fail), 0) +end + +local function check(r: Bytes.Reader) + if r.err then + error(setmetatable({ err = r.err }, Fail), 0) + end +end + +local function byte(r: Bytes.Reader): number + local v = r:u8() + check(r) + return v +end + +-- NUMBER: the first byte's leading 1 bits count the extra (little-endian) bytes +local function number(r: Bytes.Reader): number + local first = byte(r) + local mask = 0x80 + local value = 0 + for i = 0, 7 do + if bit32.band(first, mask) == 0 then + local high = bit32.band(first, mask - 1) + return value + high * 2 ^ (8 * i) + end + value += byte(r) * 2 ^ (8 * i) + mask = bit32.rshift(mask, 1) + end + return value +end + +-- a count bounded by the bytes left (every counted item takes at least `min` bytes) +local function count(r: Bytes.Reader, min: number?): number + local n = number(r) + if n * (min or 1) > r:remaining() + 1 then + bad(r, "count " .. n .. " is larger than the header") + end + return n +end + +local function bits(r: Bytes.Reader, n: number): { boolean } + local out = table.create(n, false) + local cur, mask = 0, 0 + for i = 1, n do + if mask == 0 then + cur = byte(r) + mask = 0x80 + end + out[i] = bit32.band(cur, mask) ~= 0 + mask = bit32.rshift(mask, 1) + end + return out +end + +-- bits preceded by an "all defined" byte +local function defined(r: Bytes.Reader, n: number): { boolean } + if byte(r) ~= 0 then + return table.create(n, true) + end + return bits(r, n) +end + +local function digests(r: Bytes.Reader, n: number): { [number]: number } + local def = defined(r, n) + local out = {} + for i = 1, n do + if def[i] then + out[i] = r:u32le() + end + end + check(r) + return out +end + +local function packInfo(r: Bytes.Reader, s: Streams) + s.packPos = number(r) + local n = count(r) + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.Size then + for i = 1, n do + s.packSizes[i] = number(r) + end + elseif t == K.CRC then + digests(r, n) + else + bad(r, "unexpected property " .. t .. " in pack info") + end + end + if #s.packSizes ~= n then + bad(r, "missing pack sizes") + end +end + +local function folder(r: Bytes.Reader): Folder + local ncoders = count(r) + if ncoders == 0 or ncoders > 64 then + bad(r, "bad coder count " .. ncoders) + end + local f: Folder = { coders = {}, bindPairs = {}, packed = {}, unpackSizes = {}, crc = nil, firstPack = 0, numSub = 1 } + local totalIn, totalOut = 0, 0 + for _ = 1, ncoders do + local flags = byte(r) + if bit32.band(flags, 0x80) ~= 0 then + bad(r, "alternative coder methods", Err.UNSUPPORTED) + end + local idSize = bit32.band(flags, 0x0F) + local id = r:string(idSize) + check(r) + local nin, nout = 1, 1 + if bit32.band(flags, 0x10) ~= 0 then + nin, nout = number(r), number(r) + if nin > 64 or nout > 64 then + bad(r, "bad coder stream count") + end + end + local props = buffer.create(0) + if bit32.band(flags, 0x20) ~= 0 then + local n = count(r) + props = r:bytes(n) + check(r) + end + table.insert(f.coders, { id = id, numIn = nin, numOut = nout, props = props }) + totalIn += nin + totalOut += nout + end + if totalOut == 0 then + bad(r, "a folder without output") + end + for _ = 1, totalOut - 1 do + local i, o = number(r), number(r) + table.insert(f.bindPairs, { inIndex = i, outIndex = o }) + end + local npacked = totalIn - (totalOut - 1) + if npacked < 1 then + bad(r, "bad bind pairs") + end + if npacked == 1 then + for i = 0, totalIn - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.inIndex == i then + bound = true + end + end + if not bound then + table.insert(f.packed, i) + break + end + end + if #f.packed ~= 1 then + bad(r, "no packed stream") + end + else + for _ = 1, npacked do + table.insert(f.packed, number(r)) + end + end + return f +end + +-- the folder's main out stream: the one no bind pair consumes +function Header.mainOut(f: Folder): number? + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for o = 0, total - 1 do + local bound = false + for _, bp in f.bindPairs do + if bp.outIndex == o then + bound = true + end + end + if not bound then + return o + end + end + return nil +end + +function Header.unpackSize(f: Folder): number + local m = Header.mainOut(f) + return if m then f.unpackSizes[m + 1] or 0 else 0 +end + +local function unpackInfo(r: Bytes.Reader, s: Streams) + if byte(r) ~= K.Folder then + bad(r, "expected the folder list") + end + local n = count(r) + if byte(r) ~= 0 then + bad(r, "external folders", Err.UNSUPPORTED) + end + for i = 1, n do + s.folders[i] = folder(r) + end + if byte(r) ~= K.CodersUnPackSize then + bad(r, "expected the coder unpack sizes") + end + for _, f in s.folders do + local total = 0 + for _, c in f.coders do + total += c.numOut + end + for k = 1, total do + f.unpackSizes[k] = number(r) + end + end + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.CRC then + local d = digests(r, n) + for i = 1, n do + s.folders[i].crc = d[i] + end + else + bad(r, "unexpected property " .. t .. " in unpack info") + end + end +end + +local function subStreamsInfo(r: Bytes.Reader, s: Streams) + local t = byte(r) + if t == K.NumUnPackStream then + for _, f in s.folders do + f.numSub = count(r, 0) + end + t = byte(r) + end + local sizes = s.subSizes + if t == K.Size then + for _, f in s.folders do + if f.numSub > 0 then + local sum = 0 + for _ = 1, f.numSub - 1 do + local v = number(r) + sum += v + table.insert(sizes, v) + end + local total = Header.unpackSize(f) + if sum > total then + bad(r, "substream sizes exceed the folder") + end + table.insert(sizes, total - sum) + end + end + t = byte(r) + else + for _, f in s.folders do + if f.numSub > 1 then + bad(r, "missing substream sizes") + elseif f.numSub == 1 then + table.insert(sizes, Header.unpackSize(f)) + end + end + end + -- CRCs for the streams whose folder CRC does not already cover them + local unknown = 0 + for _, f in s.folders do + if not (f.numSub == 1 and f.crc) then + unknown += f.numSub + end + end + while t ~= K.End do + if t == K.CRC then + local d = digests(r, unknown) + local k, si = 1, 1 + for _, f in s.folders do + if f.numSub == 1 and f.crc then + s.subCrcs[si] = f.crc + si += 1 + else + for _ = 1, f.numSub do + s.subCrcs[si] = d[k] + k += 1 + si += 1 + end + end + end + else + bad(r, "unexpected property " .. t .. " in substreams info") + end + t = byte(r) + end +end + +local function streamsInfo(r: Bytes.Reader): Streams + local s: Streams = { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + local sawSub = false + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.PackInfo then + packInfo(r, s) + elseif t == K.UnPackInfo then + unpackInfo(r, s) + elseif t == K.SubStreamsInfo then + subStreamsInfo(r, s) + sawSub = true + else + bad(r, "unexpected property " .. t .. " in streams info") + end + end + if not sawSub then + for i, f in s.folders do + f.numSub = 1 + table.insert(s.subSizes, Header.unpackSize(f)) + if f.crc then + s.subCrcs[i] = f.crc + end + end + end + local p = 0 + for _, f in s.folders do + f.firstPack = p + p += #f.packed + end + if p > #s.packSizes then + bad(r, "folders use more pack streams than exist") + end + return s +end + +local function utf16(b: buffer, o: number, n: number): string + local out = {} + local i = 0 + while i + 1 < n do + local u = buffer.readu16(b, o + i) + i += 2 + if u >= 0xD800 and u < 0xDC00 and i + 1 < n then + local lo = buffer.readu16(b, o + i) + if lo >= 0xDC00 and lo < 0xE000 then + u = 0x10000 + (u - 0xD800) * 1024 + (lo - 0xDC00) + i += 2 + end + end + table.insert(out, utf8.char(u)) + end + return table.concat(out) +end + +local function filesInfo(r: Bytes.Reader): { File } + local n = count(r, 0) + if n > 1000000 then + bad(r, "too many files", Err.LIMIT) + end + local files: { File } = table.create(n) + for i = 1, n do + files[i] = { name = "", emptyStream = false, emptyFile = false, anti = false } + end + local empties = {} + while true do + local t = byte(r) + if t == K.End then + break + end + local size = number(r) + if size > r:remaining() then + bad(r, "file property past the header") + end + local pr = r:slice(size) + check(r) + if t == K.EmptyStream then + local v = bits(pr, n) + empties = {} + for i = 1, n do + files[i].emptyStream = v[i] + if v[i] then + table.insert(empties, i) + end + end + elseif t == K.EmptyFile or t == K.Anti then + local v = bits(pr, #empties) + for k, i in empties do + if t == K.EmptyFile then + files[i].emptyFile = v[k] + else + files[i].anti = v[k] + end + end + elseif t == K.Name then + if byte(pr) ~= 0 then + bad(pr, "external names", Err.UNSUPPORTED) + end + local b = pr.buf + local p = pr.pos + for i = 1, n do + local q = p + while q + 1 < pr.limit and buffer.readu16(b, q) ~= 0 do + q += 2 + end + if q + 1 >= pr.limit then + bad(pr, "unterminated name") + end + files[i].name = utf16(b, p, q - p) + p = q + 2 + end + elseif t == K.MTime or t == K.WinAttributes then + local def = defined(pr, n) + if byte(pr) ~= 0 then + bad(pr, "external file properties", Err.UNSUPPORTED) + end + for i = 1, n do + if def[i] then + if t == K.MTime then + local ft = pr:u64le() + files[i].mtime = math.floor(ft / 1e7 - 11644473600) + else + files[i].attributes = pr:u32le() + end + end + end + check(pr) + end + -- other properties (CTime, ATime, StartPos, Dummy, ...) are skipped + end + return files +end + +local function header(r: Bytes.Reader): Parsed + local p: Parsed = { streams = nil, files = {}, encoded = nil } + while true do + local t = byte(r) + if t == K.End then + break + elseif t == K.ArchiveProperties then + while true do + local pt = byte(r) + if pt == 0 then + break + end + r:skip(number(r)) + check(r) + end + elseif t == K.AdditionalStreamsInfo then + streamsInfo(r) + elseif t == K.MainStreamsInfo then + p.streams = streamsInfo(r) + elseif t == K.FilesInfo then + p.files = filesInfo(r) + else + bad(r, "unexpected property " .. t .. " in the header") + end + end + return p +end + +-- parse(buf, offset, length) -> Parsed | nil, Err. An encoded header returns { encoded = streams } for the caller to +-- decode and parse again. +function Header.parse(b: buffer, o: number, n: number): (Parsed?, Err.Err?) + local r = Bytes.reader(b, o, n) + local ok, res = pcall(function(): Parsed + local t = byte(r) + if t == K.Header then + return header(r) + elseif t == K.EncodedHeader then + return { streams = nil, files = {}, encoded = streamsInfo(r) } + end + return bad(r, "bad header type " .. t) + end) + if ok then + return res, nil + end + if type(res) == "table" and getmetatable(res :: any) == Fail then + return nil, (res :: any).err + end + error(res, 0) +end + +return Header diff --git a/src/Formats/archive/7z/init.luau b/src/Formats/archive/7z/init.luau new file mode 100644 index 0000000..6d56872 --- /dev/null +++ b/src/Formats/archive/7z/init.luau @@ -0,0 +1,370 @@ +--!strict +-- archive/7z: 7z archives (7zFormat.txt from the LZMA SDK, Igor Pavlov, public domain), read as an Archive whose +-- entries decode lazily (a folder is decoded once on first read, then sliced). Supports: plain and encoded (compressed) +-- headers, solid and non-solid folders, coder chains of copy / LZMA / LZMA2 / Deflate with BCJ (x86, PowerPC, ARM, +-- ARM-Thumb, SPARC, ARM64) and delta filters, empty files and directories, anti items (skipped), UTF-16 names, mtimes, +-- Windows / Unix attributes, folder and file CRC-32s (verified on read). +-- Not supported (Err.UNSUPPORTED naming the method, on read of the affected entries): BZip2, PPMd, BCJ2, Deflate64, +-- Zstd and other plug-in codecs, AES encryption, multi-volume archives, external header references; writing. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Types = require("@formats/Types") +local Lzma = require("@formats/codecs/Lzma") +local Deflate = require("@formats/codecs/Deflate") +local Archive = require("@formats/containers/Archive") +local Header = require("@formats/archive/7z/Header") + +-- ------------------------------------------------------------------------------------------------ contract +local SevenZip = { + name = "7z", + category = "archive", + extensions = { "7z" }, + mime = { "application/x-7z-compressed" }, + deps = { "core/Err", "core/Bytes", "core/Crc32", "Types", "codecs/Lzma", "codecs/Deflate", "containers/Archive" }, + caps = { decode = true, encode = false, methods = { "copy", "lzma", "lzma2", "deflate", "bcj", "delta" }, encrypted = false }, +} + +export type DecodeOptions = { + maxBytes: number?, -- refuse a folder (solid block) or header that decodes to more than this (default 2^30) + checkCrc: boolean?, -- verify CRC-32s on read (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "7z\188\175\39\28" + +-- method id -> xz filter id (BCJ / delta) +local FILTERS: { [string]: number } = { + ["\3\3\1\3"] = 0x04, -- x86 + ["\3\3\2\5"] = 0x05, -- PowerPC + ["\3\3\5\1"] = 0x07, -- ARM + ["\3\3\7\1"] = 0x08, -- ARM-Thumb + ["\3\3\8\5"] = 0x09, -- SPARC + ["\10"] = 0x0A, -- ARM64 + ["\3"] = 0x03, -- delta +} +local NAMES: { [string]: string } = { + ["\0"] = "copy", + ["\3\1\1"] = "lzma", + ["\33"] = "lzma2", + ["\4\1\8"] = "deflate", + ["\4\1\9"] = "deflate64", + ["\4\2\2"] = "bzip2", + ["\3\4\1"] = "ppmd", + ["\3\3\1\27"] = "bcj2", + ["\6\241\7\1"] = "aes", + ["\4\247\17\1"] = "zstd", + ["\4\247\17\2"] = "brotli", + ["\3\3\1\3"] = "bcj", + ["\3\3\2\5"] = "ppc", + ["\3\3\5\1"] = "arm", + ["\3\3\7\1"] = "armt", + ["\3\3\8\5"] = "sparc", + ["\10"] = "arm64", + ["\3"] = "delta", +} + +local function methodName(id: string): string + local n = NAMES[id] + if n then + return n + end + local hex = {} + for i = 1, #id do + table.insert(hex, string.format("%02x", string.byte(id, i))) + end + return "method " .. table.concat(hex) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function SevenZip.sniff(r: Bytes.Reader): number + return if r:peek(6) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- folder decoding: evaluate the coder graph from the main out stream; every coder here has one in and one out stream +type Ctx = { buf: buffer, base: number, limit: number, maxBytes: number } + +local function packStart(ctx: Ctx, s: Header.Streams, index: number): number + local p = ctx.base + 32 + s.packPos + for i = 1, index do + p += s.packSizes[i] + end + return p +end + +local function decodeFolder(ctx: Ctx, s: Header.Streams, f: Header.Folder): (buffer?, Err.Err?) + -- coder -> first in / out stream index + local inBase, outBase = {}, {} + local ni, no = 0, 0 + for i, c in f.coders do + inBase[i], outBase[i] = ni, no + ni += c.numIn + no += c.numOut + end + local depth = 0 + local function out(outIdx: number): (buffer?, Err.Err?) + depth += 1 + if depth > 32 then + return nil, Err.new(Err.CORRUPT, "coder graph too deep") + end + local ci + for i, c in f.coders do + if outIdx >= outBase[i] and outIdx < outBase[i] + c.numOut then + ci = i + end + end + if not ci then + return nil, Err.new(Err.CORRUPT, "bad bind pair") + end + local c = f.coders[ci] + if c.numIn ~= 1 or c.numOut ~= 1 then + return nil, Err.new(Err.UNSUPPORTED, methodName(c.id) .. " (multi-stream coder)") + end + local size = f.unpackSizes[outIdx + 1] or 0 + if size > ctx.maxBytes then + return nil, Err.new(Err.LIMIT, string.format("folder of %d bytes is over maxBytes", size)) + end + -- the coder's input: another coder's output, or a packed stream + local inIdx = inBase[ci] + local src: buffer, so: number, sl: number + local bound = nil + for _, bp in f.bindPairs do + if bp.inIndex == inIdx then + bound = bp.outIndex + end + end + if bound then + local b, e = out(bound) + if not b then + return nil, e + end + src, so, sl = b, 0, buffer.len(b) + else + local k = table.find(f.packed, inIdx) + if not k then + return nil, Err.new(Err.CORRUPT, "unbound coder input") + end + local pi = f.firstPack + k - 1 + if pi >= #s.packSizes then + return nil, Err.new(Err.CORRUPT, "missing pack stream") + end + so = packStart(ctx, s, pi) + sl = s.packSizes[pi + 1] + if so + sl > ctx.limit or so < ctx.base then + return nil, Err.new(Err.TRUNCATED, "pack stream past the end of the archive", so) + end + src = ctx.buf + end + local id = c.id + local opts = { maxBytes = ctx.maxBytes } + if id == "\0" then + if sl < size then + return nil, Err.new(Err.TRUNCATED, "short stored stream") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + return b + elseif id == "\3\1\1" then + if buffer.len(c.props) < 5 then + return nil, Err.new(Err.CORRUPT, "bad LZMA properties") + end + local b, e = Lzma.lzma(src, so, sl, c.props, size, opts) + return b, if b then nil else e + elseif id == "\33" then + local b, e = Lzma.lzma2(src, so, sl, nil, size, opts) + return b, if b then nil else e + elseif id == "\4\1\8" then + local b, e = Deflate.inflate(src, so, sl, size) + return b, if b then nil else e + elseif FILTERS[id] then + if sl ~= size then + return nil, Err.new(Err.CORRUPT, "filter size mismatch") + end + local b = buffer.create(size) + buffer.copy(b, 0, src, so, size) + local ok, e = Lzma.filter(FILTERS[id], b, 0, size, c.props) + if not ok then + return nil, e + end + return b + end + return nil, Err.new(Err.UNSUPPORTED, methodName(id) .. " is not supported") + end + local main = Header.mainOut(f) + if not main then + return nil, Err.new(Err.CORRUPT, "folder without a main output") + end + return out(main) +end + +local function folderMethod(f: Header.Folder): string + local names = {} + for _, c in f.coders do + table.insert(names, methodName(c.id)) + end + return table.concat(names, "+") +end + +function SevenZip.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Archive?, Err.Err?) + local o = opts or {} + local maxBytes = if type(o.maxBytes) == "number" then o.maxBytes else 2 ^ 30 + local checkCrc = o.checkCrc ~= false + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 32 then + return nil, Err.new(Err.TRUNCATED, "truncated signature header", base) + end + if buffer.readstring(b, base, 6) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "bad 7z signature", base) + end + if buffer.readu8(b, base + 6) ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "7z major version " .. buffer.readu8(b, base + 6), base + 6) + end + if Crc32.raw(b, base + 12, 20) ~= buffer.readu32(b, base + 8) then + return nil, Err.new(Err.CHECKSUM, "start header CRC-32 mismatch", base + 8) + end + local hr = Bytes.reader(b, base + 12, 20) + local nextOff, nextSize, nextCrc = hr:u64le(), hr:u64le(), hr:u32le() + local ctx: Ctx = { buf = b, base = base, limit = limit, maxBytes = maxBytes } + local a = Archive.new("7z") + if nextSize == 0 then + return a, nil -- an empty archive + end + local ho = base + 32 + nextOff + if nextOff < 0 or ho + nextSize > limit then + return nil, Err.new(Err.TRUNCATED, "header past the end of the archive", base + 12) + end + if Crc32.raw(b, ho, nextSize) ~= nextCrc then + return nil, Err.new(Err.CHECKSUM, "header CRC-32 mismatch", ho) + end + local hbuf, hoff, hlen = b, ho, nextSize + local parsed + for _ = 1, 4 do + local p, perr = Header.parse(hbuf, hoff, hlen) + if not p then + return nil, perr + end + if not p.encoded then + parsed = p + break + end + -- an encoded header: decode folder 1 of its streams, then parse again + local es = p.encoded + local f = es.folders[1] + if not f then + return nil, Err.new(Err.CORRUPT, "encoded header without a folder") + end + local hb, herr = decodeFolder(ctx, es, f) + if not hb then + return nil, herr + end + if f.crc and Crc32.raw(hb, 0, buffer.len(hb)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "encoded header CRC-32 mismatch") + end + hbuf, hoff, hlen = hb, 0, buffer.len(hb) + end + if not parsed then + return nil, Err.new(Err.CORRUPT, "nested encoded headers") + end + local s = parsed.streams or { packPos = 0, packSizes = {}, folders = {}, subSizes = {}, subCrcs = {} } + a.meta.folders = #s.folders + a.meta.solid = false + -- folder caches and the substream -> folder map + local cache: { [number]: buffer } = {} + local subFolder, subOffset = {}, {} + do + local si = 1 + for fi, f in s.folders do + if f.numSub > 1 then + a.meta.solid = true + end + local off = 0 + for _ = 1, f.numSub do + subFolder[si], subOffset[si] = fi, off + off += s.subSizes[si] or 0 + si += 1 + end + if off > Header.unpackSize(f) then + return nil, Err.new(Err.CORRUPT, "substreams exceed their folder") + end + end + end + local function folderData(fi: number): (buffer?, Err.Err?) + local c = cache[fi] + if c then + return c + end + local f = s.folders[fi] + local d, e = decodeFolder(ctx, s, f) + if not d then + return nil, e + end + if checkCrc and f.crc and Crc32.raw(d, 0, buffer.len(d)) ~= f.crc then + return nil, Err.new(Err.CHECKSUM, "folder CRC-32 mismatch") + end + cache[fi] = d + return d + end + local si = 0 + for _, file in parsed.files do + if file.anti then + continue + end + local attr = file.attributes + local isDir = file.emptyStream and not file.emptyFile + if attr and bit32.band(attr, 0x10) ~= 0 then + isDir = true + end + local mode = if attr and bit32.band(attr, 0x8000) ~= 0 then bit32.rshift(attr, 16) else nil + local e: Archive.Entry = { + name = file.name, + size = 0, + dir = isDir, + mtime = file.mtime, + attributes = attr, + mode = mode, + } + if not file.emptyStream then + si += 1 + local idx = si + local fi = subFolder[idx] + if not fi then + return nil, Err.new(Err.CORRUPT, "more files than streams") + end + local size = s.subSizes[idx] + e.size = size + e.method = folderMethod(s.folders[fi]) + if s.folders[fi].numSub == 1 then + local pk = 0 + for k = 1, #s.folders[fi].packed do + pk += s.packSizes[s.folders[fi].firstPack + k] or 0 + end + e.compressedSize = pk + end + e.crc = s.subCrcs[idx] + e.load = function(): (buffer?, Err.Err?) + local d, derr = folderData(fi) + if not d then + return nil, derr + end + local off = subOffset[idx] + if off + size > buffer.len(d) then + return nil, Err.new(Err.CORRUPT, "substream past its folder") + end + local out = buffer.create(size) + buffer.copy(out, 0, d, off, size) + local want = s.subCrcs[idx] + if checkCrc and want and Crc32.raw(out, 0, size) ~= want then + return nil, Err.new(Err.CHECKSUM, "CRC-32 mismatch in " .. file.name) + end + return out + end + end + Archive.put(a, e) + end + return a, nil +end + +return SevenZip diff --git a/tests/archive/7z.luau b/tests/archive/7z.luau new file mode 100644 index 0000000..2d8a3d0 --- /dev/null +++ b/tests/archive/7z.luau @@ -0,0 +1,115 @@ +-- archive/7z tests: the contract and sniff; every archive 7-Zip wrote in tools/fixtures/7z.py (LZMA / LZMA2 / copy / +-- Deflate, solid and not, BCJ / ARM64 / ARM / PPC + SPARC / delta chains, plain and encoded headers) lists exactly the +-- source tree (names incl. UTF-16 surrogates, directories, empty files, mtimes) and reads every file back; unsupported +-- methods (BZip2, PPMd, BCJ2, AES) list but fail on read with Err.UNSUPPORTED naming the method; corrupt CRCs; F.load; +-- the fuzz no-throw pass. +local T = require("@tests/T") +local SevenZip = require("@formats/archive/7z") +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/7z") + +local t = T.suite("7z") + +t:eq(SevenZip.name, "7z", "name") +t:eq(SevenZip.category, "archive", "category") +t:check(SevenZip.caps.decode and not SevenZip.caps.encode, "caps") + +local function decode(data: string, opts: any?): (any, any) + return SevenZip.decode(Bytes.reader(buffer.fromstring(data)), opts) +end + +local want: { [string]: any } = {} +for _, f in Fx.files do + want[f.name] = f +end + +local nfiles = 0 +for _, c in Fx.cases do + t:eq(SevenZip.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, c.name .. ": sniff") + local a, err = decode(c.data) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + if c.empty then + t:eq(#list, 0, c.name .. ": no entries") + continue + end + local seen = {} + for _, e in list do + local w = want[e.name] + t:check(w ~= nil, c.name .. ": unexpected entry " .. e.name) + seen[e.name] = true + t:eq(e.dir, w.dir, c.name .. ": " .. e.name .. ": dir") + t:eq(e.mtime, w.mtime, c.name .. ": " .. e.name .. ": mtime") + if not w.dir then + t:eq(e.size, #w.data, c.name .. ": " .. e.name .. ": size") + local b, rerr = a:read(e.name) + if c.unsupported and #w.data > 0 then + t:check(b == nil and rerr and rerr.code == Err.UNSUPPORTED and string.find(rerr.message, c.unsupported, 1, true) ~= nil, + c.name .. ": " .. e.name .. ": unsupported: " .. tostring(rerr)) + else + t:check(b and buffer.tostring(b) == w.data, c.name .. ": " .. e.name .. ": data: " .. tostring(rerr)) + nfiles += 1 + end + end + end + for name in want do + t:check(seen[name], c.name .. ": missing " .. name) + end +end +t:note("%d archives, %d files read", #Fx.cases, nfiles) + +-- corrupt data: a flipped byte in a stored file is a CRC error on read; a flipped header byte a header CRC error +do + local c + for _, x in Fx.cases do + if x.name == "copy" then + c = x + end + end + local s = c.data + local at = string.find(s, "deep\ndeep", 1, true) :: number + local bad = string.sub(s, 1, at - 1) .. "D" .. string.sub(s, at + 1) + local a = decode(bad) + t:check(a, "copy archive with a flipped data byte still lists") + local b, e = a:read("a/b/c/deep.txt") + t:check(b == nil and e and e.code == Err.CHECKSUM, "data CRC: " .. tostring(e)) + local _, e2 = decode(string.sub(s, 1, #s - 3) .. "\0\0\0") + t:check(e2 and (e2.code == Err.CHECKSUM or e2.code == Err.CORRUPT), "header CRC: " .. tostring(e2)) + local _, e3 = decode(string.sub(s, 1, 20)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) + local a4 = decode(bad, { checkCrc = false }) + t:check(a4 and a4:read("a/b/c/deep.txt"), "checkCrc = false") +end + +-- through the api +do + local c = Fx.cases[2] + local a, err = F.load(c.data) + t:check(a and a.format == "7z", "F.load: " .. tostring(err)) + t:eq(F.detect(c.data), "7z", "F.detect") + local r = a:read("readme.txt") + t:check(r and buffer.tostring(r) == want["readme.txt"].data, "F.load read") +end + +-- fuzz: decode + read every entry +do + local samples = {} + for _, c in Fx.cases do + if #c.data < 60000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local a = SevenZip.decode(Bytes.reader(b), { maxBytes = 2 ^ 21 }) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a + end, samples, { mutations = 12, garbage = 300 }) +end + +t:done() diff --git a/tools/fixtures/7z.py b/tools/fixtures/7z.py new file mode 100644 index 0000000..c3567d3 --- /dev/null +++ b/tools/fixtures/7z.py @@ -0,0 +1,102 @@ +# 7z fixtures (tools/fixtures.py): a small tree (text, x86 machine code, runs, an empty file, empty and nested +# directories, UTF-16 names with accents and a surrogate pair) archived by 7-Zip 2x (nix _7zz) with many method chains: +# LZMA / LZMA2 / copy / Deflate, solid and non-solid, BCJ / ARM64 / delta filters, plain and compressed headers; plus +# archives whose methods are not supported (BZip2, PPMd, BCJ2, AES) and an empty archive. +# tests/gen/7z.luau { files = { { name, dir, data?, mtime } }, cases = { { name, data, unsupported? } } } +import os, random, subprocess, sys, tempfile + +TOOL = "_7zz" + + +def tree(rng): + with open(os.path.realpath(sys.executable), "rb") as f: + code = f.read(60000) + base = os.path.dirname(os.__file__) + text = b"" + for name in sorted(os.listdir(base)): + if name.endswith(".py"): + with open(os.path.join(base, name), "rb") as f: + text += f.read() + if len(text) > 50000: + break + return [ + ("readme.txt", text[:50000]), + ("bin/code.bin", code), + ("bin/runs.dat", b"ab" * 5000 + b"\0" * 9000 + bytes(range(256)) * 8), + ("bin/random.dat", rng.randbytes(3000)), + ("empty.txt", b""), + ("emptydir/", None), + ("a/b/c/deep.txt", b"deep\n" * 10), + ("héllo wörld ☃.txt", "unicode ☃\n".encode()), + ("\U0001d11e clef.txt", b"g clef\n"), + ] + + +def generate(ctx): + rng = random.Random(77) + files = tree(rng) + mtime = 1600000000 + out_files = [] + cases = [] + with tempfile.TemporaryDirectory() as d: + src = os.path.join(d, "src") + for name, data in files: + p = os.path.join(src, name) + if data is None: + os.makedirs(p, exist_ok=True) + os.utime(p, (mtime, mtime)) + out_files.append({"name": name.rstrip("/"), "dir": True, "mtime": mtime}) + else: + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.utime(p, (mtime + 60, mtime + 60)) + out_files.append({"name": name, "dir": False, "data": data, "mtime": mtime + 60}) + for sub in ("bin", "a", "a/b", "a/b/c"): + os.utime(os.path.join(src, sub), (mtime, mtime)) + out_files.append({"name": sub, "dir": True, "mtime": mtime}) + + def make(name, args, unsupported=None): + arc = os.path.join(d, name + ".7z") + if os.path.exists(arc): + os.remove(arc) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc] + args + ["."], + cwd=src, capture_output=True, check=True) + with open(arc, "rb") as f: + c = {"name": name, "data": f.read()} + if unsupported: + c["unsupported"] = unsupported + cases.append(c) + + make("lzma-nonsolid", ["-m0=LZMA", "-ms=off", "-mhc=off"]) + make("lzma-solid", ["-m0=LZMA:d=1m", "-ms=on"]) + make("lzma2-solid", ["-m0=LZMA2", "-ms=on"]) + make("lzma2-mt-blocks", ["-m0=LZMA2:d=64k:c=20k", "-ms=on", "-mmt=4"]) + make("lzma2-hc-off", ["-m0=LZMA2", "-mhc=off"]) + make("copy", ["-m0=Copy", "-mhc=off"]) + make("copy-hc", ["-m0=Copy"]) + make("deflate", ["-m0=Deflate", "-ms=on"]) + make("bcj-lzma", ["-m0=BCJ", "-m1=LZMA", "-ms=on"]) + make("bcj-lzma2", ["-m0=BCJ", "-m1=LZMA2", "-ms=off"]) + make("arm64-lzma2", ["-m0=ARM64", "-m1=LZMA2"]) + make("arm-lzma2", ["-m0=ARM", "-m1=LZMA2"]) + make("delta-lzma", ["-m0=Delta:4", "-m1=LZMA"]) + make("ppc-sparc", ["-m0=PPC", "-m1=SPARC", "-m2=LZMA2"]) + make("lzma-lc-lp", ["-m0=LZMA:lc=0:lp=2:pb=0", "-ms=e"]) + make("auto", ["-mx=9"]) + make("fast", ["-mx=1"]) + make("bzip2", ["-m0=BZip2", "-mhc=off"], unsupported="bzip2") + make("ppmd", ["-m0=PPMd", "-mhc=off"], unsupported="ppmd") + make("bcj2", ["-m0=BCJ2", "-m1=LZMA", "-m2=LZMA", "-m3=LZMA", "-mb0s0:1", "-mb0s1:2", "-mb0s2:3", "-mhc=off"], + unsupported="bcj2") + make("aes", ["-m0=LZMA2", "-mhc=off", "-pSecret"], unsupported="aes") + # an empty archive + arc = os.path.join(d, "empty.7z") + empty = os.path.join(d, "emptysrc") + os.makedirs(empty) + subprocess.run(["nix", "shell", "nixpkgs#" + TOOL, "-c", "7zz", "a", "-bd", "-y", arc, "-x!*", "."], + cwd=empty, capture_output=True) + if os.path.exists(arc): + with open(arc, "rb") as f: + cases.append({"name": "empty", "data": f.read(), "empty": True}) + ctx.emit("7z", {"files": out_files, "cases": cases})