| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | "al.essio.dev/pkg/shellescape" |
| 17 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 18 | ) |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | func (s *Server) connectProject(path string, add bool) (string, error) { |
| 24 | if path == "" { |
| 25 | path = s.workspace() |
| 26 | } |
| 27 | if isClientMountPath(path) { |
| 28 | return s.clientMountWorkspace(path) |
| 29 | } |
| 30 | path, err := validateWorkspace(path, s.profile) |
| 31 | if err != nil { |
| 32 | return "", err |
| 33 | } |
| 34 | if !add { |
| 35 | if path, err = s.projectWorkspace(path); err != nil { |
| 36 | return "", err |
| 37 | } |
| 38 | } |
| 39 | if err = s.ensureProjectShare(path); err != nil { |
| 40 | return "", err |
| 41 | } |
| 42 | if add { |
| 43 | if err = s.rememberSharedProject(path); err != nil { |
| 44 | return "", err |
| 45 | } |
| 46 | } |
| 47 | return path, nil |
| 48 | } |
| 49 | |
| 50 | func (s *Server) openProject(w http.ResponseWriter, r *http.Request) { |
| 51 | var input struct { |
| 52 | Workspace string `json:"workspace"` |
| 53 | Add bool `json:"add"` |
| 54 | Activate bool `json:"activate"` |
| 55 | } |
| 56 | if !readJSON(w, r, &input) { |
| 57 | return |
| 58 | } |
| 59 | if input.Workspace == "" { |
| 60 | http.Error(w, "请选择项目文件夹", 400) |
| 61 | return |
| 62 | } |
| 63 | if !s.op.TryLock() { |
| 64 | w.Header().Set("X-Cage-Recovery", "project-operation-busy") |
| 65 | http.Error(w, "另一个操作仍在进行,请稍候", 409) |
| 66 | return |
| 67 | } |
| 68 | defer s.op.Unlock() |
| 69 | s.mu.Lock() |
| 70 | ready, closing, preferences := s.ready, s.closing, s.preferences |
| 71 | s.mu.Unlock() |
| 72 | if closing || !ready || s.busy() { |
| 73 | http.Error(w, "环境尚未就绪或正在处理其他操作,请稍后重试", 409) |
| 74 | return |
| 75 | } |
| 76 | workspace, err := s.connectProject(input.Workspace, input.Add) |
| 77 | if errors.Is(err, errMacOSProjectApproval) { |
| 78 | path, pathErr := validateWorkspace(input.Workspace, s.profile) |
| 79 | if pathErr == nil { |
| 80 | s.mu.Lock() |
| 81 | share := s.projectShares[path] |
| 82 | grant := "" |
| 83 | if share != nil { |
| 84 | grant = share.approval |
| 85 | } |
| 86 | s.mu.Unlock() |
| 87 | if grant != "" { |
| 88 | |
| 89 | |
| 90 | ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Second) |
| 91 | _, openErr := s.guestControl(ctx, "/usr/bin/open -a /Applications/CageProjectAccess.app", "macos-project-approval") |
| 92 | cancel() |
| 93 | if openErr != nil { |
| 94 | w.Header().Set("X-Cage-Recovery", "project-approval") |
| 95 | requestError(w, errors.New("未能显示客机项目授权窗口,请重试")) |
| 96 | return |
| 97 | } |
| 98 | jsonReply(w, map[string]string{"workspace": path, "approval": grant}) |
| 99 | return |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | if err != nil { |
| 104 | var failure *projectShareError |
| 105 | if errors.As(err, &failure) && failure.Recovery != "" { |
| 106 | w.Header().Set("X-Cage-Recovery", failure.Recovery) |
| 107 | } |
| 108 | requestError(w, err) |
| 109 | return |
| 110 | } |
| 111 | if input.Activate && isClientMountPath(workspace) { |
| 112 | s.mu.Lock() |
| 113 | if m := s.clientMounts[workspace]; m == nil || !m.live() { |
| 114 | s.mu.Unlock() |
| 115 | requestError(w, errClientMountGone) |
| 116 | return |
| 117 | } |
| 118 | s.clientWorkspace = workspace |
| 119 | s.mu.Unlock() |
| 120 | } else if input.Activate { |
| 121 | preferences.Workspace = workspace |
| 122 | if err = writePrivate(filepath.Join(s.profile, "workbench.json"), preferences); err != nil { |
| 123 | requestError(w, err) |
| 124 | return |
| 125 | } |
| 126 | s.mu.Lock() |
| 127 | s.clientWorkspace = "" |
| 128 | s.preferences.Workspace = workspace |
| 129 | s.mu.Unlock() |
| 130 | } |
| 131 | jsonReply(w, map[string]string{"workspace": workspace}) |
| 132 | } |
| 133 | |
| 134 | type projectTransport struct { |
| 135 | io.ReadCloser |
| 136 | io.WriteCloser |
| 137 | } |
| 138 | |
| 139 | func (p projectTransport) Close() error { _ = p.ReadCloser.Close(); return p.WriteCloser.Close() } |
| 140 | |
| 141 | type projectShare struct { |
| 142 | cmd *exec.Cmd |
| 143 | transport projectTransport |
| 144 | done chan struct{} |
| 145 | once sync.Once |
| 146 | detach func() |
| 147 | approval string |
| 148 | approvalTimer *time.Timer |
| 149 | windowsProject *windowsProjectBinding |
| 150 | stderr *fileControlStderr |
| 151 | } |
| 152 | |
| 153 | func (p *projectShare) stop() { |
| 154 | p.once.Do(func() { |
| 155 | if p.cmd != nil && p.cmd.Process != nil { |
| 156 | _ = p.cmd.Process.Kill() |
| 157 | } |
| 158 | if p.transport.ReadCloser != nil { |
| 159 | _ = p.transport.Close() |
| 160 | } |
| 161 | }) |
| 162 | } |
| 163 | |
| 164 | func (p *projectShare) close() { |
| 165 | if p.approvalTimer != nil { |
| 166 | p.approvalTimer.Stop() |
| 167 | } |
| 168 | p.stop() |
| 169 | if p.done != nil { |
| 170 | <-p.done |
| 171 | } |
| 172 | if p.detach != nil { |
| 173 | p.detach() |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | |
| 178 | |
| 179 | func startProjectTransport(cmd *exec.Cmd, path string) (*projectShare, error) { |
| 180 | output, err := cmd.StdoutPipe() |
| 181 | if err != nil { |
| 182 | return nil, err |
| 183 | } |
| 184 | input, err := cmd.StdinPipe() |
| 185 | if err != nil { |
| 186 | _ = output.Close() |
| 187 | return nil, err |
| 188 | } |
| 189 | share := &projectShare{cmd: cmd, transport: projectTransport{output, input}, done: make(chan struct{})} |
| 190 | if err = cmd.Start(); err != nil { |
| 191 | _ = share.transport.Close() |
| 192 | return nil, err |
| 193 | } |
| 194 | go func() { |
| 195 | defer close(share.done) |
| 196 | _ = reversesshfs.ServeConfined(share.transport, path, false, nil) |
| 197 | share.stop() |
| 198 | _ = cmd.Wait() |
| 199 | }() |
| 200 | return share, nil |
| 201 | } |
| 202 | |
| 203 | |
| 204 | |
| 205 | func (s *Server) ensureProjectShare(path string) (returned error) { |
| 206 | s.mu.Lock() |
| 207 | closing := s.closing |
| 208 | s.mu.Unlock() |
| 209 | if closing { |
| 210 | return errJobsClosed |
| 211 | } |
| 212 | path, err := validateWorkspace(path, s.profile) |
| 213 | if err != nil { |
| 214 | return err |
| 215 | } |
| 216 | defer func() { |
| 217 | if returned != nil { |
| 218 | if _, err := s.projectWorkspace(path); err != nil { |
| 219 | return |
| 220 | } |
| 221 | } |
| 222 | s.setProjectError(path, returned) |
| 223 | }() |
| 224 | if s.windowsGuest != nil { |
| 225 | return s.ensureWindowsProjectShare(path) |
| 226 | } |
| 227 | if s.macosGuest != nil { |
| 228 | return s.ensureMacOSProjectShare(path) |
| 229 | } |
| 230 | if path == s.environmentDir() { |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | s.mu.Lock() |
| 235 | current := s.projectShares[path] |
| 236 | s.mu.Unlock() |
| 237 | if current != nil { |
| 238 | select { |
| 239 | case <-current.done: |
| 240 | current.close() |
| 241 | default: |
| 242 | return nil |
| 243 | } |
| 244 | } |
| 245 | ctx, cancel := context.WithTimeout(s.operationContext(), 15*time.Second) |
| 246 | defer cancel() |
| 247 | quoted := shellescape.Quote(guestPath(path)) |
| 248 | |
| 249 | |
| 250 | if _, err = s.guest(ctx, "if mountpoint -q "+quoted+"; then fusermount3 -uz "+quoted+"; fi; sudo mkdir -p "+quoted+" && sudo chown \"$(id -u):$(id -g)\" "+quoted); err != nil { |
| 251 | return errors.New("无法在 Cage 中准备项目目录") |
| 252 | } |
| 253 | probe, err := os.CreateTemp(path, ".cage-mount-probe-*") |
| 254 | if err != nil { |
| 255 | return fmt.Errorf("无法验证项目目录的读写权限:%w", err) |
| 256 | } |
| 257 | defer os.Remove(probe.Name()) |
| 258 | challenge := randomToken() |
| 259 | if _, err = probe.WriteString(challenge); err != nil { |
| 260 | _ = probe.Close() |
| 261 | return err |
| 262 | } |
| 263 | if err = probe.Close(); err != nil { |
| 264 | return err |
| 265 | } |
| 266 | |
| 267 | |
| 268 | script := "exec sshfs " + shellescape.Quote(":"+filepath.ToSlash(path)) + " " + quoted + ` -o slave,allow_other,cache=no,nodev,nosuid,uid="$(id -u)",gid="$(id -g)"` |
| 269 | cmd := s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", script) |
| 270 | share, err := startProjectTransport(cmd, path) |
| 271 | if err != nil { |
| 272 | return err |
| 273 | } |
| 274 | for { |
| 275 | if _, err = s.guest(ctx, "mountpoint -q "+quoted+" && test \"$(cat "+shellescape.Quote(guestPath(probe.Name()))+")\" = "+shellescape.Quote(challenge)); err == nil { |
| 276 | break |
| 277 | } |
| 278 | select { |
| 279 | case <-ctx.Done(): |
| 280 | share.close() |
| 281 | return errors.New("项目文件夹连接超时,原有环境与会话保持运行") |
| 282 | case <-share.done: |
| 283 | share.close() |
| 284 | return errors.New("项目文件夹未能连接,原有环境与会话保持运行") |
| 285 | case <-time.After(100 * time.Millisecond): |
| 286 | } |
| 287 | } |
| 288 | s.mu.Lock() |
| 289 | if s.projectShares == nil { |
| 290 | s.projectShares = map[string]*projectShare{} |
| 291 | } |
| 292 | s.projectShares[path] = share |
| 293 | s.mu.Unlock() |
| 294 | return nil |
| 295 | } |
| 296 | |
| 297 | type sharedProjects struct { |
| 298 | Paths []string `json:"paths"` |
| 299 | } |
| 300 | |
| 301 | type projectShareError struct { |
| 302 | Path string `json:"path"` |
| 303 | Message string `json:"message"` |
| 304 | Recovery string `json:"recovery,omitempty"` |
| 305 | } |
| 306 | |
| 307 | func (e *projectShareError) Error() string { return e.Message } |
| 308 | |
| 309 | func projectShareFailure(path string, err error) projectShareError { |
| 310 | value := projectShareError{Path: path, Message: err.Error()} |
| 311 | var failure *projectShareError |
| 312 | if errors.As(err, &failure) { |
| 313 | value.Recovery = failure.Recovery |
| 314 | } |
| 315 | return value |
| 316 | } |
| 317 | |
| 318 | func (s *Server) setProjectError(path string, err error) { |
| 319 | s.mu.Lock() |
| 320 | defer s.mu.Unlock() |
| 321 | for i, failure := range s.projectErrors { |
| 322 | if failure.Path == path { |
| 323 | if err == nil { |
| 324 | s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...) |
| 325 | } else { |
| 326 | s.projectErrors[i] = projectShareFailure(path, err) |
| 327 | } |
| 328 | return |
| 329 | } |
| 330 | } |
| 331 | if err != nil { |
| 332 | s.projectErrors = append(s.projectErrors, projectShareFailure(path, err)) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | |
| 337 | |
| 338 | func (s *Server) projectPaths() ([]string, error) { |
| 339 | var saved sharedProjects |
| 340 | if b, err := os.ReadFile(filepath.Join(s.profile, "projects.json")); err == nil { |
| 341 | if err = json.Unmarshal(b, &saved); err != nil { |
| 342 | return nil, err |
| 343 | } |
| 344 | } else if !os.IsNotExist(err) { |
| 345 | return nil, err |
| 346 | } |
| 347 | paths := []string{s.environmentDir()} |
| 348 | s.mu.Lock() |
| 349 | current := s.preferences.Workspace |
| 350 | s.mu.Unlock() |
| 351 | for _, path := range append(saved.Paths, current) { |
| 352 | found := path == "" |
| 353 | for _, existing := range paths { |
| 354 | found = found || path == existing |
| 355 | } |
| 356 | if !found { |
| 357 | paths = append(paths, path) |
| 358 | } |
| 359 | } |
| 360 | return s.appendClientMounts(paths), nil |
| 361 | } |
| 362 | |
| 363 | func (s *Server) projectWorkspace(path string) (string, error) { |
| 364 | if path == "" { |
| 365 | path = s.workspace() |
| 366 | } |
| 367 | if isClientMountPath(path) { |
| 368 | return s.clientMountWorkspace(path) |
| 369 | } |
| 370 | paths, err := s.projectPaths() |
| 371 | if err != nil { |
| 372 | return "", errors.New("无法读取项目列表,请检查项目配置") |
| 373 | } |
| 374 | for _, authorized := range paths { |
| 375 | if path == authorized { |
| 376 | return validateWorkspace(path, s.profile) |
| 377 | } |
| 378 | } |
| 379 | return "", errors.New("请先通过打开项目添加该文件夹") |
| 380 | } |
| 381 | |
| 382 | func (s *Server) rememberSharedProject(path string) error { |
| 383 | if path == s.environmentDir() { |
| 384 | return nil |
| 385 | } |
| 386 | var saved sharedProjects |
| 387 | if b, err := os.ReadFile(filepath.Join(s.profile, "projects.json")); err == nil { |
| 388 | if err = json.Unmarshal(b, &saved); err != nil { |
| 389 | return err |
| 390 | } |
| 391 | } else if !os.IsNotExist(err) { |
| 392 | return err |
| 393 | } |
| 394 | for _, p := range saved.Paths { |
| 395 | if p == path { |
| 396 | return nil |
| 397 | } |
| 398 | } |
| 399 | saved.Paths = append(saved.Paths, path) |
| 400 | return writePrivate(filepath.Join(s.profile, "projects.json"), saved) |
| 401 | } |
| 402 | func (s *Server) restoreProjectShares() { |
| 403 | var saved sharedProjects |
| 404 | if b, err := os.ReadFile(filepath.Join(s.profile, "projects.json")); err == nil { |
| 405 | _ = json.Unmarshal(b, &saved) |
| 406 | } |
| 407 | if s.macosGuest != nil { |
| 408 | saved.Paths = append([]string{s.environmentDir()}, saved.Paths...) |
| 409 | } |
| 410 | s.mu.Lock() |
| 411 | current := s.preferences.Workspace |
| 412 | s.mu.Unlock() |
| 413 | if current != "" && current != s.environmentDir() { |
| 414 | found := false |
| 415 | for _, p := range saved.Paths { |
| 416 | found = found || p == current |
| 417 | } |
| 418 | if !found { |
| 419 | saved.Paths = append(saved.Paths, current) |
| 420 | } |
| 421 | } |
| 422 | var failures []projectShareError |
| 423 | for _, path := range saved.Paths { |
| 424 | if err := s.ensureProjectShare(path); err != nil { |
| 425 | failures = append(failures, projectShareFailure(path, err)) |
| 426 | } else if err := s.rememberSharedProject(path); err != nil { |
| 427 | failures = append(failures, projectShareError{Path: path, Message: "项目已连接,但未能保存项目记录:" + err.Error()}) |
| 428 | } |
| 429 | } |
| 430 | s.mu.Lock() |
| 431 | s.projectErrors = failures |
| 432 | s.mu.Unlock() |
| 433 | } |
| 434 | func (s *Server) closeProjectShares() { |
| 435 | s.closeClientMounts() |
| 436 | s.mu.Lock() |
| 437 | shares := s.projectShares |
| 438 | s.projectShares = nil |
| 439 | s.mu.Unlock() |
| 440 | for _, share := range shares { |
| 441 | share.stop() |
| 442 | } |
| 443 | for _, share := range shares { |
| 444 | share.close() |
| 445 | } |
| 446 | } |