| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | |
| 13 | func MacOSSSHPort(config []byte) (int, error) { |
| 14 | var port int |
| 15 | for _, line := range strings.Split(string(config), "\n") { |
| 16 | fields := strings.Fields(line) |
| 17 | if len(fields) == 0 || !strings.EqualFold(fields[0], "port") { |
| 18 | continue |
| 19 | } |
| 20 | if len(fields) != 2 || port != 0 { |
| 21 | return 0, errors.New("macOS 客机 SSH 端口配置无效") |
| 22 | } |
| 23 | value, err := strconv.Atoi(fields[1]) |
| 24 | if err != nil || value < 1 || value > 65535 { |
| 25 | return 0, errors.New("macOS 客机 SSH 端口配置无效") |
| 26 | } |
| 27 | port = value |
| 28 | } |
| 29 | if port == 0 { |
| 30 | return 0, errors.New("macOS 客机 SSH 端口尚未就绪") |
| 31 | } |
| 32 | return port, nil |
| 33 | } |
| 34 | |
| 35 | func MacOSSSHArgs(profile, user string) ([]string, error) { |
| 36 | data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config")) |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | port, err := MacOSSSHPort(data) |
| 41 | if err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | known := filepath.Join(profile, "macos-known-hosts") |
| 45 | |
| 46 | base := []string{"-q", "-e", "none", "-F", os.DevNull, "-p", strconv.Itoa(port), |
| 47 | "-l", user, "-i", filepath.Join(profile, "state", "lima", "_config", "user"), |
| 48 | "-o", "Hostname=127.0.0.1", "-o", "HostKeyAlias=cage-macos", |
| 49 | "-o", "StrictHostKeyChecking=yes", "-o", "HostKeyAlgorithms=ssh-ed25519", |
| 50 | "-o", "UserKnownHostsFile=" + strconv.Quote(known), "-o", "GlobalKnownHostsFile=" + os.DevNull, |
| 51 | "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", |
| 52 | "-o", "ForwardAgent=no", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none", |
| 53 | "-o", "ConnectTimeout=3", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2"} |
| 54 | return base, nil |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | func MacOSProvisionUser(profile string) (string, error) { |
| 60 | data, err := os.ReadFile(filepath.Join(profile, "state", "lima", "mac", "ssh.config")) |
| 61 | if err != nil { |
| 62 | return "", err |
| 63 | } |
| 64 | var user string |
| 65 | for _, line := range strings.Split(string(data), "\n") { |
| 66 | fields := strings.Fields(line) |
| 67 | if len(fields) == 0 || !strings.EqualFold(fields[0], "User") { |
| 68 | continue |
| 69 | } |
| 70 | if len(fields) != 2 || user != "" || (fields[1] != "cage" && fields[1] != "cageprovision") { |
| 71 | return "", errors.New("macOS 客机安装账户配置无效") |
| 72 | } |
| 73 | user = fields[1] |
| 74 | } |
| 75 | if user == "" { |
| 76 | return "", errors.New("macOS 客机安装账户尚未就绪") |
| 77 | } |
| 78 | return user, nil |
| 79 | } |