| 1 | |
| 2 | |
| 3 | |
| 4 | package asifutil |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "encoding/xml" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "os" |
| 13 | "os/exec" |
| 14 | "strconv" |
| 15 | "strings" |
| 16 | |
| 17 | "github.com/lima-vm/lima/v2/pkg/plist" |
| 18 | ) |
| 19 | |
| 20 | |
| 21 | func NewASIF(path string, size int64) error { |
| 22 | createArgs := []string{"image", "create", "blank", "--fs", "none", "--format", "ASIF", "--size", strconv.FormatInt(size, 10), path} |
| 23 | if err := exec.CommandContext(context.Background(), "diskutil", createArgs...).Run(); err != nil { |
| 24 | return fmt.Errorf("failed to create ASIF image %#q: %w", path, err) |
| 25 | } |
| 26 | if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { |
| 27 | if _, err2 := os.Stat(path + ".asif"); !errors.Is(err2, os.ErrNotExist) { |
| 28 | |
| 29 | if err3 := os.Rename(path+".asif", path); err3 != nil { |
| 30 | return fmt.Errorf("failed to rename ASIF image from %#q to %#q: %w", path+".asif", path, err3) |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | return nil |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | func NewAttachedASIF(path string, size int64) (string, *os.File, error) { |
| 41 | if err := NewASIF(path, size); err != nil { |
| 42 | return "", nil, err |
| 43 | } |
| 44 | attachArgs := []string{"image", "attach", "--noMount", path} |
| 45 | out, err := exec.CommandContext(context.Background(), "diskutil", attachArgs...).Output() |
| 46 | if err != nil { |
| 47 | return "", nil, fmt.Errorf("failed to attach ASIF image %#q: %w", path, err) |
| 48 | } |
| 49 | devicePath := strings.TrimSpace(string(out)) |
| 50 | f, err := os.OpenFile(devicePath, os.O_RDWR, 0o644) |
| 51 | if err != nil { |
| 52 | _ = DetachASIF(devicePath) |
| 53 | return "", nil, fmt.Errorf("failed to open ASIF device %#q: %w", devicePath, err) |
| 54 | } |
| 55 | return devicePath, f, err |
| 56 | } |
| 57 | |
| 58 | |
| 59 | func DetachASIF(devicePath string) error { |
| 60 | if output, err := exec.CommandContext(context.Background(), "hdiutil", "detach", devicePath).CombinedOutput(); err != nil { |
| 61 | return fmt.Errorf("failed to detach ASIF image %#q: %w: %s", devicePath, err, output) |
| 62 | } |
| 63 | return nil |
| 64 | } |
| 65 | |
| 66 | |
| 67 | func ResizeASIF(path string, size int64) error { |
| 68 | resizeArgs := []string{"image", "resize", "--size", fmt.Sprintf("%d", size), path} |
| 69 | if output, err := exec.CommandContext(context.Background(), "diskutil", resizeArgs...).CombinedOutput(); err != nil { |
| 70 | return fmt.Errorf("failed to resize ASIF image %#q: %w: %s", path, err, output) |
| 71 | } |
| 72 | return nil |
| 73 | } |
| 74 | |
| 75 | type AttachedDisk struct { |
| 76 | Disk string |
| 77 | Container string |
| 78 | Data string |
| 79 | } |
| 80 | |
| 81 | |
| 82 | |
| 83 | func parseDiskutilImageAttachOutput(xmlStr string) (*AttachedDisk, error) { |
| 84 | var p plist.Plist |
| 85 | if err := xml.Unmarshal([]byte(xmlStr), &p); err != nil { |
| 86 | return nil, fmt.Errorf("failed to unmarshal xml: %w", err) |
| 87 | } |
| 88 | |
| 89 | if p.Value.Dict == nil { |
| 90 | return nil, errors.New("unexpected plist format: missing root dict") |
| 91 | } |
| 92 | |
| 93 | seVal, ok := p.Value.Dict["system-entities"] |
| 94 | if !ok || len(seVal.Array) == 0 { |
| 95 | return nil, errors.New("unexpected plist format: missing system-entities array") |
| 96 | } |
| 97 | |
| 98 | result := &AttachedDisk{} |
| 99 | for _, devEnt := range seVal.Array { |
| 100 | devDict := devEnt.Dict |
| 101 | if devDict == nil { |
| 102 | continue |
| 103 | } |
| 104 | devEntry, hasDevEntry := devDict["dev-entry"] |
| 105 | if !hasDevEntry || devEntry.String == nil || *devEntry.String == "" { |
| 106 | continue |
| 107 | } |
| 108 | if hint, ok := devDict["content-hint"]; ok && hint.String != nil { |
| 109 | switch *hint.String { |
| 110 | case "GUID_partition_scheme": |
| 111 | result.Disk = *devEntry.String |
| 112 | case "Apple_APFS": |
| 113 | result.Container = *devEntry.String |
| 114 | } |
| 115 | } |
| 116 | if role, ok := devDict["role"]; ok && role.String != nil && *role.String == "Data" { |
| 117 | result.Data = *devEntry.String |
| 118 | } |
| 119 | } |
| 120 | if result.Data == "" { |
| 121 | return nil, errors.New("no data device found in diskutil output") |
| 122 | } |
| 123 | |
| 124 | return result, nil |
| 125 | } |
| 126 | |
| 127 | var ErrResourceTemporarilyUnavailable = errors.New("resource temporarily unavailable") |
| 128 | |
| 129 | |
| 130 | func DiskutilImageAttachNoMount(ctx context.Context, disk string) (*AttachedDisk, error) { |
| 131 | cmd := exec.CommandContext(ctx, "diskutil", "image", "attach", "-plist", "-nomount", disk) |
| 132 | |
| 133 | cmd.Env = append(os.Environ(), "LANG=C", "LC_ALL=C") |
| 134 | var stdout, stderr bytes.Buffer |
| 135 | cmd.Stdout = &stdout |
| 136 | cmd.Stderr = &stderr |
| 137 | if err := cmd.Run(); err != nil { |
| 138 | errToWrap := err |
| 139 | if strings.Contains(stderr.String(), "Resource temporarily unavailable") { |
| 140 | errToWrap = ErrResourceTemporarilyUnavailable |
| 141 | } |
| 142 | return nil, fmt.Errorf("failed to execute %v: %w (stderr: %#q)", cmd.Args, errToWrap, stderr.String()) |
| 143 | } |
| 144 | return parseDiskutilImageAttachOutput(stdout.String()) |
| 145 | } |