diff --git a/Sources/MWBCore/ClipboardCodec.swift b/Sources/MWBCore/ClipboardCodec.swift index ea83eac..2e6b8cf 100644 --- a/Sources/MWBCore/ClipboardCodec.swift +++ b/Sources/MWBCore/ClipboardCodec.swift @@ -215,8 +215,9 @@ public enum ClipboardCodec { repeat { var packet = Packet(type: type) packet.des = MachineID.all - let end = min(index + Packet.clipboardChunkSize, payload.count) - packet.payload48 = payload.subdata(in: index.."`, which is how Windows + /// reports a missing file, a folder or an oversized file (`:1690-1697`). + case failure(String) +} + +/// What arrived over a bulk connection. +public enum BulkReceived: Sendable, Equatable { + /// A raw-DEFLATE text blob. + case text(Data) + /// PNG bytes. + case image(Data) + /// A completed staging file, and the name it should be committed under. + /// The receiver owns it: commit it or discard it, but do not leave it. + case file(staged: URL, name: String) +} + +/// What one bulk connection tells the app. Every call arrives on the channel's +/// serial queue; do the least possible work and hop to the Engine. +public protocol BulkSink: AnyObject, Sendable { + /// May this peer exchange clipboard data with us? + /// + /// The Windows gate is `MachinePool.ResolveID(name) == Src` **and** a live + /// control connection to that id (`Clipboard.cs:1009`). The answer is + /// asynchronous because it lives on the Engine actor; nothing is read from + /// or written to the connection until `reply(true)` (CLAUDE.md invariant 2). + func bulk( + _ channel: BulkChannel, authorise peerName: String, peerID: UInt32, + reply: @escaping @Sendable (Bool) -> Void) + + /// A transfer completed. + func bulk( + _ channel: BulkChannel, received: BulkReceived, from peerName: String, + postAction: UInt32) + + /// A transfer did not complete, with a line fit for the log or a + /// notification. + func bulk(_ channel: BulkChannel, failed reason: String) +} + +/// The clipboard/file transport. +/// +/// `@unchecked Sendable` for the same reason as `ControlChannel`: every mutable +/// property is touched only on `queue`, one private serial queue that each +/// connection's queue targets, so the queue is the lock (contracts C3). +public final class BulkChannel: @unchecked Sendable { + /// How long a connection may make no progress before it is dropped + /// (`CLIPBOARD_HANDSHAKE_TIMEOUT`, `Clipboard.cs:963-964`). + public static let idleTimeout: TimeInterval = 30 + /// Bytes per write (`NETWORK_STREAM_BUF_SIZE`, `Common.cs:112`). + public static let chunkSize = ClipboardCodec.bulkChunkSize + /// Connections this machine will hold at once. Windows serialises receives + /// behind one semaphore (`Clipboard.cs:925-941`); this is the equivalent + /// bound, and it keeps a hostile listener from opening sockets forever. + public static let connectionLimit = 4 + + private let queue = DispatchQueue(label: "mwb.bulk-channel") + private let sink: BulkSink + + private var config: BulkConfig + private var listener: NWListener? + private var connections: [BulkConnection] = [] + private var payload: BulkPayload? + private var connectionCount = 0 + private var running = false + private var stopped = false + + /// A channel that is not listening yet. + public init(config: BulkConfig, sink: BulkSink) { + self.config = config + self.sink = sink + } + + // MARK: - Lifecycle + + /// Opens the listener on `config.port`. + public func start() { + queue.async { [self] in + guard !running else { return } + running = true + openListener() + } + } + + /// Closes the listener and every transfer in flight. + public func stop() { + queue.async { [self] in + running = false + stopped = true + closeListener() + for connection in connections { connection.cancel("channel stopped") } + payload = nil + } + } + + /// Applies new settings. A port or key change reopens the listener and + /// drops transfers in flight, because neither can survive it. + public func reconfigure(_ new: BulkConfig) { + queue.async { [self] in + let disruptive = + new.port != config.port || new.securityKey != config.securityKey + || new.localID != config.localID || new.localName != config.localName + config = new + guard disruptive, running else { return } + closeListener() + for connection in connections { connection.cancel("settings changed") } + openListener() + } + } + + // MARK: - What the app asks of the channel + + /// Sets what a peer pulling from us gets, or clears it. + /// + /// Windows keeps the same thing in `Clipboard.LastClipboardData` / + /// `LastDragDropFile` and reads it at serve time (`:1684-1810`); the 30 s + /// freshness window is enforced by the *puller*, not here. + public func serve(_ new: BulkPayload?) { + queue.async { [self] in payload = new } + } + + /// Connects to a peer and receives whatever it is serving + /// (`ConnectAndGetData`, `Clipboard.cs:401-485`). + public func pull(from address: String, peerName: String, postAction: UInt32) { + dial(address: address, peerName: peerName, postAction: postAction, role: .pulling) + } + + /// Connects to a peer and sends it our payload — the answer to + /// `ClipboardAsk` (`Receiver.cs:320-343`). + public func push(to address: String, peerName: String, postAction: UInt32) { + dial(address: address, peerName: peerName, postAction: postAction, role: .pushing) + } + + private func dial( + address: String, peerName: String, postAction: UInt32, role: BulkConnection.Role + ) { + queue.async { [self] in + // Not gated on `running`: Windows dials the clipboard socket from + // `ConnectAndGetData` whatever state its own listener is in + // (`Clipboard.cs:1068-1099`), so a port already taken by something + // else must not also stop us pulling. + guard !stopped, let port = NWEndpoint.Port(rawValue: config.port) else { return } + guard connections.count < BulkChannel.connectionLimit else { + sink.bulk(self, failed: "too many clipboard transfers in flight") + return + } + let connection = NWConnection( + host: NWEndpoint.Host(address), port: port, using: BulkChannel.parameters()) + add(connection, role: role, peerName: peerName, postAction: postAction) + } + } + + // MARK: - Listener + + private func openListener() { + guard listener == nil, let port = NWEndpoint.Port(rawValue: config.port) else { return } + do { + let new = try NWListener(using: BulkChannel.parameters(), on: port) + new.newConnectionHandler = { [weak self] connection in + self?.accept(connection) + } + new.stateUpdateHandler = { [weak self] state in + if case .failed = state { self?.closeListener() } + } + listener = new + new.start(queue: queue) + } catch { + listener = nil + sink.bulk(self, failed: "clipboard listener could not open: \(error)") + } + } + + private func closeListener() { + listener?.newConnectionHandler = nil + listener?.stateUpdateHandler = nil + listener?.cancel() + listener = nil + } + + private func accept(_ connection: NWConnection) { + guard running, connections.count < BulkChannel.connectionLimit else { + connection.cancel() + return + } + add(connection, role: .accepted, peerName: nil, postAction: 0) + } + + /// `NoDelay` and big buffers, as `ShakeHand` sets on every clipboard socket + /// (`Clipboard.cs:965-966`). Network.framework exposes no buffer sizes. + private static func parameters() -> NWParameters { + let tcp = NWProtocolTCP.Options() + tcp.noDelay = true + let parameters = NWParameters(tls: nil, tcp: tcp) + parameters.includePeerToPeer = false + parameters.allowLocalEndpointReuse = true + return parameters + } + + // MARK: - Connections + + private func add( + _ connection: NWConnection, role: BulkConnection.Role, peerName: String?, + postAction: UInt32 + ) { + connectionCount += 1 + let peerQueue = DispatchQueue(label: "mwb.bulk.\(connectionCount)", target: queue) + do { + let transfer = try BulkConnection( + connection: connection, role: role, peerName: peerName, postAction: postAction, + config: config, queue: peerQueue, + onEvent: { [weak self] transfer, event in self?.handle(transfer, event) }) + connections.append(transfer) + transfer.start() + } catch { + connection.cancel() + sink.bulk(self, failed: "clipboard cipher could not start: \(error)") + } + } + + private func handle(_ transfer: BulkConnection, _ event: BulkConnection.Event) { + switch event { + case .authorise(let name, let id, let reply): + sink.bulk(self, authorise: name, peerID: id, reply: reply) + + case .wantsPayload(let reply): + reply(payload) + + case .received(let content, let name, let postAction): + sink.bulk(self, received: content, from: name, postAction: postAction) + + case .failed(let reason): + sink.bulk(self, failed: reason) + + case .closed: + connections.removeAll { $0 === transfer } + } + } +} diff --git a/Sources/MWBNet/BulkConnection.swift b/Sources/MWBNet/BulkConnection.swift new file mode 100644 index 0000000..d2af223 --- /dev/null +++ b/Sources/MWBNet/BulkConnection.swift @@ -0,0 +1,539 @@ +// One bulk transfer: the 48-byte cipher preamble, the unframed 64-byte `DATA` +// each way, the 1024-byte header and the body — in whichever direction the +// handshake decided. +// +// Ported from App/Core/Clipboard.cs ShakeHand (961-1066) and +// ReceiveAndProcessClipboardDataCore (498-923), and App/Class/SocketStuff.cs +// SendClipboardData (1673-1811), SendFileEx (1812-1860) and SendData (1878-1931). +// +// The 64-byte `DATA` on this connection is written **raw**, without the magic +// and checksum of `Framing` (docs/protocol.md §10.7 answer (a)), so bytes 1..3 +// of a valid one are zero and are checked to be. + +import Foundation +import MWBCore +import Network + +/// One clipboard or file transfer over its own TCP connection. +/// +/// `@unchecked Sendable`: every stored property is read and written only on +/// `queue`, a serial queue that targets the channel's queue (contracts C3). +final class BulkConnection: @unchecked Sendable { + /// Which end of the exchange this is. + enum Role { + /// We dialled to fetch the peer's clipboard (`ConnectAndGetData`). + case pulling + /// We dialled to hand the peer ours (the `ClipboardAsk` answer). + case pushing + /// The peer dialled us; its handshake packet says which way data goes. + case accepted + } + + /// What this connection tells the channel, on the connection's queue. + enum Event { + case authorise(String, UInt32, @Sendable (Bool) -> Void) + case wantsPayload(@Sendable (BulkPayload?) -> Void) + case received(BulkReceived, peerName: String, postAction: UInt32) + case failed(String) + case closed + } + + private enum Phase { + case handshake, authorising, header, body, sending, finished + } + + private enum Destination { + case memory(isImage: Bool) + case file(handle: FileHandle, url: URL, name: String) + } + + private let connection: NWConnection + private let role: Role + private let config: BulkConfig + private let queue: DispatchQueue + private let onEvent: (BulkConnection, Event) -> Void + private let writer: CipherWriter + private let reader: CipherReader + + private var phase: Phase = .handshake + private var peerName: String + private var peerID: UInt32 = MachineID.none + private var postAction: UInt32 + + private var inbox = Data() + private var destination: Destination? + private var memory = Data() + private var remaining: Int64 = 0 + + private var outboundData: Data? + private var outboundFile: FileHandle? + private var outboundOffset = 0 + private var outboundRemaining: Int64 = 0 + private var paddingRemaining = 0 + + private var deadline: DispatchWorkItem? + private var started = false + + /// Wraps an `NWConnection` that has not been started yet. Throws only when + /// the security key cannot be turned into a cipher stream. + init( + connection: NWConnection, role: Role, peerName: String?, postAction: UInt32, + config: BulkConfig, queue: DispatchQueue, + onEvent: @escaping (BulkConnection, Event) -> Void + ) throws { + self.connection = connection + self.role = role + self.config = config + self.queue = queue + self.onEvent = onEvent + self.peerName = peerName ?? "" + self.postAction = postAction + writer = try CipherWriter(securityKey: config.securityKey) + reader = CipherReader(securityKey: config.securityKey) + } + + // MARK: - Lifecycle + + func start() { + connection.stateUpdateHandler = { [weak self] state in + guard let self else { return } + switch state { + case .ready: + self.becameReady() + case .waiting, .failed, .cancelled: + self.cancel("clipboard connection closed") + default: + break + } + } + connection.start(queue: queue) + } + + /// Ends the transfer, reporting `reason` unless it already finished. + func cancel(_ reason: String) { + guard phase != .finished else { return } + fail(reason) + } + + private func becameReady() { + guard !started, phase != .finished else { return } + started = true + armDeadline() + // `ShakeHand` (`Clipboard.cs:983-987`): the cipher preamble, then one + // unframed 64-byte package, before anything is read. + send(writer.header, encrypted: false) + send(handshakePacket().bytes, encrypted: true) + receive() + } + + /// `Clipboard.cs:973-979`: the acceptor always announces `ClipboardPush` + /// and lets the *connector's* type decide the direction, so a connector + /// announces what it wants — `Clipboard (69)` to pull, `ClipboardPush (79)` + /// to push. + private func handshakePacket() -> Packet { + var packet = Packet(type: role == .pulling ? .clipboard : .clipboardPush) + packet.src = config.localID + packet.postAction = postAction + try? packet.setMachineName(config.localName) // a non-ASCII name cannot start the app + return packet + } + + // MARK: - Reading + + private func receive() { + connection.receive(minimumIncompleteLength: 1, maximumLength: BulkChannel.chunkSize) { + [weak self] content, _, isComplete, error in + guard let self, self.phase != .finished else { return } + if let error { + self.fail("clipboard read failed: \(error)") + return + } + if let content, !content.isEmpty { + self.armDeadline() + do { + self.inbox.append(try self.reader.read(content)) + } catch { + self.fail("clipboard stream could not be decrypted") + return + } + self.advance() + } + if isComplete { + self.endOfStream() + return + } + self.receiveMoreIfWanted() + } + } + + /// Reads on while there is something left to parse. While the Engine is + /// authorising, or once this side has become the sender, there is not: the + /// peer writes nothing more, and a pending read would turn its polite close + /// into a spurious failure. + private func receiveMoreIfWanted() { + switch phase { + case .handshake, .header, .body: receive() + case .authorising, .sending, .finished: break + } + } + + /// The peer closed its half. That is how a finished send ends and how a + /// truncated receive ends. + private func endOfStream() { + switch phase { + case .sending, .finished: finish() + case .handshake, .authorising, .header, .body: + fail("clipboard connection from \(peerName.isEmpty ? "a peer" : peerName) ended early") + } + } + + /// Consumes as much of `inbox` as the current phase can. + private func advance() { + while true { + switch phase { + case .handshake: + guard inbox.count >= packageSizeEx else { return } + let bytes = take(packageSizeEx) + guard acceptHandshake(bytes) else { return } + + case .header: + guard inbox.count >= ClipboardCodec.bulkHeaderSize else { return } + let bytes = take(ClipboardCodec.bulkHeaderSize) + guard openDestination(bytes) else { return } + + case .body: + guard !inbox.isEmpty else { return } + let wanted = Int(min(remaining, Int64(inbox.count))) + let chunk = take(wanted) + guard writeBody(chunk) else { return } + if remaining == 0 { + complete() + return + } + + case .authorising, .sending, .finished: + return + } + } + } + + private func take(_ count: Int) -> Data { + let chunk = inbox.prefix(count) + inbox.removeFirst(count) + return Data(chunk) + } + + // MARK: - The handshake (`Clipboard.cs:996-1037`) + + private func acceptHandshake(_ bytes: Data) -> Bool { + // The package is raw here, not framed: Windows assigns the four type + // bytes straight into the struct (`DATA.cs:115-121`), so bytes 1..3 + // must be zero or `Type` is not the value it looks like. + let raw = [UInt8](bytes) + guard raw[1] == 0, raw[2] == 0, raw[3] == 0, let packet = Packet(bytes: bytes), + packet.type == .clipboard || packet.type == .clipboardPush, + let name = packet.machineName, !name.isEmpty + else { + fail("clipboard handshake rejected") + return false + } + peerName = name + peerID = packet.src + postAction = packet.postAction + phase = .authorising + + // Nothing is read or written for this peer until the Engine says the + // name resolves to that id on a live connection (invariant 2). + let peerPushes = packet.type == .clipboardPush + onEvent( + self, + .authorise(name, packet.src) { [weak self] allowed in + guard let self else { return } + self.queue.async { self.authorised(allowed, peerPushes: peerPushes) } + }) + return false + } + + private func authorised(_ allowed: Bool, peerPushes: Bool) { + guard phase == .authorising else { return } + guard allowed else { + fail("clipboard connection from \(peerName) rejected: not a connected machine") + return + } + armDeadline() + // `SendOrReceiveClipboardData` (`SocketStuff.cs:1655-1665`): the + // acceptor receives when the connector pushed, and sends otherwise. + let weReceive = role == .pulling || (role == .accepted && peerPushes) + if weReceive { + phase = .header + advance() + receiveMoreIfWanted() + } else { + phase = .sending + onEvent(self, .wantsPayload { [weak self] payload in self?.beginSending(payload) }) + } + } + + // MARK: - Receiving (`Clipboard.cs:562-790`) + + private func openDestination(_ header: Data) -> Bool { + guard let parsed = try? ClipboardCodec.parseBulkHeader(header) else { + fail("clipboard header could not be read") + return false + } + guard parsed.byteCount > 0 else { + // `"0* not found!"` and its siblings (`SocketStuff.cs:1690-1697`). + fail("\(peerName): \(parsed.name)") + return false + } + let isText = parsed.name.caseInsensitiveCompare(ClipboardCodec.textStreamName) + == .orderedSame + let isImage = parsed.name.caseInsensitiveCompare(ClipboardCodec.imageStreamName) + == .orderedSame + + if isText || isImage { + guard parsed.byteCount <= Int64(ClipboardCodec.maxImageSize) else { + fail("clipboard payload from \(peerName) is too big") + return false + } + destination = .memory(isImage: isImage) + memory = Data() + } else { + guard parsed.byteCount <= config.maxFileSize else { + fail("file from \(peerName) is bigger than the 100MB limit") + return false + } + guard let opened = openStagingFile(named: parsed.name) else { return false } + destination = opened + } + remaining = parsed.byteCount + phase = .body + return true + } + + private func openStagingFile(named headerName: String) -> Destination? { + let name = ClipboardCodec.fileName(fromHeaderName: headerName) + let url = stagingURL() + guard FileManager.default.createFile(atPath: url.path, contents: nil), + let handle = try? FileHandle(forWritingTo: url) + else { + fail("could not create a file for \(name)") + return nil + } + return .file(handle: handle, url: url, name: name) + } + + /// The staging name `ReceivedDestinationFile` uses (`:24-27`), built here so + /// `MWBNet` needs nothing from `MWBMac`; the committing half lives in + /// `MWBMac/ReceivedFile.swift`. + private func stagingURL() -> URL { + let unique = UUID().uuidString.replacingOccurrences(of: "-", with: "") + return config.stagingDirectory.appendingPathComponent(".\(unique).partial") + } + + private func writeBody(_ chunk: Data) -> Bool { + switch destination { + case .memory: + memory.append(chunk) + case .file(let handle, _, _): + do { + try handle.write(contentsOf: chunk) + } catch { + fail("writing the received file failed: \(error)") + return false + } + case nil: + fail("clipboard body with no destination") + return false + } + remaining -= Int64(chunk.count) + return true + } + + private func complete() { + guard let destination else { return } + let content: BulkReceived + switch destination { + case .memory(let isImage): + content = isImage ? .image(memory) : .text(memory) + case .file(let handle, let url, let name): + try? handle.close() + content = .file(staged: url, name: name) + } + self.destination = nil + memory = Data() + onEvent(self, .received(content, peerName: peerName, postAction: postAction)) + finish() + } + + // MARK: - Sending (`SocketStuff.cs:1673-1811`) + + private func beginSending(_ payload: BulkPayload?) { + guard phase == .sending else { return } + guard let payload else { + fail("no clipboard data to send to \(peerName)") + return + } + switch payload { + case .failure(let reason): + send(ClipboardCodec.bulkHeader(byteCount: 0, name: reason), encrypted: true) + finishAfterFlush() + + case .text(let data): + beginBody(name: ClipboardCodec.textStreamName, length: Int64(data.count)) + outboundData = data + + case .image(let data): + beginBody(name: ClipboardCodec.imageStreamName, length: Int64(data.count)) + outboundData = data + + case .file(let url): + guard let size = ReceivedFileSize.of(url), size <= config.maxFileSize, + let handle = try? FileHandle(forReadingFrom: url) + else { + send( + ClipboardCodec.bulkHeader(byteCount: 0, name: "\(url.path) not found!"), + encrypted: true) + finishAfterFlush() + return + } + beginBody(name: url.path, length: size) + outboundFile = handle + } + pumpOutbound() + } + + private func beginBody(name: String, length: Int64) { + send(ClipboardCodec.bulkHeader(byteCount: length, name: name), encrypted: true) + outboundRemaining = length + outboundOffset = 0 + // Without this the CBC stream would hold back the final partial block + // and the peer would never see the last few bytes (§10.7 note 4). + paddingRemaining = ClipboardCodec.trailingPadding(forBodyLength: length) + } + + private func pumpOutbound() { + guard phase == .sending else { return } + if outboundRemaining > 0 { + let wanted = Int(min(outboundRemaining, Int64(BulkChannel.chunkSize))) + guard let chunk = nextOutboundChunk(wanted), !chunk.isEmpty else { + fail("reading the file to send failed") + return + } + outboundRemaining -= Int64(chunk.count) + send(chunk, encrypted: true) { [weak self] in self?.pumpOutbound() } + return + } + if paddingRemaining > 0 { + let padding = Data(repeating: 0, count: paddingRemaining) + paddingRemaining = 0 + send(padding, encrypted: true) { [weak self] in self?.pumpOutbound() } + return + } + finishAfterFlush() + } + + private func nextOutboundChunk(_ wanted: Int) -> Data? { + if let data = outboundData { + // `dropFirst`/`prefix`: `data` may be a slice with a non-zero start + // index, which `subdata(in:)` would read as an absolute range. + let chunk = Data(data.dropFirst(outboundOffset).prefix(wanted)) + guard !chunk.isEmpty else { return nil } + outboundOffset += chunk.count + return chunk + } + guard let file = outboundFile else { return nil } + return try? file.read(upToCount: wanted) + } + + // MARK: - Writing + + private func send(_ bytes: Data, encrypted: Bool, then body: (@Sendable () -> Void)? = nil) { + guard phase != .finished else { return } + let payload: Data + if encrypted { + guard let sealed = try? writer.write(bytes) else { + fail("clipboard stream could not be encrypted") + return + } + payload = sealed + } else { + payload = bytes + } + guard !payload.isEmpty else { + body?() + return + } + connection.send( + content: payload, + completion: .contentProcessed { [weak self] error in + guard let self, self.phase != .finished else { return } + if let error { + self.fail("clipboard write failed: \(error)") + return + } + self.armDeadline() + body?() + }) + } + + /// Closes once everything queued has been written, as `s.Close(10)` does + /// on Windows (`SocketStuff.cs:1716, 1758, 1789`). + private func finishAfterFlush() { + connection.send( + content: nil, contentContext: .finalMessage, isComplete: true, + completion: .contentProcessed { [weak self] _ in + guard let self else { return } + self.queue.async { self.finish() } + }) + } + + // MARK: - Ending + + private func armDeadline() { + deadline?.cancel() + let item = DispatchWorkItem { [weak self] in + self?.cancel("clipboard transfer timed out") + } + deadline = item + queue.asyncAfter(deadline: .now() + BulkChannel.idleTimeout, execute: item) + } + + private func fail(_ reason: String) { + guard phase != .finished else { return } + onEvent(self, .failed(reason)) + finish() + } + + private func finish() { + guard phase != .finished else { return } + phase = .finished + deadline?.cancel() + deadline = nil + try? outboundFile?.close() + outboundFile = nil + outboundData = nil + // An incomplete staging file is deleted, never left behind + // (`ReceivedDestinationFile.Dispose`, `:41-46`). + if case .file(let handle, let url, _) = destination { + try? handle.close() + try? FileManager.default.removeItem(at: url) + } + destination = nil + memory = Data() + inbox = Data() + connection.stateUpdateHandler = nil + connection.cancel() + onEvent(self, .closed) + } +} + +/// The size of a file to send. `MWBNet` may not import `MWBMac`, so this is the +/// one line of `ReceivedFile.size(of:)` the sender needs, kept local. +enum ReceivedFileSize { + static func of(_ url: URL) -> Int64? { + let values = try? url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]) + guard values?.isRegularFile == true, let size = values?.fileSize else { return nil } + return Int64(size) + } +}