Files
mac_without_borders/Sources/MWBNet/PeerConnection.swift
T
lucioandClaude Opus 5 c03b8cdbcf control-channel: the Awake test moves into Session, where the beat is
Round-2 QA finding: the channel reset beatInputEventCount on its own
clock, out of phase with every connection's heartbeat instant, so a
session could send Heartbeat (20) where Windows sends Awake (21) — and
Awake is what drives the peer's Common.HumanBeingDetected()
(Receiver.cs:245-248), the default-on BlockScreenSaver mechanism.

Windows's beat is the send: SendAwakeBeat() compares
lastRealInputEventCount against Event.RealInputEventCount and re-records
it in the same call (Common.cs:542-559). So the comparison belongs at the
send. Session.tick(now:userActive:) becomes
Session.tick(now:inputEventCount:), taking the raw process-wide counter
(Event.cs:51-55, InputHook.cs:223, 345) and keeping its own
beatInputEventCount — Common.lastRealInputEventCount, Common.cs:543 —
recorded on both branches (:558).

ControlChannel loses lastBeatAt and beatInputEventCount entirely;
noteUserActivity() only increments the counter and tick() hands the same
value to every connection. No userActive-shaped name is left in Sources.

Sources/MWBCore/Session.swift is session-matrix's file, edited for this
fix with the lead's authorisation, as is that lane's Handshakes section.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 01:57:03 -07:00

358 lines
13 KiB
Swift

// 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:611-615`).
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. `inputEventCount` is the
/// channel's raw real-input counter, passed straight through to the session.
func tick(now: TimeInterval, inputEventCount: UInt64) {
guard !finished, closing == nil else { return }
session.tick(now: now, inputEventCount: inputEventCount)
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
}