-
Notifications
You must be signed in to change notification settings - Fork 43
/
image_writer.go
658 lines (549 loc) · 16.6 KB
/
image_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package iso9660
import (
"bytes"
"container/list"
"errors"
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"time"
)
const (
primaryVolumeDirectoryIdentifierMaxLength = 31 // ECMA-119 7.6.3
primaryVolumeFileIdentifierMaxLength = 30 // ECMA-119 7.5
)
var (
// ErrFileTooLarge is returned when trying to process a file of size greater
// than 4GB, which due to the 32-bit address limitation is not possible
// except with ISO 9660-Level 3
ErrFileTooLarge = errors.New("file is exceeding the maximum file size of 4GB")
)
// ImageWriter is responsible for staging an image's contents
// and writing them to an image.
type ImageWriter struct {
stagingDir string
}
// NewWriter creates a new ImageWrite and initializes its temporary staging dir.
// Cleanup should be called after the ImageWriter is no longer needed.
func NewWriter() (*ImageWriter, error) {
tmp, err := os.MkdirTemp("", "")
if err != nil {
return nil, err
}
return &ImageWriter{stagingDir: tmp}, nil
}
// Cleanup deletes the underlying temporary staging directory of an ImageWriter.
// It can be called multiple times without issues.
func (iw *ImageWriter) Cleanup() error {
if iw.stagingDir == "" {
return nil
}
if err := os.RemoveAll(iw.stagingDir); err != nil {
return err
}
iw.stagingDir = ""
return nil
}
// AddFile adds a file to the ImageWriter's staging area.
// All path components are mangled to match basic ISO9660 filename requirements.
func (iw *ImageWriter) AddFile(data io.Reader, filePath string) error {
directoryPath, fileName := manglePath(filePath)
if err := os.MkdirAll(path.Join(iw.stagingDir, directoryPath), 0755); err != nil {
return err
}
f, err := os.OpenFile(path.Join(iw.stagingDir, directoryPath, fileName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, data)
return err
}
func failIfSymlink(path string) error {
info, err := os.Lstat(path)
if err != nil {
return err
}
if info.Mode()&os.ModeSymlink != 0 {
return fmt.Errorf("%q is a symlink - these are not yet supported", path)
}
return nil
}
// AddLocalFile adds a file identified by its path to the ImageWriter's staging area.
func (iw *ImageWriter) AddLocalFile(origin, target string) error {
if err := failIfSymlink(origin); err != nil {
return err
}
directoryPath, fileName := manglePath(target)
if err := os.MkdirAll(path.Join(iw.stagingDir, directoryPath), 0755); err != nil {
return err
}
// try to hardlink file to staging area before copying.
stagedFile := path.Join(iw.stagingDir, directoryPath, fileName)
if err := os.Remove(stagedFile); err != nil && !os.IsNotExist(err) {
return err
}
if err := os.Link(origin, stagedFile); err == nil {
return nil
}
f, err := os.Open(origin)
if err != nil {
return err
}
defer f.Close()
return iw.AddFile(f, target)
}
func ensureIsDirectory(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
fileinfo, err := f.Stat()
if err != nil {
return err
}
if !fileinfo.IsDir() {
return fmt.Errorf("%q is not a directory", path)
}
return nil
}
// AddLocalDirectory adds a directory recursively to the ImageWriter's staging area.
func (iw *ImageWriter) AddLocalDirectory(origin, target string) error {
if err := ensureIsDirectory(origin); err != nil {
return err
}
walkfn := func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
relPath := path[len(origin):] // We need the path to be relative to the origin.
return iw.AddLocalFile(path, filepath.Join(target, relPath))
}
return filepath.Walk(origin, walkfn)
}
func manglePath(input string) (string, string) {
input = posixifyPath(input)
nonEmptySegments := splitPath(input)
dirSegments := nonEmptySegments[:len(nonEmptySegments)-1]
name := nonEmptySegments[len(nonEmptySegments)-1]
for i := 0; i < len(dirSegments); i++ {
dirSegments[i] = mangleDirectoryName(dirSegments[i])
}
name = mangleFileName(name)
return path.Join(dirSegments...), name
}
// Converts given path to Posix (replacing \ with /)
//
// @param {string} givenPath Path to convert
//
// @returns {string} Converted filepath
func posixifyPath(path string) string {
if runtime.GOOS == "windows" {
return strings.ReplaceAll(path, "\\", "/")
}
return path
}
func splitPath(input string) []string {
rawSegments := strings.Split(input, "/")
var nonEmptySegments []string
for _, s := range rawSegments {
if len(s) > 0 {
nonEmptySegments = append(nonEmptySegments, s)
}
}
return nonEmptySegments
}
// See ECMA-119 7.5
func mangleFileName(input string) string {
// https://github.com/torvalds/linux/blob/v5.6/fs/isofs/dir.c#L29
input = strings.ToLower(input)
split := strings.Split(input, ".")
version := "1"
var filename, extension string
if len(split) == 1 {
filename = split[0]
} else {
filename = strings.Join(split[:len(split)-1], "_")
extension = split[len(split)-1]
}
// enough characters for the `.ignition` extension
extension = mangleD1String(extension, 8)
maxRemainingFilenameLength := primaryVolumeFileIdentifierMaxLength - (1 + len(version))
if len(extension) > 0 {
maxRemainingFilenameLength -= (1 + len(extension))
}
filename = mangleD1String(filename, maxRemainingFilenameLength)
if len(extension) > 0 {
return filename + "." + extension + ";" + version
}
return filename + ";" + version
}
// See ECMA-119 7.6
func mangleDirectoryName(input string) string {
return mangleD1String(input, primaryVolumeDirectoryIdentifierMaxLength)
}
func mangleD1String(input string, maxCharacters int) string {
// https://github.com/torvalds/linux/blob/v5.6/fs/isofs/dir.c#L29
input = strings.ToLower(input)
var mangledString string
for i := 0; i < len(input) && i < maxCharacters; i++ {
r := rune(input[i])
if strings.ContainsRune(d1Characters, r) {
mangledString += string(r)
} else {
mangledString += "_"
}
}
return mangledString
}
// calculateDirChildrenSectors calculates the total mashalled size of all DirectoryEntries
// within a directory. The size of each entry depends of the length of the filename.
func calculateDirChildrenSectors(path string) (uint32, error) {
contents, err := os.ReadDir(path)
if err != nil {
return 0, err
}
var sectors uint32
var currentSectorOccupied uint32 = 68 // the 0x00 and 0x01 entries
for _, c := range contents {
identifierLen := len(c.Name())
idPaddingLen := (identifierLen + 1) % 2
entryLength := uint32(33 + identifierLen + idPaddingLen)
if currentSectorOccupied+entryLength > sectorSize {
sectors++
currentSectorOccupied = entryLength
} else {
currentSectorOccupied += entryLength
}
}
if currentSectorOccupied > 0 {
sectors++
}
return sectors, nil
}
func fileLengthToSectors(l uint32) uint32 {
if (l % sectorSize) == 0 {
return l / sectorSize
}
return (l / sectorSize) + 1
}
type writeContext struct {
stagingDir string
timestamp RecordingTimestamp
freeSectorPointer uint32
}
func (wc *writeContext) allocateSectors(n uint32) uint32 {
return atomic.AddUint32(&wc.freeSectorPointer, n) - n
}
func (wc *writeContext) createDEForRoot() (*DirectoryEntry, error) {
extentLengthInSectors, err := calculateDirChildrenSectors(wc.stagingDir)
if err != nil {
return nil, err
}
extentLocation := wc.allocateSectors(extentLengthInSectors)
de := &DirectoryEntry{
ExtendedAtributeRecordLength: 0,
ExtentLocation: int32(extentLocation),
ExtentLength: uint32(extentLengthInSectors * sectorSize),
RecordingDateTime: wc.timestamp,
FileFlags: dirFlagDir,
FileUnitSize: 0, // 0 for non-interleaved write
InterleaveGap: 0, // not interleaved
VolumeSequenceNumber: 1, // we only have one volume
Identifier: string([]byte{0}),
SystemUse: []byte{},
}
return de, nil
}
type itemToWrite struct {
isDirectory bool
dirPath string
ownEntry *DirectoryEntry
parentEntery *DirectoryEntry
childrenEntries []*DirectoryEntry
targetSector uint32
}
// scanDirectory reads the directory's contents and adds them to the queue, as well as stores all their DirectoryEntries in the item,
// because we'll need them to write this item's descriptor.
func (wc *writeContext) scanDirectory(item *itemToWrite, dirPath string, ownEntry *DirectoryEntry, parentEntery *DirectoryEntry, targetSector uint32) (*list.List, error) {
contents, err := os.ReadDir(dirPath)
if err != nil {
return nil, err
}
itemsToWrite := list.New()
for _, c := range contents {
var (
fileFlags byte
extentLengthInSectors uint32
extentLength uint32
)
if c.IsDir() {
extentLengthInSectors, err = calculateDirChildrenSectors(path.Join(dirPath, c.Name()))
if err != nil {
return nil, err
}
fileFlags = dirFlagDir
extentLength = extentLengthInSectors * sectorSize
} else {
fileinfo, err := c.Info()
if err != nil {
return nil, err
}
if fileinfo.Size() > int64(math.MaxUint32) {
return nil, ErrFileTooLarge
}
extentLength = uint32(fileinfo.Size())
extentLengthInSectors = fileLengthToSectors(extentLength)
fileFlags = 0
}
extentLocation := wc.allocateSectors(extentLengthInSectors)
de := &DirectoryEntry{
ExtendedAtributeRecordLength: 0,
ExtentLocation: int32(extentLocation),
ExtentLength: uint32(extentLength),
RecordingDateTime: wc.timestamp,
FileFlags: fileFlags,
FileUnitSize: 0, // 0 for non-interleaved write
InterleaveGap: 0, // not interleaved
VolumeSequenceNumber: 1, // we only have one volume
Identifier: c.Name(),
SystemUse: []byte{},
}
// Add this child's descriptor to the currently scanned directory's list of children,
// so that later we can use it for writing the current item.
if item.childrenEntries == nil {
item.childrenEntries = []*DirectoryEntry{de}
} else {
item.childrenEntries = append(item.childrenEntries, de)
}
// queue this child for processing
itemsToWrite.PushBack(itemToWrite{
isDirectory: c.IsDir(),
dirPath: path.Join(dirPath, c.Name()),
ownEntry: de,
parentEntery: ownEntry,
targetSector: uint32(de.ExtentLocation),
})
}
return itemsToWrite, nil
}
// processDirectory writes a given directory item to the destination sectors
func processDirectory(w io.Writer, children []*DirectoryEntry, ownEntry *DirectoryEntry, parentEntry *DirectoryEntry) error {
var currentOffset uint32
currentDE := ownEntry.Clone()
currentDE.Identifier = string([]byte{0})
parentDE := parentEntry.Clone()
parentDE.Identifier = string([]byte{1})
currentDEData, err := currentDE.MarshalBinary()
if err != nil {
return err
}
parentDEData, err := parentDE.MarshalBinary()
if err != nil {
return err
}
n, err := w.Write(currentDEData)
if err != nil {
return err
}
currentOffset += uint32(n)
n, err = w.Write(parentDEData)
if err != nil {
return err
}
currentOffset += uint32(n)
for _, childDescriptor := range children {
data, err := childDescriptor.MarshalBinary()
if err != nil {
return err
}
remainingSectorSpace := sectorSize - (currentOffset % sectorSize)
if remainingSectorSpace < uint32(len(data)) {
// ECMA-119 6.8.1.1 If the body of the next descriptor won't fit into the sector,
// we fill the rest of space with zeros and skip to the next sector.
zeros := bytes.Repeat([]byte{0}, int(remainingSectorSpace))
_, err = w.Write(zeros)
if err != nil {
return err
}
// skip to the next sector
currentOffset = 0
}
n, err = w.Write(data)
if err != nil {
return err
}
currentOffset += uint32(n)
}
// fill with zeros to the end of the sector
remainingSectorSpace := sectorSize - (currentOffset % sectorSize)
if remainingSectorSpace != 0 {
zeros := bytes.Repeat([]byte{0}, int(remainingSectorSpace))
_, err = w.Write(zeros)
if err != nil {
return err
}
}
return nil
}
func processFile(w io.Writer, dirPath string) error {
f, err := os.Open(dirPath)
if err != nil {
return err
}
defer f.Close()
fileinfo, err := f.Stat()
if err != nil {
return err
}
if fileinfo.Size() > int64(math.MaxUint32) {
return ErrFileTooLarge
}
buffer := make([]byte, sectorSize)
for bytesLeft := uint32(fileinfo.Size()); bytesLeft > 0; {
var toRead uint32
if bytesLeft < sectorSize {
toRead = bytesLeft
} else {
toRead = sectorSize
}
if _, err = io.ReadAtLeast(f, buffer, int(toRead)); err != nil {
return err
}
if _, err = w.Write(buffer); err != nil {
return err
}
bytesLeft -= toRead
}
// We already write a whole sector-sized buffer, so there's need to fill with zeroes.
return nil
}
// traverseStagingDir creates a new queue of items to write by traversing the staging directory
func (wc *writeContext) traverseStagingDir(rootItem itemToWrite) (*list.List, error) {
itemsToWrite := list.New()
itemsToWrite.PushBack(rootItem)
for item := itemsToWrite.Front(); item != nil; item = item.Next() {
it := item.Value.(itemToWrite)
if it.isDirectory {
newItems, err := wc.scanDirectory(&it, it.dirPath, it.ownEntry, it.parentEntery, it.targetSector)
if err != nil {
relativePath := it.dirPath[len(wc.stagingDir):]
return nil, fmt.Errorf("processing %s: %s", relativePath, err)
}
itemsToWrite.PushBackList(newItems)
}
item.Value = it
}
return itemsToWrite, nil
}
func writeAll(w io.Writer, itemsToWrite *list.List) error {
for item := itemsToWrite.Front(); item != nil; item = item.Next() {
it := item.Value.(itemToWrite)
var err error
if it.isDirectory {
err = processDirectory(w, it.childrenEntries, it.ownEntry, it.parentEntery)
} else {
err = processFile(w, it.dirPath)
}
if err != nil {
return err
}
}
return nil
}
// WriteTo writes the image to the given WriterAt
func (iw *ImageWriter) WriteTo(w io.Writer, volumeIdentifier string) error {
now := time.Now()
wc := writeContext{
stagingDir: iw.stagingDir,
timestamp: RecordingTimestamp{},
freeSectorPointer: 18, // system area (16) + 2 volume descriptors
}
rootDE, err := wc.createDEForRoot()
if err != nil {
return fmt.Errorf("creating root directory descriptor: %s", err)
}
rootItem := itemToWrite{
isDirectory: true,
dirPath: wc.stagingDir,
ownEntry: rootDE,
parentEntery: rootDE,
targetSector: uint32(rootDE.ExtentLocation),
}
itemsToWrite, err := wc.traverseStagingDir(rootItem)
if err != nil {
return fmt.Errorf("tranversing staging directory: %s", err)
}
pvd := volumeDescriptor{
Header: volumeDescriptorHeader{
Type: volumeTypePrimary,
Identifier: standardIdentifierBytes,
Version: 1,
},
Primary: &PrimaryVolumeDescriptorBody{
SystemIdentifier: runtime.GOOS,
VolumeIdentifier: volumeIdentifier,
VolumeSpaceSize: int32(wc.freeSectorPointer),
VolumeSetSize: 1,
VolumeSequenceNumber: 1,
LogicalBlockSize: int16(sectorSize),
PathTableSize: 0,
TypeLPathTableLoc: 0,
OptTypeLPathTableLoc: 0,
TypeMPathTableLoc: 0,
OptTypeMPathTableLoc: 0,
RootDirectoryEntry: rootDE,
VolumeSetIdentifier: "",
PublisherIdentifier: "",
DataPreparerIdentifier: "",
ApplicationIdentifier: "github.com/kdomanski/iso9660",
CopyrightFileIdentifier: "",
AbstractFileIdentifier: "",
BibliographicFileIdentifier: "",
VolumeCreationDateAndTime: VolumeDescriptorTimestampFromTime(now),
VolumeModificationDateAndTime: VolumeDescriptorTimestampFromTime(now),
VolumeExpirationDateAndTime: VolumeDescriptorTimestamp{},
VolumeEffectiveDateAndTime: VolumeDescriptorTimestampFromTime(now),
FileStructureVersion: 1,
ApplicationUsed: [512]byte{},
},
}
terminator := volumeDescriptor{
Header: volumeDescriptorHeader{
Type: volumeTypeTerminator,
Identifier: standardIdentifierBytes,
Version: 1,
},
}
// write 16 sectors of zeroes
zeroSector := bytes.Repeat([]byte{0}, int(sectorSize))
for i := uint32(0); i < 16; i++ {
if _, err = w.Write(zeroSector); err != nil {
return err
}
}
buffer, err := pvd.MarshalBinary()
if err != nil {
return err
}
if _, err = w.Write(buffer); err != nil {
return err
}
if buffer, err = terminator.MarshalBinary(); err != nil {
return err
}
if _, err = w.Write(buffer); err != nil {
return err
}
if err = writeAll(w, itemsToWrite); err != nil {
return fmt.Errorf("writing files: %s", err)
}
return nil
}