diff --git a/filesystem/iso9660/directoryentry.go b/filesystem/iso9660/directoryentry.go index af164d7d..59cbf84b 100644 --- a/filesystem/iso9660/directoryentry.go +++ b/filesystem/iso9660/directoryentry.go @@ -577,7 +577,7 @@ func (de *directoryEntry) statT() *StatT { s.UID = e.uid s.GID = e.gid s.NLink = e.linkCount - s.Inode = uint32(e.serial) + s.Inode = e.serial case rockRidgeSymlink: s.RockRidge = true if !e.continued { diff --git a/filesystem/iso9660/finalize.go b/filesystem/iso9660/finalize.go index 72833845..04d4db6c 100644 --- a/filesystem/iso9660/finalize.go +++ b/filesystem/iso9660/finalize.go @@ -1,6 +1,7 @@ package iso9660 import ( + "bytes" "fmt" "io" "io/fs" @@ -9,6 +10,7 @@ import ( "path" "path/filepath" "regexp" + "slices" "sort" "strings" "time" @@ -100,7 +102,7 @@ type finalizeFileInfo struct { // content in memory content of file. If this is anything other than nil, including a zero-length slice, // then this content is used, rather than anything on disk. content []byte - serial uint64 + serial uint32 } func finalizeFileInfoFromFile(p, fullPath string, fi fs.FileInfo) (*finalizeFileInfo, error) { @@ -393,7 +395,14 @@ func (fi *finalizeFileInfo) toJolietDirectory(fsm *FileSystem, jolietLocation, p parent.location = parentJolietLocation entries := []*directoryEntry{self, parent} - for _, child := range fi.children { + // Joliet identifiers use the original names, which can sort differently + // from the shortened ISO 9660 identifiers in fi.children. Compare the + // bytes that are written, since UCS-2 order differs from string order. + children := append([]*finalizeFileInfo(nil), fi.children...) + sort.Slice(children, func(i, j int) bool { + return bytes.Compare(ucs2StringToBytes(jolietFilename(children[i])), ucs2StringToBytes(jolietFilename(children[j]))) < 0 + }) + for _, child := range children { de := child.toJolietDirectoryEntry(fsm, false, false) entries = append(entries, de) } @@ -697,20 +706,49 @@ func (fsm *FileSystem) Finalize(options FinalizeOptions) error { accessTime: now, changeTime: now, } - // make it the first file - files = append([]*finalizeFileInfo{catEntry}, files...) - - // if we were not told to hide the catalog, add it to its parent - if !options.ElTorito.HideBootCatalog { - var parent *finalizeFileInfo - parent, err = root.findEntry(path.Dir(catname)) - if err != nil { - return fmt.Errorf("error finding parent for boot catalog %s: %v", catname, err) + parent, err := root.findEntry(path.Dir(catname)) + if err != nil { + return fmt.Errorf("error finding parent for boot catalog %s: %v", catname, err) + } + if parent == nil && !options.ElTorito.HideBootCatalog { + return fmt.Errorf("unable to find parent directory for boot catalog %s", catname) + } + var existing *finalizeFileInfo + if parent != nil { + for _, child := range parent.children { + if child.name == catEntry.name { + existing = child + break + } } - if parent == nil { - return fmt.Errorf("unable to find parent directory for boot catalog %s", catname) + } + // trueChild marks the placeholder of a relocated directory + if existing != nil && (existing.IsDir() || existing.trueChild != nil || existing.mode&os.ModeSymlink != 0) { + if !options.ElTorito.HideBootCatalog { + return fmt.Errorf("boot catalog %s collides with a directory or symlink", catname) + } + // a hidden catalog has no directory record, so nothing collides + existing = nil + } + if existing != nil { + if options.ElTorito.HideBootCatalog { + parent.children = slices.DeleteFunc(parent.children, func(child *finalizeFileInfo) bool { return child == existing }) + files = slices.DeleteFunc(files, func(file *finalizeFileInfo) bool { return file == existing }) + } else { + catEntry = existing + } + } + catEntry.content = bootcat + catEntry.size = catSize + catEntry.blocks = calculateBlocks(catSize, fsm.blocksize) + if existing == nil || options.ElTorito.HideBootCatalog { + files = append([]*finalizeFileInfo{catEntry}, files...) + if !options.ElTorito.HideBootCatalog { + if err := giveUniqueIdentifier(catEntry, parent.children); err != nil { + return fmt.Errorf("unable to name boot catalog %s: %w", catname, err) + } + parent.addChild(catEntry) } - parent.addChild(catEntry) } for _, e := range options.ElTorito.Entries { var parent, child *finalizeFileInfo @@ -733,11 +771,21 @@ func (fsm *FileSystem) Finalize(options FinalizeOptions) error { if child == nil { return fmt.Errorf("unable to find image child %s: %v", e.BootFile, err) } + if child == catEntry { + return fmt.Errorf("boot image file %s is also the boot catalog", e.BootFile) + } // save the child so we can add location late e.size = uint32(child.size) child.elToritoEntry = e } } + // Directory records must be ordered by their ISO 9660 file identifiers. + // Do this before calculating directory sizes, since record order affects padding. + for _, dir := range dirs { + sort.Slice(dir.children, func(i, j int) bool { + return lessISOIdentifier(dir.children[i], dir.children[j]) + }) + } var size, ceBlocks int for _, dir := range dirs { @@ -1250,7 +1298,7 @@ func walkTree(workspace string) ([]*finalizeFileInfo, map[string]*finalizeFileIn fileList = make([]*finalizeFileInfo, 0) collisionGroups = make(map[string]*collisionGroup) entry *finalizeFileInfo - serial uint64 + serial uint32 ) err := filepath.WalkDir(workspace, func(actualPath string, d fs.DirEntry, err error) error { if err != nil { @@ -1410,6 +1458,52 @@ func resolveCollisionGroup(group *collisionGroup) error { return fmt.Errorf("too many filename collisions for: %s", name) } +// lessISOIdentifier follows ECMA-119's directory order: file name first, +// then extension. Comparing the whole identifier puts A.1;1 before A.;1. +func lessISOIdentifier(a, b *finalizeFileInfo) bool { + if a.shortname != b.shortname { + return a.shortname < b.shortname + } + if a.extension != b.extension { + return a.extension < b.extension + } + // The name and the extension can be equal for two different identifiers: + // a directory FOO and a file FOO.;1, which has no extension. + // walkTree prevents this pair in a source directory. But Rock Ridge + // relocation moves a deep directory into the root and does no such check. + // ECMA-119 does not give an order for this pair. The directory goes + // first, as xorriso and genisoimage write it. + return a.Name() < b.Name() +} + +// giveUniqueIdentifier keeps an unrelated source file intact when the +// generated catalog's ISO 9660 identifier would otherwise collide with it. +func giveUniqueIdentifier(entry *finalizeFileInfo, siblings []*finalizeFileInfo) error { + used := make(map[string]bool, len(siblings)) + for _, sibling := range siblings { + used[sibling.Name()] = true + } + if !used[entry.Name()] { + return nil + } + base := entry.shortname + limit := 1 + for digits := 1; digits < 8; digits++ { + limit *= 10 + prefix := base + if len(prefix) > 8-digits { + prefix = prefix[:8-digits] + } + for n := 0; n < limit; n++ { + entry.shortname = fmt.Sprintf("%s%0*d", prefix, digits, n) + if !used[entry.Name()] { + return nil + } + } + } + return fmt.Errorf("too many ISO 9660 identifier collisions for %s", entry.name) +} + func calculateBlocks(size, blocksize int64) uint32 { blocks := uint32(size / blocksize) // add one for partial diff --git a/filesystem/iso9660/finalize_catalog_internal_test.go b/filesystem/iso9660/finalize_catalog_internal_test.go new file mode 100644 index 00000000..19d3319b --- /dev/null +++ b/filesystem/iso9660/finalize_catalog_internal_test.go @@ -0,0 +1,265 @@ +package iso9660 + +import ( + "bytes" + "encoding/binary" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/diskfs/go-diskfs/backend/file" +) + +// finalizeCatalogImage writes the files below workspace/isolinux, finalizes an +// image with the options and returns the image with a reader for it. +func finalizeCatalogImage(t *testing.T, files map[string]string, options FinalizeOptions) (*os.File, *FileSystem) { + t.Helper() + root := t.TempDir() + workspace := filepath.Join(root, "workspace") + isoDir := filepath.Join(workspace, "isolinux") + if err := os.MkdirAll(isoDir, 0o755); err != nil { + t.Fatal(err) + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(isoDir, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + image, err := os.Create(filepath.Join(root, "image.iso")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { image.Close() }) + backend := file.New(image, false) + writer, err := Create(backend, 0, 0, 2048, workspace) + if err != nil { + t.Fatal(err) + } + if err := writer.Finalize(options); err != nil { + t.Fatal(err) + } + reader, err := Read(backend, 0, 0, 2048) + if err != nil { + t.Fatal(err) + } + return image, reader +} + +func catalogOptions(catalog string, hide bool) FinalizeOptions { + return FinalizeOptions{ + RockRidge: true, + Joliet: true, + ElTorito: &ElTorito{ + BootCatalog: catalog, + HideBootCatalog: hide, + Entries: []*ElToritoEntry{{ + Platform: BIOS, Emulation: NoEmulation, BootFile: "/isolinux/boot.img", + }}, + }, + } +} + +// childNames returns the names of the entries, without self and parent. +func childNames(entries []*directoryEntry) []string { + names := make([]string, 0, len(entries)) + for _, entry := range entries { + if !entry.isSelf && !entry.isParent { + names = append(names, entry.filename) + } + } + return names +} + +func findChild(entries []*directoryEntry, name string) *directoryEntry { + for _, entry := range entries { + if entry.filename == name { + return entry + } + } + return nil +} + +// bootCatalogLocation returns the catalog sector from the boot volume descriptor. +func bootCatalogLocation(t *testing.T, image *os.File) uint32 { + t.Helper() + for sector := int64(16); sector < 20; sector++ { + vd := make([]byte, 2048) + if _, err := image.ReadAt(vd, sector*2048); err != nil { + t.Fatal(err) + } + if vd[0] == byte(volumeDescriptorBoot) && string(vd[1:6]) == "CD001" { + return binary.LittleEndian.Uint32(vd[0x47:0x4b]) + } + } + t.Fatal("no boot volume descriptor") + return 0 +} + +func readExtent(t *testing.T, image *os.File, location, size uint32) []byte { + t.Helper() + content := make([]byte, size) + if _, err := image.ReadAt(content, int64(location)*2048); err != nil { + t.Fatal(err) + } + return content +} + +func TestFinalizeBootCatalogCollisionAndDirectoryOrder(t *testing.T) { + for _, tt := range []struct { + name string + sourceFile bool + hide bool + }{ + {name: "existing catalog", sourceFile: true}, + {name: "generated catalog"}, + {name: "hidden existing catalog", sourceFile: true, hide: true}, + } { + t.Run(tt.name, func(t *testing.T) { + files := map[string]string{ + "a": "no extension", + "a.1": "number extension", + "boot.img": "boot image", + "boot.msg": "boot message", + "vesamenu.c32": "menu", + } + if tt.sourceFile { + files["boot.cat"] = "stale catalog" + } + options := catalogOptions("/isolinux/boot.cat", tt.hide) + image, reader := finalizeCatalogImage(t, files, options) + + primary, err := reader.readDirectoryPVD("/isolinux") + if err != nil { + t.Fatal(err) + } + wantPrimary := []string{"A.;1", "A.1;1", "BOOT.CAT;1", "BOOT.IMG;1", "BOOT.MSG;1", "VESAMENU.C32;1"} + wantJoliet := []string{"a", "a.1", "boot.cat", "boot.img", "boot.msg", "vesamenu.c32"} + if tt.hide { + wantPrimary = slices.Delete(wantPrimary, 2, 3) + wantJoliet = slices.Delete(wantJoliet, 2, 3) + } + if names := childNames(primary); !slices.Equal(names, wantPrimary) { + t.Errorf("primary directory entries = %q, want %q", names, wantPrimary) + } + joliet, err := reader.readDirectoryJoliet("/isolinux") + if err != nil { + t.Fatal(err) + } + if names := childNames(joliet); !slices.Equal(names, wantJoliet) { + t.Errorf("Joliet directory entries = %q, want %q", names, wantJoliet) + } + + bootCatalog, err := options.ElTorito.generateCatalog() + if err != nil { + t.Fatal(err) + } + location := bootCatalogLocation(t, image) + if !bytes.Equal(readExtent(t, image, location, uint32(len(bootCatalog))), bootCatalog) { + t.Error("boot volume descriptor does not point to the generated catalog") + } + catalog := findChild(primary, "BOOT.CAT;1") + if catalog != nil && (catalog.location != location || catalog.size != uint32(len(bootCatalog))) { + t.Errorf("visible catalog record has location %d size %d, want location %d size %d", catalog.location, catalog.size, location, len(bootCatalog)) + } + }) + } +} + +func TestFinalizeBootCatalogIdentifierCollisionPreservesSource(t *testing.T) { + options := catalogOptions("/isolinux/boot.catalog", false) + image, reader := finalizeCatalogImage(t, map[string]string{ + "boot.cat": "unrelated source content", + "boot.img": "boot image", + }, options) + + primary, err := reader.readDirectoryPVD("/isolinux") + if err != nil { + t.Fatal(err) + } + source, catalog := findChild(primary, "BOOT.CAT;1"), findChild(primary, "BOOT0.CAT;1") + if source == nil || catalog == nil { + t.Fatalf("source and generated catalog records not both present: %q", childNames(primary)) + } + if content := readExtent(t, image, source.location, source.size); string(content) != "unrelated source content" { + t.Errorf("source content = %q", content) + } + bootCatalog, err := options.ElTorito.generateCatalog() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(readExtent(t, image, catalog.location, catalog.size), bootCatalog) { + t.Error("generated catalog record does not contain the catalog") + } + if location := bootCatalogLocation(t, image); location != catalog.location { + t.Errorf("boot descriptor catalog location = %d, want %d", location, catalog.location) + } + joliet, err := reader.readDirectoryJoliet("/isolinux") + if err != nil { + t.Fatal(err) + } + names := childNames(joliet) + if !slices.Contains(names, "boot.cat") || !slices.Contains(names, "boot.catalog") { + t.Errorf("Joliet names = %q, want both source and requested catalog", names) + } +} + +func TestFinalizeHiddenBootCatalogIgnoresDirectoryOfSameName(t *testing.T) { + root := t.TempDir() + workspace := filepath.Join(root, "workspace") + if err := os.MkdirAll(filepath.Join(workspace, "isolinux", "boot.cat"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "isolinux", "boot.img"), []byte("boot image"), 0o600); err != nil { + t.Fatal(err) + } + image, err := os.Create(filepath.Join(root, "image.iso")) + if err != nil { + t.Fatal(err) + } + defer image.Close() + backend := file.New(image, false) + writer, err := Create(backend, 0, 0, 2048, workspace) + if err != nil { + t.Fatal(err) + } + options := catalogOptions("/isolinux/boot.cat", true) + options.Joliet = false + if err := writer.Finalize(options); err != nil { + t.Fatal(err) + } + reader, err := Read(backend, 0, 0, 2048) + if err != nil { + t.Fatal(err) + } + entries, err := reader.readDirectoryPVD("/isolinux") + if err != nil { + t.Fatal(err) + } + if !slices.ContainsFunc(entries, func(e *directoryEntry) bool { return e.isSubdirectory && !e.isSelf && !e.isParent }) { + t.Errorf("source directory boot.cat missing from /isolinux: %q", childNames(entries)) + } +} + +func TestFinalizeRejectsBootCatalogThatIsABootImage(t *testing.T) { + root := t.TempDir() + workspace := filepath.Join(root, "workspace") + if err := os.MkdirAll(filepath.Join(workspace, "isolinux"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "isolinux", "boot.img"), []byte("boot image"), 0o600); err != nil { + t.Fatal(err) + } + image, err := os.Create(filepath.Join(root, "image.iso")) + if err != nil { + t.Fatal(err) + } + defer image.Close() + writer, err := Create(file.New(image, false), 0, 0, 2048, workspace) + if err != nil { + t.Fatal(err) + } + if err := writer.Finalize(catalogOptions("/isolinux/boot.img", false)); err == nil { + t.Fatal("Finalize accepted a boot catalog path that is also a boot image") + } +} diff --git a/filesystem/iso9660/rockridge.go b/filesystem/iso9660/rockridge.go index 3dc010a8..b2fdfb65 100644 --- a/filesystem/iso9660/rockridge.go +++ b/filesystem/iso9660/rockridge.go @@ -273,7 +273,7 @@ type rockRidgePosixAttributes struct { linkCount uint32 uid uint32 gid uint32 - serial uint64 + serial uint32 } func (d rockRidgePosixAttributes) Equal(o directoryEntrySystemUseExtension) bool { @@ -346,7 +346,8 @@ func (d rockRidgePosixAttributes) Data() []byte { binary.LittleEndian.PutUint32(ret[24:28], d.gid) binary.BigEndian.PutUint32(ret[28:32], d.gid) if d.length == 44 { - binary.LittleEndian.PutUint64(ret[32:40], d.serial) + binary.LittleEndian.PutUint32(ret[32:36], d.serial) + binary.BigEndian.PutUint32(ret[36:40], d.serial) } return ret } @@ -415,9 +416,9 @@ func (r *rockRidgeExtension) parsePosixAttributes(b []byte) (directoryEntrySyste m |= uint32(os.ModeNamedPipe) } - var serial uint64 + var serial uint32 if len(b) == 44 { - serial = binary.LittleEndian.Uint64(b[36:44]) + serial = binary.LittleEndian.Uint32(b[36:40]) } return rockRidgePosixAttributes{ mode: os.FileMode(m), diff --git a/filesystem/iso9660/rockridge_internal_test.go b/filesystem/iso9660/rockridge_internal_test.go index 88c64489..504abc09 100644 --- a/filesystem/iso9660/rockridge_internal_test.go +++ b/filesystem/iso9660/rockridge_internal_test.go @@ -1,6 +1,7 @@ package iso9660 import ( + "bytes" "fmt" "os" "os/user" @@ -132,9 +133,13 @@ func TestRockRidgePosixAttributesRoundTrip(t *testing.T) { uid: 1000, gid: 1000, length: rr.pxLength, - serial: 42, + serial: 0x12345678, } b := original.Bytes() + wantSerial := []byte{0x78, 0x56, 0x34, 0x12, 0x12, 0x34, 0x56, 0x78} + if !bytes.Equal(b[36:44], wantSerial) { + t.Fatalf("PX serial bytes = %x, want %x", b[36:44], wantSerial) + } parsed, err := rr.parsePosixAttributes(b) if err != nil { t.Fatalf("unexpected error parsing PX: %v", err)