merge ws/arch2-unix (cpio, ar/deb, rpm, z, iso, lz4; containers/Cpio, Iso9660; codecs UnixCompress, Xxh32, Lz4 from ws/roblox)
This commit is contained in:
commit
242e38c4fe
36 files changed
+5171
-7
No files matched your search
@@ -590,6 +590,18 @@ local list: { Entry } = {
|
||||
return require("@formats/font/ttf")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "type1",
|
||||
category = "font",
|
||||
path = "font/type1",
|
||||
extensions = { "pfb", "pfa", "t1" },
|
||||
mime = { "application/x-font-type1" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Raster", "codecs/font/GlyphNames" },
|
||||
caps = { decode = true, encode = false, outlines = { "type1" }, variants = { "pfb", "pfa" } },
|
||||
load = function()
|
||||
return require("@formats/font/type1")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "woff",
|
||||
category = "font",
|
||||
@@ -650,6 +662,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/applesingle")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "ar",
|
||||
category = "archive",
|
||||
path = "archive/ar",
|
||||
extensions = { "a", "ar", "deb", "lib" },
|
||||
mime = { "application/x-archive", "application/vnd.debian.binary-package" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
|
||||
load = function()
|
||||
return require("@formats/archive/ar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "arj",
|
||||
category = "archive",
|
||||
@@ -698,6 +722,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/bz2")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "cpio",
|
||||
category = "archive",
|
||||
path = "archive/cpio",
|
||||
extensions = { "cpio" },
|
||||
mime = { "application/x-cpio" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
|
||||
load = function()
|
||||
return require("@formats/archive/cpio")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "d64",
|
||||
category = "archive",
|
||||
@@ -734,6 +770,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/gzip")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "iso",
|
||||
category = "archive",
|
||||
path = "archive/iso",
|
||||
extensions = { "iso" },
|
||||
mime = { "application/x-iso9660-image" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
|
||||
caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
|
||||
load = function()
|
||||
return require("@formats/archive/iso")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "lha",
|
||||
category = "archive",
|
||||
@@ -746,6 +794,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/lha")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "lz4",
|
||||
category = "archive",
|
||||
path = "archive/lz4",
|
||||
extensions = { "lz4", "tlz4" },
|
||||
mime = { "application/x-lz4" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, legacy = true },
|
||||
load = function()
|
||||
return require("@formats/archive/lz4")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "macbinary",
|
||||
category = "archive",
|
||||
@@ -758,6 +818,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/macbinary")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "rpm",
|
||||
category = "archive",
|
||||
path = "archive/rpm",
|
||||
extensions = { "rpm" },
|
||||
mime = { "application/x-rpm" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
|
||||
load = function()
|
||||
return require("@formats/archive/rpm")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "tar",
|
||||
category = "archive",
|
||||
@@ -806,6 +878,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/yenc")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "z",
|
||||
category = "archive",
|
||||
path = "archive/z",
|
||||
extensions = { "z", "taz", "tz" },
|
||||
mime = { "application/x-compress" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
|
||||
load = function()
|
||||
return require("@formats/archive/z")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "zip",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
--!strict
|
||||
-- archive/ar: Unix ar archives ("!<arch>\n"): System V / GNU (names ending in "/", the "//" long-name table, the "/"
|
||||
-- and "/SYM64/" symbol tables) and BSD (inline "#1/<len>" names, the "__.SYMDEF" symbol table), read into the standard
|
||||
-- Archive value and written (opts.variant "gnu", the default, or "bsd") from any Archive value. Symbol tables are not
|
||||
-- entries: their symbols land in meta.symbols ({ name, member }). Debian packages (.deb) are ar archives: their
|
||||
-- meta.payload names the data.tar.* member (the api loads a .deb as that data tar, meta.outer = this archive) and
|
||||
-- meta.control holds the fields of the control file in control.tar / .gz / .xz / .zst / .bz2 / .lzma (decompressed
|
||||
-- with codecs/compress/*, read with containers/Tar). Written from the ar(5) manual pages (GNU binutils, FreeBSD) and
|
||||
-- deb(5) (dpkg); no code ported. Not supported: thin archives ("!<thin>"), writing symbol tables (a re-written
|
||||
-- library needs ranlib), writing .deb control data (any entries write as a plain ar).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Lzma = require("@formats/codecs/compress/Lzma")
|
||||
local Zstd = require("@formats/codecs/compress/Zstd")
|
||||
local Bzip2 = require("@formats/codecs/compress/Bzip2")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Tar = require("@formats/containers/Tar")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Ar = {
|
||||
name = "ar",
|
||||
category = "archive",
|
||||
extensions = { "a", "ar", "deb", "lib" },
|
||||
mime = { "application/x-archive", "application/vnd.debian.binary-package" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Tar" },
|
||||
caps = { decode = true, encode = true, variants = { "gnu", "bsd" }, deb = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
maxBytes: number?, -- .deb: the largest control.tar to decompress (default 2^26)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
variant: ("gnu" | "bsd")?, -- default: the source archive's ("bsd" for a .deb: plain names), else "gnu"
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = "!<arch>\n"
|
||||
local HEADER = 60
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Ar.sniff(r: Bytes.Reader): number
|
||||
if r:peek(8) == MAGIC then
|
||||
return if r:peek(13, 68) == "debian-binary" then 1 else 0.9
|
||||
end
|
||||
return if r:peek(8) == "!<thin>\n" then 0.5 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, at, n)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function decimal(s: string): number?
|
||||
local d = string.match(s, "^%s*(%d+)%s*$")
|
||||
return if d then tonumber(d) else (if string.find(s, "^%s*$") then 0 else nil)
|
||||
end
|
||||
|
||||
-- the System V symbol table: a big-endian count, the member offsets, then the NUL-terminated names
|
||||
local function sysvSymbols(b: buffer, o: number, n: number, wide: boolean): { { name: string, offset: number } }
|
||||
local out = {}
|
||||
local w = if wide then 8 else 4
|
||||
if n < w then
|
||||
return out
|
||||
end
|
||||
local count = if wide then bit32.byteswap(buffer.readu32(b, o + 4)) else bit32.byteswap(buffer.readu32(b, o))
|
||||
if count * w + w > n then
|
||||
return out
|
||||
end
|
||||
local s = o + w + count * w
|
||||
local e = o + n
|
||||
for i = 0, count - 1 do
|
||||
local off = bit32.byteswap(buffer.readu32(b, o + w + i * w + (w - 4)))
|
||||
local q = s
|
||||
while q < e and buffer.readu8(b, q) ~= 0 do
|
||||
q += 1
|
||||
end
|
||||
table.insert(out, { name = buffer.readstring(b, s, q - s), offset = off })
|
||||
s = q + 1
|
||||
if s > e then
|
||||
break
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the BSD __.SYMDEF table: a byte count of { name index, member offset } u32 pairs, the string table size, the strings
|
||||
local function bsdSymbols(b: buffer, o: number, n: number): { { name: string, offset: number } }
|
||||
local out = {}
|
||||
if n < 8 then
|
||||
return out
|
||||
end
|
||||
local rb = buffer.readu32(b, o)
|
||||
if rb % 8 ~= 0 or rb + 8 > n then
|
||||
return out
|
||||
end
|
||||
local strs = o + 8 + rb
|
||||
local strn = math.min(buffer.readu32(b, o + 4 + rb), o + n - strs)
|
||||
for i = 0, rb // 8 - 1 do
|
||||
local sx = buffer.readu32(b, o + 4 + i * 8)
|
||||
if sx < strn then
|
||||
local q = strs + sx
|
||||
while q < strs + strn and buffer.readu8(b, q) ~= 0 do
|
||||
q += 1
|
||||
end
|
||||
table.insert(out, { name = buffer.readstring(b, strs + sx, q - strs - sx), offset = buffer.readu32(b, o + 8 + i * 8) })
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- the fields of a deb control file ("Field: value", continuation lines start with a space or tab)
|
||||
local function controlFields(s: string): { [string]: string }
|
||||
local out: { [string]: string } = {}
|
||||
local last: string? = nil
|
||||
for line in string.gmatch(s, "([^\n]*)\n?") do
|
||||
local c = string.sub(line, 1, 1)
|
||||
if (c == " " or c == "\t") and last then
|
||||
out[last] ..= "\n" .. string.sub(line, 2)
|
||||
else
|
||||
local k, v = string.match(line, "^([^:%s]+):%s*(.-)%s*$")
|
||||
if k then
|
||||
out[k], last = v :: string, k
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- control.tar[.ext] -> the control file's fields, or nil
|
||||
local function debControl(b: buffer, o: number, n: number, name: string, maxBytes: number): { [string]: string }?
|
||||
local ext = string.match(name, "^control%.tar%.?(%w*)$")
|
||||
local raw: buffer?
|
||||
local opts: any = { maxBytes = maxBytes }
|
||||
if ext == "" then
|
||||
raw = buffer.create(n)
|
||||
buffer.copy(raw :: buffer, 0, b, o, n)
|
||||
elseif ext == "gz" then
|
||||
raw = Deflate.gunzip(b, o, n)
|
||||
elseif ext == "xz" then
|
||||
raw = Lzma.xz(b, o, n, opts)
|
||||
elseif ext == "lzma" then
|
||||
raw = Lzma.alone(b, o, n, opts)
|
||||
elseif ext == "zst" then
|
||||
raw = Zstd.decompress(b, o, n, opts)
|
||||
elseif ext == "bz2" then
|
||||
raw = Bzip2.decompress(b, o, n, opts)
|
||||
end
|
||||
if not raw then
|
||||
return nil
|
||||
end
|
||||
local list = Tar.read(raw)
|
||||
for _, e in list or {} do
|
||||
if (e.name == "./control" or e.name == "control") and e.type == "0" then
|
||||
return controlFields(buffer.readstring(raw, e.offset, e.size))
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Ar.encode(archive, opts)
|
||||
end
|
||||
|
||||
function Ar.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local maxEntries = o.maxEntries or 1e6
|
||||
local b, base, e = r.buf, r.base, r.limit
|
||||
if r:peek(8) == "!<thin>\n" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "thin archives (members are outside the file)", base)
|
||||
end
|
||||
if r:peek(8) ~= MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", base)
|
||||
end
|
||||
local a = Archive.new("ar", encode)
|
||||
local variant = "gnu"
|
||||
local longNames: string? = nil
|
||||
local symbols: { { name: string, offset: number } }? = nil
|
||||
local offsets: { [number]: string } = {} -- header offset (from the start) -> member name
|
||||
local count = 0
|
||||
local p = base + 8
|
||||
while p < e do
|
||||
local c = buffer.readu8(b, p)
|
||||
if (c == 0 or c == 10) and not string.find(buffer.readstring(b, p, math.min(e - p, 65536)), "[^%z\n]") then
|
||||
break -- trailing padding (bsdtar fills its last 10240-byte block with zeros)
|
||||
end
|
||||
if p + HEADER > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "member header past the end", p)
|
||||
end
|
||||
if buffer.readstring(b, p + 58, 2) ~= "`\n" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad member header", p + 58)
|
||||
end
|
||||
local rawName = buffer.readstring(b, p, 16)
|
||||
local mtime = decimal(buffer.readstring(b, p + 16, 12))
|
||||
local uid = decimal(buffer.readstring(b, p + 28, 6))
|
||||
local gid = decimal(buffer.readstring(b, p + 34, 6))
|
||||
local modeS = string.match(buffer.readstring(b, p + 40, 8), "^%s*([0-7]*)%s*$")
|
||||
local size = decimal(buffer.readstring(b, p + 48, 10))
|
||||
if not (mtime and uid and gid and modeS and size) then
|
||||
return nil, Err.new(Err.CORRUPT, "bad member header field", p)
|
||||
end
|
||||
local mode = if modeS == "" then 0 else tonumber(modeS, 8) :: number
|
||||
local data = p + HEADER
|
||||
if data + size > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "member data past the end", data)
|
||||
end
|
||||
local nextP = data + size + size % 2
|
||||
local name = string.gsub(rawName, " +$", "")
|
||||
local dataSize = size
|
||||
if string.sub(name, 1, 3) == "#1/" then
|
||||
local n = tonumber(string.sub(name, 4))
|
||||
if not n or n > size then
|
||||
return nil, Err.new(Err.CORRUPT, "bad BSD name length", p)
|
||||
end
|
||||
name = buffer.readstring(b, data, n)
|
||||
local z = string.find(name, "\0", 1, true)
|
||||
if z then
|
||||
name = string.sub(name, 1, z - 1)
|
||||
end
|
||||
data += n
|
||||
dataSize -= n
|
||||
variant = "bsd"
|
||||
elseif name == "//" then
|
||||
longNames = buffer.readstring(b, data, size)
|
||||
p = nextP
|
||||
continue
|
||||
elseif name == "/" or name == "/SYM64/" then
|
||||
symbols = sysvSymbols(b, data, size, name == "/SYM64/")
|
||||
p = nextP
|
||||
continue
|
||||
elseif string.match(name, "^/%d+$") then
|
||||
local off = tonumber(string.sub(name, 2)) :: number
|
||||
if not longNames or off >= #longNames then
|
||||
return nil, Err.new(Err.CORRUPT, "long name outside the name table", p)
|
||||
end
|
||||
local s = string.match(longNames, "^([^\n]*)", off + 1) :: string
|
||||
name = string.gsub(s, "/$", "")
|
||||
elseif string.sub(name, -1) == "/" then
|
||||
name = string.sub(name, 1, -2)
|
||||
end
|
||||
if name == "__.SYMDEF" or name == "__.SYMDEF SORTED" or name == "__.SYMDEF_64" or name == "__.SYMDEF_64 SORTED" then
|
||||
symbols = bsdSymbols(b, data, dataSize)
|
||||
variant = "bsd"
|
||||
p = nextP
|
||||
continue
|
||||
end
|
||||
if name == "" then
|
||||
return nil, Err.new(Err.CORRUPT, "empty member name", p)
|
||||
end
|
||||
offsets[p - base] = name
|
||||
count += 1
|
||||
if count > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
|
||||
end
|
||||
Archive.put(a, {
|
||||
name = name,
|
||||
size = dataSize,
|
||||
dir = false,
|
||||
mtime = mtime,
|
||||
uid = uid,
|
||||
gid = gid,
|
||||
mode = bit32.band(mode, 0xFFF),
|
||||
armode = modeS,
|
||||
method = "store",
|
||||
load = if dataSize > 0 then lazy(b, data, dataSize) else nil,
|
||||
})
|
||||
p = nextP
|
||||
end
|
||||
if symbols then
|
||||
local out = {}
|
||||
for _, s in symbols do
|
||||
table.insert(out, { name = s.name, member = offsets[s.offset] })
|
||||
end
|
||||
a.meta.symbols = out
|
||||
end
|
||||
a.meta.source = { format = "ar", variant = variant }
|
||||
-- Debian packages
|
||||
local list = a._entries
|
||||
if list[1] and list[1].name == "debian-binary" then
|
||||
a.meta.source.variant = "deb"
|
||||
local v = a:read("debian-binary")
|
||||
a.meta.debian = if v then (string.match(buffer.tostring(v), "^%s*(.-)%s*$")) else nil
|
||||
for _, ent in list do
|
||||
if string.match(ent.name, "^data%.tar") then
|
||||
a.meta.payload = ent.name
|
||||
elseif string.match(ent.name, "^control%.tar") then
|
||||
local cb = a:read(ent.name)
|
||||
if cb then
|
||||
a.meta.control = debControl(cb, 0, buffer.len(cb), ent.name, o.maxBytes or 2 ^ 26)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function pad(s: string, n: number): string
|
||||
return s .. string.rep(" ", n - #s)
|
||||
end
|
||||
|
||||
local function header(name: string, e: any, size: number): string?
|
||||
local mtime = math.floor(if type(e.mtime) == "number" then e.mtime else 0)
|
||||
local uid = if type(e.uid) == "number" then e.uid else 0
|
||||
local gid = if type(e.gid) == "number" then e.gid else 0
|
||||
local mode: string = if type(e.armode) == "string" and string.find(e.armode, "^[0-7]+$") then e.armode
|
||||
else string.format("%o", if type(e.mode) == "number" then bit32.band(e.mode, 0xFFF) else 0x1A4)
|
||||
local f: { string } = { tostring(mtime), tostring(uid), tostring(gid), mode, tostring(size) }
|
||||
local w = { 12, 6, 6, 8, 10 }
|
||||
for i, s in f do
|
||||
if #s > w[i] or string.find(s, "[^%d]") then
|
||||
return nil
|
||||
end
|
||||
end
|
||||
return pad(name, 16) .. pad(f[1], 12) .. pad(f[2], 6) .. pad(f[3], 6) .. pad(f[4], 8) .. pad(f[5], 10) .. "`\n"
|
||||
end
|
||||
|
||||
function Ar.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local o: EncodeOptions = opts or {}
|
||||
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
|
||||
local variant = o.variant or (if src and src.format == "ar" and (src.variant == "bsd" or src.variant == "deb") then "bsd" else "gnu")
|
||||
if variant ~= "gnu" and variant ~= "bsd" then
|
||||
return nil, Err.new(Err.ARG, "variant must be gnu or bsd")
|
||||
end
|
||||
local files = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
if not e.dir and (e.type == nil or e.type == "0") then
|
||||
local data, err = it.read()
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(files, { e = e, data = data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(1024)
|
||||
w:string(MAGIC)
|
||||
-- GNU: names over 15 bytes (or holding "/" or a space) go into the "//" table
|
||||
local table_: { string } = {}
|
||||
local nameOf: { string } = {}
|
||||
local tsize = 0
|
||||
for i, f in files do
|
||||
local name: string = f.e.name
|
||||
if string.find(name, "\n") or name == "" then
|
||||
return nil, Err.new(Err.ARG, "entry " .. i .. ": bad name for ar")
|
||||
end
|
||||
if variant == "gnu" then
|
||||
if #name > 15 or string.find(name, "[/ ]") then
|
||||
nameOf[i] = "/" .. tsize
|
||||
table.insert(table_, name .. "/\n")
|
||||
tsize += #name + 2
|
||||
else
|
||||
nameOf[i] = name .. "/"
|
||||
end
|
||||
end
|
||||
end
|
||||
if #table_ > 0 then
|
||||
local t = table.concat(table_)
|
||||
if #t % 2 == 1 then
|
||||
t ..= "\n"
|
||||
end
|
||||
w:string(pad("//", 48) .. pad(tostring(#t), 10) .. "`\n" .. t)
|
||||
end
|
||||
for i, f in files do
|
||||
local name: string = f.e.name
|
||||
local size = buffer.len(f.data)
|
||||
local prefix = ""
|
||||
local field = nameOf[i]
|
||||
if variant == "bsd" then
|
||||
if #name > 16 or string.find(name, " ") then
|
||||
field = "#1/" .. #name
|
||||
prefix = name
|
||||
else
|
||||
field = name
|
||||
end
|
||||
end
|
||||
local h = header(field, f.e, size + #prefix)
|
||||
if not h then
|
||||
return nil, Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the ar header")
|
||||
end
|
||||
w:string(h)
|
||||
w:string(prefix)
|
||||
w:bytes(f.data)
|
||||
if (size + #prefix) % 2 == 1 then
|
||||
w:string("\n")
|
||||
end
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty ar Archive: a:add(name, data, { mtime, mode }); a:write({ variant = "bsd" })
|
||||
function Ar.new(): any
|
||||
local a = Archive.new("ar", encode)
|
||||
a.meta.source = { format = "ar", variant = "gnu" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Ar
|
||||
@@ -0,0 +1,172 @@
|
||||
--!strict
|
||||
-- archive/cpio: cpio archives (newc, crc, odc, old binary in both byte orders; see containers/Cpio) read into the
|
||||
-- standard Archive value (entries read lazily: a copy of the stored bytes) and written as newc (default), crc or odc
|
||||
-- from any Archive value (a tar, a zip, ...: list() + read()). Entries carry the cpio fields: type (tar letters),
|
||||
-- mode (permission bits; the type is in type), uid, gid, nlink, ino, devmajor / devminor, rdevmajor / rdevminor,
|
||||
-- link (symlinks), hardlink (the first link of a hard link group; every link reads the data). Tar hard links ("1")
|
||||
-- written as cpio share an inode with their target. Not supported: tar-only fields (uname, gname: dropped).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Cpio = require("@formats/containers/Cpio")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local CpioFormat = {
|
||||
name = "cpio",
|
||||
category = "archive",
|
||||
extensions = { "cpio" },
|
||||
mime = { "application/x-cpio" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = true, variants = { "newc", "crc", "odc", "bin" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
verify: boolean?, -- crc archives: check the data sums (default true)
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
variant: ("newc" | "crc" | "odc")?, -- default: the source archive's (old binary: newc), else "newc"
|
||||
format: string?, -- "newc", "crc" or "odc" here too; any other value (the api's "cpio") means the variant default
|
||||
block: number?, -- pad to a multiple of this many bytes (default 512, as GNU cpio; 1 = none)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function CpioFormat.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(6)
|
||||
if m == "070701" or m == "070702" or m == "070707" then
|
||||
return 1
|
||||
end
|
||||
local b2 = r:peek(2)
|
||||
if (b2 == "\199\113" or b2 == "\113\199") and r:remaining() >= 26 then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
|
||||
return function(): (buffer?, Err.Err?)
|
||||
local out = buffer.create(n)
|
||||
buffer.copy(out, 0, b, at, n)
|
||||
return out, nil
|
||||
end
|
||||
end
|
||||
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return CpioFormat.encode(archive, opts)
|
||||
end
|
||||
|
||||
function CpioFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, info = Cpio.read(r.buf, r.base, r.limit - r.base, opts)
|
||||
if not list then
|
||||
return nil, info
|
||||
end
|
||||
local a = Archive.new("cpio", encode)
|
||||
for _, e in list do
|
||||
local data = e.type == "0" and e.size > 0
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = if data then e.size else 0,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
mode = bit32.band(e.mode, 0xFFF),
|
||||
uid = e.uid,
|
||||
gid = e.gid,
|
||||
type = e.type,
|
||||
link = e.link,
|
||||
hardlink = e.hardlink,
|
||||
nlink = e.nlink,
|
||||
ino = e.ino,
|
||||
devmajor = e.devmajor,
|
||||
devminor = e.devminor,
|
||||
rdevmajor = e.rdevmajor,
|
||||
rdevminor = e.rdevminor,
|
||||
method = "store",
|
||||
load = if data then lazy(r.buf, e.offset, e.size) else nil,
|
||||
})
|
||||
end
|
||||
a.meta.source = { format = "cpio", variant = info.format }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function num(v: any): number?
|
||||
return if type(v) == "number" then v else nil
|
||||
end
|
||||
|
||||
function CpioFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items = Archive.entries(archive)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive")
|
||||
end
|
||||
local index: { [string]: number } = {}
|
||||
for i, it in items do
|
||||
index[it.entry.name] = index[it.entry.name] or i
|
||||
end
|
||||
-- tar hard links ("1"): the same inode as their target, which counts the links
|
||||
local links: { [number]: number } = {}
|
||||
local target: { [number]: number } = {}
|
||||
for i, it in items do
|
||||
local e: any = it.entry
|
||||
if e.type == "1" and type(e.link) == "string" and index[e.link] then
|
||||
local t = index[e.link]
|
||||
target[i] = t
|
||||
links[t] = (links[t] or 1) + 1
|
||||
end
|
||||
end
|
||||
local list: { Cpio.WriteEntry } = {}
|
||||
for i, it in items do
|
||||
local e: any = it.entry
|
||||
local typ = if type(e.type) == "string" and Cpio.TYPE_MODE[e.type] then e.type elseif e.dir then "5" else "0"
|
||||
local src = target[i]
|
||||
local ino, nlink = num(e.ino), num(e.nlink)
|
||||
if src then
|
||||
typ, ino, nlink = "0", src, links[src]
|
||||
elseif links[i] then
|
||||
ino, nlink = i, links[i]
|
||||
end
|
||||
local data: buffer? = nil
|
||||
if typ == "0" then
|
||||
local b, err = (items[src or i] :: any).read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local mode = num(e.mode)
|
||||
table.insert(list, {
|
||||
name = e.name,
|
||||
data = data,
|
||||
type = typ,
|
||||
link = if type(e.link) == "string" and typ == "2" then e.link else nil,
|
||||
mode = if mode then bit32.band(mode, 0xFFF) else nil,
|
||||
uid = num(e.uid),
|
||||
gid = num(e.gid),
|
||||
nlink = nlink,
|
||||
mtime = num(e.mtime),
|
||||
ino = ino,
|
||||
devmajor = num(e.devmajor),
|
||||
devminor = num(e.devminor),
|
||||
rdevmajor = num(e.rdevmajor),
|
||||
rdevminor = num(e.rdevminor),
|
||||
})
|
||||
end
|
||||
-- opts.format may also be the api's format name ("cpio"): the variant default then
|
||||
local o: any = opts or {}
|
||||
local src = type(archive.meta) == "table" and type(archive.meta.source) == "table" and archive.meta.source
|
||||
local own = if src and src.format == "cpio" and (src.variant == "crc" or src.variant == "odc") then src.variant else "newc"
|
||||
local variant = o.variant or (if o.format == "crc" or o.format == "odc" or o.format == "newc" then o.format else own)
|
||||
return Cpio.write(list, { format = variant, block = o.block })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty cpio Archive: a:add(name, data, { mtime, mode, dir }); a:write()
|
||||
function CpioFormat.new(): any
|
||||
local a = Archive.new("cpio", encode)
|
||||
a.meta.source = { format = "cpio" }
|
||||
return a
|
||||
end
|
||||
|
||||
return CpioFormat
|
||||
@@ -0,0 +1,75 @@
|
||||
--!strict
|
||||
-- archive/iso: ISO 9660 CD / DVD images (.iso) read into the standard Archive value through containers/Iso9660:
|
||||
-- plain ISO 9660 names, Joliet and Rock Ridge (names, modes, owners, times, symlinks, relocated deep directories;
|
||||
-- Rock Ridge is used when present, else Joliet, else the plain names: opts.prefer picks another), multi-extent files.
|
||||
-- Directories are dir entries; file data reads lazily (a copy of the extents). meta.iso holds the volume facts
|
||||
-- (volumeId, systemId, publisher, blockSize, blocks, created, joliet level, rockRidge, tree) and meta.boot the El
|
||||
-- Torito boot catalog (platform, bootable, media, load segment, sector count, image LBA) when there is one.
|
||||
-- Not supported: writing, UDF, interleaved files (read: Err.UNSUPPORTED), zisofs-compressed files (read: the stored
|
||||
-- bytes), multi-session images (the first session).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Iso9660 = require("@formats/containers/Iso9660")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Iso = {
|
||||
name = "iso",
|
||||
category = "archive",
|
||||
extensions = { "iso" },
|
||||
mime = { "application/x-iso9660-image" },
|
||||
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Iso9660" },
|
||||
caps = { decode = true, encode = false, extensions = { "joliet", "rockridge", "eltorito" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Iso.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(5, 16 * 2048 + 1) == "CD001" then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Iso.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local list, info = Iso9660.read(r.buf, r.base, r.limit - r.base, opts)
|
||||
if not list then
|
||||
return nil, info
|
||||
end
|
||||
local a = Archive.new("iso")
|
||||
local b, limit = r.buf, r.limit
|
||||
for _, e in list do
|
||||
local data = e.type == "0" and e.size > 0
|
||||
Archive.put(a, {
|
||||
name = e.name,
|
||||
size = e.size,
|
||||
dir = e.dir,
|
||||
mtime = e.mtime,
|
||||
type = e.type,
|
||||
mode = e.mode,
|
||||
uid = e.uid,
|
||||
gid = e.gid,
|
||||
nlink = e.nlink,
|
||||
link = e.link,
|
||||
rdev = e.rdev,
|
||||
hidden = e.hidden,
|
||||
method = if e.zisofs then "zisofs" else "store",
|
||||
load = if data
|
||||
then function(): (buffer?, Err.Err?)
|
||||
return Iso9660.extract(b, e, limit)
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
end
|
||||
a.meta.boot = info.boot
|
||||
info.boot = nil
|
||||
a.meta.iso = info
|
||||
a.meta.source = { format = "iso", tree = info.tree }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
return Iso
|
||||
@@ -0,0 +1,353 @@
|
||||
--!strict
|
||||
-- archive/lz4: LZ4 frame files (.lz4: lz4 doc/lz4_Frame_format.md 1.6.x) as a single-stream Archive: one entry (the
|
||||
-- decompressed data), named after the file without .lz4 (.tlz4 -> .tar), else "data"; meta.stream = true, so the api
|
||||
-- unwraps a .tar.lz4. Reading: concatenated frames, skippable frames (magic 0x184D2A50..5F, skipped), the legacy
|
||||
-- frame (magic 0x184C2102, 8 MB blocks), independent and linked blocks, block sizes 64 KB .. 4 MB, uncompressed
|
||||
-- blocks, the header checksum, block checksums and the content checksum (XXH32, codecs/compress/Xxh32: verified
|
||||
-- unless opts.verify = false), the content size (checked). Writing: one frame of independent blocks
|
||||
-- (codecs/compress/Lz4), with opts for the block size, block checksums, the content checksum and the content size;
|
||||
-- several entries are written as a tar inside. Written from the specification; no code ported. Not supported:
|
||||
-- dictionaries (frames with a dictionary ID: Err.UNSUPPORTED), writing linked blocks or legacy frames.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Lz4 = require("@formats/codecs/compress/Lz4")
|
||||
local Xxh32 = require("@formats/codecs/compress/Xxh32")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Lz4Format = {
|
||||
name = "lz4",
|
||||
category = "archive",
|
||||
extensions = { "lz4", "tlz4" },
|
||||
mime = { "application/x-lz4" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Lz4", "codecs/compress/Xxh32", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, legacy = true },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
verify: boolean?, -- check the block / content checksums (default true; the header checksum is always checked)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
blockSize: number?, -- 65536, 262144, 1048576 or 4194304 (default 4 MB, as the lz4 tool)
|
||||
blockChecksum: boolean?, -- default false
|
||||
contentChecksum: boolean?, -- default true
|
||||
contentSize: boolean?, -- store the content size (default false)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAGIC = 0x184D2204
|
||||
local LEGACY = 0x184C2102
|
||||
local LEGACY_BLOCK = 8 * 1048576
|
||||
local SIZES: { [number]: number } = { [4] = 65536, [5] = 262144, [6] = 1048576, [7] = 4194304 }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Lz4Format.sniff(r: Bytes.Reader): number
|
||||
local m = r:peek(4)
|
||||
if m == "\4\34\77\24" then
|
||||
return 1
|
||||
elseif m == "\2\33\76\24" then
|
||||
return 0.9
|
||||
elseif #m == 4 and string.byte(m, 1) >= 0x50 and string.byte(m, 1) <= 0x5F and string.sub(m, 2) == "\42\77\24" then
|
||||
-- a skippable frame (zstd shares the magic): an LZ4 frame after it
|
||||
local h = r:peek(4, 4)
|
||||
if #h == 4 then
|
||||
local n = string.byte(h, 1) + string.byte(h, 2) * 256 + string.byte(h, 3) * 65536 + string.byte(h, 4) * 16777216
|
||||
if r:peek(4, 8 + n) == "\4\34\77\24" then
|
||||
return 1
|
||||
end
|
||||
end
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function skippable(m: number): boolean
|
||||
return m >= 0x184D2A50 and m <= 0x184D2A5F
|
||||
end
|
||||
|
||||
type Out = { buf: buffer, n: number, max: number }
|
||||
|
||||
-- room for k more bytes in the output (doubling, up to max) | false
|
||||
local function room(out: Out, k: number): boolean
|
||||
local need = out.n + k
|
||||
if need > out.max then
|
||||
return false
|
||||
end
|
||||
if need > buffer.len(out.buf) then
|
||||
local nb = buffer.create(math.min(math.max(buffer.len(out.buf) * 2, need), out.max))
|
||||
buffer.copy(nb, 0, out.buf, 0, out.n)
|
||||
out.buf = nb
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- one LZ4 frame at p -> the input offset after it | nil, Err
|
||||
local function frame(b: buffer, p: number, e: number, out: Out, verify: boolean): (number?, Err.Err?)
|
||||
if p + 7 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", p)
|
||||
end
|
||||
local flg, bd = buffer.readu8(b, p + 4), buffer.readu8(b, p + 5)
|
||||
if bit32.rshift(flg, 6) ~= 1 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frame version " .. bit32.rshift(flg, 6), p + 4)
|
||||
end
|
||||
if bit32.band(flg, 2) ~= 0 or bit32.band(bd, 0x8F) ~= 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "reserved descriptor bits set", p + 4)
|
||||
end
|
||||
local independent = bit32.band(flg, 0x20) ~= 0
|
||||
local blockSum = bit32.band(flg, 0x10) ~= 0
|
||||
local hasSize = bit32.band(flg, 0x08) ~= 0
|
||||
local contentSum = bit32.band(flg, 0x04) ~= 0
|
||||
local hasDict = bit32.band(flg, 0x01) ~= 0
|
||||
local bmax = SIZES[bit32.rshift(bd, 4)]
|
||||
if not bmax then
|
||||
return nil, Err.new(Err.CORRUPT, "bad block maximum size", p + 5)
|
||||
end
|
||||
local q = p + 6
|
||||
local size: number? = nil
|
||||
if hasSize then
|
||||
if q + 8 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
|
||||
end
|
||||
size = buffer.readu32(b, q) + buffer.readu32(b, q + 4) * 4294967296
|
||||
q += 8
|
||||
end
|
||||
if hasDict then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "frames with a dictionary", q)
|
||||
end
|
||||
if q + 1 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "frame header past the end", q)
|
||||
end
|
||||
local hc = bit32.band(bit32.rshift(Xxh32.hash(b, p + 4, q - p - 4), 8), 255)
|
||||
if hc ~= buffer.readu8(b, q) then
|
||||
return nil, Err.new(Err.CHECKSUM, "frame header checksum mismatch", q)
|
||||
end
|
||||
q += 1
|
||||
if size and out.n + size > out.max then
|
||||
return nil, Err.new(Err.LIMIT, "content over " .. out.max .. " bytes", p)
|
||||
end
|
||||
local start = out.n
|
||||
while true do
|
||||
if q + 4 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block header past the end", q)
|
||||
end
|
||||
local bs = buffer.readu32(b, q)
|
||||
q += 4
|
||||
if bs == 0 then
|
||||
break
|
||||
end
|
||||
local raw = bit32.band(bs, 0x80000000) ~= 0
|
||||
local n = bit32.band(bs, 0x7FFFFFFF)
|
||||
if n > bmax then
|
||||
return nil, Err.new(Err.CORRUPT, "block larger than the maximum", q - 4)
|
||||
end
|
||||
if q + n + (if blockSum then 4 else 0) > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
|
||||
end
|
||||
if blockSum and verify and Xxh32.hash(b, q, n) ~= buffer.readu32(b, q + n) then
|
||||
return nil, Err.new(Err.CHECKSUM, "block checksum mismatch", q + n)
|
||||
end
|
||||
if not room(out, if raw then n else bmax) and not room(out, if raw then n else math.min(bmax, out.max - out.n)) then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
if raw then
|
||||
buffer.copy(out.buf, out.n, b, q, n)
|
||||
out.n += n
|
||||
else
|
||||
local lim = math.min(out.n + bmax, buffer.len(out.buf))
|
||||
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim, if independent then out.n else start)
|
||||
if not dEnd then
|
||||
if msg and string.sub(msg, 1, 6) == "limit:" and lim < out.n + bmax then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
return nil, Err.from(msg, q)
|
||||
end
|
||||
out.n = dEnd
|
||||
end
|
||||
q += n + (if blockSum then 4 else 0)
|
||||
end
|
||||
if contentSum then
|
||||
if q + 4 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "content checksum past the end", q)
|
||||
end
|
||||
if verify and Xxh32.hash(out.buf, start, out.n - start) ~= buffer.readu32(b, q) then
|
||||
return nil, Err.new(Err.CHECKSUM, "content checksum mismatch", q)
|
||||
end
|
||||
q += 4
|
||||
end
|
||||
if size and out.n - start ~= size then
|
||||
return nil, Err.new(Err.CORRUPT, "content size mismatch", p + 6)
|
||||
end
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- a legacy frame at p: blocks of up to 8 MB until the input ends or a magic number follows
|
||||
local function legacy(b: buffer, p: number, e: number, out: Out): (number?, Err.Err?)
|
||||
local q = p + 4
|
||||
while q + 4 <= e do
|
||||
local n = buffer.readu32(b, q)
|
||||
if n == MAGIC or n == LEGACY or skippable(n) then
|
||||
break
|
||||
end
|
||||
q += 4
|
||||
if q + n > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "block past the end", q)
|
||||
end
|
||||
if not room(out, LEGACY_BLOCK) and not room(out, math.min(LEGACY_BLOCK, out.max - out.n)) then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. out.max .. " bytes", q)
|
||||
end
|
||||
local lim = math.min(out.n + LEGACY_BLOCK, buffer.len(out.buf))
|
||||
local dEnd, msg = Lz4.decodeInto(b, q, q + n, out.buf, out.n, lim)
|
||||
if not dEnd then
|
||||
return nil, Err.from(msg, q)
|
||||
end
|
||||
out.n = dEnd
|
||||
q += n
|
||||
end
|
||||
return q, nil
|
||||
end
|
||||
|
||||
-- decompress(buf, offset?, length?, opts?) -> the data of every frame | nil, Err
|
||||
function Lz4Format.decompress(src: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("Lz4.decompress", src, offset, length)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
|
||||
local verify = not (opts and opts.verify == false)
|
||||
local out: Out = { buf = buffer.create(math.min(math.max(n * 3, 256), maxBytes)), n = 0, max = maxBytes }
|
||||
local p, e = o, o + n
|
||||
local frames = 0
|
||||
while p + 4 <= e do
|
||||
local m = buffer.readu32(b, p)
|
||||
local q, err
|
||||
if m == MAGIC then
|
||||
q, err = frame(b, p, e, out, verify)
|
||||
frames += 1
|
||||
elseif m == LEGACY then
|
||||
q, err = legacy(b, p, e, out)
|
||||
frames += 1
|
||||
elseif skippable(m) then
|
||||
if p + 8 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
|
||||
end
|
||||
q = p + 8 + buffer.readu32(b, p + 4)
|
||||
if q > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "skippable frame past the end", p)
|
||||
end
|
||||
elseif frames > 0 then
|
||||
break -- trailing data after the frames (as lz4 -d, which warns)
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", p)
|
||||
end
|
||||
if not q then
|
||||
return nil, err
|
||||
end
|
||||
p = q :: number
|
||||
end
|
||||
if frames == 0 then
|
||||
return nil, Err.new(if n < 4 then Err.TRUNCATED else Err.CORRUPT, "no LZ4 frame", o)
|
||||
end
|
||||
local res = buffer.create(out.n)
|
||||
buffer.copy(res, 0, out.buf, 0, out.n)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Lz4Format.encode(value, opts)
|
||||
end
|
||||
|
||||
function Lz4Format.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, err = Lz4Format.decompress(r.buf, r.base, n, o)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("lz4", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "lz4", legacy = r:peek(4) == "\2\33\76\24" }
|
||||
local name = Archive.streamName(o, { "lz4" })
|
||||
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
|
||||
if stem and ext and string.lower(ext) == "tlz4" then
|
||||
name = stem .. ".tar"
|
||||
end
|
||||
Archive.put(a, { name = name, size = buffer.len(out), compressedSize = n, method = "lz4", dir = false, data = out })
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- compress(data, opts?) -> one LZ4 frame | nil, Err
|
||||
function Lz4Format.compress(data: buffer | string, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("Lz4.compress", data, nil, nil)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local op: EncodeOptions = opts or {}
|
||||
local bsize = op.blockSize or 4194304
|
||||
local bd = nil
|
||||
for k, v in SIZES do
|
||||
if v == bsize then
|
||||
bd = k
|
||||
end
|
||||
end
|
||||
if not bd then
|
||||
return nil, Err.new(Err.ARG, "blockSize must be 65536, 262144, 1048576 or 4194304")
|
||||
end
|
||||
local blockSum = op.blockChecksum == true
|
||||
local contentSum = op.contentChecksum ~= false
|
||||
local withSize = op.contentSize == true
|
||||
local w = Bytes.writer(n + n // 200 + 64)
|
||||
w:u32le(MAGIC)
|
||||
local flg = 0x40 + 0x20 + (if blockSum then 0x10 else 0) + (if withSize then 0x08 else 0) + (if contentSum then 0x04 else 0)
|
||||
w:u8(flg)
|
||||
w:u8(bd * 16)
|
||||
if withSize then
|
||||
w:u32le(n % 4294967296)
|
||||
w:u32le(n // 4294967296)
|
||||
end
|
||||
local hc = bit32.band(bit32.rshift(Xxh32.hash(w.buf, 4, w.pos - 4), 8), 255)
|
||||
w:u8(hc)
|
||||
local scratch = buffer.create(Lz4.bound(math.min(bsize, math.max(n, 1))))
|
||||
local p = o
|
||||
while p < o + n do
|
||||
local k = math.min(bsize, o + n - p)
|
||||
local c = Lz4.encodeInto(b, p, k, scratch, 0)
|
||||
local at = w.pos
|
||||
if c < k then
|
||||
w:u32le(c)
|
||||
local q = w:reserve(c)
|
||||
buffer.copy(w.buf, q, scratch, 0, c)
|
||||
w.pos = q + c
|
||||
else
|
||||
w:u32le(k + 0x80000000)
|
||||
local q = w:reserve(k)
|
||||
buffer.copy(w.buf, q, b, p, k)
|
||||
w.pos = q + k
|
||||
end
|
||||
if blockSum then
|
||||
local len = w.pos - at - 4
|
||||
w:u32le(Xxh32.hash(w.buf, at + 4, len))
|
||||
end
|
||||
p += k
|
||||
end
|
||||
w:u32le(0)
|
||||
if contentSum then
|
||||
w:u32le(Xxh32.hash(b, o, n))
|
||||
end
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- encode(value, opts?): a buffer / string, an Archive's one file, or a tar of the Archive's entries, as one frame
|
||||
function Lz4Format.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local data, err = Archive.streamData(value)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
return Lz4Format.compress(data, opts)
|
||||
end
|
||||
|
||||
return Lz4Format
|
||||
@@ -0,0 +1,333 @@
|
||||
--!strict
|
||||
-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
|
||||
-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
|
||||
-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
|
||||
-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
|
||||
-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
|
||||
-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
|
||||
-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
|
||||
-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
|
||||
-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Lzma = require("@formats/codecs/compress/Lzma")
|
||||
local Zstd = require("@formats/codecs/compress/Zstd")
|
||||
local Bzip2 = require("@formats/codecs/compress/Bzip2")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Cpio = require("@formats/containers/Cpio")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Rpm = {
|
||||
name = "rpm",
|
||||
category = "archive",
|
||||
extensions = { "rpm" },
|
||||
mime = { "application/x-rpm" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
|
||||
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- the largest decompressed payload (default 2^30)
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local LEAD_MAGIC = "\237\171\238\219"
|
||||
local HEADER_MAGIC = "\142\173\232\1"
|
||||
local RPMFILE_GHOST = 64
|
||||
|
||||
-- the tags meta.rpm names
|
||||
local NAMES: { [number]: string } = {
|
||||
[1000] = "name",
|
||||
[1001] = "version",
|
||||
[1002] = "release",
|
||||
[1003] = "epoch",
|
||||
[1004] = "summary",
|
||||
[1005] = "description",
|
||||
[1006] = "buildtime",
|
||||
[1007] = "buildhost",
|
||||
[1009] = "size",
|
||||
[1010] = "distribution",
|
||||
[1011] = "vendor",
|
||||
[1014] = "license",
|
||||
[1015] = "packager",
|
||||
[1016] = "group",
|
||||
[1020] = "url",
|
||||
[1021] = "os",
|
||||
[1022] = "arch",
|
||||
[1044] = "sourcerpm",
|
||||
[1047] = "provides",
|
||||
[1049] = "requires",
|
||||
[1124] = "payloadFormat",
|
||||
[1125] = "payloadCompressor",
|
||||
[1126] = "payloadFlags",
|
||||
[5009] = "longsize",
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Rpm.sniff(r: Bytes.Reader): number
|
||||
return if r:peek(4) == LEAD_MAGIC then 1 else 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- a header structure at p -> { [tag] = value }, end offset | nil, Err
|
||||
local function header(b: buffer, p: number, e: number): (any, any)
|
||||
if p + 16 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
|
||||
end
|
||||
if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
|
||||
end
|
||||
local n = bit32.byteswap(buffer.readu32(b, p + 8))
|
||||
local hsize = bit32.byteswap(buffer.readu32(b, p + 12))
|
||||
local index = p + 16
|
||||
local store = index + n * 16
|
||||
if n > 0x10000 or hsize > 0x10000000 then
|
||||
return nil, Err.new(Err.LIMIT, "header too large", p)
|
||||
end
|
||||
if store + hsize > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header data past the end", p)
|
||||
end
|
||||
local tags: { [number]: any } = {}
|
||||
local se = store + hsize
|
||||
for i = 0, n - 1 do
|
||||
local q = index + i * 16
|
||||
local tag = bit32.byteswap(buffer.readu32(b, q))
|
||||
local typ = bit32.byteswap(buffer.readu32(b, q + 4))
|
||||
local off = bit32.byteswap(buffer.readu32(b, q + 8))
|
||||
local count = bit32.byteswap(buffer.readu32(b, q + 12))
|
||||
local d = store + off
|
||||
if off > hsize then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0
|
||||
if width > 0 then
|
||||
if d + count * width > se then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
local v = table.create(count)
|
||||
for k = 0, count - 1 do
|
||||
local x = d + k * width
|
||||
v[k + 1] = if width == 1 then buffer.readu8(b, x)
|
||||
elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1))
|
||||
elseif width == 4 then bit32.byteswap(buffer.readu32(b, x))
|
||||
else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4))
|
||||
end
|
||||
tags[tag] = v
|
||||
elseif typ == 7 then
|
||||
if d + count > se then
|
||||
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
|
||||
end
|
||||
tags[tag] = buffer.readstring(b, d, count)
|
||||
elseif typ == 6 or typ == 8 or typ == 9 then
|
||||
local v = {}
|
||||
local s = d
|
||||
local want = if typ == 6 then 1 else count
|
||||
if want > hsize then
|
||||
return nil, Err.new(Err.CORRUPT, "bad string count", q)
|
||||
end
|
||||
for _ = 1, want do
|
||||
local z = s
|
||||
while z < se and buffer.readu8(b, z) ~= 0 do
|
||||
z += 1
|
||||
end
|
||||
if z >= se then
|
||||
return nil, Err.new(Err.CORRUPT, "unterminated string", s)
|
||||
end
|
||||
table.insert(v, buffer.readstring(b, s, z - s))
|
||||
s = z + 1
|
||||
end
|
||||
tags[tag] = if typ == 6 then v[1] else v
|
||||
end
|
||||
end
|
||||
return tags, se
|
||||
end
|
||||
|
||||
-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
|
||||
local function files(tags: { [number]: any }): { any }
|
||||
local names: { string } = {}
|
||||
local bn, dn, di = tags[1117], tags[1118], tags[1116]
|
||||
if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then
|
||||
for i, base in bn do
|
||||
local d = dn[(di[i] or 0) + 1]
|
||||
names[i] = (if type(d) == "string" then d else "") .. base
|
||||
end
|
||||
elseif type(tags[1027]) == "table" then
|
||||
names = tags[1027]
|
||||
end
|
||||
local sizes = tags[5008] or tags[1028] or {}
|
||||
local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {}
|
||||
local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {}
|
||||
local out = {}
|
||||
for i, n in names do
|
||||
table.insert(out, {
|
||||
name = n,
|
||||
size = sizes[i] or 0,
|
||||
mode = modes[i] or 0,
|
||||
mtime = mtimes[i] or 0,
|
||||
link = if links[i] and links[i] ~= "" then links[i] else nil,
|
||||
user = users[i],
|
||||
group = groups[i],
|
||||
flags = flags[i] or 0,
|
||||
})
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function strip(name: string): string
|
||||
return (string.gsub(name, "^%.?/+", ""))
|
||||
end
|
||||
|
||||
-- the payload: decompressed, then its cpio entries by stripped name
|
||||
local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
|
||||
local n = e - p
|
||||
local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
|
||||
local raw: buffer?, err: any
|
||||
local m = if n >= 6 then buffer.readstring(b, p, 6) else ""
|
||||
if string.sub(m, 1, 2) == "\31\139" then
|
||||
raw, err = Deflate.gunzip(b, p, n)
|
||||
elseif m == "\253" .. "7zXZ\0" then
|
||||
raw, err = Lzma.xz(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 3) == "BZh" then
|
||||
raw, err = Bzip2.decompress(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 4) == "\40\181\47\253" then
|
||||
raw, err = Zstd.decompress(b, p, n, opts)
|
||||
elseif compressor == "lzma" then
|
||||
raw, err = Lzma.alone(b, p, n, opts)
|
||||
elseif string.sub(m, 1, 5) == "07070" then
|
||||
raw = buffer.create(n)
|
||||
buffer.copy(raw :: buffer, 0, b, p, n)
|
||||
else
|
||||
return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p)
|
||||
end
|
||||
if not raw then
|
||||
return nil, err
|
||||
end
|
||||
if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)")
|
||||
end
|
||||
local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries })
|
||||
if not list then
|
||||
return nil, cerr
|
||||
end
|
||||
local by = {}
|
||||
for _, ent in list do
|
||||
by[strip(ent.name)] = ent
|
||||
end
|
||||
return { buf = raw, by = by }, nil
|
||||
end
|
||||
|
||||
function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local b, base, e = r.buf, r.base, r.limit
|
||||
if e - base < 96 then
|
||||
return nil, Err.new(Err.TRUNCATED, "lead past the end", base)
|
||||
end
|
||||
if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then
|
||||
return nil, Err.new(Err.CORRUPT, "bad lead magic", base)
|
||||
end
|
||||
local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5)
|
||||
local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7))
|
||||
local leadName = buffer.readstring(b, base + 10, 66)
|
||||
leadName = string.match(leadName, "^[^%z]*") :: string
|
||||
if major < 3 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4)
|
||||
end
|
||||
local sig, sigEnd = header(b, base + 96, e)
|
||||
if not sig then
|
||||
return nil, sigEnd
|
||||
end
|
||||
local hp = base + (sigEnd - base + 7) // 8 * 8
|
||||
local tags, hEnd = header(b, hp, e)
|
||||
if not tags then
|
||||
return nil, hEnd
|
||||
end
|
||||
local a = Archive.new("rpm")
|
||||
local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } }
|
||||
for tag, key in NAMES do
|
||||
local v = tags[tag]
|
||||
if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value
|
||||
v = v[1]
|
||||
end
|
||||
info[key] = v
|
||||
end
|
||||
a.meta.rpm = info
|
||||
a.meta.source = { format = "rpm", compressor = info.payloadCompressor }
|
||||
if info.payloadFormat and info.payloadFormat ~= "cpio" then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd)
|
||||
end
|
||||
local cache: any = nil
|
||||
local cacheErr: Err.Err? = nil
|
||||
local function entry(name: string): (any, Err.Err?)
|
||||
if not cache and not cacheErr then
|
||||
cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o)
|
||||
end
|
||||
if not cache then
|
||||
return nil, cacheErr
|
||||
end
|
||||
local ent = cache.by[name]
|
||||
if not ent then
|
||||
return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload")
|
||||
end
|
||||
return ent, nil
|
||||
end
|
||||
local list = files(tags)
|
||||
if #list > (o.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many files")
|
||||
end
|
||||
for _, f in list do
|
||||
if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then
|
||||
continue
|
||||
end
|
||||
local name = strip(f.name)
|
||||
local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0"
|
||||
local data = typ == "0" and f.size > 0
|
||||
Archive.put(a, {
|
||||
name = name,
|
||||
size = if data then f.size else 0,
|
||||
dir = typ == "5",
|
||||
mtime = f.mtime,
|
||||
mode = bit32.band(f.mode, 0xFFF),
|
||||
type = typ,
|
||||
link = if typ == "2" then f.link else nil,
|
||||
uname = f.user,
|
||||
gname = f.group,
|
||||
method = if info.payloadCompressor then info.payloadCompressor else "store",
|
||||
load = if data
|
||||
then function(): (buffer?, Err.Err?)
|
||||
local ent, err = entry(name)
|
||||
if not ent then
|
||||
return nil, err
|
||||
end
|
||||
local out = buffer.create(ent.size)
|
||||
buffer.copy(out, 0, cache.buf, ent.offset, ent.size)
|
||||
return out, nil
|
||||
end
|
||||
else nil,
|
||||
})
|
||||
end
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
|
||||
function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local a, err = Rpm.decode(r, opts)
|
||||
if not a then
|
||||
return nil, err
|
||||
end
|
||||
local p = r.base + 96
|
||||
local _, sigEnd = header(r.buf, p, r.limit)
|
||||
local hp = r.base + (sigEnd - r.base + 7) // 8 * 8
|
||||
local _, hEnd = header(r.buf, hp, r.limit)
|
||||
local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {})
|
||||
if not pl then
|
||||
return nil, perr
|
||||
end
|
||||
return pl.buf, nil
|
||||
end
|
||||
|
||||
return Rpm
|
||||
@@ -0,0 +1,98 @@
|
||||
--!strict
|
||||
-- archive/z: Unix compress files (.Z: LZW, magic 1F 9D, 9..16-bit codes, block mode) as a single-stream Archive: one
|
||||
-- entry, named after the file without .Z (.taz / .tZ -> .tar), else "data"; meta.stream = true, so the api unwraps a
|
||||
-- .tar.Z into the tar. Writing: an Archive with one file entry (or a buffer / string) becomes that file compressed,
|
||||
-- byte for byte what ncompress writes; an Archive with several entries is written as a tar inside (a .tar.Z). The LZW is
|
||||
-- codecs/compress/UnixCompress. Not supported: pack (.z, 1F 1E) and compact (1F FF) files.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Z = {
|
||||
name = "z",
|
||||
category = "archive",
|
||||
extensions = { "z", "taz", "tz" },
|
||||
mime = { "application/x-compress" },
|
||||
deps = { "core/Err", "core/Bytes", "codecs/compress/UnixCompress", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, stream = true, bits = { 9, 16 } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = {
|
||||
maxBytes: number?, -- refuse output larger than this (default 2^30)
|
||||
name: string?, -- the file name (the api passes it): names the entry
|
||||
}
|
||||
export type EncodeOptions = {
|
||||
maxBits: number?, -- 9..16 (compress -b), default 16
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Z.sniff(r: Bytes.Reader): number
|
||||
if r:peek(2) ~= "\31\157" then
|
||||
return 0
|
||||
end
|
||||
local f = r:peekU8(2)
|
||||
return if f >= 0 and bit32.band(f, 0x60) == 0 and bit32.band(f, 0x1F) >= 9 and bit32.band(f, 0x1F) <= 16 then 1 else 0.3
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the entry name: the file name without .Z; .taz / .tz name a tar
|
||||
local function entryName(opts: DecodeOptions): string
|
||||
local name = Archive.streamName(opts, { "z" })
|
||||
local stem, ext = string.match(name, "^(.+)%.(%w+)$")
|
||||
if stem and ext and (string.lower(ext) == "taz" or string.lower(ext) == "tz") then
|
||||
return stem .. ".tar"
|
||||
end
|
||||
return name
|
||||
end
|
||||
|
||||
local function encode(value: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Z.encode(value, opts)
|
||||
end
|
||||
|
||||
function Z.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local n = r.limit - r.base
|
||||
local out, err = UnixCompress.decompress(r.buf, r.base, n, o)
|
||||
if not out then
|
||||
return nil, err
|
||||
end
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z", maxBits = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x1F), blockMode = bit32.band(buffer.readu8(r.buf, r.base + 2), 0x80) ~= 0 }
|
||||
Archive.put(a, {
|
||||
name = entryName(o),
|
||||
size = buffer.len(out),
|
||||
compressedSize = n,
|
||||
method = "lzw",
|
||||
dir = false,
|
||||
data = out,
|
||||
})
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Z.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local data, err = Archive.streamData(value)
|
||||
if not data then
|
||||
return nil, err
|
||||
end
|
||||
return UnixCompress.compress(data, 0, buffer.len(data), { maxBits = opts and opts.maxBits })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new(data?, name?) -> a .Z Archive holding one entry
|
||||
function Z.new(data: (buffer | string)?, name: string?): any
|
||||
local a = Archive.new("z", encode)
|
||||
a.meta.stream = true
|
||||
a.meta.source = { format = "z" }
|
||||
if data then
|
||||
a:add(name or "data", data)
|
||||
end
|
||||
return a
|
||||
end
|
||||
|
||||
return Z
|
||||
@@ -0,0 +1,291 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Lz4: the LZ4 block format (lz4 doc/lz4_Block_format.md): decode and a greedy hash-chain-free encoder
|
||||
-- (the reference "fast" strategy: one 4-byte hash table, 64 KB window). A codec (layer 3): model/rbxm chunk bodies,
|
||||
-- and the LZ4 frame format (archive) builds on it. New code, written from the specification. Never throws.
|
||||
--
|
||||
-- local out, err = Lz4.decompress(src, offset?, length?, outSize?, opts?) -- a block -> buffer | nil, Err
|
||||
-- local packed = Lz4.compress(src, offset?, length?) -- -> buffer (a block) | nil, Err
|
||||
-- local dEnd, msg = Lz4.decodeInto(src, p, limit, dst, d, dstLimit, histStart?) -- low level (linked blocks)
|
||||
-- local n = Lz4.encodeInto(src, p, n, dst, d) -- low level; dst has bound(n) room
|
||||
-- Lz4.bound(n) -- worst-case block size for n bytes
|
||||
--
|
||||
-- decodeInto decodes one block from src[p, limit) to dst[d, dstLimit): matches may reach back to histStart (default
|
||||
-- d), so a frame decoder with linked blocks keeps the previous output in front of d. It returns the output end, or
|
||||
-- nil and a message ("truncated", "corrupt: ...", "limit: output ...") for the caller's Err.from.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local Lz4 = {}
|
||||
|
||||
export type Options = {
|
||||
maxBytes: number?, -- refuse output larger than this when outSize is not given (default 2^28)
|
||||
}
|
||||
|
||||
local readu8, writeu8, readu16, writeu16, readu32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readu32
|
||||
local bcopy, bcreate, blen = buffer.copy, buffer.create, buffer.len
|
||||
local band, rshift = bit32.band, bit32.rshift
|
||||
|
||||
local MINMATCH = 4
|
||||
local LASTLITERALS = 5 -- the last 5 bytes are always literals
|
||||
local MFLIMIT = 12 -- the last match starts at least 12 bytes before the end
|
||||
local MAX_OFFSET = 65535
|
||||
local HASH_BITS = 13
|
||||
local HASH_SIZE = 2 ^ HASH_BITS
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
function Lz4.decodeInto(src: buffer, p: number, limit: number, dst: buffer, d: number, dstLimit: number, histStart: number?): (number?, string?)
|
||||
local lo = histStart or d
|
||||
if limit > blen(src) or dstLimit > blen(dst) or p < 0 or d < 0 or lo < 0 or lo > d then
|
||||
return nil, "corrupt: bad ranges"
|
||||
end
|
||||
if p >= limit then
|
||||
return nil, "truncated: empty block"
|
||||
end
|
||||
while true do
|
||||
if p >= limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local token = readu8(src, p)
|
||||
p += 1
|
||||
local lit = rshift(token, 4)
|
||||
if lit == 15 then
|
||||
local b = 255
|
||||
while b == 255 do
|
||||
if p >= limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
b = readu8(src, p)
|
||||
p += 1
|
||||
lit += b
|
||||
end
|
||||
end
|
||||
if lit > 0 then
|
||||
if p + lit > limit then
|
||||
return nil, "truncated: literals past the end"
|
||||
end
|
||||
if d + lit > dstLimit then
|
||||
return nil, "limit: output larger than expected"
|
||||
end
|
||||
bcopy(dst, d, src, p, lit)
|
||||
p += lit
|
||||
d += lit
|
||||
end
|
||||
if p >= limit then
|
||||
return d, nil -- the last sequence has no match
|
||||
end
|
||||
if p + 2 > limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
local off = readu16(src, p)
|
||||
p += 2
|
||||
if off == 0 or d - off < lo then
|
||||
return nil, "corrupt: bad match offset"
|
||||
end
|
||||
local ml = band(token, 15)
|
||||
if ml == 15 then
|
||||
local b = 255
|
||||
while b == 255 do
|
||||
if p >= limit then
|
||||
return nil, "truncated"
|
||||
end
|
||||
b = readu8(src, p)
|
||||
p += 1
|
||||
ml += b
|
||||
end
|
||||
end
|
||||
ml += MINMATCH
|
||||
if d + ml > dstLimit then
|
||||
return nil, "limit: output larger than expected"
|
||||
end
|
||||
local s = d - off
|
||||
if off >= ml then
|
||||
bcopy(dst, d, dst, s, ml)
|
||||
d += ml
|
||||
elseif off == 1 then
|
||||
buffer.fill(dst, d, readu8(dst, s), ml)
|
||||
d += ml
|
||||
else
|
||||
-- an overlapping match repeats the off-byte pattern: copy what is already there, doubling each time
|
||||
local n = ml
|
||||
while n > 0 do
|
||||
local c = d - s
|
||||
if c > n then
|
||||
c = n
|
||||
end
|
||||
bcopy(dst, d, dst, s, c)
|
||||
d += c
|
||||
n -= c
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- decompress(src, offset?, length?, outSize?, opts?) -> buffer | nil, Err: one block. With outSize the output must be
|
||||
-- exactly that long (CORRUPT otherwise); without it the output grows up to opts.maxBytes.
|
||||
function Lz4.decompress(src: buffer | string, offset: number?, length: number?, outSize: number?, opts: Options?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Lz4.decompress", src, offset, length)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
if outSize ~= nil then
|
||||
if type(outSize) ~= "number" or outSize < 0 or outSize % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "Lz4.decompress: bad outSize")
|
||||
end
|
||||
local out = bcreate(outSize)
|
||||
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, outSize)
|
||||
if not e then
|
||||
return nil, Err.from(msg, o)
|
||||
end
|
||||
if e ~= outSize then
|
||||
return nil, Err.new(Err.CORRUPT, string.format("block decodes to %d bytes, expected %d", e, outSize), o)
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
local max = (opts and opts.maxBytes) or 2 ^ 28
|
||||
local size = math.min(math.max(l * 4, 256), max)
|
||||
while true do
|
||||
local out = bcreate(size)
|
||||
local e, msg = Lz4.decodeInto(b, o, o + l, out, 0, size)
|
||||
if e then
|
||||
local res = bcreate(e)
|
||||
bcopy(res, 0, out, 0, e)
|
||||
return res, nil
|
||||
end
|
||||
if not (msg and string.sub(msg, 1, 6) == "limit:") then
|
||||
return nil, Err.from(msg, o)
|
||||
end
|
||||
if size >= max then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. max .. " bytes", o)
|
||||
end
|
||||
size = math.min(size * 4, max)
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
-- bound(n) -> the largest block n input bytes can produce
|
||||
function Lz4.bound(n: number): number
|
||||
return n + n // 255 + 16
|
||||
end
|
||||
|
||||
-- writes a length's 255-run extension at o; returns the next offset
|
||||
local function extend(dst: buffer, o: number, n: number): number
|
||||
while n >= 255 do
|
||||
writeu8(dst, o, 255)
|
||||
o += 1
|
||||
n -= 255
|
||||
end
|
||||
writeu8(dst, o, n)
|
||||
return o + 1
|
||||
end
|
||||
|
||||
-- hash(v) -> 1 .. HASH_SIZE: Knuth's multiplicative hash (v * 2654435761 mod 2^32, top bits), exact in doubles
|
||||
local function hash(v: number): number
|
||||
local vl, vh = band(v, 0xFFFF), rshift(v, 16)
|
||||
local mid = (vh * 0x79B1 + vl * 0x9E37) % 65536
|
||||
return ((vl * 0x79B1 + mid * 65536) % 4294967296) // (2 ^ (32 - HASH_BITS)) + 1
|
||||
end
|
||||
|
||||
local hashTable: { number } = table.create(HASH_SIZE, -1e9)
|
||||
|
||||
-- encodeInto(src, p, n, dst, d) -> the block's length: src[p, p + n) compressed to dst[d ..] (room for bound(n))
|
||||
function Lz4.encodeInto(src: buffer, p: number, n: number, dst: buffer, d: number): number
|
||||
local op = d
|
||||
local anchor = p
|
||||
local iend = p + n
|
||||
local ht = hashTable
|
||||
for i = 1, HASH_SIZE do
|
||||
ht[i] = -1e9
|
||||
end
|
||||
if n >= MFLIMIT + 1 then
|
||||
local mflimit = iend - MFLIMIT -- a match starts before this
|
||||
local matchEnd = iend - LASTLITERALS -- and ends at or before this
|
||||
local ip = p
|
||||
local skip = 64
|
||||
while ip < mflimit do
|
||||
local v = readu32(src, ip)
|
||||
local h = hash(v)
|
||||
local ref = ht[h]
|
||||
ht[h] = ip
|
||||
if ref >= p and ip - ref <= MAX_OFFSET and readu32(src, ref) == v then
|
||||
-- back over equal bytes before the match (into the pending literals)
|
||||
while ip > anchor and ref > p and readu8(src, ip - 1) == readu8(src, ref - 1) do
|
||||
ip -= 1
|
||||
ref -= 1
|
||||
end
|
||||
local a = ip + MINMATCH
|
||||
local bpos = ref + MINMATCH
|
||||
while a + 4 <= matchEnd and readu32(src, a) == readu32(src, bpos) do
|
||||
a += 4
|
||||
bpos += 4
|
||||
end
|
||||
while a < matchEnd and readu8(src, a) == readu8(src, bpos) do
|
||||
a += 1
|
||||
bpos += 1
|
||||
end
|
||||
local ml = a - ip
|
||||
local lit = ip - anchor
|
||||
local tok = op
|
||||
op += 1
|
||||
local tl = if lit >= 15 then 15 else lit
|
||||
if lit >= 15 then
|
||||
op = extend(dst, op, lit - 15)
|
||||
end
|
||||
if lit > 0 then
|
||||
bcopy(dst, op, src, anchor, lit)
|
||||
op += lit
|
||||
end
|
||||
writeu16(dst, op, ip - ref)
|
||||
op += 2
|
||||
local m = ml - MINMATCH
|
||||
local tm = if m >= 15 then 15 else m
|
||||
if m >= 15 then
|
||||
op = extend(dst, op, m - 15)
|
||||
end
|
||||
writeu8(dst, tok, tl * 16 + tm)
|
||||
ip = a
|
||||
anchor = ip
|
||||
skip = 64
|
||||
-- index the position just before the next one (better ratio at no cost)
|
||||
if ip - 2 >= p and ip - 2 < mflimit then
|
||||
local w = readu32(src, ip - 2)
|
||||
ht[hash(w)] = ip - 2
|
||||
end
|
||||
else
|
||||
ip += rshift(skip, 6) -- step up over incompressible data (the reference's acceleration)
|
||||
skip += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the last literals
|
||||
local lit = iend - anchor
|
||||
local tok = op
|
||||
op += 1
|
||||
if lit >= 15 then
|
||||
op = extend(dst, op, lit - 15)
|
||||
writeu8(dst, tok, 0xF0)
|
||||
else
|
||||
writeu8(dst, tok, lit * 16)
|
||||
end
|
||||
if lit > 0 then
|
||||
bcopy(dst, op, src, anchor, lit)
|
||||
op += lit
|
||||
end
|
||||
return op - d
|
||||
end
|
||||
|
||||
-- compress(src, offset?, length?) -> buffer (one block) | nil, Err
|
||||
function Lz4.compress(src: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?)
|
||||
local b, o, l, aerr = Bytes.span("Lz4.compress", src, offset, length)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local tmp = bcreate(Lz4.bound(l))
|
||||
local n = Lz4.encodeInto(b, o, l, tmp, 0)
|
||||
local out = bcreate(n)
|
||||
bcopy(out, 0, tmp, 0, n)
|
||||
return out, nil
|
||||
end
|
||||
|
||||
return Lz4
|
||||
@@ -0,0 +1,319 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/UnixCompress: the LZW of Unix compress (.Z files: magic 1F 9D, a flags byte with the maximum code
|
||||
-- width 9..16 and the block mode bit), decode and encode. A codec (layer 3): archive/z builds on it. Codes are
|
||||
-- LSB-first, 9 bits wide at the start; the width grows when the next free code passes 2^width - 1 (up to the
|
||||
-- maximum), and in block mode code 256 clears the table. compress writes codes in groups of eight: when the width
|
||||
-- changes or a CLEAR is read, the rest of the current group (counted from the previous change) is skipped. The encoder
|
||||
-- reproduces ncompress 5.0 bit for bit: greedy longest match, a full table frozen until the compression ratio checked
|
||||
-- every 10000 input bytes drops, then a CLEAR. Written from the ncompress sources (public domain, The Unlicense: read
|
||||
-- for the format and the encoder's ratio check; licenses/ncompress-UNLICENSE.txt). Never throws.
|
||||
--
|
||||
-- local out, err = UnixCompress.decompress(buf, offset?, length?, { maxBytes = 2^28 }) -- a whole .Z file
|
||||
-- local z = UnixCompress.compress(buf, offset?, length?, { maxBits = 16 }) -- -> a .Z file
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local UnixCompress = {}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number? } -- refuse output larger than this (default 2^30)
|
||||
export type EncodeOptions = { maxBits: number? } -- 9..16, default 16
|
||||
|
||||
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
|
||||
local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift
|
||||
local bcreate, bcopy, blen = buffer.create, buffer.copy, buffer.len
|
||||
|
||||
local MAXCODES = 65536
|
||||
local CHECK_GAP = 10000
|
||||
|
||||
-- decoder tables (per call state lives in locals; the tables are reused: decode never yields)
|
||||
local prefix = bcreate(MAXCODES * 4) -- u32: the code an entry extends
|
||||
local suffix = bcreate(MAXCODES) -- u8: its last byte
|
||||
local first = bcreate(MAXCODES) -- u8: its first byte
|
||||
local length = bcreate(MAXCODES * 4) -- u32: its length
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- decompress(buf, offset?, length?, opts?) -> buffer | nil, Err
|
||||
function UnixCompress.decompress(buf: buffer | string, offset: number?, len: number?, opts: DecodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("UnixCompress.decompress", buf, offset, len)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local maxBytes = (opts and opts.maxBytes) or 2 ^ 30
|
||||
if n < 3 then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", o)
|
||||
end
|
||||
if readu8(b, o) ~= 0x1F or readu8(b, o + 1) ~= 0x9D then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", o)
|
||||
end
|
||||
local flags = readu8(b, o + 2)
|
||||
local maxbits = band(flags, 0x1F)
|
||||
local block = band(flags, 0x80) ~= 0
|
||||
if maxbits < 9 or maxbits > 16 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "maximum code width " .. maxbits, o + 2)
|
||||
end
|
||||
if band(flags, 0x60) ~= 0 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "reserved flag bits set", o + 2)
|
||||
end
|
||||
local maxmax = lshift(1, maxbits)
|
||||
for i = 0, 255 do
|
||||
writeu32(prefix, i * 4, 0)
|
||||
writeu8(suffix, i, i)
|
||||
writeu8(first, i, i)
|
||||
writeu32(length, i * 4, 1)
|
||||
end
|
||||
local cap = math.min(math.max(n * 3, 1024), maxBytes)
|
||||
local out = bcreate(cap)
|
||||
local op = 0
|
||||
local totalBits = (n - 3) * 8
|
||||
local base = o + 3
|
||||
local pos = 0 -- bit position from the first code
|
||||
local gbase = 0 -- where the current group sequence starts
|
||||
local nbits = 9
|
||||
local mask = 511
|
||||
local maxcode = 511
|
||||
local freeEnt = if block then 257 else 256
|
||||
local prev = -1
|
||||
while pos + nbits <= totalBits do
|
||||
if freeEnt > maxcode then
|
||||
local g = nbits * 8
|
||||
pos = gbase + (pos - gbase + g - 1) // g * g
|
||||
gbase = pos
|
||||
nbits += 1
|
||||
maxcode = if nbits == maxbits then maxmax else lshift(1, nbits) - 1
|
||||
mask = lshift(1, nbits) - 1
|
||||
continue
|
||||
end
|
||||
-- the code: up to 23 bits from three bytes
|
||||
local q = base + rshift(pos, 3)
|
||||
local acc = readu8(b, q)
|
||||
if q + 1 < o + n then
|
||||
acc = bor(acc, lshift(readu8(b, q + 1), 8))
|
||||
end
|
||||
if q + 2 < o + n then
|
||||
acc = bor(acc, lshift(readu8(b, q + 2), 16))
|
||||
end
|
||||
local c = band(rshift(acc, band(pos, 7)), mask)
|
||||
pos += nbits
|
||||
if c == 256 and block then
|
||||
local g = nbits * 8
|
||||
pos = gbase + (pos - gbase + g - 1) // g * g
|
||||
gbase = pos
|
||||
nbits = 9
|
||||
mask = 511
|
||||
maxcode = 511
|
||||
freeEnt = 257
|
||||
prev = -1
|
||||
continue
|
||||
end
|
||||
local l
|
||||
if prev < 0 then
|
||||
if c >= 256 then
|
||||
return nil, Err.new(Err.CORRUPT, "first code is not a literal", base + rshift(pos, 3))
|
||||
end
|
||||
l = 1
|
||||
elseif c < freeEnt then
|
||||
l = readu32(length, c * 4)
|
||||
elseif c == freeEnt then
|
||||
l = readu32(length, prev * 4) + 1
|
||||
else
|
||||
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
|
||||
end
|
||||
if op + l > cap then
|
||||
if op + l > maxBytes then
|
||||
return nil, Err.new(Err.LIMIT, "output over " .. maxBytes .. " bytes")
|
||||
end
|
||||
local ncap = math.min(math.max(cap * 2, op + l), maxBytes)
|
||||
local nb = bcreate(ncap)
|
||||
bcopy(nb, 0, out, 0, op)
|
||||
out, cap = nb, ncap
|
||||
end
|
||||
-- the new entry (prev + first byte of c's string) before the copy: KwKwK reads it
|
||||
if prev >= 0 and freeEnt < maxmax then
|
||||
local f = if c == freeEnt then readu8(first, prev) else readu8(first, c)
|
||||
writeu32(prefix, freeEnt * 4, prev)
|
||||
writeu8(suffix, freeEnt, f)
|
||||
writeu8(first, freeEnt, readu8(first, prev))
|
||||
writeu32(length, freeEnt * 4, readu32(length, prev * 4) + 1)
|
||||
freeEnt += 1
|
||||
elseif prev >= 0 then
|
||||
if c == freeEnt then
|
||||
return nil, Err.new(Err.CORRUPT, "code past the table", base + rshift(pos, 3))
|
||||
end
|
||||
end
|
||||
local p = op + l - 1
|
||||
local k = c
|
||||
while p >= op do
|
||||
writeu8(out, p, readu8(suffix, k))
|
||||
k = readu32(prefix, k * 4)
|
||||
p -= 1
|
||||
end
|
||||
op += l
|
||||
prev = c
|
||||
end
|
||||
local res = bcreate(op)
|
||||
bcopy(res, 0, out, 0, op)
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local HSIZE = 1 * 131072 -- open addressing over (prefix << 8 | byte) + 1 keys: twice the 65536 entries
|
||||
local hkey = bcreate(HSIZE * 4)
|
||||
local hval = bcreate(HSIZE * 4)
|
||||
|
||||
-- compress(buf, offset?, length?, opts?) -> a .Z file (block mode) | nil, Err
|
||||
function UnixCompress.compress(buf: buffer | string, offset: number?, len: number?, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local b, o, n, aerr = Bytes.span("UnixCompress.compress", buf, offset, len)
|
||||
if not b then
|
||||
return nil, aerr
|
||||
end
|
||||
local maxbits = (opts and opts.maxBits) or 16
|
||||
if type(maxbits) ~= "number" or maxbits < 9 or maxbits > 16 or maxbits % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "maxBits must be 9..16")
|
||||
end
|
||||
-- at most 17 bits per input byte, plus group padding (< one group per width change / clear)
|
||||
local cap = 3 + n * 2 + 64
|
||||
local out = bcreate(cap)
|
||||
writeu8(out, 0, 0x1F)
|
||||
writeu8(out, 1, 0x9D)
|
||||
writeu8(out, 2, bor(maxbits, 0x80))
|
||||
local outbits = 24
|
||||
local boff = 24
|
||||
local acc, nb = 0, 0 -- pending bits not yet written (below 2^24)
|
||||
local nbits = 9
|
||||
local extcode = 513
|
||||
local maxmax = lshift(1, maxbits)
|
||||
local stcode = true
|
||||
local freeEnt = 257
|
||||
local ratio = 0
|
||||
local checkpoint = CHECK_GAP
|
||||
buffer.fill(hkey, 0, 0, HSIZE * 4)
|
||||
local function put(code: number)
|
||||
acc = bor(acc, lshift(code, nb))
|
||||
nb += nbits
|
||||
outbits += nbits
|
||||
while nb >= 8 do
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
acc = rshift(acc, 8)
|
||||
nb -= 8
|
||||
end
|
||||
end
|
||||
local function align()
|
||||
-- round outbits up to a whole group of nbits-bit codes since boff; the skipped bits are zeros
|
||||
local g = nbits * 8
|
||||
local nbits2 = boff + (outbits - boff + g - 1) // g * g
|
||||
if nb > 0 then
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
end
|
||||
acc, nb = 0, 0
|
||||
outbits = nbits2
|
||||
boff = nbits2
|
||||
end
|
||||
if n == 0 then
|
||||
local res = bcreate(3)
|
||||
bcopy(res, 0, out, 0, 3)
|
||||
return res, nil
|
||||
end
|
||||
local ent = readu8(b, o)
|
||||
local e = o + n
|
||||
local i = o + 1
|
||||
-- checks happen with a one-byte current string, right after an output (and at the start)
|
||||
local function checks(consumed: number)
|
||||
if freeEnt >= extcode then
|
||||
if nbits < maxbits then
|
||||
align()
|
||||
nbits += 1
|
||||
extcode = if nbits < maxbits then lshift(1, nbits) + 1 else lshift(1, nbits)
|
||||
else
|
||||
extcode = math.huge
|
||||
stcode = false
|
||||
end
|
||||
end
|
||||
if not stcode and consumed >= checkpoint then
|
||||
checkpoint = consumed + CHECK_GAP
|
||||
local outBytes = rshift(outbits, 3)
|
||||
local rat
|
||||
if consumed > 0x7FFFFF then
|
||||
local d = rshift(outBytes, 8)
|
||||
rat = if d == 0 then 0x7FFFFFFF else consumed // d
|
||||
else
|
||||
rat = (consumed * 256) // outBytes
|
||||
end
|
||||
if rat >= ratio then
|
||||
ratio = rat
|
||||
else
|
||||
ratio = 0
|
||||
buffer.fill(hkey, 0, 0, HSIZE * 4)
|
||||
put(256)
|
||||
align()
|
||||
nbits = 9
|
||||
extcode = 513
|
||||
freeEnt = 257
|
||||
stcode = true
|
||||
end
|
||||
end
|
||||
end
|
||||
checks(1)
|
||||
while i < e do
|
||||
local c = readu8(b, i)
|
||||
i += 1
|
||||
local key = ent * 256 + c + 1
|
||||
local h = band(ent * 4099 + c * 131 + rshift(ent, 5), HSIZE - 1)
|
||||
local found = -1
|
||||
while true do
|
||||
local k = readu32(hkey, h * 4)
|
||||
if k == 0 then
|
||||
break
|
||||
elseif k == key then
|
||||
found = readu32(hval, h * 4)
|
||||
break
|
||||
end
|
||||
h = band(h + 1, HSIZE - 1)
|
||||
end
|
||||
if found >= 0 then
|
||||
ent = found
|
||||
else
|
||||
put(ent)
|
||||
if stcode then
|
||||
writeu32(hkey, h * 4, key)
|
||||
writeu32(hval, h * 4, freeEnt)
|
||||
freeEnt += 1
|
||||
end
|
||||
ent = c
|
||||
checks(i - o)
|
||||
end
|
||||
if rshift(outbits, 3) + 8 > cap then
|
||||
-- grow (rare: only incompressible input passes 2 bytes per byte)
|
||||
local ncap = cap * 2
|
||||
local nbuf = bcreate(ncap)
|
||||
bcopy(nbuf, 0, out, 0, cap)
|
||||
out, cap = nbuf, ncap
|
||||
end
|
||||
end
|
||||
put(ent)
|
||||
if nb > 0 then
|
||||
local q = rshift(outbits - nb, 3)
|
||||
if q < cap then
|
||||
writeu8(out, q, band(acc, 255))
|
||||
end
|
||||
end
|
||||
local size = rshift(outbits + 7, 3)
|
||||
local res = bcreate(size)
|
||||
bcopy(res, 0, out, 0, math.min(size, cap))
|
||||
return res, nil
|
||||
end
|
||||
|
||||
-- isCompress(buf, offset?) -> true when the bytes at offset start a .Z file
|
||||
function UnixCompress.isCompress(b: buffer, o: number?): boolean
|
||||
local p = o or 0
|
||||
return p + 3 <= blen(b) and readu8(b, p) == 0x1F and readu8(b, p + 1) == 0x9D
|
||||
end
|
||||
|
||||
return UnixCompress
|
||||
@@ -0,0 +1,72 @@
|
||||
--!strict
|
||||
--!native
|
||||
--!optimize 2
|
||||
-- codecs/compress/Xxh32: XXH32 of a buffer range (any seed), for the LZ4 frame format's header, block and content
|
||||
-- checksums. 32 x 32 -> 32 products split one operand into 16-bit limbs so every partial product is exact in a double.
|
||||
-- From the xxHash specification (Yann Collet, BSD-2); no code copied. Never throws (the range is clamped to the buffer).
|
||||
--
|
||||
-- local h = Xxh32.hash(buf, offset?, length?, seed?) -- a number in 0 .. 2^32 - 1
|
||||
local Xxh32 = {}
|
||||
|
||||
local bxor, bor, lshift, rshift = bit32.bxor, bit32.bor, bit32.lshift, bit32.rshift
|
||||
local readu8, readu32 = buffer.readu8, buffer.readu32
|
||||
|
||||
local T32 = 4294967296
|
||||
local P1, P2, P3, P4, P5 = 0x9E3779B1, 0x85EBCA77, 0xC2B2AE3D, 0x27D4EB2F, 0x165667B1
|
||||
|
||||
-- a * b mod 2^32 (a, b below 2^32)
|
||||
local function mul(a: number, b: number): number
|
||||
local a0 = a % 65536
|
||||
local a1 = (a - a0) / 65536
|
||||
return (a0 * b + ((a1 * b) % 65536) * 65536) % T32
|
||||
end
|
||||
|
||||
local function rotl(x: number, r: number): number
|
||||
return bor(lshift(x, r), rshift(x, 32 - r))
|
||||
end
|
||||
|
||||
local function round(acc: number, lane: number): number
|
||||
return mul(rotl((acc + mul(lane, P2)) % T32, 13), P1)
|
||||
end
|
||||
|
||||
-- hash(buf, offset?, length?, seed?) -> XXH32
|
||||
function Xxh32.hash(b: buffer, offset: number?, length: number?, seed: number?): number
|
||||
local n0 = buffer.len(b)
|
||||
local o = math.clamp(offset or 0, 0, n0)
|
||||
local n = math.clamp(length or (n0 - o), 0, n0 - o)
|
||||
local s = (seed or 0) % T32
|
||||
local p = o
|
||||
local e = o + n
|
||||
local h
|
||||
if n >= 16 then
|
||||
local v1 = (s + P1 + P2) % T32
|
||||
local v2 = (s + P2) % T32
|
||||
local v3 = s
|
||||
local v4 = (s - P1) % T32
|
||||
local last = e - 16
|
||||
while p <= last do
|
||||
v1 = round(v1, readu32(b, p))
|
||||
v2 = round(v2, readu32(b, p + 4))
|
||||
v3 = round(v3, readu32(b, p + 8))
|
||||
v4 = round(v4, readu32(b, p + 12))
|
||||
p += 16
|
||||
end
|
||||
h = (rotl(v1, 1) + rotl(v2, 7) + rotl(v3, 12) + rotl(v4, 18)) % T32
|
||||
else
|
||||
h = (s + P5) % T32
|
||||
end
|
||||
h = (h + n) % T32
|
||||
while p + 4 <= e do
|
||||
h = mul(rotl((h + mul(readu32(b, p), P3)) % T32, 17), P4)
|
||||
p += 4
|
||||
end
|
||||
while p < e do
|
||||
h = mul(rotl((h + readu8(b, p) * P5) % T32, 11), P1)
|
||||
p += 1
|
||||
end
|
||||
h = mul(bxor(h, rshift(h, 15)), P2)
|
||||
h = mul(bxor(h, rshift(h, 13)), P3)
|
||||
return bxor(h, rshift(h, 16))
|
||||
end
|
||||
|
||||
return Xxh32
|
||||
@@ -13,6 +13,7 @@
|
||||
-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Tar = require("@formats/containers/Tar")
|
||||
|
||||
local Archive = {}
|
||||
|
||||
@@ -176,6 +177,38 @@ function Archive.files(value: any, name: string?): ({ { name: string, data: buff
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- streamData(value) -> what a single-stream encoder compresses: a buffer / string as it is, an Archive's one file, or
|
||||
-- a tar of the Archive's entries (files, directories, symlinks with their mode / mtime) | nil, Err
|
||||
function Archive.streamData(value: any): (buffer?, Err.Err?)
|
||||
if type(value) == "buffer" then
|
||||
return value, nil
|
||||
elseif type(value) == "string" then
|
||||
return buffer.fromstring(value), nil
|
||||
end
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
|
||||
end
|
||||
if #items == 1 and not items[1].entry.dir then
|
||||
return items[1].read()
|
||||
end
|
||||
local list = {}
|
||||
for _, it in items do
|
||||
local e: any = it.entry
|
||||
local data: buffer? = nil
|
||||
if not e.dir and (e.type == nil or e.type == "0") then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
data = b
|
||||
end
|
||||
local typ = if type(e.type) == "string" and #e.type == 1 then e.type else nil
|
||||
table.insert(list, { name = e.name, data = data, dir = e.dir, type = typ, link = e.link, mtime = e.mtime, mode = e.mode })
|
||||
end
|
||||
return Tar.write(list)
|
||||
end
|
||||
|
||||
-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store
|
||||
-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date
|
||||
function Archive.fromDos(stamp: number): number?
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
--!strict
|
||||
-- containers/Cpio: cpio archives, read and written. Reading: SVR4 "newc" (070701, hex fields, 4-byte alignment),
|
||||
-- "crc" (070702: newc plus a byte-sum of the data, verified), POSIX.1 "odc" (070707, octal fields, no padding) and the
|
||||
-- old binary format in both byte orders (magic 070707 as a little / big endian u16, 2-byte alignment), up to the
|
||||
-- TRAILER!!! entry. Hard links: newc / crc store the data once, on the last link of an inode (as GNU cpio and bsdtar
|
||||
-- write it); every link of the group reads that data, and the later links name the first one in `hardlink`. Symlinks
|
||||
-- hold their target as data (`link`). Writing: newc (default), crc or odc, padded to opts.block bytes (default 512, as
|
||||
-- GNU cpio). Written from the cpio(5) manual pages (libarchive, GNU cpio) and POSIX.1-1988 (odc); no code ported. The
|
||||
-- archive formats (archive/cpio, archive/rpm's payload) build on it.
|
||||
--
|
||||
-- local entries, info = Cpio.read(buf, offset?, length?, opts?) -- { Entry } , { format = "newc" | ... } | nil, Err
|
||||
-- local out, err = Cpio.write({ { name = "a.txt", data = buf, mode = 0o100644, mtime = 0 } }, { format = "odc" })
|
||||
--
|
||||
-- Never throws: bad data returns nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
|
||||
local Cpio = {}
|
||||
|
||||
export type Entry = {
|
||||
name: string,
|
||||
size: number, -- data bytes (a symlink's target length; a hard link: the shared data's size)
|
||||
mode: number, -- the whole st_mode (file type bits included)
|
||||
type: string, -- tar type letters: "0" file, "5" directory, "2" symlink, "3" char device, "4" block device, "6" fifo, "s" socket
|
||||
dir: boolean,
|
||||
uid: number,
|
||||
gid: number,
|
||||
nlink: number,
|
||||
mtime: number,
|
||||
ino: number,
|
||||
devmajor: number,
|
||||
devminor: number,
|
||||
rdevmajor: number,
|
||||
rdevminor: number,
|
||||
link: string?, -- symlink target
|
||||
hardlink: string?, -- the first entry of this entry's hard link group (for the later links)
|
||||
offset: number, -- absolute offset of the data in the buffer
|
||||
check: number?, -- crc format: the stored byte sum
|
||||
}
|
||||
export type ReadOptions = {
|
||||
maxEntries: number?, -- default 1e6
|
||||
verify: boolean?, -- crc format: check the byte sums (default true)
|
||||
}
|
||||
export type Info = { format: string } -- "newc" | "crc" | "odc" | "bin" | "binbe"
|
||||
|
||||
local S_IFMT = 0xF000
|
||||
local TYPES: { [number]: string } = {
|
||||
[0x8000] = "0",
|
||||
[0x4000] = "5",
|
||||
[0xA000] = "2",
|
||||
[0x2000] = "3",
|
||||
[0x6000] = "4",
|
||||
[0x1000] = "6",
|
||||
[0xC000] = "s",
|
||||
}
|
||||
local MODES: { [string]: number } = {}
|
||||
for m, t in TYPES do
|
||||
MODES[t] = m
|
||||
end
|
||||
Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits
|
||||
Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter
|
||||
|
||||
local TRAILER = "TRAILER!!!"
|
||||
|
||||
-- format(buf, offset) -> "newc" | "crc" | "odc" | "bin" | "binbe" | nil: the format of the header at offset
|
||||
function Cpio.format(b: buffer, o: number): string?
|
||||
local n = buffer.len(b)
|
||||
if o + 6 <= n then
|
||||
local m = buffer.readstring(b, o, 6)
|
||||
if m == "070701" then
|
||||
return "newc"
|
||||
elseif m == "070702" then
|
||||
return "crc"
|
||||
elseif m == "070707" then
|
||||
return "odc"
|
||||
end
|
||||
end
|
||||
if o + 2 <= n then
|
||||
local v = buffer.readu16(b, o)
|
||||
if v == 0x71C7 then
|
||||
return "bin"
|
||||
elseif v == 0xC771 then
|
||||
return "binbe"
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- a fixed-width number field: hex (newc) or octal (odc); nil when not all digits
|
||||
local function num(b: buffer, o: number, n: number, base: number): number?
|
||||
local s = buffer.readstring(b, o, n)
|
||||
if base == 16 then
|
||||
if not string.find(s, "^%x+$") then
|
||||
return nil
|
||||
end
|
||||
elseif not string.find(s, "^[0-7]+$") then
|
||||
return nil
|
||||
end
|
||||
return tonumber(s, base)
|
||||
end
|
||||
|
||||
-- checksum(buf, offset, n) -> the crc format's sum of the data bytes (mod 2^32)
|
||||
function Cpio.checksum(b: buffer, o: number, n: number): number
|
||||
local s = 0
|
||||
local i = o
|
||||
local e = o + n
|
||||
while i + 4 <= e do
|
||||
local v = buffer.readu32(b, i)
|
||||
s += bit32.band(v, 255) + bit32.band(bit32.rshift(v, 8), 255) + bit32.band(bit32.rshift(v, 16), 255) + bit32.rshift(v, 24)
|
||||
i += 4
|
||||
end
|
||||
while i < e do
|
||||
s += buffer.readu8(b, i)
|
||||
i += 1
|
||||
end
|
||||
return s % 4294967296
|
||||
end
|
||||
|
||||
-- one header at p -> entry fields, header end (the name's start), name size, data size | nil, Err
|
||||
local function header(b: buffer, p: number, e: number, fmt: string): (any, Err.Err?)
|
||||
local h: any = {}
|
||||
local nameAt
|
||||
if fmt == "newc" or fmt == "crc" then
|
||||
if p + 110 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
|
||||
end
|
||||
local f = {} :: { number }
|
||||
for i = 1, 13 do
|
||||
local v = num(b, p + 6 + (i - 1) * 8, 8, 16)
|
||||
if not v then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header field", p + 6 + (i - 1) * 8)
|
||||
end
|
||||
f[i] = v
|
||||
end
|
||||
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.size = f[1], f[2], f[3], f[4], f[5], f[6], f[7]
|
||||
h.devmajor, h.devminor, h.rdevmajor, h.rdevminor, h.namesize, h.check = f[8], f[9], f[10], f[11], f[12], f[13]
|
||||
nameAt = p + 110
|
||||
elseif fmt == "odc" then
|
||||
if p + 76 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
|
||||
end
|
||||
local widths = { 6, 6, 6, 6, 6, 6, 6, 11, 6, 11 }
|
||||
local f = {} :: { number }
|
||||
local q = p + 6
|
||||
for i, w in widths do
|
||||
local v = num(b, q, w, 8)
|
||||
if not v then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header field", q)
|
||||
end
|
||||
f[i] = v
|
||||
q += w
|
||||
end
|
||||
h.ino, h.mode, h.uid, h.gid, h.nlink, h.mtime, h.namesize, h.size = f[2], f[3], f[4], f[5], f[6], f[8], f[9], f[10]
|
||||
h.devmajor, h.devminor = bit32.rshift(f[1], 8), bit32.band(f[1], 255)
|
||||
h.rdevmajor, h.rdevminor = bit32.rshift(f[7], 8), bit32.band(f[7], 255)
|
||||
nameAt = p + 76
|
||||
else
|
||||
if p + 26 > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
|
||||
end
|
||||
local be = fmt == "binbe"
|
||||
local function u16(i: number): number
|
||||
local v = buffer.readu16(b, p + i * 2)
|
||||
return if be then bit32.bor(bit32.rshift(v, 8), bit32.band(bit32.lshift(v, 8), 0xFF00)) else v
|
||||
end
|
||||
local dev, rdev = u16(1), u16(7)
|
||||
h.ino, h.mode, h.uid, h.gid, h.nlink = u16(2), u16(3), u16(4), u16(5), u16(6)
|
||||
h.mtime = u16(8) * 65536 + u16(9)
|
||||
h.namesize = u16(10)
|
||||
h.size = u16(11) * 65536 + u16(12)
|
||||
h.devmajor, h.devminor = bit32.rshift(dev, 8), bit32.band(dev, 255)
|
||||
h.rdevmajor, h.rdevminor = bit32.rshift(rdev, 8), bit32.band(rdev, 255)
|
||||
nameAt = p + 26
|
||||
end
|
||||
if h.namesize < 1 or nameAt + h.namesize > e then
|
||||
return nil, Err.new(if h.namesize < 1 then Err.CORRUPT else Err.TRUNCATED, "bad name size", nameAt)
|
||||
end
|
||||
h.nameAt = nameAt
|
||||
return h, nil
|
||||
end
|
||||
|
||||
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
|
||||
function Cpio.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
|
||||
local o = offset or 0
|
||||
local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
|
||||
local maxEntries = (opts and opts.maxEntries) or 1e6
|
||||
local verify = not (opts and opts.verify == false)
|
||||
local fmt = Cpio.format(b, o)
|
||||
if not fmt or o >= e then
|
||||
return nil, Err.new(Err.CORRUPT, "not a cpio archive", o)
|
||||
end
|
||||
local align = if fmt == "newc" or fmt == "crc" then 4 elseif fmt == "odc" then 1 else 2
|
||||
local out: { Entry } = {}
|
||||
local groups: { [string]: { Entry } } = {}
|
||||
local p = o
|
||||
while true do
|
||||
if p >= e then
|
||||
return nil, Err.new(Err.TRUNCATED, "no TRAILER!!! entry", p)
|
||||
end
|
||||
if Cpio.format(b, p) ~= fmt then
|
||||
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
|
||||
end
|
||||
local h, herr = header(b, p, e, fmt)
|
||||
if not h then
|
||||
return nil, herr
|
||||
end
|
||||
local name = buffer.readstring(b, h.nameAt, h.namesize)
|
||||
local z = string.find(name, "\0", 1, true)
|
||||
if z then
|
||||
name = string.sub(name, 1, z - 1)
|
||||
end
|
||||
local data = h.nameAt + h.namesize
|
||||
data = o + (data - o + align - 1) // align * align
|
||||
if name == TRAILER then
|
||||
break
|
||||
end
|
||||
if data + h.size > e then
|
||||
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " data past the end", data)
|
||||
end
|
||||
local typ = TYPES[bit32.band(h.mode, S_IFMT)] or "0"
|
||||
local entry: Entry = {
|
||||
name = name,
|
||||
size = h.size,
|
||||
mode = h.mode,
|
||||
type = typ,
|
||||
dir = typ == "5",
|
||||
uid = h.uid,
|
||||
gid = h.gid,
|
||||
nlink = h.nlink,
|
||||
mtime = h.mtime,
|
||||
ino = h.ino,
|
||||
devmajor = h.devmajor,
|
||||
devminor = h.devminor,
|
||||
rdevmajor = h.rdevmajor,
|
||||
rdevminor = h.rdevminor,
|
||||
link = if typ == "2" then buffer.readstring(b, data, h.size) else nil,
|
||||
hardlink = nil,
|
||||
offset = data,
|
||||
check = if fmt == "crc" then h.check else nil,
|
||||
}
|
||||
if fmt == "crc" and verify and typ == "0" and Cpio.checksum(b, data, h.size) ~= h.check then
|
||||
return nil, Err.new(Err.CHECKSUM, "entry " .. name .. ": data checksum mismatch", data)
|
||||
end
|
||||
if typ == "0" and h.nlink > 1 then
|
||||
local key = h.devmajor .. ":" .. h.devminor .. ":" .. h.ino
|
||||
local g = groups[key]
|
||||
if not g then
|
||||
g = {}
|
||||
groups[key] = g
|
||||
else
|
||||
entry.hardlink = g[1].name
|
||||
end
|
||||
table.insert(g, entry)
|
||||
end
|
||||
table.insert(out, entry)
|
||||
if #out > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
|
||||
end
|
||||
p = data + h.size
|
||||
p = o + (p - o + align - 1) // align * align
|
||||
end
|
||||
-- hard links: the links stored without data read the group's data (newc / crc keep it on the last link)
|
||||
for _, g in groups do
|
||||
local holder: Entry? = nil
|
||||
for _, x in g do
|
||||
if x.size > 0 then
|
||||
holder = x
|
||||
end
|
||||
end
|
||||
if holder then
|
||||
for _, x in g do
|
||||
if x.size == 0 then
|
||||
x.size, x.offset = holder.size, holder.offset
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out, { format = fmt }
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ writing
|
||||
export type WriteEntry = {
|
||||
name: string,
|
||||
data: buffer?, -- file data (a symlink: its target, else taken from link)
|
||||
mode: number?, -- st_mode; permission bits alone get the type bits from type / dir (default 0o644 / 0o755)
|
||||
type: string?, -- a type letter (see Entry.type); default "0" ("5" for dir)
|
||||
dir: boolean?,
|
||||
link: string?, -- symlink target
|
||||
uid: number?,
|
||||
gid: number?,
|
||||
nlink: number?, -- default 1 (2 for directories)
|
||||
mtime: number?, -- unix seconds (default 0)
|
||||
ino: number?, -- default: the entry's index (1, 2, ...); hard links share one
|
||||
devmajor: number?,
|
||||
devminor: number?,
|
||||
rdevmajor: number?,
|
||||
rdevminor: number?,
|
||||
}
|
||||
export type WriteOptions = {
|
||||
format: ("newc" | "crc" | "odc")?, -- default "newc"
|
||||
block: number?, -- pad the archive to a multiple of this many bytes (default 512; 1 = no padding)
|
||||
}
|
||||
|
||||
local function hex8(v: number): string?
|
||||
if v < 0 or v % 1 ~= 0 or v >= 4294967296 then
|
||||
return nil
|
||||
end
|
||||
return string.format("%08X", v)
|
||||
end
|
||||
|
||||
local function oct(v: number, w: number): string?
|
||||
if v < 0 or v % 1 ~= 0 or v >= 8 ^ w then
|
||||
return nil
|
||||
end
|
||||
local s = string.format("%o", v)
|
||||
return string.rep("0", w - #s) .. s
|
||||
end
|
||||
|
||||
-- write(entries, opts?) -> buffer | nil, Err
|
||||
function Cpio.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
|
||||
local fmt = (opts and opts.format) or "newc"
|
||||
if fmt ~= "newc" and fmt ~= "crc" and fmt ~= "odc" then
|
||||
return nil, Err.new(Err.ARG, "format must be newc, crc or odc")
|
||||
end
|
||||
local block = (opts and opts.block) or 512
|
||||
if type(block) ~= "number" or block < 1 or block % 1 ~= 0 then
|
||||
return nil, Err.new(Err.ARG, "block must be a positive integer")
|
||||
end
|
||||
-- newc / crc: a hard link group's data goes on its last link only
|
||||
local last: { [string]: number } = {}
|
||||
local prepared: { any } = table.create(#entries)
|
||||
for i, e in entries do
|
||||
if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
|
||||
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
|
||||
end
|
||||
local typ = e.type or (if e.dir then "5" else "0")
|
||||
local tbits = MODES[typ]
|
||||
if not tbits then
|
||||
return nil, Err.new(Err.ARG, "entry " .. e.name .. ": unknown type " .. tostring(typ))
|
||||
end
|
||||
local mode = e.mode or (if typ == "5" then 0x1ED elseif typ == "2" then 0x1FF else 0x1A4)
|
||||
if bit32.band(mode, S_IFMT) == 0 then
|
||||
mode = bit32.bor(mode, tbits)
|
||||
end
|
||||
local data = e.data
|
||||
if typ == "2" and not data then
|
||||
data = buffer.fromstring(e.link or "")
|
||||
elseif typ ~= "0" and typ ~= "2" then
|
||||
data = nil
|
||||
end
|
||||
local nlink = e.nlink or (if typ == "5" then 2 else 1)
|
||||
local ino = e.ino or i
|
||||
local p = { e = e, mode = mode, data = data or buffer.create(0), nlink = nlink, ino = ino, typ = typ }
|
||||
prepared[i] = p
|
||||
if typ == "0" and nlink > 1 then
|
||||
last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. ino] = i
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer(1024)
|
||||
local function put(name: string, p: any, data: buffer): Err.Err?
|
||||
local e = p.e
|
||||
local namesize = #name + 1
|
||||
local size = buffer.len(data)
|
||||
if fmt == "odc" then
|
||||
local dev = (e.devmajor or 0) * 256 + (e.devminor or 0)
|
||||
local rdev = (e.rdevmajor or 0) * 256 + (e.rdevminor or 0)
|
||||
local fields = {
|
||||
oct(dev, 6),
|
||||
oct(p.ino, 6),
|
||||
oct(p.mode, 6),
|
||||
oct(e.uid or 0, 6),
|
||||
oct(e.gid or 0, 6),
|
||||
oct(p.nlink, 6),
|
||||
oct(rdev, 6),
|
||||
oct(math.floor(e.mtime or 0), 11),
|
||||
oct(namesize, 6),
|
||||
oct(size, 11),
|
||||
}
|
||||
for k = 1, 10 do
|
||||
if not fields[k] then
|
||||
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the odc header")
|
||||
end
|
||||
end
|
||||
w:string("070707" .. table.concat(fields :: { string }))
|
||||
w:string(name)
|
||||
w:u8(0)
|
||||
w:bytes(data)
|
||||
else
|
||||
local check = if fmt == "crc" and p.typ == "0" then Cpio.checksum(data, 0, size) else 0
|
||||
local fields = {
|
||||
hex8(p.ino),
|
||||
hex8(p.mode),
|
||||
hex8(e.uid or 0),
|
||||
hex8(e.gid or 0),
|
||||
hex8(p.nlink),
|
||||
hex8(math.floor(e.mtime or 0)),
|
||||
hex8(size),
|
||||
hex8(e.devmajor or 0),
|
||||
hex8(e.devminor or 0),
|
||||
hex8(e.rdevmajor or 0),
|
||||
hex8(e.rdevminor or 0),
|
||||
hex8(namesize),
|
||||
hex8(check),
|
||||
}
|
||||
for k = 1, 13 do
|
||||
if not fields[k] then
|
||||
return Err.new(Err.ARG, "entry " .. name .. ": a field does not fit the newc header")
|
||||
end
|
||||
end
|
||||
w:string((if fmt == "crc" then "070702" else "070701") .. table.concat(fields :: { string }))
|
||||
w:string(name)
|
||||
w:u8(0)
|
||||
w:fill(0, (4 - (110 + namesize) % 4) % 4)
|
||||
w:bytes(data)
|
||||
w:fill(0, (4 - size % 4) % 4)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
for i, p in prepared do
|
||||
local data = p.data
|
||||
if fmt ~= "odc" and p.typ == "0" and p.nlink > 1 then
|
||||
local e = p.e
|
||||
if last[(e.devmajor or 0) .. ":" .. (e.devminor or 0) .. ":" .. p.ino] ~= i then
|
||||
data = buffer.create(0)
|
||||
end
|
||||
end
|
||||
local err = put(p.e.name, p, data)
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
local err = put(TRAILER, { e = {}, ino = 0, mode = 0, nlink = 1 }, buffer.create(0))
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
w:fill(0, (block - w.pos % block) % block)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
return Cpio
|
||||
@@ -0,0 +1,525 @@
|
||||
--!strict
|
||||
-- containers/Iso9660: ISO 9660 (ECMA-119) CD / DVD images, read. The volume descriptors from sector 16 (primary,
|
||||
-- supplementary, boot record, terminator); the directory tree walked through directory records (records never cross
|
||||
-- a sector; multi-extent files are joined; associated files skipped; interleaved files listed, their read is
|
||||
-- Err.UNSUPPORTED). Three name sets: plain ISO 9660 (";1" versions and a lone trailing "." dropped), Joliet (UCS-2 names
|
||||
-- of a supplementary descriptor with the %/@, %/C or %/E escape) and Rock Ridge (SUSP 1.12 / RRIP 1.12 in the
|
||||
-- primary tree: SP, CE continuation areas, NM names, PX modes / links / ids, PN devices, TF times, SL symlinks, CL / RE
|
||||
-- / PL relocated deep directories, with the rr_moved directory hidden when it ends up empty). The tree used is Rock
|
||||
-- Ridge when present, else Joliet, else plain (opts.prefer overrides). El Torito: the boot record's catalog
|
||||
-- (validation entry, initial / default entry) in info.boot. Written from ECMA-119, the SUSP / RRIP 1.12 and Joliet
|
||||
-- specifications and El Torito 1.0; no code ported. Not supported: zisofs (ZF) compressed files (listed; read returns
|
||||
-- the stored bytes), UDF, writing.
|
||||
--
|
||||
-- local entries, info = Iso9660.read(buf, offset?, length?, opts?) -- { Entry }, Info | nil, Err
|
||||
-- local data, err = Iso9660.extract(buf, base, entry) -- the entry's bytes (a copy of its extents)
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Text = require("@formats/codecs/text/Text")
|
||||
|
||||
local Iso9660 = {}
|
||||
|
||||
export type Extent = { at: number, size: number } -- byte offset (from the image start) and length
|
||||
export type Entry = {
|
||||
name: string, -- the path, "/" separated, no leading "/"
|
||||
dir: boolean,
|
||||
size: number,
|
||||
extents: { Extent },
|
||||
mtime: number?, -- unix seconds
|
||||
type: string, -- tar letters: "0" file, "5" directory, "2" symlink, "3" / "4" devices, "6" fifo, "s" socket
|
||||
mode: number?, -- Rock Ridge: the permission bits
|
||||
uid: number?,
|
||||
gid: number?,
|
||||
nlink: number?,
|
||||
link: string?, -- Rock Ridge symlink target
|
||||
rdev: number?, -- Rock Ridge PN: high * 2^32 + low
|
||||
hidden: boolean?,
|
||||
interleaved: boolean?,
|
||||
zisofs: boolean?,
|
||||
}
|
||||
export type ReadOptions = {
|
||||
prefer: ("rockridge" | "joliet" | "iso9660")?, -- the name set (default: Rock Ridge, else Joliet, else plain)
|
||||
maxEntries: number?, -- default 1e6
|
||||
}
|
||||
|
||||
local SECTOR = 2048
|
||||
local S_TYPES: { [number]: string } = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2", [0x2000] = "3", [0x6000] = "4", [0x1000] = "6", [0xC000] = "s" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fields
|
||||
local function u16(b: buffer, o: number): number
|
||||
return buffer.readu16(b, o)
|
||||
end
|
||||
local function u32(b: buffer, o: number): number
|
||||
return buffer.readu32(b, o)
|
||||
end
|
||||
local function str(b: buffer, o: number, n: number): string
|
||||
return (string.gsub(buffer.readstring(b, o, n), "[ %z]+$", ""))
|
||||
end
|
||||
|
||||
-- a 7-byte directory record date -> unix seconds
|
||||
local function recDate(b: buffer, o: number): number?
|
||||
local y = buffer.readu8(b, o)
|
||||
local m, d = buffer.readu8(b, o + 1), buffer.readu8(b, o + 2)
|
||||
if m < 1 or m > 12 or d < 1 or d > 31 then
|
||||
return nil
|
||||
end
|
||||
local off = buffer.readi8(b, o + 6)
|
||||
return Types.Date.toUnix({ kind = "datetime", year = 1900 + y, month = m, day = d, hour = buffer.readu8(b, o + 3), minute = buffer.readu8(b, o + 4), second = buffer.readu8(b, o + 5), offset = off * 15 })
|
||||
end
|
||||
|
||||
-- a 17-byte descriptor date ("YYYYMMDDHHMMSScc" + offset) -> unix seconds
|
||||
local function longDate(b: buffer, o: number): number?
|
||||
local s = buffer.readstring(b, o, 16)
|
||||
local y, mo, d, h, mi, se = string.match(s, "^(%d%d%d%d)(%d%d)(%d%d)(%d%d)(%d%d)(%d%d)%d%d$")
|
||||
if not y or tonumber(y) == 0 then
|
||||
return nil
|
||||
end
|
||||
local off = buffer.readi8(b, o + 16)
|
||||
return Types.Date.toUnix({ kind = "datetime", year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), minute = tonumber(mi), second = tonumber(se), offset = off * 15 })
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ SUSP / Rock Ridge
|
||||
type Susp = { [string]: any }
|
||||
|
||||
-- the SUSP entries of a system use area (following CE continuation areas) -> { { sig, at, len } }
|
||||
local function suspEntries(b: buffer, base: number, limit: number, o: number, e: number, bs: number, budget: { number }): { { any } }
|
||||
local out = {}
|
||||
while o + 4 <= e do
|
||||
local sig = buffer.readstring(b, o, 2)
|
||||
local len = buffer.readu8(b, o + 2)
|
||||
if len < 4 or o + len > e then
|
||||
break
|
||||
end
|
||||
if sig == "ST" then
|
||||
break
|
||||
elseif sig == "CE" and len >= 28 then
|
||||
local blk, off, n = u32(b, o + 4), u32(b, o + 12), u32(b, o + 20)
|
||||
local at = base + blk * bs + off
|
||||
budget[1] -= 1
|
||||
if budget[1] < 0 or at < base or at + n > limit or n > 65536 then
|
||||
break
|
||||
end
|
||||
-- the rest of this area first, then the continuation (it holds what did not fit)
|
||||
local rest = suspEntries(b, base, limit, o + len, e, bs, budget)
|
||||
for _, x in rest do
|
||||
table.insert(out, x)
|
||||
end
|
||||
local cont = suspEntries(b, base, limit, at, at + n, bs, budget)
|
||||
for _, x in cont do
|
||||
table.insert(out, x)
|
||||
end
|
||||
return out
|
||||
end
|
||||
table.insert(out, { sig, o, len })
|
||||
o += len
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- Rock Ridge fields of a record: { name, mode, uid, gid, nlink, mtime, link, rdev, child, relocated, zisofs }
|
||||
local function rockRidge(b: buffer, base: number, limit: number, o: number, e: number, bs: number): Susp
|
||||
local rr: Susp = {}
|
||||
local name: { string }? = nil
|
||||
local slParts: { string }? = nil
|
||||
local slRoot = false
|
||||
local slCont = false
|
||||
for _, x in suspEntries(b, base, limit, o, e, bs, { 32 }) do
|
||||
local sig, at, len = x[1], x[2], x[3]
|
||||
if sig == "NM" and len >= 5 then
|
||||
local flags = buffer.readu8(b, at + 4)
|
||||
if bit32.band(flags, 6) == 0 then
|
||||
name = name or {}
|
||||
table.insert(name :: { string }, buffer.readstring(b, at + 5, len - 5))
|
||||
end
|
||||
elseif sig == "PX" and len >= 36 then
|
||||
rr.mode, rr.nlink, rr.uid, rr.gid = u32(b, at + 4), u32(b, at + 12), u32(b, at + 20), u32(b, at + 28)
|
||||
elseif sig == "PN" and len >= 20 then
|
||||
rr.rdev = u32(b, at + 4) * 4294967296 + u32(b, at + 12)
|
||||
elseif sig == "TF" and len >= 5 then
|
||||
local flags = buffer.readu8(b, at + 4)
|
||||
local w = if bit32.band(flags, 0x80) ~= 0 then 17 else 7
|
||||
local q = at + 5
|
||||
for bit = 0, 6 do
|
||||
if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
|
||||
if q + w > at + len then
|
||||
break
|
||||
end
|
||||
if bit == 1 then
|
||||
rr.mtime = if w == 17 then longDate(b, q) else recDate(b, q)
|
||||
end
|
||||
q += w
|
||||
end
|
||||
end
|
||||
elseif sig == "SL" and len >= 5 then
|
||||
slParts = slParts or {}
|
||||
local parts = slParts :: { string }
|
||||
local q = at + 5
|
||||
while q + 2 <= at + len do
|
||||
local cf, cl = buffer.readu8(b, q), buffer.readu8(b, q + 1)
|
||||
if q + 2 + cl > at + len then
|
||||
break
|
||||
end
|
||||
local piece = if bit32.band(cf, 2) ~= 0 then "." elseif bit32.band(cf, 4) ~= 0 then ".." else buffer.readstring(b, q + 2, cl)
|
||||
if bit32.band(cf, 8) ~= 0 then
|
||||
slRoot = #parts == 0
|
||||
piece = ""
|
||||
end
|
||||
if slCont and #parts > 0 then
|
||||
parts[#parts] ..= piece
|
||||
elseif bit32.band(cf, 8) == 0 or #parts > 0 then
|
||||
table.insert(parts, piece)
|
||||
end
|
||||
slCont = bit32.band(cf, 1) ~= 0
|
||||
q += 2 + cl
|
||||
end
|
||||
elseif sig == "CL" and len >= 12 then
|
||||
rr.child = u32(b, at + 4)
|
||||
elseif sig == "RE" then
|
||||
rr.relocated = true
|
||||
elseif sig == "ZF" then
|
||||
rr.zisofs = true
|
||||
end
|
||||
end
|
||||
if name then
|
||||
rr.name = table.concat(name)
|
||||
end
|
||||
if slParts then
|
||||
rr.link = (if slRoot then "/" else "") .. table.concat(slParts, "/")
|
||||
end
|
||||
return rr
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ directories
|
||||
type Record = {
|
||||
name: string,
|
||||
dir: boolean,
|
||||
lba: number,
|
||||
size: number,
|
||||
ear: number,
|
||||
flags: number,
|
||||
interleave: boolean,
|
||||
mtime: number?,
|
||||
rr: Susp?,
|
||||
}
|
||||
|
||||
-- the records of a directory extent (without "." and "..") | nil, Err
|
||||
local function records(b: buffer, base: number, limit: number, at: number, size: number, bs: number, joliet: boolean, rrSkip: number?): ({ Record }?, Err.Err?)
|
||||
if at + size > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", at)
|
||||
end
|
||||
local out: { Record } = {}
|
||||
local p = at
|
||||
local e = at + size
|
||||
while p < e do
|
||||
local len = buffer.readu8(b, p)
|
||||
if len == 0 then
|
||||
p = at + ((p - at) // SECTOR + 1) * SECTOR -- the rest of the sector is padding
|
||||
continue
|
||||
end
|
||||
if len < 34 or p + len > e then
|
||||
return nil, Err.new(Err.CORRUPT, "bad directory record", p)
|
||||
end
|
||||
local nl = buffer.readu8(b, p + 32)
|
||||
if 33 + nl > len then
|
||||
return nil, Err.new(Err.CORRUPT, "bad name length", p + 32)
|
||||
end
|
||||
local raw = buffer.readstring(b, p + 33, nl)
|
||||
if raw ~= "\0" and raw ~= "\1" then
|
||||
local flags = buffer.readu8(b, p + 25)
|
||||
local name
|
||||
if joliet then
|
||||
name = Text.utf16(b, p + 33, nl, true)
|
||||
else
|
||||
name = raw
|
||||
end
|
||||
name = string.gsub(name, ";%d*$", "")
|
||||
if not joliet and bit32.band(flags, 2) == 0 then
|
||||
name = string.gsub(name, "%.$", "")
|
||||
end
|
||||
local r: Record = {
|
||||
name = name,
|
||||
dir = bit32.band(flags, 2) ~= 0,
|
||||
lba = u32(b, p + 2),
|
||||
size = u32(b, p + 10),
|
||||
ear = buffer.readu8(b, p + 1),
|
||||
flags = flags,
|
||||
interleave = buffer.readu8(b, p + 26) ~= 0 or buffer.readu8(b, p + 27) ~= 0,
|
||||
mtime = recDate(b, p + 18),
|
||||
rr = nil,
|
||||
}
|
||||
if rrSkip then
|
||||
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0) + rrSkip
|
||||
r.rr = rockRidge(b, base, limit, su, p + len, bs)
|
||||
end
|
||||
table.insert(out, r)
|
||||
end
|
||||
p += len
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- the root record of a volume descriptor at vd -> lba, size
|
||||
local function root(b: buffer, vd: number): (number, number)
|
||||
return u32(b, vd + 156 + 2), u32(b, vd + 156 + 10)
|
||||
end
|
||||
|
||||
-- Rock Ridge in use: the root's "." record starts its system use area with SP (BE EF); its skip length
|
||||
local function rockRidgeSkip(b: buffer, base: number, limit: number, lba: number, bs: number): number?
|
||||
local p = base + lba * bs
|
||||
if p + 34 > limit then
|
||||
return nil
|
||||
end
|
||||
local len = buffer.readu8(b, p)
|
||||
local nl = buffer.readu8(b, p + 32)
|
||||
local su = p + 33 + nl + (if nl % 2 == 0 then 1 else 0)
|
||||
if len < 34 or su + 7 > p + len or p + len > limit then
|
||||
return nil
|
||||
end
|
||||
if buffer.readstring(b, su, 2) == "SP" and buffer.readu8(b, su + 4) == 0xBE and buffer.readu8(b, su + 5) == 0xEF then
|
||||
return buffer.readu8(b, su + 6)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ El Torito
|
||||
local function boot(b: buffer, base: number, limit: number, vd: number, bs: number): { [string]: any }?
|
||||
if str(b, vd + 7, 32) ~= "EL TORITO SPECIFICATION" then
|
||||
return nil
|
||||
end
|
||||
local cat = u32(b, vd + 0x47)
|
||||
local p = base + cat * bs
|
||||
local info: { [string]: any } = { catalog = cat }
|
||||
if p + 64 > limit or buffer.readu8(b, p) ~= 1 or buffer.readu8(b, p + 30) ~= 0x55 or buffer.readu8(b, p + 31) ~= 0xAA then
|
||||
return info
|
||||
end
|
||||
local sum = 0
|
||||
for i = 0, 30, 2 do
|
||||
sum += u16(b, p + i)
|
||||
end
|
||||
info.valid = sum % 65536 == 0
|
||||
info.platform = buffer.readu8(b, p + 1)
|
||||
info.id = str(b, p + 4, 24)
|
||||
local d = p + 32
|
||||
info.bootable = buffer.readu8(b, d) == 0x88
|
||||
info.media = buffer.readu8(b, d + 1) -- 0 no emulation, 1..3 floppies, 4 hard disk
|
||||
info.loadSegment = u16(b, d + 2)
|
||||
info.systemType = buffer.readu8(b, d + 4)
|
||||
info.sectors = u16(b, d + 6) -- 512-byte virtual sectors
|
||||
info.lba = u32(b, d + 8)
|
||||
return info
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ read
|
||||
-- read(buf, offset?, length?, opts?) -> { Entry }, Info | nil, Err
|
||||
function Iso9660.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, any)
|
||||
local base = offset or 0
|
||||
local limit = math.min(buffer.len(b), base + (length or (buffer.len(b) - base)))
|
||||
local o: ReadOptions = opts or {}
|
||||
local maxEntries = o.maxEntries or 1e6
|
||||
local pvd: number? = nil
|
||||
local svd: number? = nil
|
||||
local jolietLevel: number? = nil
|
||||
local bootInfo = nil
|
||||
local p = base + 16 * SECTOR
|
||||
for _ = 1, 64 do
|
||||
if p + SECTOR > limit then
|
||||
return nil, Err.new(Err.TRUNCATED, "volume descriptors past the end", p)
|
||||
end
|
||||
if buffer.readstring(b, p + 1, 5) ~= "CD001" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad volume descriptor", p)
|
||||
end
|
||||
local t = buffer.readu8(b, p)
|
||||
if t == 255 then
|
||||
break
|
||||
elseif t == 1 and not pvd then
|
||||
pvd = p
|
||||
elseif t == 2 then
|
||||
local esc = buffer.readstring(b, p + 88, 3)
|
||||
if esc == "%/@" or esc == "%/C" or esc == "%/E" then
|
||||
svd = p
|
||||
jolietLevel = if esc == "%/@" then 1 elseif esc == "%/C" then 2 else 3
|
||||
end
|
||||
elseif t == 0 then
|
||||
bootInfo = bootInfo or { vd = p }
|
||||
end
|
||||
p += SECTOR
|
||||
end
|
||||
if not pvd then
|
||||
return nil, Err.new(Err.CORRUPT, "no primary volume descriptor", base + 16 * SECTOR)
|
||||
end
|
||||
local pv = pvd :: number
|
||||
local bs = u16(b, pv + 128)
|
||||
if bs ~= 512 and bs ~= 1024 and bs ~= 2048 then
|
||||
return nil, Err.new(Err.CORRUPT, "bad logical block size " .. bs, pv + 128)
|
||||
end
|
||||
local info: { [string]: any } = {
|
||||
blockSize = bs,
|
||||
blocks = u32(b, pv + 80),
|
||||
systemId = str(b, pv + 8, 32),
|
||||
volumeId = str(b, pv + 40, 32),
|
||||
volumeSet = str(b, pv + 190, 128),
|
||||
publisher = str(b, pv + 318, 128),
|
||||
preparer = str(b, pv + 446, 128),
|
||||
application = str(b, pv + 574, 128),
|
||||
created = longDate(b, pv + 813),
|
||||
modified = longDate(b, pv + 830),
|
||||
joliet = jolietLevel,
|
||||
}
|
||||
if bootInfo then
|
||||
info.boot = boot(b, base, limit, bootInfo.vd, bs)
|
||||
end
|
||||
local rlba, rsize = root(b, pv)
|
||||
local rrSkip = rockRidgeSkip(b, base, limit, rlba, bs)
|
||||
info.rockRidge = rrSkip ~= nil
|
||||
local tree = o.prefer or (if rrSkip then "rockridge" elseif svd then "joliet" else "iso9660")
|
||||
if tree == "joliet" and not svd then
|
||||
tree = "iso9660"
|
||||
elseif tree == "rockridge" and not rrSkip then
|
||||
tree = "iso9660"
|
||||
end
|
||||
info.tree = tree
|
||||
local joliet = tree == "joliet"
|
||||
local useRR = if tree == "rockridge" then rrSkip else nil
|
||||
if joliet then
|
||||
rlba, rsize = root(b, svd :: number)
|
||||
end
|
||||
if tree == "joliet" then
|
||||
info.volumeId = (string.gsub(Text.utf16(b, (svd :: number) + 40, 32, true), "[ %z]+$", ""))
|
||||
end
|
||||
local out: { Entry } = {}
|
||||
local visited: { [number]: boolean } = {}
|
||||
local stack = { { lba = rlba, size = rsize, path = "" } }
|
||||
local relocatedDirs: { [string]: boolean } = {}
|
||||
while #stack > 0 do
|
||||
local d = table.remove(stack) :: any
|
||||
if visited[d.lba] then
|
||||
continue
|
||||
end
|
||||
visited[d.lba] = true
|
||||
local list, err = records(b, base, limit, base + d.lba * bs, d.size, bs, joliet, useRR)
|
||||
if not list then
|
||||
return nil, err
|
||||
end
|
||||
local i = 1
|
||||
local subdirs = {}
|
||||
while i <= #list do
|
||||
local r = list[i]
|
||||
-- multi-extent: this record and the following ones of the same name
|
||||
local extents: { Extent } = { { at = base + (r.lba + r.ear) * bs, size = r.size } }
|
||||
local total = r.size
|
||||
local last = r
|
||||
while bit32.band(last.flags, 0x80) ~= 0 and i < #list and list[i + 1].name == r.name do
|
||||
i += 1
|
||||
last = list[i]
|
||||
table.insert(extents, { at = base + (last.lba + last.ear) * bs, size = last.size })
|
||||
total += last.size
|
||||
end
|
||||
i += 1
|
||||
if bit32.band(r.flags, 4) ~= 0 then
|
||||
continue -- an associated file (resource fork)
|
||||
end
|
||||
local rr: any = r.rr
|
||||
if rr and rr.relocated then
|
||||
continue -- shown where its CL placeholder is
|
||||
end
|
||||
local name = if rr and rr.name then rr.name else r.name
|
||||
local path = d.path .. name
|
||||
local isDir = r.dir
|
||||
local lba: number, size: number = r.lba, r.size
|
||||
if rr and rr.child then
|
||||
-- a deep directory relocated by Rock Ridge: the placeholder points at it; its size is its "." record's
|
||||
isDir = true
|
||||
lba = rr.child
|
||||
local q = base + lba * bs
|
||||
size = if q + 14 <= limit then u32(b, q + 10) else 0
|
||||
end
|
||||
local typ = if isDir then "5" else "0"
|
||||
if rr and rr.mode then
|
||||
typ = S_TYPES[bit32.band(rr.mode, 0xF000)] or typ
|
||||
end
|
||||
local e: Entry = {
|
||||
name = path,
|
||||
dir = isDir,
|
||||
size = if isDir or typ ~= "0" then 0 else total,
|
||||
extents = if isDir or typ ~= "0" then {} else extents,
|
||||
mtime = if rr and rr.mtime then rr.mtime else r.mtime,
|
||||
type = typ,
|
||||
mode = if rr and rr.mode then bit32.band(rr.mode, 0xFFF) else nil,
|
||||
uid = rr and rr.uid,
|
||||
gid = rr and rr.gid,
|
||||
nlink = rr and rr.nlink,
|
||||
link = if rr and typ == "2" then rr.link else nil,
|
||||
rdev = rr and rr.rdev,
|
||||
hidden = if bit32.band(r.flags, 1) ~= 0 then true else nil,
|
||||
interleaved = if r.interleave then true else nil,
|
||||
zisofs = if rr and rr.zisofs then true else nil,
|
||||
}
|
||||
table.insert(out, e)
|
||||
if #out > maxEntries then
|
||||
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
|
||||
end
|
||||
if isDir then
|
||||
table.insert(subdirs, { lba = lba, size = size, path = path .. "/" })
|
||||
end
|
||||
end
|
||||
for k = #subdirs, 1, -1 do
|
||||
table.insert(stack, subdirs[k])
|
||||
end
|
||||
if useRR then
|
||||
for _, r in list do
|
||||
if r.rr and r.rr.relocated then
|
||||
relocatedDirs[d.path] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- rr_moved (genisoimage's home of relocated directories): hidden when nothing else is in it
|
||||
if useRR then
|
||||
for dirPath in relocatedDirs do
|
||||
local name = string.sub(dirPath, 1, -2)
|
||||
local holds = false
|
||||
for _, e in out do
|
||||
if string.sub(e.name, 1, #dirPath) == dirPath then
|
||||
holds = true
|
||||
break
|
||||
end
|
||||
end
|
||||
if not holds then
|
||||
for k, e in out do
|
||||
if e.name == name then
|
||||
table.remove(out, k)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- archive order: depth-first walk order is kept; directories sorted as the image stores them
|
||||
return out, info
|
||||
end
|
||||
|
||||
-- extract(buf, entry, limit?) -> a copy of the entry's data | nil, Err
|
||||
function Iso9660.extract(b: buffer, e: Entry, limit: number?): (buffer?, Err.Err?)
|
||||
if e.interleaved then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "interleaved file " .. e.name)
|
||||
end
|
||||
local lim = limit or buffer.len(b)
|
||||
local out = buffer.create(e.size)
|
||||
local q = 0
|
||||
for _, x in e.extents do
|
||||
if x.at < 0 or x.at + x.size > lim then
|
||||
return nil, Err.new(Err.TRUNCATED, "file " .. e.name .. " data past the end", x.at)
|
||||
end
|
||||
buffer.copy(out, q, b, x.at, x.size)
|
||||
q += x.size
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- valid(buf, offset?) -> true when a volume descriptor "CD001" sits at sector 16
|
||||
function Iso9660.valid(b: buffer, offset: number?): boolean
|
||||
local p = (offset or 0) + 16 * SECTOR
|
||||
return p + 6 <= buffer.len(b) and buffer.readstring(b, p + 1, 5) == "CD001"
|
||||
end
|
||||
|
||||
return Iso9660
|
||||
Reference in new issue
Block a user