| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/json" |
| 8 | "encoding/xml" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net" |
| 13 | "net/http" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "runtime" |
| 18 | "strconv" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 22 | "github.com/sylvinus/agent-vm/internal/host" |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | func CorePath() (string, error) { |
| 27 | exe, err := os.Executable() |
| 28 | if err != nil { |
| 29 | return "", err |
| 30 | } |
| 31 | name := "mihomo" |
| 32 | if runtime.GOOS == "windows" { |
| 33 | name += ".exe" |
| 34 | } |
| 35 | for _, p := range []string{filepath.Join(filepath.Dir(exe), name), filepath.Join(filepath.Dir(exe), "..", "proxy-core", name)} { |
| 36 | if st, e := os.Stat(p); e == nil && st.Mode().IsRegular() && (runtime.GOOS == "windows" || st.Mode()&0111 != 0) { |
| 37 | return filepath.Clean(p), nil |
| 38 | } |
| 39 | } |
| 40 | return "", errors.New("Cage 随附代理核心缺失,请重新安装完整应用;开发构建请运行 scripts/fetch-proxy-core.sh") |
| 41 | } |
| 42 | func Validate(ctx context.Context, profile string, s Store) error { |
| 43 | core, err := CorePath() |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | b, err := s.Runtime(profile) |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | dir := Dir(profile) |
| 52 | if err = host.EnsurePrivateDir(dir); err != nil { |
| 53 | return err |
| 54 | } |
| 55 | f, err := os.CreateTemp(dir, "validate-*.yaml") |
| 56 | if err != nil { |
| 57 | return err |
| 58 | } |
| 59 | defer os.Remove(f.Name()) |
| 60 | if err = host.ProtectFile(f.Name()); err != nil { |
| 61 | f.Close() |
| 62 | return err |
| 63 | } |
| 64 | if _, err = f.Write(b); err != nil { |
| 65 | f.Close() |
| 66 | return err |
| 67 | } |
| 68 | f.Close() |
| 69 | ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 70 | defer cancel() |
| 71 | cmd := exec.CommandContext(ctx, core, "-t", "-d", dir, "-f", f.Name()) |
| 72 | cmd.Env = coreEnvironment(dir) |
| 73 | output := diagnostics.New(profile).Stream("proxy-validation", "error") |
| 74 | defer output.Close() |
| 75 | cmd.Stdout, cmd.Stderr = output, output |
| 76 | if e := cmd.Run(); e != nil { |
| 77 | return errors.New("随附的 Mihomo 核心未通过配置校验,请核对节点协议和参数;可在设置的“日志与诊断”中导出诊断包查看校验记录;原配置已保留") |
| 78 | } |
| 79 | return nil |
| 80 | } |
| 81 | func API(ctx context.Context, profile, method, path string, body any, reply any) error { |
| 82 | tr := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 83 | return (&net.Dialer{Timeout: 2 * time.Second}).DialContext(ctx, "unix", Socket(profile)) |
| 84 | }} |
| 85 | defer tr.CloseIdleConnections() |
| 86 | client := &http.Client{Transport: tr, Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }} |
| 87 | var data []byte |
| 88 | var err error |
| 89 | if body != nil { |
| 90 | data, err = json.Marshal(body) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | } |
| 95 | req, err := http.NewRequestWithContext(ctx, method, "http://cage-proxy"+path, bytes.NewReader(data)) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | req.Header.Set("Content-Type", "application/json") |
| 100 | res, err := client.Do(req) |
| 101 | if err != nil { |
| 102 | return errors.New("Cage 代理核心尚未就绪") |
| 103 | } |
| 104 | defer res.Body.Close() |
| 105 | if res.StatusCode < 200 || res.StatusCode > 299 { |
| 106 | return fmt.Errorf("代理核心操作失败(HTTP %d)", res.StatusCode) |
| 107 | } |
| 108 | if reply != nil { |
| 109 | if json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(reply) != nil { |
| 110 | return errors.New("代理核心响应无效") |
| 111 | } |
| 112 | } |
| 113 | return nil |
| 114 | } |
| 115 | func Running(ctx context.Context, profile string, s Store) bool { |
| 116 | var cfg struct { |
| 117 | Port int `json:"mixed-port"` |
| 118 | Interface string `json:"interface-name"` |
| 119 | UnifiedDelay bool `json:"unified-delay"` |
| 120 | } |
| 121 | var group struct { |
| 122 | Now string `json:"now"` |
| 123 | } |
| 124 | bound, err := BoundInterface(filepath.Join(Dir(profile), "config.yaml")) |
| 125 | return err == nil && bound != "" && API(ctx, profile, "GET", "/configs", nil, &cfg) == nil && cfg.Port == s.Port && cfg.Interface == bound && cfg.UnifiedDelay && API(ctx, profile, "GET", "/proxies/"+Group, nil, &group) == nil && group.Now == s.Selected |
| 126 | } |
| 127 | func label(profile string) string { |
| 128 | h := sha256.Sum256([]byte(profile)) |
| 129 | return fmt.Sprintf("local.claude-cage.managed-proxy.%x", h[:8]) |
| 130 | } |
| 131 | func servicePath(profile string) string { return filepath.Join(Dir(profile), "managed-service.plist") } |
| 132 | func Stop(profile string) error { |
| 133 | if runtime.GOOS == "windows" { |
| 134 | return stopWindowsCore(profile) |
| 135 | } |
| 136 | if runtime.GOOS == "linux" { |
| 137 | return stopLinuxCore(profile) |
| 138 | } |
| 139 | if _, err := os.Stat(servicePath(profile)); os.IsNotExist(err) { |
| 140 | return nil |
| 141 | } |
| 142 | if runtime.GOOS != "darwin" { |
| 143 | return errors.New("内置代理当前支持 macOS") |
| 144 | } |
| 145 | domain := "gui/" + strconv.Itoa(os.Getuid()) |
| 146 | if exec.Command("launchctl", "print", domain+"/"+label(profile)).Run() != nil { |
| 147 | return nil |
| 148 | } |
| 149 | if exec.Command("launchctl", "bootout", domain, servicePath(profile)).Run() != nil { |
| 150 | return errors.New("未能停止 Cage 专属代理进程") |
| 151 | } |
| 152 | return nil |
| 153 | } |
| 154 | func Start(ctx context.Context, profile string, s Store) error { |
| 155 | if runtime.GOOS == "windows" { |
| 156 | return startWindowsCore(ctx, profile, s) |
| 157 | } |
| 158 | if runtime.GOOS == "linux" { |
| 159 | return startLinuxCore(ctx, profile, s) |
| 160 | } |
| 161 | if runtime.GOOS != "darwin" { |
| 162 | return errors.New("内置代理当前支持 macOS") |
| 163 | } |
| 164 | name, err := PhysicalInterface(ctx) |
| 165 | if err != nil { |
| 166 | return err |
| 167 | } |
| 168 | path := filepath.Join(Dir(profile), "config.yaml") |
| 169 | bound, _ := BoundInterface(path) |
| 170 | if bound == name && Running(ctx, profile, s) { |
| 171 | return nil |
| 172 | } |
| 173 | if err := Validate(ctx, profile, s); err != nil { |
| 174 | return err |
| 175 | } |
| 176 | if err := Stop(profile); err != nil { |
| 177 | return err |
| 178 | } |
| 179 | |
| 180 | l, err := net.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", s.Port)) |
| 181 | if err != nil { |
| 182 | return errors.New("Cage 代理端口已被占用,请更换独立端口") |
| 183 | } |
| 184 | l.Close() |
| 185 | _, err = CorePath() |
| 186 | if err != nil { |
| 187 | return err |
| 188 | } |
| 189 | if err = os.MkdirAll(filepath.Dir(Socket(profile)), 0700); err != nil { |
| 190 | return err |
| 191 | } |
| 192 | if err = os.Chmod(filepath.Dir(Socket(profile)), 0700); err != nil { |
| 193 | return err |
| 194 | } |
| 195 | b, err := s.Runtime(profile) |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | b, err = BindInterface(b, name) |
| 200 | if err != nil { |
| 201 | return err |
| 202 | } |
| 203 | if err = Write(path, b); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | _ = os.Remove(Socket(profile)) |
| 207 | executable, err := os.Executable() |
| 208 | if err != nil { |
| 209 | return err |
| 210 | } |
| 211 | configPath := os.Getenv("CLAUDE_CAGE_CONFIG") |
| 212 | if configPath == "" { |
| 213 | configPath = filepath.Join(profile, "config.json") |
| 214 | } |
| 215 | escape := func(s string) string { var b bytes.Buffer; _ = xml.EscapeText(&b, []byte(s)); return b.String() } |
| 216 | plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>%s</string><key>ProgramArguments</key><array><string>%s</string><string>log-relay</string><string>proxy</string></array><key>EnvironmentVariables</key><dict><key>HOME</key><string>%s</string><key>PATH</key><string>/usr/bin:/bin</string><key>CLAUDE_CAGE_CONFIG</key><string>%s</string></dict><key>RunAtLoad</key><true/></dict></plist>`, escape(label(profile)), escape(executable), escape(Dir(profile)), escape(configPath)) |
| 217 | |
| 218 | if err = Write(servicePath(profile), []byte(plist)); err != nil { |
| 219 | return err |
| 220 | } |
| 221 | if exec.CommandContext(ctx, "launchctl", "bootstrap", "gui/"+strconv.Itoa(os.Getuid()), servicePath(profile)).Run() != nil { |
| 222 | return errors.New("无法启动 Cage 自带代理核心") |
| 223 | } |
| 224 | ticker := time.NewTicker(100 * time.Millisecond) |
| 225 | defer ticker.Stop() |
| 226 | deadline := time.NewTimer(10 * time.Second) |
| 227 | defer deadline.Stop() |
| 228 | for { |
| 229 | select { |
| 230 | case <-ctx.Done(): |
| 231 | _ = Stop(profile) |
| 232 | return ctx.Err() |
| 233 | case <-deadline.C: |
| 234 | _ = Stop(profile) |
| 235 | return errors.New("代理核心启动超时,请查看私有代理日志") |
| 236 | case <-ticker.C: |
| 237 | if Running(ctx, profile, s) { |
| 238 | if err = os.Chmod(Socket(profile), 0600); err != nil { |
| 239 | _ = Stop(profile) |
| 240 | return err |
| 241 | } |
| 242 | return nil |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | } |