Documentation
¶
Overview ¶
VHD Dynamic Disk Header Parser
Package reader provides high-level APIs for reading VHD/VHDX virtual disk files.
Package reader provides high-level APIs for reading VHD/VHDX virtual disk files.
VHDX File Information and Image Header Parser
Index ¶
- Constants
- Variables
- func GUIDString(guid [16]byte) string
- func ParseGUID(s string) ([16]byte, error)
- type ChainEntry
- type DiscoverOptions
- type DiskInfo
- type Extent
- type ExtentKind
- type FooterSource
- type Geometry
- type Lineage
- type LogReplayStats
- type Node
- type Options
- type ParentRequest
- type ParentResolver
- type ParentResolverFunc
- type ParentSource
- type Provenance
- type Role
- type Run
- type StreamOptions
- type StructuralError
- type Tree
- func (t *Tree) Branched() bool
- func (t *Tree) Find(id [16]byte) (*Node, error)
- func (t *Tree) FindPath(path string) (*Node, error)
- func (t *Tree) Leaves() []*Node
- func (t *Tree) Lineage(n *Node) Lineage
- func (t *Tree) Lineages() []Lineage
- func (t *Tree) Roots() []*Node
- func (t *Tree) Unreadable() []*Node
- type VHDDynamicDiskHeaderParser
- type VHDFooterParser
- type VHDXFileInfoParser
- type VHDXImageHeaderParser
- type VHDXRegionTableParser
- type VirtualDisk
- func Open(r io.ReaderAt, opts *Options) (*VirtualDisk, error)
- func OpenFile(path string) (*VirtualDisk, error)
- func OpenFileWith(name string, opts *Options) (*VirtualDisk, error)
- func OpenVHD(r io.ReaderAt, fileSize int64) (*VirtualDisk, error)
- func OpenVHDX(r io.ReaderAt, fileSize int64) (*VirtualDisk, error)
- func (d *VirtualDisk) AllExtents() ([]Extent, error)
- func (d *VirtualDisk) AllExtentsContext(ctx context.Context) ([]Extent, error)
- func (d *VirtualDisk) BlockSize() uint32
- func (d *VirtualDisk) Chain() []ChainEntry
- func (d *VirtualDisk) ChainComplete() bool
- func (d *VirtualDisk) ChainDepth() int
- func (d *VirtualDisk) ChangedBytes(ctx context.Context, sinceChainIndex int) (written, unresolved int64, err error)
- func (d *VirtualDisk) ChangedExtents(ctx context.Context, sinceChainIndex int) ([]Extent, error)
- func (d *VirtualDisk) ChangedSince(ctx context.Context, path string) ([]Extent, error)
- func (d *VirtualDisk) Close() error
- func (d *VirtualDisk) DataWriteIdentifier() [16]byte
- func (d *VirtualDisk) DiskType() types.DiskType
- func (d *VirtualDisk) Extents(virtualOffset, length int64) ([]Extent, error)
- func (d *VirtualDisk) ExtentsContext(ctx context.Context, virtualOffset, length int64) ([]Extent, error)
- func (d *VirtualDisk) FooterRecovered() bool
- func (d *VirtualDisk) FooterSource() FooterSource
- func (d *VirtualDisk) Format() types.FileFormat
- func (d *VirtualDisk) GUIDString() string
- func (d *VirtualDisk) Geometry() Geometry
- func (d *VirtualDisk) HasLog() bool
- func (d *VirtualDisk) HasWarnings() bool
- func (d *VirtualDisk) Identifier() [16]byte
- func (d *VirtualDisk) IsDifferencing() bool
- func (d *VirtualDisk) IsDirty() bool
- func (d *VirtualDisk) LogReplayStats() (LogReplayStats, bool)
- func (d *VirtualDisk) LogReplayed() bool
- func (d *VirtualDisk) MappedBytes() (int64, error)
- func (d *VirtualDisk) MappedBytesContext(ctx context.Context) (int64, error)
- func (d *VirtualDisk) NeedsParent() bool
- func (d *VirtualDisk) Parent() *VirtualDisk
- func (d *VirtualDisk) ParentFilename() string
- func (d *VirtualDisk) ParentIdentifier() [16]byte
- func (d *VirtualDisk) ParentLocators() []types.ParentLocatorEntry
- func (d *VirtualDisk) ParentResolveError() error
- func (d *VirtualDisk) Path() string
- func (d *VirtualDisk) Provenance() Provenance
- func (d *VirtualDisk) ReadAt(p []byte, offset int64) (int, error)
- func (d *VirtualDisk) ReadAtContext(ctx context.Context, p []byte, offset int64) (int, error)
- func (d *VirtualDisk) SectionReader() *io.SectionReader
- func (d *VirtualDisk) SectorSize() uint32
- func (d *VirtualDisk) SetParent(parent *VirtualDisk) error
- func (d *VirtualDisk) Size() uint64
- func (d *VirtualDisk) Stream(ctx context.Context, opts *StreamOptions, visit func(Run) error) error
- func (d *VirtualDisk) VirtualToFileOffset(virtualOffset int64) (fileOffset int64, mapped bool, err error)
- func (d *VirtualDisk) Warnings() []Warning
- type Warning
- type WarningKind
Constants ¶
const DefaultMaxChainDepth = 32
DefaultMaxChainDepth bounds how many disks a differencing chain may contain, counting the child itself.
Variables ¶
var ErrChainCycle = errors.New("libvhdi: parent chain contains a cycle")
ErrChainCycle is returned when a parent chain refers back to a disk already in the chain.
var ErrChainTooDeep = errors.New("libvhdi: parent chain exceeds maximum depth")
ErrChainTooDeep is returned when a parent chain exceeds Options.MaxChainDepth.
var ErrCorruptImage = types.ErrCorruptImage
ErrCorruptImage is returned when an image's headers are internally inconsistent, fail a checksum, or describe structures that do not fit the file.
It is the same sentinel the parsers below the reader wrap, so errors.Is answers the question regardless of which layer noticed. A parser that can say where the problem is returns a *types.StructuralError wrapping it.
var ErrDirtyImage = errors.New("libvhdi: image has an unreplayed log and may be stale")
ErrDirtyImage is returned when a VHDX image carries an unreplayed log. Its block allocation table and metadata may be stale, so decoded contents cannot be trusted. Set Options.AllowDirtyImage to read it anyway.
var ErrNotFound = errors.New("libvhdi: no such disk in the chain tree")
ErrNotFound is returned when a node named by identity is not in the tree.
var ErrParentMismatch = errors.New("libvhdi: parent image does not match child metadata")
ErrParentMismatch is returned when a located parent does not match the identity recorded in the child.
var ErrParentNotFound = errors.New("libvhdi: parent image not found")
ErrParentNotFound is returned by a ParentResolver that exhausted its search without locating the requested parent image.
var ErrParentRequired = diff.ErrParentRequired
ErrParentRequired is returned when a read on a differencing disk resolves to a parent that has not been attached. Differencing disks fail closed: silently returning zeroes would be indistinguishable from genuine disk contents.
var ErrSizeUnknown = errors.New("libvhdi: cannot determine file size; set Options.Size")
ErrSizeUnknown is returned when a disk's total file size can neither be derived from the supplied reader nor was given explicitly.
var ErrSplitImage = fmt.Errorf("%w: split or segmented multi-file images are not a VHD/VHDX layout", types.ErrUnsupportedFeature)
ErrSplitImage is returned for a file that looks like one piece of a split or segmented disk.
Neither the VHD nor the VHDX specification defines such a layout: a multi-file disk in these formats is always a differencing chain, and split images are a VMDK and VDI concept. A file named like a VMDK extent is therefore not a VHD this library is failing to read -- it is a different format, and saying so is more useful than "invalid signature".
var ErrUnsupportedFeature = types.ErrUnsupportedFeature
ErrUnsupportedFeature is returned when an image is well-formed but uses something this library does not implement, such as a reserved VHD disk type or a VHDX metadata item marked required that this parser does not know.
It is deliberately distinct from ErrCorruptImage. One says the file is broken; the other says to try a different tool. Conflating them sends an examiner looking for damage that is not there.
Functions ¶
func GUIDString ¶ added in v0.3.0
GUIDString renders a 16-byte GUID in the canonical RFC 4122 form.
Both VHD and VHDX store the first three fields of a GUID little-endian and the rest big-endian. Printing the bytes in order therefore produces a string that looks like a GUID and names a different one, which is a mistake every caller makes once. Exporting the conversion is cheaper than each of them getting it wrong.
Types ¶
type ChainEntry ¶
type ChainEntry struct {
// Index is the disk's position: 0 is the disk Chain was called on, 1 its
// parent, and so on.
Index int
// Path is the file the disk was opened from, or "" when it came from a bare
// io.ReaderAt.
Path string
// Identifier is the disk's own GUID.
Identifier [16]byte
// ParentIdentifier is the GUID this disk records for its parent, zero for a
// disk that has none.
ParentIdentifier [16]byte
// ParentFilename is the parent path recorded in this disk's metadata.
ParentFilename string
Format types.FileFormat
DiskType types.DiskType
// VirtualSize is the disk's virtual size. Every link in a valid chain
// reports the same value.
VirtualSize uint64
// IsDifferencing reports whether this disk depends on a parent.
IsDifferencing bool
// HasLog and LogReplayed describe the disk's VHDX log state.
HasLog bool
LogReplayed bool
}
ChainEntry describes one disk in a differencing chain.
func (ChainEntry) GUIDString ¶
func (e ChainEntry) GUIDString() string
GUIDString returns the disk's identifier as a formatted GUID.
type DiscoverOptions ¶ added in v0.3.0
type DiscoverOptions struct {
// Recursive descends into subdirectories. Hyper-V keeps a machine's disks
// in one folder by default, so the default is a single level.
Recursive bool
// Extensions limits which files are probed. Nil means the four disk
// extensions: .vhd, .vhdx, .avhd and .avhdx.
//
// A renamed image is still a valid image, so pass the extensions in use
// rather than expecting the library to sniff every file in the directory --
// which on a machine folder would mean reading memory dumps.
Extensions []string
// MaxFiles bounds how many files are probed, guarding against being pointed
// at a directory of a hundred thousand files. Zero means 4096.
MaxFiles int
}
DiscoverOptions controls a directory scan. The zero value is usable.
type DiskInfo ¶ added in v0.3.0
type DiskInfo struct {
// Path is the file this was read from.
Path string
// Format and DiskType are what the image says it is.
Format types.FileFormat
DiskType types.DiskType
// Identifier is the image's own GUID.
Identifier [16]byte
// LinkIdentity is the GUID a differencing child of this image would record
// to name it. It is the image's own identifier for VHD and its data-write
// identifier for VHDX, which are different fields -- conflating them is what
// makes a chain fail to link up.
LinkIdentity [16]byte
// ParentIdentifier is the GUID this image records for its parent, zero when
// it has none.
ParentIdentifier [16]byte
// ParentFilename is the parent path recorded in this image, and
// ParentLocators every path candidate it lists.
ParentFilename string
ParentLocators []types.ParentLocatorEntry
// VirtualSize is the device size this image presents.
VirtualSize uint64
// FileSize is the size of the file on disk.
FileSize int64
// HasLog reports a VHDX carrying journalled writes. Discovery does not
// replay the log, so a true value here means the image's structures may be
// stale and a full open is needed to say more.
HasLog bool
FooterSource FooterSource
}
DiskInfo is what a header-only probe can learn about an image.
It exists so that a directory of images can be surveyed without opening any of them. A full open parses the block allocation table, which for a large disk is megabytes of read and allocation per image -- and discovery needs none of it. Everything here comes from structures at fixed offsets near the start and end of the file.
func ProbeFile ¶ added in v0.3.0
ProbeFile reads an image's headers without opening it.
This is what makes scanning a directory of large images cheap: no block allocation table is read, nothing is allocated in proportion to the disk's size, and no log is replayed. It is enough to build a chain tree and no more.
func (DiskInfo) HasCheckpointExtension ¶ added in v0.3.0
HasCheckpointExtension reports whether the file uses Hyper-V's naming convention for a checkpoint disk.
A differencing image without this extension is still a checkpoint, and an image with it that is not differencing is a file that has been renamed or converted. Either disagreement is worth reporting rather than resolving.
func (DiskInfo) IsDifferencing ¶ added in v0.3.0
IsDifferencing reports whether this image depends on a parent.
func (DiskInfo) Role ¶ added in v0.3.0
Role classifies this image.
Hyper-V names a checkpoint's differencing disk with an .avhdx or .avhd extension, but the extension is a convention rather than a format: the file is an ordinary differencing image and a renamed one is still a checkpoint. The disk type is therefore what decides, and the extension is only a corroborating signal.
type Extent ¶
type Extent struct {
// VirtualOffset and Length bound the run in the virtual disk's address
// space.
VirtualOffset int64
Length int64
// Kind says what backs the run.
Kind ExtentKind
// FileOffset is the byte offset of the run within the backing file. Valid
// only when Kind is ExtentMapped.
FileOffset int64
// ChainIndex identifies the backing disk: 0 is the disk Extents was called
// on, 1 its parent, and so on. Meaningful when Kind is ExtentMapped.
ChainIndex int
// Path is the backing disk's file path when known, for provenance.
Path string
}
Extent describes a contiguous run of the virtual disk address space and what backs it.
type ExtentKind ¶
type ExtentKind int
ExtentKind describes what backs a range of the virtual disk.
const ( // ExtentZero: the range has no backing bytes anywhere in the chain and reads // as zeroes. An acquisition tool can skip it rather than write zeroes. ExtentZero ExtentKind = iota // ExtentMapped: the range is backed by a contiguous run of bytes in one of // the files in the chain, at FileOffset. ExtentMapped // ExtentUnresolved: the range resolves to a parent that is not attached, so // its contents are unknown. Reading it returns ErrParentRequired. ExtentUnresolved // ExtentZeroedByChild: a differencing disk explicitly recorded this range as // zero, overriding whatever the parent held there. // // It reads as zeroes exactly like ExtentZero, and the distinction exists for // one reason: this is a *write*. The child did something here. ExtentZero // means the range was never written anywhere in the chain, which is a // different fact and, for change tracking, the opposite one -- a deletion // that clears a region records PAYLOAD_BLOCK_ZERO or PAYLOAD_BLOCK_UNMAPPED, // and without this kind it is indistinguishable from "the parent was already // zero". Change detection would silently under-report deletions. // // This kind is VHDX-only, and the reason is a limitation of VHD rather than // of this library. A VHD differencing disk has no way to say "explicitly // zero": its per-block sector bitmap distinguishes only "this sector is // mine" from "read this sector from the parent", and there is no block state // meaning zero. A region cleared on a VHD chain is therefore recorded as // belonging to the parent and reads back as the parent's old contents, not // as zeroes -- so on VHD the clearing is not merely invisible to change // tracking, it did not happen at the format level. Callers doing // deletion-aware change detection need VHDX. ExtentZeroedByChild )
func (ExtentKind) IsWrite ¶ added in v0.3.0
func (k ExtentKind) IsWrite() bool
IsWrite reports whether a disk in the chain actively wrote this range, whether with data or with zeroes.
func (ExtentKind) ReadsAsZero ¶ added in v0.3.0
func (k ExtentKind) ReadsAsZero() bool
ReadsAsZero reports whether a range of this kind returns zeroes when read.
Both ExtentZero and ExtentZeroedByChild do. They differ in what they say about who put the zeroes there, not in what a read returns.
type FooterSource ¶ added in v0.3.0
type FooterSource uint8
FooterSource identifies which copy of the VHD footer an image was opened from.
A VHD carries its footer at the end of the file, and dynamic and differencing disks additionally mirror it at offset 0 precisely so that a damaged tail stays recoverable. Which copy was used is forensically material: a disk opened from its mirror is one whose trailing footer is unreadable, and a report that does not say so presents a recovered image as an intact one.
const ( // which has no footer at all. FooterSourceUnknown FooterSource = iota // where the specification puts it and where an intact image is read from. FooterSourceTrailing // Microsoft Virtual PC before the format was documented. FooterSourceTrailingLegacy // trailing footer could not be read, so the image is damaged even though it // opened. FooterSourceMirror )
func (FooterSource) Recovered ¶ added in v0.3.0
func (s FooterSource) Recovered() bool
Recovered reports whether the footer came from somewhere other than the conformant trailing sector, which means the image is damaged.
func (FooterSource) String ¶ added in v0.3.0
func (s FooterSource) String() string
String names the footer copy for a report or a log line.
type Geometry ¶ added in v0.3.0
type Geometry struct {
// VirtualSize is the device size presented to a guest, in bytes.
VirtualSize uint64
// BlockSize is the allocation unit: the span one block allocation table
// entry covers. A fixed VHD has no blocks and reports its whole size.
BlockSize uint32
// LogicalSectorSize is the sector size the guest sees, and
// PhysicalSectorSize the one the image claims to sit on. They differ on a
// 512e disk, where a guest addressing 512-byte sectors is really writing to
// 4096-byte media.
LogicalSectorSize uint32
PhysicalSectorSize uint32
// Cylinders, Heads and SectorsPerTrack are the CHS geometry, VHD only.
Cylinders uint16
Heads uint8
SectorsPerTrack uint8
}
Geometry describes the physical shape an image reports for itself.
Both formats record more than the virtual size, and the extra fields matter to an examiner even when they do not affect decoding: a disk's CHS geometry constrains how a legacy guest partitioned it, and a physical sector size of 4096 changes what alignment the guest's filesystem was built for.
A zero field means the image did not record that value. It does not mean zero. VHDX has no CHS geometry at all, so Cylinders, Heads and SectorsPerTrack are always zero there, and HasCHS distinguishes the two cases.
func (Geometry) CHSCapacity ¶ added in v0.3.0
CHSCapacity returns the byte capacity the CHS geometry describes, and whether a geometry was recorded at all.
A CHS capacity smaller than VirtualSize is normal rather than suspicious: the encoding tops out at about 127 GB, so every larger disk records a geometry that cannot describe it. The comparison is worth making at smaller sizes, where a disagreement means the footer is internally inconsistent.
type Lineage ¶ added in v0.3.0
type Lineage struct {
// Nodes is the path, Nodes[0] being the root and the last entry the leaf.
Nodes []*Node
}
Lineage is one path through the tree, ordered from the root outwards.
This is the set of files that together constitute one device, which is what an evidence record has to name -- and, read in order, the sequence of states the disk passed through.
func (Lineage) Checkpoints ¶ added in v0.3.0
Checkpoints returns the differencing images in the lineage, root-most first.
func (Lineage) Complete ¶ added in v0.3.0
Complete reports whether the lineage starts at a disk that needs no parent.
A false result means the chain is missing its base: the images present cannot reconstruct the device, and reads into the missing ranges fail with ErrParentRequired rather than returning zeroes.
func (Lineage) Leaf ¶ added in v0.3.0
Leaf returns the outermost image, or nil for an empty lineage.
func (Lineage) Open ¶ added in v0.3.0
func (l Lineage) Open(opts *Options) (*VirtualDisk, error)
Open opens the lineage's leaf, which presents the merged view of every image below it.
No new read logic is involved: opening the leaf resolves the chain and the result is the device as it stood at that point. This exists as a named entry point because "open the leaf" is not obvious from a tree, and because a branched tree has several leaves and no single current disk.
type LogReplayStats ¶
type LogReplayStats struct {
// Entries is the number of log entries replayed.
Entries int
// Descriptors is the number of descriptors applied across those entries.
Descriptors int
// Sectors is the number of distinct 4 KB file sectors the replay overrides.
Sectors int
// FirstSequence and LastSequence bound the replayed sequence numbers.
FirstSequence, LastSequence uint64
}
LogReplayStats describes what a log replay applied.
type Node ¶ added in v0.3.0
type Node struct {
// Info is what the header-only probe read. It is the zero value when the
// image could not be read; Err then says why.
Info DiskInfo
// Path is the file this node came from. It is set even when the probe
// failed, since naming the unreadable file is the point.
Path string
// Err is non-nil when the image could not be probed. Such a node is kept in
// the tree rather than dropped: an unreadable file sitting in a checkpoint
// directory is a finding, and silently omitting it would make the tree look
// complete when it is not.
Err error
// Parent is the node this image differences against, or nil for a root or
// for a child whose parent is not in the scanned set.
Parent *Node
// Children are the images that difference against this one, ordered by
// path so a scan is reproducible.
Children []*Node
}
Node is one image in a chain tree.
func (*Node) Depth ¶ added in v0.3.0
Depth returns how many images lie between this one and its root.
func (*Node) IsLeaf ¶ added in v0.3.0
IsLeaf reports whether nothing differences against this image.
A leaf is a disk that could be written to. On a tree with several leaves, which one a virtual machine is actually using is recorded in its configuration, not in the disks -- see Tree.Leaves.
type Options ¶
type Options struct {
// ParentResolver locates parents for differencing disks.
//
// Nil means the default: a resolver that searches the image's own
// directory, which is where a differencing chain's parents conventionally
// live. Set it to NoParentResolution to suppress resolution entirely and
// attach parents by hand with SetParent.
ParentResolver ParentResolver
// Size is the total size of the image in bytes. When zero, Open derives it
// from the reader. Required for VHD images whose reader exposes neither a
// size nor a seek nor a stat method.
Size int64
// MaxChainDepth bounds the length of a differencing chain, counting the
// child. Zero means DefaultMaxChainDepth.
MaxChainDepth int
// AllowParentGUIDMismatch skips verification that a resolved parent's
// identifier matches the one recorded in the child. Leaving this false
// prevents an unrelated image of the right size from being read as the
// parent.
AllowParentGUIDMismatch bool
// RequireParentChain makes Open fail when a differencing disk's parent
// cannot be resolved. By default resolution is best-effort: the disk opens
// with NeedsParent reporting true and reads that need the parent failing
// with ErrParentRequired.
RequireParentChain bool
// AllowDirtyImage opens a VHDX image whose log could not be replayed.
//
// Log replay is implemented and is attempted automatically: a replayable log
// is applied into a read-only in-memory overlay, leaving the file itself
// byte-identical, and such an image is not dirty. This option covers the
// remaining case, where the log is present but unreplayable -- a torn write,
// a truncated buffer, a broken sequence. Then the block allocation table and
// metadata may be stale and the contents may not reflect the last committed
// state.
//
// Setting it trades a hard failure for a documented risk. The result reports
// IsDirty, and LogReplayed distinguishes an image that needed no replay from
// one whose replay was skipped. Leaving it false refuses the image with
// ErrDirtyImage.
AllowDirtyImage bool
}
Options controls how a disk is opened.
The zero value is safe: parent GUIDs are verified, dirty images are refused, and differencing disks with no parent fail closed on read. Every field that relaxes a check is named so that false — the zero value — is the strict setting.
type ParentRequest ¶
type ParentRequest struct {
// ChildPath is the filesystem path of the child, when it was opened from
// one. Empty for disks opened from a bare io.ReaderAt.
ChildPath string
// ChildDir is the directory containing the child, when known. Parents are
// conventionally stored alongside or near their children, so this is the
// first place to look.
ChildDir string
// ParentFilename is the path recorded in the child's metadata. It is
// typically a Windows path and may be relative or absolute.
ParentFilename string
// ParentIdentifier is the GUID the parent must carry. Callers should not
// need to check this themselves; the chain builder verifies it.
ParentIdentifier [16]byte
// Locators carries the child's parent locator entries, which may hold
// additional candidate paths.
Locators []types.ParentLocatorEntry
// Format is the child's format. A parent is normally the same format.
Format types.FileFormat
// Depth is 0 for the immediate parent of the disk the caller opened, 1 for
// its grandparent, and so on.
Depth int
}
ParentRequest describes the parent image a differencing disk is looking for.
type ParentResolver ¶
type ParentResolver interface {
ResolveParent(req ParentRequest) (ParentSource, error)
}
ParentResolver locates the parent image of a differencing disk.
Implementations should return ErrParentNotFound (possibly wrapped) when the parent cannot be located, so callers can distinguish a missing parent from an I/O failure.
var NoParentResolution ParentResolver = noParentResolution{}
NoParentResolution suppresses automatic parent chain resolution.
It exists so that nil can mean "the default" in Options.ParentResolver without leaving a caller who genuinely wants no resolution unable to say so. Before v0.3.0 nil meant no resolution in Open but the default in OpenFile, which is the sort of difference that is discovered by a differencing disk quietly failing to resolve rather than by reading the documentation.
A disk opened this way reports NeedsParent, and reads that resolve to the missing parent fail with ErrParentRequired rather than returning zeroes.
func DirParentResolver ¶
func DirParentResolver(dirs ...string) ParentResolver
DirParentResolver returns a ParentResolver that searches the child's own directory first, then each of the supplied directories, for the parent named in the child's metadata.
For each directory it tries the recorded relative path and then the bare filename, so a chain that has been moved as a unit still resolves.
func FSParentResolver ¶
func FSParentResolver(fsys fs.FS) ParentResolver
FSParentResolver returns a ParentResolver that searches an fs.FS. Paths are interpreted as slash-separated and relative to the root of fsys, matching io/fs conventions, which makes it usable with embedded, archived or test filesystems.
type ParentResolverFunc ¶
type ParentResolverFunc func(req ParentRequest) (ParentSource, error)
ParentResolverFunc adapts a function to the ParentResolver interface.
func (ParentResolverFunc) ResolveParent ¶
func (f ParentResolverFunc) ResolveParent(req ParentRequest) (ParentSource, error)
ResolveParent implements ParentResolver.
type ParentSource ¶
type ParentSource struct {
// ReaderAt is the parent's backing reader. Required.
ReaderAt io.ReaderAt
// Size is the parent file's total size in bytes. Required for VHD, whose
// footer is located from the end of the file.
Size int64
// Closer, if non-nil, is closed when the child disk is closed. Resolvers
// that open files should set this so the chain owns the handle.
Closer io.Closer
// Name is a human-readable identifier used in diagnostics.
Name string
// ModTime is the parent file's modification time, when the resolver can
// supply one. It is optional; the zero value means "not known".
//
// A differencing child records its parent's modification time, and the
// only way to check that record is against the file the resolver actually
// found. Resolvers that stat a file should set this so the check can
// happen; those that cannot simply leave it zero and the check is skipped.
ModTime time.Time
}
ParentSource is an opened parent image returned by a ParentResolver.
type Provenance ¶ added in v0.3.0
type Provenance struct {
// Format and DiskType are what the image says it is.
Format types.FileFormat
DiskType types.DiskType
// CreatorApplication identifies the producer. For VHD it is the footer's
// four-byte code -- "win " for Hyper-V, "qemu" for qemu-img, "vpc " for
// Virtual PC -- and for VHDX it is the creator string, which is free text.
CreatorApplication string
// CreatorVersion is the producer's version, VHD only, packed as two 16-bit
// halves. CreatorVersionString renders it.
CreatorVersion uint32
// CreatorOS is the producer's host operating system as a four-byte code,
// VHD only: "Wi2k" for Windows, "Mac " for Macintosh.
CreatorOS string
// Created is the image's creation time. It is the zero Time when the image
// recorded none, which is a different fact from an epoch timestamp.
Created time.Time
// Identifier is the image's own GUID, and DataWriteIdentifier the GUID
// VHDX rewrites on every modification -- which is what a differencing child
// records to name its parent.
Identifier string
DataWriteIdentifier string
// OriginalSize is the disk's size at creation, where Geometry.VirtualSize
// is its size now. They differ on an image that has been expanded, and this
// is the only record that the expansion happened. VHD only.
OriginalSize uint64
// Features is the VHD footer's feature flag word.
Features uint32
// SavedState marks a VHD saved from a running machine. Its filesystem is a
// crash-consistent snapshot rather than a cleanly unmounted one, which
// changes what its contents can be taken to mean.
SavedState bool
// LeaveBlocksAllocated is the VHDX file parameter saying blocks are never
// returned to the free pool once written. On such an image an allocated
// block does not imply live data, so an extent map overstates what is in
// use.
LeaveBlocksAllocated bool
// Anything but FooterSourceTrailing means the image was recovered.
FooterSource FooterSource
// HasLog and LogReplayed describe the VHDX log. An image with a log that
// was not replayed may not reflect its last committed state.
HasLog bool
LogReplayed bool
// Path is the file the image was opened from, when it was opened from one.
Path string
// FileSize is the size of the backing file in bytes, as distinct from the
// virtual size of the device it describes.
FileSize int64
// Warnings are the caveats raised for this image alone. Disk.Warnings
// covers the whole chain; this field is deliberately per-image so that a
// chain's record attributes each caveat to the disk it came from.
Warnings []Warning
}
Provenance describes what produced an image, when, and how much of that can be trusted.
A forensic report has to be self-describing: given only the report, a reader must be able to say which tool wrote the image, which tool read it, and whether anything about the read was unusual. Every field here exists to answer one of those.
Fields an image does not record are left zero rather than guessed.
func (Provenance) CreatorVersionString ¶ added in v0.3.0
func (p Provenance) CreatorVersionString() string
CreatorVersionString renders the packed creator version as "major.minor". It returns "" when no version was recorded.
type Role ¶ added in v0.3.0
type Role uint8
Role classifies an image's part in a Hyper-V chain.
const ( // RoleUnknown means the image's role could not be determined. RoleUnknown Role = iota // RoleBase is the disk a chain starts from: a fixed or dynamic image with // no parent. RoleBase // RoleCheckpoint is a differencing image holding the writes made since the // checkpoint below it was taken. RoleCheckpoint )
type Run ¶ added in v0.3.0
type Run struct {
// Extent is the run's place in the virtual address space and what backs it.
Extent Extent
// Data holds the run's bytes. It is valid only until the visit function
// returns: Stream reuses one buffer across runs so a whole-disk walk does
// not allocate per run. Copy what you need to keep.
Data []byte
}
Run is one contiguous piece of the device as Stream emits it.
type StreamOptions ¶ added in v0.3.0
type StreamOptions struct {
// BufferSize caps how many bytes are read at once. Zero selects 4 MiB.
//
// A mapped extent can be the entire disk, so runs are emitted in pieces no
// larger than this rather than materialising a whole extent in memory.
BufferSize int
// IncludeZero emits sparse regions as runs with a nil Data. The default
// skips them entirely, which is the point of streaming: a 4 TB device
// holding 8 GB of data should cost 8 GB of reads, not 4 TB.
//
// Turn it on when the consumer needs to account for every byte of the
// address space rather than only the bytes that exist.
IncludeZero bool
// FailOnUnresolved makes an unresolved extent -- one that resolves to a
// parent that is not attached -- stop the walk with ErrParentRequired.
//
// The default emits it as a run with nil Data and lets the visit function
// decide. Neither choice is safe by default: failing loses a partial
// acquisition that may be all there is, and continuing risks a consumer
// treating the gap as zeroes. The kind is on every run so the decision can
// be made with the facts.
FailOnUnresolved bool
}
StreamOptions controls a Stream walk. The zero value is usable.
type StructuralError ¶ added in v0.3.0
type StructuralError = types.StructuralError
StructuralError says what was being parsed, where in the image, and what was wrong with it. Errors from the parsers are returned as *StructuralError wherever the location is known.
type Tree ¶ added in v0.3.0
type Tree struct {
// Dir is the directory that was scanned.
Dir string
// Nodes holds every image found, ordered by path.
Nodes []*Node
// Skipped records files that were not images at all, with the reason. A
// directory holds .vmcx, .vmrs, .bin and .vsv files alongside the disks, and
// listing them as failures would bury the real ones.
Skipped []string
// contains filtered or unexported fields
}
Tree is the parent-to-children graph of a set of images.
func DiscoverChain ¶ added in v0.3.0
DiscoverChain scans a directory of images and builds the parent-to-children tree they form.
Only headers are read. A full open parses the block allocation table, whose size scales with the virtual disk -- a million entries for a 1 TB disk with 1 MB blocks -- and discovery needs none of it. A probe's own cost is fixed at two headers, up to two 64 KB region tables and the metadata region, so the saving is negligible on small images and large on the ones a checkpoint directory actually holds.
A file that cannot be probed becomes a node carrying the error rather than failing the scan. One corrupt image in a directory must not prevent the rest of the tree from being described, and the unreadable file may be exactly what the examiner is looking for.
Files without a disk extension are recorded in Tree.Skipped. A Hyper-V machine folder holds .vmcx, .vmrs, .bin and .vsv files alongside the disks, and reporting those as failures would bury the real ones.
func (*Tree) Find ¶ added in v0.3.0
Find returns the node a child would reach by recording id as its parent identifier.
func (*Tree) Leaves ¶ added in v0.3.0
Leaves returns the images nothing differences against, ordered by path.
More than one leaf means the checkpoint tree has branched. This library reports the branches and declines to guess which one a virtual machine is using: that fact lives in the machine's configuration, not in the disks, and a library that guessed would be wrong silently.
func (*Tree) Lineages ¶ added in v0.3.0
Lineages returns one lineage per leaf, so a branched tree yields every distinct device the directory describes.
func (*Tree) Roots ¶ added in v0.3.0
Roots returns the images nothing in the tree differences from, ordered by path.
A root is usually the base disk. It can also be a differencing disk whose own parent was not in the scanned directory, which Node.Info.IsDifferencing distinguishes -- and that distinction matters, because such a root cannot be read to completion.
func (*Tree) Unreadable ¶ added in v0.3.0
Unreadable returns every node whose image could not be probed.
These are kept rather than dropped because an unreadable file in a checkpoint directory is itself a finding: it may be the link that would have joined two halves of the tree.
type VHDDynamicDiskHeaderParser ¶
type VHDDynamicDiskHeaderParser struct {
// contains filtered or unexported fields
}
VHDDynamicDiskHeaderParser provides functionality to parse VHD dynamic disk headers.
func NewVHDDynamicDiskHeaderParser ¶
func NewVHDDynamicDiskHeaderParser(r io.ReaderAt) *VHDDynamicDiskHeaderParser
NewVHDDynamicDiskHeaderParser creates a new VHD dynamic disk header parser.
func (*VHDDynamicDiskHeaderParser) ReadHeaderAt ¶
func (p *VHDDynamicDiskHeaderParser) ReadHeaderAt(offset int64) (*types.ParsedDynamicDiskHeader, error)
ReadHeaderAt reads a VHD dynamic disk header from a specific offset.
func (*VHDDynamicDiskHeaderParser) VerifyHeaderChecksum ¶
func (p *VHDDynamicDiskHeaderParser) VerifyHeaderChecksum(header *types.DynamicDiskHeader) bool
VerifyHeaderChecksum verifies the dynamic disk header's checksum.
Per the VHD specification this is a one's complement of the sum of all header bytes with the checksum field zeroed — not a CRC. CRC-32C applies only to VHDX structures.
type VHDFooterParser ¶
type VHDFooterParser struct {
// contains filtered or unexported fields
}
VHDFooterParser provides functionality to parse VHD file footers.
func NewVHDFooterParser ¶
func NewVHDFooterParser(r io.ReaderAt) *VHDFooterParser
NewVHDFooterParser creates a new VHD footer parser.
func (*VHDFooterParser) ReadFooterAt ¶
func (p *VHDFooterParser) ReadFooterAt(offset int64) (*types.ParsedFileFooter, error)
ReadFooterAt reads the VHD footer from a specific offset.
func (*VHDFooterParser) ReadFooterFromEnd ¶
func (p *VHDFooterParser) ReadFooterFromEnd(fileSize int64) (*types.ParsedFileFooter, error)
ReadFooterFromEnd reads the VHD footer from the end of the file (at offset -512).
This is the strict path: it reads only the conformant trailing footer and reports an error for anything else. Callers wanting the recovery paths -- the legacy 511-byte footer and the mirror copy at offset 0 -- want readFooterWithRecovery instead.
func (*VHDFooterParser) VerifyFooterChecksum ¶
func (p *VHDFooterParser) VerifyFooterChecksum(footer *types.FileFooter) bool
VerifyFooterChecksum verifies the footer's checksum.
Per the VHD specification this is a one's complement of the sum of all footer bytes with the checksum field zeroed — not a CRC. CRC-32C applies only to VHDX structures.
type VHDXFileInfoParser ¶
type VHDXFileInfoParser struct {
// contains filtered or unexported fields
}
VHDXFileInfoParser provides functionality to parse VHDX file information.
func NewVHDXFileInfoParser ¶
func NewVHDXFileInfoParser(r io.ReaderAt) *VHDXFileInfoParser
NewVHDXFileInfoParser creates a new VHDX file info parser.
func (*VHDXFileInfoParser) ReadFileInfo ¶
func (p *VHDXFileInfoParser) ReadFileInfo() (*types.ParsedFileInformation, error)
ReadFileInfo reads the VHDX file identifier at offset 0.
The structure is the 8-byte signature followed by a 512-byte Creator field naming the tool that produced the image. That string is the only provenance VHDX records about its producer, which makes it worth reading even though nothing about decoding the image depends on it.
type VHDXImageHeaderParser ¶
type VHDXImageHeaderParser struct {
// contains filtered or unexported fields
}
VHDXImageHeaderParser provides functionality to parse VHDX image headers.
func NewVHDXImageHeaderParser ¶
func NewVHDXImageHeaderParser(r io.ReaderAt) *VHDXImageHeaderParser
NewVHDXImageHeaderParser creates a new VHDX image header parser.
func (*VHDXImageHeaderParser) ReadImageHeader ¶
func (p *VHDXImageHeaderParser) ReadImageHeader() (*types.ParsedImageHeader, error)
ReadImageHeader reads and validates both image headers, returning the valid one with the higher sequence number (per the VHDX spec).
func (*VHDXImageHeaderParser) ReadImageHeaderAt ¶
func (p *VHDXImageHeaderParser) ReadImageHeaderAt(offset int64) (*types.ParsedImageHeader, error)
ReadImageHeaderAt reads and validates a single VHDX image header at the given offset. CRC-32 is computed over all 4096 bytes with the checksum field (bytes 4-7) zeroed.
type VHDXRegionTableParser ¶
type VHDXRegionTableParser struct {
// contains filtered or unexported fields
}
VHDXRegionTableParser provides functionality to parse VHDX region tables.
func NewVHDXRegionTableParser ¶
func NewVHDXRegionTableParser(r io.ReaderAt) *VHDXRegionTableParser
NewVHDXRegionTableParser creates a new VHDX region table parser.
func (*VHDXRegionTableParser) ReadRegionTableAt ¶
func (p *VHDXRegionTableParser) ReadRegionTableAt(offset int64) ([]types.ParsedRegionTableEntry, error)
ReadRegionTableAt reads a VHDX region table from a specific offset. The region table is 64KB; CRC-32 is verified over the full 64KB with the checksum field (bytes 4-7) zeroed before calculation.
type VirtualDisk ¶
type VirtualDisk struct {
// contains filtered or unexported fields
}
VirtualDisk provides a unified read interface for VHD and VHDX virtual disks.
func Open ¶
func Open(r io.ReaderAt, opts *Options) (*VirtualDisk, error)
Open opens a VHD or VHDX image from r, detecting the format automatically.
The image size is taken from opts.Size when set, and otherwise derived from r: readers exposing Size, Stat or Seek are all handled, which covers *os.File, *bytes.Reader, *strings.Reader, io.SectionReader and fs.File. A bare io.ReaderAt with none of those must supply opts.Size for VHD images.
Differencing parent chains are resolved automatically, exactly as OpenFile does. When r names a file -- an *os.File does -- its directory is searched, since that is where a chain's parents conventionally live. Set opts.ParentResolver to change where the search looks, or to NoParentResolution to suppress it and attach parents by hand.
Resolution is best-effort unless opts.requireParentChain() is set: a chain that cannot be completed still opens, with NeedsParent reporting true and reads that need the parent failing with ErrParentRequired rather than returning zeroes.
opts may be nil, which selects the documented defaults.
func OpenFile ¶
func OpenFile(path string) (*VirtualDisk, error)
OpenFile opens a VHD or VHDX file by path, auto-detecting the format.
For a differencing disk, parents are resolved automatically from the image's own directory, so the returned disk presents a correct contiguous device without manual SetParent wiring. Resolution is best-effort: if the chain cannot be completed the disk still opens, ParentResolveError explains why, and reads that need the missing parent return ErrParentRequired rather than zeroes.
Use OpenFileWith for control over parent resolution and the other options.
func OpenFileWith ¶
func OpenFileWith(name string, opts *Options) (*VirtualDisk, error)
OpenFileWith opens a VHD or VHDX file by path with explicit options.
When opts.ParentResolver is nil, a resolver searching the image's own directory is used, since that is where a differencing chain's parents conventionally live.
func OpenVHD ¶
func OpenVHD(r io.ReaderAt, fileSize int64) (*VirtualDisk, error)
OpenVHD opens a VHD file (fixed, dynamic, or differencing). fileSize must be the total size of the file in bytes. For differencing disks, call SetParent before reading.
func OpenVHDX ¶
func OpenVHDX(r io.ReaderAt, fileSize int64) (*VirtualDisk, error)
OpenVHDX opens a VHDX file. fileSize must be the total size of the file in bytes.
If the image carries a log, it is replayed into an in-memory overlay before anything else is parsed, so the disk presents the last committed state. The file itself is never modified. An image whose log cannot be replayed — no valid entries, or an incomplete sequence — is refused with ErrDirtyImage; use Open with Options.AllowDirtyImage to read it as-is anyway.
func (*VirtualDisk) AllExtents ¶
func (d *VirtualDisk) AllExtents() ([]Extent, error)
AllExtents maps the whole disk. It is shorthand for Extents(0, Size()).
func (*VirtualDisk) AllExtentsContext ¶ added in v0.3.0
func (d *VirtualDisk) AllExtentsContext(ctx context.Context) ([]Extent, error)
AllExtentsContext maps the whole disk, checking for cancellation as it goes.
On a large differencing chain this is the expensive call in the library: it walks every block of every disk in the chain and, for partially written blocks, every sector bitmap. A caller that has walked away should not have to wait for it.
func (*VirtualDisk) BlockSize ¶
func (d *VirtualDisk) BlockSize() uint32
BlockSize returns the block size in bytes.
func (*VirtualDisk) Chain ¶
func (d *VirtualDisk) Chain() []ChainEntry
Chain returns the disks backing this one, from this disk outwards.
A fixed or dynamic disk yields a single entry. A differencing disk yields one entry per attached link, so the result is the set of files that together constitute the device — which is what an evidence record needs to name.
The chain may be shorter than the image requires: if the last entry reports IsDifferencing, its parent was never attached, and ParentResolveError explains why. Reads into that parent's ranges fail with ErrParentRequired.
func (*VirtualDisk) ChainComplete ¶
func (d *VirtualDisk) ChainComplete() bool
ChainComplete reports whether every link the chain needs is attached, meaning the whole virtual disk is readable.
func (*VirtualDisk) ChainDepth ¶
func (d *VirtualDisk) ChainDepth() int
ChainDepth returns the number of disks backing this one, including itself. A fixed or dynamic disk has depth 1.
func (*VirtualDisk) ChangedBytes ¶ added in v0.3.0
func (d *VirtualDisk) ChangedBytes(ctx context.Context, sinceChainIndex int) (written, unresolved int64, err error)
ChangedBytes returns how many bytes the disks nearer the leaf than sinceChainIndex wrote.
Zeroed ranges count: clearing a region is a write, and a caller sizing a delta acquisition has to account for the fact that those ranges must be zeroed at the destination rather than skipped.
Unresolved ranges are excluded and reported separately, because counting them either way would be a guess. Use ChangedExtents when the distinction matters.
func (*VirtualDisk) ChangedExtents ¶ added in v0.3.0
ChangedExtents returns the ranges of the virtual disk that were written by the disks nearer the leaf than sinceChainIndex.
Chain indices count outward from the disk this is called on: 0 is that disk, 1 its parent, and so on, matching Chain and Extent.ChainIndex. So on a chain of leaf, checkpoint, base:
ChangedExtents(ctx, 1) // what the leaf wrote ChangedExtents(ctx, 2) // what the leaf and the checkpoint wrote together
A returned extent is either ExtentMapped, meaning a disk in that range wrote data, or ExtentZeroedByChild, meaning a disk explicitly cleared the region. The second kind matters as much as the first: clearing a region is a write, and a deletion that zeroes its blocks shows up only this way. Filtering on ExtentMapped alone silently under-reports deletions.
Ranges the chain never wrote, and ranges supplied by a disk at or beyond sinceChainIndex, are not returned -- they are unchanged by definition.
An unresolved range, one that needs a parent that is not attached, is returned as ExtentUnresolved. It is neither changed nor unchanged: the disk that would say is missing. Reporting it as unchanged would be a guess in the direction that loses evidence.
func (*VirtualDisk) ChangedSince ¶ added in v0.3.0
ChangedSince returns the ranges written since the given disk in the chain was the leaf.
It is ChangedExtents addressed by path rather than by index, which is how a caller holding a checkpoint tree naturally thinks about the question: "what changed since this checkpoint?" rather than "what changed since chain index two?".
func (*VirtualDisk) Close ¶
func (d *VirtualDisk) Close() error
Close releases any resources held by the disk, including parents opened by automatic chain resolution. Parents attached by hand with SetParent are left alone; their lifetime stays with whoever opened them.
The first error encountered is returned, but every link is still closed.
func (*VirtualDisk) DataWriteIdentifier ¶ added in v0.3.0
func (d *VirtualDisk) DataWriteIdentifier() [16]byte
DataWriteIdentifier returns the VHDX DataWriteGuid from the active image header, which a producer rewrites whenever the disk's contents change. It is the zero GUID for VHD, which has no equivalent field.
This is not the disk's stable identity — use Identifier for that. It is the value a VHDX differencing child records in its parent_linkage locator, so a change here means the parent was written to after the child was created.
func (*VirtualDisk) DiskType ¶
func (d *VirtualDisk) DiskType() types.DiskType
DiskType returns the disk type (fixed, dynamic, differencing).
func (*VirtualDisk) Extents ¶
func (d *VirtualDisk) Extents(virtualOffset, length int64) ([]Extent, error)
Extents maps a range of the virtual disk to the runs that back it.
This is the sparse-aware view of the disk: an acquisition or carving tool can walk the extents, read only what is mapped, and skip zero runs instead of reading and writing megabytes of zeroes. For a differencing chain each mapped extent also identifies which disk in the chain supplies it, which VirtualToFileOffset cannot express.
Adjacent runs are merged when they share a kind and, for mapped runs, continue contiguously in the same file. The returned extents tile the requested range exactly, clamped to the disk size, and are ordered by VirtualOffset.
A range resolving to a parent that has not been attached yields ExtentUnresolved rather than an error, so a caller can discover which parts of a chain it is missing.
func (*VirtualDisk) ExtentsContext ¶ added in v0.3.0
func (d *VirtualDisk) ExtentsContext(ctx context.Context, virtualOffset, length int64) ([]Extent, error)
ExtentsContext is Extents with cancellation.
func (*VirtualDisk) FooterRecovered ¶ added in v0.3.0
func (d *VirtualDisk) FooterRecovered() bool
FooterRecovered reports whether this disk was opened from a fallback footer copy rather than the conformant trailing one, meaning the image is damaged.
func (*VirtualDisk) FooterSource ¶ added in v0.3.0
func (d *VirtualDisk) FooterSource() FooterSource
FooterSource reports which copy of the VHD footer this disk was opened from.
It is FooterSourceTrailing for an intact image and FooterSourceUnknown for a VHDX, which has no footer. Anything else means the conformant footer could not be read and the image was recovered from a fallback copy, which an acquisition record must state rather than presenting the result as an intact read.
func (*VirtualDisk) Format ¶
func (d *VirtualDisk) Format() types.FileFormat
Format returns the file format.
func (*VirtualDisk) GUIDString ¶
func (d *VirtualDisk) GUIDString() string
GUIDString returns the disk identifier as a formatted GUID string.
func (*VirtualDisk) Geometry ¶ added in v0.3.0
func (d *VirtualDisk) Geometry() Geometry
Geometry returns the physical shape this image reports for itself.
func (*VirtualDisk) HasLog ¶
func (d *VirtualDisk) HasLog() bool
HasLog reports whether this VHDX image's active header carries a log GUID, meaning it holds journalled writes. This is true whether or not the log was replayable, so it is the right signal for recording that an image was captured mid-write.
func (*VirtualDisk) HasWarnings ¶ added in v0.3.0
func (d *VirtualDisk) HasWarnings() bool
HasWarnings reports whether Warnings would return anything.
func (*VirtualDisk) Identifier ¶
func (d *VirtualDisk) Identifier() [16]byte
Identifier returns the disk's unique identifier GUID.
func (*VirtualDisk) IsDifferencing ¶
func (d *VirtualDisk) IsDifferencing() bool
IsDifferencing reports whether this is a differencing (child) disk.
func (*VirtualDisk) IsDirty ¶
func (d *VirtualDisk) IsDirty() bool
IsDirty reports whether this image carries a log that was not replayed, in which case its block allocation table and metadata may be stale and the decoded contents may not reflect the last committed state.
Such an image only opens when Options.AllowDirtyImage is set, since either the log held no valid entries or its sequence was incomplete.
func (*VirtualDisk) LogReplayStats ¶
func (d *VirtualDisk) LogReplayStats() (LogReplayStats, bool)
LogReplayStats returns what the log replay applied, and false if no log was replayed.
The sector count is a useful evidentiary signal: it measures how much of the image was still in flight when the file was captured.
func (*VirtualDisk) LogReplayed ¶
func (d *VirtualDisk) LogReplayed() bool
LogReplayed reports whether the image's log was replayed into an in-memory overlay, in which case reads present the last committed state. The file itself is never modified.
func (*VirtualDisk) MappedBytes ¶
func (d *VirtualDisk) MappedBytes() (int64, error)
MappedBytes returns how many bytes of the disk are backed by real data, which for a sparse image is what an acquisition actually has to read.
func (*VirtualDisk) MappedBytesContext ¶ added in v0.3.0
func (d *VirtualDisk) MappedBytesContext(ctx context.Context) (int64, error)
MappedBytesContext is MappedBytes with cancellation.
func (*VirtualDisk) NeedsParent ¶
func (d *VirtualDisk) NeedsParent() bool
NeedsParent reports whether this disk is a differencing disk whose parent has not been attached yet. Reads that resolve to the parent fail with ErrParentRequired while this is true.
func (*VirtualDisk) Parent ¶
func (d *VirtualDisk) Parent() *VirtualDisk
Parent returns the attached parent disk, or nil if none is attached.
func (*VirtualDisk) ParentFilename ¶
func (d *VirtualDisk) ParentFilename() string
ParentFilename returns the parent disk path for a differencing disk.
func (*VirtualDisk) ParentIdentifier ¶
func (d *VirtualDisk) ParentIdentifier() [16]byte
ParentIdentifier returns the parent disk GUID for a VHD differencing disk. Returns a zero GUID if this is not a differencing VHD.
func (*VirtualDisk) ParentLocators ¶
func (d *VirtualDisk) ParentLocators() []types.ParentLocatorEntry
ParentLocators returns the parent locator entries recorded in a differencing disk, which may carry candidate paths to the parent image.
func (*VirtualDisk) ParentResolveError ¶
func (d *VirtualDisk) ParentResolveError() error
ParentResolveError reports why automatic parent chain resolution stopped short, or nil if the chain is complete or no resolution was attempted.
Resolution is best-effort by default, so a disk can open successfully with an incomplete chain. Reads that need the missing parent fail with ErrParentRequired rather than returning zeroes.
func (*VirtualDisk) Path ¶
func (d *VirtualDisk) Path() string
Path returns the filesystem path this disk was opened from, or "" when it was opened from a bare io.ReaderAt.
func (*VirtualDisk) Provenance ¶ added in v0.3.0
func (d *VirtualDisk) Provenance() Provenance
Provenance returns what is known about this image's origin.
It describes this disk alone. For a differencing chain, call it on each entry of Chain(): the child and its parents were often produced by different tools at different times, and flattening that into one record loses the detail that makes a chain explicable.
func (*VirtualDisk) ReadAt ¶
func (d *VirtualDisk) ReadAt(p []byte, offset int64) (int, error)
ReadAt reads len(p) bytes from the virtual disk at the given virtual offset. Implements io.ReaderAt.
Reads are clamped to the virtual disk size: a request straddling the end of the device returns the available bytes and io.EOF. Without clamping, callers would receive trailing block padding — and, for fixed VHDs, the file footer — as if it were disk content.
func (*VirtualDisk) ReadAtContext ¶ added in v0.3.0
ReadAtContext is ReadAt with cancellation.
ReadAt itself deliberately does not take a context: io.ReaderAt is what makes a *VirtualDisk composable with the rest of the standard library and with a filesystem parser layered on top, and changing its signature would break that. This is the cancellable form for callers that need one.
Cancellation is checked before the read begins and does not interrupt one in flight. A single ReadAt is bounded by the length of p; the operations worth cancelling are the ones that walk the whole disk, and those take a context of their own.
func (*VirtualDisk) SectionReader ¶ added in v0.3.0
func (d *VirtualDisk) SectionReader() *io.SectionReader
SectionReader returns an io.SectionReader over the whole decoded device.
This is the adapter that lets a *VirtualDisk be handed to code expecting a Read/Seek stream -- a hasher, an archiver, a filesystem parser -- without the caller tracking an offset. It reads the device densely, including its sparse regions, which is the right behaviour for anything that needs every byte and the wrong one for acquisition. Use Stream for that.
func (*VirtualDisk) SectorSize ¶
func (d *VirtualDisk) SectorSize() uint32
SectorSize returns the logical sector size in bytes.
func (*VirtualDisk) SetParent ¶
func (d *VirtualDisk) SetParent(parent *VirtualDisk) error
SetParent wires a parent disk for this differencing disk. After calling SetParent, reads on unallocated blocks are transparently satisfied by the parent disk. Returns an error if the disk is not a differencing disk or if the parent's virtual size doesn't match.
func (*VirtualDisk) Size ¶
func (d *VirtualDisk) Size() uint64
Size returns the total virtual disk size in bytes.
func (*VirtualDisk) Stream ¶ added in v0.3.0
func (d *VirtualDisk) Stream(ctx context.Context, opts *StreamOptions, visit func(Run) error) error
Stream walks the device and calls visit for each run, in virtual offset order, reading only what is actually backed by data.
This is the sparse-acquisition pattern: on an image whose extent map shows a few mapped runs in a large address space, streaming reads those runs and nothing else. Reading the device end to end instead would move the whole virtual size through memory, most of it zeroes the image never stored.
Runs never span an extent, so every run has one kind, one backing file and one chain index -- which is what lets a caller record provenance per run rather than per disk. A long mapped extent is split into several runs of at most opts.BufferSize bytes.
visit returning an error stops the walk and Stream returns that error. The Data slice is reused between calls; copy anything that must outlive the call.
func (*VirtualDisk) VirtualToFileOffset ¶
func (d *VirtualDisk) VirtualToFileOffset(virtualOffset int64) (fileOffset int64, mapped bool, err error)
VirtualToFileOffset resolves a virtual disk byte offset to an absolute byte offset in the backing file when a direct mapping exists.
The returned mapped flag is false for sparse/unallocated regions (virtual zeros) and for differencing disks, where a single file offset cannot express the answer because different byte ranges come from different files in the chain. Use Extents for those: it resolves per sector and reports which disk in the chain backs each run.
Offsets returned by this method are absolute from the start of the backing VHD/VHDX file, not relative to BAT/region/block structures.
func (*VirtualDisk) Warnings ¶ added in v0.3.0
func (d *VirtualDisk) Warnings() []Warning
Warnings returns every warning raised for this disk and for each parent attached below it, in chain order.
A differencing disk is only as trustworthy as the chain behind it, so a caller recording provenance wants the whole chain's caveats, not just the leaf's. Each warning carries the path of the image it concerns.
The result is a fresh slice; modifying it does not affect the disk.
type Warning ¶ added in v0.3.0
type Warning struct {
// Kind classifies the warning.
Kind WarningKind
// Path is the image the warning concerns, when it was opened from one.
Path string
// Detail is a human-readable explanation. It is meant to be shown, not
// parsed; match on Kind instead.
Detail string
}
Warning records something suspicious about an image or its parent chain that does not prevent it from being read.
Warnings exist because refusing to open a damaged image and opening it silently are both wrong for forensic use. The first loses recoverable evidence; the second presents a recovered or unverified reconstruction as an intact one. A warning lets the image be read and makes the caveat part of the record.
type WarningKind ¶ added in v0.3.0
type WarningKind string
WarningKind names a class of warning. It is a string so that a report can carry it verbatim and a consumer can match on it without depending on this package's iota ordering.
const ( // rather than the conformant trailing one, so the image is damaged even // though it opened. WarningFooterRecovered WarningKind = "footer_recovered" // WarningParentTimestampMismatch means a differencing child records a // different modification time for its parent than the parent file actually // carries. // // This is a warning rather than an error on purpose. Filesystem timestamps // do not survive a copy, so a chain moved between machines mismatches // routinely and is still the right chain. What the warning is for is the // other case: a parent that has been modified since the child was created, // which makes the reconstructed device wrong in a way nothing else detects. WarningParentTimestampMismatch WarningKind = "parent_timestamp_mismatch" // WarningParentIdentityUnverifiable means a child records no parent // identifier, so the only check its parent could be held to was virtual // size -- which any image of the same size satisfies. WarningParentIdentityUnverifiable WarningKind = "parent_identity_unverifiable" // WarningParentIdentityUnchecked means identity verification was disabled // by Options.AllowParentGUIDMismatch. WarningParentIdentityUnchecked WarningKind = "parent_identity_unchecked" )