--!strict -- archive/ar: Unix ar ("!\n"; ar(5), deb(5); no code ported): System V / GNU ("//" names, "/" and "/SYM64/" -- symbols) and BSD ("#1/", "__.SYMDEF"); .deb payload and control fields. Supports: read, write gnu / bsd. -- Not supported: thin archives ("!"), writing symbol tables or .deb control data. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Deflate = require("@rosetta/codecs/compress/Deflate") local Lzma = require("@rosetta/codecs/compress/Lzma") local Zstd = require("@rosetta/codecs/compress/Zstd") local Bzip2 = require("@rosetta/codecs/compress/Bzip2") local Archive = require("@rosetta/containers/Archive") local Tar = require("@rosetta/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 control.tar limit (default 2^26) } export type EncodeOptions = { variant: ("gnu" | "bsd")?, -- default: the source's ("bsd" for a .deb), else "gnu" } -- ------------------------------------------------------------------------------------------------ constants local MAGIC = "!\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) == "!\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 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) == "!\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 } = {} 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 } 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 function Ar.new(): any local a = Archive.new("ar", encode) a.meta.source = { format = "ar", variant = "gnu" } return a end return Ar