388 lines
12 KiB
Luau
388 lines
12 KiB
Luau
--!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 / BZip2 /
|
|
-- Zstd (7-Zip-zstd's plain frames; untested: stock 7-Zip cannot write it) 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): PPMd, BCJ2, Deflate64, other
|
|
-- plug-in codecs (Brotli, LZ4, ...), 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 Bzip2 = require("@formats/codecs/Bzip2")
|
|
local Zstd = require("@formats/codecs/Zstd")
|
|
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", "codecs/Bzip2", "codecs/Zstd", "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 id == "\4\2\2" or id == "\4\247\17\1" then -- BZip2, Zstd (7-Zip-zstd: plain zstd frames)
|
|
local b, e
|
|
if id == "\4\2\2" then
|
|
b, e = Bzip2.decompress(src, so, sl, opts)
|
|
else
|
|
b, e = Zstd.decompress(src, so, sl, opts)
|
|
end
|
|
if not b then
|
|
return nil, e
|
|
end
|
|
if buffer.len(b) ~= size then
|
|
return nil, Err.new(Err.CORRUPT, methodName(id) .. " stream decodes to the wrong size")
|
|
end
|
|
return b
|
|
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
|