| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/sylvinus/agent-vm/internal/cage" |
| 12 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 13 | ) |
| 14 | |
| 15 | var ( |
| 16 | validateProxyCore = managedproxy.Validate |
| 17 | startProxyCore = managedproxy.Start |
| 18 | fetchProxySource = managedproxy.Fetch |
| 19 | ) |
| 20 | |
| 21 | type proxyInput struct { |
| 22 | ID string `json:"id"` |
| 23 | Name string `json:"name"` |
| 24 | URL string `json:"url"` |
| 25 | Content string `json:"content"` |
| 26 | Interval int `json:"interval_hours"` |
| 27 | HostDownload bool `json:"host_download"` |
| 28 | NodeID string `json:"node_id"` |
| 29 | NodeIDs []string `json:"node_ids"` |
| 30 | Port int `json:"port"` |
| 31 | } |
| 32 | |
| 33 | func (s *Server) proxyStatus(w http.ResponseWriter, r *http.Request) { |
| 34 | p, err := managedproxy.Load(s.profile) |
| 35 | if err != nil { |
| 36 | requestError(w, err) |
| 37 | return |
| 38 | } |
| 39 | cfg, err := loadConfig(s.configPath) |
| 40 | if err != nil { |
| 41 | requestError(w, err) |
| 42 | return |
| 43 | } |
| 44 | sources := []any{} |
| 45 | for _, src := range p.Sources { |
| 46 | nodes := []any{} |
| 47 | for _, n := range src.Nodes { |
| 48 | nodes = append(nodes, map[string]any{"id": n.ID, "name": n.Name, "type": n.Type}) |
| 49 | } |
| 50 | host := "" |
| 51 | if u, e := url.Parse(src.URL); e == nil { |
| 52 | host = u.Hostname() |
| 53 | } |
| 54 | sources = append(sources, map[string]any{"id": src.ID, "name": src.Name, "remote": src.URL != "", "host": host, "interval_hours": src.Interval, "updated_at": src.Updated, "error": src.Error, "usage": src.Usage, "nodes": nodes, "skipped": src.Skipped}) |
| 55 | } |
| 56 | ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) |
| 57 | defer cancel() |
| 58 | _, appliedErr := managedproxy.Applied(s.profile, cfg.ProxyURL, cfg.ProxyRevision) |
| 59 | active := appliedErr == nil |
| 60 | running := managedproxy.Running(ctx, s.profile, p) |
| 61 | state, label := "unconfigured", "尚未配置" |
| 62 | _, selected := p.Find(p.Selected) |
| 63 | if selected { |
| 64 | state, label = "unapplied", "尚未应用" |
| 65 | } |
| 66 | if active { |
| 67 | state, label = "stopped", "代理已停止" |
| 68 | if running { |
| 69 | state, label = "prepared", "待启动环境" |
| 70 | if s.vmRunning() { |
| 71 | state, label = "paused", "外网未放行" |
| 72 | if client, e := s.gateClient(); e == nil { |
| 73 | if gate, e := client.Status(ctx); e == nil { |
| 74 | if gate.Mode == cage.GateChecking { |
| 75 | state, label = "checking", "正在检查" |
| 76 | } else if gate.Mode == cage.GateOpen && gate.Report != nil && gate.Report.Authorizes(gate.RunID, cfg.Fingerprint(), time.Now()) == nil && time.Now().Before(gate.Until) { |
| 77 | state, label = "ready", "已联网" |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | var version struct { |
| 85 | Version string `json:"version"` |
| 86 | } |
| 87 | if running { |
| 88 | _ = managedproxy.API(ctx, s.profile, "GET", "/version", nil, &version) |
| 89 | } |
| 90 | _, coreErr := managedproxy.CorePath() |
| 91 | route, routeErr := p.Route() |
| 92 | if route == nil { |
| 93 | route = append([]string{}, p.Chain...) |
| 94 | } |
| 95 | routeError := "" |
| 96 | if routeErr != nil && selected { |
| 97 | routeError = routeErr.Error() |
| 98 | } |
| 99 | jsonReply(w, map[string]any{"route": route, "route_error": routeError, "sources": sources, "selected": p.Selected, "port": p.Port, "running": running, "active": active, "state": state, "state_label": label, "network_open": state == "ready", "core_available": coreErr == nil, "version": version.Version, "revision": p.Revision, "bootstrap_dns": strings.Join(managedproxy.BootstrapDNSURLs(), "、"), "udp_blocked": true, "ipv6_blocked": true}) |
| 100 | } |
| 101 | func (s *Server) proxyMutation(w http.ResponseWriter, r *http.Request) { |
| 102 | var input proxyInput |
| 103 | if !readJSON(w, r, &input, 12<<20) { |
| 104 | return |
| 105 | } |
| 106 | action := r.PathValue("action") |
| 107 | allowed := map[string]bool{"import": true, "refresh": true, "edit": true, "delete": true, "select": true, "restart": true, "stop": true, "route": true} |
| 108 | if !allowed[action] { |
| 109 | http.NotFound(w, r) |
| 110 | return |
| 111 | } |
| 112 | s.mu.Lock() |
| 113 | pauseVersion := s.safety.pauseVersion |
| 114 | s.mu.Unlock() |
| 115 | s.launch(w, "proxy", func() error { return s.changeProxy(action, input, &pauseVersion) }) |
| 116 | } |
| 117 | func (s *Server) subscriptionClient(host bool) (*http.Client, error) { |
| 118 | if host { |
| 119 | return managedproxy.BootstrapClient(), nil |
| 120 | } |
| 121 | cfg, err := loadConfig(s.configPath) |
| 122 | if err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | if err = cfg.RequireManagedProxy(s.profile); err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | e, err := cage.NewEgress(cfg) |
| 129 | if err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | return &http.Client{Transport: &http.Transport{Proxy: nil, DialContext: e.DialContext}, Timeout: 30 * time.Second, CheckRedirect: func(r *http.Request, via []*http.Request) error { |
| 133 | if len(via) >= 3 || r.URL.Scheme != "https" || r.URL.User != nil { |
| 134 | return errors.New("订阅重定向被拒绝") |
| 135 | } |
| 136 | return nil |
| 137 | }}, nil |
| 138 | } |
| 139 | func (s *Server) changeProxy(action string, in proxyInput, resumeVersion *uint64) error { |
| 140 | p, err := managedproxy.Load(s.profile) |
| 141 | if err != nil { |
| 142 | return err |
| 143 | } |
| 144 | cfg, err := loadConfig(s.configPath) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | ctx := s.operationContext() |
| 149 | if action == "stop" { |
| 150 | if err = s.closeProxyGate("内置代理已停止,外网保持关闭"); err != nil { |
| 151 | return err |
| 152 | } |
| 153 | return managedproxy.Stop(s.profile) |
| 154 | } |
| 155 | if action == "select" || action == "restart" || action == "route" { |
| 156 | if action == "route" { |
| 157 | if len(in.NodeIDs) == 0 { |
| 158 | return errors.New("请至少选择一个最终出口") |
| 159 | } |
| 160 | p.Chain = append([]string(nil), in.NodeIDs...) |
| 161 | p.Selected = p.Chain[len(p.Chain)-1] |
| 162 | if _, err := p.Route(); err != nil { |
| 163 | return err |
| 164 | } |
| 165 | } |
| 166 | if action == "select" { |
| 167 | if _, ok := p.Find(in.NodeID); !ok { |
| 168 | return errors.New("所选节点已不存在,请刷新列表") |
| 169 | } |
| 170 | p.Selected = in.NodeID |
| 171 | if len(p.Chain) > 0 { |
| 172 | p.Chain[len(p.Chain)-1] = in.NodeID |
| 173 | } |
| 174 | } |
| 175 | if in.Port != 0 { |
| 176 | if in.Port < 1024 || in.Port > 65535 { |
| 177 | return errors.New("代理端口应为 1024–65535") |
| 178 | } |
| 179 | p.Port = in.Port |
| 180 | } |
| 181 | return s.applyProxy(p, cfg, resumeVersion) |
| 182 | } |
| 183 | index := -1 |
| 184 | for i, src := range p.Sources { |
| 185 | if src.ID == in.ID { |
| 186 | index = i |
| 187 | break |
| 188 | } |
| 189 | } |
| 190 | if action == "delete" { |
| 191 | if index < 0 { |
| 192 | return errors.New("订阅来源不存在") |
| 193 | } |
| 194 | if len(p.Chain) > 1 { |
| 195 | for _, id := range p.Chain { |
| 196 | for _, n := range p.Sources[index].Nodes { |
| 197 | if n.ID == id { |
| 198 | return errors.New("该来源包含当前代理链中的节点,请先选择并应用其他来源的节点") |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | p.Sources = append(p.Sources[:index], p.Sources[index+1:]...) |
| 204 | if _, ok := p.Find(p.Selected); !ok { |
| 205 | p.Selected = "" |
| 206 | p.Chain = nil |
| 207 | } |
| 208 | } else if action == "edit" { |
| 209 | if index < 0 { |
| 210 | return errors.New("订阅来源不存在") |
| 211 | } |
| 212 | if strings.TrimSpace(in.Name) == "" || len(in.Name) > 100 || in.Interval < 0 || in.Interval > 168 { |
| 213 | return errors.New("名称或更新间隔无效") |
| 214 | } |
| 215 | p.Sources[index].Name = strings.TrimSpace(in.Name) |
| 216 | p.Sources[index].Interval = in.Interval |
| 217 | if in.URL != "" { |
| 218 | u, e := url.Parse(in.URL) |
| 219 | if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" { |
| 220 | return errors.New("订阅需要完整的 HTTPS 网址") |
| 221 | } |
| 222 | p.Sources[index].URL = in.URL |
| 223 | } |
| 224 | return p.Save(s.profile) |
| 225 | } else { |
| 226 | var data []byte |
| 227 | usage := "" |
| 228 | if action == "refresh" { |
| 229 | if index < 0 || p.Sources[index].URL == "" { |
| 230 | return errors.New("该来源没有订阅链接") |
| 231 | } |
| 232 | src := p.Sources[index] |
| 233 | in.Name, in.URL, in.Interval = src.Name, src.URL, src.Interval |
| 234 | } else { |
| 235 | data = []byte(in.Content) |
| 236 | in.ID = "" |
| 237 | } |
| 238 | if in.URL != "" { |
| 239 | s.setMessage("正在下载节点订阅…") |
| 240 | client, e := s.subscriptionClient(in.HostDownload) |
| 241 | if e != nil { |
| 242 | s.proxySourceFailure(in.ID, e) |
| 243 | return e |
| 244 | } |
| 245 | defer client.CloseIdleConnections() |
| 246 | data, usage, err = fetchProxySource(ctx, client, in.URL) |
| 247 | if err != nil { |
| 248 | if index >= 0 { |
| 249 | p.Sources[index].Error = err.Error() |
| 250 | p.Sources[index].Attempted = time.Now() |
| 251 | _ = p.Save(s.profile) |
| 252 | } |
| 253 | return err |
| 254 | } |
| 255 | } |
| 256 | if err = p.Import(in.Name, in.URL, data, in.ID, in.Interval, usage); err != nil { |
| 257 | s.proxySourceFailure(in.ID, err) |
| 258 | return err |
| 259 | } |
| 260 | candidate := p |
| 261 | if candidate.Selected == "" { |
| 262 | candidate.Selected = candidate.Sources[0].Nodes[0].ID |
| 263 | } |
| 264 | if _, ok := candidate.Find(candidate.Selected); !ok { |
| 265 | candidate.Selected = candidate.Sources[0].Nodes[0].ID |
| 266 | } |
| 267 | if err = validateProxyCore(ctx, s.profile, candidate); err != nil { |
| 268 | s.proxySourceFailure(in.ID, err) |
| 269 | return err |
| 270 | } |
| 271 | if _, ok := p.Find(p.Selected); !ok { |
| 272 | p.Selected = "" |
| 273 | } |
| 274 | } |
| 275 | if cfg.ProxyRevision != "" && cfg.ProxyURL == p.Endpoint() { |
| 276 | if p.Selected == "" { |
| 277 | if err = s.closeProxyGate("当前节点已被移除,请选择新节点"); err != nil { |
| 278 | return err |
| 279 | } |
| 280 | if err = managedproxy.Stop(s.profile); err != nil { |
| 281 | return err |
| 282 | } |
| 283 | return p.Save(s.profile) |
| 284 | } |
| 285 | return s.applyProxy(p, cfg, resumeVersion) |
| 286 | } |
| 287 | return p.Save(s.profile) |
| 288 | } |
| 289 | |
| 290 | func (s *Server) proxySourceFailure(id string, failure error) { |
| 291 | if id == "" { |
| 292 | return |
| 293 | } |
| 294 | p, err := managedproxy.Load(s.profile) |
| 295 | if err != nil { |
| 296 | return |
| 297 | } |
| 298 | for i := range p.Sources { |
| 299 | if p.Sources[i].ID == id { |
| 300 | p.Sources[i].Error = failure.Error() |
| 301 | p.Sources[i].Attempted = time.Now() |
| 302 | _ = p.Save(s.profile) |
| 303 | return |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | func (s *Server) closeProxyGate(reason string) error { |
| 308 | if !s.vmRunning() { |
| 309 | return nil |
| 310 | } |
| 311 | return s.revokeNetworkNow(reason, false) |
| 312 | } |
| 313 | |
| 314 | func (s *Server) activateProxy(p managedproxy.Store, old cage.Config) (returned error) { |
| 315 | |
| 316 | |
| 317 | return s.applyProxy(p, old, nil) |
| 318 | } |
| 319 | |
| 320 | func (s *Server) applyProxy(p managedproxy.Store, old cage.Config, resumeVersion *uint64) (returned error) { |
| 321 | ctx := s.operationContext() |
| 322 | previous, err := managedproxy.Load(s.profile) |
| 323 | if err != nil { |
| 324 | return err |
| 325 | } |
| 326 | s.setMessage("正在验证节点配置…") |
| 327 | if err := validateProxyCore(ctx, s.profile, p); err != nil { |
| 328 | return err |
| 329 | } |
| 330 | |
| 331 | |
| 332 | restartVM := s.vmRunning() && old.ProxyURL != p.Endpoint() |
| 333 | if err := s.closeProxyGate("代理节点切换中,旧连接及检测授权已关闭"); err != nil { |
| 334 | return err |
| 335 | } |
| 336 | if restartVM { |
| 337 | if err := s.stopEnvironment(); err != nil { |
| 338 | return err |
| 339 | } |
| 340 | } |
| 341 | s.setMessage("正在应用内置代理节点…") |
| 342 | if err := managedproxy.Stop(s.profile); err != nil { |
| 343 | return err |
| 344 | } |
| 345 | committed := false |
| 346 | defer func() { |
| 347 | if returned != nil && !committed { |
| 348 | _ = previous.Save(s.profile) |
| 349 | _ = writePrivate(s.configPath, old) |
| 350 | } |
| 351 | }() |
| 352 | p.Revision = managedproxy.Token() |
| 353 | if err := p.Save(s.profile); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | cfg := old |
| 357 | cfg.ProxyURL = p.Endpoint() |
| 358 | cfg.ProxyRevision = p.Revision |
| 359 | if err := writePrivate(s.configPath, cfg); err != nil { |
| 360 | return err |
| 361 | } |
| 362 | if err := startProxyCore(ctx, s.profile, p); err != nil { |
| 363 | return err |
| 364 | } |
| 365 | committed = true |
| 366 | if resumeVersion != nil { |
| 367 | if err := s.resumeNetworkIntentAt(*resumeVersion); err != nil { |
| 368 | return err |
| 369 | } |
| 370 | } |
| 371 | s.mu.Lock() |
| 372 | |
| 373 | |
| 374 | paused := s.networkPaused |
| 375 | s.exitProbeError = "" |
| 376 | s.locationError = "" |
| 377 | s.location = nil |
| 378 | s.safety.Report = nil |
| 379 | s.mu.Unlock() |
| 380 | if s.vmRunning() { |
| 381 | client, err := s.gateClient() |
| 382 | if err != nil { |
| 383 | return err |
| 384 | } |
| 385 | state, err := client.SyncProxyRevision(ctx) |
| 386 | if err != nil { |
| 387 | return err |
| 388 | } |
| 389 | s.publishGate(state) |
| 390 | if paused { |
| 391 | return nil |
| 392 | } |
| 393 | s.setMessage("节点已应用,正在重新检查环境出口…") |
| 394 | return s.runSafetyCheck() |
| 395 | } |
| 396 | if restartVM { |
| 397 | return s.startEnvironment(false) |
| 398 | } |
| 399 | s.setMessage("节点已应用;启动 Cage 环境后完成联网检查") |
| 400 | return nil |
| 401 | } |
| 402 | |
| 403 | func (s *Server) proxyDelay(w http.ResponseWriter, r *http.Request) { |
| 404 | var in proxyInput |
| 405 | if !readJSON(w, r, &in) { |
| 406 | return |
| 407 | } |
| 408 | p, err := managedproxy.Load(s.profile) |
| 409 | if err != nil { |
| 410 | requestError(w, err) |
| 411 | return |
| 412 | } |
| 413 | if _, ok := p.Find(in.NodeID); !ok { |
| 414 | requestError(w, errors.New("节点不存在")) |
| 415 | return |
| 416 | } |
| 417 | var v struct { |
| 418 | Delay int `json:"delay"` |
| 419 | } |
| 420 | err = managedproxy.API(r.Context(), s.profile, "GET", "/proxies/"+url.PathEscape(in.NodeID)+"/delay?timeout=5000&url="+url.QueryEscape("https://www.gstatic.com/generate_204"), nil, &v) |
| 421 | if err != nil { |
| 422 | requestError(w, errors.New("节点未载入核心或测速失败;请先应用节点以载入当前列表")) |
| 423 | return |
| 424 | } |
| 425 | jsonReply(w, v) |
| 426 | } |
| 427 | func (s *Server) proxyConnections(w http.ResponseWriter, r *http.Request) { |
| 428 | var response struct { |
| 429 | Upload int64 `json:"uploadTotal"` |
| 430 | Download int64 `json:"downloadTotal"` |
| 431 | Connections []struct { |
| 432 | ID string `json:"id"` |
| 433 | Upload int64 `json:"upload"` |
| 434 | Download int64 `json:"download"` |
| 435 | Metadata struct { |
| 436 | Network string `json:"network"` |
| 437 | Host string `json:"host"` |
| 438 | IP string `json:"destinationIP"` |
| 439 | Port string `json:"destinationPort"` |
| 440 | } `json:"metadata"` |
| 441 | } `json:"connections"` |
| 442 | } |
| 443 | if err := managedproxy.API(r.Context(), s.profile, "GET", "/connections", nil, &response); err != nil { |
| 444 | jsonReply(w, map[string]any{"connections": []any{}, "uploadTotal": 0, "downloadTotal": 0}) |
| 445 | return |
| 446 | } |
| 447 | items := []any{} |
| 448 | for i, c := range response.Connections { |
| 449 | if i >= 100 { |
| 450 | break |
| 451 | } |
| 452 | host := c.Metadata.Host |
| 453 | if host == "" { |
| 454 | host = c.Metadata.IP |
| 455 | } |
| 456 | items = append(items, map[string]any{"id": c.ID, "host": host, "port": c.Metadata.Port, "network": c.Metadata.Network, "upload": c.Upload, "download": c.Download}) |
| 457 | } |
| 458 | jsonReply(w, map[string]any{"connections": items, "uploadTotal": response.Upload, "downloadTotal": response.Download}) |
| 459 | } |
| 460 | func (s *Server) proxyLogs(w http.ResponseWriter, r *http.Request) { |
| 461 | p, err := managedproxy.Load(s.profile) |
| 462 | if err != nil { |
| 463 | requestError(w, err) |
| 464 | return |
| 465 | } |
| 466 | |
| 467 | |
| 468 | lines := []string{"客机公网 UDP、IPv6、ICMP:阻断", "业务 DNS:经选定节点转发", "代理基础设施 DNS:" + strings.Join(managedproxy.BootstrapDNSURLs(), "、") + "(主机网络,并行查询)"} |
| 469 | if managedproxy.Running(r.Context(), s.profile, p) { |
| 470 | lines = append(lines, "内置核心运行中;已读回当前节点选择") |
| 471 | } else { |
| 472 | lines = append(lines, "内置核心未就绪;不会直连回退") |
| 473 | } |
| 474 | for _, src := range p.Sources { |
| 475 | lines = append(lines, src.Updated.Format("2006-01-02 15:04")+" · "+src.Name+" · "+src.Error) |
| 476 | } |
| 477 | s.mu.Lock() |
| 478 | if issue := s.currentNetworkErrorLocked(); issue != "" { |
| 479 | lines = append(lines, issue) |
| 480 | } |
| 481 | s.mu.Unlock() |
| 482 | jsonReply(w, map[string]any{"lines": lines}) |
| 483 | } |
| 484 | func (s *Server) refreshProxySubscriptions() { |
| 485 | if s.busy() { |
| 486 | return |
| 487 | } |
| 488 | p, err := managedproxy.Load(s.profile) |
| 489 | if err != nil { |
| 490 | return |
| 491 | } |
| 492 | for _, src := range p.Sources { |
| 493 | if src.URL != "" && src.Interval > 0 && time.Since(src.Updated) >= time.Duration(src.Interval)*time.Hour && time.Since(src.Attempted) > 15*time.Minute { |
| 494 | |
| 495 | _, _ = s.submitJob("proxy-update", func() error { return s.changeProxy("refresh", proxyInput{ID: src.ID}, nil) }) |
| 496 | return |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | func (s *Server) checkProxyHealth() { |
| 502 | if s.busy() { |
| 503 | return |
| 504 | } |
| 505 | cfg, err := loadConfig(s.configPath) |
| 506 | if !s.vmRunning() { |
| 507 | return |
| 508 | } |
| 509 | if err != nil { |
| 510 | _ = s.closeProxyGate("代理配置无法读取,外网保持关闭") |
| 511 | return |
| 512 | } |
| 513 | p, err := managedproxy.Load(s.profile) |
| 514 | ctx, cancel := context.WithTimeout(s.lifetimeContext(), 2*time.Second) |
| 515 | defer cancel() |
| 516 | if err == nil && cfg.RequireManagedProxy(s.profile) == nil && managedproxy.Running(ctx, s.profile, p) { |
| 517 | return |
| 518 | } |
| 519 | _ = s.closeProxyGate("内置代理已中断或节点状态变化,请重试应用节点") |
| 520 | s.mu.Lock() |
| 521 | s.safety.monitorError = "内置代理未就绪;外网保持关闭" |
| 522 | s.mu.Unlock() |
| 523 | } |