Files
mac_without_borders/Sources/MWBNet/ChannelConfig.swift
T
lucioandClaude Opus 5 c4ac584df0 control-channel: CLAUDE.md re-read — citation and doc-comment fixes
Item 4 of the rework brief: re-read the four MWBNet files against
CLAUDE.md. Sizes (189/234/356/524), function lengths, layering, the
one-sentence responsibility test, no force-unwrap/try!/fatalError/
precondition, no logging of any kind and no packet interpretation all
hold; `swift-format format -i` is a no-op on all four. Three citations
were off and are corrected against the source:

- `Common.SendByeBye` is Common.cs:611-615, not 612-616 (ControlChannel,
  PeerConnection).
- `SkSend`'s stamp-and-fan-out is Common.cs:916-930, and the
  `Des == ID.ALL` matrix test is :922-930, not :912-930 / :919-929.

`DisconnectReason.idCollision` and `channelDetectedIDCollision` now say
in their doc comments what the previous commit made true in the code:
the collision is looked for on outbound connections only
(SocketStuff.cs:1980-1992).

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

192 lines
8.2 KiB
Swift

// The vocabulary the control channel shares with the app: what it needs to be
// told to run (`ChannelConfig`), what it reports (`EngineSink`,
// `DisconnectReason`, `PeerStatus`) and who a packet is for (`Destination`).
// Nothing here does I/O or interprets a packet.
//
// Defined before first use, as contracts C4 requires: the channel takes a
// lane-specific config struct and knows nothing about `Settings`, which the
// app-shell lane maps onto this.
import Foundation
import MWBCore
/// Everything the control channel needs from the app to run.
///
/// The app rebuilds one of these and calls `ControlChannel.reconfigure(_:)`
/// when a setting changes; the channel reopens whatever the change invalidated
/// (contracts C4).
public struct ChannelConfig: Sendable, Equatable {
/// This machine's name, as the peers know it (`docs/protocol.md` §1.1).
public var localName: String
/// This machine's id (the `MachineID` setting).
public var localID: UInt32
/// The base TCP port (`TCPPort`, default 15100). The control listener is
/// on `port + 1`; the bulk clipboard listener on `port` belongs to the
/// clipboard lane (`SocketStuff.cs:475-495`).
public var port: UInt16
/// The shared security key. Everything on the wire is derived from it.
public var securityKey: String
/// The four matrix slot names; every non-local, non-empty one gets an
/// outbound client (`SocketStuff.cs:797-837`).
public var matrixNames: [String]
/// The `Name2IP` setting: CRLF-separated `"<name> <ip>"` lines, used in
/// addition to DNS (`SocketStuff.cs:904-946, 1258-1259`).
public var name2IP: String
/// `SameSubnetOnly`: drop a peer whose IPv4 addresses share no first two
/// octets with ours (`SocketStuff.cs:1065-1107`).
public var sameSubnetOnly: Bool
/// `ValidateRemoteMachineIP`: reverse-look-up every resolved address and
/// keep only those that name the peer (`SocketStuff.cs:991-1032`).
public var validateRemoteIP: Bool
/// `BlockScreenSaverOnOtherMachines`, which sets the heartbeat cadence
/// (60 s vs 300 s, `frmScreen.cs:565-570`).
public var blockScreenSaver: Bool
/// The port the control channel listens and dials on: `port + 1`
/// (`SocketStuff.cs:478, 1169`).
public var controlPort: UInt16 { port &+ 1 }
/// A channel configuration.
public init(
localName: String,
localID: UInt32,
port: UInt16 = 15100,
securityKey: String,
matrixNames: [String] = [],
name2IP: String = "",
sameSubnetOnly: Bool = false,
validateRemoteIP: Bool = false,
blockScreenSaver: Bool = true
) {
self.localName = localName
self.localID = localID
self.port = port
self.securityKey = securityKey
self.matrixNames = matrixNames
self.name2IP = name2IP
self.sameSubnetOnly = sameSubnetOnly
self.validateRemoteIP = validateRemoteIP
self.blockScreenSaver = blockScreenSaver
}
/// Whether a change from `other` invalidates every open connection.
///
/// The key changes the cipher stream and the magic number, and the port
/// changes both listener and clients, so either one means a full reopen —
/// Windows writes the same rule as "a key change reopens all sockets"
/// (`docs/protocol.md` §2.4, `Setting.cs:479-511`).
func needsFullReopen(comparedTo other: ChannelConfig) -> Bool {
securityKey != other.securityKey || port != other.port || localName != other.localName
|| localID != other.localID
}
}
/// Who a packet is for.
///
/// `.all` reaches every trusted connection whose peer is in the matrix, which
/// is what `SkSend` does for `Des == ID.ALL` (`Common.cs:922-930`). `.peer`
/// reaches **both** of a peer's connections when it has two; the receiver's
/// replay ring collapses the duplicate, and that is the mechanism, not an
/// accident (contracts C1, `Receiver.cs:40-82`).
public enum Destination: Sendable, Equatable {
/// Every trusted connection to a machine in the matrix.
case all
/// Every connection to one machine id.
case peer(UInt32)
}
/// Why a connection ended.
public enum DisconnectReason: Sendable, Equatable {
/// The peer closed the connection, or we did on the app's request.
case closed
/// A read failed, or six 0-byte reads arrived in a row
/// (`SocketStuff.cs:1334-1364`).
case readError
/// A write failed, did not complete within 500 ms
/// (`SocketStuff.cs:1286`) or overflowed the bounded outbox (contracts C3).
case sendError
/// The peer does not share our security key (`SocketStuff.cs:1387-1410`).
case invalidKey(InvalidKeyReason)
/// More than ten invalid-key outcomes came from this address, so we stop
/// dialling it until `reopenAll()` (`SocketStuff.cs:1482-1499`).
case peerRejected
/// The controlled peer went quiet for 30 s while we were sending it input
/// (contracts C2).
case stall
/// A second outbound connection to a peer we already have; the first one
/// connected wins (`SocketStuff.cs:1421-1428, 1980-1998`).
case duplicateClient
/// The peer is this machine (`SocketStuff.cs:1430-1437`).
case selfConnection
/// A peer we dialled reports our own machine id; Windows checks this on
/// client sockets only (`SocketStuff.cs:1980-1992`).
case idCollision
/// No connection could be made within 30 s (`SocketStuff.cs:158, 1179-1198`).
case timeout
/// Closed by `stop()`, `reopenAll()` or a `reconfigure(_:)` that
/// invalidated the connection.
case forceClosed
}
/// One row of the channel's status table, for the menu bar.
///
/// There is one row per live connection plus one per name the channel is
/// currently resolving or dialling — Windows shows the same thing by adding a
/// placeholder socket while it resolves (`SocketStuff.cs:897-899`).
public struct PeerStatus: Sendable, Equatable {
/// The peer's name: from the matrix while dialling, from the
/// `HandshakeAck` once trusted.
public var name: String
/// The connection's state, in the Windows numbering so the colours match.
public var status: SocketStatus
/// Whether we dialled this connection out.
public var isOutbound: Bool
/// The peer's machine id, known once trusted.
public var peerID: UInt32?
/// The remote address, when there is a socket.
public var address: String?
/// A status row.
public init(
name: String, status: SocketStatus, isOutbound: Bool, peerID: UInt32? = nil,
address: String? = nil
) {
self.name = name
self.status = status
self.isOutbound = isOutbound
self.peerID = peerID
self.address = address
}
}
/// What the channel tells the app.
///
/// Every call is made on the channel's own serial queue, so an implementation
/// must return promptly and hop to its actor rather than block (contracts C3).
/// The channel never interprets a packet: `received` hands over exactly what
/// `Session` delivered, after framing, the trust gate and the replay ring.
public protocol EngineSink: AnyObject, Sendable {
/// A connection changed state; drive the menu-bar colours from this.
func channel(
_ channel: ControlChannel, connectionStatus: SocketStatus, peerName: String?,
isOutbound: Bool)
/// A connection completed its handshake and is trusted.
func channel(_ channel: ControlChannel, connected peerName: String, peerID: UInt32)
/// A trusted, de-duplicated application packet arrived.
func channel(_ channel: ControlChannel, received packet: Packet, from peerID: UInt32)
/// A connection ended. `peerID` and `peerName` are `nil` when it died
/// before the handshake told us who was on the other end.
func channel(
_ channel: ControlChannel, disconnected peerID: UInt32?, peerName: String?,
reason: DisconnectReason)
/// A peer we dialled reports our own machine id. The app picks a new one,
/// hands it over in a `reconfigure(_:)` and calls `reopenAll()`. Like
/// Windows, the channel only looks for this on an outbound connection
/// (`SocketStuff.cs:1980-1992`).
func channelDetectedIDCollision(_ channel: ControlChannel)
}