iso9660

package module
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 16 Imported by: 5 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-filesystems/iso9660

iso9660

Go Reference CI

Pure-Go access to ISO 9660 (ECMA-119) CD/DVD images — no root, no external tools, no CGO. Reading is read-only (the format has no in-place update model, matching real optical media); authoring a fresh image is supported via Builder.

ISO 9660 is the optical-disc filesystem used by .iso images produced by mkisofs / genisoimage / xorriso. This driver reads the Primary Volume Descriptor, walks directory records and reads file extents, exposing the image through the shared github.com/go-filesystems/interface Filesystem API.

Support summary

Feature Status Notes
Open / Close ✅ Primary Volume Descriptor (CD001)
ReadFile ✅ Single- and multi-extent files (incl. multi-sector)
Read at an offset ✅ (*FS).OpenFile(path) → io.ReaderAt + Size() (filesystem.Opener / filesystem.File); extent-aware, reads no data at open
ListDir ✅ Directory records; ./.. filtered out
Stat ✅ Rock Ridge POSIX mode when present, else synthesised; size + extent LBA
Names ✅ Rock Ridge real names when present; else base ECMA-119 (;version stripped, case-insensitive)
Rock Ridge (POSIX names/perms/symlinks) ✅ SP/NM/PX/SL/CE continuation; deep-dir relocation (CL/PL/RE) not yet
ReadLink / symlinks ✅ Rock Ridge SL targets
Joliet (UCS-2 long names) ✅ Supplementary VD; used when Rock Ridge is absent
Multi-extent files ✅ ECMA-119 §6.5.1; consecutive records merged, extents concatenated in order
Author a fresh image ✅ Builder (NewBuilder/AddDir/AddFile/WriteTo) masters a base ECMA-119 image, interchange level 1; images round-trip through this package's own reader
Mutate an already-mastered image ❌ Once opened, an image is read-only — every filesystem.Filesystem mutator (WriteFile, MkDir, …) returns ErrReadOnly, matching the real on-disk format (ISO 9660 media has no in-place update model)

References

  • ECMA-119 (ISO 9660)
  • mkisofs / genisoimage / xorriso

Module

github.com/go-filesystems/iso9660

Usage

Reading
fs, err := iso9660.OpenFile("image.iso")
if err != nil { /* ... */ }
defer fs.Close()

data, err := fs.ReadFile("/BOOT/GRUB/GRUB.CFG")
entries, err := fs.ListDir("/")
Reading part of a file

ReadFile returns the whole file, which is no use to anything that serves reads on demand — a mount, an NFS or 9P export — where a 4 KiB request out of a multi-gigabyte ISO must not read the lot. The driver implements the optional filesystem.Opener capability:

var generic filesystem.Filesystem = fs
if o, ok := generic.(filesystem.Opener); ok {
    f, err := o.OpenFile("/BOOT/BIG.IMG")
    if err != nil { /* ... */ }
    defer f.Close()

    buf := make([]byte, 4096)
    n, err := f.ReadAt(buf, 1<<30) // only the bytes asked for
    _, _ = n, err
    _ = f.Size()                   // from the directory record; reads nothing
}

OpenFile records where the file's extents live and reads none of them. File data is contiguous within an extent, and a multi-extent file (ECMA-119 §6.5.1) is the concatenation of several whose lengths are byte counts, not block counts — so extent boundaries do not fall on logical-block boundaries and the offset→disk mapping is a search, never a division. ReadAt follows io.ReaderAt exactly (n < len(p) only with a non-nil error, io.EOF at the end) and is safe to call concurrently.

Note the method (*FS).OpenFile(path) (filesystem.File, error) is distinct from the package-level iso9660.OpenFile(path) (*FS, error), which opens an image from the host filesystem.

Authoring a fresh image
b := iso9660.NewBuilder("MYVOLUME")
_ = b.AddDir("/boot")
_ = b.AddFile("/boot/grub.cfg", []byte("..."))

f, err := os.Create("out.iso")
if err != nil { /* ... */ }
defer f.Close()
if err := b.WriteTo(f); err != nil { /* ... */ }

Untrusted images

An image is attacker-controlled input and every length in it is a claim. Each input-driven allocation is bounded before it is made (bombs_test.go measures each road with runtime.MemStats):

Claim in the image Bound
a file's or directory's length, image size known at most the image size, and the extent must lie inside the image (checked before anything is reserved)
the same, image size unknown (Open(rs, -1)) the buffer grows with the bytes the reader actually delivers (1 MiB steps, doubling), so a forged 512 MiB length over a 40 KiB image costs 40 KiB; claims above 1 GiB are refused
a directory extent at most 16 MiB (ErrCorrupt wrapping safeio.ErrTooLarge)
the volume-descriptor scan sectors 16-99, as in the Linux reader

ReadFile returns the whole file; for large files use OpenFile + ReadAt, which allocates nothing proportional to the claimed size.

Fuzz targets: FuzzOpen, FuzzBombs (asserts a per-input allocation budget).

Judged by

