| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "syscall" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | "golang.org/x/sys/unix" |
| 20 | ) |
| 21 | |
| 22 | type linuxCoreRecord struct { |
| 23 | PID int `json:"pid"` |
| 24 | Executable string `json:"executable"` |
| 25 | Started uint64 `json:"started"` |
| 26 | BootID string `json:"boot_id"` |
| 27 | } |
| 28 | |
| 29 | func linuxCoreRecordPath(profile string) string { |
| 30 | return filepath.Join(Dir(profile), "managed-process.json") |
| 31 | } |
| 32 | |
| 33 | func identifyLinuxCore(pid int) (linuxCoreRecord, error) { |
| 34 | var record linuxCoreRecord |
| 35 | root := filepath.Join("/proc", strconv.Itoa(pid)) |
| 36 | executable, err := os.Readlink(filepath.Join(root, "exe")) |
| 37 | if err != nil { |
| 38 | return record, err |
| 39 | } |
| 40 | started, err := linuxProcessStart(pid) |
| 41 | if err != nil { |
| 42 | return record, err |
| 43 | } |
| 44 | bootID, err := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| 45 | if err != nil { |
| 46 | return record, err |
| 47 | } |
| 48 | return linuxCoreRecord{PID: pid, Executable: executable, Started: started, BootID: strings.TrimSpace(string(bootID))}, nil |
| 49 | } |
| 50 | |
| 51 | func linuxProcessStart(pid int) (uint64, error) { |
| 52 | stat, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) |
| 53 | if err != nil { |
| 54 | return 0, err |
| 55 | } |
| 56 | |
| 57 | end := strings.LastIndexByte(string(stat), ')') |
| 58 | if end < 0 { |
| 59 | return 0, errors.New("无法读取代理进程启动时间") |
| 60 | } |
| 61 | fields := strings.Fields(string(stat)[end+1:]) |
| 62 | if len(fields) < 20 { |
| 63 | return 0, errors.New("无法读取代理进程启动时间") |
| 64 | } |
| 65 | return strconv.ParseUint(fields[19], 10, 64) |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | func stopLinuxProcess(record linuxCoreRecord, core string) error { |
| 71 | bootID, err := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | if strings.TrimSpace(string(bootID)) != record.BootID { |
| 76 | return nil |
| 77 | } |
| 78 | resolved, err := filepath.EvalSymlinks(core) |
| 79 | if err != nil { |
| 80 | return err |
| 81 | } |
| 82 | if resolved != record.Executable { |
| 83 | return errors.New("Cage 代理进程不属于当前安装目录") |
| 84 | } |
| 85 | fd, err := unix.PidfdOpen(record.PID, 0) |
| 86 | if errors.Is(err, unix.ESRCH) { |
| 87 | return nil |
| 88 | } |
| 89 | if err != nil { |
| 90 | return fmt.Errorf("无法安全打开 Cage 代理进程(需要 Linux 5.3 或更新内核): %w", err) |
| 91 | } |
| 92 | defer unix.Close(fd) |
| 93 | |
| 94 | |
| 95 | started, err := linuxProcessStart(record.PID) |
| 96 | if os.IsNotExist(err) || err == nil && started != record.Started { |
| 97 | return nil |
| 98 | } |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | current, err := identifyLinuxCore(record.PID) |
| 103 | if os.IsNotExist(err) { |
| 104 | return nil |
| 105 | } |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | if current != record { |
| 110 | |
| 111 | |
| 112 | return nil |
| 113 | } |
| 114 | for _, signal := range []unix.Signal{unix.SIGTERM, unix.SIGKILL} { |
| 115 | if err := unix.PidfdSendSignal(fd, signal, nil, 0); errors.Is(err, unix.ESRCH) { |
| 116 | return nil |
| 117 | } else if err != nil { |
| 118 | return err |
| 119 | } |
| 120 | deadline := time.Now().Add(5 * time.Second) |
| 121 | for time.Now().Before(deadline) { |
| 122 | poll := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} |
| 123 | n, err := unix.Poll(poll, 100) |
| 124 | if err != nil && !errors.Is(err, unix.EINTR) { |
| 125 | return err |
| 126 | } |
| 127 | if n > 0 && poll[0].Revents&unix.POLLIN != 0 { |
| 128 | return nil |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | return errors.New("Cage 代理进程未能及时停止") |
| 133 | } |
| 134 | |
| 135 | func stopLinuxCore(profile string) error { |
| 136 | path := linuxCoreRecordPath(profile) |
| 137 | if err := host.CheckPrivateFile(path); os.IsNotExist(err) { |
| 138 | return nil |
| 139 | } else if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | b, err := os.ReadFile(path) |
| 143 | if err != nil { |
| 144 | return err |
| 145 | } |
| 146 | var record linuxCoreRecord |
| 147 | if len(b) > 4096 || json.Unmarshal(b, &record) != nil || record.PID <= 1 || record.Started == 0 || record.BootID == "" { |
| 148 | return errors.New("Cage 代理进程记录无效") |
| 149 | } |
| 150 | core, err := CorePath() |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | if err := stopLinuxProcess(record, core); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | _ = os.Remove(Socket(profile)) |
| 158 | return os.Remove(path) |
| 159 | } |
| 160 | |
| 161 | func startLinuxCore(ctx context.Context, profile string, s Store) error { |
| 162 | name, err := PhysicalInterface(ctx) |
| 163 | if err != nil { |
| 164 | return err |
| 165 | } |
| 166 | path := filepath.Join(Dir(profile), "config.yaml") |
| 167 | bound, _ := BoundInterface(path) |
| 168 | if bound == name && Running(ctx, profile, s) { |
| 169 | return nil |
| 170 | } |
| 171 | if err := Validate(ctx, profile, s); err != nil { |
| 172 | return err |
| 173 | } |
| 174 | if err := stopLinuxCore(profile); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | l, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", s.Port)) |
| 178 | if err != nil { |
| 179 | return errors.New("Cage 代理端口已被占用,请更换独立端口") |
| 180 | } |
| 181 | l.Close() |
| 182 | core, err := CorePath() |
| 183 | if err != nil { |
| 184 | return err |
| 185 | } |
| 186 | if err := host.EnsurePrivateDir(filepath.Dir(Socket(profile))); err != nil { |
| 187 | return err |
| 188 | } |
| 189 | b, err := s.Runtime(profile) |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | b, err = BindInterface(b, name) |
| 194 | if err != nil { |
| 195 | return err |
| 196 | } |
| 197 | if err := Write(path, b); err != nil { |
| 198 | return err |
| 199 | } |
| 200 | _ = os.Remove(Socket(profile)) |
| 201 | log := diagnostics.New(profile).Stream("proxy", "warn") |
| 202 | |
| 203 | cmd := exec.Command(core, "-d", Dir(profile), "-f", path) |
| 204 | cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log |
| 205 | cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| 206 | if err := cmd.Start(); err != nil { |
| 207 | _ = log.Close() |
| 208 | return err |
| 209 | } |
| 210 | record, err := identifyLinuxCore(cmd.Process.Pid) |
| 211 | if err == nil { |
| 212 | var data []byte |
| 213 | data, err = json.Marshal(record) |
| 214 | if err == nil { |
| 215 | err = Write(linuxCoreRecordPath(profile), data) |
| 216 | } |
| 217 | } |
| 218 | if err != nil { |
| 219 | _ = cmd.Process.Kill() |
| 220 | _ = cmd.Wait() |
| 221 | return err |
| 222 | } |
| 223 | exited := make(chan struct{}) |
| 224 | go func() { |
| 225 | err := cmd.Wait() |
| 226 | _ = log.Close() |
| 227 | if err != nil { |
| 228 | _ = diagnostics.New(profile).Record("error", "proxy", "core exited: "+err.Error()) |
| 229 | } |
| 230 | close(exited) |
| 231 | }() |
| 232 | ticker := time.NewTicker(100 * time.Millisecond) |
| 233 | defer ticker.Stop() |
| 234 | timeout := time.NewTimer(15 * time.Second) |
| 235 | defer timeout.Stop() |
| 236 | for { |
| 237 | select { |
| 238 | case <-ctx.Done(): |
| 239 | _ = stopLinuxCore(profile) |
| 240 | return ctx.Err() |
| 241 | case <-exited: |
| 242 | _ = stopLinuxCore(profile) |
| 243 | return errors.New("代理核心启动失败,请查看私有代理日志") |
| 244 | case <-timeout.C: |
| 245 | _ = stopLinuxCore(profile) |
| 246 | return errors.New("代理核心启动超时,请查看私有代理日志") |
| 247 | case <-ticker.C: |
| 248 | if Running(ctx, profile, s) { |
| 249 | if err := host.ProtectFile(Socket(profile)); err != nil { |
| 250 | _ = stopLinuxCore(profile) |
| 251 | return err |
| 252 | } |
| 253 | return nil |
| 254 | } |
| 255 | } |
| 256 | } |
| 257 | } |