| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/url" |
| 13 | "os/exec" |
| 14 | "time" |
| 15 | "unicode/utf8" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 18 | ) |
| 19 | |
| 20 | func (s *Server) nativeBrowserClient() *windowsBrowserClient { |
| 21 | s.mu.Lock() |
| 22 | defer s.mu.Unlock() |
| 23 | if s.windowsBrowserControl == nil { |
| 24 | if s.macosGuest != nil { |
| 25 | ctx, cancel := context.WithCancel(s.lifetimeContextLocked()) |
| 26 | s.windowsBrowserControl = &windowsBrowserClient{ctx: ctx, cancel: cancel, ownsBrowser: true, start: func(ctx context.Context) (*exec.Cmd, error) { |
| 27 | const base = "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/" |
| 28 | return s.macOSSSHCommand(ctx, "-T", s.sshTarget(), "--", "exec "+base+"editor/lib/node "+base+"controller/macos-native-browser.mjs"), nil |
| 29 | }} |
| 30 | } else { |
| 31 | s.windowsBrowserControl = newWindowsBrowserClient(s.lifetimeContextLocked(), s.profile) |
| 32 | } |
| 33 | } |
| 34 | return s.windowsBrowserControl |
| 35 | } |
| 36 | |
| 37 | func (s *Server) closeWindowsBrowser() { |
| 38 | s.mu.Lock() |
| 39 | browser := s.windowsBrowserControl |
| 40 | s.windowsBrowserControl = nil |
| 41 | s.mu.Unlock() |
| 42 | if browser != nil { |
| 43 | browser.close() |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func (s *Server) nativeBrowserAPI(ctx context.Context, method, path string, body []byte) ([]byte, error) { |
| 48 | if method == http.MethodPost && path == "/paste-image" { |
| 49 | var input struct { |
| 50 | ID string `json:"id"` |
| 51 | PNG string `json:"png"` |
| 52 | Transfer string `json:"transfer"` |
| 53 | } |
| 54 | if json.Unmarshal(body, &input) != nil { |
| 55 | return nil, browserInputError{errors.New("图片粘贴请求无效")} |
| 56 | } |
| 57 | data, err := decodeInputImage(input.PNG) |
| 58 | if err != nil { |
| 59 | return nil, browserInputError{err} |
| 60 | } |
| 61 | return s.nativeBrowserClient().pasteImage(ctx, input.ID, data, input.Transfer) |
| 62 | } |
| 63 | var input any |
| 64 | if len(body) != 0 && json.Unmarshal(body, &input) != nil { |
| 65 | return nil, browserInputError{errors.New("浏览器请求无效")} |
| 66 | } |
| 67 | return s.nativeBrowserClient().request(ctx, method, path, input) |
| 68 | } |
| 69 | |
| 70 | type browserClipboardInput struct { |
| 71 | ID string `json:"id"` |
| 72 | Tab string `json:"tab"` |
| 73 | Context string `json:"context"` |
| 74 | Document string `json:"document"` |
| 75 | } |
| 76 | |
| 77 | func (s *Server) browserClipboard(w http.ResponseWriter, r *http.Request) { |
| 78 | var input browserClipboardInput |
| 79 | if !readJSON(w, r, &input) { |
| 80 | return |
| 81 | } |
| 82 | if !browserFileID.MatchString(input.ID) || !validInputToken(input.Tab) || !validInputToken(input.Context) || !validInputToken(input.Document) { |
| 83 | http.Error(w, "复制内容或网页上下文无效", http.StatusBadRequest) |
| 84 | return |
| 85 | } |
| 86 | s.mu.Lock() |
| 87 | ready := s.ready |
| 88 | s.mu.Unlock() |
| 89 | if !ready { |
| 90 | http.Error(w, "环境尚未就绪", http.StatusConflict) |
| 91 | return |
| 92 | } |
| 93 | if s.macosGuest == nil { |
| 94 | http.Error(w, "当前客机使用系统共享剪贴板", http.StatusNotImplemented) |
| 95 | return |
| 96 | } |
| 97 | ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| 98 | defer cancel() |
| 99 | reader, size, mime, err := s.nativeBrowserClient().downloadClipboard(ctx, input) |
| 100 | if err != nil { |
| 101 | http.Error(w, err.Error(), http.StatusBadGateway) |
| 102 | return |
| 103 | } |
| 104 | defer reader.Close() |
| 105 | limit := int64(maxImageBytes) |
| 106 | if mime == "text/plain" { |
| 107 | limit = 2 << 20 |
| 108 | } |
| 109 | if (mime != "image/png" && mime != "text/plain") || size > limit { |
| 110 | http.Error(w, "客机复制内容的类型或大小无效", http.StatusBadGateway) |
| 111 | return |
| 112 | } |
| 113 | data, err := io.ReadAll(io.LimitReader(reader, limit+1)) |
| 114 | if err != nil || int64(len(data)) != size { |
| 115 | http.Error(w, "复制内容未完整收到,请重新复制", http.StatusBadGateway) |
| 116 | return |
| 117 | } |
| 118 | if mime == "text/plain" { |
| 119 | if !utf8.Valid(data) { |
| 120 | http.Error(w, "复制文字的编码无效", http.StatusBadGateway) |
| 121 | return |
| 122 | } |
| 123 | jsonReply(w, map[string]string{"text": string(data)}) |
| 124 | return |
| 125 | } |
| 126 | if _, err := validateInputImage(data); err != nil { |
| 127 | http.Error(w, err.Error(), http.StatusBadGateway) |
| 128 | return |
| 129 | } |
| 130 | jsonReply(w, map[string]string{"png": base64.StdEncoding.EncodeToString(data)}) |
| 131 | } |
| 132 | |
| 133 | func (s *Server) subscribeNativeBrowser(parent context.Context) io.ReadCloser { |
| 134 | ctx, cancel := context.WithCancel(parent) |
| 135 | reader, writer := io.Pipe() |
| 136 | go func() { |
| 137 | defer writer.Close() |
| 138 | defer cancel() |
| 139 | ticker := time.NewTicker(300 * time.Millisecond) |
| 140 | defer ticker.Stop() |
| 141 | var previous string |
| 142 | var latest json.RawMessage |
| 143 | var sequence uint64 |
| 144 | var downloadRevision uint64 |
| 145 | for { |
| 146 | body, _ := json.Marshal(map[string]any{"after": sequence, "onlyChanges": true}) |
| 147 | data, err := s.nativeBrowserAPI(ctx, "GET", "/events", body) |
| 148 | if err != nil { |
| 149 | _ = writer.CloseWithError(err) |
| 150 | return |
| 151 | } |
| 152 | var update struct { |
| 153 | Sequence uint64 `json:"sequence"` |
| 154 | State json.RawMessage `json:"state"` |
| 155 | Events []struct { |
| 156 | Sequence uint64 `json:"sequence"` |
| 157 | Type string `json:"type"` |
| 158 | Value json.RawMessage `json:"value"` |
| 159 | } `json:"events"` |
| 160 | } |
| 161 | if err = json.Unmarshal(data, &update); err != nil { |
| 162 | _ = writer.CloseWithError(err) |
| 163 | return |
| 164 | } |
| 165 | if update.Sequence < sequence { |
| 166 | |
| 167 | |
| 168 | sequence, previous, latest = 0, "", nil |
| 169 | continue |
| 170 | } |
| 171 | for _, event := range update.Events { |
| 172 | if event.Sequence <= sequence || event.Sequence > update.Sequence { |
| 173 | continue |
| 174 | } |
| 175 | switch event.Type { |
| 176 | case "clipboard", "native-clipboard", "copy-expired": |
| 177 | if len(event.Value) == 0 { |
| 178 | continue |
| 179 | } |
| 180 | if _, err = fmt.Fprintf(writer, "id: %d\nevent: %s\ndata: %s\n\n", event.Sequence, event.Type, event.Value); err != nil { |
| 181 | return |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | sequence = update.Sequence |
| 186 | if len(update.State) != 0 { |
| 187 | latest = update.State |
| 188 | } |
| 189 | s.mu.Lock() |
| 190 | revision := s.nativeDownloadRevision |
| 191 | s.mu.Unlock() |
| 192 | |
| 193 | |
| 194 | if len(latest) != 0 && (string(latest) != previous || revision != downloadRevision) { |
| 195 | if _, err = writer.Write(append(append([]byte("data: "), latest...), '\n', '\n')); err != nil { |
| 196 | return |
| 197 | } |
| 198 | previous, downloadRevision = string(latest), revision |
| 199 | } |
| 200 | select { |
| 201 | case <-ctx.Done(): |
| 202 | return |
| 203 | case <-ticker.C: |
| 204 | } |
| 205 | } |
| 206 | }() |
| 207 | return &windowsBrowserEventStream{ReadCloser: reader, cancel: cancel} |
| 208 | } |
| 209 | |
| 210 | type windowsBrowserEventStream struct { |
| 211 | io.ReadCloser |
| 212 | cancel context.CancelFunc |
| 213 | } |
| 214 | |
| 215 | func (s *windowsBrowserEventStream) Close() error { s.cancel(); return s.ReadCloser.Close() } |
| 216 | |
| 217 | func (s *Server) nativeBrowserFile(w http.ResponseWriter, r *http.Request, method, path string, body io.Reader) { |
| 218 | request, err := url.Parse(path) |
| 219 | if err != nil { |
| 220 | http.Error(w, "浏览器文件操作无效", 400) |
| 221 | return |
| 222 | } |
| 223 | query := request.Query() |
| 224 | if method == "POST" && request.Path == "/upload-file" { |
| 225 | result, err := s.nativeBrowserClient().upload(r.Context(), query.Get("id"), query.Get("name"), body, r.ContentLength) |
| 226 | if err != nil { |
| 227 | http.Error(w, err.Error(), 502) |
| 228 | return |
| 229 | } |
| 230 | w.Header().Set("Content-Type", "application/json") |
| 231 | _, _ = w.Write(result) |
| 232 | return |
| 233 | } |
| 234 | if method == "GET" && request.Path == "/download-file" { |
| 235 | reader, size, _, err := s.nativeBrowserClient().download(r.Context(), query.Get("id")) |
| 236 | if err != nil { |
| 237 | http.Error(w, err.Error(), 502) |
| 238 | return |
| 239 | } |
| 240 | defer reader.Close() |
| 241 | w.Header().Set("Content-Type", "application/octet-stream") |
| 242 | if size < 0 { |
| 243 | http.Error(w, "文件大小无效", 502) |
| 244 | return |
| 245 | } |
| 246 | w.Header().Set("Content-Length", fmt.Sprint(size)) |
| 247 | _, _ = io.Copy(w, reader) |
| 248 | return |
| 249 | } |
| 250 | http.Error(w, "Windows 浏览器文件操作尚未接通", 501) |
| 251 | } |
| 252 | |
| 253 | func (s *Server) nativeBrowserVNC(w http.ResponseWriter, r *http.Request) { |
| 254 | ctx, cancel := context.WithCancel(r.Context()) |
| 255 | defer cancel() |
| 256 | var client *windowsBrowserClient |
| 257 | release := func() {} |
| 258 | |
| 259 | |
| 260 | ownConnection := s.macosGuest == nil |
| 261 | if s.macosGuest != nil { |
| 262 | client = s.nativeBrowserClient() |
| 263 | } else { |
| 264 | client = newWindowsBrowserClient(ctx, s.profile) |
| 265 | release = client.close |
| 266 | } |
| 267 | defer func() { release() }() |
| 268 | var current windowsWindowFrame |
| 269 | inputSuspended := false |
| 270 | request := func(input map[string]any, output any) error { |
| 271 | var data []byte |
| 272 | var err error |
| 273 | switch input["action"] { |
| 274 | case "frame": |
| 275 | if inputSuspended { |
| 276 | delete(input, "after") |
| 277 | } |
| 278 | data, err = requestBrowserFrame(ctx, client.request, input) |
| 279 | if err == nil { |
| 280 | var next windowsWindowFrame |
| 281 | if err = json.Unmarshal(data, &next); err == nil { |
| 282 | if !next.Unchanged { |
| 283 | current = next |
| 284 | inputSuspended = false |
| 285 | } |
| 286 | *output.(*windowsWindowFrame) = next |
| 287 | } |
| 288 | } |
| 289 | return err |
| 290 | case "pointer", "key": |
| 291 | if inputSuspended { |
| 292 | return nil |
| 293 | } |
| 294 | input["kind"] = input["action"] |
| 295 | delete(input, "action") |
| 296 | s.mu.Lock() |
| 297 | keyboard := s.preferences.Keyboard |
| 298 | s.mu.Unlock() |
| 299 | if input["kind"] == "key" && s.windowsGuest != nil { |
| 300 | if key, ok := input["keysym"].(uint32); ok { |
| 301 | input["keysym"] = windowsGuestKeysym(key, keyboard) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | |
| 306 | |
| 307 | var releaseInput func() |
| 308 | if ownConnection { |
| 309 | releaseInput = func() { |
| 310 | inputSuspended = true |
| 311 | client.releaseViewerInput() |
| 312 | } |
| 313 | } |
| 314 | data, err = recoverBrowserInputFocus(ctx, client.request, input, releaseInput) |
| 315 | case "text": |
| 316 | if inputSuspended { |
| 317 | return nil |
| 318 | } |
| 319 | data, err = client.request(ctx, "POST", "/insert-text", map[string]any{"id": current.ID, "document": current.Document, "text": input["text"]}) |
| 320 | default: |
| 321 | return errors.New("浏览器画面操作无效") |
| 322 | } |
| 323 | if err != nil { |
| 324 | return err |
| 325 | } |
| 326 | if output != nil { |
| 327 | return json.Unmarshal(data, output) |
| 328 | } |
| 329 | return nil |
| 330 | } |
| 331 | if err := request(map[string]any{"action": "frame"}, ¤t); err != nil { |
| 332 | http.Error(w, err.Error(), 409) |
| 333 | return |
| 334 | } |
| 335 | if s.macosGuest != nil { |
| 336 | owner := client |
| 337 | client, release = owner.viewer(ctx) |
| 338 | ownConnection = client != owner |
| 339 | if client != owner { |
| 340 | if err := request(map[string]any{"action": "frame"}, ¤t); err != nil { |
| 341 | http.Error(w, err.Error(), 409) |
| 342 | return |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | local, remote := net.Pipe() |
| 347 | defer local.Close() |
| 348 | done := make(chan struct{}) |
| 349 | go func() { |
| 350 | defer close(done) |
| 351 | defer remote.Close() |
| 352 | err := serveWindowsWindowRFB(remote, current, request) |
| 353 | if err != nil && ctx.Err() == nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrClosedPipe) && !errors.Is(err, net.ErrClosed) { |
| 354 | _ = diagnostics.New(s.profile).Record("warn", "native-browser-display", err.Error()) |
| 355 | } |
| 356 | }() |
| 357 | s.streamVNC(w, r, local, local, func() { cancel(); local.Close(); remote.Close(); release() }) |
| 358 | <-done |
| 359 | } |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | func recoverBrowserInputFocus(ctx context.Context, request func(context.Context, string, string, any) ([]byte, error), input map[string]any, release func()) ([]byte, error) { |
| 367 | data, err := request(ctx, "POST", "/input", input) |
| 368 | var failure windowsBrowserFailure |
| 369 | if release == nil || !errors.As(err, &failure) || (failure.code != "browser_focus_required" && failure.code != "browser_target_changed" && failure.code != "target_changed") { |
| 370 | return data, err |
| 371 | } |
| 372 | |
| 373 | |
| 374 | |
| 375 | release() |
| 376 | return nil, nil |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | func requestBrowserFrame(ctx context.Context, request func(context.Context, string, string, any) ([]byte, error), input map[string]any) ([]byte, error) { |
| 383 | for attempt := 0; ; attempt++ { |
| 384 | data, err := request(ctx, "GET", "/frame", input) |
| 385 | var failure windowsBrowserFailure |
| 386 | if attempt >= 5 || !errors.As(err, &failure) || !transientWindowFrame(failure.code) { |
| 387 | return data, err |
| 388 | } |
| 389 | timer := time.NewTimer(80 * time.Millisecond) |
| 390 | select { |
| 391 | case <-ctx.Done(): |
| 392 | timer.Stop() |
| 393 | return nil, ctx.Err() |
| 394 | case <-timer.C: |
| 395 | } |
| 396 | } |
| 397 | } |