blob: d734eb7d659f4ab269f4ad3d84fb5d2f0aafa111 [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 {
273 if strings.ToLower(child.Name) == strings.ToLower(part) {
274 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 {
348 if opts.BlockSize == 0 {
349 opts.BlockSize = 512
350 }
351 if bits.OnesCount16(opts.BlockSize) != 1 {
352 return fmt.Errorf("option BlockSize is not a power of two")
353 }
354 if opts.BlockSize < 512 {
355 return fmt.Errorf("option BlockSize must be at least 512 bytes")
356 }
357 if opts.ID == 0 {
358 var buf [4]byte
359 if _, err := rand.Read(buf[:]); err != nil {
360 return fmt.Errorf("failed to assign random FAT ID: %v", err)
361 }
362 opts.ID = binary.BigEndian.Uint32(buf[:])
363 }
364 if rootInode.Attrs&AttrDirectory == 0 {
365 return errors.New("root inode must be a directory (i.e. have AttrDirectory set)")
366 }
367 wb := newBlockWriter(w)
368 bs := bootSector{
369 // Assembled x86_32 machine code corresponding to
370 // jmp $
371 // nop
372 // i.e. an infinite loop doing nothing. Nothing created in the last 35
373 // years should boot this anyway.
374 // TODO(q3k): write a stub
375 JmpInstruction: [3]byte{0xEB, 0xFE, 0x90},
376 // Identification
377 OEMName: [8]byte{'M', 'O', 'N', 'O', 'G', 'O', 'N'},
378 ID: opts.ID,
379 // Block geometry
380 BlockSize: opts.BlockSize,
381 TotalBlocks: opts.BlockCount,
382 // BootSector block + FSInfo Block, backup copy at blocks 6 and 7
383 ReservedBlocks: 8,
384 // FSInfo block is always in block 1, right after this block
385 FSInfoBlock: 1,
386 // Start block of the backup of the boot block and FSInfo block
387 // De facto this must be 6 as it is only used when the primary
388 // boot block is damaged at which point this field can no longer be
389 // read.
390 BackupStartBlock: 6,
391 // A lot of implementations only work with 2, so use that
392 NumFATs: 2,
393 BlocksPerCluster: 1,
394 // Flags and signatures
395 MediaCode: 0xf8,
396 BootSignature: 0x29,
397 Label: [11]byte{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
398 Type: [8]byte{'F', 'A', 'T', '3', '2', ' ', ' ', ' '},
399 Signature: [2]byte{0x55, 0xaa},
400 }
401
402 copy(bs.Label[:], opts.Label)
403
404 fs := fsinfo{
405 // Signatures
406 LeadSignature: [4]byte{0x52, 0x52, 0x61, 0x41},
407 StructSignature: [4]byte{0x72, 0x72, 0x41, 0x61},
408 TrailingSignature: [2]byte{0x55, 0xAA},
409
410 // This is the unset value which is always legal
411 NextFreeCluster: 0xFFFFFFFF,
412 }
413
414 p := planningState{
415 clusterSize: int64(bs.BlocksPerCluster) * int64(bs.BlockSize),
416 }
417 if opts.BlockCount != 0 {
418 // Preallocate FAT if we know how big it needs to be
419 p.fat = make([]uint32, 0, opts.BlockCount/uint32(bs.BlocksPerCluster))
420 } else {
421 // Preallocate minimum size FAT
422 // See the spec page 15 for the origin of this calculation.
423 p.fat = make([]uint32, 0, 65525+2)
424 }
425 // First two clusters are special
426 p.fat = append(p.fat, 0x0fffff00|uint32(bs.MediaCode), 0x0fffffff)
427 err := rootInode.placeRecursively(&p)
428 if err != nil {
429 return err
430 }
431
432 allocClusters := len(p.fat)
433 if allocClusters >= fatMask&math.MaxUint32 {
434 return fmt.Errorf("filesystem contains more than 2^28 FAT entries, this is unsupported. Note that this package currently always creates minimal clusters.")
435 }
436
437 // Fill out FAT to minimum size for FAT32
438 for len(p.fat) < 65525+2 {
439 p.fat = append(p.fat, fatFree)
440 }
441
442 bs.RootClusterNumber = uint32(rootInode.startCluster)
443
444 bs.BlocksPerFAT = uint32(binary.Size(p.fat)+int(opts.BlockSize)-1) / uint32(opts.BlockSize)
445 occupiedBlocks := uint32(bs.ReservedBlocks) + (uint32(len(p.fat)-2) * uint32(bs.BlocksPerCluster)) + bs.BlocksPerFAT*uint32(bs.NumFATs)
446 if bs.TotalBlocks == 0 {
447 bs.TotalBlocks = occupiedBlocks
448 } else if bs.TotalBlocks < occupiedBlocks {
449 return fmt.Errorf("content (minimum %d blocks) would exceed number of blocks specified (%d blocks)", occupiedBlocks, bs.TotalBlocks)
450 } else { // Fixed-size file system with enough space
451 blocksToDistribute := bs.TotalBlocks - uint32(bs.ReservedBlocks)
452 // Number of data blocks which can be described by one metadata/FAT
453 // block. Always an integer because 4 (bytes per uint32) is a divisor of
454 // all powers of two equal or bigger than 8 and FAT32 requires a minimum
455 // of 512.
456 dataBlocksPerFATBlock := (uint32(bs.BlocksPerCluster) * uint32(bs.BlockSize)) / (uint32(binary.Size(p.fat[0])))
457 // Split blocksToDistribute between metadata and data so that exactly as
458 // much metadata (FAT) exists for describing the amount of data blocks
459 // while respecting alignment.
460 divisor := dataBlocksPerFATBlock + uint32(bs.NumFATs)
461 // 2*blocksPerCluster compensates for the first two "magic" FAT entries
462 // which do not have corresponding data.
463 bs.BlocksPerFAT = (bs.TotalBlocks + 2*uint32(bs.BlocksPerCluster) + (divisor - 1)) / divisor
464 dataBlocks := blocksToDistribute - (uint32(bs.NumFATs) * bs.BlocksPerFAT)
465 // Align to full clusters
466 dataBlocks -= dataBlocks % uint32(bs.BlocksPerCluster)
467 // Magic +2 as the first two entries do not describe data
468 for len(p.fat) < (int(dataBlocks)/int(bs.BlocksPerCluster))+2 {
469 p.fat = append(p.fat, fatFree)
470 }
471 }
472 fs.FreeCount = uint32(len(p.fat) - allocClusters)
473 if fs.FreeCount > 1 {
474 fs.NextFreeCluster = uint32(allocClusters) + 1
475 }
476
477 // Write superblock
478 if err := binary.Write(wb, binary.LittleEndian, bs); err != nil {
479 return err
480 }
481 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
482 return err
483 }
484 if err := binary.Write(wb, binary.LittleEndian, fs); err != nil {
485 return err
486 }
487 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
488 return err
489 }
490
491 block := make([]byte, opts.BlockSize)
492 for i := 0; i < 4; i++ {
493 if _, err := wb.Write(block); err != nil {
494 return err
495 }
496 }
497 // Backup of superblock at block 6
498 if err := binary.Write(wb, binary.LittleEndian, bs); err != nil {
499 return err
500 }
501 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
502 return err
503 }
504 if err := binary.Write(wb, binary.LittleEndian, fs); err != nil {
505 return err
506 }
507 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
508 return err
509 }
510
511 for i := uint8(0); i < bs.NumFATs; i++ {
512 if err := binary.Write(wb, binary.LittleEndian, p.fat); err != nil {
513 return err
514 }
515 if err := wb.FinishBlock(int64(opts.BlockSize), true); err != nil {
516 return err
517 }
518 }
519
520 for _, i := range p.orderedInodes {
521 if err := i.writeData(wb, bs.Label); err != nil {
522 return fmt.Errorf("failed to write inode %q: %v", i.Name, err)
523 }
524 if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.BlocksPerCluster), false); err != nil {
525 return err
526 }
527 }
528 // Creatively use block writer to write out all empty data at the end
529 if err := wb.FinishBlock(int64(opts.BlockSize)*int64(bs.TotalBlocks), false); err != nil {
530 return err
531 }
532 return nil
533}