Listener and dials ported from SocketStuff.cs:475-495, 1566-1666 and Clipboard.cs:401-485, 1068-1099; the transfer from Clipboard.ShakeHand (961-1066), ReceiveAndProcessClipboardDataCore (498-923) and SocketStuff.SendClipboardData/SendFileEx/SendData (1673-1931). The 64-byte DATA on this connection is raw, not framed (docs/protocol.md §10.7 (a)): bytes 1..3 must be zero and are checked. Verified on loopback in the scratchpad: pull of text, push of a file, a 3 MB image across chunks, and an unauthorised peer refused. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
296 lines
11 KiB
Swift
296 lines
11 KiB
Swift
// The bulk channel: the listener on the TCP port itself (15100, not port + 1)
|
|
// that big clipboard payloads and files travel over, and the outbound dials
|
|
// that pull from a peer or push to one.
|
|
//
|
|
// Ported from App/Class/SocketStuff.cs CreateSocket (475-495),
|
|
// AcceptConnectionAndSendClipboardData (1566-1600) and SendOrReceiveClipboardData
|
|
// (1602-1666); App/Core/Clipboard.cs ConnectToRemoteClipboardSocket (1068-1099),
|
|
// ConnectAndGetData (401-485) and the ClipboardAsk answer in
|
|
// App/Core/Receiver.cs (315-344).
|
|
//
|
|
// This file owns sockets and lifetimes; `BulkConnection` owns one transfer.
|
|
// Neither interprets a clipboard payload beyond the 1024-byte header.
|
|
|
|
import Foundation
|
|
import MWBCore
|
|
import Network
|
|
|
|
/// Everything the bulk channel needs from the app's settings (contracts C4).
|
|
public struct BulkConfig: Sendable, Equatable {
|
|
/// This Mac's name on the wire; goes in the handshake packet.
|
|
public var localName: String
|
|
/// This Mac's machine id.
|
|
public var localID: UInt32
|
|
/// `TCPPort` itself — the bulk listener, unlike the control channel, does
|
|
/// not add one (`SocketStuff.cs:475-479`).
|
|
public var port: UInt16
|
|
/// The shared secret both cipher streams are derived from.
|
|
public var securityKey: String
|
|
/// Where a received file is streamed while it is incomplete. The commit is
|
|
/// a rename inside this same directory, so it must be the download folder.
|
|
public var stagingDirectory: URL
|
|
/// Refuse a transfer that announces more than this many bytes
|
|
/// (`Clipboard.cs:44`).
|
|
public var maxFileSize: Int64
|
|
|
|
/// A configuration with the Windows limits.
|
|
public init(
|
|
localName: String, localID: UInt32, port: UInt16, securityKey: String,
|
|
stagingDirectory: URL, maxFileSize: Int64 = ClipboardCodec.maxFileSize
|
|
) {
|
|
self.localName = localName
|
|
self.localID = localID
|
|
self.port = port
|
|
self.securityKey = securityKey
|
|
self.stagingDirectory = stagingDirectory
|
|
self.maxFileSize = maxFileSize
|
|
}
|
|
}
|
|
|
|
/// What this machine offers a peer that pulls from it
|
|
/// (`SocketStuff.SendClipboardData`, `:1673-1811`).
|
|
public enum BulkPayload: Sendable, Equatable {
|
|
/// A raw-DEFLATE text blob; announced as `text`.
|
|
case text(Data)
|
|
/// PNG bytes; announced as `image`.
|
|
case image(Data)
|
|
/// A file on disk; announced by its full path.
|
|
case file(URL)
|
|
/// Nothing sendable, only a message: `"0*<reason>"`, 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 }
|
|
}
|
|
}
|
|
}
|