--!strict -- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles -- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path, -- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields, -- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar -- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more, -- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX -- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi- -- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes). -- -- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } } -- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts) -- -- Never throws: bad data returns nil, Err. local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Tar = {} export type Entry = { name: string, size: number, type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ... dir: boolean, mode: number, uid: number, gid: number, mtime: number, link: string?, uname: string?, gname: string?, offset: number, -- absolute offset of the data in the buffer pax: { [string]: string }?, } local BLOCK = 512 local function zeros(b: buffer, o: number): boolean for i = 0, BLOCK - 1, 4 do if buffer.readu32(b, o + i) ~= 0 then return false end end return true end -- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte) local function number(b: buffer, o: number, n: number): number? local first = buffer.readu8(b, o) if first >= 0x80 then local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative for i = 1, n - 1 do v = v * 256 + buffer.readu8(b, o + i) end return v end local s = buffer.readstring(b, o, n) s = string.match(s, "^[ %z]*([0-7]*)") or "" if s == "" then return 0 end return tonumber(s, 8) end local function str(b: buffer, o: number, n: number): string local s = buffer.readstring(b, o, n) local z = string.find(s, "\0", 1, true) return if z then string.sub(s, 1, z - 1) else s end local function checksum(b: buffer, o: number): (number, number) local u, s = 0, 0 for i = 0, BLOCK - 1 do local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i) u += v s += if v >= 128 then v - 256 else v end return u, s end -- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum function Tar.valid(b: buffer, o: number): boolean if o + BLOCK > buffer.len(b) or zeros(b, o) then return false end local want = number(b, o + 148, 8) local u, s = checksum(b, o) return want == u or want == s end -- pax records "len key=value\n" -> { key = value } local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean local s = buffer.readstring(b, o, n) local p = 1 while p <= #s do if string.byte(s, p) == 0 then break end local len = string.match(s, "^(%d+) ", p) if not len then return false end local l = tonumber(len) :: number if l < #len + 3 or p + l - 1 > #s then return false end local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline local eq = string.find(rec, "=", 1, true) if not eq then return false end into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1) p += l end return true end export type ReadOptions = { maxEntries: number? } -- default 1e6 -- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?) 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 out: { Entry } = {} local global: { [string]: string } = {} local nextPax: { [string]: string }? = nil local longName: string? = nil local longLink: string? = nil local p = o while true do if p + BLOCK > e then if p == e then break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning) end return nil, Err.new(Err.TRUNCATED, "header past the end", p) end if zeros(b, p) then break -- end of archive (one or two zero blocks; what follows is padding) end local want = number(b, p + 148, 8) local u, s = checksum(b, p) if want ~= u and want ~= s then return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148) end local typ = buffer.readstring(b, p + 156, 1) if typ == "\0" then typ = "0" end local size = number(b, p + 124, 12) if not size or size < 0 then return nil, Err.new(Err.CORRUPT, "bad size field", p + 124) end local data = p + BLOCK local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK local ustar = buffer.readstring(b, p + 257, 5) == "ustar" -- meta records: pax / GNU long names if typ == "x" or typ == "g" or typ == "L" or typ == "K" then if data + size > e then return nil, Err.new(Err.TRUNCATED, "extended header past the end", data) end if typ == "x" or typ == "g" then local into = if typ == "g" then global else (nextPax or {}) if not pax(b, data, size, into) then return nil, Err.new(Err.CORRUPT, "bad pax record", data) end if typ == "x" then nextPax = into end elseif typ == "L" then longName = str(b, data, size) else longLink = str(b, data, size) end p = nextHeader continue end local name = str(b, p, 100) if ustar then local prefix = str(b, p + 345, 155) if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times) name = prefix .. "/" .. name end end local entry: Entry = { name = name, size = size, type = typ, dir = typ == "5", mode = number(b, p + 100, 8) or 0, uid = number(b, p + 108, 8) or 0, gid = number(b, p + 116, 8) or 0, mtime = number(b, p + 136, 12) or 0, link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil, uname = if ustar then str(b, p + 265, 32) else nil, gname = if ustar then str(b, p + 297, 32) else nil, offset = data, pax = nil, } if longName then entry.name = longName end if longLink then entry.link = longLink end local px = nextPax for _, rec in { global, px } do if rec then if rec.path then entry.name = rec.path end if rec.linkpath then entry.link = rec.linkpath end if rec.size then local sz = tonumber(rec.size) if not sz or sz < 0 or sz % 1 ~= 0 then return nil, Err.new(Err.CORRUPT, "bad pax size", p) end entry.size = sz end if rec.mtime then entry.mtime = tonumber(rec.mtime) or entry.mtime end if rec.uid then entry.uid = tonumber(rec.uid) or entry.uid end if rec.gid then entry.gid = tonumber(rec.gid) or entry.gid end if rec.uname then entry.uname = rec.uname end if rec.gname then entry.gname = rec.gname end end end if px then entry.pax = px end if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then entry.dir = true end -- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir) local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size if typ == "5" or typ == "1" or typ == "2" then entry.size = 0 end nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK if typ ~= "5" and data + dataSize > e then return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data) end table.insert(out, entry) if #out > maxEntries then return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries") end nextPax, longName, longLink = nil, nil, nil p = nextHeader end return out, nil end -- ------------------------------------------------------------------------------------------------ writing export type WriteEntry = { name: string, data: buffer?, dir: boolean?, type: string?, -- default "0" ("5" for dir) link: string?, mode: number?, -- default 0o644 (0o755 for directories) uid: number?, gid: number?, uname: string?, gname: string?, mtime: number?, -- unix seconds (default 0) } export type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed) local function octal(w: buffer, o: number, n: number, v: number): boolean -- n - 1 octal digits and a NUL; false when it does not fit local s = string.format("%o", v) if v < 0 or v % 1 ~= 0 or #s > n - 1 then return false end buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s) buffer.writeu8(w, o + n - 1, 0) return true end local function field(w: buffer, o: number, n: number, s: string) buffer.writestring(w, o, string.sub(s, 1, n)) end local function ascii(s: string): boolean return not string.find(s, "[\128-\255]") end local function paxRecord(key: string, value: string): string local body = " " .. key .. "=" .. value .. "\n" local n = #body + 1 while #tostring(n) + #body ~= n do n = #tostring(n) + #body end return tostring(n) .. body end -- one header block (the checksum filled in) local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer local h = buffer.create(BLOCK) field(h, 0, 100, name) local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4) octal(h, 100, 8, mode % 0x200000) octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF)) octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF)) octal(h, 124, 12, size) octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1)) field(h, 148, 8, " ") field(h, 156, 1, typ) field(h, 157, 100, link) field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000") field(h, 265, 32, e.uname or "") field(h, 297, 32, e.gname or "") field(h, 345, 155, prefix) local u = checksum(h, 0) field(h, 148, 8, string.format("%06o", u) .. "\0 ") return h end -- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil local function split(path: string): (string?, string?) if #path <= 100 then return "", path end for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then return string.sub(path, 1, i - 1), string.sub(path, i + 1) end end return nil, nil end -- write(entries, opts?) -> buffer | nil, Err function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?) local fmt = (opts and opts.format) or "pax" local w = Bytes.writer(BLOCK * (2 * #entries + 2)) 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 data = e.data or buffer.create(0) local typ = e.type or (if e.dir then "5" else "0") local name = e.name if typ == "5" and string.sub(name, -1) ~= "/" then name ..= "/" end local size = if typ == "0" or typ == "7" then buffer.len(data) else 0 local link = e.link or "" -- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole local prefix, short if fmt == "ustar" then prefix, short = split(name) elseif #name <= 100 then prefix, short = "", name end local paxRecs: { string } = {} -- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name)) local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link)) if needName or needLink then if fmt == "ustar" then return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar") elseif fmt == "gnu" then if needName then local ln = buffer.fromstring(name .. "\0") w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true)) w:bytes(ln) w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK) end if needLink then local ll = buffer.fromstring(link .. "\0") w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true)) w:bytes(ll) w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK) end else if needName then table.insert(paxRecs, paxRecord("path", name)) end if needLink then table.insert(paxRecs, paxRecord("linkpath", link)) end end end if size >= 8 ^ 11 then if fmt ~= "pax" then return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax") end table.insert(paxRecs, paxRecord("size", tostring(size))) end local mt = e.mtime or 0 if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", ""))) end if #paxRecs > 0 then local body = buffer.fromstring(table.concat(paxRecs)) w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false)) w:bytes(body) w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK) end if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then -- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile) local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?") prefix, short = "", string.sub(stand, 1, 100) end w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu")) if size > 0 then w:bytes(data) w:fill(0, (BLOCK - size % BLOCK) % BLOCK) end end w:fill(0, BLOCK * 2) return w:finish(), nil end return Tar