control-channel: ChannelConfig, Resolver, PeerConnection, ControlChannel; drop MWBNet placeholder
This commit is contained in:
1 parent
0db3aa8c9a
commit
f6cc824e91
5 files changed
+1279
-9
No files matched your search
@@ -0,0 +1,356 @@
|
||||
// One TCP control connection: the cipher header exchange, a read loop that
|
||||
// reads exactly the number of bytes Windows reads, a bounded outbox with a
|
||||
// 500 ms send timeout, and the `Session` that decides what any of it means.
|
||||
//
|
||||
// Ported from App/Class/SocketStuff.cs: the socket options and the opening
|
||||
// handshake (1283-1299), TcpReceiveData's two-phase read (557-610), the I/O
|
||||
// halves of MainTCPRoutine (1261-1330, 1543-1549) and TcpSendData (497-529).
|
||||
//
|
||||
// This file interprets no packet: bytes go to `CipherReader` and then to
|
||||
// `Session`, and what comes back out is whatever `Session` decided.
|
||||
|
||||
import Foundation
|
||||
import MWBCore
|
||||
import Network
|
||||
|
||||
/// One control connection, client or server side.
|
||||
///
|
||||
/// `@unchecked Sendable` because Network.framework's completion handlers are
|
||||
/// `@Sendable` closures: every stored property is read and written only on
|
||||
/// `queue`, a serial queue that targets the channel's own serial queue, so
|
||||
/// exactly one of these methods runs at a time across the whole channel
|
||||
/// (contracts C3).
|
||||
final class PeerConnection: @unchecked Sendable {
|
||||
/// What one connection tells the channel. Delivered on the channel's queue.
|
||||
enum Event {
|
||||
case status(SocketStatus)
|
||||
case connected(peerName: String, peerID: UInt32)
|
||||
case packet(Packet)
|
||||
case closed(DisconnectReason)
|
||||
}
|
||||
|
||||
/// Bytes read at a time once the peer's 48-byte preamble is consumed: one
|
||||
/// Windows `ReadEx(buf, 0, PACKAGE_SIZE)` (`SocketStuff.cs:574`). After
|
||||
/// the preamble the cipher is block-aligned, so 32 bytes of ciphertext are
|
||||
/// exactly 32 bytes of plaintext and a short read means here what it means
|
||||
/// there. `Session` does the 32-then-32 reassembly of a big packet.
|
||||
static let readChunk = packageSize
|
||||
/// Salt, IV and the sacrificial block the peer writes first
|
||||
/// (`docs/protocol.md` §2.3).
|
||||
static let preambleSize = 48
|
||||
/// Framed packets the outbox holds before the connection is closed
|
||||
/// (contracts C3; Windows instead sizes the socket buffer at 320 000
|
||||
/// bytes, `SocketStuff.cs:1283-1284`).
|
||||
static let outboxLimit = 512
|
||||
/// How long one write may take before the connection is considered dead
|
||||
/// (`Socket.SendTimeout = 500`, `SocketStuff.cs:1286`).
|
||||
static let sendTimeout: TimeInterval = 0.5
|
||||
/// Silence tolerated from the machine we are controlling (contracts C2).
|
||||
static let stallTimeout: TimeInterval = 30
|
||||
|
||||
let isOutbound: Bool
|
||||
let remoteAddress: String
|
||||
private(set) var status: SocketStatus = .na
|
||||
private(set) var peerName: String?
|
||||
private(set) var peerID: UInt32?
|
||||
/// Set by the channel from `markControlled(peerID:)`; arms the stall rule.
|
||||
var isControlled = false
|
||||
|
||||
private let connection: NWConnection
|
||||
private let session: Session
|
||||
private let writer: CipherWriter
|
||||
private let reader: CipherReader
|
||||
private let queue: DispatchQueue
|
||||
private let onEvent: (PeerConnection, Event) -> Void
|
||||
|
||||
private var outbox: [Data] = []
|
||||
private var sending = false
|
||||
private var sendDeadline: DispatchWorkItem?
|
||||
private var started = false
|
||||
private var closing: DisconnectReason?
|
||||
private var finished = false
|
||||
private var lastReceive: TimeInterval = 0
|
||||
private var lastForward: TimeInterval = 0
|
||||
|
||||
/// Wraps an `NWConnection` that has not been started yet.
|
||||
///
|
||||
/// Throws only when the cipher stream cannot be built, which means the
|
||||
/// security key could not be turned into a key.
|
||||
init(
|
||||
connection: NWConnection,
|
||||
isOutbound: Bool,
|
||||
remoteAddress: String,
|
||||
peerNameHint: String?,
|
||||
config: ChannelConfig,
|
||||
sequencer: PacketSequencer,
|
||||
replay: ReplayFilter,
|
||||
queue: DispatchQueue,
|
||||
onEvent: @escaping (PeerConnection, Event) -> Void
|
||||
) throws {
|
||||
self.connection = connection
|
||||
self.isOutbound = isOutbound
|
||||
self.remoteAddress = remoteAddress
|
||||
self.queue = queue
|
||||
self.onEvent = onEvent
|
||||
self.peerName = peerNameHint
|
||||
writer = try CipherWriter(securityKey: config.securityKey)
|
||||
reader = CipherReader(securityKey: config.securityKey)
|
||||
session = Session(
|
||||
config: SessionConfig(
|
||||
localName: config.localName,
|
||||
localID: config.localID,
|
||||
magic: MagicHash.magicNumber(for: config.securityKey),
|
||||
blockScreenSaver: config.blockScreenSaver,
|
||||
peerNameHint: peerNameHint),
|
||||
sequencer: sequencer,
|
||||
replay: replay,
|
||||
isClient: isOutbound)
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Starts the connection.
|
||||
///
|
||||
/// `.waiting` counts as a failed attempt rather than something to sit in:
|
||||
/// Windows retries a refused connect on its own one-second cadence
|
||||
/// (`SocketStuff.cs:1176-1198`) and the channel owns that cadence here.
|
||||
func start(now: TimeInterval) {
|
||||
lastReceive = now
|
||||
connection.stateUpdateHandler = { [weak self] state in
|
||||
guard let self else { return }
|
||||
switch state {
|
||||
case .ready:
|
||||
self.becameReady()
|
||||
case .waiting, .failed, .cancelled:
|
||||
self.close(.closed)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
report(isOutbound ? .connecting : .handshaking)
|
||||
connection.start(queue: queue)
|
||||
}
|
||||
|
||||
/// Closes the connection, flushing what is already queued first so the peer
|
||||
/// still gets the ten `Invalid` packets Windows sends before it hangs up
|
||||
/// (`SocketStuff.cs:1394-1400`).
|
||||
func close(_ reason: DisconnectReason) {
|
||||
guard !finished else { return }
|
||||
if closing == nil { closing = reason }
|
||||
if !sending && outbox.isEmpty { finish() }
|
||||
}
|
||||
|
||||
private func finish() {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
sendDeadline?.cancel()
|
||||
sendDeadline = nil
|
||||
connection.stateUpdateHandler = nil
|
||||
connection.cancel()
|
||||
onEvent(self, .closed(closing ?? .closed))
|
||||
}
|
||||
|
||||
private func becameReady() {
|
||||
guard !finished, closing == nil, !started else { return }
|
||||
started = true
|
||||
let now = monotonicNow()
|
||||
lastReceive = now
|
||||
enqueue(writer.header) // 48 bytes in the clear, before anything else
|
||||
session.start(now: now)
|
||||
pump()
|
||||
readPreamble()
|
||||
}
|
||||
|
||||
// MARK: - Reading
|
||||
|
||||
/// The peer's 48-byte preamble, read in one piece so every read after it
|
||||
/// lands on a packet boundary (`docs/protocol.md` §2.3). It yields no
|
||||
/// plaintext: `CipherReader` eats the salt and IV and discards the
|
||||
/// sacrificial block.
|
||||
private func readPreamble() {
|
||||
receiveExactly(PeerConnection.preambleSize) { [weak self] bytes in
|
||||
guard let self else { return }
|
||||
self.consume(bytes)
|
||||
self.readPacket()
|
||||
}
|
||||
}
|
||||
|
||||
private func readPacket() {
|
||||
receiveExactly(PeerConnection.readChunk) { [weak self] bytes in
|
||||
guard let self else { return }
|
||||
self.lastReceive = monotonicNow()
|
||||
self.consume(bytes)
|
||||
guard !self.finished, self.closing == nil else { return }
|
||||
self.readPacket()
|
||||
}
|
||||
}
|
||||
|
||||
/// One read of exactly `count` bytes.
|
||||
///
|
||||
/// A read that returns a different number of bytes is what Windows turns
|
||||
/// into a package of its own — `Error` for 0 bytes, `Invalid` for a short
|
||||
/// count (`SocketStuff.cs:574-578, 588-593`) — and runs through the same
|
||||
/// loop body, so the real count goes to `noteReceiveError(bytesReceived:)`
|
||||
/// unchanged. A read that *fails* builds no package on Windows either: the
|
||||
/// exception lands in `MainTCPRoutine`'s catch, which sets
|
||||
/// `SocketStatus.Error` and closes (`:1543-1549`).
|
||||
private func receiveExactly(_ count: Int, then body: @escaping @Sendable (Data) -> Void) {
|
||||
connection.receive(minimumIncompleteLength: count, maximumLength: count) {
|
||||
[weak self] content, _, _, error in
|
||||
guard let self, !self.finished, self.closing == nil else { return }
|
||||
if error != nil {
|
||||
self.report(.error)
|
||||
self.close(.readError)
|
||||
return
|
||||
}
|
||||
let received = content ?? Data()
|
||||
guard received.count == count else {
|
||||
self.session.noteReceiveError(bytesReceived: received.count)
|
||||
self.pump()
|
||||
self.close(received.isEmpty ? .closed : .readError)
|
||||
return
|
||||
}
|
||||
body(received)
|
||||
}
|
||||
}
|
||||
|
||||
private func consume(_ ciphertext: Data) {
|
||||
guard !ciphertext.isEmpty else { return }
|
||||
do {
|
||||
session.feed(try reader.read(ciphertext))
|
||||
} catch {
|
||||
session.noteReceiveError(bytesReceived: 0)
|
||||
}
|
||||
pump()
|
||||
}
|
||||
|
||||
// MARK: - Writing
|
||||
|
||||
/// Queues an application packet the app has already sequenced (contracts
|
||||
/// C1). `Session.forward` adds `Src` and framing and nothing else.
|
||||
func forward(_ packet: Packet, now: TimeInterval) {
|
||||
guard status == .connected, !finished, closing == nil else { return }
|
||||
lastForward = now
|
||||
session.forward(packet)
|
||||
pump()
|
||||
}
|
||||
|
||||
/// Queues `ByeBye` on the way out (`Common.cs:612-616`).
|
||||
func sayGoodbye() {
|
||||
guard status == .connected, !finished, closing == nil else { return }
|
||||
session.sayGoodbye()
|
||||
pump()
|
||||
}
|
||||
|
||||
/// Reports a socket-level status the session cannot see for itself.
|
||||
func report(_ new: SocketStatus) {
|
||||
session.report(new)
|
||||
pump()
|
||||
}
|
||||
|
||||
/// Drains whatever the session wants written, then whatever it wants said.
|
||||
private func pump() {
|
||||
for framed in session.drain() {
|
||||
do {
|
||||
enqueue(try writer.write(framed))
|
||||
} catch {
|
||||
close(.sendError)
|
||||
return
|
||||
}
|
||||
}
|
||||
for event in session.events() { handle(event) }
|
||||
}
|
||||
|
||||
private func enqueue(_ bytes: Data) {
|
||||
guard !finished else { return }
|
||||
guard outbox.count < PeerConnection.outboxLimit else {
|
||||
close(.sendError) // contracts C3: overflow closes the connection
|
||||
return
|
||||
}
|
||||
outbox.append(bytes)
|
||||
sendNext()
|
||||
}
|
||||
|
||||
private func sendNext() {
|
||||
guard !sending, !finished else { return }
|
||||
guard !outbox.isEmpty else {
|
||||
if closing != nil { finish() }
|
||||
return
|
||||
}
|
||||
let next = outbox.removeFirst()
|
||||
sending = true
|
||||
armSendTimeout()
|
||||
connection.send(
|
||||
content: next,
|
||||
completion: .contentProcessed { [weak self] error in
|
||||
guard let self, !self.finished else { return }
|
||||
self.sendDeadline?.cancel()
|
||||
self.sendDeadline = nil
|
||||
self.sending = false
|
||||
guard error == nil else {
|
||||
self.report(.sendError)
|
||||
self.close(.sendError)
|
||||
return
|
||||
}
|
||||
self.sendNext()
|
||||
})
|
||||
}
|
||||
|
||||
/// A write that has not completed in 500 ms is a dead connection, which is
|
||||
/// what `Socket.SendTimeout` means on Windows (`SocketStuff.cs:1286`).
|
||||
/// Nothing queued behind it is worth waiting for, so this closes at once.
|
||||
private func armSendTimeout() {
|
||||
let deadline = DispatchWorkItem { [weak self] in
|
||||
guard let self, self.sending, !self.finished else { return }
|
||||
self.status = .sendError
|
||||
self.onEvent(self, .status(.sendError))
|
||||
self.outbox.removeAll()
|
||||
self.closing = .sendError
|
||||
self.finish()
|
||||
}
|
||||
sendDeadline = deadline
|
||||
queue.asyncAfter(deadline: .now() + PeerConnection.sendTimeout, execute: deadline)
|
||||
}
|
||||
|
||||
// MARK: - Time
|
||||
|
||||
/// Heartbeats, and the C2 rule that a controlled peer which has gone quiet
|
||||
/// for 30 s while we are feeding it input is gone.
|
||||
func tick(now: TimeInterval, userActive: Bool) {
|
||||
guard !finished, closing == nil else { return }
|
||||
session.tick(now: now, userActive: userActive)
|
||||
pump()
|
||||
|
||||
guard status == .connected, isControlled, lastForward > lastReceive else { return }
|
||||
if now - lastReceive > PeerConnection.stallTimeout { close(.stall) }
|
||||
}
|
||||
|
||||
// MARK: - Session events
|
||||
|
||||
private func handle(_ event: SessionEvent) {
|
||||
switch event {
|
||||
case .status(let new):
|
||||
status = new
|
||||
if new == .error && closing == nil { closing = .readError }
|
||||
onEvent(self, .status(new))
|
||||
case .connected(let name, let id):
|
||||
peerName = name
|
||||
peerID = id
|
||||
onEvent(self, .connected(peerName: name, peerID: id))
|
||||
case .packet(let packet):
|
||||
onEvent(self, .packet(packet))
|
||||
case .invalidKey(let reason):
|
||||
closing = .invalidKey(reason)
|
||||
case .selfConnection:
|
||||
closing = .selfConnection
|
||||
case .close:
|
||||
close(closing ?? .closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds from a clock that does not jump when the wall clock is corrected.
|
||||
/// Windows measures every interval in this protocol with `GetTick()`.
|
||||
func monotonicNow() -> TimeInterval {
|
||||
TimeInterval(DispatchTime.now().uptimeNanoseconds) / 1_000_000_000
|
||||
}
|
||||
Reference in new issue
Block a user