blob: e0d460fef4a17a3d0fbe70f33c7daa81c894dd14 [file] [log] [blame]
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +00001// Package fat32 implements a writer for the FAT32 filesystem.
2package fat32
3
4import (
5 "crypto/rand"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "io"
10 "io/fs"
11 "math"
12 "math/bits"
13 "strings"
14 "time"
15 "unicode/utf16"
16)
17
18// This package contains multiple references to the FAT32 specification, called
19// Microsoft Extensible Firmware Initiative FAT32 File System Specification
20// version 1.03 (just called the spec from now on). You can get it at
21// https://download.microsoft.com/download/0/8/4/\
22// 084c452b-b772-4fe5-89bb-a0cbf082286a/fatgen103.doc
23
24type Options struct {
25 // Size of a logical block on the block device. Needs to be a power of two
26 // equal or bigger than 512. If left at zero, defaults to 512.
27 BlockSize uint16
28
29 // Number of blocks the filesystem should span. If zero, it will be exactly
30 // as large as it needs to be.
31 BlockCount uint32
32
33 // Human-readable filesystem label. Maximum 10 bytes (gets cut off), should
34 // be uppercase alphanumeric.
35 Label string
36
37 // Filesystem identifier. If unset (i.e. left at zero) a random value will
38 // be assigned by WriteFS.
39 ID uint32
40}
41
42// SizedReader is an io.Reader with a known size
43type SizedReader interface {
44 io.Reader
45 Size() int64
46}
47
48// Attribute is a bitset of flags set on an inode.
49// See also the spec page 24
50type Attribute uint8
51
52const (
53 // AttrReadOnly marks a file as read-only
54 AttrReadOnly Attribute = 0x01
55 // AttrHidden indicates that directory listings should not show this file.
56 AttrHidden Attribute = 0x02
57 // AttrSystem indicates that this is an operating system file.
58 AttrSystem Attribute = 0x04
59 // AttrDirectory indicates that this is a directory and not a file.
60 AttrDirectory Attribute = 0x10
61 // AttrArchive canonically indicates that a file has been created/modified
62 // since the last backup. Its use in practice is inconsistent.
63 AttrArchive Attribute = 0x20
64)
65
66// Inode is file or directory on the FAT32 filesystem. Note that the concept
67// of an inode doesn't really exist on FAT32, its directories are just special
68// files.
69type Inode struct {
70 // Name of the file or directory (not including its path)
71 Name string
72 // Time the file or directory was last modified
73 ModTime time.Time
74 // Time the file or directory was created
75 CreateTime time.Time
76 // Attributes
77 Attrs Attribute
78 // Children of this directory (only valid when Attrs has AttrDirectory set)
79 Children []*Inode
80 // Content of this file
81 // Only valid when Attrs doesn't have AttrDirectory set.
82 Content SizedReader
83
84 // Filled out on placement and write-out
85 startCluster int
86 parent *Inode
87 dosName [11]byte
88}
89
90// Number of LFN entries + normal entry (all 32 bytes)
91func (i Inode) metaSize() (int64, error) {
92 fileNameUTF16 := utf16.Encode([]rune(i.Name))
93 // VFAT file names are null-terminated
94 fileNameUTF16 = append(fileNameUTF16, 0x00)
95 if len(fileNameUTF16) > 255 {
96 return 0, errors.New("file name too long, maximum is 255 UTF-16 code points")
97 }
98
99 // ⌈len(fileNameUTF16)/codepointsPerEntry⌉
100 numEntries := (len(fileNameUTF16) + codepointsPerEntry - 1) / codepointsPerEntry
101 return (int64(numEntries) + 1) * 32, nil
102}
103
104func lfnChecksum(dosName [11]byte) uint8 {
105 var sum uint8
106 for _, b := range dosName {
107 sum = ((sum & 1) << 7) + (sum >> 1) + b
108 }
109 return sum
110}
111
112// writeMeta writes information about this inode into the contents of the parent
113// inode.
114func (i Inode) writeMeta(w io.Writer) error {
115 fileNameUTF16 := utf16.Encode([]rune(i.Name))
116 // VFAT file names are null-terminated
117 fileNameUTF16 = append(fileNameUTF16, 0x00)
118 if len(fileNameUTF16) > 255 {
119 return errors.New("file name too long, maximum is 255 UTF-16 code points")
120 }
121
122 // ⌈len(fileNameUTF16)/codepointsPerEntry⌉
123 numEntries := (len(fileNameUTF16) + codepointsPerEntry - 1) / codepointsPerEntry
124 // Fill up to space in given number of entries with fill code point 0xffff
125 fillCodePoints := (numEntries * codepointsPerEntry) - len(fileNameUTF16)
126 for j := 0; j < fillCodePoints; j++ {
127 fileNameUTF16 = append(fileNameUTF16, 0xffff)
128 }
129
130 // Write entries in reverse order
131 for j := numEntries; j > 0; j-- {
132 // Index of the code point being processed
133 cpIdx := (j - 1) * codepointsPerEntry
134 var entry lfnEntry
135 entry.Checksum = lfnChecksum(i.dosName)
136 // Downcast is safe as i <= numEntries <= ⌈255/codepointsPerEntry⌉
137 entry.SequenceNumber = uint8(j)
138 if j == numEntries {
139 entry.SequenceNumber |= lastSequenceNumberFlag
140 }
141 entry.Attributes = 0x0F
142 copy(entry.NamePart1[:], fileNameUTF16[cpIdx:])
143 cpIdx += len(entry.NamePart1)
144 copy(entry.NamePart2[:], fileNameUTF16[cpIdx:])
145 cpIdx += len(entry.NamePart2)
146 copy(entry.NamePart3[:], fileNameUTF16[cpIdx:])
147 cpIdx += len(entry.NamePart3)
148
149 if err := binary.Write(w, binary.LittleEndian, entry); err != nil {
150 return err
151 }
152 }
153 selfSize, err := i.dataSize()
154 if err != nil {
155 return err
156 }
157 if selfSize >= 4*1024*1024*1024 {
158 return errors.New("single file size exceeds 4GiB which is prohibited in FAT32")
159 }
160 if i.Attrs&AttrDirectory != 0 {
161 selfSize = 0 // Directories don't have an explicit size
162 }
163 date, t, _ := timeToMsDosTime(i.ModTime)
164 if err := binary.Write(w, binary.LittleEndian, &dirEntry{
165 DOSName: i.dosName,
166 Attributes: uint8(i.Attrs),
167 FirstClusterHigh: uint16(i.startCluster >> 16),
168 LastWrittenToTime: t,
169 LastWrittenToDate: date,
170 FirstClusterLow: uint16(i.startCluster & 0xffff),
171 FileSize: uint32(selfSize),
172 }); err != nil {
173 return err
174 }
175 return nil
176}
177
178// writeData writes the contents of this inode (including possible metadata
179// of its children, but not its children's data)
180func (i Inode) writeData(w io.Writer, volumeLabel [11]byte) error {
181 if i.Attrs&AttrDirectory != 0 {
182 if i.parent == nil {
183 if err := binary.Write(w, binary.LittleEndian, &dirEntry{
184 DOSName: volumeLabel,
185 Attributes: 0x08, // Volume ID, internal use only
186 }); err != nil {
187 return err
188 }
189 } else {
190 date, t, _ := timeToMsDosTime(i.ModTime)
191 cdate, ctime, ctens := timeToMsDosTime(i.CreateTime)
192 if err := binary.Write(w, binary.LittleEndian, &dirEntry{
193 DOSName: [11]byte{'.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
194 CreationDate: cdate,
195 CreationTime: ctime,
196 CreationTenMilli: ctens,
197 LastWrittenToTime: t,
198 LastWrittenToDate: date,
199 Attributes: uint8(i.Attrs),
200 FirstClusterHigh: uint16(i.startCluster >> 16),
201 FirstClusterLow: uint16(i.startCluster & 0xffff),
202 }); err != nil {
203 return err
204 }
205 startCluster := i.parent.startCluster
206 if i.parent.parent == nil {
207 // Special case: When the dotdot directory points to the root
208 // directory, the start cluster is defined to be zero even if
209 // it isn't.
210 startCluster = 0
211 }
212 // Time is intentionally taken from this directory, not the parent
213 if err := binary.Write(w, binary.LittleEndian, &dirEntry{
214 DOSName: [11]byte{'.', '.', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
215 LastWrittenToTime: t,
216 LastWrittenToDate: date,
217 Attributes: uint8(AttrDirectory),
218 FirstClusterHigh: uint16(startCluster >> 16),
219 FirstClusterLow: uint16(startCluster & 0xffff),
220 }); err != nil {
221 return err
222 }
223 }
224 err := makeUniqueDOSNames(i.Children)
225 if err != nil {
226 return err
227 }
228 for _, c := range i.Children {
229 if err := c.writeMeta(w); err != nil {
230 return err
231 }
232 }
233 } else {
234 if _, err := io.CopyN(w, i.Content, i.Content.Size()); err != nil {
235 return err
236 }
237 }
238 return nil
239}
240
241func (i Inode) dataSize() (int64, error) {
242 if i.Attrs&AttrDirectory != 0 {
243 var size int64
244 if i.parent != nil {
245 // Dot and dotdot directories
246 size += 2 * 32
247 } else {
248 // Volume ID
249 size += 1 * 32
250 }
251 for _, c := range i.Children {
252 cs, err := c.metaSize()
253 if err != nil {
254 return 0, err
255 }
256 size += cs
257 }
258 if size > 2*1024*1024 {
259 return 0, errors.New("directory contains > 2MiB of metadata which is prohibited in FAT32")
260 }
261 return size, nil
262 } else {
263 return i.Content.Size(), nil
264 }
265}
266
267func (i *Inode) PlaceFile(path string, reader SizedReader) error {
268 pathParts := strings.Split(path, "/")
269 inodeRef := i
270 for j, part := range pathParts {
271 var childExists bool
272 for _, child := range inodeRef.Children {
Tim Windelschmidtc4ac94e2024-04-18 23:12:38 +0200273 if strings.EqualFold(child.Name, part) {
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000274 inodeRef = child
275 childExists = true
276 break
277 }
278 }
279 if j == len(pathParts)-1 { // Is last path part (i.e. file name)
280 if childExists {
281 return &fs.PathError{Path: path, Err: fs.ErrExist, Op: "create"}
282 }
283 newInode := &Inode{
284 Name: part,
285 Content: reader,
286 }
287 inodeRef.Children = append(inodeRef.Children, newInode)
288 return nil
289 } else if !childExists {
290 newInode := &Inode{
291 Name: part,
292 Attrs: AttrDirectory,
293 }
294 inodeRef.Children = append(inodeRef.Children, newInode)
295 inodeRef = newInode
296 }
297 }
298 panic("unreachable")
299}
300
301type planningState struct {
302 // List of inodes in filesystem layout order
303 orderedInodes []*Inode
304 // File Allocation Table
305 fat []uint32
306 // Size of a single cluster in the FAT in bytes
307 clusterSize int64
308}
309
310// Allocates clusters capable of holding at least b bytes and returns the
311// starting cluster index
312func (p *planningState) allocBytes(b int64) int {
313 // Zero-byte data entries are located at the cluster zero by definition
314 // No actual allocation is performed
315 if b == 0 {
316 return 0
317 }
318 // Calculate the number of clusters to be allocated
319 n := (b + p.clusterSize - 1) / p.clusterSize
320 allocStartCluster := len(p.fat)
321 for i := int64(0); i < n-1; i++ {
322 p.fat = append(p.fat, uint32(len(p.fat)+1))
323 }
324 p.fat = append(p.fat, fatEOF)
325 return allocStartCluster
326}
327
328func (i *Inode) placeRecursively(p *planningState) error {
329 selfDataSize, err := i.dataSize()
330 if err != nil {
331 return fmt.Errorf("%s: %w", i.Name, err)
332 }
333 i.startCluster = p.allocBytes(selfDataSize)
334 p.orderedInodes = append(p.orderedInodes, i)
335 for _, c := range i.Children {
336 c.parent = i
337 err = c.placeRecursively(p)
338 if err != nil {
339 return fmt.Errorf("%s/%w", i.Name, err)
340 }
341 }
342 return nil
343}
344
345// WriteFS writes a filesystem described by a root inode and its children to a
346// given io.Writer.
347func WriteFS(w io.Writer, rootInode Inode, opts Options) error {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200348 bs, fsi, p, err := prepareFS(&opts, rootInode)
349 if err != nil {
350 return err
351 }
352
353 wb := newBlockWriter(w)
354
355 // Write superblock
356 if err := binary.Write(wb, binary.LittleEndian, bs); err != nil {
357 return err
358 }
359 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
360 return err
361 }
362 if err := binary.Write(wb, binary.LittleEndian, fsi); err != nil {
363 return err
364 }
365 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
366 return err
367 }
368
369 block := make([]byte, opts.BlockSize)
370 for i := 0; i < 4; i++ {
371 if _, err := wb.Write(block); err != nil {
372 return err
373 }
374 }
375 // Backup of superblock at block 6
376 if err := binary.Write(wb, binary.LittleEndian, bs); err != nil {
377 return err
378 }
379 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
380 return err
381 }
382 if err := binary.Write(wb, binary.LittleEndian, fsi); err != nil {
383 return err
384 }
385 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
386 return err
387 }
388
389 for i := uint8(0); i < bs.NumFATs; i++ {
390 if err := binary.Write(wb, binary.LittleEndian, p.fat); err != nil {
391 return err
392 }
393 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
394 return err
395 }
396 }
397
398 for _, i := range p.orderedInodes {
399 if err := i.writeData(wb, bs.Label); err != nil {
Tim Windelschmidt5f1a7de2024-09-19 02:00:14 +0200400 return fmt.Errorf("failed to write inode %q: %w", i.Name, err)
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200401 }
402 if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.BlocksPerCluster), false); err != nil {
403 return err
404 }
405 }
406 // Creatively use block writer to write out all empty data at the end
407 if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.TotalBlocks), false); err != nil {
408 return err
409 }
410 return nil
411}
412
413func prepareFS(opts *Options, rootInode Inode) (*bootSector, *fsinfo, *planningState, error) {
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000414 if opts.BlockSize == 0 {
415 opts.BlockSize = 512
416 }
417 if bits.OnesCount16(opts.BlockSize) != 1 {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200418 return nil, nil, nil, fmt.Errorf("option BlockSize is not a power of two")
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000419 }
420 if opts.BlockSize < 512 {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200421 return nil, nil, nil, fmt.Errorf("option BlockSize must be at least 512 bytes")
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000422 }
423 if opts.ID == 0 {
424 var buf [4]byte
425 if _, err := rand.Read(buf[:]); err != nil {
Tim Windelschmidt5f1a7de2024-09-19 02:00:14 +0200426 return nil, nil, nil, fmt.Errorf("failed to assign random FAT ID: %w", err)
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000427 }
428 opts.ID = binary.BigEndian.Uint32(buf[:])
429 }
430 if rootInode.Attrs&AttrDirectory == 0 {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200431 return nil, nil, nil, errors.New("root inode must be a directory (i.e. have AttrDirectory set)")
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000432 }
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000433 bs := bootSector{
434 // Assembled x86_32 machine code corresponding to
435 // jmp $
436 // nop
437 // i.e. an infinite loop doing nothing. Nothing created in the last 35
438 // years should boot this anyway.
439 // TODO(q3k): write a stub
440 JmpInstruction: [3]byte{0xEB, 0xFE, 0x90},
441 // Identification
442 OEMName: [8]byte{'M', 'O', 'N', 'O', 'G', 'O', 'N'},
443 ID: opts.ID,
444 // Block geometry
445 BlockSize: opts.BlockSize,
446 TotalBlocks: opts.BlockCount,
447 // BootSector block + FSInfo Block, backup copy at blocks 6 and 7
448 ReservedBlocks: 8,
449 // FSInfo block is always in block 1, right after this block
450 FSInfoBlock: 1,
451 // Start block of the backup of the boot block and FSInfo block
452 // De facto this must be 6 as it is only used when the primary
453 // boot block is damaged at which point this field can no longer be
454 // read.
455 BackupStartBlock: 6,
456 // A lot of implementations only work with 2, so use that
457 NumFATs: 2,
458 BlocksPerCluster: 1,
459 // Flags and signatures
460 MediaCode: 0xf8,
461 BootSignature: 0x29,
462 Label: [11]byte{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
463 Type: [8]byte{'F', 'A', 'T', '3', '2', ' ', ' ', ' '},
464 Signature: [2]byte{0x55, 0xaa},
465 }
466
467 copy(bs.Label[:], opts.Label)
468
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200469 fsi := fsinfo{
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000470 // Signatures
471 LeadSignature: [4]byte{0x52, 0x52, 0x61, 0x41},
472 StructSignature: [4]byte{0x72, 0x72, 0x41, 0x61},
473 TrailingSignature: [2]byte{0x55, 0xAA},
474
475 // This is the unset value which is always legal
476 NextFreeCluster: 0xFFFFFFFF,
477 }
478
479 p := planningState{
480 clusterSize: int64(bs.BlocksPerCluster) * int64(bs.BlockSize),
481 }
482 if opts.BlockCount != 0 {
483 // Preallocate FAT if we know how big it needs to be
484 p.fat = make([]uint32, 0, opts.BlockCount/uint32(bs.BlocksPerCluster))
485 } else {
486 // Preallocate minimum size FAT
487 // See the spec page 15 for the origin of this calculation.
488 p.fat = make([]uint32, 0, 65525+2)
489 }
490 // First two clusters are special
491 p.fat = append(p.fat, 0x0fffff00|uint32(bs.MediaCode), 0x0fffffff)
492 err := rootInode.placeRecursively(&p)
493 if err != nil {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200494 return nil, nil, nil, err
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000495 }
496
497 allocClusters := len(p.fat)
498 if allocClusters >= fatMask&math.MaxUint32 {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200499 return nil, nil, nil, fmt.Errorf("filesystem contains more than 2^28 FAT entries, this is unsupported. Note that this package currently always creates minimal clusters")
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000500 }
501
502 // Fill out FAT to minimum size for FAT32
503 for len(p.fat) < 65525+2 {
504 p.fat = append(p.fat, fatFree)
505 }
506
507 bs.RootClusterNumber = uint32(rootInode.startCluster)
508
509 bs.BlocksPerFAT = uint32(binary.Size(p.fat)+int(opts.BlockSize)-1) / uint32(opts.BlockSize)
510 occupiedBlocks := uint32(bs.ReservedBlocks) + (uint32(len(p.fat)-2) * uint32(bs.BlocksPerCluster)) + bs.BlocksPerFAT*uint32(bs.NumFATs)
511 if bs.TotalBlocks == 0 {
512 bs.TotalBlocks = occupiedBlocks
513 } else if bs.TotalBlocks < occupiedBlocks {
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200514 return nil, nil, nil, fmt.Errorf("content (minimum %d blocks) would exceed number of blocks specified (%d blocks)", occupiedBlocks, bs.TotalBlocks)
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000515 } else { // Fixed-size file system with enough space
516 blocksToDistribute := bs.TotalBlocks - uint32(bs.ReservedBlocks)
517 // Number of data blocks which can be described by one metadata/FAT
518 // block. Always an integer because 4 (bytes per uint32) is a divisor of
519 // all powers of two equal or bigger than 8 and FAT32 requires a minimum
520 // of 512.
521 dataBlocksPerFATBlock := (uint32(bs.BlocksPerCluster) * uint32(bs.BlockSize)) / (uint32(binary.Size(p.fat[0])))
522 // Split blocksToDistribute between metadata and data so that exactly as
523 // much metadata (FAT) exists for describing the amount of data blocks
524 // while respecting alignment.
525 divisor := dataBlocksPerFATBlock + uint32(bs.NumFATs)
526 // 2*blocksPerCluster compensates for the first two "magic" FAT entries
527 // which do not have corresponding data.
528 bs.BlocksPerFAT = (bs.TotalBlocks + 2*uint32(bs.BlocksPerCluster) + (divisor - 1)) / divisor
529 dataBlocks := blocksToDistribute - (uint32(bs.NumFATs) * bs.BlocksPerFAT)
530 // Align to full clusters
531 dataBlocks -= dataBlocks % uint32(bs.BlocksPerCluster)
532 // Magic +2 as the first two entries do not describe data
533 for len(p.fat) < (int(dataBlocks)/int(bs.BlocksPerCluster))+2 {
534 p.fat = append(p.fat, fatFree)
535 }
536 }
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200537 fsi.FreeCount = uint32(len(p.fat) - allocClusters)
538 if fsi.FreeCount > 1 {
539 fsi.NextFreeCluster = uint32(allocClusters) + 1
540 }
541 return &bs, &fsi, &p, nil
542}
543
544// SizeFS returns the number of blocks required to hold the filesystem defined
545// by rootInode and opts. This can be used for sizing calculations before
546// calling WriteFS.
547func SizeFS(rootInode Inode, opts Options) (int64, error) {
548 bs, _, _, err := prepareFS(&opts, rootInode)
549 if err != nil {
550 return 0, err
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000551 }
552
Tim Windelschmidtd7e34c42024-07-09 17:32:13 +0200553 return int64(bs.TotalBlocks), nil
Lorenz Brunbd2ce6d2022-07-22 00:00:13 +0000554}