|
| 1 | +package vzvmnetshared |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + _ "embed" |
| 7 | + "fmt" |
| 8 | + "net/netip" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "path/filepath" |
| 12 | + "text/template" |
| 13 | + |
| 14 | + "github.com/Code-Hex/vz/v3" |
| 15 | + "github.com/Code-Hex/vz/v3/pkg/xpc" |
| 16 | + |
| 17 | + "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" |
| 18 | +) |
| 19 | + |
| 20 | +//go:embed io.lima-vm.vz.vmnet.shared.plist |
| 21 | +var launchdTemplate string |
| 22 | + |
| 23 | +const ( |
| 24 | + launchdLabel = "io.lima-vm.vz.vmnet.shared" |
| 25 | + MachServiceName = launchdLabel + ".subnet" |
| 26 | +) |
| 27 | + |
| 28 | +// RegisterMachService registers the "io.lima-vm.vz.vmnet.shared" launchd service. |
| 29 | +// |
| 30 | +// - It creates a launchd plist under ~/Library/LaunchAgents and bootstraps it. |
| 31 | +// - The mach service "io.lima-vm.vz.vmnet.shared.subnet" is registered. |
| 32 | +// - The working directory is $LIMA_HOME/_networks/vz-vmnet-shared. |
| 33 | +// - It also creates a shell script named "io.lima-vm.vz.vmnet.shared.sh" that runs |
| 34 | +// "limactl vz-vmnet-shared" to avoid launching "limactl" directly from launchd. |
| 35 | +// macOS System Settings (General > Login Items & Extensions) shows the first |
| 36 | +// element of ProgramArguments as the login item name; using a shell script with |
| 37 | +// a fixed filename makes the item easier to identify. |
| 38 | +func RegisterMachService(ctx context.Context) error { |
| 39 | + executablePath, workDir, scriptPath, launchdPlistPath, err := relatedPaths(launchdLabel) |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + |
| 44 | + // Create a shell script that runs "limactl vz-vmnet-shared" |
| 45 | + scriptContent := "#!/bin/sh\nexec " + executablePath + " vz-vmnet-shared --mach-service='" + MachServiceName + "' \"$@\"" |
| 46 | + if err := os.WriteFile(scriptPath, []byte(scriptContent), 0o755); err != nil { |
| 47 | + return fmt.Errorf("failed to write %q launch script: %w", scriptPath, err) |
| 48 | + } |
| 49 | + |
| 50 | + // Create launchd plist |
| 51 | + params := struct { |
| 52 | + Label string |
| 53 | + ProgramArguments []string |
| 54 | + WorkingDirectory string |
| 55 | + MachServices []string |
| 56 | + }{ |
| 57 | + Label: launchdLabel, |
| 58 | + ProgramArguments: []string{scriptPath}, |
| 59 | + WorkingDirectory: workDir, |
| 60 | + MachServices: []string{MachServiceName}, |
| 61 | + } |
| 62 | + template, err := template.New("plist").Parse(launchdTemplate) |
| 63 | + if err != nil { |
| 64 | + return fmt.Errorf("failed to parse launchd plist template: %w", err) |
| 65 | + } |
| 66 | + var b bytes.Buffer |
| 67 | + if err := template.Execute(&b, params); err != nil { |
| 68 | + return fmt.Errorf("failed to execute launchd plist template: %w", err) |
| 69 | + } |
| 70 | + if err := os.WriteFile(launchdPlistPath, b.Bytes(), 0o644); err != nil { |
| 71 | + return fmt.Errorf("failed to write launchd plist %q: %w", launchdPlistPath, err) |
| 72 | + } |
| 73 | + |
| 74 | + // Bootstrap launchd plist |
| 75 | + cmd := exec.CommandContext(ctx, "launchctl", "bootstrap", serviceDomain(), launchdPlistPath) |
| 76 | + if err := cmd.Run(); err != nil { |
| 77 | + return fmt.Errorf("failed to execute bootstrap: %v: %w", cmd.Args, err) |
| 78 | + } |
| 79 | + return nil |
| 80 | +} |
| 81 | + |
| 82 | +// UnregisterMachService unregisters the "io.lima-vm.vz.vmnet.shared" launchd service. |
| 83 | +// |
| 84 | +// - It unbootstraps the launchd plist. |
| 85 | +// - It removes the launchd plist file under ~/Library/LaunchAgents. |
| 86 | +// - It removes the shell script used to launch "limactl vz-vmnet-shared". |
| 87 | +func UnregisterMachService(ctx context.Context) error { |
| 88 | + serviceTarget := serviceTarget(launchdLabel) |
| 89 | + cmd := exec.CommandContext(ctx, "launchctl", "bootout", serviceTarget) |
| 90 | + if err := cmd.Run(); err != nil { |
| 91 | + return fmt.Errorf("failed to execute bootout: %v: %w", cmd.Args, err) |
| 92 | + } |
| 93 | + _, _, scriptPath, launchdPlistPath, err := relatedPaths(launchdLabel) |
| 94 | + if err != nil { |
| 95 | + return err |
| 96 | + } |
| 97 | + if err := os.Remove(launchdPlistPath); err != nil && !os.IsNotExist(err) { |
| 98 | + return fmt.Errorf("failed to remove launchd plist %q: %w", launchdPlistPath, err) |
| 99 | + } |
| 100 | + if err := os.Remove(scriptPath); err != nil && !os.IsNotExist(err) { |
| 101 | + return fmt.Errorf("failed to remove launch script file %q: %w", scriptPath, err) |
| 102 | + } |
| 103 | + return nil |
| 104 | +} |
| 105 | + |
| 106 | +func relatedPaths(launchdLabel string) (executablePath, workDir, scriptPath, plistPath string, err error) { |
| 107 | + executablePath, err = os.Executable() |
| 108 | + if err != nil { |
| 109 | + return "", "", "", "", fmt.Errorf("failed to get executable path: %w", err) |
| 110 | + } |
| 111 | + networksDir, err := dirnames.LimaNetworksDir() |
| 112 | + if err != nil { |
| 113 | + return "", "", "", "", fmt.Errorf("failed to get Lima networks directory: %w", err) |
| 114 | + } |
| 115 | + // Working directory |
| 116 | + workDir = filepath.Join(networksDir, "vz-vmnet-shared") |
| 117 | + if err := os.MkdirAll(workDir, 0o755); err != nil { |
| 118 | + return "", "", "", "", fmt.Errorf("failed to create working directory %q: %w", workDir, err) |
| 119 | + } |
| 120 | + // Shell script path |
| 121 | + scriptPath = filepath.Join(workDir, launchdLabel+".sh") |
| 122 | + // Launchd plist path |
| 123 | + userHomeDir, err := os.UserHomeDir() |
| 124 | + if err != nil { |
| 125 | + return "", "", "", "", fmt.Errorf("failed to get user home directory: %w", err) |
| 126 | + } |
| 127 | + plistPath = filepath.Join(userHomeDir, "Library", "LaunchAgents", launchdLabel+".plist") |
| 128 | + return executablePath, workDir, scriptPath, plistPath, nil |
| 129 | +} |
| 130 | + |
| 131 | +func serviceDomain() string { |
| 132 | + return fmt.Sprintf("gui/%d", os.Getuid()) |
| 133 | +} |
| 134 | + |
| 135 | +func serviceTarget(launchdLabel string) string { |
| 136 | + return fmt.Sprintf("%s/%s", serviceDomain(), launchdLabel) |
| 137 | +} |
| 138 | + |
| 139 | +// RunMachService runs the mach service at specified service name. |
| 140 | +// |
| 141 | +// It listens for incoming mach messages requesting a shared VmnetNetwork |
| 142 | +// for a given subnet, creates the VmnetNetwork if not already created, |
| 143 | +// and returns the serialized network object via mach IPC. |
| 144 | +func RunMachService(ctx context.Context, serviceName string) error { |
| 145 | + serializationStore := make(map[netip.Prefix]*xpc.Object) |
| 146 | + listener, err := xpc.NewListener(serviceName, |
| 147 | + xpc.NewSessionHandler( |
| 148 | + func(msg *xpc.Object) *xpc.Object { |
| 149 | + errorReply := func(errMsg string, args ...any) *xpc.Object { |
| 150 | + return msg.DictionaryCreateReply( |
| 151 | + xpc.WithString("Error", fmt.Sprintf(errMsg, args...)), |
| 152 | + ) |
| 153 | + } |
| 154 | + // Handle the message |
| 155 | + subnetStr := msg.DictionaryGetString("Subnet") |
| 156 | + if subnetStr == "" { |
| 157 | + return errorReply("missing Subnet key") |
| 158 | + } |
| 159 | + prefix, err := netip.ParsePrefix(subnetStr) |
| 160 | + if err != nil { |
| 161 | + return errorReply("failed to parse Subnet %q: %v", subnetStr, err) |
| 162 | + } |
| 163 | + // Modify the prefix to having IP that VmnetNetwork can accept. |
| 164 | + prefix = netip.PrefixFrom(prefix.Masked().Addr().Next(), prefix.Bits()) |
| 165 | + serialization, ok := serializationStore[prefix] |
| 166 | + if !ok { |
| 167 | + if config, err := vz.NewVmnetNetworkConfiguration(vz.SharedMode); err != nil { |
| 168 | + return errorReply("failed to create network configuration: %v", err) |
| 169 | + } else if err := config.SetIPv4Subnet(prefix); err != nil { |
| 170 | + return errorReply("failed to set IPv4 subnet: %v", err) |
| 171 | + } else if newNetwork, err := vz.NewVmnetNetwork(config); err != nil { |
| 172 | + return errorReply("failed to create VmnetNetwork: %v", err) |
| 173 | + } else if rawSerialization, err := newNetwork.CopySerialization(); err != nil { |
| 174 | + return errorReply("failed to copy network serialization: %v", err) |
| 175 | + } else { |
| 176 | + serialization = xpc.NewObject(rawSerialization) |
| 177 | + serializationStore[prefix] = serialization |
| 178 | + } |
| 179 | + } |
| 180 | + return msg.DictionaryCreateReply( |
| 181 | + xpc.WithValue("Network", serialization), |
| 182 | + ) |
| 183 | + }, |
| 184 | + nil, |
| 185 | + ), |
| 186 | + ) |
| 187 | + if err != nil { |
| 188 | + return err |
| 189 | + } |
| 190 | + listener.Activate() |
| 191 | + <-ctx.Done() |
| 192 | + return listener.Close() |
| 193 | +} |
| 194 | + |
| 195 | +// RequestSharedVmnetNetwork requests a shared VmnetNetwork for the given subnet |
| 196 | +// from the mach service "io.lima-vm.vz.vmnet.shared.subnet". |
| 197 | +func RequestSharedVmnetNetwork(ctx context.Context, subnet netip.Prefix) (*vz.VmnetNetwork, error) { |
| 198 | + session, err := xpc.NewSession(MachServiceName) |
| 199 | + if err != nil { |
| 200 | + return nil, fmt.Errorf("failed to create xpc session to %q: %w", MachServiceName, err) |
| 201 | + } |
| 202 | + defer session.Cancel() |
| 203 | + reply, err := session.SendDictionaryWithReply( |
| 204 | + ctx, |
| 205 | + xpc.WithString("Subnet", subnet.String()), |
| 206 | + ) |
| 207 | + if err != nil { |
| 208 | + return nil, fmt.Errorf("failed to send xpc message to %q: %w", MachServiceName, err) |
| 209 | + } |
| 210 | + if errMsg := reply.DictionaryGetString("Error"); errMsg != "" { |
| 211 | + return nil, fmt.Errorf("error from mach service %q: %s", MachServiceName, errMsg) |
| 212 | + } |
| 213 | + serialization := reply.DictionaryGetValue("Network") |
| 214 | + if serialization == nil { |
| 215 | + return nil, fmt.Errorf("no Network object in reply from %q", MachServiceName) |
| 216 | + } |
| 217 | + network, err := vz.NewVmnetNetworkWithSerialization(serialization.XpcObject) |
| 218 | + if err != nil { |
| 219 | + return nil, fmt.Errorf("failed to create VmnetNetwork (%v) from serialization: %w", subnet, err) |
| 220 | + } |
| 221 | + return network, nil |
| 222 | +} |
0 commit comments