跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

guest-clipboard-macos.swift

805 行 · 44.9 KB历史下载
1// Per-user GUI clipboard agent and its private SSH client for a Cage macOS guest.
2import AppKit
3import ApplicationServices
4import ImageIO
5import Security
6import UniformTypeIdentifiers
7
8private let wireLimit = 30 * 1024 * 1024
9private let textLimit = 2 * 1024 * 1024
10private let imageLimit = 20 * 1024 * 1024
11private let label = "dev.cage.GuestClipboard"
12
13private struct ClipboardFailure: Error {
14 let reason: String
15 init(_ reason: String) { self.reason = reason }
16}
17
18private func requireGuest() throws {
19 var model = [CChar](repeating: 0, count: 256), size = 256
20 guard sysctlbyname("hw.model", &model, &size, nil, 0) == 0,
21 String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil,
22 getuid() >= 500 else { throw ClipboardFailure("not_guest") }
23 let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
24 guard fd >= 0 else { throw ClipboardFailure("not_guest") }
25 defer { close(fd) }
26 var info = stat()
27 guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == 0,
28 info.st_mode & 0o022 == 0, (5...6).contains(info.st_size) else { throw ClipboardFailure("not_guest") }
29 let data = try FileHandle(fileDescriptor: fd, closeOnDealloc: false).read(upToCount: 6) ?? Data()
30 guard [Data("macos".utf8), Data("macos\n".utf8)].contains(data) else { throw ClipboardFailure("not_guest") }
31}
32
33private func guiAvailable() -> Bool {
34 var info = stat(), attributes: SessionAttributeBits = []
35 return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 &&
36 SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess && attributes.contains(.sessionHasGraphicAccess) &&
37 (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true
38}
39
40private func onGUI<T>(_ body: () throws -> T) rethrows -> T {
41 if Thread.isMainThread { return try body() }
42 return try DispatchQueue.main.sync(execute: body)
43}
44
45private func writeAll(_ fd: Int32, _ data: Data) throws {
46 try data.withUnsafeBytes { bytes in
47 var position = 0
48 while position < bytes.count {
49 let count = Darwin.write(fd, bytes.baseAddress!.advanced(by: position), bytes.count - position)
50 if count < 0 && errno == EINTR { continue }
51 guard count > 0 else { throw ClipboardFailure("connection_closed") }
52 position += count
53 }
54 }
55}
56
57private final class Reader {
58 let fd: Int32
59 private var buffer = Data()
60 init(_ fd: Int32) { self.fd = fd }
61 func line(limit: Int = wireLimit) throws -> Data? {
62 while true {
63 if let newline = buffer.firstIndex(of: 10) {
64 let value = Data(buffer[..<newline])
65 buffer.removeSubrange(...newline)
66 guard value.count <= limit else { throw ClipboardFailure("message_too_large") }
67 return value
68 }
69 guard buffer.count <= limit else { throw ClipboardFailure("message_too_large") }
70 var bytes = [UInt8](repeating: 0, count: min(65536, limit + 1 - buffer.count))
71 let count = Darwin.read(fd, &bytes, bytes.count)
72 if count < 0 && errno == EINTR { continue }
73 if count == 0 { if buffer.isEmpty { return nil }; throw ClipboardFailure("incomplete_message") }
74 guard count > 0 else { throw ClipboardFailure("connection_closed") }
75 buffer.append(contentsOf: bytes.prefix(count))
76 }
77 }
78 func exact(_ length: Int) throws -> Data {
79 var output = Data()
80 if !buffer.isEmpty {
81 let count = min(length, buffer.count)
82 output.append(buffer.prefix(count)); buffer.removeFirst(count)
83 }
84 while output.count < length {
85 var bytes = [UInt8](repeating: 0, count: min(65536, length - output.count))
86 let count = Darwin.read(fd, &bytes, bytes.count)
87 if count < 0 && errno == EINTR { continue }
88 guard count > 0 else { throw ClipboardFailure("incomplete_message") }
89 output.append(contentsOf: bytes.prefix(count))
90 }
91 return output
92 }
93 func copy(to output: FileHandle) throws {
94 if !buffer.isEmpty { try output.write(contentsOf: buffer); buffer.removeAll() }
95 while true {
96 var bytes = [UInt8](repeating: 0, count: 65536)
97 let count = Darwin.read(fd, &bytes, bytes.count)
98 if count < 0 && errno == EINTR { continue }
99 if count == 0 { return }
100 guard count > 0 else { throw ClipboardFailure("connection_closed") }
101 try output.write(contentsOf: Data(bytes.prefix(count)))
102 }
103 }
104}
105
106private func json(_ data: Data) throws -> [String: Any] {
107 guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw ClipboardFailure("invalid_message") }
108 return value
109}
110
111private func jsonData(_ value: [String: Any]) throws -> Data {
112 var data = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])
113 guard data.count <= wireLimit else { throw ClipboardFailure("message_too_large") }
114 data.append(10)
115 return data
116}
117
118private func paths(_ value: Any?) throws -> [String] {
119 guard let values = value as? [String], (1...100).contains(values.count) else { throw ClipboardFailure("invalid_files") }
120 for path in values {
121 guard path.hasPrefix("/"), !path.contains("\0"), URL(fileURLWithPath: path).standardizedFileURL.path == path else { throw ClipboardFailure("invalid_files") }
122 }
123 return values
124}
125
126private func image(_ data: Data, requirePNG: Bool = false) throws -> CGImage {
127 if requirePNG {
128 guard data.count <= imageLimit, data.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) else { throw ClipboardFailure("invalid_image") }
129 }
130 guard let source = CGImageSourceCreateWithData(data as CFData, nil),
131 let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
132 let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int,
133 width > 0, height > 0, width <= 40_000_000 / height,
134 let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ClipboardFailure("invalid_image") }
135 return image
136}
137
138private func png(_ image: CGImage) throws -> Data {
139 let data = NSMutableData()
140 guard let output = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { throw ClipboardFailure("invalid_image") }
141 CGImageDestinationAddImage(output, image, nil)
142 guard CGImageDestinationFinalize(output), data.length <= imageLimit else { throw ClipboardFailure("image_too_large") }
143 return data as Data
144}
145
146private func boardContent(_ board: NSPasteboard) throws -> [String: Any] {
147 if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {
148 guard urls.allSatisfy({ $0.isFileURL && ($0.host == nil || $0.host == "" || $0.host == "localhost") }) else { throw ClipboardFailure("invalid_files") }
149 return ["files": try paths(urls.map(\.path))]
150 }
151 if let value = board.data(forType: .png) {
152 _ = try image(value, requirePNG: true)
153 return ["png": value.base64EncodedString()]
154 }
155 if let value = board.data(forType: .tiff) { return ["png": try png(image(value)).base64EncodedString()] }
156 let value = board.string(forType: .string) ?? ""
157 guard value.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") }
158 return ["text": value]
159}
160
161private func setBoard(_ board: NSPasteboard, _ value: [String: Any]) throws {
162 if let text = value["text"] as? String {
163 guard text.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") }
164 board.clearContents()
165 guard board.setString(text, forType: .string) else { throw ClipboardFailure("clipboard_write_failed") }
166 } else if value["png"] != nil {
167 guard let encoded = value["png"] as? String, let data = Data(base64Encoded: encoded) else { throw ClipboardFailure("invalid_image") }
168 let bitmap = try image(data, requirePNG: true)
169 let native = NSImage(cgImage: bitmap, size: .zero)
170 board.clearContents()
171 guard board.writeObjects([native]) else { throw ClipboardFailure("clipboard_write_failed") }
172 } else {
173 let files = try paths(value["files"])
174 board.clearContents()
175 guard board.writeObjects(files.map { NSURL(fileURLWithPath: $0) }) else { throw ClipboardFailure("clipboard_write_failed") }
176 }
177}
178
179private final class Stream: @unchecked Sendable {
180 private struct Snapshot { let data: Data; let completed: (Bool) -> Void }
181 let fd: Int32
182 private let outputLock = NSLock()
183 private let stateLock = NSLock()
184 private var closed = false
185 private var publishing = false
186 private var pending: Snapshot?
187 var initialized = false // GUI-thread owned
188 init(_ fd: Int32) { self.fd = fd }
189 func send(_ value: [String: Any]) throws {
190 try sendData(jsonData(value))
191 }
192 private func sendData(_ data: Data) throws {
193 outputLock.lock(); defer { outputLock.unlock() }
194 stateLock.lock(); let ended = closed; stateLock.unlock()
195 guard !ended else { throw ClipboardFailure("connection_closed") }
196 try writeAll(fd, data)
197 }
198 // Keep only the latest unsent snapshot. A slow client cannot block the GUI
199 // thread or accumulate a queue of full-resolution clipboard images.
200 func publish(_ value: [String: Any], completed: @escaping (Bool) -> Void = { _ in }) {
201 guard let data = try? jsonData(value) else { completed(false); return }
202 stateLock.lock()
203 guard !closed else { stateLock.unlock(); completed(false); return }
204 let superseded = pending
205 pending = Snapshot(data: data, completed: completed)
206 let start = !publishing
207 publishing = true
208 stateLock.unlock()
209 superseded?.completed(false)
210 guard start else { return }
211 DispatchQueue.global(qos: .userInitiated).async {
212 while true {
213 self.stateLock.lock()
214 guard let next = self.pending, !self.closed else {
215 self.publishing = false; self.stateLock.unlock(); return
216 }
217 self.pending = nil
218 self.stateLock.unlock()
219 do { try self.sendData(next.data); next.completed(true) }
220 catch { next.completed(false); self.close(); return }
221 }
222 }
223 }
224 func close() {
225 outputLock.lock()
226 stateLock.lock()
227 let discarded = pending
228 if !closed { closed = true; pending = nil; shutdown(fd, SHUT_RDWR) }
229 stateLock.unlock()
230 outputLock.unlock()
231 discarded?.completed(false)
232 }
233}
234
235private final class SnapshotDelivery: @unchecked Sendable {
236 var remaining: Int
237 var published = false
238 init(_ count: Int) { remaining = count }
239}
240
241private final class ClipboardAgent: @unchecked Sendable {
242 private var streams: [Int32: Stream] = [:]
243 private var records: [[String]] = []
244 private var known = Set<String>()
245 private var owned = Set<String>()
246 private struct CachedCopy { let id: String; let paths: [String]; var pinned: Bool; let clipboard: Bool }
247 private var copies: [String: CachedCopy] = [:]
248 private var fileReaders: [UUID: [String]] = [:]
249 private var copiesLoaded = false
250 private var collectingCopies = false
251 private var copiesNeedCollection = false
252 private let cacheQueue = DispatchQueue(label: "cage.clipboard.cache")
253 private var session = UUID().uuidString.lowercased()
254 private let board: NSPasteboard
255 private let gui: () -> Bool
256 private let diagnostic: (String) -> Void
257 private var available: Bool
258 private var revision: Int
259 private var snapshotPending = false
260 private var transfers: [UUID: Process] = [:]
261 private let helper: URL
262 init(board: NSPasteboard = .general, gui: @escaping () -> Bool = guiAvailable,
263 diagnostic: @escaping (String) -> Void = { GuestDiagnostic.record("clipboard", $0) }) {
264 self.board = board
265 self.gui = gui
266 self.diagnostic = diagnostic
267 available = gui()
268 revision = board.changeCount
269 helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/cage-guest-files")
270 }
271 private func check(_ expectedSession: String? = nil) throws {
272 guard gui(), available, expectedSession == nil || expectedSession == session else { throw ClipboardFailure("requires_gui_login") }
273 guard FileManager.default.isExecutableFile(atPath: helper.path) else { throw ClipboardFailure("files_helper_missing") }
274 }
275 private func hello() -> [String: Any] {
276 let gui = self.gui()
277 let files = FileManager.default.isExecutableFile(atPath: helper.path)
278 return ["hello": ["version": 1, "os": "darwin", "session": session, "formats": ["text", "png", "files"],
279 "available": gui && files,
280 "file_release": true,
281 "reason": !gui ? "requires_gui_login" : (!files ? "files_helper_missing" : "")]]
282 }
283 private func record(_ files: [String], copied: Bool = false) {
284 records.append(files)
285 if records.count > 128 { records.removeFirst(); known = Set(records.flatMap { $0 }) }
286 else { known.formUnion(files) }
287 if copied { owned.formUnion(files) }
288 }
289 private func cacheControl(_ action: String, id: String = "") throws -> [String: Any] {
290 let process = Process(), output = Pipe()
291 process.executableURL = helper
292 process.arguments = ["cache", String(data: try JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), encoding: .utf8)!]
293 process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice
294 try process.run()
295 let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } }
296 DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: timeout)
297 defer { timeout.cancel() }
298 let data = try output.fileHandleForReading.readToEnd() ?? Data()
299 process.waitUntilExit()
300 guard process.terminationStatus == 0, data.count <= wireLimit else { throw ClipboardFailure("clipboard_cache_failed") }
301 return try json(data)
302 }
303 private func rememberCopy(_ result: [String: Any], clipboard: Bool) {
304 guard let id = result["cache_id"] as? String, let paths = result["paths"] as? [String], !paths.isEmpty else { return }
305 copies[id] = CachedCopy(id: id, paths: paths, pinned: true, clipboard: clipboard)
306 cacheQueue.async { _ = try? self.cacheControl("publish", id: id) }
307 }
308 private func retireCopies(_ paths: [String]) {
309 let selected = Set(paths)
310 for (id, copy) in copies where !selected.isDisjoint(with: copy.paths) { copies[id]?.pinned = false }
311 collectCopies()
312 }
313 private func collectCopies() {
314 guard !collectingCopies else { copiesNeedCollection = true; return }
315 collectingCopies = true
316 cacheQueue.async {
317 defer {
318 onGUI {
319 self.collectingCopies = false
320 if self.copiesNeedCollection { self.copiesNeedCollection = false; self.collectCopies() }
321 }
322 }
323 if !onGUI({ self.copiesLoaded }) {
324 let previous = try? self.cacheControl("list")
325 onGUI {
326 self.copiesLoaded = true
327 for item in previous?["selections"] as? [[String: Any]] ?? [] {
328 if let id = item["cache_id"] as? String, let paths = item["paths"] as? [String], !paths.isEmpty, self.copies[id] == nil {
329 self.copies[id] = CachedCopy(id: id, paths: paths, pinned: false, clipboard: true)
330 }
331 }
332 }
333 }
334 for copy in onGUI({ Array(self.copies.values) }) {
335 let retain = onGUI { () -> Bool in
336 guard self.copies[copy.id]?.pinned == false else { return true }
337 let selected = (self.board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []).map(\.path)
338 let root = URL(fileURLWithPath: copy.paths[0]).deletingLastPathComponent().standardizedFileURL.path
339 return (selected + self.fileReaders.values.flatMap { $0 }).contains { value in
340 let path = URL(fileURLWithPath: value).standardizedFileURL.path
341 return path == root || path.hasPrefix(root + "/") || root.hasPrefix(path + "/")
342 }
343 }
344 if retain { continue }
345 if (try? self.cacheControl("release", id: copy.id)) != nil {
346 onGUI { self.copies.removeValue(forKey: copy.id); self.owned.subtract(copy.paths); self.known.subtract(copy.paths) }
347 }
348 }
349 }
350 }
351 private func beginTransfer(_ operation: String, input: FileHandle?, name: String? = nil) throws -> (Process, Pipe, UUID, String) {
352 let epoch = try onGUI { () -> String in try check(); return session }
353 let process = Process(); process.executableURL = helper
354 process.arguments = [operation] + (name.map { [$0] } ?? (operation == "import" ? [] : ["--paths-stdin"]))
355 let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice
356 process.standardInput = input ?? FileHandle.nullDevice
357 let id = UUID()
358 try onGUI {
359 try check(epoch); transfers[id] = process
360 do { try process.run() } catch { transfers.removeValue(forKey: id); throw error }
361 }
362 return (process, output, id, epoch)
363 }
364 private func finishTransfer(_ process: Process, id: UUID, epoch: String) throws {
365 process.waitUntilExit()
366 try onGUI { transfers.removeValue(forKey: id); try check(epoch) }
367 guard process.terminationStatus == 0 else { throw ClipboardFailure("file_transfer_failed") }
368 }
369 private func fileJSON(_ operation: String, values: [String]) throws -> [String] {
370 let reader = UUID()
371 var recorded = false
372 onGUI { fileReaders[reader] = values }
373 defer { onGUI { fileReaders.removeValue(forKey: reader); if !recorded { copiesLoaded = false }; collectCopies() } }
374 let input = Pipe()
375 let (process, output, id, epoch) = try beginTransfer(operation, input: input.fileHandleForReading)
376 defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; process.waitUntilExit(); onGUI { _ = transfers.removeValue(forKey: id) } }
377 try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: values)); try input.fileHandleForWriting.close()
378 let data = try output.fileHandleForReading.readToEnd() ?? Data()
379 guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
380 let response = try json(data)
381 let result = try paths(response["paths"])
382 onGUI { record(result, copied: true); rememberCopy(response, clipboard: operation == "copy") }
383 recorded = true
384 do { try finishTransfer(process, id: id, epoch: epoch) }
385 catch { onGUI { retireCopies(result) }; throw error }
386 return result
387 }
388 private func snapshot() throws -> [String: Any] {
389 let (epoch, captured, content) = try onGUI { () -> (String, Int, [String: Any]) in
390 try check(); return (session, board.changeCount, try boardContent(board))
391 }
392 var result = content
393 if let selected = content["files"] as? [String] {
394 onGUI { record(selected) }
395 // File snapshots are frozen in the GUI agent's readable cache.
396 result["files"] = try fileJSON("copy", values: selected)
397 }
398 do { try onGUI { try check(epoch); guard board.changeCount == captured else { throw ClipboardFailure("superseded") } } }
399 catch { if let files = result["files"] as? [String] { onGUI { retireCopies(files) } }; throw error }
400 result["revision"] = captured
401 result["source"] = "guest"
402 return result
403 }
404 private func apply(_ value: [String: Any], echo: Bool) throws -> [String: Any] {
405 try onGUI {
406 if value["release"] != nil { retireCopies(try paths(value["release"])); return ["released": true] }
407 try check()
408 if let expected = value["revision"] as? Int, expected != board.changeCount { throw ClipboardFailure("superseded") }
409 if value["files"] != nil {
410 let selected = try paths(value["files"])
411 guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") }
412 }
413 try setBoard(board, value)
414 if !echo { revision = board.changeCount }
415 return ["ack": value["serial"] as? Int ?? 0, "revision": board.changeCount]
416 }
417 }
418 private func copiedText(_ request: [String: Any]) throws -> [String: Any] {
419 guard let expected = request["revision"] as? Int, let epoch = request["session"] as? String else { throw ClipboardFailure("invalid_copy_request") }
420 let deadline = Date().addingTimeInterval(2)
421 repeat {
422 let value = try onGUI { () -> [String: Any]? in
423 try check(epoch)
424 let captured = board.changeCount
425 guard captured != expected else { return nil }
426 guard let text = board.string(forType: .string), text.utf8.count <= textLimit else { throw ClipboardFailure("clipboard_text_unavailable") }
427 guard board.changeCount == captured else { return nil }
428 return ["text": text, "revision": captured, "session": session]
429 }
430 if let value { return value }
431 Thread.sleep(forTimeInterval: 0.025)
432 } while Date() < deadline
433 throw ClipboardFailure("clipboard_copy_not_observed")
434 }
435 func poll() {
436 collectCopies()
437 let current = gui()
438 if current != available {
439 available = current; session = UUID().uuidString.lowercased()
440 revision = board.changeCount
441 if !current { for process in transfers.values where process.isRunning { process.terminate() } }
442 // Reconnect under a fresh GUI-session hello. Unsent snapshots from
443 // the previous login must not cross the session transition.
444 for stream in streams.values { stream.close() }
445 }
446 guard current, !snapshotPending, streams.values.contains(where: { $0.initialized }), revision != board.changeCount else { return }
447 revision = board.changeCount
448 snapshotPending = true
449 let capturedSession = session
450 DispatchQueue.global(qos: .userInitiated).async {
451 let result: [String: Any]
452 do { result = try self.snapshot() }
453 catch { result = (error as? ClipboardFailure)?.reason == "superseded" ? [:] : ["error": (error as? ClipboardFailure)?.reason ?? "clipboard_read_failed"] }
454 onGUI {
455 self.snapshotPending = false
456 guard !result.isEmpty else { return }
457 let files = result["files"] as? [String] ?? []
458 let recipients = self.streams.values.filter { $0.initialized }
459 guard self.session == capturedSession, !recipients.isEmpty else { self.retireCopies(files); return }
460 let delivery = SnapshotDelivery(recipients.count)
461 for stream in recipients {
462 stream.publish(result) { sent in
463 DispatchQueue.main.async {
464 delivery.remaining -= 1
465 delivery.published = delivery.published || sent
466 if delivery.remaining == 0 && !delivery.published { self.retireCopies(files) }
467 }
468 }
469 }
470 }
471 }
472 }
473 func serve(_ fd: Int32) {
474 var stream: Stream?
475 defer {
476 stream?.close()
477 onGUI {
478 _ = streams.removeValue(forKey: fd)
479 if stream != nil && streams.isEmpty { for (id, copy) in copies where copy.clipboard { copies[id]?.pinned = false }; collectCopies() }
480 }
481 close(fd)
482 }
483 var user = uid_t(), group = gid_t()
484 guard getpeereid(fd, &user, &group) == 0, user == getuid() else { return }
485 var timeout = timeval(tv_sec: 1800, tv_usec: 0)
486 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
487 var outputTimeout = timeval(tv_sec: 2, tv_usec: 0)
488 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &outputTimeout, socklen_t(MemoryLayout.size(ofValue: outputTimeout)))
489 let reader = Reader(fd)
490 do {
491 guard let first = try reader.line(), let operation = try json(first)["operation"] as? String else { return }
492 let request = try json(first)
493 switch operation {
494 case "copy-prepare":
495 let value = try onGUI { () -> [String: Any] in try check(); return ["revision": board.changeCount, "session": session] }
496 try writeAll(fd, jsonData(value))
497 case "copy-read":
498 try writeAll(fd, jsonData(copiedText(request)))
499 case "stream":
500 let connection = Stream(fd)
501 stream = connection
502 onGUI { streams[fd] = connection }
503 try connection.send(onGUI { hello() })
504 while let line = try reader.line() {
505 do {
506 let reply = try apply(json(line), echo: false)
507 onGUI { connection.initialized = true }
508 try connection.send(reply)
509 } catch { try connection.send(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_write_failed"]) }
510 }
511 case "read":
512 let value = try snapshot()
513 do { try writeAll(fd, jsonData(value)) }
514 catch { if let files = value["files"] as? [String] { onGUI { retireCopies(files) } }; throw error }
515 case "write":
516 try writeAll(fd, jsonData(apply(request, echo: true)))
517 case "prepare-files":
518 let selected = try paths(request["files"])
519 try onGUI { try check(); guard selected.allSatisfy({ owned.contains($0) && known.contains($0) }) else { throw ClipboardFailure("unregistered_files") } }
520 let copied = try fileJSON("link-cached", values: selected)
521 do { try writeAll(fd, jsonData(["paths": copied])) }
522 catch { onGUI { retireCopies(copied) }; throw error }
523 case "discard":
524 let selected = try paths(request["files"])
525 try onGUI {
526 guard selected.allSatisfy({ owned.contains($0) }) else { throw ClipboardFailure("unregistered_files") }
527 retireCopies(selected)
528 let tracked = Set(copies.values.flatMap(\.paths))
529 for file in selected where !tracked.contains(file) {
530 try? FileManager.default.removeItem(atPath: file)
531 owned.remove(file); known.remove(file)
532 // Remove only an empty cache directory owned by this transfer.
533 _ = rmdir((file as NSString).deletingLastPathComponent)
534 }
535 }
536 try writeAll(fd, jsonData(["ok": true]))
537 case "import", "upload":
538 let capturedStreams = onGUI { Set(streams.values.map(ObjectIdentifier.init)) }
539 let name = operation == "upload" ? request["name"] as? String : nil
540 if operation == "upload" && (name == nil || name!.utf8.count > 255) { throw ClipboardFailure("invalid_files") }
541 let input = Pipe()
542 let (process, output, id, epoch) = try beginTransfer(operation == "upload" ? "save" : "import", input: input.fileHandleForReading, name: name)
543 var recorded = false
544 defer {
545 try? input.fileHandleForWriting.close()
546 if process.isRunning { process.terminate() }
547 process.waitUntilExit()
548 onGUI { transfers.removeValue(forKey: id); if !recorded { copiesLoaded = false }; collectCopies() }
549 }
550 try reader.copy(to: input.fileHandleForWriting); try input.fileHandleForWriting.close()
551 let data = try output.fileHandleForReading.readToEnd() ?? Data()
552 guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
553 let response = try json(data)
554 let imported = try paths(response["paths"])
555 onGUI { record(imported, copied: true); rememberCopy(response, clipboard: operation == "import") }
556 recorded = true
557 do {
558 try finishTransfer(process, id: id, epoch: epoch)
559 try onGUI {
560 if operation == "import", !capturedStreams.isEmpty,
561 capturedStreams.isDisjoint(with: streams.values.map(ObjectIdentifier.init)) { throw ClipboardFailure("connection_closed") }
562 }
563 try writeAll(fd, jsonData(["paths": imported]))
564 }
565 catch { onGUI { retireCopies(imported) }; throw error }
566 case "export":
567 let selected = try paths(request["paths"])
568 let readerID = UUID()
569 try onGUI { try check(); guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") }; fileReaders[readerID] = selected }
570 defer { onGUI { fileReaders.removeValue(forKey: readerID); collectCopies() } }
571 let input = Pipe()
572 let (process, output, id, epoch) = try beginTransfer("export", input: input.fileHandleForReading)
573 defer { if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
574 try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: selected)); try input.fileHandleForWriting.close()
575 while let data = try output.fileHandleForReading.read(upToCount: 65536), !data.isEmpty {
576 var count = UInt32(data.count).bigEndian
577 try writeAll(fd, Data(bytes: &count, count: 4)); try writeAll(fd, data)
578 }
579 var zero: UInt32 = 0
580 try writeAll(fd, Data(bytes: &zero, count: 4))
581 do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["ok": true])) }
582 catch { try writeAll(fd, jsonData(["error": "file_transfer_failed"])) }
583 default:
584 throw ClipboardFailure("unknown_operation")
585 }
586 } catch {
587 let reason = (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed"
588 diagnostic(reason)
589 try? writeAll(fd, jsonData(["error": reason]))
590 }
591 }
592}
593
594private func connect() throws -> Int32 {
595 let folder = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Caches/" + label)
596 var info = stat()
597 guard lstat(folder.path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
598 let path = folder.appendingPathComponent("clipboard.sock").path
599 guard lstat(path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
600 var address = sockaddr_un(); address.sun_family = sa_family_t(AF_UNIX)
601 let bytes = Array(path.utf8) + [UInt8(0)]
602 guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw ClipboardFailure("clipboard_service_unavailable") }
603 withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: bytes) }
604 let fd = socket(AF_UNIX, SOCK_STREAM, 0)
605 guard fd >= 0 else { throw ClipboardFailure("clipboard_service_unavailable") }
606 let result = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } }
607 guard result == 0 else { close(fd); throw ClipboardFailure("clipboard_service_unavailable") }
608 return fd
609}
610
611private func client(_ operation: String) throws {
612 try requireGuest()
613 let fd = try connect(); defer { close(fd) }
614 let reader = Reader(fd)
615 switch operation {
616 case "stream":
617 try writeAll(fd, jsonData(["operation": "stream"]))
618 DispatchQueue.global().async {
619 do { try Reader(fd).copy(to: .standardOutput); exit(0) }
620 catch { exit(1) }
621 }
622 try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false))
623 shutdown(fd, SHUT_WR)
624 dispatchMain()
625 case "import":
626 try writeAll(fd, jsonData(["operation": "import"]))
627 try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR)
628 guard let line = try reader.line(), try json(line)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") }
629 try writeAll(STDOUT_FILENO, line + Data([10]))
630 case "upload":
631 let input = Reader(STDIN_FILENO)
632 guard let line = try input.line(limit: 4096), let name = try json(line)["name"] as? String, name.utf8.count <= 255 else {
633 throw ClipboardFailure("invalid_files")
634 }
635 try writeAll(fd, jsonData(["operation": "upload", "name": name]))
636 try input.copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR)
637 guard let reply = try reader.line(), try json(reply)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") }
638 try writeAll(STDOUT_FILENO, reply + Data([10]))
639 case "export":
640 var data = Data()
641 while let chunk = try FileHandle.standardInput.read(upToCount: 65536), !chunk.isEmpty {
642 data.append(chunk)
643 guard data.count <= 1 << 20 else { throw ClipboardFailure("invalid_files") }
644 }
645 let selected = try paths(JSONSerialization.jsonObject(with: data))
646 try writeAll(fd, jsonData(["operation": "export", "paths": selected])); shutdown(fd, SHUT_WR)
647 while true {
648 let length = try reader.exact(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
649 if length == 0 { break }
650 guard length <= 65536 else { throw ClipboardFailure("file_transfer_failed") }
651 try writeAll(STDOUT_FILENO, reader.exact(Int(length)))
652 }
653 guard let line = try reader.line(), try json(line)["ok"] as? Bool == true else { throw ClipboardFailure("file_transfer_failed") }
654 case "request":
655 guard let line = try Reader(STDIN_FILENO).line(), let action = try json(line)["operation"] as? String, ["read", "write", "prepare-files", "discard", "copy-prepare", "copy-read"].contains(action) else { throw ClipboardFailure("unknown_operation") }
656 try writeAll(fd, line + Data([10])); shutdown(fd, SHUT_WR)
657 guard let reply = try reader.line() else { throw ClipboardFailure("clipboard_service_unavailable") }
658 try writeAll(STDOUT_FILENO, reply + Data([10]))
659 if try json(reply)["error"] != nil { throw ClipboardFailure("clipboard_operation_failed") }
660 default: throw ClipboardFailure("unknown_operation")
661 }
662}
663
664private final class ClipboardTestState: @unchecked Sendable {
665 var available = true // Used only on the GUI thread.
666 let lock = NSLock()
667 var failure: Error?
668}
669
670private func testAgentTransport(_ board: NSPasteboard) throws {
671 let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-clipboard-selftest-" + UUID().uuidString)
672 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false)
673 let previousTemp = getenv("TMPDIR").map { String(cString: $0) }
674 setenv("TMPDIR", root.path, 1)
675 defer {
676 if let previousTemp { setenv("TMPDIR", previousTemp, 1) } else { unsetenv("TMPDIR") }
677 try? FileManager.default.removeItem(at: root)
678 }
679 let state = ClipboardTestState()
680 let agent = ClipboardAgent(board: board, gui: { state.available }, diagnostic: { _ in })
681 let done = DispatchGroup()
682 done.enter()
683 DispatchQueue.global(qos: .userInitiated).async {
684 defer { done.leave() }
685 func connection() throws -> (Int32, DispatchGroup) {
686 var sockets: [Int32] = [0, 0]
687 guard socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets) == 0 else { throw ClipboardFailure("test_socket_failed") }
688 var timeout = timeval(tv_sec: 5, tv_usec: 0)
689 setsockopt(sockets[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
690 let ended = DispatchGroup()
691 ended.enter()
692 let server = sockets[0]
693 DispatchQueue.global().async { agent.serve(server); ended.leave() }
694 return (sockets[1], ended)
695 }
696 func rpc(_ value: [String: Any], bytes: Data = Data()) throws -> [String: Any] {
697 let (fd, ended) = try connection()
698 defer { close(fd); ended.wait() }
699 try writeAll(fd, jsonData(value))
700 try writeAll(fd, bytes)
701 shutdown(fd, SHUT_WR)
702 guard let line = try Reader(fd).line() else { throw ClipboardFailure("test_reply_missing") }
703 return try json(line)
704 }
705 do {
706 let prepared = try rpc(["operation": "copy-prepare"])
707 let unchanged = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!])
708 guard unchanged["error"] as? String == "clipboard_copy_not_observed" else { throw ClipboardFailure("test_old_text_returned") }
709 let largeText = String(repeating: "x", count: textLimit)
710 onGUI { board.clearContents(); board.setString(largeText, forType: .string) }
711 let fresh = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!])
712 guard fresh["text"] as? String == largeText, fresh["session"] as? String == prepared["session"] as? String else { throw ClipboardFailure("test_web_copy_failed") }
713 let (fd, ended) = try connection()
714 defer { close(fd); ended.wait() }
715 let reader = Reader(fd)
716 try writeAll(fd, jsonData(["operation": "stream"]))
717 guard let first = try reader.line(), let hello = try json(first)["hello"] as? [String: Any],
718 hello["os"] as? String == "darwin", hello["available"] as? Bool == true else { throw ClipboardFailure("test_hello_failed") }
719 try writeAll(fd, jsonData(["text": "stream text 中文", "serial": 9]))
720 guard let acknowledged = try reader.line(), try json(acknowledged)["ack"] as? Int == 9 else { throw ClipboardFailure("test_ack_failed") }
721 onGUI { board.clearContents(); board.setString("guest pushed text", forType: .string); agent.poll() }
722 guard let pushed = try reader.line(), try json(pushed)["text"] as? String == "guest pushed text" else { throw ClipboardFailure("test_push_failed") }
723
724 var bytes = Data([0, 255, 128, 10])
725 var length = UInt32(bytes.count).littleEndian
726 bytes = Data(bytes: &length, count: 4) + bytes + Data(repeating: 0, count: 4)
727 let saved = try rpc(["operation": "upload", "name": "中文 ' .bin"], bytes: bytes)
728 guard let files = saved["paths"] as? [String], files.count == 1,
729 try Data(contentsOf: URL(fileURLWithPath: files[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_upload_failed") }
730 let accepted = try rpc(["operation": "write", "files": files, "serial": 10])
731 guard accepted["ack"] as? Int == 10 else { throw ClipboardFailure("test_file_paste_failed") }
732 let copied = try rpc(["operation": "prepare-files", "files": files])
733 guard let duplicates = copied["paths"] as? [String], duplicates.count == 1,
734 try Data(contentsOf: URL(fileURLWithPath: duplicates[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_copy_failed") }
735 let denied = try rpc(["operation": "write", "files": ["/etc/passwd"]])
736 guard denied["error"] as? String == "unregistered_files" else { throw ClipboardFailure("test_unregistered_file_accepted") }
737 let discarded = try rpc(["operation": "discard", "files": duplicates])
738 let cleanupDeadline = Date().addingTimeInterval(5)
739 while FileManager.default.fileExists(atPath: duplicates[0]), Date() < cleanupDeadline {
740 Thread.sleep(forTimeInterval: 0.01)
741 }
742 guard discarded["ok"] as? Bool == true, !FileManager.default.fileExists(atPath: duplicates[0]) else { throw ClipboardFailure("test_discard_failed") }
743 onGUI { state.available = false; agent.poll() }
744 guard try reader.line() == nil else { throw ClipboardFailure("test_old_session_survived") }
745 } catch {
746 state.lock.lock(); state.failure = error; state.lock.unlock()
747 }
748 }
749 let deadline = Date().addingTimeInterval(30)
750 while done.wait(timeout: .now()) != .success && Date() < deadline {
751 _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01))
752 }
753 guard done.wait(timeout: .now()) == .success else { throw ClipboardFailure("test_transport_timeout") }
754 state.lock.lock(); let error = state.failure; state.lock.unlock()
755 if let error { throw error }
756}
757
758private func selfTest() throws {
759 let board = NSPasteboard(name: NSPasteboard.Name("cage-clipboard-qa-" + UUID().uuidString))
760 defer { board.releaseGlobally() }
761 let text = "中文🙂\nexact text"
762 try setBoard(board, ["text": text]); guard try boardContent(board)["text"] as? String == text else { throw ClipboardFailure("text_test_failed") }
763 let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 11, pixelsHigh: 7, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!
764 let value = bitmap.representation(using: .png, properties: [:])!
765 try setBoard(board, ["png": value.base64EncodedString()]); let actual = try boardContent(board)
766 guard let encoded = actual["png"] as? String, let data = Data(base64Encoded: encoded), try image(data).width == 11 else { throw ClipboardFailure("image_test_failed") }
767 do { try setBoard(board, ["png": "not-png"]); throw ClipboardFailure("invalid_image_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_image" else { throw error } }
768 do { _ = try paths(["/tmp/../escape"]); throw ClipboardFailure("invalid_files_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_files" else { throw error } }
769 try testAgentTransport(board)
770 print("macOS clipboard: named pasteboard text/image, private socket stream, framed file upload, registered-file checks, cleanup and GUI-session revocation passed")
771}
772
773@main
774struct GuestClipboard {
775 static func main() {
776 _ = signal(SIGPIPE, SIG_IGN)
777 do {
778 if CommandLine.arguments.dropFirst() == ["--self-test"] { try selfTest(); return }
779 if CommandLine.arguments.count == 3 && CommandLine.arguments[1] == "--client" { try client(CommandLine.arguments[2]); return }
780 try requireGuest()
781 let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1)
782 var count = 0
783 guard launch_activate_socket("Clipboard", storage, &count) == 0, count == 1 else { throw ClipboardFailure("clipboard_service_unavailable") }
784 let sockets = storage.pointee; storage.deallocate(); let listener = sockets[0]; free(sockets)
785 GuestDiagnostic.record("clipboard", "started")
786 NSApplication.shared.setActivationPolicy(.accessory)
787 let agent = ClipboardAgent()
788 let timer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) { _ in agent.poll() }
789 DispatchQueue.global(qos: .userInitiated).async {
790 let connections = DispatchSemaphore(value: 16)
791 while true {
792 connections.wait()
793 let fd = accept(listener, nil, nil)
794 if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(2) }
795 DispatchQueue.global(qos: .userInitiated).async { agent.serve(fd); connections.signal() }
796 }
797 }
798 NSApplication.shared.run(); timer.invalidate()
799 } catch {
800 GuestDiagnostic.record("clipboard", (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed")
801 try? writeAll(STDOUT_FILENO, jsonData(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed"]))
802 exit(1)
803 }
804 }
805}