diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 09df9b9..4ce087a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -56,6 +56,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | | archive | d64 | .d64 .d71 .d81 | yes | yes | variants: "d64", "d71", "d81" | `tests/archive/d64.luau` | +| archive | fat | .img .ima .vfd .flp .fat | yes | yes | variants: "fat12", "fat16", "fat32" | `tests/archive/fat.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | | archive | macbinary | .bin .macbin | yes | yes | forks: true, variants: "I", "II", "III" | `tests/archive/macbinary.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 8afbe1f..b8d52ad 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -626,6 +626,18 @@ local list: { Entry } = { return require("@formats/archive/d64") end, }, + { + name = "fat", + category = "archive", + path = "archive/fat", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, + load = function() + return require("@formats/archive/fat") + end, + }, { name = "gzip", category = "archive", diff --git a/src/Formats/archive/fat/init.luau b/src/Formats/archive/fat/init.luau new file mode 100644 index 0000000..4815642 --- /dev/null +++ b/src/Formats/archive/fat/init.luau @@ -0,0 +1,124 @@ +--!strict +-- archive/fat: FAT12 / FAT16 / FAT32 disk images (floppy images, and hard-disk images with an MBR partition table: the +-- first FAT partition, or opts.partition) as an Archive, through containers/Fat: VFAT long names, NT lower-case 8.3 +-- names, directories (entries ending in "/"), file dates (DOS local time read as UTC), attributes (entry.attr) and the +-- 8.3 name (entry.shortName); files read lazily. meta.fat = 12 / 16 / 32, meta.label, meta.oem. Writes FAT12 floppy +-- images (1.44 MB by default; 360 / 720 / 1200 / 2880 KB with opts.size) from any Archive, with long names where a +-- name is not a plain 8.3 name; mtools and fsck.fat read them. Not supported: writing FAT16 / FAT32, exFAT, boot code. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Archive = require("@formats/containers/Archive") +local Fat = require("@formats/containers/Fat") + +-- ------------------------------------------------------------------------------------------------ contract +local FatFormat = { + name = "fat", + category = "archive", + extensions = { "img", "ima", "vfd", "flp", "fat" }, + mime = { "application/x-fat-image" }, + deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Fat" }, + caps = { decode = true, encode = true, variants = { "fat12", "fat16", "fat32" } }, +} + +export type DecodeOptions = { + partition: number?, -- MBR partition 1..4 (default: the first FAT partition, or the image itself) + maxEntries: number?, -- default 65536 +} +export type EncodeOptions = { + size: number?, -- floppy size in KB: 360 / 720 / 1200 / 1440 / 2880 (default 1440) + label: string?, -- volume label +} + +-- ------------------------------------------------------------------------------------------------ sniff +function FatFormat.sniff(r: Bytes.Reader): number + if r:remaining() < 512 then + return 0 + end + local v = Fat.open(r.buf, r.base + r.pos, r.limit - r.base - r.pos) + if not v then + return 0 + end + return if v.partition then 0.6 else 0.8 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encoder(a: any, o: any?): (buffer?, Err.Err?) + return FatFormat.encode(a, o) +end + +function FatFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local o: DecodeOptions = opts or {} + local v, err = Fat.open(r.buf, r.base, r.limit - r.base, { partition = o.partition }) + if not v then + return nil, Err.from(err) + end + local list, lerr = Fat.list(v, o.maxEntries) + if not list then + return nil, Err.from(lerr) + end + local a = Archive.new("fat", encoder) + for _, e in list do + local entry = e + Archive.put(a, { + name = e.name, + size = e.size, + dir = e.dir, + mtime = e.mtime, + attr = e.attr, + shortName = e.shortName, + method = "store", + load = if e.dir or e.size == 0 then nil else function(): (buffer?, Err.Err?) + local b, rerr = Fat.read(v :: Fat.Volume, entry) + if not b then + return nil, Err.from(rerr) + end + return b, nil + end, + }) + end + a.meta.fat = v.bits + a.meta.label = v.label + a.meta.oem = v.oem + a.meta.partition = v.partition + a.meta.source = { format = "fat", bits = v.bits, clusterSize = v.spc * v.bps } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function FatFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local files: { Fat.WriteFile } = {} + for _, it in items do + local e: any = it.entry + local data: buffer? = nil + if not e.dir then + local b, err = it.read() + if not b then + return nil, err + end + data = b + end + table.insert(files, { name = e.name, data = data, dir = e.dir, mtime = e.mtime }) + end + local img, err = Fat.write(files, { size = o.size, label = o.label }) + if not img then + return nil, if string.match(tostring(err), "^limit") then Err.from(err) else Err.new(Err.ARG, tostring(err)) + end + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new() -> an empty floppy: a:add("dir/file.txt", data, { mtime }); a:write({ size = 1440, label = "DISK" }) +function FatFormat.new(): any + local a = Archive.new("fat", encoder) + a.meta.source = { format = "fat" } + return a +end + +return FatFormat diff --git a/src/Formats/containers/Fat.luau b/src/Formats/containers/Fat.luau new file mode 100644 index 0000000..6e50631 --- /dev/null +++ b/src/Formats/containers/Fat.luau @@ -0,0 +1,747 @@ +--!strict +-- containers/Fat: the FAT file system (FAT12 / FAT16 / FAT32) over a byte range: the BPB, the FAT chains, directories +-- with VFAT long names (UCS-2, checksum-validated against their 8.3 entry) and the NT lower-case flags of 8.3 names, +-- and a FAT12 floppy writer (1.44 MB / 720 KB / 2.88 MB, long names when a name is not a plain 8.3 name). Disk images +-- with an MBR partition table open their first FAT partition (or the one asked for). New code, written from +-- Microsoft's "FAT: General Overview of On-Disk Format" (fatgen103) and the VFAT long-name layout. +-- +-- local vol, err = Fat.open(buf, offset, length, { partition = 1 }) -- Volume | nil, message +-- local list, err = Fat.list(vol, maxEntries) -- { Entry } (paths with "/", dirs end in "/") +-- local data, err = Fat.read(vol, entry) -- buffer | nil, message +-- local img, err = Fat.write(files, { size = 1440, label = "DISK" }) -- FAT12 floppy image +-- +-- DOS dates are local time without a zone: they are read and written as UTC. Never throws; every chain is bounded by +-- the cluster count (loops are errors). +local Fat = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 + +export type Volume = { + b: buffer, + base: number, -- byte offset of the volume (partition) in b + limit: number, + bps: number, -- bytes per sector + spc: number, -- sectors per cluster + fatOffset: number, -- byte offset of the first FAT (relative to base) + fatSize: number, -- bytes per FAT + rootOffset: number, -- FAT12 / 16: the fixed root directory + rootEntries: number, + rootCluster: number, -- FAT32 + dataOffset: number, -- byte offset of cluster 2 + clusters: number, -- data clusters + bits: number, -- 12 / 16 / 32 + label: string?, + oem: string, + media: number, + partition: number?, +} + +export type Entry = { + name: string, + dir: boolean, + size: number, + mtime: number?, + cluster: number, + attr: number, + shortName: string, +} + +-- ------------------------------------------------------------------------------------------------ open +local function bpbAt(b: buffer, o: number, len: number): (Volume?, string?) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + local jump = readu8(b, o) + local bps = readu16(b, o + 11) + local spc = readu8(b, o + 13) + if (jump ~= 0xEB and jump ~= 0xE9 and jump ~= 0xE8) or (bps ~= 512 and bps ~= 1024 and bps ~= 2048 and bps ~= 4096) then + return nil, "no FAT boot sector" + end + if spc == 0 or bit32.band(spc, spc - 1) ~= 0 then + return nil, "bad sectors per cluster" + end + local reserved, nfats, rootEntries = readu16(b, o + 14), readu8(b, o + 16), readu16(b, o + 17) + local total = readu16(b, o + 19) + if total == 0 then + total = readu32(b, o + 32) + end + local fatSectors = readu16(b, o + 22) + local fat32 = fatSectors == 0 + if fat32 then + fatSectors = readu32(b, o + 36) + end + if reserved == 0 or nfats == 0 or fatSectors == 0 or total == 0 then + return nil, "bad BPB" + end + local rootSectors = math.ceil(rootEntries * 32 / bps) + local dataSector = reserved + nfats * fatSectors + rootSectors + if dataSector >= total then + return nil, "bad BPB: no data area" + end + local clusters = (total - dataSector) // spc + local bits = if clusters < 4085 then 12 elseif clusters < 65525 then 16 else 32 + if fat32 and bits ~= 32 then + bits = 32 -- some small FAT32 volumes (mkfs.fat -F 32 on tiny images) are FAT32 regardless of the count + end + if total * bps > len then + -- images cut short at the last used sector are common: allow, reads past the end fail + total = len // bps + end + local labelAt = if bits == 32 then 71 else 43 + local sig = readu8(b, o + (if bits == 32 then 66 else 38)) + local label: string? = if sig == 0x29 then (string.gsub(buffer.readstring(b, o + labelAt, 11), " +$", "")) else nil + if label == "NO NAME" or label == "" then + label = nil + end + return { + b = b, + base = o, + limit = o + len, + bps = bps, + spc = spc, + fatOffset = reserved * bps, + fatSize = fatSectors * bps, + rootOffset = (reserved + nfats * fatSectors) * bps, + rootEntries = rootEntries, + rootCluster = if bits == 32 then readu32(b, o + 44) else 0, + dataOffset = dataSector * bps, + clusters = clusters, + bits = bits, + label = label, + oem = buffer.readstring(b, o + 3, 8), + media = readu8(b, o + 21), + }, nil +end + +export type OpenOptions = { partition: number? } -- 1..4: the MBR partition (default: the first FAT one) + +local FAT_TYPES = { [0x01] = true, [0x04] = true, [0x06] = true, [0x0B] = true, [0x0C] = true, [0x0E] = true, [0x11] = true, [0x14] = true, [0x16] = true, [0x1B] = true, [0x1C] = true, [0x1E] = true } + +function Fat.open(b: buffer, off: number, len: number, opts: OpenOptions?): (Volume?, string?) + local o: OpenOptions = opts or {} + off = math.max(0, off) + len = math.min(len, buffer.len(b) - off) + if len < 512 then + return nil, "truncated: smaller than a boot sector" + end + if not o.partition then + local v = bpbAt(b, off, len) + if v then + return v, nil + end + end + -- an MBR: 0x55AA and four partition entries + if readu8(b, off + 510) ~= 0x55 or readu8(b, off + 511) ~= 0xAA then + return nil, "no FAT boot sector and no partition table" + end + for i = 1, 4 do + local e = off + 446 + (i - 1) * 16 + local ptype = readu8(b, e + 4) + local lba, count = readu32(b, e + 8), readu32(b, e + 12) + if (o.partition == i or (not o.partition and FAT_TYPES[ptype])) and ptype ~= 0 then + if lba * 512 >= len then + return nil, "truncated: partition " .. i .. " starts past the end" + end + local v, err = bpbAt(b, off + lba * 512, math.min(count * 512, len - lba * 512)) + if v then + v.partition = i + end + return v, err + end + end + return nil, if o.partition then "no partition " .. o.partition else "no FAT partition" +end + +-- ------------------------------------------------------------------------------------------------ chains +local function nextCluster(v: Volume, c: number): number + local f = v.base + v.fatOffset + if v.bits == 12 then + local p = f + c + c // 2 + if p + 1 >= v.limit then + return 0xFFFFFFF + end + local w = readu16(v.b, p) + local n = if c % 2 == 0 then bit32.band(w, 0xFFF) else bit32.rshift(w, 4) + return if n >= 0xFF8 then 0xFFFFFFF elseif n == 0xFF7 then 0xFFFFFF7 else n + elseif v.bits == 16 then + local p = f + c * 2 + if p + 2 > v.limit then + return 0xFFFFFFF + end + local n = readu16(v.b, p) + return if n >= 0xFFF8 then 0xFFFFFFF elseif n == 0xFFF7 then 0xFFFFFF7 else n + end + local p = f + c * 4 + if p + 4 > v.limit then + return 0xFFFFFFF + end + return bit32.band(readu32(v.b, p), 0x0FFFFFFF) +end + +-- the clusters of a chain (nil, message when it leaves the volume or loops) +local function chainOf(v: Volume, first: number, maxClusters: number): ({ number }?, string?) + local out = {} + local c = first + while c >= 2 and c < 0xFFFFFF7 do + if c >= v.clusters + 2 then + return nil, "cluster " .. c .. " outside the volume" + end + table.insert(out, c) + if #out > maxClusters then + return nil, "cluster chain loops" + end + c = nextCluster(v, c) + end + if c == 0xFFFFFF7 then + return nil, "bad cluster in a chain" + end + return out, nil +end + +local function clusterOffset(v: Volume, c: number): number + return v.base + v.dataOffset + (c - 2) * v.spc * v.bps +end + +-- the bytes of a chain, up to size bytes (nil = the whole chain) +local function readChain(v: Volume, first: number, size: number?): (buffer?, string?) + local csize = v.spc * v.bps + local maxClusters = if size then math.ceil(size / csize) + 1 else v.clusters + local list, err = chainOf(v, first, math.min(maxClusters, v.clusters + 1)) + if not list then + return nil, err + end + local total = if size then size else #list * csize + if #list * csize < total then + return nil, "file data ends early (chain of " .. #list .. " clusters for " .. total .. " bytes)" + end + local out = buffer.create(total) + local o = 0 + for _, c in list do + local n = math.min(csize, total - o) + if n <= 0 then + break + end + local at = clusterOffset(v, c) + if at + n > v.limit then + return nil, "truncated: cluster " .. c .. " past the end of the image" + end + buffer.copy(out, o, v.b, at, n) + o += n + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ directories +local function dosTime(date: number, time: number): number? + if date == 0 then + return nil + end + local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31) + local hh, mm, ss = bit32.rshift(time, 11), bit32.band(bit32.rshift(time, 5), 63), bit32.band(time, 31) * 2 + if m < 1 or m > 12 or d < 1 then + return nil + end + -- days from civil (Howard Hinnant's algorithm) + local yy = if m <= 2 then y - 1 else y + local era = yy // 400 + local yoe = yy - era * 400 + local doy = (153 * (if m > 2 then m - 3 else m + 9) + 2) // 5 + d - 1 + local doe = yoe * 365 + yoe // 4 - yoe // 100 + doy + local days = era * 146097 + doe - 719468 + return days * 86400 + hh * 3600 + mm * 60 + ss +end + +local function latin1(s: string): string + if not string.find(s, "[\128-\255]") then + return s + end + local out = table.create(#s) + for i = 1, #s do + out[i] = utf8.char(string.byte(s, i)) + end + return table.concat(out) +end + +local function shortChecksum(raw: string): number + local sum = 0 + for i = 1, 11 do + sum = (bit32.rshift(sum, 1) + bit32.lshift(bit32.band(sum, 1), 7) + string.byte(raw, i)) % 256 + end + return sum +end + +local function ucs2(b: buffer, o: number, n: number, out: { number }) + for k = 0, n - 1 do + table.insert(out, readu16(b, o + k * 2)) + end +end + +-- the entries of one directory's bytes +local function parseDir(d: buffer, prefix: string, out: { Entry }): { Entry } + local lfn: { [number]: { number } } = {} + local lfnSum, lfnCount = -1, 0 + local subdirs = {} + for p = 0, buffer.len(d) - 32, 32 do + local first = readu8(d, p) + if first == 0 then + break + end + local attr = readu8(d, p + 11) + if first == 0xE5 then + lfn, lfnSum, lfnCount = {}, -1, 0 + elseif attr == 0x0F then + local seq = bit32.band(first, 0x3F) + if bit32.band(first, 0x40) ~= 0 then + lfn, lfnCount = {}, seq + lfnSum = readu8(d, p + 13) + end + if seq >= 1 and seq <= 20 and readu8(d, p + 13) == lfnSum then + local chars = {} + ucs2(d, p + 1, 5, chars) + ucs2(d, p + 14, 6, chars) + ucs2(d, p + 28, 2, chars) + lfn[seq] = chars + end + else + local raw = buffer.readstring(d, p, 11) + if first == 0x05 then + raw = "\229" .. string.sub(raw, 2) + end + local long: string? = nil + if lfnCount > 0 and lfnSum == shortChecksum(buffer.readstring(d, p, 11)) then + local cps = {} + local complete = true + for s = 1, lfnCount do + if not lfn[s] then + complete = false + break + end + for _, c in lfn[s] do + if c == 0 or c == 0xFFFF then + break + end + table.insert(cps, c) + end + end + if complete then + local parts = table.create(#cps) + for i, c in cps do + parts[i] = utf8.char(if c >= 0xD800 and c < 0xE000 then 0xFFFD else c) + end + long = table.concat(parts) + end + end + lfn, lfnSum, lfnCount = {}, -1, 0 + local nt = readu8(d, p + 12) + local base = string.gsub(string.sub(raw, 1, 8), " +$", "") + local ext = string.gsub(string.sub(raw, 9, 11), " +$", "") + if bit32.band(nt, 0x08) ~= 0 then + base = string.lower(base) + end + if bit32.band(nt, 0x10) ~= 0 then + ext = string.lower(ext) + end + local short = latin1(if ext ~= "" then base .. "." .. ext else base) + local isDir = bit32.band(attr, 0x10) ~= 0 + local isLabel = bit32.band(attr, 0x08) ~= 0 + if not isLabel and short ~= "." and short ~= ".." then + local name = prefix .. (long or short) + local cluster = readu16(d, p + 26) + readu16(d, p + 20) * 65536 + local e: Entry = { + name = if isDir then name .. "/" else name, + dir = isDir, + size = if isDir then 0 else readu32(d, p + 28), + mtime = dosTime(readu16(d, p + 24), readu16(d, p + 22)), + cluster = cluster, + attr = attr, + shortName = short, + } + table.insert(out, e) + if isDir then + table.insert(subdirs, e) + end + end + end + end + return subdirs +end + +-- list(vol, maxEntries?) -> every file and directory (depth first, directories before their contents) +function Fat.list(v: Volume, maxEntries: number?): ({ Entry }?, string?) + local out: { Entry } = {} + local limit = maxEntries or 65536 + local root: buffer?, err: string? + if v.bits == 32 then + root, err = readChain(v, v.rootCluster, nil) + else + local n = v.rootEntries * 32 + if v.base + v.rootOffset + n > v.limit then + return nil, "truncated: root directory past the end" + end + root = buffer.create(n) + buffer.copy(root :: buffer, 0, v.b, v.base + v.rootOffset, n) + end + if not root then + return nil, err + end + local seen: { [number]: boolean } = {} + local function walk(d: buffer, prefix: string, depth: number): string? + if depth > 64 then + return "directories nested too deep" + end + local start = #out + local subdirs = parseDir(d, prefix, out) + if #out > limit then + return "limit: more than maxEntries entries" + end + local _ = start + for _, s in subdirs do + if s.cluster >= 2 then + if seen[s.cluster] then + return "directory loop at cluster " .. s.cluster + end + seen[s.cluster] = true + local sd, serr = readChain(v, s.cluster, nil) + if not sd then + return s.name .. ": " .. tostring(serr) + end + local werr = walk(sd, s.name, depth + 1) + if werr then + return werr + end + end + end + return nil + end + local werr = walk(root :: buffer, "", 0) + if werr then + return nil, werr + end + return out, nil +end + +-- read(vol, entry) -> the file's bytes +function Fat.read(v: Volume, e: Entry): (buffer?, string?) + if e.dir or e.size == 0 then + return buffer.create(0), nil + end + if e.cluster < 2 then + return nil, "file without clusters" + end + return readChain(v, e.cluster, e.size) +end + +-- ------------------------------------------------------------------------------------------------ write +export type WriteFile = { name: string, data: buffer?, dir: boolean?, mtime: number? } +export type WriteOptions = { + size: number?, -- 360 / 720 / 1200 / 1440 / 2880 KB (default 1440) + label: string?, -- volume label (default none) + serial: number?, -- volume serial number (default 0x12345678) +} + +local GEOMETRY = { + [360] = { sectors = 720, spc = 2, root = 112, media = 0xFD, fat = 2, spt = 9, heads = 2 }, + [720] = { sectors = 1440, spc = 2, root = 112, media = 0xF9, fat = 3, spt = 9, heads = 2 }, + [1200] = { sectors = 2400, spc = 1, root = 224, media = 0xF9, fat = 7, spt = 15, heads = 2 }, + [1440] = { sectors = 2880, spc = 1, root = 224, media = 0xF0, fat = 9, spt = 18, heads = 2 }, + [2880] = { sectors = 5760, spc = 2, root = 240, media = 0xF0, fat = 9, spt = 36, heads = 2 }, +} + +local VALID83 = "^[%w!#%$%%&'%(%)%-@%^_`{}~]+$" + +local function toDos(t: number?): (number, number) + local s = math.floor(t or 315532800) + if s < 315532800 then + s = 315532800 -- 1980-01-01 + end + local days = s // 86400 + local rem = s - days * 86400 + -- civil from days (Howard Hinnant) + local z = days + 719468 + local era = z // 146097 + local doe = z - era * 146097 + local yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365 + local y = yoe + era * 400 + local doy = doe - (365 * yoe + yoe // 4 - yoe // 100) + local mp = (5 * doy + 2) // 153 + local d = doy - (153 * mp + 2) // 5 + 1 + local m = if mp < 10 then mp + 3 else mp - 9 + if m <= 2 then + y += 1 + end + if y > 2107 then + y, m, d = 2107, 12, 31 + end + local date = bit32.bor(bit32.lshift(y - 1980, 9), bit32.lshift(m, 5), d) + local time = bit32.bor(bit32.lshift(rem // 3600, 11), bit32.lshift((rem // 60) % 60, 5), (rem % 60) // 2) + return date, time +end + +type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number } + +-- the 11-byte short name and NT flags for a long name, unique within used; and whether a long name entry is needed +local function shortName(name: string, used: { [string]: boolean }): (string, number, boolean) + local base, ext = string.match(name, "^(.*)%.([^%.]*)$") + if not base or base == "" then + base, ext = name, "" + end + local b, e = base :: string, ext :: string + -- a plain 8.3 name, all upper or all lower case per part: no long name needed + if #b <= 8 and #e <= 3 and string.match(b, VALID83) and (e == "" or string.match(e, VALID83)) then + local bu, eu = string.upper(b), string.upper(e) + local nt = 0 + local ok = true + if b ~= bu then + if b == string.lower(b) then + nt = bit32.bor(nt, 0x08) + else + ok = false + end + end + if e ~= eu then + if e == string.lower(e) then + nt = bit32.bor(nt, 0x10) + else + ok = false + end + end + local raw = bu .. string.rep(" ", 8 - #bu) .. eu .. string.rep(" ", 3 - #eu) + if ok and not used[raw] then + used[raw] = true + return raw, nt, false + end + end + local function clean(s: string): string + s = string.upper((string.gsub(s, "[%s%.]", ""))) + return (string.gsub(s, "[^%w!#%$%%&'%(%)%-@%^_`{}~]", "_")) + end + local cb, ce = clean(b), string.sub(clean(e), 1, 3) + if cb == "" then + cb = "_" + end + for n = 1, 999999 do + local tail = "~" .. n + local raw = string.sub(cb, 1, 8 - #tail) .. tail + raw = raw .. string.rep(" ", 8 - #raw) .. ce .. string.rep(" ", 3 - #ce) + if not used[raw] then + used[raw] = true + return raw, 0, true + end + end + return " ___", 0, true +end + +-- the directory entries (32 bytes each) of a node's children +local function dirEntries(n: Node, parentCluster: number, isRoot: boolean, label: string?): buffer + local w = {} + local function entry(raw: string, attr: number, nt: number, cluster: number, size: number, mtime: number?) + local e = buffer.create(32) + buffer.writestring(e, 0, raw) + buffer.writeu8(e, 11, attr) + buffer.writeu8(e, 12, nt) + local date, time = toDos(mtime) + buffer.writeu16(e, 14, time) + buffer.writeu16(e, 16, date) + buffer.writeu16(e, 18, date) + buffer.writeu16(e, 22, time) + buffer.writeu16(e, 24, date) + buffer.writeu16(e, 26, cluster) + buffer.writeu32(e, 28, size) + table.insert(w, e) + end + if isRoot and label then + local l = string.sub(string.upper(label), 1, 11) + entry(l .. string.rep(" ", 11 - #l), 0x08, 0, 0, 0, n.mtime) + end + if not isRoot then + entry(". ", 0x10, 0, n.cluster, 0, n.mtime) + entry(".. ", 0x10, 0, parentCluster, 0, n.mtime) + end + local used: { [string]: boolean } = {} + for _, c in n.children do + local raw, nt, needLong = shortName(c.name, used) + if needLong then + local cps = {} + if utf8.len(c.name) then + for _, cp in utf8.codes(c.name) do + table.insert(cps, if cp > 0xFFFF then 0x5F else cp) + end + else + for i = 1, #c.name do + table.insert(cps, (string.byte(c.name, i))) + end + end + local count = math.ceil(#cps / 13) + local sum = shortChecksum(raw) + for s = count, 1, -1 do + local e = buffer.create(32) + buffer.writeu8(e, 0, if s == count then bit32.bor(s, 0x40) else s) + buffer.writeu8(e, 11, 0x0F) + buffer.writeu8(e, 13, sum) + local slots = { 1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30 } + for k = 1, 13 do + local i = (s - 1) * 13 + k + local v = if i <= #cps then cps[i] elseif i == #cps + 1 then 0 else 0xFFFF + buffer.writeu16(e, slots[k], v) + end + table.insert(w, e) + end + end + entry(raw, if c.dir then 0x10 else 0x20, nt, c.cluster, if c.dir then 0 else buffer.len(c.data or buffer.create(0)), c.mtime) + end + local out = buffer.create(#w * 32) + for i, e in w do + buffer.copy(out, (i - 1) * 32, e) + end + return out +end + +-- write(files, opts?) -> a FAT12 floppy image holding the files (directories created from the paths) +function Fat.write(files: { WriteFile }, opts: WriteOptions?): (buffer?, string?) + local o: WriteOptions = opts or {} + local g = GEOMETRY[o.size or 1440] + if not g then + return nil, "size must be 360, 720, 1200, 1440 or 2880" + end + local bps = 512 + local root: Node = { name = "", dir = true, children = {}, byName = {}, cluster = 0 } + local function node(path: string, isDir: boolean): (Node?, string?) + local cur = root + local parts = string.split(path, "/") + for i, p in parts do + if p ~= "" and p ~= "." then + if p == ".." then + return nil, "'..' in a path" + end + local last = i == #parts or (i == #parts - 1 and parts[#parts] == "") + local child: Node? = cur.byName[string.lower(p)] + if not child then + local nc: Node = { name = p, dir = isDir or not last, children = {}, byName = {}, cluster = 0 } + cur.byName[string.lower(p)] = nc + table.insert(cur.children, nc) + child = nc + elseif not child.dir and (not last or isDir) then + return nil, p .. " is both a file and a directory" + end + cur = child :: Node + end + end + return cur, nil + end + for _, f in files do + local n, err = node(f.name, f.dir == true) + if not n then + return nil, err + end + if n ~= root then + n.mtime = f.mtime + if not n.dir then + n.data = f.data or buffer.create(0) + end + end + end + local csize = g.spc * bps + local dataSector = 1 + 2 * g.fat + g.root * 32 // bps + local clusters = (g.sectors - dataSector) // g.spc + local img = buffer.create(g.sectors * bps) + local fat = buffer.create(g.fat * bps) + local nextFree = 2 + local function setFat(c: number, v: number) + local p = c + c // 2 + local w = buffer.readu16(fat, p) + if c % 2 == 0 then + w = bit32.bor(bit32.band(w, 0xF000), v) + else + w = bit32.bor(bit32.band(w, 0x000F), bit32.lshift(v, 4)) + end + buffer.writeu16(fat, p, w) + end + local function alloc(bytes: number): number? + local n = math.max(1, math.ceil(bytes / csize)) + if nextFree + n - 1 > clusters + 1 then + return nil + end + local first = nextFree + for k = 0, n - 1 do + setFat(first + k, if k == n - 1 then 0xFFF else first + k + 1) + end + nextFree += n + return first + end + -- clusters: files get theirs first; a directory's size depends on its entries (long names), so measure first + local function place(n: Node): string? + for _, c in n.children do + if c.dir then + local size = buffer.len(dirEntries(c, 0, false, nil)) + local cl = alloc(size) + if not cl then + return "disk full" + end + c.cluster = cl + local err = place(c) + if err then + return err + end + elseif c.data and buffer.len(c.data) > 0 then + local cl = alloc(buffer.len(c.data)) + if not cl then + return "disk full" + end + c.cluster = cl + local at = (dataSector + (cl - 2) * g.spc) * bps + buffer.copy(img, at, c.data) + end + end + return nil + end + local perr = place(root) + if perr then + return nil, "limit: " .. perr + end + local function writeDirs(n: Node, parent: number): string? + for _, c in n.children do + if c.dir then + local d = dirEntries(c, parent, false, nil) + buffer.copy(img, (dataSector + (c.cluster - 2) * g.spc) * bps, d) + local err = writeDirs(c, c.cluster) + if err then + return err + end + end + end + return nil + end + writeDirs(root, 0) + local rootDir = dirEntries(root, 0, true, o.label) + if buffer.len(rootDir) > g.root * 32 then + return nil, "limit: too many entries in the root directory" + end + buffer.copy(img, (1 + 2 * g.fat) * bps, rootDir) + setFat(0, 0xF00 + g.media) + setFat(1, 0xFFF) + buffer.copy(img, bps, fat) + buffer.copy(img, (1 + g.fat) * bps, fat) + -- boot sector + buffer.writestring(img, 0, "\235\60\144" .. "FMTSLUAU") + buffer.writeu16(img, 11, bps) + buffer.writeu8(img, 13, g.spc) + buffer.writeu16(img, 14, 1) + buffer.writeu8(img, 16, 2) + buffer.writeu16(img, 17, g.root) + buffer.writeu16(img, 19, g.sectors) + buffer.writeu8(img, 21, g.media) + buffer.writeu16(img, 22, g.fat) + buffer.writeu16(img, 24, g.spt) + buffer.writeu16(img, 26, g.heads) + buffer.writeu8(img, 36, 0) + buffer.writeu8(img, 38, 0x29) + buffer.writeu32(img, 39, o.serial or 0x12345678) + local label = string.upper(string.sub(o.label or "NO NAME", 1, 11)) + buffer.writestring(img, 43, label .. string.rep(" ", 11 - #label) .. "FAT12 ") + buffer.writestring(img, 62, "\244\235\253") -- hlt; jmp $ (no boot code) + buffer.writeu8(img, 510, 0x55) + buffer.writeu8(img, 511, 0xAA) + return img, nil +end + +return Fat diff --git a/tests/archive/fat.luau b/tests/archive/fat.luau new file mode 100644 index 0000000..277a15b --- /dev/null +++ b/tests/archive/fat.luau @@ -0,0 +1,84 @@ +-- archive/fat tests (and containers/Fat): FAT12 (1.44 MB, 720 KB) / FAT16 / FAT32 images by mkfs.fat filled by mtools +-- (long names over several entries, lower-case 8.3, non-ASCII names, nested directories, empty and many-cluster files) +-- and a hard-disk image with an MBR partition list what mtools extracts (names, sizes, data CRCs, dates as UTC, +-- directories), FAT width and label; our floppies pass fsck.fat -n and extract with mtools (fixture step) and +-- round-trip; errors; the fuzz pass. Fixtures: tools/fixtures/fat.py (images gzip-compressed). +local T = require("@tests/T") +local F = require("@formats") +local FatF = require("@formats/archive/fat") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Deflate = require("@formats/codecs/compress/Deflate") +local E = require("@tests/archive/_entries") +local Fx = require("@tests/gen/fat") + +local t = T.suite("fat") +t:eq(FatF.name, "fat", "name") + +local samples = {} +for _, c in Fx.cases do + local gz = buffer.fromstring(c.gz) + local data = Deflate.gunzip(gz, 0, buffer.len(gz)) :: buffer + local a, err = FatF.decode(Bytes.reader(data)) + t:check(a, c.name .. ": " .. tostring(err)) + if a then + E.check(t, a, c.entries, c.name) + t:eq(a.meta.fat, c.bits, c.name .. ": bits") + t:eq(a.meta.label, c.label, c.name .. ": label") + end + t:eq(F.detect(data), "fat", c.name .. ": detect") + if c.name == "fat12 720K" then + table.insert(samples, data) + end +end +for _, o in Fx.ours do + t:check(o.ok, "mtools extracts our " .. o.size .. " KB floppy") + t:check(not string.find(o.fsck, "rror") and string.find(o.fsck, " files, ", 1, true) ~= nil and select(2, string.gsub(o.fsck, "\n", "")) == 2, "fsck.fat -n is clean: " .. o.fsck) +end +for _, size in { 1440, 720, 360, 2880 } do + E.roundTrip(t, FatF, { size = size }, "round trip " .. size) +end +-- long and short names, directories, dates +local a = FatF.new() +a:add("Some Long Name.html", "a", { mtime = 1700000000 }) +a:add("dir/UPPER.TXT", "b", { mtime = 1700000002 }) +a:add("dir/lower.txt", "c") +a:add("dir/Same Prefix 1.txt", "d") +a:add("dir/Same Prefix 2.txt", "e") +a:add("empty dir/", "", { dir = true }) +local back = FatF.decode(Bytes.reader(a:write({ label = "Test" }) :: buffer)) :: any +t:check(back, "names round trip decodes") +for _, n in { "Some Long Name.html", "dir/UPPER.TXT", "dir/lower.txt", "dir/Same Prefix 1.txt", "dir/Same Prefix 2.txt", "empty dir/", "dir/" } do + t:check(back._byName[n], "names round trip: " .. n) +end +t:eq(back._byName["dir/UPPER.TXT"].mtime, 1700000002, "dos time") +t:eq(back._byName["dir/Same Prefix 2.txt"].shortName, "SAMEPR~2.TXT", "numeric tail") +t:eq(back.meta.label, "TEST", "label") + +-- errors +local function code(b: buffer): string? + local _, e = FatF.decode(Bytes.reader(b)) + return e and e.code +end +t:eq(code(buffer.create(100)), Err.TRUNCATED, "short") +t:eq(code(buffer.create(4096)), Err.CORRUPT, "no boot sector") +local big = FatF.new() +big:add("big", buffer.create(2000000)) +t:eq((select(2, big:write()) :: any).code, Err.LIMIT, "disk full") +local clash = FatF.new() +clash:add("x", "file") +clash:add("x/y", "under a file") +t:eq((select(2, clash:write()) :: any).code, Err.ARG, "file and directory clash") +t:eq((select(2, FatF.encode(FatF.new(), { size = 999 })) :: any).code, Err.ARG, "bad size") + +-- fuzz: the boot sector, FAT and directories are in the first 16 KB +t:fuzz("decode", function(b: buffer) + local r = FatF.decode(Bytes.reader(b)) + if r then + for _, e in r:list() do + r:read(e.name) + end + end + return r +end, samples, { mutations = 200, garbage = 20, seed = 5 }) +t:done() diff --git a/tools/fixtures/fat.py b/tools/fixtures/fat.py new file mode 100644 index 0000000..d32177e --- /dev/null +++ b/tools/fixtures/fat.py @@ -0,0 +1,75 @@ +# FAT disk image fixtures (tools/fixtures.py): FAT12 / FAT16 / FAT32 images made by dosfstools' `mkfs.fat` and filled +# by mtools' `mcopy -s` (long names, lower-case 8.3 names, non-ASCII names, nested directories, an empty file, files +# over many clusters), a hard-disk image with an MBR and a FAT16 partition (mkfs.fat --offset); the reference listing +# is the tree mtools extracts again (`mcopy -s`), dates under TZ=UTC. Our writer's floppies (tools/fixtures/ +# _arch2_ours.luau) are checked by `fsck.fat -n` and extracted by mtools. Images are emitted gzip-compressed. +# tests/gen/fat.luau { cases = { { name, gz, bits, label?, entries = { { name, size?, crc?, dir?, mtime? } } } }, +# ours = { { size, ok, fsck } } } +import gzip, importlib.util, os, shutil, struct, zlib + +_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py")) +A = importlib.util.module_from_spec(_s) +_s.loader.exec_module(A) + +INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/containers/Fat.luau", "src/Formats/archive/fat"] +PKGS = ["dosfstools", "mtools"] + + +def extract(img, out, tmp): + os.makedirs(out, exist_ok=True) + A.tool(PKGS, ["mcopy", "-s", "-n", "-m", "-i", img, "::/*", out + "/"], cwd=tmp) + return A.read_tree(out) + + +def generate(ctx): + os.environ["TZ"] = "UTC" + os.environ["MTOOLS_SKIP_CHECK"] = "1" + rng = ctx.rng(12) + tree = [("README.TXT", b"upper 8.3\n"), ("lower.txt", b"lower case 8.3\n"), ("Mixed Case Long Name.text", b"long\n"), + ("docs/a very long file name that spans several entries.md", b"x" * 3000), ("docs/sub/deep/leaf.bin", rng.randbytes(20000)), + ("empty.dat", b""), ("naïve café 日本.txt", "unicode".encode()), ("big.bin", rng.randbytes(150000))] + tmp = A.tmpdir() + try: + src = os.path.join(tmp, "src") + A.tree(tree, src) + dirs = {"docs/", "docs/sub/", "docs/sub/deep/"} + cases = [] + for bits, kb, label in ((12, 1440, "FLOPPY"), (12, 720, None), (16, 16384, "SIXTEEN"), (32, 40960, "THIRTYTWO")): + img = os.path.join(tmp, "t%d-%d.img" % (bits, kb)) + argv = ["mkfs.fat", "-C", "-F", str(bits)] + (["-n", label] if label else []) + [img, str(kb)] + A.tool(PKGS, argv, cwd=tmp) + items = [os.path.join(src, n) for n in os.listdir(src)] + A.tool(PKGS, ["mcopy", "-s", "-m", "-i", img] + items + ["::/"], cwd=tmp) + got = extract(img, os.path.join(tmp, "x%d-%d" % (bits, kb)), tmp) + ents = [{"name": d, "dir": True} for d in sorted(dirs)] + for n, d in tree: + assert got.get(n) == zlib.crc32(d), (img, n) + ents.append({"name": n, "size": len(d), "crc": zlib.crc32(d), "mtime": A.MTIME}) + e = {"name": "fat%d %dK" % (bits, kb), "gz": gzip.compress(open(img, "rb").read(), mtime=0), "bits": bits, "entries": ents} + if label: + e["label"] = label + cases.append(e) + # a hard-disk image: MBR + a FAT16 partition at sector 2048 + img = os.path.join(tmp, "hd.img") + A.tool(PKGS, ["mkfs.fat", "-C", "-F", "16", "--offset", "2048", "-n", "PART1", img, str(8192 + 1024)], cwd=tmp) + with open(img, "r+b") as f: + mbr = bytearray(512) + mbr[446:462] = struct.pack("