| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "path/filepath" |
| 15 | |
| 16 | "golang.org/x/sys/windows" |
| 17 | ) |
| 18 | |
| 19 | func WindowsMaintenanceCommand(ctx context.Context, profile, kit, manifest string, tools bool) (*exec.Cmd, error) { |
| 20 | binding, err := LoadWindowsProfile(profile) |
| 21 | if err != nil { |
| 22 | return nil, err |
| 23 | } |
| 24 | if binding == nil { |
| 25 | return nil, errors.New("此配置尚未绑定 Windows 客机") |
| 26 | } |
| 27 | system, err := windows.GetSystemDirectory() |
| 28 | if err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | data, err := os.ReadFile(manifest) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | hash := fmt.Sprintf("%x", sha256.Sum256(data)) |
| 36 | args := []string{"-NoLogo", "-NoProfile", "-ExecutionPolicy", "RemoteSigned", "-File", filepath.Join(kit, "maintain-windows-workbench.ps1"), "-Profile", profile, "-ManifestPath", manifest, "-ManifestSHA256", hash} |
| 37 | if tools { |
| 38 | args = append(args, "-Tools") |
| 39 | } |
| 40 | return exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), args...), nil |
| 41 | } |
| 42 | |
| 43 | |
| 44 | |
| 45 | func RepairWindowsHostManager(ctx context.Context, profile, kit string, stdout, stderr io.Writer) error { |
| 46 | manifest, err := RequiredNativeComponents(kit, Windows11) |
| 47 | if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | file, err := os.CreateTemp(profile, "native-host-repair-*.json") |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | defer os.Remove(file.Name()) |
| 55 | err = json.NewEncoder(file).Encode(manifest) |
| 56 | if err = errors.Join(err, file.Close()); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | command, err := WindowsMaintenanceCommand(ctx, profile, kit, file.Name(), false) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | command.Args = append(command.Args, "-HostOnly") |
| 64 | command.Stdout, command.Stderr = stdout, stderr |
| 65 | if err := command.Run(); err != nil { |
| 66 | if ctx.Err() != nil { |
| 67 | return ctx.Err() |
| 68 | } |
| 69 | return err |
| 70 | } |
| 71 | return nil |
| 72 | } |