| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "os" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "strconv" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | "github.com/sylvinus/agent-vm/internal/host" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | func desktopConfigPath(fullConfig string) string { |
| 19 | return filepath.Join(filepath.Dir(fullConfig), "desktop-entry", "config.json") |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | func DesktopHelperConfig(fullConfig, connection string) string { |
| 26 | if connection != "" && connection != "local" { |
| 27 | entry := desktopConfigPath(fullConfig) |
| 28 | if _, err := os.Lstat(filepath.Join(filepath.Dir(entry), "control.json")); !os.IsNotExist(err) { |
| 29 | return entry |
| 30 | } |
| 31 | } |
| 32 | return fullConfig |
| 33 | } |
| 34 | |
| 35 | func DesktopEntry(fullConfig string, opts DesktopOptions) (DesktopResult, error) { |
| 36 | |
| 37 | |
| 38 | if opts.UseExisting { |
| 39 | c, err := connectController(filepath.Dir(fullConfig)) |
| 40 | if err == nil { |
| 41 | defer c.close() |
| 42 | want, err := currentController() |
| 43 | if err != nil { |
| 44 | return DesktopResult{}, err |
| 45 | } |
| 46 | if !want.matches(c.launch.Controller) { |
| 47 | return DesktopResult{Status: "existing", URL: c.launch.URL, Controller: c.launch.Controller, Legacy: c.launch.Controller.Protocol == 0}, nil |
| 48 | } |
| 49 | } else if !errors.Is(err, errControllerUnavailable) { |
| 50 | return DesktopResult{}, err |
| 51 | } |
| 52 | } |
| 53 | if opts.CompleteUpdate { |
| 54 | if _, err := PrepareDesktopUpdate(fullConfig, true); err != nil { |
| 55 | return DesktopResult{}, err |
| 56 | } |
| 57 | opts.CompleteUpdate = false |
| 58 | } |
| 59 | profile := filepath.Dir(desktopConfigPath(fullConfig)) |
| 60 | owner := 0 |
| 61 | if value := os.Getenv("CAGE_DESKTOP_OWNER_PID"); value != "" { |
| 62 | var err error |
| 63 | if owner, err = strconv.Atoi(value); err != nil || owner < 2 { |
| 64 | return DesktopResult{}, errors.New("桌面窗口进程标识无效") |
| 65 | } |
| 66 | } |
| 67 | result, err := desktopLaunch(profile, true, opts, func() error { |
| 68 | if err := host.EnsurePrivateDir(profile); err != nil { |
| 69 | return err |
| 70 | } |
| 71 | exe, err := os.Executable() |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | cmd := exec.Command(exe, "serve-desktop") |
| 76 | cmd.Dir = profile |
| 77 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+fullConfig) |
| 78 | detachController(cmd) |
| 79 | if err := cmd.Start(); err != nil { |
| 80 | return err |
| 81 | } |
| 82 | return cmd.Process.Release() |
| 83 | }) |
| 84 | if err != nil || owner == 0 || result.URL == "" { |
| 85 | return result, err |
| 86 | } |
| 87 | c, err := connectController(profile) |
| 88 | if err != nil { |
| 89 | return DesktopResult{}, err |
| 90 | } |
| 91 | defer c.close() |
| 92 | if !c.launch.DesktopGateway || c.launch.Controller.PID != result.Controller.PID { |
| 93 | return DesktopResult{}, errors.New("桌面连接服务身份不匹配") |
| 94 | } |
| 95 | code, err := c.call("POST", "/api/desktop-owner", map[string]any{"token": c.record.Token, "pid": owner}, nil) |
| 96 | if err != nil || code != http.StatusOK { |
| 97 | return DesktopResult{}, errors.New("无法关联桌面窗口和连接服务") |
| 98 | } |
| 99 | return result, nil |
| 100 | } |
| 101 | |
| 102 | func (s *Server) registerDesktopOwner(w http.ResponseWriter, r *http.Request) { |
| 103 | var input struct { |
| 104 | Token string `json:"token"` |
| 105 | PID int `json:"pid"` |
| 106 | } |
| 107 | if !readJSON(w, r, &input) { |
| 108 | return |
| 109 | } |
| 110 | if !equalSecret(input.Token, s.token) || input.PID < 2 || !processExists(input.PID) { |
| 111 | http.Error(w, "桌面窗口身份无效", http.StatusForbidden) |
| 112 | return |
| 113 | } |
| 114 | s.mu.Lock() |
| 115 | defer s.mu.Unlock() |
| 116 | if s.closing { |
| 117 | http.Error(w, "桌面入口正在退出", http.StatusConflict) |
| 118 | return |
| 119 | } |
| 120 | if s.windowOwners == nil { |
| 121 | s.windowOwners = make(map[int]bool) |
| 122 | } |
| 123 | s.windowOwners[input.PID] = true |
| 124 | jsonReply(w, map[string]bool{"ok": true}) |
| 125 | } |
| 126 | |
| 127 | func (s *Server) watchDesktopOwners(done <-chan struct{}) { |
| 128 | |
| 129 | |
| 130 | initial, _ := strconv.Atoi(os.Getenv("CAGE_DESKTOP_OWNER_PID")) |
| 131 | if initial > 1 { |
| 132 | s.mu.Lock() |
| 133 | if s.windowOwners == nil { |
| 134 | s.windowOwners = make(map[int]bool) |
| 135 | } |
| 136 | s.windowOwners[initial] = true |
| 137 | s.mu.Unlock() |
| 138 | } |
| 139 | ticker := time.NewTicker(time.Second) |
| 140 | defer ticker.Stop() |
| 141 | for { |
| 142 | select { |
| 143 | case <-done: |
| 144 | return |
| 145 | case <-ticker.C: |
| 146 | s.mu.Lock() |
| 147 | hadOwners := len(s.windowOwners) > 0 |
| 148 | for pid := range s.windowOwners { |
| 149 | if !processExists(pid) { |
| 150 | delete(s.windowOwners, pid) |
| 151 | } |
| 152 | } |
| 153 | exit := hadOwners && len(s.windowOwners) == 0 |
| 154 | if exit { |
| 155 | s.closing = true |
| 156 | } |
| 157 | s.mu.Unlock() |
| 158 | if exit { |
| 159 | s.shutdown() |
| 160 | return |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | func (s *Server) handoffEntry(w http.ResponseWriter, r *http.Request) { |
| 167 | if !s.launcherAuthenticated(w, r) { |
| 168 | return |
| 169 | } |
| 170 | jsonReply(w, map[string]bool{"stopping": true}) |
| 171 | _ = http.NewResponseController(w).Flush() |
| 172 | go s.shutdown() |
| 173 | } |
| 174 | |
| 175 | func (c *controllerClient) releaseDesktopEntry() error { |
| 176 | if !c.launch.DesktopGateway { |
| 177 | return errors.New("无法核对桌面连接服务身份") |
| 178 | } |
| 179 | status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) |
| 180 | if err != nil || status != http.StatusOK { |
| 181 | return errors.New("桌面连接服务未能退出") |
| 182 | } |
| 183 | return c.waitForExit() |
| 184 | } |
| 185 | |
| 186 | |
| 187 | |
| 188 | func PrepareDesktopUpdate(fullConfig string, stop bool) (DesktopResult, error) { |
| 189 | result, err := PrepareUpdate(fullConfig, stop) |
| 190 | if err != nil || result.Status != "prepared" { |
| 191 | return result, err |
| 192 | } |
| 193 | profile := filepath.Dir(desktopConfigPath(fullConfig)) |
| 194 | c, err := connectController(profile) |
| 195 | if errors.Is(err, errControllerUnavailable) { |
| 196 | |
| 197 | return PrepareUpdate(desktopConfigPath(fullConfig), false) |
| 198 | } |
| 199 | if err != nil { |
| 200 | return DesktopResult{}, err |
| 201 | } |
| 202 | defer c.close() |
| 203 | if err = c.releaseDesktopEntry(); err != nil { |
| 204 | return DesktopResult{}, err |
| 205 | } |
| 206 | return result, nil |
| 207 | } |