547 lines
20 KiB
Swift
547 lines
20 KiB
Swift
// 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 }
|
|
// Either way this ends the loop: the handshake is followed by a
|
|
// wait for the Engine's answer, or by failure.
|
|
acceptHandshake(take(packageSizeEx))
|
|
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) {
|
|
// 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
|
|
}
|
|
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) }
|
|
})
|
|
}
|
|
|
|
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*<path> 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)
|
|
// 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)
|
|
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)
|
|
}
|
|
}
|