--!strict -- containers/Fat: FAT12 / FAT16 / FAT32 over a byte range (BPB, chains, VFAT long names checksum-validated against -- their 8.3 entry, NT lower-case flags; an MBR's first FAT partition) and a FAT12 floppy writer. New code, from -- Microsoft's fatgen103 and the VFAT long-name layout. -- 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 Archive = require("@rosetta/containers/Archive") 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, } 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 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 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 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 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 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 = Archive.fromDos(readu16(d, p + 24) * 65536 + 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 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 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 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 v = Archive.toDos(t) return v // 65536, v % 65536 end type Node = { name: string, data: buffer?, dir: boolean, mtime: number?, children: { Node }, byName: { [string]: Node }, cluster: number } 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 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 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) 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