From 197ddc561a5bae67cfd813c09e086d997ccd8ec8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:33:57 -0500 Subject: [PATCH] ws-arch2-unix: containers/Iso9660 (volume descriptors, directory records, multi-extent, Joliet, Rock Ridge SUSP / RRIP incl. CE, NM, PX, PN, TF, SL, CL / RE relocation, El Torito catalog) + archive/iso, tests vs xorriso / genisoimage images, the source tree and pycdlib --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/archive/iso/init.luau | 75 ++++ src/Formats/containers/Iso9660.luau | 525 ++++++++++++++++++++++++++++ tests/archive/iso.luau | 134 +++++++ tools/fixtures/iso.py | 195 +++++++++++ 6 files changed, 942 insertions(+) create mode 100644 src/Formats/archive/iso/init.luau create mode 100644 src/Formats/containers/Iso9660.luau create mode 100644 tests/archive/iso.luau create mode 100644 tools/fixtures/iso.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 31829c3..b1ce9d3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -55,6 +55,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | iso | .iso | yes | - | extensions: "joliet", "rockridge", "eltorito" | `tests/archive/iso.luau` | | archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.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 65e2173..e3f814e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -614,6 +614,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 = "rpm", category = "archive", diff --git a/src/Formats/archive/iso/init.luau b/src/Formats/archive/iso/init.luau new file mode 100644 index 0000000..0354aa4 --- /dev/null +++ b/src/Formats/archive/iso/init.luau @@ -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 diff --git a/src/Formats/containers/Iso9660.luau b/src/Formats/containers/Iso9660.luau new file mode 100644 index 0000000..c947ba2 --- /dev/null +++ b/src/Formats/containers/Iso9660.luau @@ -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 diff --git a/tests/archive/iso.luau b/tests/archive/iso.luau new file mode 100644 index 0000000..c961d9d --- /dev/null +++ b/tests/archive/iso.luau @@ -0,0 +1,134 @@ +-- archive/iso tests (and containers/Iso9660): xorriso images (plain names, Joliet, Rock Ridge, Joliet + Rock Ridge with +-- deep directories / a 200-byte name / a long symlink target) and a genisoimage -J -R image (rr_moved relocation, CE +-- areas) list what the source tree holds (Rock Ridge: names, modes, symlink targets, mtimes, data CRCs) or what pycdlib +-- reads (plain and Joliet names, sizes, data CRCs); prefer = "joliet" on a -J -R image; an El Torito boot catalog as +-- xorriso reports it; a crafted multi-extent file reads whole; an interleaved file is UNSUPPORTED; errors; the fuzz pass. +-- Fixtures: tools/fixtures/iso.py. +local T = require("@tests/T") +local F = require("@formats") +local Iso = require("@formats/archive/iso") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/iso") + +local t = T.suite("iso") +t:eq(Iso.name, "iso", "name") + +local function dataOf(c: any): string + return if c.same then Fx.images[c.same].data else c.data +end + +for _, c in Fx.images do + local a, err = Iso.decode(Bytes.reader(buffer.fromstring(dataOf(c))), { prefer = c.tree :: any }) + t:check(a, c.name .. ": " .. tostring(err)) + t:eq(a.meta.iso.tree, c.tree, c.name .. ": name set") + t:eq(F.detect(dataOf(c)), "iso", c.name .. ": F.detect") + local by = {} + for _, e in a:list() do + by[e.name] = e + end + t:eq(#a:list(), #c.entries, c.name .. ": entry count") + for _, w in c.entries do + local e = by[w.name] + t:check(e, c.name .. ": has " .. w.name) + t:eq(e.dir, w.dir, c.name .. ": " .. w.name .. " dir") + if w.mode then + t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode") + end + if w.link then + t:eq(e.type, "2", c.name .. ": " .. w.name .. " symlink") + t:eq(e.link, w.link, c.name .. ": " .. w.name .. " target") + end + if w.mtime and not w.dir then + t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime") + end + if w.crc then + t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size") + local b, rerr = a:read(w.name) + t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr)) + t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data") + end + end + t:note("%-24s %-9s %3d entries", c.name, c.tree, #c.entries) +end + +-- the default name set: Rock Ridge over Joliet; Joliet over plain +do + local jr = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[5].data))) + t:eq(jr.meta.iso.tree, "rockridge", "-J -R: Rock Ridge by default") + t:eq(jr.meta.iso.joliet, 3, "-J -R: Joliet level 3 seen") + t:check(jr.meta.iso.rockRidge, "-J -R: rockRidge") + local j = Iso.decode(Bytes.reader(buffer.fromstring(Fx.images[2].data))) + t:eq(j.meta.iso.tree, "joliet", "-J: Joliet by default") + local p = F.load(Fx.images[1].data) + t:eq(p.format, "iso", "F.load") + t:eq(p.meta.iso.tree, "iso9660", "plain") + t:check(p.meta.iso.blockSize == 2048 and p.meta.iso.blocks > 0, "volume facts") + -- any Archive converts: iso -> tar + local tar = F.load(assert(F.save(jr, nil, { format = "tar" }))) + t:eq(buffer.tostring(tar:read("hello.txt")), "hello, iso\n", "iso -> tar") +end + +-- El Torito +do + local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.boot.data))) + local bt = a.meta.boot + t:check(bt, "boot catalog") + t:eq(bt.catalog, Fx.boot.catalog, "boot: catalog LBA") + t:eq(bt.lba, Fx.boot.lba, "boot: image LBA") + t:eq(bt.sectors, Fx.boot.sectors, "boot: load size") + t:eq(bt.bootable, Fx.boot.bootable, "boot: bootable") + t:eq(bt.media, 0, "boot: no emulation") + t:check(bt.valid, "boot: validation entry checksum") +end + +-- multi-extent and interleaved records +do + local a = Iso.decode(Bytes.reader(buffer.fromstring(Fx.multi.data))) + local n = 0 + for _, e in a:list() do + if e.name == Fx.multi.name then + n += 1 + t:eq(e.size, Fx.multi.size, "multi-extent: size") + end + end + t:eq(n, 1, "multi-extent: one entry") + t:eq(Crc32.of(a:read(Fx.multi.name)), Fx.multi.crc, "multi-extent: data") + local il = Iso.decode(Bytes.reader(buffer.fromstring(Fx.interleaved))) + local _, e = il:read("HELLO.TXT") + t:check(e and e.code == Err.UNSUPPORTED, "interleaved: " .. tostring(e)) +end + +-- errors +do + local good = Fx.images[1].data + local _, e1 = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20000)))) + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local b = buffer.fromstring(good) + buffer.writeu8(b, 16 * 2048 + 1, 0x58) + local _, e2 = Iso.decode(Bytes.reader(b)) + t:check(e2 and e2.code == Err.CORRUPT, "bad descriptor: " .. tostring(e2)) + local cut = Iso.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 20 * 2048)))) + t:check(cut == nil or cut, "a cut image: no throw") + t:eq(Iso.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 40000)))), 0, "zeros are not an iso") +end + +-- fuzz: the volume descriptors and directories (the first 64 KB of a few images: their data lies further out) +local samples = {} +for i, c in Fx.images do + if c.data and (i == 1 or i == 3 or i == 5) then + table.insert(samples, string.sub(c.data, 1, 26 * 2048)) + end +end +t:fuzz("decode", function(b: buffer) + local a = Iso.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + end + return a +end, samples, { mutations = 40, keepHeader = 16 * 2048 }) + +t:done() diff --git a/tools/fixtures/iso.py b/tools/fixtures/iso.py new file mode 100644 index 0000000..036ed9c --- /dev/null +++ b/tools/fixtures/iso.py @@ -0,0 +1,195 @@ +# iso fixtures (tools/fixtures.py): ISO 9660 images of one tree built by xorriso (nixpkgs#xorriso: plain and Joliet +# with -rockridge off, then the mkisofs emulation -R, -J -R, an El Torito no-emulation boot image) and genisoimage (nixpkgs#cdrkit, -J -R: deep directories +# relocated to rr_moved, long names and symlink targets in CE continuation areas), plus a multi-extent file and an +# interleaved file crafted here by splitting / editing a directory record. Expected listings: the source tree (os.lstat) +# for Rock Ridge images, pycdlib (a second reader, run through nix python) for the plain and Joliet name sets. +# tests/gen/iso.luau { images = { { name, data (or same = the index of the image with the same data), tree, entries = { { name, dir, size?, crc?, mode?, link?, mtime? } } } }, +# boot = { data, lba, sectors, catalog }, multi = { data, name, size, crc }, interleaved = data } +import json, os, shutil, stat, struct, subprocess, tempfile, zlib + +MTIME = 1650000000 +DUMP = r""" +import json, sys, io, zlib, pycdlib +path, kind = sys.argv[1], sys.argv[2] +iso = pycdlib.PyCdlib() +iso.open(path) +out = [] +key = {"joliet": "joliet_path", "iso9660": "iso_path"}[kind] +for d, dirs, files in iso.walk(**{key: "/"}): + base = d.rstrip("/") + for n in dirs: + out.append({"name": (base + "/" + n).lstrip("/"), "dir": True}) + for n in files: + p = base + "/" + n + b = io.BytesIO() + iso.get_file_from_iso_fp(b, **{key: p}) + name = p.lstrip("/") + if ";" in name: + name = name[:name.rindex(";")] + if kind == "iso9660" and name.endswith("."): + name = name[:-1] + out.append({"name": name, "dir": False, "size": len(b.getvalue()), "crc": zlib.crc32(b.getvalue())}) +iso.close() +sys.stdout.write(json.dumps(out)) +""" + + +def sh(pkg, argv, cwd): + return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c"] + argv, cwd=cwd, capture_output=True, check=True).stdout + + +def tree_entries(root, skip_deep=False): + out = [] + for dirpath, dirs, files in os.walk(root): + dirs.sort() + for n in sorted(dirs + files): + p = os.path.join(dirpath, n) + rel = os.path.relpath(p, root) + st = os.lstat(p) + e = {"name": rel, "dir": stat.S_ISDIR(st.st_mode), "mode": stat.S_IMODE(st.st_mode), "mtime": MTIME} + if stat.S_ISLNK(st.st_mode): + e["link"] = os.readlink(p) + elif stat.S_ISREG(st.st_mode): + with open(p, "rb") as f: + d = f.read() + e["size"], e["crc"] = len(d), zlib.crc32(d) + out.append(e) + return out + + +def split_record(data, name, at_bytes): + """a multi-extent copy: the directory record of name split into two records (the first flagged 0x80)""" + img = bytearray(data) + root_lba = struct.unpack_from("I", a, 14, at_bytes) + a[25] |= 0x80 + struct.pack_into("I", b2, 6, lba + at_bytes // 2048) + struct.pack_into("I", b2, 14, size - at_bytes) + sector_end = (p // 2048 + 1) * 2048 + used = sector_end + q = p + ln + while q < sector_end and img[q] != 0: + q += img[q] + assert q + ln <= sector_end, "no room in the directory sector" + img[p:q + ln] = a + b2 + img[p + ln:q] + return bytes(img), size + p += ln + raise Exception("record not found") + + +def set_interleave(data, name): + img = bytearray(data) + root_lba = struct.unpack_from("