The Linux kernel (7.0), isoinfo and xorriso/genisoimage, run as root in a Tart VM by kerneljudge (kerneljudge run --driver <clone>; the test is kerneljudge_test.go, behind FS_KERNEL_JUDGE=1). Images written by Builder, by xorriso -as mkisofs and by genisoimage (all ISO level 1) are each held to a fixed corpus (nested directories, a 1 MiB and a 32 MiB file, empty and odd-sized files) by isoinfo, a read-only kernel mount and this reader: all three pass, byte for byte, and no defect was found. The corpus names are mapped to level-1 upper-case 8.3 names (the base writer has no Joliet or Rock Ridge, so UTF-8 names, symlinks, xattrs and permissions are outside what this format holds here).

Limitations

  • An already-mastered image is read-only once opened (the on-disk format has no in-place update model); Builder masters a fresh image instead.
  • Builder writes the base ECMA-119 layer (interchange level 1) only — Rock Ridge and Joliet extensions are decoded on read but not yet written.
  • Rock Ridge (SP/NM/PX/SL) is decoded, including CE continuation areas; deep-directory relocation (CL/PL/RE) is not. One path lookup follows at most 40 symlinks IN TOTAL (a go-volumes/safeio SymlinkBudget), not only 40 deep: a chain a -> b/b -> ... would otherwise cost 2^n lookups. It is refused with ErrTooManyLinks, which also matches safeio.ErrSymlinkLoop.
  • Joliet (UCS-2 long names) is decoded from the supplementary volume descriptor and used when Rock Ridge is absent; without either, names appear uppercased.
  • Multi-extent files (ECMA-119 §6.5.1) are read: a file recorded as several consecutive directory records — every record but the last carrying the multi-extent flag — is presented as one entry whose contents are the in-order concatenation of its extents.
  • Intended for tooling and testing.

Documentation

Overview

Package iso9660 is a pure-Go driver for the ISO 9660 (ECMA-119) CD/DVD image format produced by mkisofs/genisoimage/xorriso. It reads the Primary Volume Descriptor, walks directory records, and reads contiguous file extents.

On read, the base ECMA-119 layer (uppercase ;version-suffixed names) plus the Rock Ridge (POSIX long names/permissions/symlinks, including CE continuation areas) and Joliet (UCS-2 long names) extensions are decoded. When a tree carries Rock Ridge it takes precedence, then Joliet, then the base tree.

An existing image is read-only once mastered: every mutating method of filesystem.Filesystem (WriteFile, MkDir, ...) returns ErrReadOnly. To author a new image, use Builder (NewBuilder / AddDir / AddFile / WriteTo), which masters a base ECMA-119 image — system area, Primary Volume Descriptor, Volume Descriptor Set Terminator, Type-L/Type-M path tables, directory extents and file data. Writing covers the base ECMA-119 layer (interchange level 1); the Rock Ridge and Joliet extensions are decoded on read but not yet written.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrReadOnly is returned by every mutating method (WriteFile, MkDir,
	// DeleteFile, DeleteDir, Rename). ISO 9660 is a read-only format.
	ErrReadOnly = errors.New("iso9660: filesystem is read-only")

	// ErrBadDescriptor is returned when no valid Primary Volume Descriptor
	// (standard identifier "CD001") is found.
	ErrBadDescriptor = errors.New("iso9660: no valid primary volume descriptor")

	// ErrNotFound is returned when a path component cannot be located.
	ErrNotFound = fmt.Errorf("iso9660: path not found: %w", iofs.ErrNotExist)

	// ErrNotDirectory is returned when ListDir targets a non-directory.
	ErrNotDirectory = errors.New("iso9660: not a directory")

	// ErrNotRegular is returned when ReadFile targets a non-regular file.
	ErrNotRegular = errors.New("iso9660: not a regular file")

	// ErrNotSymlink is returned by ReadLink when the target is not a symlink.
	// Symlinks come from the Rock Ridge SL entry (base ISO 9660 has none), so
	// this is also what ReadLink returns on a plain (non-Rock-Ridge) image.
	ErrNotSymlink = errors.New("iso9660: not a symbolic link")

	// ErrTooManyLinks is returned when path resolution exceeds the symlink hop
	// limit, indicating a loop.
	ErrTooManyLinks = errors.New("iso9660: too many symbolic link traversals")

	// ErrCorrupt is returned when an on-disk structure fails a sanity check.
	ErrCorrupt = errors.New("iso9660: corrupt image")

	// ErrInvalidName is returned by the Builder when an Add* path is empty or
	// otherwise unusable.
	ErrInvalidName = errors.New("iso9660: invalid name")

	// ErrExists is returned by the Builder when an Add* path collides with an
	// entry of the wrong type (a file where a directory is needed, or vice
	// versa).
	ErrExists = errors.New("iso9660: path already exists")
)

Sentinel errors. Compare with errors.Is so wrapped errors continue to match.

Functions

func OpenReader added in v0.3.0

func OpenReader(r io.ReaderAt, size int64) (filesystem.Filesystem, error)

OpenReader opens the ISO 9660 filesystem at the start of r, exactly as Open does, and returns it as a filesystem.Filesystem.

