418 lines
11 KiB
Go
418 lines
11 KiB
Go
//go:build windows
|
|
|
|
package host
|
|
|
|
import (
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"syscall"
|
|
"unsafe"
|
|
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
var (
|
|
procFindFirstVolumeW = kernel32.NewProc("FindFirstVolumeW")
|
|
procFindNextVolumeW = kernel32.NewProc("FindNextVolumeW")
|
|
procFindVolumeClose = kernel32.NewProc("FindVolumeClose")
|
|
procGetVolumeInformationW = kernel32.NewProc("GetVolumeInformationW")
|
|
procGetVolumePathNameW = kernel32.NewProc("GetVolumePathNameW")
|
|
)
|
|
|
|
const (
|
|
ioctlVolumeGetVolumeDiskExtents = 0x00560000
|
|
ioctlDiskGetDriveLayoutEx = 0x00070050
|
|
ioctlDiskGetLengthInfo = 0x0007405C
|
|
ioctlDiskGetDiskAttributes = 0x000700F0
|
|
diskAttributeOffline = 0x1
|
|
diskAttributeReadOnly = 0x2
|
|
)
|
|
|
|
// ListRawPartitions enumerates Windows raw partitions and offline disks that
|
|
// are safe to pass through to a VM (excluding OS disk, dataRoot disk, EFI/MSR/Recovery,
|
|
// mounted volumes, and Windows filesystems).
|
|
func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) {
|
|
excluded := excludedHostDiskNumbers(dataRoot)
|
|
extentsByDisk, err := indexVolumesByExtent()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
maxSeenDisk := maxDiskNumber(excluded, extentsByDisk)
|
|
var observations []RawVolumeObservation
|
|
|
|
consecutiveMisses := 0
|
|
for diskNum := uint32(0); diskNum < 512; diskNum++ {
|
|
if excluded[diskNum] {
|
|
consecutiveMisses = 0
|
|
continue
|
|
}
|
|
offline, readOnly, ok := queryDiskAttributes(diskNum)
|
|
if !ok {
|
|
consecutiveMisses++
|
|
if diskNum >= 31 && diskNum >= maxSeenDisk && consecutiveMisses >= 32 {
|
|
break
|
|
}
|
|
continue
|
|
}
|
|
consecutiveMisses = 0
|
|
observations = appendDiskObservations(observations, diskNum, offline, readOnly, extentsByDisk[diskNum])
|
|
}
|
|
|
|
return filterRawPartitionCandidates(observations, excluded), nil
|
|
}
|
|
|
|
func maxDiskNumber(excluded map[uint32]bool, extents map[uint32][]indexedVolumeExtent) uint32 {
|
|
var maxDisk uint32
|
|
for d := range excluded {
|
|
if d > maxDisk {
|
|
maxDisk = d
|
|
}
|
|
}
|
|
for d := range extents {
|
|
if d > maxDisk {
|
|
maxDisk = d
|
|
}
|
|
}
|
|
return maxDisk
|
|
}
|
|
|
|
func appendDiskObservations(observations []RawVolumeObservation, diskNum uint32, offline, readOnly bool, extents []indexedVolumeExtent) []RawVolumeObservation {
|
|
dev := fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum)
|
|
if offline {
|
|
sizeBytes, _ := queryDeviceLengthBytes(dev)
|
|
if sizeBytes > 0 {
|
|
observations = append(observations, RawVolumeObservation{
|
|
DevicePath: dev,
|
|
DiskNumber: diskNum,
|
|
SizeBytes: sizeBytes,
|
|
Offline: true,
|
|
ReadOnly: readOnly,
|
|
})
|
|
}
|
|
return observations
|
|
}
|
|
for _, p := range queryDiskPartitions(diskNum) {
|
|
if p.number == 0 || p.length == 0 {
|
|
continue
|
|
}
|
|
obs := RawVolumeObservation{
|
|
DevicePath: fmt.Sprintf(`\\.\Harddisk%dPartition%d`, diskNum, p.number),
|
|
DiskNumber: diskNum,
|
|
PartitionNumber: p.number,
|
|
SizeBytes: p.length,
|
|
PartitionTypeGUID: p.typeGUID,
|
|
ReadOnly: readOnly,
|
|
}
|
|
applyPartitionExtentMatches(&obs, p.offset, p.length, extents)
|
|
if exact, ok := queryDeviceLengthBytes(obs.DevicePath); ok && exact > 0 {
|
|
obs.SizeBytes = exact
|
|
}
|
|
observations = append(observations, obs)
|
|
}
|
|
return observations
|
|
}
|
|
|
|
type volumeDiskExtent struct {
|
|
diskNumber uint32
|
|
startingOffset int64
|
|
extentLength uint64
|
|
}
|
|
|
|
type diskPartitionEntry struct {
|
|
number uint32
|
|
offset int64
|
|
length uint64
|
|
typeGUID string
|
|
}
|
|
|
|
func indexVolumesByExtent() (map[uint32][]indexedVolumeExtent, error) {
|
|
out := map[uint32][]indexedVolumeExtent{}
|
|
volNames, err := enumVolumeNames()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, volWithSlash := range volNames {
|
|
volDev := strings.TrimSuffix(volWithSlash, `\`)
|
|
extents, ok := queryVolumeDiskExtents(volDev)
|
|
if !ok {
|
|
continue
|
|
}
|
|
hasMounts, mountErr := volumeHasMountPoints(volWithSlash)
|
|
fsName, fsKnown := queryVolumeFilesystem(volWithSlash)
|
|
multi := len(extents) > 1
|
|
occupied := multi || mountErr != nil || hasMounts || !fsKnown
|
|
for _, ext := range extents {
|
|
end := ext.startingOffset + int64(ext.extentLength)
|
|
if end <= ext.startingOffset {
|
|
end = 1<<63 - 1
|
|
}
|
|
out[ext.diskNumber] = append(out[ext.diskNumber], indexedVolumeExtent{
|
|
start: ext.startingOffset,
|
|
end: end,
|
|
volDev: volDev,
|
|
multiExtent: multi,
|
|
hasMountPoints: hasMounts,
|
|
filesystem: fsName,
|
|
occupied: occupied,
|
|
})
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func excludedHostDiskNumbers(dataRoot string) map[uint32]bool {
|
|
excluded := map[uint32]bool{}
|
|
addPath := func(p string) {
|
|
p = strings.TrimSpace(p)
|
|
if p == "" {
|
|
return
|
|
}
|
|
volDev := volumeDeviceForPath(p)
|
|
if volDev == "" {
|
|
return
|
|
}
|
|
if extents, ok := queryVolumeDiskExtents(volDev); ok {
|
|
for _, ext := range extents {
|
|
excluded[ext.diskNumber] = true
|
|
}
|
|
}
|
|
}
|
|
if sysRoot := os.Getenv("SystemRoot"); sysRoot != "" {
|
|
addPath(sysRoot)
|
|
} else if sysDrive := os.Getenv("SystemDrive"); sysDrive != "" {
|
|
addPath(sysDrive + `\`)
|
|
}
|
|
addPath(dataRoot)
|
|
return excluded
|
|
}
|
|
|
|
func volumeDeviceForPath(path string) string {
|
|
p, err := syscall.UTF16PtrFromString(path)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
mount := make([]uint16, 32768)
|
|
r, _, _ := procGetVolumePathNameW.Call(uintptr(unsafe.Pointer(p)), uintptr(unsafe.Pointer(&mount[0])), uintptr(len(mount)))
|
|
if r == 0 {
|
|
return ""
|
|
}
|
|
var vol [64]uint16
|
|
r2, _, _ := procGetVolumeNameForVolumeMountPointW.Call(uintptr(unsafe.Pointer(&mount[0])), uintptr(unsafe.Pointer(&vol[0])), uintptr(len(vol)))
|
|
if r2 == 0 {
|
|
return ""
|
|
}
|
|
return strings.TrimSuffix(syscall.UTF16ToString(vol[:]), `\`)
|
|
}
|
|
|
|
func enumVolumeNames() ([]string, error) {
|
|
buf := make([]uint16, 32768)
|
|
h, _, err := procFindFirstVolumeW.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
|
if h == uintptr(windows.InvalidHandle) {
|
|
return nil, err
|
|
}
|
|
defer procFindVolumeClose.Call(h)
|
|
|
|
var out []string
|
|
for {
|
|
name := syscall.UTF16ToString(buf)
|
|
if name != "" {
|
|
out = append(out, name)
|
|
}
|
|
r, _, _ := procFindNextVolumeW.Call(h, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
|
if r == 0 {
|
|
break
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func volumeHasMountPoints(volWithSlash string) (bool, error) {
|
|
p, err := windows.UTF16PtrFromString(volWithSlash)
|
|
if err != nil {
|
|
return true, err
|
|
}
|
|
buf := make([]uint16, 1024)
|
|
var needed uint32
|
|
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
|
|
if needed > uint32(len(buf)) {
|
|
buf = make([]uint16, needed)
|
|
if err := windows.GetVolumePathNamesForVolumeName(p, &buf[0], uint32(len(buf)), &needed); err != nil {
|
|
return true, err
|
|
}
|
|
} else {
|
|
return true, err
|
|
}
|
|
}
|
|
return len(buf) > 0 && buf[0] != 0, nil
|
|
}
|
|
|
|
func queryVolumeFilesystem(volWithSlash string) (string, bool) {
|
|
p, err := syscall.UTF16PtrFromString(volWithSlash)
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
fsBuf := make([]uint16, 64)
|
|
r, _, callErr := procGetVolumeInformationW.Call(
|
|
uintptr(unsafe.Pointer(p)),
|
|
0, 0,
|
|
0, 0, 0,
|
|
uintptr(unsafe.Pointer(&fsBuf[0])), uintptr(len(fsBuf)),
|
|
)
|
|
if r == 0 {
|
|
// Unformatted / foreign volumes (e.g. APFS) yield ERROR_UNRECOGNIZED_VOLUME (1005).
|
|
// Any other probe error (e.g. ERROR_ACCESS_DENIED) is treated fail-closed by caller.
|
|
if errors.Is(callErr, windows.ERROR_UNRECOGNIZED_VOLUME) {
|
|
return "", true
|
|
}
|
|
return "", false
|
|
}
|
|
return syscall.UTF16ToString(fsBuf), true
|
|
}
|
|
|
|
func openDeviceMeta(devicePath string, access uint32) (windows.Handle, error) {
|
|
p, err := windows.UTF16PtrFromString(devicePath)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return windows.CreateFile(
|
|
p,
|
|
access,
|
|
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,
|
|
nil,
|
|
windows.OPEN_EXISTING,
|
|
0,
|
|
0,
|
|
)
|
|
}
|
|
|
|
func queryVolumeDiskExtents(volDev string) ([]volumeDiskExtent, bool) {
|
|
h, err := openDeviceMeta(volDev, 0)
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
defer windows.CloseHandle(h)
|
|
|
|
var buf []byte
|
|
var n uint32
|
|
for size := 256; size <= 65536; size *= 2 {
|
|
buf = make([]byte, size)
|
|
err = windows.DeviceIoControl(h, ioctlVolumeGetVolumeDiskExtents, nil, 0, &buf[0], uint32(len(buf)), &n, nil)
|
|
if err == nil {
|
|
break
|
|
}
|
|
if !errors.Is(err, windows.ERROR_MORE_DATA) {
|
|
return nil, false
|
|
}
|
|
}
|
|
if err != nil || n < 32 {
|
|
return nil, false
|
|
}
|
|
count := binary.LittleEndian.Uint32(buf[0:4])
|
|
var out []volumeDiskExtent
|
|
for i := uint32(0); i < count; i++ {
|
|
off := 8 + int(i)*24
|
|
if off+24 > int(n) {
|
|
break
|
|
}
|
|
out = append(out, volumeDiskExtent{
|
|
diskNumber: binary.LittleEndian.Uint32(buf[off : off+4]),
|
|
startingOffset: int64(binary.LittleEndian.Uint64(buf[off+8 : off+16])),
|
|
extentLength: binary.LittleEndian.Uint64(buf[off+16 : off+24]),
|
|
})
|
|
}
|
|
return out, len(out) > 0
|
|
}
|
|
|
|
func queryDeviceLengthBytes(devPath string) (uint64, bool) {
|
|
h, err := openDeviceMeta(devPath, windows.GENERIC_READ)
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
defer windows.CloseHandle(h)
|
|
var out [8]byte
|
|
var n uint32
|
|
if err := windows.DeviceIoControl(h, ioctlDiskGetLengthInfo, nil, 0, &out[0], 8, &n, nil); err != nil || n < 8 {
|
|
return 0, false
|
|
}
|
|
return binary.LittleEndian.Uint64(out[:]), true
|
|
}
|
|
|
|
func queryDiskAttributes(diskNum uint32) (offline, readOnly, ok bool) {
|
|
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), 0)
|
|
if err != nil {
|
|
return false, false, false
|
|
}
|
|
defer windows.CloseHandle(h)
|
|
var out [16]byte
|
|
var n uint32
|
|
if err := windows.DeviceIoControl(h, ioctlDiskGetDiskAttributes, nil, 0, &out[0], uint32(len(out)), &n, nil); err != nil || n < 16 {
|
|
return false, false, false
|
|
}
|
|
attrs := binary.LittleEndian.Uint64(out[8:16])
|
|
return (attrs & diskAttributeOffline) != 0, (attrs & diskAttributeReadOnly) != 0, true
|
|
}
|
|
|
|
func queryDiskPartitions(diskNum uint32) []diskPartitionEntry {
|
|
h, err := openDeviceMeta(fmt.Sprintf(`\\.\PhysicalDrive%d`, diskNum), windows.GENERIC_READ)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer windows.CloseHandle(h)
|
|
// Accommodate up to 128 GPT partitions: 48 + 128*144 = 18480 bytes.
|
|
buf := make([]byte, 48+128*144)
|
|
var n uint32
|
|
if err := windows.DeviceIoControl(h, ioctlDiskGetDriveLayoutEx, nil, 0, &buf[0], uint32(len(buf)), &n, nil); err != nil || n < 48 {
|
|
return nil
|
|
}
|
|
style := binary.LittleEndian.Uint32(buf[0:4])
|
|
if style != 0 && style != 1 {
|
|
return nil
|
|
}
|
|
count := binary.LittleEndian.Uint32(buf[4:8])
|
|
var out []diskPartitionEntry
|
|
// Per winioctl.h (DRIVE_LAYOUT_INFORMATION_EX), the Mbr/Gpt union is padded to
|
|
// 40 bytes (DRIVE_LAYOUT_INFORMATION_GPT), so PartitionEntry[0] starts at byte 48
|
|
// for both MBR (style=0) and GPT (style=1).
|
|
for i := uint32(0); i < count; i++ {
|
|
off := 48 + int(i)*144
|
|
if off+144 > int(n) {
|
|
break
|
|
}
|
|
entryStyle := binary.LittleEndian.Uint32(buf[off : off+4])
|
|
if style == 0 && entryStyle == 0 {
|
|
mbrType := buf[off+32]
|
|
if mbrType == 0x00 || mbrType == 0x05 || mbrType == 0x0F {
|
|
continue
|
|
}
|
|
}
|
|
startOff := int64(binary.LittleEndian.Uint64(buf[off+8 : off+16]))
|
|
length := binary.LittleEndian.Uint64(buf[off+16 : off+24])
|
|
num := binary.LittleEndian.Uint32(buf[off+24 : off+28])
|
|
guid := ""
|
|
if style == 1 && entryStyle == 1 {
|
|
guid = formatWinGUID(buf[off+32 : off+48])
|
|
}
|
|
out = append(out, diskPartitionEntry{
|
|
number: num,
|
|
offset: startOff,
|
|
length: length,
|
|
typeGUID: guid,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
func formatWinGUID(b []byte) string {
|
|
if len(b) < 16 {
|
|
return ""
|
|
}
|
|
d1 := binary.LittleEndian.Uint32(b[0:4])
|
|
d2 := binary.LittleEndian.Uint16(b[4:6])
|
|
d3 := binary.LittleEndian.Uint16(b[6:8])
|
|
return fmt.Sprintf("%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
|
|
d1, d2, d3, b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15])
|
|
}
|