diff --git a/Sources/MWBMac/ReceivedFile.swift b/Sources/MWBMac/ReceivedFile.swift index d045db6..7a41b58 100644 --- a/Sources/MWBMac/ReceivedFile.swift +++ b/Sources/MWBMac/ReceivedFile.swift @@ -29,15 +29,20 @@ public enum ReceivedFile { /// (`Clipboard.cs:679`, `Common.cs:1321-1327`). public static let folderName = "MouseWithoutBorders" + /// Where received files go, **without** creating anything: the app must not + /// put a folder on the user's Desktop until a file actually arrives. + public static func destinationURL() -> URL { + let manager = FileManager.default + let desktop = + manager.urls(for: .desktopDirectory, in: .userDomainMask).first + ?? manager.homeDirectoryForCurrentUser.appendingPathComponent("Desktop") + return desktop.appendingPathComponent(folderName, isDirectory: true) + } + /// `~/Desktop/MouseWithoutBorders/`, created if it is not there yet. public static func destinationDirectory() throws -> URL { let manager = FileManager.default - guard - let desktop = manager.urls(for: .desktopDirectory, in: .userDomainMask).first - else { - throw ReceivedFileError.destinationUnavailable("no Desktop folder") - } - let folder = desktop.appendingPathComponent(folderName, isDirectory: true) + let folder = destinationURL() if !manager.fileExists(atPath: folder.path) { do { try manager.createDirectory(at: folder, withIntermediateDirectories: true) diff --git a/Sources/MWBNet/BulkConnection.swift b/Sources/MWBNet/BulkConnection.swift index d2af223..b7c343c 100644 --- a/Sources/MWBNet/BulkConnection.swift +++ b/Sources/MWBNet/BulkConnection.swift @@ -286,9 +286,11 @@ final class BulkConnection: @unchecked Sendable { fail("\(peerName): \(parsed.name)") return false } - let isText = parsed.name.caseInsensitiveCompare(ClipboardCodec.textStreamName) + let isText = + parsed.name.caseInsensitiveCompare(ClipboardCodec.textStreamName) == .orderedSame - let isImage = parsed.name.caseInsensitiveCompare(ClipboardCodec.imageStreamName) + let isImage = + parsed.name.caseInsensitiveCompare(ClipboardCodec.imageStreamName) == .orderedSame if isText || isImage { @@ -313,6 +315,10 @@ final class BulkConnection: @unchecked Sendable { private func openStagingFile(named headerName: String) -> Destination? { let name = ClipboardCodec.fileName(fromHeaderName: headerName) + // The download folder is created here, not at startup: nothing appears + // on the user's Desktop until a file is actually on its way. + try? FileManager.default.createDirectory( + at: config.stagingDirectory, withIntermediateDirectories: true) let url = stagingURL() guard FileManager.default.createFile(atPath: url.path, contents: nil), let handle = try? FileHandle(forWritingTo: url) diff --git a/Sources/mwb/ClipboardBridge.swift b/Sources/mwb/ClipboardBridge.swift new file mode 100644 index 0000000..b185292 --- /dev/null +++ b/Sources/mwb/ClipboardBridge.swift @@ -0,0 +1,498 @@ +// 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) + /// 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 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 + 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 [] } + 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 ClipboardCodec.chunkPackets(payload: bytes, isImage: isImage).map { .send($0) } + } + 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")] + } + + /// Puts a received file's URL on the pasteboard, as + /// `Clipboard.SetFileDropList` does (`Clipboard.cs:864-868`). + public func announce(_ file: URL) { + watcher.write(.file(file)) + } +} + +/// The `Sendable` object the bulk channel and the pasteboard watcher call. +/// +/// Both call on their own queues and must not be blocked there (control-channel +/// Handshakes), so every method does one hop onto the Engine and returns. The +/// hop is a `Task`, not the Engine's `AsyncStream`, because the authorisation +/// call needs an answer back; clipboard events carry no ordering requirement +/// against input, so nothing is lost by not sharing that queue. +/// +/// `@unchecked Sendable`: the only stored property is a `weak` reference set +/// once at construction. It is weak so that Engine → bridge → channel → relay +/// does not close a retain cycle on the whole app. +public final class ClipboardRelay: BulkSink, @unchecked Sendable { + private weak var engine: Engine? + + /// A relay for one Engine. + public init(engine: Engine) { + self.engine = engine + } + + /// The user copied something on this Mac. + func copied(_ content: ClipboardContent) { + Task { [weak engine] in await engine?.clipboardCopied(content) } + } + + public func bulk( + _ channel: BulkChannel, authorise peerName: String, peerID: UInt32, + reply: @escaping @Sendable (Bool) -> 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 .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)") + } + } + } + + /// `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)") + } + } +} diff --git a/Sources/mwb/Engine.swift b/Sources/mwb/Engine.swift index 077ed3a..225bae9 100644 --- a/Sources/mwb/Engine.swift +++ b/Sources/mwb/Engine.swift @@ -161,6 +161,9 @@ public actor Engine { let injector: Injector var tap: EventTap? var channel: ControlChannel? + /// Clipboard sharing: the bulk channel, the pasteboard watcher and the + /// policy that drives them (the clipboard lane, `ClipboardBridge.swift`). + var clipboard: ClipboardBridge? private let events: AsyncStream let emit: @Sendable (EngineEvent) -> Void @@ -248,6 +251,7 @@ public actor Engine { applyConfiguration() startTap() startChannel() + startClipboard() // the clipboard lane Log.app.info("engine started as \(switcher.localName), id \(switcher.localID)") publish() } @@ -261,6 +265,7 @@ public actor Engine { if switcher.destinationIsRemote || switcher.isBroadcasting { recoverLocal(reason: .quitting) } + stopClipboard() // the clipboard lane channel?.sayGoodbye() try? await Task.sleep(for: .milliseconds(150)) channel?.stop() @@ -518,11 +523,15 @@ public actor Engine { // `Receiver.cs:378-384`: a peer took control; park and let go. perform(switcher.handleHideMouse()) - case .machineSwitched, .clipboard, .clipboardAsk, .clipboardPush, .clipboardText, - .clipboardImage, .clipboardCapture, .clipboardDataEnd, .clipboardDragDrop, - .clipboardDragDropEnd, .clipboardDragDropOperation, .explorerDragDrop, - .captureScreenCommand: - break // the clipboard lane; nothing here interprets a payload. + case .clipboard, .machineSwitched, .clipboardAsk, .clipboardText, .clipboardImage, + .clipboardDataEnd: + clipboardDispatch(packet, from: peerID) // the clipboard lane + + case .clipboardPush, .clipboardCapture, .clipboardDragDrop, .clipboardDragDropEnd, + .clipboardDragDropOperation, .explorerDragDrop, .captureScreenCommand: + // `ClipboardPush` only ever appears on a bulk connection; the rest + // are drag-and-drop and screen capture, out of scope (README D6). + break case .heartbeatExL2, .heartbeatExL3: break // key propagation, out of scope (README D6). diff --git a/Sources/mwb/EngineActions.swift b/Sources/mwb/EngineActions.swift index 4f7675f..4ea4288 100644 --- a/Sources/mwb/EngineActions.swift +++ b/Sources/mwb/EngineActions.swift @@ -83,7 +83,7 @@ extension Engine { reconfigureChannel() case .remoteClipboardWanted: - break // the clipboard lane asks the machine we just left for its data. + pullRemoteClipboard() // the clipboard lane } } @@ -229,6 +229,7 @@ extension Engine { moveRelatively: settings.moveMouseRelatively) tap?.reconfigure(captureConfig()) injector.reconfigure(InjectorConfig(lockMachine: settings.lockMachineShortcut)) + applyClipboardConfiguration() // the clipboard lane syncRouting() }