| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "os" |
| 12 | "os/exec" |
| 13 | pathpkg "path" |
| 14 | "path/filepath" |
| 15 | "runtime" |
| 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/sylvinus/agent-vm/internal/host" |
| 20 | ) |
| 21 | |
| 22 | type desktopFileOpen struct { |
| 23 | ID string `json:"id,omitempty"` |
| 24 | Path string `json:"path,omitempty"` |
| 25 | Action string `json:"action,omitempty"` |
| 26 | Handled bool `json:"handled,omitempty"` |
| 27 | } |
| 28 | |
| 29 | |
| 30 | |
| 31 | func resolveProjectFilePath(guest string, projects []string) (string, error) { |
| 32 | if !pathpkg.IsAbs(guest) || pathpkg.Clean(guest) != guest || strings.ContainsAny(guest, "\x00\\") { |
| 33 | return "", errors.New("文件位置无效") |
| 34 | } |
| 35 | for _, project := range projects { |
| 36 | if isClientMountPath(project) { |
| 37 | continue |
| 38 | } |
| 39 | root := strings.TrimRight(guestPath(project), "/") |
| 40 | if guest != root && !strings.HasPrefix(guest, root+"/") { |
| 41 | continue |
| 42 | } |
| 43 | hostRoot, err := filepath.EvalSymlinks(project) |
| 44 | if err != nil { |
| 45 | continue |
| 46 | } |
| 47 | target, err := filepath.EvalSymlinks(filepath.Join(hostRoot, filepath.FromSlash(strings.TrimPrefix(guest, root)))) |
| 48 | if err != nil { |
| 49 | return "", errors.New("文件已移动、删除或无法访问") |
| 50 | } |
| 51 | relative, err := filepath.Rel(hostRoot, target) |
| 52 | if err != nil || relative == ".." || strings.HasPrefix(relative, ".."+string(filepath.Separator)) || filepath.IsAbs(relative) { |
| 53 | return "", errors.New("文件指向 Cage 项目目录之外,无法打开") |
| 54 | } |
| 55 | info, err := os.Stat(target) |
| 56 | if err != nil || (!info.Mode().IsRegular() && !info.IsDir()) { |
| 57 | return "", errors.New("请选择 Cage 项目中的普通文件或文件夹") |
| 58 | } |
| 59 | return target, nil |
| 60 | } |
| 61 | return "", errors.New("只能打开 Cage 项目目录中的文件和文件夹") |
| 62 | } |
| 63 | |
| 64 | func (s *Server) resolveDesktopProjectFile(guest string, projects []string) (string, error) { |
| 65 | if s.macosGuest == nil && s.windowsGuest == nil { |
| 66 | return resolveProjectFilePath(guest, projects) |
| 67 | } |
| 68 | if s.windowsGuest != nil { |
| 69 | guest = strings.ReplaceAll(guest, "\\", "/") |
| 70 | if !windowsCLIAbsolutePath(guest) || strings.Contains(guest[2:], ":") { |
| 71 | return "", errors.New("文件位置无效") |
| 72 | } |
| 73 | } |
| 74 | if pathpkg.Clean(guest) != guest || strings.ContainsAny(guest, "\x00\\") { |
| 75 | return "", errors.New("文件位置无效") |
| 76 | } |
| 77 | for _, project := range projects { |
| 78 | if isClientMountPath(project) { |
| 79 | continue |
| 80 | } |
| 81 | var root string |
| 82 | if s.macosGuest != nil { |
| 83 | root = macOSProjectPath(s.macosGuest.User, project) |
| 84 | } else { |
| 85 | binding, err := s.windowsProjectForHost(project) |
| 86 | if err != nil { |
| 87 | continue |
| 88 | } |
| 89 | root = strings.ReplaceAll(binding.Path, "\\", "/") |
| 90 | } |
| 91 | root = strings.TrimRight(root, "/") |
| 92 | if !cliWorkspaceWithin(guest, root, s.windowsGuest != nil) { |
| 93 | continue |
| 94 | } |
| 95 | mapped := strings.TrimRight(guestPath(project), "/") + guest[len(root):] |
| 96 | return resolveProjectFilePath(mapped, []string{project}) |
| 97 | } |
| 98 | return "", errors.New("只能打开已授权 Cage 项目中的文件和文件夹") |
| 99 | } |
| 100 | |
| 101 | func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) { |
| 102 | var input struct { |
| 103 | ID string `json:"id"` |
| 104 | Stage string `json:"stage"` |
| 105 | Error string `json:"error"` |
| 106 | } |
| 107 | if !readJSON(w, r, &input) { |
| 108 | return |
| 109 | } |
| 110 | if !browserFileID.MatchString(input.ID) || (input.Stage != "claim" && input.Stage != "complete") { |
| 111 | http.Error(w, "文件打开请求无效", 400) |
| 112 | return |
| 113 | } |
| 114 | if !s.fileTargetReady("desktop", "") { |
| 115 | http.Error(w, "环境尚未就绪", 409) |
| 116 | return |
| 117 | } |
| 118 | ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute) |
| 119 | defer cancel() |
| 120 | body, _ := json.Marshal(input) |
| 121 | result, err := s.guestFiles(ctx, "desktop", "POST", "/open-"+input.Stage, bytes.NewReader(body), "") |
| 122 | if err != nil { |
| 123 | requestError(w, err) |
| 124 | return |
| 125 | } |
| 126 | if input.Stage == "complete" || result["handled"] == true { |
| 127 | jsonReply(w, result) |
| 128 | return |
| 129 | } |
| 130 | guest, _ := result["path"].(string) |
| 131 | action, _ := result["action"].(string) |
| 132 | var target string |
| 133 | download, _ := result["download_id"].(string) |
| 134 | if message, _ := result["error"].(string); message != "" { |
| 135 | err = errors.New(message) |
| 136 | } else if action != "open" && action != "reveal" { |
| 137 | err = errors.New("文件打开操作无效") |
| 138 | } else if download != "" && (s.macosGuest != nil || s.windowsGuest != nil) { |
| 139 | var saved browserDownloadInfo |
| 140 | saved, err = s.downloadInfo(ctx, download) |
| 141 | if err == nil && saved.State != "saved" { |
| 142 | err = errors.New("文件尚未完整保存到主机,请稍后重新打开") |
| 143 | } |
| 144 | target = saved.Path |
| 145 | if err == nil && result["directory"] == true { |
| 146 | target = filepath.Dir(target) |
| 147 | } |
| 148 | } else { |
| 149 | var projects []string |
| 150 | projects, err = s.projectPaths() |
| 151 | if err == nil { |
| 152 | target, err = s.resolveDesktopProjectFile(guest, projects) |
| 153 | } |
| 154 | } |
| 155 | if err != nil { |
| 156 | body, _ = json.Marshal(map[string]string{"id": input.ID, "error": err.Error()}) |
| 157 | cleanup, cancelCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| 158 | defer cancelCleanup() |
| 159 | _, _ = s.guestFiles(cleanup, "desktop", "POST", "/open-complete", bytes.NewReader(body), "") |
| 160 | requestError(w, err) |
| 161 | return |
| 162 | } |
| 163 | jsonReply(w, desktopFileOpen{ID: input.ID, Path: target, Action: action}) |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | func DesktopFileForConnection(configPath, connectionID, id string) (map[string]any, error) { |
| 169 | if !browserFileID.MatchString(id) { |
| 170 | return nil, errors.New("文件打开标识无效") |
| 171 | } |
| 172 | client, err := connectController(filepath.Dir(configPath)) |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | defer client.close() |
| 177 | entry, _ := url.Parse(client.launch.URL) |
| 178 | status, err := client.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil) |
| 179 | if err != nil || status != 200 { |
| 180 | return nil, errors.New("无法连接文件操作会话") |
| 181 | } |
| 182 | connection, err := client.bindConnection(connectionID) |
| 183 | if err != nil { |
| 184 | return nil, err |
| 185 | } |
| 186 | var request desktopFileOpen |
| 187 | err = desktopOpenCall(client, map[string]string{"id": id, "stage": "claim"}, &request) |
| 188 | if err != nil { |
| 189 | return nil, err |
| 190 | } |
| 191 | if request.Handled { |
| 192 | return map[string]any{"handled": true}, nil |
| 193 | } |
| 194 | if connection.Mode == "remote" { |
| 195 | err = errors.New("此文件位于远程环境,请先在下载列表中保存到本机") |
| 196 | } else if request.ID != id || !filepath.IsAbs(request.Path) || (request.Action != "open" && request.Action != "reveal") { |
| 197 | err = errors.New("文件打开响应无效") |
| 198 | } else { |
| 199 | err = openHostFile(request.Path, request.Action) |
| 200 | } |
| 201 | message := "" |
| 202 | if err != nil { |
| 203 | message = err.Error() |
| 204 | } |
| 205 | completeErr := desktopOpenCall(client, map[string]string{"id": id, "stage": "complete", "error": message}, nil) |
| 206 | if err != nil { |
| 207 | return nil, err |
| 208 | } |
| 209 | if completeErr != nil { |
| 210 | return nil, completeErr |
| 211 | } |
| 212 | return map[string]any{"ok": true}, nil |
| 213 | } |
| 214 | |
| 215 | func desktopOpenCall(client *controllerClient, input map[string]string, output any) error { |
| 216 | body, _ := json.Marshal(input) |
| 217 | request, _ := http.NewRequest("POST", client.origin+"/api/input/files/desktop/open", bytes.NewReader(body)) |
| 218 | request.Header.Set("Origin", client.origin) |
| 219 | request.Header.Set("Content-Type", "application/json") |
| 220 | response, err := client.client.Do(request) |
| 221 | if err != nil { |
| 222 | return errors.New("文件操作连接已中断,请重新打开") |
| 223 | } |
| 224 | defer response.Body.Close() |
| 225 | data, err := io.ReadAll(io.LimitReader(response.Body, 65537)) |
| 226 | if err != nil || len(data) > 65536 { |
| 227 | return errors.New("文件操作响应无效") |
| 228 | } |
| 229 | if response.StatusCode != http.StatusOK { |
| 230 | message := strings.TrimSpace(string(data)) |
| 231 | if message == "" { |
| 232 | message = "文件打开请求已失效,请重新操作" |
| 233 | } |
| 234 | return errors.New(message) |
| 235 | } |
| 236 | if output != nil && json.Unmarshal(data, output) != nil { |
| 237 | return errors.New("文件操作响应无效") |
| 238 | } |
| 239 | return nil |
| 240 | } |
| 241 | |
| 242 | func hostFileCommand(platform, path, action string, directory bool) *exec.Cmd { |
| 243 | switch platform { |
| 244 | case "darwin": |
| 245 | if action == "reveal" { |
| 246 | return exec.Command("/usr/bin/open", "-R", "--", path) |
| 247 | } |
| 248 | return exec.Command("/usr/bin/open", "--", path) |
| 249 | case "windows": |
| 250 | if action == "reveal" { |
| 251 | return exec.Command("explorer.exe", "/select,"+path) |
| 252 | } |
| 253 | if directory { |
| 254 | return exec.Command("explorer.exe", path) |
| 255 | } |
| 256 | return exec.Command("rundll32.exe", "url.dll,FileProtocolHandler", path) |
| 257 | default: |
| 258 | if action == "reveal" { |
| 259 | uri := (&url.URL{Scheme: "file", Path: filepath.ToSlash(path)}).String() |
| 260 | return exec.Command("gdbus", "call", "--session", "--dest", "org.freedesktop.FileManager1", "--object-path", "/org/freedesktop/FileManager1", "--method", "org.freedesktop.FileManager1.ShowItems", "[\""+uri+"\"]", "") |
| 261 | } |
| 262 | return exec.Command("gio", "open", path) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | func openHostFile(path, action string) error { |
| 267 | info, err := os.Stat(path) |
| 268 | if err != nil || (!info.Mode().IsRegular() && !info.IsDir()) { |
| 269 | return errors.New("文件已移动、删除或无法访问") |
| 270 | } |
| 271 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 272 | defer cancel() |
| 273 | command := hostFileCommand(runtime.GOOS, path, action, info.IsDir()) |
| 274 | cmd := exec.CommandContext(ctx, command.Path, command.Args[1:]...) |
| 275 | host.HideCommandWindow(cmd) |
| 276 | if err = cmd.Run(); err != nil { |
| 277 | if runtime.GOOS != "linux" || action != "reveal" { |
| 278 | return errors.New("无法打开本机文件或文件管理器,请检查默认应用和文件权限") |
| 279 | } |
| 280 | fallback := exec.CommandContext(ctx, "gio", "open", filepath.Dir(path)) |
| 281 | if fallback.Run() != nil { |
| 282 | return errors.New("无法打开本机文件管理器,请检查桌面环境和文件权限") |
| 283 | } |
| 284 | } |
| 285 | return nil |
| 286 | } |