// The control channel: one listener on port + 1, one outbound client per // non-local matrix name, and the policies that are keyed by endpoint rather // than by connection โ€” keep one client per peer, the per-address failure // budget, the machine-id collision, the reconnect triggers and the 100 ms tick. // // Ported from App/Class/SocketStuff.cs: CreateSocket (475-495), TCPServerThread // and AddSocket (681-770), UpdateTCPClients (797-837), StartNewTcpClientThread's // retry loop (1130-1198), the duplicate-client and id-collision rules in // UpdateTcpSockets (1964-2004) and the per-endpoint failure budget (1482-1499); // App/Core/InitAndCleanup.cs reopen triggers (28-31, 137-139, 246-290) and // App/Form/frmScreen.cs the reopen countdown (427-461). // // No packet is interpreted here. import Foundation import MWBCore import Network import os /// The TCP side of the protocol: listener, clients, and the lifecycle the app /// needs to see. /// /// `@unchecked Sendable` because Network.framework hands its results to /// `@Sendable` closures: all mutable state is touched only on `queue`, one /// private serial queue that every connection's own queue targets, so the /// queue is the lock (contracts C3). public final class ControlChannel: @unchecked Sendable { /// How long the channel keeps dialling a name before it gives up and waits /// for a reconnect trigger: `CONNECT_TIMEOUT / 2`, measured from the moment /// the sockets were opened (`SocketStuff.cs:158, 276, 1179-1198`). public static let connectTimeout: TimeInterval = 30 /// The gap between dial attempts (`Thread.Sleep(1000)`, `SocketStuff.cs:1186`). public static let retryInterval: TimeInterval = 1 /// The tick that drives heartbeats and the stall rule โ€” the same 100 ms /// timer Windows runs its whole liveness logic on (`frmScreen.cs:285-288`). public static let tickInterval: TimeInterval = 0.1 /// Invalid-key outcomes tolerated from one address before the channel stops /// dialling it until `reopenAll()` (`SocketStuff.cs:1487-1497`, where /// Windows quits the app instead). public static let endpointFailureLimit = 10 private let queue = DispatchQueue(label: "mwb.control-channel") private let resolverQueue = DispatchQueue( label: "mwb.control-channel.resolver", attributes: .concurrent) private let sequencer: PacketSequencer private let replay: ReplayFilter private let sink: EngineSink private let statusStore = OSAllocatedUnfairLock(initialState: [PeerStatus]()) private var config: ChannelConfig private var listener: NWListener? private var monitor: NWPathMonitor? private var timer: DispatchSourceTimer? private var connections: [PeerConnection] = [] private var dialers: [String: Dialer] = [:] private var failures: [String: Int] = [:] private var blocked: Set = [] private var dialDeadline: TimeInterval = 0 private var inputEventCount: UInt64 = 0 private var controlledPeerID: UInt32? private var lastPathStatus: NWPath.Status? private var connectionCount = 0 private var running = false /// What the channel is doing about one matrix name it has no client for. private struct Dialer { var status: SocketStatus = .na var resolving = false var inFlight = 0 var retryAt: TimeInterval = 0 var stopped = false } /// A channel that is not running yet. `sequencer` and `replay` are the /// process-wide pair the Engine owns (contracts C1). public init( config: ChannelConfig, sequencer: PacketSequencer, replay: ReplayFilter, sink: EngineSink ) { self.config = config self.sequencer = sequencer self.replay = replay self.sink = sink } // MARK: - Lifecycle /// Opens the listener, starts watching the network path and starts the /// 100 ms tick. public func start() { queue.async { [self] in guard !running else { return } running = true dialDeadline = monotonicNow() + ControlChannel.connectTimeout openListener() startMonitor() startTimer() updateClients(now: monotonicNow()) } } /// Closes everything. The channel can be started again afterwards. public func stop() { queue.async { [self] in running = false timer?.cancel() timer = nil monitor?.cancel() monitor = nil lastPathStatus = nil closeListener() closeAll(.forceClosed) dialers.removeAll() publishStatuses() } } /// Queues `ByeBye` on every trusted connection (`Common.cs:611-615`). Call /// it before `stop()` on a clean exit. public func sayGoodbye() { queue.async { [self] in for connection in connections { connection.sayGoodbye() } } } /// Applies new settings, reopening whatever the change invalidated: the key, /// the port, the local name or the local id mean everything reopens /// (`docs/protocol.md` ยง2.4); a matrix change only starts or stops clients. public func reconfigure(_ new: ChannelConfig) { queue.async { [self] in let full = new.needsFullReopen(comparedTo: config) let matrixChanged = new.matrixNames != config.matrixNames config = new guard !full else { reopen() return } if matrixChanged { // Editing the matrix is a reconnect trigger: a name added after // the connect budget expired must get its own 30 s to answer. dialers.removeAll() dialDeadline = monotonicNow() + ControlChannel.connectTimeout } updateClients(now: monotonicNow()) } } /// Closes everything and starts over: the reconnect hotkey, wake, a display /// change, a network change or an id collision all land here /// (`InitAndCleanup.cs:28-31`, `frmScreen.cs:427-461`). public func reopenAll() { queue.async { [self] in reopen() } } private func reopen() { guard running else { return } closeListener() closeAll(.forceClosed) dialers.removeAll() failures.removeAll() blocked.removeAll() dialDeadline = monotonicNow() + ControlChannel.connectTimeout openListener() updateClients(now: monotonicNow()) publishStatuses() } // MARK: - What the app asks of the channel /// Sends a packet the app has **already** sequenced (contracts C1). /// /// `.all` goes to every trusted connection whose peer is in the matrix, and /// `.peer` to both of a peer's connections when it has two โ€” the same /// bytes, the same `Id`, exactly as `SkSend` fans one packet out over many /// sockets (`Common.cs:916-930`). public func forward(_ packet: Packet, to destination: Destination) { queue.async { [self] in let now = monotonicNow() for connection in connections where connection.status == .connected { guard matches(connection, destination) else { continue } connection.forward(packet, now: now) } } } private func matches(_ connection: PeerConnection, _ destination: Destination) -> Bool { switch destination { case .all: guard let name = connection.peerName else { return false } return inMatrix(name) case .peer(let id): return connection.peerID == id } } /// Tells the channel the user just did something, which is what turns a /// connection's next `Heartbeat` into an `Awake` (`Common.cs:545-559`). /// /// This is exactly our `Event.RealInputEventCount++` (`Event.cs:51-55`, /// `InputHook.cs:223, 345`) and nothing more: the channel only counts, and /// each `Session` decides `Awake` against the count it saw at its own /// previous beat. public func noteUserActivity() { queue.async { [self] in inputEventCount &+= 1 } } /// Names the peer currently receiving our input, or `nil` when control is /// local. Only that connection is subject to the 30 s stall rule (C2). public func markControlled(peerID: UInt32?) { queue.async { [self] in controlledPeerID = peerID } } /// The status table for the menu bar. Safe to read from any thread. public var statuses: [PeerStatus] { statusStore.withLock { $0 } } // MARK: - Listener private func openListener() { guard listener == nil, let port = NWEndpoint.Port(rawValue: config.controlPort) else { return } do { let new = try NWListener(using: ControlChannel.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 } } private func closeListener() { listener?.newConnectionHandler = nil listener?.stateUpdateHandler = nil listener?.cancel() listener = nil } /// Windows names an inbound peer by reverse DNS and lets the `HandshakeAck` /// override it (`SocketStuff.cs:733-762, 1412-1419`). Reverse DNS blocks, so /// the hint here is the address; the ack still supplies the real name. private func accept(_ connection: NWConnection) { let address = ControlChannel.addressText(of: connection.endpoint) add(connection, isOutbound: false, address: address, nameHint: address) } /// TCP with `NoDelay`, as Windows sets on every socket /// (`SocketStuff.cs:1285`). Network.framework exposes no socket buffer /// size, so the 320 000-byte buffers (`:1283-1284`) have no equivalent; the /// bounded outbox in `PeerConnection` is what limits queued bytes here. 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: - Clients /// Starts a client for every non-local matrix name that has no connected /// client (`UpdateTCPClients`, `SocketStuff.cs:797-837`). private func updateClients(now: TimeInterval) { guard running else { return } for raw in config.matrixNames { let name = raw.trimmingCharacters(in: .whitespaces) guard !name.isEmpty, name.caseInsensitiveCompare(config.localName) != .orderedSame else { continue } if hasConnectedClient(to: name) { dialers[name] = nil continue } var dialer = dialers[name] ?? Dialer() guard !dialer.stopped, !dialer.resolving, dialer.inFlight == 0, now >= dialer.retryAt else { continue } guard now < dialDeadline else { dialer.stopped = true dialer.status = .timeout dialers[name] = dialer report(name: name, status: .timeout, isOutbound: true) continue } dialer.resolving = true dialer.status = .resolving dialers[name] = dialer report(name: name, status: .resolving, isOutbound: true) resolve(name) } } /// Name resolution blocks, so it never runs on the channel queue. private func resolve(_ name: String) { let snapshot = config resolverQueue.async { [weak self] in let addresses = Resolver.addresses(for: name, config: snapshot) guard let self else { return } self.queue.async { self.dial(name, to: addresses) } } } private func dial(_ name: String, to addresses: [String]) { var dialer = dialers[name] ?? Dialer() dialer.resolving = false let usable = addresses.filter { !blocked.contains($0) } guard running, !usable.isEmpty else { dialer.status = .timeout dialer.retryAt = monotonicNow() + ControlChannel.retryInterval dialers[name] = dialer report(name: name, status: .timeout, isOutbound: true) return } dialer.status = .connecting dialer.inFlight = usable.count dialers[name] = dialer guard let port = NWEndpoint.Port(rawValue: config.controlPort) else { return } for address in usable { let endpoint = NWEndpoint.Host(address) let connection = NWConnection(host: endpoint, port: port, using: ControlChannel.parameters()) add(connection, isOutbound: true, address: address, nameHint: name) } } private func add( _ connection: NWConnection, isOutbound: Bool, address: String, nameHint: String? ) { connectionCount += 1 let peerQueue = DispatchQueue(label: "mwb.peer.\(connectionCount)", target: queue) do { let peer = try PeerConnection( connection: connection, isOutbound: isOutbound, remoteAddress: address, peerNameHint: nameHint, config: config, sequencer: sequencer, replay: replay, queue: peerQueue, onEvent: { [weak self] peer, event in self?.handle(peer, event) }) connections.append(peer) peer.start(now: monotonicNow()) publishStatuses() } catch { connection.cancel() if isOutbound { noteDialFailed(nameHint) } } } // MARK: - Connection events private func handle(_ peer: PeerConnection, _ event: PeerConnection.Event) { switch event { case .status(let status): sink.channel(self, connectionStatus: status, peerName: peer.peerName, isOutbound: peer.isOutbound) publishStatuses() case .connected(let name, let id): accept(peer, name: name, id: id) case .packet(let packet): guard let id = peer.peerID else { return } sink.channel(self, received: packet, from: id) case .closed(let reason): closed(peer, reason) } } /// The handshake completed. Two policies apply only here, because both are /// keyed by things a single connection cannot see (`SocketStuff.cs:1964-2004`). /// /// Both are client-only: `UpdateTcpSockets` runs the whole /// collision-and-dedup block under `status == SocketStatus.Connected && /// tcp.IsClient` (`:1980-1981`), so neither the id check (`:1984-1992`) nor /// the keep-the-first-client rule (`:1993-1997`) ever sees a /// server-accepted socket. private func accept(_ peer: PeerConnection, name: String, id: UInt32) { if peer.isOutbound { if id == config.localID { // SocketStuff.cs:1984-1992 sink.channelDetectedIDCollision(self) closeAll(.idCollision) return } // Keep the first client that connected; a later one is redundant // (SocketStuff.cs:1421-1428, 1996-2004). if hasConnectedClient(to: name, excluding: peer) { peer.close(.duplicateClient) return } } dialers[name] = nil sink.channel(self, connected: name, peerID: id) publishStatuses() } private func closed(_ peer: PeerConnection, _ reason: DisconnectReason) { connections.removeAll { $0 === peer } var outcome = reason if case .invalidKey = reason, spendFailureBudget(for: peer.remoteAddress) { outcome = .peerRejected } if peer.isOutbound, peer.peerID == nil { noteDialFailed(peer.peerName) } sink.channel(self, disconnected: peer.peerID, peerName: peer.peerName, reason: outcome) publishStatuses() } /// More than ten invalid-key outcomes from one address and we stop dialling /// it until `reopenAll()`. Windows counts only the mismatched-ack branch and /// quits the whole app on the eleventh (`SocketStuff.cs:1487-1497`); we /// count every invalid-key outcome and only give up on that address, which /// keeps the other peers working. private func spendFailureBudget(for address: String) -> Bool { let count = (failures[address] ?? 0) + 1 failures[address] = count guard count > ControlChannel.endpointFailureLimit else { return false } blocked.insert(address) return true } private func noteDialFailed(_ name: String?) { guard let name, var dialer = dialers[name] else { return } dialer.inFlight = max(0, dialer.inFlight - 1) guard dialer.inFlight == 0 else { dialers[name] = dialer return } let now = monotonicNow() if now >= dialDeadline { dialer.stopped = true dialer.status = .timeout report(name: name, status: .timeout, isOutbound: true) } else { dialer.retryAt = now + ControlChannel.retryInterval dialer.status = .connecting } dialers[name] = dialer } // MARK: - The 100 ms tick private func startTimer() { let source = DispatchSource.makeTimerSource(queue: queue) source.schedule( deadline: .now() + ControlChannel.tickInterval, repeating: ControlChannel.tickInterval) source.setEventHandler { [weak self] in self?.tick() } timer = source source.resume() } /// The tick hands every connection the raw real-input counter and decides /// nothing about it. `SendAwakeBeat`'s `lastRealInputEventCount != /// Event.RealInputEventCount` test is a comparison against the counter *as of /// the previous beat*, and the beat is the send (`Common.cs:545-559`, /// `frmScreen.cs:565-575`), so the comparison belongs where the send is /// scheduled: inside each `Session`, which owns its own heartbeat instant. /// A boundary kept here instead would be out of phase with every connection's /// own beat and could swallow the input a peer needs to stay awake. private func tick() { guard running else { return } let now = monotonicNow() let count = inputEventCount for connection in connections { connection.isControlled = connection.peerID != nil && connection.peerID == controlledPeerID connection.tick(now: now, inputEventCount: count) } updateClients(now: now) } private func startMonitor() { let path = NWPathMonitor() path.pathUpdateHandler = { [weak self] update in self?.pathChanged(update.status) } monitor = path path.start(queue: queue) } /// A network change reopens everything, which is what Windows schedules /// from `NetworkAvailabilityChanged` (`InitAndCleanup.cs:246-290`). The /// first update is the current state, not a change. private func pathChanged(_ status: NWPath.Status) { defer { lastPathStatus = status } guard let previous = lastPathStatus, previous != status, running else { return } reopen() } // MARK: - Small queries private func inMatrix(_ name: String) -> Bool { config.matrixNames.contains { $0.trimmingCharacters(in: .whitespaces).caseInsensitiveCompare(name) == .orderedSame } } private func hasConnectedClient(to name: String, excluding peer: PeerConnection? = nil) -> Bool { connections.contains { candidate in candidate !== peer && candidate.isOutbound && candidate.status == .connected && candidate.peerName?.caseInsensitiveCompare(name) == .orderedSame } } private func closeAll(_ reason: DisconnectReason) { for connection in connections { connection.close(reason) } } private func report(name: String, status: SocketStatus, isOutbound: Bool) { sink.channel(self, connectionStatus: status, peerName: name, isOutbound: isOutbound) publishStatuses() } private func publishStatuses() { var rows = connections.map { PeerStatus( name: $0.peerName ?? $0.remoteAddress, status: $0.status, isOutbound: $0.isOutbound, peerID: $0.peerID, address: $0.remoteAddress) } for (name, dialer) in dialers where dialer.status != .na { rows.append(PeerStatus(name: name, status: dialer.status, isOutbound: true)) } let published = rows statusStore.withLock { $0 = published } } private static func addressText(of endpoint: NWEndpoint) -> String { guard case .hostPort(let host, _) = endpoint else { return "\(endpoint)" } switch host { case .ipv4(let address): return "\(address)" case .ipv6(let address): return "\(address)" case .name(let name, _): return name @unknown default: return "\(host)" } } }