// Clipboard policy: what a local copy does, what each clipboard packet means, // when to pull a peer's big payload and when to ask it to push one. // // Ported from App/Core/Clipboard.cs CheckClipboardEx (85-251), // SendClipboardDataUsingTCP (253-306), ReceiveClipboardDataUsingTCP (308-373) // and GetRemoteClipboard (377-399); the clipboard cases of // App/Core/Receiver.cs (273-380); and App/Core/Event.cs (219-231). // // Isolation: `ClipboardBridge` is a plain class stored on the `Engine` actor and // called only from it, so it needs no locking of its own — the actor is the // lock, exactly as `Switcher` is held (contracts C3). Like `Switcher` it decides // and returns `[ClipboardAction]`; the Engine performs them, because only the // Engine may stamp a packet (contracts C1) and only it can see the connections. // The two things the bridge *does* own are `Sendable` and thread-safe on their // own queues: the bulk channel and the pasteboard watcher. import AppKit import Foundation import MWBCore import MWBMac import MWBNet /// What the Engine must do on the bridge's behalf. public enum ClipboardAction: Sendable { /// Route this packet; the Engine stamps `Id` and `Src` (contracts C1). case send(Packet) /// Send a small payload in-band as 48-byte chunks, paced (see /// `ClipboardBridge.beginChunkedSend`). case sendChunks(payload: Data, isImage: Bool) /// Fetch the big payload waiting on `machine`: pull if we have an outbound /// connection to it, else ask it to push (`Clipboard.cs:425-449`). case getRemoteClipboard(machine: String, postAction: UInt32) /// Answer a `ClipboardAsk` by pushing to `machine` (`Receiver.cs:320-343`). case pushClipboard(machine: String, postAction: UInt32) /// Move a completed staging file into the download folder and reveal it. case commitFile(staged: URL, name: String) /// Something worth one line in the log. case note(String) } /// The clipboard half of the app. public final class ClipboardBridge { /// The bulk transport. Thread-safe on its own queue. let bulk: BulkChannel private let watcher: PasteboardWatcher private var config: BulkConfig private var shareClipboard: Bool private var transferFile: Bool /// The machine whose `Clipboard (69)` beat we saw last, and when /// (`Clipboard.lastMachineWithClipboardData` / `clipboardCopiedTime`). private var machineWithData: String? private var beatTime: TimeInterval = 0 private var reassemblers: [UInt32: Reassembler] = [:] private var sendTask: Task? private var started = false /// Builds the bridge. `relay` is the `Sendable` object the channel and the /// watcher call back on; it hops to the Engine. public init( config: BulkConfig, shareClipboard: Bool, transferFile: Bool, relay: ClipboardRelay ) { self.config = config self.shareClipboard = shareClipboard self.transferFile = transferFile bulk = BulkChannel(config: config, sink: relay) watcher = PasteboardWatcher(onChange: { [weak relay] content in relay?.copied(content) }) } // MARK: - Lifecycle /// Opens the bulk listener and starts watching the pasteboard. public func start() { guard !started else { return } started = true bulk.start() if shareClipboard { watcher.start() } } /// Stops both, and forgets what was on offer. public func stop() { started = false sendTask?.cancel() sendTask = nil watcher.stop() bulk.serve(nil) bulk.stop() reassemblers.removeAll() } /// Re-applies the settings (`ShareClipboard`, `TransferFile`, the key, the /// port and this Mac's identity). public func apply(config new: BulkConfig, shareClipboard: Bool, transferFile: Bool) { self.transferFile = transferFile if new != config { config = new bulk.reconfigure(new) } guard shareClipboard != self.shareClipboard else { return } self.shareClipboard = shareClipboard // Turning sharing off stops the watcher and withdraws whatever was on // offer; nothing of this Mac's clipboard leaves after that. if shareClipboard { if started { watcher.start() } } else { watcher.stop() bulk.serve(nil) } } // MARK: - A local copy (`CheckClipboardEx`, `Clipboard.cs:85-251`) /// The user copied something. Small payloads go in-band as 48-byte chunks; /// big ones and every file become a `Clipboard (69)` beat plus a payload /// the peer can pull. public func localCopy(_ content: ClipboardContent, now: TimeInterval) -> [ClipboardAction] { guard shareClipboard else { return [] } // `Clipboard.cs:111-114`: whatever was on offer is forgotten before the // new clipboard contents are looked at, so a branch that decides not to // share leaves nothing behind for a peer to pull. bulk.serve(nil) switch content { case .file(let url): return localFile(url) case .text(let text): guard !text.isEmpty else { return [] } guard let blob = try? ClipboardCodec.encodeText(text) else { return [.note("clipboard text could not be compressed")] } return offer(.text(blob), bytes: blob, isImage: false) case .image(let png): guard !png.isEmpty, png.count <= ClipboardCodec.maxImageSize else { return [] } return offer(.image(png), bytes: png, isImage: true) } } /// `Clipboard.cs:141-187`: a folder, a file over 100 MB and a missing file /// are all still announced — the message travels as the transfer's header, /// so the other machine can say what went wrong. private func localFile(_ url: URL) -> [ClipboardAction] { guard transferFile else { return [] } let payload: BulkPayload if ReceivedFile.isDirectory(url) { payload = .failure("\(url.path) - Folder is not supported, zip it first!") } else if let size = ReceivedFile.size(of: url) { payload = size > ClipboardCodec.maxFileSize ? .failure( "\(url.path) - File too big (greater than 100MB)," + " please drag and drop the file instead!") : .file(url) } else { return [.note("clipboard file not found")] } bulk.serve(payload) return [.send(beat())] } /// Serves the payload either way — Windows keeps `LastClipboardData` set /// whatever its size (`:229-240`) — and then either beats or chunks. private func offer(_ payload: BulkPayload, bytes: Data, isImage: Bool) -> [ClipboardAction] { bulk.serve(payload) guard bytes.count > ClipboardCodec.inBandLimit else { return [.sendChunks(payload: bytes, isImage: isImage)] } return [.send(beat())] } /// `Common.SendClipboardBeat` (`Common.cs:617-620`): `Clipboard (69)` to /// everybody, carrying this machine's name. private func beat() -> Packet { var packet = Packet(type: .clipboard) packet.des = MachineID.all try? packet.setMachineName(config.localName) return packet } // MARK: - Received packets (`Receiver.cs:273-380`) /// The clipboard cases of `ProcessPackage`. `peerName` is the pool's name /// for `packet.Src`, which is what `GetNameOfMachineWithClipboardData` /// looks up (`Receiver.cs:406-414`). public func handle(_ packet: Packet, from peerName: String?, now: TimeInterval) -> [ClipboardAction] { switch packet.type { case .clipboard: // `Receiver.cs:273-281`: a beat is not addressed to anyone in // particular; whoever hears it remembers who has the data. beatTime = now machineWithData = peerName ?? packet.machineName return [] case .machineSwitched: // `Receiver.cs:284-291`: we are the machine being switched to, and // the switcher had big data within the window. guard packet.des == config.localID else { return [] } return pullIfFresh(now: now) case .clipboardAsk: // `Receiver.cs:315-344`: it cannot reach us, so we go to it. guard packet.des == config.localID, let name = packet.machineName, !name.isEmpty else { return [] } return [.pushClipboard(machine: name, postAction: packet.postAction)] case .clipboardText, .clipboardImage, .clipboardDataEnd: beatTime = 0 // Receiver.cs:363 return inBand(packet, now: now) default: // Drag and drop, screen capture and the `Heartbeat_ex` family are // out of scope (README D6); nothing here interprets them. return [] } } /// The pull half of `Event.PrepareToSwitchToMachine` (`Event.cs:219-226`): /// control came home and a peer had big data within the last 30 seconds. public func wantsRemoteClipboard(now: TimeInterval) -> [ClipboardAction] { pullIfFresh(now: now) } private func pullIfFresh(now: TimeInterval) -> [ClipboardAction] { guard now - beatTime < ClipboardCodec.bigDataWindow, let machine = machineWithData, !machine.isEmpty else { return [] } beatTime = 0 return [.getRemoteClipboard(machine: machine, postAction: 0)] } // MARK: - In-band reassembly (`Clipboard.cs:308-373`) private func inBand(_ packet: Packet, now: TimeInterval) -> [ClipboardAction] { pruneReassemblers(now: now) let source = packet.src let reassembler = reassemblers[source] ?? Reassembler(now: now) reassemblers[source] = reassembler guard let payload = reassembler.feed(packet, now: now) else { if reassembler.abandoned { reassemblers[source] = nil return [.note("clipboard payload from \(source) was too big")] } return [] } let isImage = reassembler.isImage reassemblers[source] = nil return write(payload, isImage: isImage) } /// A sender that stops mid-transfer would otherwise hold its buffer for as /// long as the app runs. Windows has no such state: its receive loop blocks /// until the terminator and gives up after 100 foreign packets /// (docs/protocol.md §10.7). private func pruneReassemblers(now: TimeInterval) { reassemblers = reassemblers.filter { now - $0.value.lastChunk < ClipboardCodec.bigDataWindow } } // MARK: - Something arrived /// A completed bulk transfer. public func received(_ content: BulkReceived, from peerName: String) -> [ClipboardAction] { switch content { case .text(let blob): return write(blob, isImage: false) case .image(let png): return write(png, isImage: true) case .file(let staged, let name): return [.commitFile(staged: staged, name: name)] } } /// Puts a decoded payload on this Mac's pasteboard /// (`Clipboard.cs:353-363`, `1101-1194`). private func write(_ payload: Data, isImage: Bool) -> [ClipboardAction] { if isImage { guard !payload.isEmpty else { return [] } watcher.write(.image(png: payload)) return [.note("image received")] } guard let text = try? ClipboardCodec.decodeText(payload), !text.isEmpty else { return [.note("clipboard text could not be decoded")] } watcher.write(.text(text)) return [.note("text received")] } // MARK: - Pacing the in-band chunks /// Chunks handed to the channel at once. static let chunkBatch = 128 /// How long the sender waits between batches. static let chunkPause = Duration.milliseconds(5) /// Feeds a chunked payload to the Engine a batch at a time. /// /// A 1 MB payload is 21 846 packets. Handing them over in one go would /// overrun the 512-packet outbox a connection is allowed (contracts C3) and /// close it, and would put a second of clipboard traffic in front of the /// next mouse packet. Windows paces naturally because /// `SendClipboardDataUsingTCP` writes each packet down a blocking socket /// from its own thread (`Clipboard.cs:260-305`); this is that thread. /// /// Only one chunked send runs at a time: a second copy cancels the first, /// because interleaved chunks from two payloads would arrive as one /// corrupt stream. func beginChunkedSend( _ packets: [Packet], forward: @escaping @Sendable ([Packet]) async -> Void ) { sendTask?.cancel() // Captures nothing but `packets` and `forward`, both `Sendable`, so the // task does not drag this actor-isolated object off the Engine. sendTask = Task { var index = 0 while index < packets.count { if Task.isCancelled { return } let end = min(index + ClipboardBridge.chunkBatch, packets.count) await forward(Array(packets[index.. Void ) { Task { [weak engine] in guard let engine else { reply(false) return } reply(await engine.clipboardTrusts(name: peerName, peerID: peerID)) } } public func bulk( _ channel: BulkChannel, received: BulkReceived, from peerName: String, postAction: UInt32 ) { Task { [weak engine] in await engine?.clipboardReceived(received, from: peerName) } } public func bulk(_ channel: BulkChannel, failed reason: String) { Task { [weak engine] in await engine?.clipboardFailed(reason) } } } extension Engine { // MARK: - Lifecycle /// Builds and starts the clipboard bridge. Idempotent. func startClipboard() { guard clipboard == nil else { return } let bridge = ClipboardBridge( config: bulkConfig(), shareClipboard: settings.shareClipboard, transferFile: settings.transferFile, relay: ClipboardRelay(engine: self)) clipboard = bridge bridge.start() Log.engine.info("clipboard sharing \(settings.shareClipboard ? "on" : "off")") } /// Stops it and drops it. func stopClipboard() { clipboard?.stop() clipboard = nil } /// The bulk channel's half of the settings (contracts C4). func bulkConfig() -> BulkConfig { BulkConfig( localName: switcher.localName, localID: switcher.localID, port: settings.tcpPort, securityKey: settings.securityKey, stagingDirectory: ReceivedFile.destinationURL()) } /// Re-applies the settings; called from `applyConfiguration()`. func applyClipboardConfiguration() { clipboard?.apply( config: bulkConfig(), shareClipboard: settings.shareClipboard, transferFile: settings.transferFile) } // MARK: - The bridge's inputs /// A clipboard packet from a trusted, de-duplicated connection. func clipboardDispatch(_ packet: Packet, from peerID: UInt32) { guard let clipboard else { return } // `GetNameOfMachineWithClipboardData` looks the sender up in the pool by // `Src` (`Receiver.cs:406-414`); the packet's own name is the fallback. let name = switcher.pool.name(for: packet.src) ?? peerNames[peerID] ?? packet.machineName perform(clipboard.handle(packet, from: name, now: EventTap.now())) } /// The user copied something here. func clipboardCopied(_ content: ClipboardContent) { guard let clipboard else { return } perform(clipboard.localCopy(content, now: EventTap.now())) } /// Control came home and a peer may have big data waiting /// (`SwitchAction.remoteClipboardWanted`, `Event.cs:221-226`). func pullRemoteClipboard() { guard let clipboard else { return } perform(clipboard.wantsRemoteClipboard(now: EventTap.now())) } /// The bulk channel's trust gate (`Clipboard.cs:1009`): the name must /// resolve to that id in the pool **and** that id must be connected. func clipboardTrusts(name: String, peerID: UInt32) -> Bool { guard peerID != MachineID.none, switcher.pool.resolveID(name: name) == peerID else { return false } return switcher.isConnected(to: peerID) } /// A bulk transfer completed. func clipboardReceived(_ content: BulkReceived, from peerName: String) { guard let clipboard else { if case .file(let staged, _) = content { ReceivedFile.discard(staged) } return } perform(clipboard.received(content, from: peerName)) } /// A bulk transfer did not. func clipboardFailed(_ reason: String) { Log.engine.info("clipboard: \(reason)") } // MARK: - Performing the bridge's actions func perform(_ actions: [ClipboardAction]) { for action in actions { switch action { case .send(let packet): stampAndForward(packet) case .sendChunks(let payload, let isImage): clipboard?.beginChunkedSend( ClipboardCodec.chunkPackets(payload: payload, isImage: isImage), forward: { [weak self] batch in await self?.forwardClipboardBatch(batch) }) case .getRemoteClipboard(let machine, let postAction): getRemoteClipboard(from: machine, postAction: postAction) case .pushClipboard(let machine, let postAction): pushClipboard(to: machine, postAction: postAction) case .commitFile(let staged, let name): commitReceivedFile(staged: staged, name: name) case .note(let text): Log.engine.info("clipboard: \(text)") } } } /// One batch of in-band clipboard chunks, each stamped once and fanned out /// unchanged (contracts C1). func forwardClipboardBatch(_ packets: [Packet]) { for packet in packets { stampAndForward(packet) } } /// `ConnectAndGetData` (`Clipboard.cs:419-449`): pull over an outbound /// connection if there is one, otherwise ask the peer to push, because a /// machine we never dialled may not be reachable from here at all. private func getRemoteClipboard(from machine: String, postAction: UInt32) { guard let clipboard else { return } if let address = outboundAddress(to: machine) { clipboard.bulk.pull(from: address, peerName: machine, postAction: postAction) return } guard let id = switcher.pool.resolveID(name: machine) else { Log.engine.info("clipboard: \(machine) is not in the machine pool") return } var packet = Packet(type: .clipboardAsk) packet.des = id packet.postAction = postAction try? packet.setMachineName(switcher.localName) stampAndForward(packet) } private func pushClipboard(to machine: String, postAction: UInt32) { guard let clipboard, let address = clipboardAddress(for: machine) else { return } clipboard.bulk.push(to: address, peerName: machine, postAction: postAction) } /// `Common.IsConnectedByAClientSocketTo` (`Common.cs:1142-1161`), plus the /// address that connection used — `GetConnectedClientSocketIPAddressFor`. private func outboundAddress(to machine: String) -> String? { (channel?.statuses ?? []).first { row in row.isOutbound && row.status == .connected && row.name.caseInsensitiveCompare(machine) == .orderedSame }?.address } /// Where to dial a peer's port 15100: its connected socket's address if we /// have one, else the name itself, which is what /// `ConnectToRemoteClipboardSocket` falls back to (`Clipboard.cs:1083-1090`). private func clipboardAddress(for machine: String) -> String? { guard !machine.isEmpty else { return nil } if let outbound = outboundAddress(to: machine) { return outbound } let connected = (channel?.statuses ?? []).first { row in row.status == .connected && row.name.caseInsensitiveCompare(machine) == .orderedSame } return connected?.address ?? machine } /// Puts a received file where Windows puts it and shows it to the user /// (`Clipboard.cs:787-798, 840-868`). A commit that fails leaves the /// previous file alone and deletes the staging copy. private func commitReceivedFile(staged: URL, name: String) { do { let directory = try ReceivedFile.destinationDirectory() let file = try ReceivedFile.commit(staged: staged, toFileNamed: name, in: directory) clipboard?.announce(file) Log.engine.info("clipboard: received \(name)") Task { @MainActor in ReceivedFile.reveal(file) } } catch { ReceivedFile.discard(staged) Log.engine.error("clipboard: could not save \(name): \(error)") } } }