| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "unsafe" |
| 13 | |
| 14 | "golang.org/x/sys/windows" |
| 15 | ) |
| 16 | |
| 17 | var storageVirtualDiskDLL = windows.NewLazySystemDLL("virtdisk.dll") |
| 18 | |
| 19 | type storageVirtualDiskType struct { |
| 20 | Device uint32 |
| 21 | Vendor windows.GUID |
| 22 | } |
| 23 | |
| 24 | var storageVHDXType = storageVirtualDiskType{ |
| 25 | Device: 3, |
| 26 | Vendor: windows.GUID{Data1: 0xec984aec, Data2: 0xa0f9, Data3: 0x47e9, Data4: [8]byte{0x90, 0x1f, 0x71, 0x41, 0x5a, 0x66, 0x34, 0x5b}}, |
| 27 | } |
| 28 | |
| 29 | |
| 30 | type storageVirtualDiskCreate struct { |
| 31 | Version uint32 |
| 32 | _ uint32 |
| 33 | Identifier windows.GUID |
| 34 | MaximumSize uint64 |
| 35 | BlockSize uint32 |
| 36 | SectorSize uint32 |
| 37 | PhysicalSector uint32 |
| 38 | ParentPath *uint16 |
| 39 | SourcePath *uint16 |
| 40 | OpenFlags uint32 |
| 41 | ParentType storageVirtualDiskType |
| 42 | SourceType storageVirtualDiskType |
| 43 | Resiliency windows.GUID |
| 44 | } |
| 45 | |
| 46 | type storageVirtualDiskMetadata struct { |
| 47 | Subtype uint32 |
| 48 | Identifier windows.GUID |
| 49 | VirtualSize uint64 |
| 50 | BlockSize uint32 |
| 51 | SectorSize uint32 |
| 52 | PhysicalSector uint32 |
| 53 | } |
| 54 | |
| 55 | func readWindowsStorageDisk(path string) (storageVirtualDiskMetadata, error) { |
| 56 | var metadata storageVirtualDiskMetadata |
| 57 | name, err := windows.UTF16PtrFromString(path) |
| 58 | if err != nil { |
| 59 | return metadata, err |
| 60 | } |
| 61 | parameters := struct { |
| 62 | Version uint32 |
| 63 | InfoOnly int32 |
| 64 | ReadOnly int32 |
| 65 | Resiliency windows.GUID |
| 66 | }{Version: 2, InfoOnly: 1, ReadOnly: 1} |
| 67 | var handle windows.Handle |
| 68 | status, _, _ := storageVirtualDiskDLL.NewProc("OpenVirtualDisk").Call( |
| 69 | uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0, |
| 70 | uintptr(unsafe.Pointer(¶meters)), uintptr(unsafe.Pointer(&handle))) |
| 71 | runtime.KeepAlive(name) |
| 72 | if status != 0 { |
| 73 | return metadata, fmt.Errorf("读取 Windows 客机磁盘失败:%w", windows.Errno(status)) |
| 74 | } |
| 75 | defer windows.CloseHandle(handle) |
| 76 | for _, version := range []uint32{1, 2, 7, 10} { |
| 77 | information := struct { |
| 78 | Version uint32 |
| 79 | _ uint32 |
| 80 | Data [4]uint64 |
| 81 | }{Version: version} |
| 82 | size, used := uint32(unsafe.Sizeof(information)), uint32(0) |
| 83 | status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskInformation").Call( |
| 84 | uintptr(handle), uintptr(unsafe.Pointer(&size)), uintptr(unsafe.Pointer(&information)), uintptr(unsafe.Pointer(&used))) |
| 85 | if status != 0 { |
| 86 | return metadata, fmt.Errorf("读取 Windows 客机磁盘属性失败:%w", windows.Errno(status)) |
| 87 | } |
| 88 | switch version { |
| 89 | case 1: |
| 90 | metadata.VirtualSize = information.Data[0] |
| 91 | metadata.BlockSize = uint32(information.Data[2]) |
| 92 | metadata.SectorSize = uint32(information.Data[2] >> 32) |
| 93 | case 2: |
| 94 | metadata.Identifier = *(*windows.GUID)(unsafe.Pointer(&information.Data[0])) |
| 95 | case 7: |
| 96 | metadata.Subtype = uint32(information.Data[0]) |
| 97 | case 10: |
| 98 | metadata.PhysicalSector = uint32(information.Data[0]) |
| 99 | } |
| 100 | } |
| 101 | return metadata, nil |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | func createWindowsStorageDisk(ctx context.Context, path string, parameters *storageVirtualDiskCreate, flags uint32) (err error) { |
| 107 | if err := ctx.Err(); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | name, err := windows.UTF16PtrFromString(path) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | event, err := windows.CreateEvent(nil, 1, 0, nil) |
| 115 | if err != nil { |
| 116 | return err |
| 117 | } |
| 118 | defer windows.CloseHandle(event) |
| 119 | overlapped := &windows.Overlapped{HEvent: event} |
| 120 | var pinned runtime.Pinner |
| 121 | pinned.Pin(overlapped) |
| 122 | pinned.Pin(parameters) |
| 123 | pinned.Pin(name) |
| 124 | if parameters.SourcePath != nil { |
| 125 | pinned.Pin(parameters.SourcePath) |
| 126 | } |
| 127 | if parameters.ParentPath != nil { |
| 128 | pinned.Pin(parameters.ParentPath) |
| 129 | } |
| 130 | defer pinned.Unpin() |
| 131 | var handle windows.Handle |
| 132 | status, _, _ := storageVirtualDiskDLL.NewProc("CreateVirtualDisk").Call( |
| 133 | uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0, uintptr(flags), 0, |
| 134 | uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&handle))) |
| 135 | if handle != 0 && handle != windows.InvalidHandle { |
| 136 | defer func() { err = errors.Join(err, windows.CloseHandle(handle)) }() |
| 137 | } |
| 138 | if status != 0 && status != uintptr(windows.ERROR_IO_PENDING) { |
| 139 | return fmt.Errorf("创建独立 Windows 客机磁盘失败:%w", windows.Errno(status)) |
| 140 | } |
| 141 | if status == 0 { |
| 142 | return ctx.Err() |
| 143 | } |
| 144 | cancelDone := make(chan struct{}) |
| 145 | var cancelErr error |
| 146 | stopCancel := context.AfterFunc(ctx, func() { |
| 147 | cancelErr = windows.CancelIoEx(handle, overlapped) |
| 148 | close(cancelDone) |
| 149 | }) |
| 150 | wait, waitErr := windows.WaitForSingleObject(event, windows.INFINITE) |
| 151 | if !stopCancel() { |
| 152 | <-cancelDone |
| 153 | } |
| 154 | if waitErr != nil || wait != windows.WAIT_OBJECT_0 { |
| 155 | |
| 156 | _ = windows.CancelIoEx(handle, overlapped) |
| 157 | var transferred uint32 |
| 158 | drainErr := windows.GetOverlappedResult(handle, overlapped, &transferred, true) |
| 159 | return errors.Join(fmt.Errorf("等待 Windows 磁盘复制完成失败 (%d)", wait), waitErr, drainErr) |
| 160 | } |
| 161 | if errors.Is(cancelErr, windows.ERROR_NOT_FOUND) { |
| 162 | cancelErr = nil |
| 163 | } |
| 164 | if err := ctx.Err(); err != nil { |
| 165 | return errors.Join(err, cancelErr) |
| 166 | } |
| 167 | progress := struct { |
| 168 | Status uint32 |
| 169 | Current, Total uint64 |
| 170 | }{} |
| 171 | status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskOperationProgress").Call( |
| 172 | uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&progress))) |
| 173 | if status != 0 { |
| 174 | return fmt.Errorf("查询 Windows 磁盘复制结果失败:%w", windows.Errno(status)) |
| 175 | } |
| 176 | if progress.Status != 0 { |
| 177 | return fmt.Errorf("Windows 磁盘复制失败:%w", windows.Errno(progress.Status)) |
| 178 | } |
| 179 | return nil |
| 180 | } |
| 181 | |
| 182 | func prepareWindowsStorageDisk(ctx context.Context, source, copied string) (err error) { |
| 183 | if err := ctx.Err(); err != nil { |
| 184 | return err |
| 185 | } |
| 186 | before, err := readWindowsStorageDisk(source) |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | if before.Subtype == 2 || before.Subtype == 3 { |
| 191 | return nil |
| 192 | } |
| 193 | if before.Subtype != 4 { |
| 194 | return fmt.Errorf("Windows 客机磁盘类型无效 (%d)", before.Subtype) |
| 195 | } |
| 196 | original, err := os.Stat(source) |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | destination, err := os.Stat(copied) |
| 201 | if err != nil { |
| 202 | return err |
| 203 | } |
| 204 | if os.SameFile(original, destination) { |
| 205 | return errors.New("独立磁盘副本与原磁盘必须使用不同文件") |
| 206 | } |
| 207 | folder, err := os.MkdirTemp(filepath.Dir(copied), ".windows-disk-*") |
| 208 | if err != nil { |
| 209 | return err |
| 210 | } |
| 211 | defer func() { err = errors.Join(err, os.RemoveAll(folder)) }() |
| 212 | path := filepath.Join(folder, "disk.vhdx") |
| 213 | name, err := windows.UTF16PtrFromString(source) |
| 214 | if err != nil { |
| 215 | return err |
| 216 | } |
| 217 | parameters := storageVirtualDiskCreate{ |
| 218 | Version: 2, Identifier: before.Identifier, BlockSize: before.BlockSize, |
| 219 | SectorSize: before.SectorSize, PhysicalSector: before.PhysicalSector, |
| 220 | SourcePath: name, SourceType: storageVHDXType, |
| 221 | } |
| 222 | if err := createWindowsStorageDisk(ctx, path, ¶meters, 0); err != nil { |
| 223 | return err |
| 224 | } |
| 225 | after, err := readWindowsStorageDisk(path) |
| 226 | if err != nil { |
| 227 | return err |
| 228 | } |
| 229 | expected := before |
| 230 | expected.Subtype = 3 |
| 231 | if after != expected { |
| 232 | return errors.New("独立磁盘副本的标识或磁盘参数不一致") |
| 233 | } |
| 234 | if err := ctx.Err(); err != nil { |
| 235 | return err |
| 236 | } |
| 237 | from, err := windows.UTF16PtrFromString(path) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | to, err := windows.UTF16PtrFromString(copied) |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) |
| 246 | } |