| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "runtime" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | type legacyProcessIdentity struct { |
| 17 | PID int |
| 18 | Executable, Started string |
| 19 | } |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | func identifyLegacyController(profile string, record controlFile) (legacyProcessIdentity, error) { |
| 25 | refused := errors.New("无法确认旧后台进程身份,未停止任何进程。请保留现有环境并重试更新。") |
| 26 | if runtime.GOOS != "darwin" || record.PID <= 1 || record.PID == os.Getpid() { |
| 27 | return legacyProcessIdentity{}, refused |
| 28 | } |
| 29 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 30 | defer cancel() |
| 31 | read := func(binary string, args ...string) (string, error) { |
| 32 | b, err := exec.CommandContext(ctx, binary, args...).Output() |
| 33 | return strings.TrimSpace(string(b)), err |
| 34 | } |
| 35 | pid := strconv.Itoa(record.PID) |
| 36 | uid, err := read("/bin/ps", "-p", pid, "-o", "uid=") |
| 37 | if err != nil || uid != strconv.Itoa(os.Getuid()) { |
| 38 | return legacyProcessIdentity{}, refused |
| 39 | } |
| 40 | started, err := read("/bin/ps", "-p", pid, "-o", "lstart=") |
| 41 | if err != nil || started == "" { |
| 42 | return legacyProcessIdentity{}, refused |
| 43 | } |
| 44 | executable, err := read("/bin/ps", "-p", pid, "-o", "comm=") |
| 45 | if err != nil || !filepath.IsAbs(executable) || filepath.Base(executable) != "cage" { |
| 46 | return legacyProcessIdentity{}, refused |
| 47 | } |
| 48 | command, err := read("/bin/ps", "-ww", "-p", pid, "-o", "command=") |
| 49 | if err != nil || command != executable+" serve" { |
| 50 | return legacyProcessIdentity{}, refused |
| 51 | } |
| 52 | cwd, err := read("/usr/sbin/lsof", "-a", "-p", pid, "-d", "cwd", "-Fn") |
| 53 | realProfile, pathErr := filepath.EvalSymlinks(profile) |
| 54 | if err != nil || pathErr != nil || !strings.Contains("\n"+cwd+"\n", "\nn"+realProfile+"\n") { |
| 55 | return legacyProcessIdentity{}, refused |
| 56 | } |
| 57 | listener, err := read("/usr/sbin/lsof", "-nP", "-a", "-p", pid, fmt.Sprintf("-iTCP:%d", record.Port), "-sTCP:LISTEN", "-Fn") |
| 58 | if err != nil || !strings.Contains("\n"+listener+"\n", fmt.Sprintf("\nn127.0.0.1:%d\n", record.Port)) { |
| 59 | return legacyProcessIdentity{}, refused |
| 60 | } |
| 61 | finalStart, err := read("/bin/ps", "-p", pid, "-o", "lstart=") |
| 62 | if err != nil || finalStart != started { |
| 63 | return legacyProcessIdentity{}, refused |
| 64 | } |
| 65 | return legacyProcessIdentity{PID: record.PID, Executable: executable, Started: started}, nil |
| 66 | } |