| 1 | |
| 2 | package managedproxy |
| 3 | |
| 4 | import ( |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "runtime" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | "go.yaml.in/yaml/v3" |
| 20 | ) |
| 21 | |
| 22 | const Group = "CAGE" |
| 23 | const MaxImport = 8 << 20 |
| 24 | const maxStoreSize = 32 << 20 |
| 25 | |
| 26 | type Node struct { |
| 27 | ID string `json:"id"` |
| 28 | Name string `json:"name"` |
| 29 | Type string `json:"type"` |
| 30 | Config map[string]any `json:"config"` |
| 31 | } |
| 32 | type Source struct { |
| 33 | ID string `json:"id"` |
| 34 | Name string `json:"name"` |
| 35 | URL string `json:"url,omitempty"` |
| 36 | Interval int `json:"interval_hours"` |
| 37 | Updated time.Time `json:"updated_at"` |
| 38 | Attempted time.Time `json:"attempted_at"` |
| 39 | Error string `json:"error,omitempty"` |
| 40 | Usage string `json:"usage,omitempty"` |
| 41 | Nodes []Node `json:"nodes"` |
| 42 | Skipped []NodeIssue `json:"skipped,omitempty"` |
| 43 | } |
| 44 | type Store struct { |
| 45 | Version int `json:"version"` |
| 46 | Port int `json:"port"` |
| 47 | Auth string `json:"auth"` |
| 48 | Revision string `json:"revision"` |
| 49 | Selected string `json:"selected"` |
| 50 | Chain []string `json:"chain,omitempty"` |
| 51 | Sources []Source `json:"sources"` |
| 52 | } |
| 53 | |
| 54 | func Token() string { |
| 55 | b := make([]byte, 24) |
| 56 | if _, err := rand.Read(b); err != nil { |
| 57 | panic(err) |
| 58 | } |
| 59 | return hex.EncodeToString(b) |
| 60 | } |
| 61 | func Dir(profile string) string { return filepath.Join(profile, "proxy") } |
| 62 | func Socket(profile string) string { |
| 63 | h := sha256.Sum256([]byte(filepath.Clean(profile))) |
| 64 | if runtime.GOOS == "windows" { |
| 65 | return filepath.Join(os.TempDir(), fmt.Sprintf("cage-proxy-%x", h[:8]), "control.sock") |
| 66 | } |
| 67 | return filepath.Join("/tmp", fmt.Sprintf("cage-proxy-%d-%x", os.Getuid(), h[:8]), "control.sock") |
| 68 | } |
| 69 | func Load(profile string) (Store, error) { |
| 70 | var s Store |
| 71 | f, err := os.Open(filepath.Join(Dir(profile), "sources.json")) |
| 72 | if os.IsNotExist(err) { |
| 73 | return Store{Version: 1, Port: 17896, Auth: Token(), Sources: []Source{}}, nil |
| 74 | } |
| 75 | if err != nil { |
| 76 | return s, err |
| 77 | } |
| 78 | defer f.Close() |
| 79 | b, err := io.ReadAll(io.LimitReader(f, maxStoreSize+1)) |
| 80 | if err != nil { |
| 81 | return s, err |
| 82 | } |
| 83 | if len(b) > maxStoreSize || json.Unmarshal(b, &s) != nil || s.Version != 1 || s.Port < 1024 || s.Port > 65535 || len(s.Auth) != 48 { |
| 84 | return s, errors.New("Cage 代理配置无效,请恢复私有配置备份") |
| 85 | } |
| 86 | return s, nil |
| 87 | } |
| 88 | func Write(path string, data []byte) error { |
| 89 | if err := host.EnsurePrivateDir(filepath.Dir(path)); err != nil { |
| 90 | return err |
| 91 | } |
| 92 | f, err := os.CreateTemp(filepath.Dir(path), ".proxy-*") |
| 93 | if err != nil { |
| 94 | return err |
| 95 | } |
| 96 | defer os.Remove(f.Name()) |
| 97 | if err = host.ProtectFile(f.Name()); err == nil { |
| 98 | _, err = f.Write(data) |
| 99 | } |
| 100 | if err == nil { |
| 101 | err = f.Sync() |
| 102 | } |
| 103 | if e := f.Close(); err == nil { |
| 104 | err = e |
| 105 | } |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | return os.Rename(f.Name(), path) |
| 110 | } |
| 111 | func (s Store) Save(profile string) error { |
| 112 | b, err := json.MarshalIndent(s, "", " ") |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | if len(b) > maxStoreSize { |
| 117 | return errors.New("代理来源配置总大小超过 32 MiB,请减少来源或节点;原配置已保留") |
| 118 | } |
| 119 | return Write(filepath.Join(Dir(profile), "sources.json"), b) |
| 120 | } |
| 121 | func (s Store) Endpoint() string { return fmt.Sprintf("socks5://cage:%[email protected]:%d", s.Auth, s.Port) } |
| 122 | func (s Store) Find(id string) (Node, bool) { |
| 123 | for _, src := range s.Sources { |
| 124 | for _, n := range src.Nodes { |
| 125 | if n.ID == id { |
| 126 | return n, true |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | return Node{}, false |
| 131 | } |
| 132 | func (s Store) Count() int { |
| 133 | n := 0 |
| 134 | for _, src := range s.Sources { |
| 135 | n += len(src.Nodes) |
| 136 | } |
| 137 | return n |
| 138 | } |
| 139 | func (s *Store) Import(name, rawURL string, data []byte, id string, interval int, usage string) error { |
| 140 | name = strings.TrimSpace(name) |
| 141 | if name == "" || len(name) > 100 { |
| 142 | return errors.New("请填写 1–100 字节的来源名称") |
| 143 | } |
| 144 | if interval < 0 || interval > 168 { |
| 145 | return errors.New("更新间隔应为 0–168 小时,0 表示手动更新") |
| 146 | } |
| 147 | if id == "" { |
| 148 | id = Token()[:16] |
| 149 | } |
| 150 | nodes, skipped, err := parseNodes(data, id) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | src := Source{ID: id, Name: name, URL: rawURL, Interval: interval, Updated: time.Now(), Attempted: time.Now(), Nodes: nodes, Usage: usage, Skipped: skipped} |
| 155 | for i := range s.Sources { |
| 156 | if s.Sources[i].ID == id { |
| 157 | |
| 158 | |
| 159 | route, routeErr := s.Route() |
| 160 | if s.Selected != "" && routeErr != nil { |
| 161 | return routeErr |
| 162 | } |
| 163 | available := make(map[string]bool, len(nodes)) |
| 164 | for _, n := range nodes { |
| 165 | available[n.ID] = true |
| 166 | } |
| 167 | required := make(map[string]bool, len(route)) |
| 168 | for _, hop := range route { |
| 169 | required[hop] = true |
| 170 | } |
| 171 | for _, old := range s.Sources[i].Nodes { |
| 172 | if required[old.ID] && !available[old.ID] { |
| 173 | reason := "节点未包含在更新中" |
| 174 | for _, issue := range skipped { |
| 175 | if issue.Name == old.Name { |
| 176 | reason = issue.Reason |
| 177 | break |
| 178 | } |
| 179 | } |
| 180 | return fmt.Errorf("订阅更新移除或跳过了当前出口或中转节点 %q:%s;原配置已保留,请先应用其他节点再更新", old.Name, reason) |
| 181 | } |
| 182 | } |
| 183 | s.Sources[i] = src |
| 184 | return nil |
| 185 | } |
| 186 | } |
| 187 | s.Sources = append(s.Sources, src) |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | func unsafeOption(v any) bool { |
| 192 | switch x := v.(type) { |
| 193 | case map[string]any: |
| 194 | for k, v := range x { |
| 195 | if unsafeField(k, v) { |
| 196 | return true |
| 197 | } |
| 198 | } |
| 199 | case map[any]any: |
| 200 | |
| 201 | for k, v := range x { |
| 202 | key, _ := k.(string) |
| 203 | if unsafeField(key, v) { |
| 204 | return true |
| 205 | } |
| 206 | } |
| 207 | case []any: |
| 208 | for _, v := range x { |
| 209 | if unsafeOption(v) { |
| 210 | return true |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | return false |
| 215 | } |
| 216 | |
| 217 | func unsafeField(key string, value any) bool { |
| 218 | key = optionKey(key) |
| 219 | if strings.Contains(key, "path") && key != "path" { |
| 220 | return true |
| 221 | } |
| 222 | switch key { |
| 223 | case "ca", "certificate", "private-key", "interface-name", "routing-mark": |
| 224 | return true |
| 225 | } |
| 226 | return unsafeOption(value) |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | func (s Store) Route() ([]string, error) { |
| 232 | if _, ok := s.Find(s.Selected); !ok { |
| 233 | return nil, errors.New("请先选择有效的最终出口") |
| 234 | } |
| 235 | if len(s.Chain) > 0 { |
| 236 | if s.Chain[len(s.Chain)-1] != s.Selected { |
| 237 | return nil, errors.New("代理链与最终出口不一致,请重新配置代理") |
| 238 | } |
| 239 | seen := map[string]bool{} |
| 240 | for _, id := range s.Chain { |
| 241 | if _, ok := s.Find(id); !ok { |
| 242 | return nil, errors.New("代理链中的节点已被移除,请重新选择;原配置已保留") |
| 243 | } |
| 244 | if seen[id] { |
| 245 | return nil, errors.New("代理链不能重复使用同一个节点") |
| 246 | } |
| 247 | seen[id] = true |
| 248 | } |
| 249 | return append([]string(nil), s.Chain...), nil |
| 250 | } |
| 251 | var reversed []string |
| 252 | seen := map[string]bool{} |
| 253 | for id := s.Selected; id != ""; { |
| 254 | n, ok := s.Find(id) |
| 255 | if !ok || seen[id] { |
| 256 | return nil, errors.New("导入的代理链存在循环或缺失节点,请检查来源配置") |
| 257 | } |
| 258 | seen[id] = true |
| 259 | reversed = append(reversed, id) |
| 260 | id, _ = n.Config["dialer-proxy"].(string) |
| 261 | } |
| 262 | for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 { |
| 263 | reversed[i], reversed[j] = reversed[j], reversed[i] |
| 264 | } |
| 265 | return reversed, nil |
| 266 | } |
| 267 | |
| 268 | func (s Store) Runtime(profile string) ([]byte, error) { |
| 269 | if _, err := s.Route(); err != nil { |
| 270 | return nil, err |
| 271 | } |
| 272 | dialers := map[string]string{} |
| 273 | for i, id := range s.Chain { |
| 274 | dialers[id] = "" |
| 275 | if i > 0 { |
| 276 | dialers[id] = s.Chain[i-1] |
| 277 | } |
| 278 | } |
| 279 | proxies := []map[string]any{} |
| 280 | for _, src := range s.Sources { |
| 281 | for _, n := range src.Nodes { |
| 282 | config := make(map[string]any, len(n.Config)) |
| 283 | for key, value := range n.Config { |
| 284 | config[key] = value |
| 285 | } |
| 286 | |
| 287 | if err := normalizeWebSocket(config); err != nil { |
| 288 | return nil, fmt.Errorf("节点 %q:%w", n.Name, err) |
| 289 | } |
| 290 | if via, overridden := dialers[n.ID]; overridden { |
| 291 | delete(config, "dialer-proxy") |
| 292 | if via != "" { |
| 293 | config["dialer-proxy"] = via |
| 294 | } |
| 295 | } |
| 296 | proxies = append(proxies, config) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | |
| 301 | dns := map[string]any{"enable": true, "ipv6": false, "use-hosts": false, "use-system-hosts": false, "default-nameserver": BootstrapDNSURLs(), "proxy-server-nameserver": BootstrapDNSURLs(), "nameserver": []string{"https://1.1.1.1/dns-query#" + Group}} |
| 302 | config := map[string]any{"mixed-port": s.Port, "bind-address": "127.0.0.1", "allow-lan": false, "authentication": []string{"cage:" + s.Auth}, "skip-auth-prefixes": []string{}, "mode": "rule", "ipv6": false, "log-level": "warning", "find-process-mode": "off", "external-controller-unix": Socket(profile), "tun": map[string]any{"enable": false}, "dns": dns, "geo-auto-update": false, "profile": map[string]any{"store-selected": false}, "proxies": proxies, "proxy-groups": []any{map[string]any{"name": Group, "type": "select", "proxies": []string{s.Selected}}}, "rules": []string{"MATCH," + Group}} |
| 303 | |
| 304 | |
| 305 | config["unified-delay"] = true |
| 306 | return yaml.Marshal(config) |
| 307 | } |