// 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 /// Raw bytes the scheme-mismatch diagnostic needs before it can replay the /// peer's opening under the other scheme: the longest preamble either /// scheme has (`.modern`'s 48) plus one packet (`docs/protocol.md` §2.5). static let diagnosticBytes = CipherScheme.modern.preambleSize + packageSize /// 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 /// Kept for the scheme-mismatch diagnostic only, which needs to redo the /// peer's opening bytes under the other scheme and re-check their framing. private let securityKey: String private let cipherScheme: CipherScheme private let magic: UInt32 private var probe: SchemeProbe? = SchemeProbe() 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 securityKey = config.securityKey cipherScheme = config.cipherScheme magic = MagicHash.magicNumber(for: config.securityKey) writer = try CipherWriter(securityKey: config.securityKey, scheme: config.cipherScheme) reader = CipherReader(securityKey: config.securityKey, scheme: config.cipherScheme) session = Session( config: SessionConfig( localName: config.localName, localID: config.localID, magic: magic, 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 // The scheme's preamble, before anything else: 48 bytes under // `.modern` (salt, IV, sacrificial block), 16 under `.legacy`. enqueue(writer.header) session.start(now: now) pump() readPreamble() } // MARK: - Reading /// The peer's preamble, read in one piece so every read after it lands on a /// packet boundary (`docs/protocol.md` §2.3, §2.5): 48 bytes under /// `.modern`, 16 under `.legacy`. It yields no plaintext — `CipherReader` /// eats the salt and IV, if the scheme has them, and discards the /// sacrificial block. private func readPreamble() { receiveExactly(cipherScheme.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 { let plaintext = try reader.read(ciphertext) if noteForDiagnostic(ciphertext: ciphertext, plaintext: plaintext) { closing = .invalidKey(.cipherSchemeMismatch) report(.cipherSchemeMismatch) close(.invalidKey(.cipherSchemeMismatch)) return } session.feed(plaintext) } catch { session.noteReceiveError(bytesReceived: 0) } pump() } // MARK: - The scheme-mismatch diagnostic (`docs/protocol.md` §2.5) /// The peer's opening bytes, kept only until one packet has been framed. /// /// There is no negotiation in this protocol and no MAC, so a peer running /// the other vintage of PowerToys looks exactly like a peer with the wrong /// key: garbage plaintext, failed framing. Replaying the same bytes under /// the other scheme is the only way to tell the two apart, and it is worth /// one AES setup on a connection that was going to fail anyway. private struct SchemeProbe { var raw = Data() var plaintext = Data() } /// Feeds the probe and answers whether the peer is speaking the other /// scheme. Nothing here acts on the bytes: a `true` only closes the /// connection with a reason the menu can explain (CLAUDE.md invariant 2). private func noteForDiagnostic(ciphertext: Data, plaintext: Data) -> Bool { guard probe != nil else { return false } probe?.raw.append(ciphertext) probe?.plaintext.append(plaintext) guard let probe, probe.plaintext.count >= packageSize else { return false } // One packet that frames is all it takes to prove the scheme is right. guard framingFails(probe.plaintext) else { self.probe = nil return false } // Wait for enough raw bytes to cover the other scheme's preamble too; // meanwhile the garbage keeps spending the session's untrusted budget, // exactly as it would without this diagnostic. guard probe.raw.count >= PeerConnection.diagnosticBytes else { return false } self.probe = nil return framesUnderOtherScheme(probe.raw) } private func framingFails(_ plaintext: Data) -> Bool { Framing.open(Data(plaintext.prefix(packageSize)), magic: magic).type == .invalid } private func framesUnderOtherScheme(_ raw: Data) -> Bool { let other = CipherReader(securityKey: securityKey, scheme: cipherScheme.other) guard let plaintext = try? other.read(raw), plaintext.count >= packageSize else { return false } return !framingFails(plaintext) } // 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 }