control-channel
Goal
The sockets. MWBNet turns Session + CipherWriter/CipherReader
into live TCP connections on port+1 (docs/protocol.md §3.1, §3.3, §7):
an NWListener for inbound peers, one outbound NWConnection per
non-local matrix name with the Windows retry cadence, name resolution
with Name2IP, the keep-one-client-per-peer rule, reconnect triggers,
and the bounded queues and stall detection that contracts C2/C3
require. It reports SessionEvents and connection lifecycle to an
EngineSink protocol; the Engine itself arrives in the app-shell lane.
No packet is interpreted here.
Assumptions
- Network.framework only (
NWListener,NWConnection,NWPathMonitor,NWEndpoint); no BSD sockets exceptgetaddrinfoinsideResolverfor theName2IP-free path, becauseNWConnection(host:port:)already resolves names — prefer it and usegetaddrinfoonly for the reverse-lookup validation option. - Two listeners are the protocol's shape (
SocketStuff.cs:475-495): this lane opens the control listener onport + 1only; the clipboard listener onportis the clipboard lane's. - Per connection: one
PeerConnectionowningNWConnection,Session,CipherWriter,CipherReader, one serialDispatchQueue, a bounded outbound queue (512 framed packets) and a 500 ms send timeout (SocketStuff.cs:1286). The first bytes written areCipherWriter.header(48 bytes); the first bytes read go intoCipherReader, whose output feedsSession.feed. A read that returns fewer than 32 bytes at EOF or errors callsSession.noteReceiveError(bytesReceived:)with the real count (contracts, session-matrix Review). - Outbound clients: for every matrix name that is not the local
name and has no connected client, dial
name:port+1; retry every 1 s until 30 s have passed (SocketStuff.cs:158, 276, 1179-1198), then report.timeoutand wait for the next reconnect trigger. Socket options mirror Windows:NoDelay, 320 000-byte buffers where Network.framework exposes them (SocketStuff.cs:1283-1286). - Keep one client per peer (
SocketStuff.cs:1980-2004): when a second connection to the same peer name reaches.connected, the later client connection is closed; inbound (server-side) connections are always kept. The channel therefore ends with at most one outbound and one inbound connection per peer, and forwards every app packet to both — the receiver's replay ring collapses the pair (contracts C1). - Machine-id collision (
SocketStuff.cs:1984-1992): if a trusted peer reports our own id, the channel reports.idCollisionto the sink; the app regenerates and callsreopenAll(). - Failure budget per endpoint (
SocketStuff.cs:1482-1499): more than 10.invalidKeyoutcomes from the same remote address ⇒ report.peerRejected(address)and stop dialling it untilreopenAll(). - Reconnect triggers (§3.3):
NWPathMonitorstatus change, an explicitreopenAll()(the app calls it on wake, display change and the reconnect hotkey), a connection reset, and the settings change of key/port/matrix (the app callsreconfigure(_:)). - Ticks: the channel runs one 100 ms
DispatchSourceTimerthat callsSession.tick(now:userActive:)on every connection (the app reportsuserActivevianoteUserActivity()), drains outboxes and events, and detects the C2 "30 s silence while we are sending input" stall: if the connection the sink marked ascontrolledreceives nothing for 30 s while packets are being forwarded to it, close it. ChannelConfig(contracts C4) carries everything: local name, local id, port, security key, matrix names,Name2IPtext,sameSubnetOnly,validateRemoteIP,blockScreenSaver.- Threading: all mutation of channel state happens on one private
serial queue;
EngineSinkcalls are made from that queue and the sink is expected to hop to its actor.PeerConnectionis notSendable; it never escapes the channel's queue.
Handshakes
Consumed
wire-core:CipherWriter,CipherReader,MagicHash.session-matrix:Session,SessionConfig,SessionEvent,SocketStatus,PacketSequencer,ReplayFilter,Packet.
Promised (to app-shell, clipboard)
public struct ChannelConfig: Sendable { localName, localID, port: UInt16, securityKey, matrixNames: [String], name2IP: String, sameSubnetOnly, validateRemoteIP, blockScreenSaver }
public protocol EngineSink: AnyObject, Sendable {
func channel(_ c: ControlChannel, connectionStatus: SocketStatus, peerName: String?, isOutbound: Bool)
func channel(_ c: ControlChannel, connected peerName: String, peerID: UInt32)
func channel(_ c: ControlChannel, received packet: Packet, from peerID: UInt32)
func channel(_ c: ControlChannel, disconnected peerID: UInt32, reason: DisconnectReason) // includes invalidKey, stall, reset, byeBye, closed
func channelDetectedIDCollision(_ c: ControlChannel)
}
public final class ControlChannel {
public init(config: ChannelConfig, sequencer: PacketSequencer, replay: ReplayFilter, sink: EngineSink)
public func start(); public func stop()
public func reconfigure(_ config: ChannelConfig) // reopens what changed
public func reopenAll()
public func forward(_ packet: Packet, to: Destination) // .all | .peer(UInt32); packet already sequenced (C1)
public func noteUserActivity()
public func markControlled(peerID: UInt32?) // for the 30 s stall rule
public var statuses: [PeerStatus] // name, status, isOutbound — for the menu bar
}
public enum Resolver { static func addresses(for name: String, config: ChannelConfig) -> [String] } // Name2IP first, then DNS
Status / TODO
Sources/MWBNet/ChannelConfig.swift: config,EngineSink,DisconnectReason,PeerStatus,Destination.Sources/MWBNet/PeerConnection.swift: one connection — cipher header exchange, read loop with 32/64 framing left toSession, bounded outbox, 500 ms send timeout, stall detection, close (SocketStuff.cs:1261-1565I/O side,:1283-1286).Sources/MWBNet/Resolver.swift:Name2IPparsing (SocketStuff.cs:904-946, 1258-1259), same-/16 check (:1065-1107), reverse validation (:991-1032).Sources/MWBNet/ControlChannel.swift: listener, dial loop with retry (:797-837, 1169-1198), one-client-per-peer (:1980-2004), id collision (:1984-1992), per-endpoint failure budget (:1482-1499),NWPathMonitor+reopenAll(§3.3), 100 ms tick.- Delete
Sources/MWBNet/Placeholder.swift. docs/protocol.md: append §10.3 with anything learned, cited.