From a05199c34dd9c36f58fb395cf42ca0e343c3be0d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:02:43 -0500 Subject: [PATCH] ws-arch2-unix: containers/Cpio (newc / crc / odc / old binary both endians read; newc / crc / odc write; hard links, symlinks, devices) + archive/cpio (any Archive -> cpio), tests vs GNU cpio (byte-identical re-encode) and bsdtar --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/archive/cpio/init.luau | 169 +++++++++++ src/Formats/containers/Cpio.luau | 439 +++++++++++++++++++++++++++++ tests/archive/cpio.luau | 164 +++++++++++ tools/fixtures/cpio.py | 110 ++++++++ 6 files changed, 895 insertions(+) create mode 100644 src/Formats/archive/cpio/init.luau create mode 100644 src/Formats/containers/Cpio.luau create mode 100644 tests/archive/cpio.luau create mode 100644 tools/fixtures/cpio.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0d7ba63..d8e7438 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -52,6 +52,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` | | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | +| archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..e1b1387 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -578,6 +578,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 = "gzip", category = "archive", diff --git a/src/Formats/archive/cpio/init.luau b/src/Formats/archive/cpio/init.luau new file mode 100644 index 0000000..469e4e3 --- /dev/null +++ b/src/Formats/archive/cpio/init.luau @@ -0,0 +1,169 @@ +--!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 = { + format: string?, -- "newc" (default), "crc" or "odc" (any other value: newc) + 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 newc default then + local o: any = opts or {} + local variant = if o.format == "crc" or o.format == "odc" then o.format else "newc" + 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 diff --git a/src/Formats/containers/Cpio.luau b/src/Formats/containers/Cpio.luau new file mode 100644 index 0000000..aebf6d5 --- /dev/null +++ b/src/Formats/containers/Cpio.luau @@ -0,0 +1,439 @@ +--!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 + +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 diff --git a/tests/archive/cpio.luau b/tests/archive/cpio.luau new file mode 100644 index 0000000..d4e4b42 --- /dev/null +++ b/tests/archive/cpio.luau @@ -0,0 +1,164 @@ +-- archive/cpio tests (and containers/Cpio): GNU cpio archives of one tree in newc / crc / odc / bin (and the bin one +-- byte-swapped to big endian) and bsdtar newc / odc archives list the entries os.lstat sees (names, types, modes, sizes, +-- mtimes, link counts, symlink targets, data CRCs, hard links reading the shared data); re-encoding the GNU newc / crc / +-- odc archives gives GNU's bytes; devices (rdev fields), crc sums, a .cpio.gz through the api, conversions to and from +-- tar (hard links share an inode), errors, the fuzz pass. Fixtures: tools/fixtures/cpio.py. +local T = require("@tests/T") +local F = require("@formats") +local CpioF = require("@formats/archive/cpio") +local Cpio = require("@formats/containers/Cpio") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/cpio") + +local t = T.suite("cpio") +t:eq(CpioF.name, "cpio", "name") + +local function check(a: any, want: any, label: string) + local list = a:list() + t:eq(#list, #want, label .. ": entry count") + local by = {} + for _, e in list do + by[e.name] = e + end + for _, w in want do + local e = by[w.name] + t:check(e, label .. ": has " .. w.name) + t:eq(e.type, w.type, label .. ": " .. w.name .. " type") + t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode") + t:eq(e.size, w.size, label .. ": " .. w.name .. " size") + t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime") + if w.type ~= "5" then + t:eq(e.nlink, w.nlink, label .. ": " .. w.name .. " nlink") + end + t:eq(e.link, w.link, label .. ": " .. w.name .. " link") + t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir") + if w.crc then + local b, err = a:read(w.name) + t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err)) + t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data") + end + end +end + +-- 1. reading +for _, c in Fx.archives do + local a, err = CpioF.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + do + check(a, c.entries, c.name) + t:eq(a.meta.source.variant, c.format, c.name .. ": variant") + t:eq(F.detect(c.data), "cpio", c.name .. ": F.detect") + -- hard links: the later links of the hello.txt group name the first + local hl = 0 + for _, e in a:list() do + if e.hardlink then + hl += 1 + end + end + t:eq(hl, 2, c.name .. ": two later hard links") + end +end + +-- 2. writing: GNU's bytes back from the decoded archive (newc / crc / odc) +for _, c in Fx.archives do + if c.gnu and c.format ~= "bin" then + local a = CpioF.decode(Bytes.reader(buffer.fromstring(c.data))) + local out, err = a:write({ format = c.format }) + t:check(out, c.name .. ": write: " .. tostring(err)) + t:check(out and buffer.tostring(out) == c.data, c.name .. ": bytes identical to GNU cpio") + end +end + +-- 3. devices, sums, the container directly +do + local list, info = Cpio.read(buffer.fromstring(Fx.devices)) + t:check(list and info.format == "newc", "devices: read") + t:eq(#list, 4, "devices: entries") + t:eq(list[2].type, "3", "char device") + t:eq(list[2].rdevmajor * 256 + list[2].rdevminor, 259, "null: rdev 1:3") + t:eq(list[3].type, "4", "block device") + t:eq(list[3].rdevmajor, 8, "sda: rdev major") + t:eq(list[4].type, "s", "socket") + local _, e1 = Cpio.read(buffer.fromstring(Fx.badcrc)) + t:check(e1 and e1.code == Err.CHECKSUM, "crc: bad sum: " .. tostring(e1)) + t:check(Cpio.read(buffer.fromstring(Fx.badcrc), 0, nil, { verify = false }), "crc: verify = false") + -- devices survive a newc and an odc write + for _, fmt in { "newc", "odc" } do + local a = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.devices))) + local back = CpioF.decode(Bytes.reader(assert(a:write({ format = fmt })))) + local d = back:list()[3] + t:check(d.type == "4" and d.rdevmajor == 8 and d.rdevminor == 0, fmt .. ": block device round trip") + end +end + +-- 4. the api: .cpio.gz unwraps, Archive values, conversions +do + local a, err = F.load(Fx.gz, { name = "tree.cpio.gz" }) + t:check(a and a.format == "cpio" and a.meta.compression == "gzip", "cpio.gz unwraps: " .. tostring(err)) + local c = CpioF.new() + c:add("bin/", "", { dir = true }) + c:add("bin/run.sh", "#!/bin/sh\n", { mode = 493, mtime = 1767225600 }) + local back = F.load(assert(F.save(c))) + t:eq(back.format, "cpio", "F.save(cpio) round trip") + t:eq(back:list()[2].mode, 493, "mode round trip") + t:eq(back:list()[2].mtime, 1767225600, "mtime round trip") + t:eq(buffer.tostring(back:read("bin/run.sh")), "#!/bin/sh\n", "data round trip") + -- cpio -> tar keeps symlinks; tar -> cpio turns tar hard links into a shared inode + local gnu = CpioF.decode(Bytes.reader(buffer.fromstring(Fx.archives[1].data))) + local tar = F.load(assert(F.save(gnu, nil, { format = "tar" }))) + local sym + for _, e in tar:list() do + if e.name == "sym" then + sym = e + end + end + t:check(sym and sym.type == "2" and sym.link == "hello.txt", "cpio -> tar: symlink") + local tf = F.format("tar").new() + tf:add("a.txt", "shared") + tf:add("b.txt", "") + tf._byName["b.txt"].type, tf._byName["b.txt"].link = "1", "a.txt" + local cp = F.load(assert(F.save(tf, nil, { format = "cpio" }))) + t:eq(buffer.tostring(cp:read("b.txt")), "shared", "tar hard link -> cpio: data") + t:eq(cp:list()[2].hardlink, "a.txt", "tar hard link -> cpio: hardlink") + t:eq(cp:list()[1].nlink, 2, "tar hard link -> cpio: nlink") +end + +-- 5. errors +do + local good = Fx.archives[1].data + local _, e1 = CpioF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 300)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local b = buffer.fromstring(good) + buffer.writeu8(b, 10, string.byte("z")) + local _, e2 = CpioF.decode(Bytes.reader(b)) + t:check(e2 and e2.code == Err.CORRUPT, "bad hex field: " .. tostring(e2)) + local _, e3 = CpioF.encode({ kind = "image" }) + t:check(e3 and e3.code == Err.ARG, "encode a non-archive") + local _, e4 = Cpio.write({ { name = "x", data = buffer.create(1), mtime = 2 ^ 40 } }, { format = "odc" }) + t:check(e4 and e4.code == Err.ARG, "odc: mtime too large") + local _, e5 = CpioF.decode(Bytes.reader(buffer.fromstring("070701"))) + t:check(e5 and e5.code == Err.TRUNCATED, "header past the end") + t:eq(CpioF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 64)))), 0, "zeros are not cpio") +end + +local samples = {} +for _, c in Fx.archives do + if #c.data <= 20000 then + table.insert(samples, c.data) + end +end +table.insert(samples, Fx.devices) +t:fuzz("decode", function(b: buffer) + local a = CpioF.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 30, keepHeader = 0 }) + +t:done() diff --git a/tools/fixtures/cpio.py b/tools/fixtures/cpio.py new file mode 100644 index 0000000..2376125 --- /dev/null +++ b/tools/fixtures/cpio.py @@ -0,0 +1,110 @@ +# cpio fixtures (tools/fixtures.py): GNU cpio (nixpkgs#cpio, --reproducible) archives of one tree in newc / crc / odc / +# bin, the bin one byte-swapped into the big-endian old binary format, bsdtar (libarchive) newc / odc archives, a crafted +# newc archive with device nodes and a bad crc sum, and a .cpio.gz. The expected entries come from os.lstat of the tree. +# tests/gen/cpio.luau { archives = { { name, data, format, gnu?, entries = { { name, type, mode, size, mtime, nlink, +# link?, crc? } } } }, devices = data, badcrc = data, gz = data } +import gzip, os, shutil, stat, struct, subprocess, tempfile, zlib + +TYPES = {stat.S_IFREG: "0", stat.S_IFDIR: "5", stat.S_IFLNK: "2", stat.S_IFIFO: "6", stat.S_IFCHR: "3", stat.S_IFBLK: "4"} + + +def run(ctx, pkg, script, cwd): + return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", script], cwd=cwd, capture_output=True, check=True).stdout + + +def swap_bin(data): + """the little-endian old binary archive -> the big-endian one (every u16 header field swapped)""" + out, p = bytearray(), 0 + while True: + f = struct.unpack("<13H", data[p:p + 26]) + ns, fs = f[10], f[11] << 16 | f[12] + name = data[p + 26:p + 26 + ns - 1] + out += struct.pack(">13H", *f) + q = p + 26 + ns + (ns & 1) + e = q + fs + (fs & 1) + out += data[p + 26:e] + p = e + if name == b"TRAILER!!!": + return bytes(out + data[p:]) + + +def newc(name, mode, size=0, data=b"", nlink=1, rdev=(0, 0), check=0, ino=1, crc=False): + ns = len(name) + 1 + h = b"070701" + b"".join(b"%08X" % v for v in (ino, mode, 0, 0, nlink, 1600000000, size, 0, 0, rdev[0], rdev[1], ns, check)) + if crc: + h = b"070702" + h[6:] + b = h + name + b"\0" + b += b"\0" * (-len(b) % 4) + data + b"\0" * (-len(data) % 4) + return b + + +def generate(ctx): + rng = ctx.rng(11) + files = [ + ("hello.txt", b"hello, cpio\n"), + ("empty", b""), + ("dir/sub/data.bin", rng.randbytes(3000)), + ("exact4", b"four"), + ("odd", b"x" * 7), + ("d" * 60 + "/" + "e" * 80 + "/a-name-longer-than-a-hundred-bytes.txt", b"long " * 40), + ("unicodé/naïve.txt", "ünïcödé".encode()), + ] + tmp = tempfile.mkdtemp() + try: + root = os.path.join(tmp, "tree") + for name, data in files: + p = os.path.join(root, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(data) + os.chmod(os.path.join(root, "odd"), 0o755) + os.makedirs(os.path.join(root, "emptydir")) + os.symlink("hello.txt", os.path.join(root, "sym")) + os.symlink("dir/sub/data.bin", os.path.join(root, "dir/sublink")) + os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard")) + os.link(os.path.join(root, "hello.txt"), os.path.join(root, "dir/hard2")) + os.mkfifo(os.path.join(root, "fifo")) + for dirpath, dirs, fs in os.walk(root): + for n in dirs + fs: + os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False) + os.utime(root, (1650000000, 1650000000)) + names = sorted(subprocess.run(["find", "."], cwd=root, capture_output=True, check=True).stdout.decode().split("\n")[:-1]) + names = [n[2:] if n.startswith("./") else n for n in names] + + def expected(): + out = [] + for n in names: + st = os.lstat(os.path.join(root, n)) + t = TYPES[stat.S_IFMT(st.st_mode)] + e = {"name": n, "type": t, "mode": stat.S_IMODE(st.st_mode), "mtime": int(st.st_mtime), "nlink": st.st_nlink, + "size": st.st_size if t == "0" else 0} + if t == "2": + e["link"] = os.readlink(os.path.join(root, n)) + if t == "0": + with open(os.path.join(root, n), "rb") as f: + e["crc"] = zlib.crc32(f.read()) + out.append(e) + return out + + want = expected() + listing = "find . | LC_ALL=C sort | " + archives = [] + for fmt in ("newc", "crc", "odc", "bin"): + data = run(ctx, "cpio", listing + "cpio -o -H %s --reproducible 2>/dev/null" % fmt, root) + archives.append({"name": "gnu-" + fmt, "data": data, "format": fmt, "gnu": True, "entries": want}) + archives.append({"name": "gnu-binbe", "data": swap_bin(archives[3]["data"]), "format": "binbe", "entries": want}) + for fmt in ("newc", "odc"): + data = run(ctx, "libarchive", listing + "sed 's|^\\./||' | bsdtar --format=%s -n -cf - -T -" % fmt, root) + archives.append({"name": "bsdtar-" + fmt, "data": data, "format": fmt, "entries": want}) + gz = gzip.compress(archives[0]["data"], mtime=0) + finally: + shutil.rmtree(tmp) + devices = b"".join([ + newc(b"dev", 0o040755, nlink=2, ino=1), + newc(b"dev/null", 0o020666, rdev=(1, 3), ino=2), + newc(b"dev/sda", 0o060660, rdev=(8, 0), ino=3), + newc(b"dev/sock", 0o140755, ino=4), + newc(b"TRAILER!!!", 0, ino=0), + ]) + badcrc = newc(b"f", 0o100644, 3, b"abc", check=1, crc=True) + newc(b"TRAILER!!!", 0, ino=0, crc=True) + ctx.emit("cpio", {"archives": archives, "devices": devices, "badcrc": badcrc, "gz": gz})