| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | package maclogin |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | import "C" |
| 13 | |
| 14 | import ( |
| 15 | "bytes" |
| 16 | "context" |
| 17 | "crypto/rand" |
| 18 | "crypto/subtle" |
| 19 | "encoding/json" |
| 20 | "errors" |
| 21 | "io" |
| 22 | "net" |
| 23 | "os" |
| 24 | "os/exec" |
| 25 | "path/filepath" |
| 26 | "runtime" |
| 27 | |
| 28 | "al.essio.dev/pkg/shellescape" |
| 29 | "time" |
| 30 | "unsafe" |
| 31 | |
| 32 | apple "github.com/Code-Hex/vz/v3" |
| 33 | driver "github.com/lima-vm/lima/v2/pkg/driver/vz" |
| 34 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 35 | ) |
| 36 | |
| 37 | type objectReference interface{ CageViewObject() unsafe.Pointer } |
| 38 | |
| 39 | func init() { |
| 40 | if _, built := any((*apple.VirtualMachine)(nil)).(objectReference); !built { |
| 41 | return |
| 42 | } |
| 43 | if len(os.Args) > 1 && (os.Args[1] == "hostagent" || os.Args[1] == "--debug") { |
| 44 | runtime.LockOSThread() |
| 45 | } |
| 46 | driver.OwnsOffscreenView = func(dir string) bool { |
| 47 | config := os.Getenv("CLAUDE_CAGE_CONFIG") |
| 48 | if !filepath.IsAbs(config) || !sameGuestDirectory(dir, filepath.Join(filepath.Dir(config), "state", "lima", "mac")) { |
| 49 | return false |
| 50 | } |
| 51 | profile, err := guestos.LoadMacOSProfile(filepath.Dir(config)) |
| 52 | return err == nil && profile != nil |
| 53 | } |
| 54 | driver.OffscreenView = run |
| 55 | } |
| 56 | |
| 57 | type request = guestos.MacLoginRequest |
| 58 | type reply = guestos.MacLoginReply |
| 59 | |
| 60 | type loginSession struct { |
| 61 | profile string |
| 62 | token string |
| 63 | expires time.Time |
| 64 | screenID string |
| 65 | setup bool |
| 66 | maintenance string |
| 67 | maintenanceFrame string |
| 68 | maintenanceMachineID string |
| 69 | maintenanceAdministrator string |
| 70 | passwordSelection passwordSelection |
| 71 | } |
| 72 | |
| 73 | func (s *loginSession) currentScreen() string { |
| 74 | if s.maintenance != "" { |
| 75 | surface, err := s.maintenanceProbe(false) |
| 76 | if err != nil { |
| 77 | return "" |
| 78 | } |
| 79 | return "maintenance-" + surface.Session |
| 80 | } |
| 81 | |
| 82 | |
| 83 | bound, err := guestos.LoadMacOSProfile(s.profile) |
| 84 | if err != nil || bound == nil { |
| 85 | return "" |
| 86 | } |
| 87 | if s.setup { |
| 88 | if bound.SetupID == "" { |
| 89 | return "" |
| 90 | } |
| 91 | return "setup-" + bound.SetupID |
| 92 | } |
| 93 | user, err := guestos.MacOSProvisionUser(s.profile) |
| 94 | if err != nil { |
| 95 | return "" |
| 96 | } |
| 97 | args, err := guestos.MacOSSSHArgs(s.profile, user) |
| 98 | if err != nil { |
| 99 | return "" |
| 100 | } |
| 101 | ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond) |
| 102 | defer cancel() |
| 103 | script := `set -eu |
| 104 | /usr/bin/pgrep -x loginwindow >/dev/null |
| 105 | owner=$(/usr/bin/stat -f '%u %Su' /dev/console) |
| 106 | if [ "$owner" = "0 root" ]; then /usr/bin/printf 'system-login'; exit 0; fi |
| 107 | uid=$(/usr/bin/id -u ` + shellescape.Quote(bound.User) + `) |
| 108 | /usr/bin/printf '%s %s\n' "$owner" "$uid" |
| 109 | /usr/sbin/ioreg -a -d1 -c IORegistryEntry -k IOConsoleUsers -l | /usr/bin/plutil -extract IOConsoleUsers xml1 -o - -` |
| 110 | cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...) |
| 111 | cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} |
| 112 | reader, err := cmd.StdoutPipe() |
| 113 | if err != nil || cmd.Start() != nil { |
| 114 | return "" |
| 115 | } |
| 116 | b, readErr := io.ReadAll(io.LimitReader(reader, (32<<10)+1)) |
| 117 | if readErr != nil || len(b) > 32<<10 { |
| 118 | cancel() |
| 119 | } |
| 120 | if err = cmd.Wait(); err != nil || readErr != nil || len(b) > 32<<10 { |
| 121 | return "" |
| 122 | } |
| 123 | return permittedLoginScreen(bytes.TrimSpace(b), bound.User) |
| 124 | } |
| 125 | |
| 126 | func (s *loginSession) close() { |
| 127 | if s.token != "" { |
| 128 | C.cageLoginEnable(false) |
| 129 | } |
| 130 | s.token = "" |
| 131 | s.screenID = "" |
| 132 | s.setup = false |
| 133 | s.maintenance = "" |
| 134 | s.maintenanceFrame = "" |
| 135 | s.maintenanceMachineID = "" |
| 136 | s.maintenanceAdministrator = "" |
| 137 | s.passwordSelection = passwordSelection{} |
| 138 | } |
| 139 | |
| 140 | func (s *loginSession) handle(in request) reply { |
| 141 | if in.Maintenance != "" || (s.maintenance != "" && in.Action != "open") { |
| 142 | return s.handleMaintenance(in) |
| 143 | } |
| 144 | if in.Action == "finish" && in.Setup { |
| 145 | bound, err := guestos.LoadMacOSProfile(s.profile) |
| 146 | if err != nil || bound == nil || bound.SetupID == "" { |
| 147 | return reply{Closed: true} |
| 148 | } |
| 149 | s.close() |
| 150 | if err = guestos.FinishMacOSSetup(s.profile, bound.SetupID); err != nil { |
| 151 | return reply{Error: "未能保存首次设置,请重试"} |
| 152 | } |
| 153 | return reply{Closed: true} |
| 154 | } |
| 155 | if in.Action == "open" { |
| 156 | s.close() |
| 157 | s.setup = in.Setup |
| 158 | s.screenID = s.currentScreen() |
| 159 | if s.screenID == "" { |
| 160 | return reply{Error: "客机已解锁,或尚未进入系统登录画面。"} |
| 161 | } |
| 162 | s.token = rand.Text() |
| 163 | s.expires = time.Now().Add(2 * time.Minute) |
| 164 | if s.setup { |
| 165 | s.expires = time.Now().Add(15 * time.Minute) |
| 166 | } |
| 167 | C.cageLoginEnable(true) |
| 168 | return reply{Session: s.token} |
| 169 | } |
| 170 | if s.token == "" || s.setup != in.Setup || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 { |
| 171 | return reply{Closed: true} |
| 172 | } |
| 173 | if time.Now().After(s.expires) || in.Action == "close" || s.currentScreen() != s.screenID { |
| 174 | s.close() |
| 175 | return reply{Closed: true} |
| 176 | } |
| 177 | switch in.Action { |
| 178 | case "fill-password": |
| 179 | if err := s.fillSetupPassword(in.Password); err != nil { |
| 180 | return reply{Error: err.Error()} |
| 181 | } |
| 182 | case "frame": |
| 183 | var n C.int |
| 184 | p := C.cageLoginImage(&n) |
| 185 | if p == nil { |
| 186 | return reply{Error: "尚未收到 Apple 登录画面"} |
| 187 | } |
| 188 | defer C.free(p) |
| 189 | if s.currentScreen() != s.screenID { |
| 190 | s.close() |
| 191 | return reply{Closed: true} |
| 192 | } |
| 193 | return reply{Image: C.GoBytes(p, n), MIME: "image/jpeg"} |
| 194 | case "click": |
| 195 | s.passwordSelection = passwordSelection{} |
| 196 | if in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) { |
| 197 | return reply{Error: "无效的登录位置"} |
| 198 | } |
| 199 | if s.setup { |
| 200 | s.selectPasswordPosition(in.X, in.Y) |
| 201 | } |
| 202 | case "key": |
| 203 | s.passwordSelection = passwordSelection{} |
| 204 | |
| 205 | setupNavigation := s.setup && (in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121) |
| 206 | if in.Code < 0 || (in.Code > 53 && !setupNavigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) { |
| 207 | return reply{Error: "不支持此登录按键"} |
| 208 | } |
| 209 | case "scroll": |
| 210 | s.passwordSelection = passwordSelection{} |
| 211 | if !s.setup || in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || |
| 212 | in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 || |
| 213 | !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) { |
| 214 | return reply{Error: "无效的首次设置滚动操作"} |
| 215 | } |
| 216 | default: |
| 217 | return reply{Error: "未知的登录操作"} |
| 218 | } |
| 219 | return reply{} |
| 220 | } |
| 221 | |
| 222 | func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error { |
| 223 | if !driver.OwnsOffscreenView(dir) { |
| 224 | return errors.New("invalid local macOS login view") |
| 225 | } |
| 226 | socket := filepath.Join(dir, "cage-login.sock") |
| 227 | if fi, err := os.Lstat(socket); err == nil { |
| 228 | if fi.Mode()&os.ModeSocket == 0 { |
| 229 | return errors.New("unexpected login socket path") |
| 230 | } |
| 231 | existing, err := net.DialTimeout("unix", socket, 300*time.Millisecond) |
| 232 | if err == nil { |
| 233 | existing.Close() |
| 234 | return errors.New("this instance already has a login view") |
| 235 | } |
| 236 | if err = os.Remove(socket); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | } |
| 240 | ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: socket, Net: "unix"}) |
| 241 | if err != nil { |
| 242 | return err |
| 243 | } |
| 244 | defer ln.Close() |
| 245 | if err = os.Chmod(socket, 0600); err != nil { |
| 246 | return err |
| 247 | } |
| 248 | runCtx, cancel := context.WithCancel(ctx) |
| 249 | defer cancel() |
| 250 | s := loginSession{profile: filepath.Dir(os.Getenv("CLAUDE_CAGE_CONFIG"))} |
| 251 | go func() { |
| 252 | for { |
| 253 | _ = ln.SetDeadline(time.Now().Add(time.Second)) |
| 254 | conn, err := ln.Accept() |
| 255 | if err != nil { |
| 256 | if n, ok := err.(net.Error); ok && n.Timeout() && runCtx.Err() == nil { |
| 257 | if s.token != "" && (time.Now().After(s.expires) || s.currentScreen() != s.screenID) { |
| 258 | s.close() |
| 259 | } |
| 260 | continue |
| 261 | } |
| 262 | return |
| 263 | } |
| 264 | _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) |
| 265 | var input request |
| 266 | if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&input) == nil { |
| 267 | if input.Maintenance != "" { |
| 268 | _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) |
| 269 | } |
| 270 | result := s.handle(input) |
| 271 | if err := json.NewEncoder(conn).Encode(result); err != nil && result.Session != "" { |
| 272 | s.close() |
| 273 | } |
| 274 | } |
| 275 | _ = conn.Close() |
| 276 | } |
| 277 | }() |
| 278 | go func() { |
| 279 | ticker := time.NewTicker(250 * time.Millisecond) |
| 280 | defer ticker.Stop() |
| 281 | running := false |
| 282 | for { |
| 283 | select { |
| 284 | case <-runCtx.Done(): |
| 285 | C.cageLoginStop() |
| 286 | return |
| 287 | case <-ticker.C: |
| 288 | state := machine.State() |
| 289 | if state == apple.VirtualMachineStateRunning { |
| 290 | running = true |
| 291 | } |
| 292 | if running && (state == apple.VirtualMachineStateStopped || state == apple.VirtualMachineStateError) { |
| 293 | C.cageLoginStop() |
| 294 | return |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | }() |
| 299 | ref, ok := any(machine).(objectReference) |
| 300 | if !ok { |
| 301 | return errors.New("this build has no macOS login view") |
| 302 | } |
| 303 | C.cageLoginLoop(ref.CageViewObject()) |
| 304 | runtime.KeepAlive(machine) |
| 305 | return nil |
| 306 | } |