It exists so every driver in go-filesystems answers to ONE name for the same thing. github.com/go-filesystems/detect's Opener is func(io.ReaderAt, int64) (filesystem.Filesystem, error): Open here is the right shape but returns a concrete *FS, which is a different type and does not fit. The drivers that could only be opened from a PATH have grown this function; this one is that same function, so a caller can write

detect.Register(detect.T, driver.OpenReader)

for every driver instead of a closure per driver.

The concrete type is still there for a caller that wants what it has beyond the common interface: Open returns it.

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder accumulates a directory tree in memory and then writes it as a base ISO 9660 image. Construct one with NewBuilder, populate it with AddDir and AddFile, then call WriteTo.

Builder is the write-side counterpart to Open: an image produced here reads back through this package's own reader (see the round-trip tests).

func NewBuilder

func NewBuilder(volumeID string) *Builder

NewBuilder returns an empty Builder whose root directory is "/". volumeID becomes the Primary Volume Descriptor volume identifier (uppercased and truncated to the 32-byte ECMA-119 field; empty yields "CDROM").

func (*Builder) AddDir

func (b *Builder) AddDir(path string) error

AddDir creates the directory at the slash-separated absolute path, creating any missing parents. It is idempotent for an already-existing directory and returns an error if a path component already exists as a regular file.

func (*Builder) AddFile

func (b *Builder) AddFile(path string, data []byte) error

AddFile creates the regular file at the slash-separated absolute path with the given contents, creating any missing parent directories. An existing file at the path is replaced; an existing directory there is an error.

func (*Builder) WriteTo

func (b *Builder) WriteTo(w io.WriterAt) error

WriteTo masters the accumulated tree into a base ISO 9660 image written through w. w is written sector by sector at absolute offsets, so a freshly created (or truncated) file or an in-memory buffer is the expected target.

type FS

type FS struct {
	// contains filtered or unexported fields
}

FS is an opened, read-only ISO 9660 filesystem.

func Open

func Open(rs io.ReaderAt, size int64) (*FS, error)

Open parses the ISO 9660 volume descriptors and returns a read-only handle. The caller retains ownership of rs unless it implements io.Closer. Pass size = -1 if unknown.

func OpenFile

func OpenFile(path string) (*FS, error)

OpenFile opens path read-only and wires it into Open.

func (*FS) Close

func (fs *FS) Close() error

Close releases the backing file handle if FS opened one.

func (*FS) DeleteDir

func (fs *FS) DeleteDir(string) error

func (*FS) DeleteFile

func (fs *FS) DeleteFile(string) error

func (*FS) ListDir

func (fs *FS) ListDir(path string) ([]filesystem.DirEntry, error)

ListDir enumerates the directory at path, excluding the "." and ".." special entries.

func (*FS) MkDir

func (fs *FS) MkDir(string, os.FileMode) error

func (*FS) OpenFile added in v0.2.0

func (fs *FS) OpenFile(path string) (filesystem.File, error)

OpenFile opens the regular file at path for random access.

It resolves the path exactly as ReadFile does — following Rock Ridge symlinks — and then records where the file's extents live, without reading any of them. Note that this METHOD on *FS is distinct from the package-level OpenFile(path) function, which opens an image file from the host filesystem and returns an *FS; Go keeps package scope and method sets apart, and the method is the one filesystem.Opener asks for.

func (*FS) ReadFile

func (fs *FS) ReadFile(path string) ([]byte, error)

ReadFile returns the full contents of the regular file at path.

func (fs *FS) ReadLink(path string) (string, error)

ReadLink returns the target of a Rock Ridge symbolic link. Base ISO 9660 without Rock Ridge has no symlinks, so ReadLink reports ErrNotSymlink.

SECURITY: the returned target is the raw, UNTRUSTED Rock Ridge SL value from the image. It may contain ".." components or an absolute path, so a malicious image can point it anywhere. In-driver path resolution (resolveFrom) is unaffected — it filters "."/".." and rebases absolute targets against the image root, and caps symlink follows with a safeio.SymlinkBudget — so the link can never escape the image when traversed through this package. Callers that interpret the returned string against the HOST filesystem (for example to recreate the link on disk during extraction) MUST sanitise it first; otherwise a "../../etc/passwd" or "/etc/passwd" target is a path traversal vector.

func (*FS) Rename

func (fs *FS) Rename(string, string) error

func (*FS) Stat

func (fs *FS) Stat(path string) (filesystem.Stat, error)

Stat resolves path and returns a synthesised mode (type + default perms), size and a pseudo-inode (the extent LBA).

func (*FS) Volume

func (fs *FS) Volume() *Volume

Volume returns the decoded Primary Volume Descriptor. Owned by FS.

func (*FS) WriteFile

func (fs *FS) WriteFile(string, []byte, os.FileMode) error

type Volume

type Volume struct {
	VolumeID  string
	BlockSize uint32 // logical block size (usually 2048)
	SpaceSize uint32 // volume space size in logical blocks
	// contains filtered or unexported fields
}

Volume is the decoded volume-descriptor data the reader needs. It carries both the Primary tree root and, when present, the Joliet (UCS-2) tree root; the FS picks which to traverse.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址