control-channel: ChannelConfig, Resolver, PeerConnection, ControlChannel; drop MWBNet placeholder
This commit is contained in:
1 parent
0db3aa8c9a
commit
f6cc824e91
5 files changed
+1279
-9
No files matched your search
@@ -0,0 +1,189 @@
|
||||
// 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:919-929`). `.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
|
||||
/// The peer reports our own machine id (`SocketStuff.cs:1984-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 trusted peer reports our own machine id. The app picks a new one,
|
||||
/// hands it over in a `reconfigure(_:)` and calls `reopenAll()`
|
||||
/// (`SocketStuff.cs:1984-1992`).
|
||||
func channelDetectedIDCollision(_ channel: ControlChannel)
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
// 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<String> = []
|
||||
private var dialDeadline: TimeInterval = 0
|
||||
private var lastUserActivity: TimeInterval = 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:612-616`). 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)
|
||||
config = new
|
||||
if full {
|
||||
reopen()
|
||||
} else {
|
||||
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:912-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 the
|
||||
/// next `Heartbeat` into an `Awake` (`Common.cs:545-552`).
|
||||
public func noteUserActivity() {
|
||||
queue.async { [self] in lastUserActivity = monotonicNow() }
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
private func accept(_ peer: PeerConnection, name: String, id: UInt32) {
|
||||
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, 1998). Inbound connections are always kept.
|
||||
if peer.isOutbound, 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()
|
||||
}
|
||||
|
||||
private func tick() {
|
||||
guard running else { return }
|
||||
let now = monotonicNow()
|
||||
let interval = config.blockScreenSaver ? Session.fastHeartbeat : Session.slowHeartbeat
|
||||
let userActive = lastUserActivity > 0 && now - lastUserActivity <= interval
|
||||
for connection in connections {
|
||||
connection.isControlled = connection.peerID != nil && connection.peerID == controlledPeerID
|
||||
connection.tick(now: now, userActive: userActive)
|
||||
}
|
||||
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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// 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:612-616`).
|
||||
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.
|
||||
func tick(now: TimeInterval, userActive: Bool) {
|
||||
guard !finished, closing == nil else { return }
|
||||
session.tick(now: now, userActive: userActive)
|
||||
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
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import Network
|
||||
|
||||
/// Placeholder so the `MWBNet` target compiles before the `control-channel`
|
||||
/// lane lands. That lane deletes this file (docs/topo.md §1.1).
|
||||
public enum MWBNetPlaceholder {
|
||||
/// The framework this target is allowed to import, named so the layering
|
||||
/// rule (README D2) is visible in the placeholder itself.
|
||||
public static let framework = "Network"
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Name → addresses, the way Windows does it: the user's `Name2IP` mappings
|
||||
// first, then DNS, then the two optional filters (reverse-lookup validation
|
||||
// and the same-subnet check). There is no discovery in this protocol
|
||||
// (`docs/protocol.md` §7).
|
||||
//
|
||||
// Ported from App/Class/SocketStuff.cs StartNewTcpClient (904-1046),
|
||||
// CheckForSameSubNet (1065-1107) and GetMyIPv4Addresses (1109-1127).
|
||||
//
|
||||
// Every call here blocks: `getaddrinfo` talks to the network. The channel
|
||||
// calls it from a resolver queue, never from its own serial queue.
|
||||
|
||||
import Foundation
|
||||
import MWBCore
|
||||
|
||||
/// Turns a machine name into the addresses to dial.
|
||||
public enum Resolver {
|
||||
/// The addresses to try for `name`, in the order Windows tries them:
|
||||
/// the `Name2IP` mappings first, then whatever DNS returns, with
|
||||
/// duplicates removed (`SocketStuff.cs:904-1046`).
|
||||
///
|
||||
/// Returns an empty array when nothing resolves or when the same-subnet
|
||||
/// check rejects the peer, which is Windows returning from
|
||||
/// `ClientThread` without starting a socket (`:1035-1044`).
|
||||
public static func addresses(for name: String, config: ChannelConfig) -> [String] {
|
||||
var found: [String] = []
|
||||
for ip in mappedAddresses(for: name, in: config.name2IP) where !found.contains(ip) {
|
||||
found.append(ip)
|
||||
}
|
||||
|
||||
// Only DNS results go through the reverse-lookup filter: Windows dials
|
||||
// the Name2IP addresses before it ever looks the name up (`:924-941`).
|
||||
var resolved = lookup(name).filter { !found.contains($0) }
|
||||
if config.validateRemoteIP {
|
||||
resolved = resolved.filter { validates(address: $0, as: name) }
|
||||
}
|
||||
found.append(contentsOf: resolved)
|
||||
|
||||
guard !found.isEmpty else { return [] }
|
||||
guard !config.sameSubnetOnly || isSameSubnet(found) else { return [] }
|
||||
return found
|
||||
}
|
||||
|
||||
/// The `Name2IP` addresses mapped to `name`.
|
||||
///
|
||||
/// The setting is CRLF-separated lines of `"<name> <ip>"` split on blanks,
|
||||
/// matched case-insensitively, with anything past the second field ignored
|
||||
/// (`SocketStuff.cs:908-925, 1258-1259`).
|
||||
public static func mappedAddresses(for name: String, in name2IP: String) -> [String] {
|
||||
var out: [String] = []
|
||||
for line in name2IP.components(separatedBy: .newlines) {
|
||||
let fields = line.split(separator: " ", omittingEmptySubsequences: true)
|
||||
guard fields.count >= 2 else { continue }
|
||||
guard
|
||||
fields[0].trimmingCharacters(in: .whitespaces)
|
||||
.caseInsensitiveCompare(name) == .orderedSame
|
||||
else { continue }
|
||||
let ip = fields[1].trimmingCharacters(in: .whitespaces)
|
||||
guard isNumericAddress(ip), !out.contains(ip) else { continue }
|
||||
out.append(ip)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Every IPv4 and IPv6 address DNS has for `name` (`Dns.GetHostEntry`,
|
||||
/// `SocketStuff.cs:950, 976-988`). Empty when the name does not resolve.
|
||||
public static func lookup(_ name: String) -> [String] {
|
||||
var hints = addrinfo()
|
||||
hints.ai_family = AF_UNSPEC
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
hints.ai_protocol = IPPROTO_TCP
|
||||
|
||||
var list: UnsafeMutablePointer<addrinfo>?
|
||||
guard getaddrinfo(name, nil, &hints, &list) == 0, let head = list else { return [] }
|
||||
defer { freeaddrinfo(head) }
|
||||
|
||||
var out: [String] = []
|
||||
var node: UnsafeMutablePointer<addrinfo>? = head
|
||||
while let current = node {
|
||||
let info = current.pointee
|
||||
if let text = presentation(of: info.ai_addr, length: info.ai_addrlen),
|
||||
!out.contains(text)
|
||||
{
|
||||
out.append(text)
|
||||
}
|
||||
node = info.ai_next
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// The name reverse DNS gives `address`, with no domain part stripped.
|
||||
/// `nil` when there is no PTR record (`Dns.GetHostEntry(ip).HostName`,
|
||||
/// `SocketStuff.cs:1002`).
|
||||
public static func reverseName(for address: String) -> String? {
|
||||
withSockaddr(address) { pointer, length in
|
||||
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
guard
|
||||
getnameinfo(
|
||||
pointer, length, &buffer, socklen_t(buffer.count), nil, 0, NI_NAMEREQD) == 0
|
||||
else { return nil }
|
||||
return string(from: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
/// The short name for an address, for labelling an inbound connection
|
||||
/// before its `HandshakeAck` arrives: reverse DNS with the domain part
|
||||
/// removed, falling back to the address itself
|
||||
/// (`GetMachineNameFromSocket`, `SocketStuff.cs:733-762`).
|
||||
public static func shortName(for address: String) -> String {
|
||||
guard let full = reverseName(for: address), !full.isEmpty else { return address }
|
||||
guard let dot = full.firstIndex(of: "."), dot > full.startIndex else { return full }
|
||||
return String(full[full.startIndex..<dot])
|
||||
}
|
||||
|
||||
// MARK: - The two optional filters
|
||||
|
||||
/// Whether reverse DNS agrees that `address` belongs to `name`.
|
||||
///
|
||||
/// Windows accepts the address when the resolved host name *starts with*
|
||||
/// the machine name, case-insensitively — so `mac.example.com` validates
|
||||
/// `mac` — or when it is the address text itself
|
||||
/// (`SocketStuff.cs:1004-1009`). A lookup that fails rejects the address
|
||||
/// (`:1019-1031`).
|
||||
static func validates(address: String, as name: String) -> Bool {
|
||||
guard let host = reverseName(for: address) else { return false }
|
||||
if host.caseInsensitiveCompare(address) == .orderedSame { return true }
|
||||
return host.lowercased().hasPrefix(name.lowercased())
|
||||
}
|
||||
|
||||
/// Whether any of `addresses` is on one of our own IPv4 networks.
|
||||
///
|
||||
/// "Same network" is the first two octets only, and the check passes when
|
||||
/// either side has no IPv4 address at all — Windows only filters when it
|
||||
/// can compare (`SocketStuff.cs:1065-1107`).
|
||||
static func isSameSubnet(_ addresses: [String]) -> Bool {
|
||||
let remote = addresses.compactMap(ipv4Octets)
|
||||
guard !remote.isEmpty else { return true }
|
||||
let local = localIPv4Addresses().compactMap(ipv4Octets)
|
||||
guard !local.isEmpty else { return true }
|
||||
|
||||
for mine in local where remote.contains(where: { $0[0] == mine[0] && $0[1] == mine[1] }) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// This machine's IPv4 addresses on interfaces that are up and not
|
||||
/// loopback (`GetMyIPv4Addresses`, `SocketStuff.cs:1109-1127`).
|
||||
static func localIPv4Addresses() -> [String] {
|
||||
var list: UnsafeMutablePointer<ifaddrs>?
|
||||
guard getifaddrs(&list) == 0, let head = list else { return [] }
|
||||
defer { freeifaddrs(head) }
|
||||
|
||||
var out: [String] = []
|
||||
var node: UnsafeMutablePointer<ifaddrs>? = head
|
||||
while let current = node {
|
||||
let interface = current.pointee
|
||||
node = interface.ifa_next
|
||||
|
||||
let flags = Int32(interface.ifa_flags)
|
||||
guard flags & IFF_UP != 0, flags & IFF_LOOPBACK == 0 else { continue }
|
||||
guard let address = interface.ifa_addr, address.pointee.sa_family == UInt8(AF_INET)
|
||||
else { continue }
|
||||
if let text = presentation(
|
||||
of: address, length: socklen_t(MemoryLayout<sockaddr_in>.size)),
|
||||
!out.contains(text)
|
||||
{
|
||||
out.append(text)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: - Small C helpers, wrapped once
|
||||
|
||||
/// The four octets of a dotted-quad address, or `nil` if it is not IPv4.
|
||||
static func ipv4Octets(_ text: String) -> [UInt8]? {
|
||||
let parts = text.split(separator: ".", omittingEmptySubsequences: false)
|
||||
guard parts.count == 4 else { return nil }
|
||||
var octets: [UInt8] = []
|
||||
for part in parts {
|
||||
guard let value = UInt8(part) else { return nil }
|
||||
octets.append(value)
|
||||
}
|
||||
return octets
|
||||
}
|
||||
|
||||
/// Whether `text` is already a numeric address, so it needs no lookup.
|
||||
static func isNumericAddress(_ text: String) -> Bool {
|
||||
withSockaddr(text) { _, _ in true } ?? false
|
||||
}
|
||||
|
||||
/// Runs `body` with a `sockaddr` parsed from a numeric address string.
|
||||
/// Returns `nil` when the text is not an address.
|
||||
private static func withSockaddr<T>(
|
||||
_ text: String, _ body: (UnsafeMutablePointer<sockaddr>, socklen_t) -> T?
|
||||
) -> T? {
|
||||
var hints = addrinfo()
|
||||
hints.ai_family = AF_UNSPEC
|
||||
hints.ai_socktype = SOCK_STREAM
|
||||
hints.ai_flags = AI_NUMERICHOST
|
||||
|
||||
var list: UnsafeMutablePointer<addrinfo>?
|
||||
guard getaddrinfo(text, nil, &hints, &list) == 0, let head = list else { return nil }
|
||||
defer { freeaddrinfo(head) }
|
||||
guard let address = head.pointee.ai_addr else { return nil }
|
||||
return body(address, head.pointee.ai_addrlen)
|
||||
}
|
||||
|
||||
/// The numeric text of a `sockaddr` (`NI_NUMERICHOST`), including the
|
||||
/// `%interface` suffix IPv6 link-local addresses need.
|
||||
private static func presentation(
|
||||
of address: UnsafeMutablePointer<sockaddr>?, length: socklen_t
|
||||
) -> String? {
|
||||
guard let address else { return nil }
|
||||
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||
guard
|
||||
getnameinfo(address, length, &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST)
|
||||
== 0
|
||||
else { return nil }
|
||||
return string(from: buffer)
|
||||
}
|
||||
|
||||
private static func string(from buffer: [CChar]) -> String? {
|
||||
buffer.withUnsafeBufferPointer { pointer in
|
||||
guard let base = pointer.baseAddress else { return nil }
|
||||
return String(validatingCString: base)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user