| 1 | |
| 2 | |
| 3 | |
| 4 | package osutil |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/xml" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "runtime" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | |
| 19 | "github.com/sirupsen/logrus" |
| 20 | |
| 21 | "github.com/lima-vm/lima/v2/pkg/plist" |
| 22 | ) |
| 23 | |
| 24 | var MachineID = sync.OnceValue(func() string { |
| 25 | x, err := machineID(context.Background()) |
| 26 | if err == nil && x != "" { |
| 27 | return x |
| 28 | } |
| 29 | logrus.WithError(err).Debug("failed to get machine ID, falling back to use hostname instead") |
| 30 | hostname, err := os.Hostname() |
| 31 | if err != nil { |
| 32 | panic(fmt.Errorf("failed to get hostname: %w", err)) |
| 33 | } |
| 34 | return hostname |
| 35 | }) |
| 36 | |
| 37 | func machineID(ctx context.Context) (string, error) { |
| 38 | if runtime.GOOS == "darwin" { |
| 39 | ioPlatformExpertDeviceCmd := exec.CommandContext(ctx, "/usr/sbin/ioreg", "-a", "-d2", "-c", "IOPlatformExpertDevice") |
| 40 | ioPlatformExpertDevice, err := ioPlatformExpertDeviceCmd.CombinedOutput() |
| 41 | if err != nil { |
| 42 | return "", err |
| 43 | } |
| 44 | return parseIOPlatformUUIDFromIOPlatformExpertDevice(bytes.NewReader(ioPlatformExpertDevice)) |
| 45 | } |
| 46 | |
| 47 | candidates := []string{ |
| 48 | "/etc/machine-id", |
| 49 | "/var/lib/dbus/machine-id", |
| 50 | |
| 51 | } |
| 52 | for _, f := range candidates { |
| 53 | b, err := os.ReadFile(f) |
| 54 | if err == nil { |
| 55 | return strings.TrimSpace(string(b)), nil |
| 56 | } |
| 57 | } |
| 58 | return "", fmt.Errorf("no machine-id found, tried %v", candidates) |
| 59 | } |
| 60 | |
| 61 | func parseIOPlatformUUIDFromIOPlatformExpertDevice(r io.Reader) (string, error) { |
| 62 | var p plist.Plist |
| 63 | dec := xml.NewDecoder(r) |
| 64 | if err := dec.Decode(&p); err != nil { |
| 65 | return "", err |
| 66 | } |
| 67 | if p.Value.Dict == nil { |
| 68 | return "", errors.New("invalid plist: top-level value is not a dict") |
| 69 | } |
| 70 | ioRegistryEntryChildren, ok := p.Value.Dict["IORegistryEntryChildren"] |
| 71 | if !ok || ioRegistryEntryChildren.Array == nil || len(ioRegistryEntryChildren.Array) == 0 { |
| 72 | return "", errors.New("invalid plist: IORegistryEntryChildren not found or empty") |
| 73 | } |
| 74 | for _, child := range ioRegistryEntryChildren.Array { |
| 75 | if child.Dict == nil { |
| 76 | continue |
| 77 | } |
| 78 | ioPlatformUUID, ok := child.Dict["IOPlatformUUID"] |
| 79 | if !ok || ioPlatformUUID.String == nil { |
| 80 | continue |
| 81 | } |
| 82 | return *ioPlatformUUID.String, nil |
| 83 | } |
| 84 | |
| 85 | return "", errors.New("invalid plist: IOPlatformUUID not found in any child of IORegistryEntryChildren") |
| 86 | } |