ws-arch: archive/7z: 7z read (plain / encoded headers, solid folders, copy / LZMA / LZMA2 / Deflate with BCJ / ARM64 / delta filters, UTF-16 names, mtimes, attributes, CRCs; lazy per-folder decode); tests against 7-Zip 26

This commit is contained in:
4DBug committed 2026-10-31 08:37:15 -05:00
1 parent 0a56389b09
commit 77b840166e
6 files changed
+1142

No files matched your search

+12
View File
@@ -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",
+542
View File
@@ -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
+370
View File
@@ -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