Files
mac_without_borders/Sources/MWBCore/Session.swift
T

387 lines
15 KiB
Swift

// One TCP control connection's protocol state: the handshake that decides
// whether the peer knows the security key, the trust gate that keeps everything
// else out until it does, packet reassembly, replay rejection and heartbeats.
// See docs/protocol.md §1.4, §3.2-§3.3.
//
// Ported from App/Class/SocketStuff.cs MainTCPRoutine (1261-1565) and
// TcpReceiveData (557-610), App/Core/Receiver.cs PreProcess (40-82),
// App/Core/Common.cs SendPackage/SendHeartBeat (499-513), SendAwakeBeat
// (545-558), SendByeBye (612-616) and TestSend (822-847),
// App/Form/frmScreen.cs the 100 ms timer (285-288, 555-575).
import Foundation
/// How a connection is doing, in the Windows numbering so the menu-bar colours
/// can stay the same (`SocketStatus`, `SocketStuff.cs:54-66`).
public enum SocketStatus: Int, Sendable {
/// Not in use.
case na = 0
/// Looking the peer's name up.
case resolving
/// TCP connect in progress.
case connecting
/// Connected, exchanging handshakes.
case handshaking
/// Read or write failed.
case error
/// Closed by us.
case forceClosed
/// The peer does not share our security key.
case invalidKey
/// The peer stopped answering.
case timeout
/// A write failed.
case sendError
/// Trusted and carrying traffic.
case connected
}
/// Why a session gave up on a peer's key.
public enum InvalidKeyReason: Sendable, Equatable {
/// More than ten packets arrived before the handshake completed
/// (`SocketStuff.cs:1387-1406`).
case tooManyUntrustedPackets
/// The `HandshakeAck` nonce was not the complement we sent
/// (`SocketStuff.cs:1409-1410`).
case handshakeAckMismatch
}
/// What a session tells its owner.
public enum SessionEvent: Sendable, Equatable {
/// The connection's status changed; drive the UI from this.
case status(SocketStatus)
/// The handshake completed and the peer is trusted.
case connected(peerName: String, peerID: UInt32)
/// A trusted, non-duplicate application packet. Nothing is delivered here
/// before the handshake (CLAUDE.md invariant 2).
case packet(Packet)
/// The peer failed the key check.
case invalidKey(InvalidKeyReason)
/// The peer is us — Windows closes such a socket (`SocketStuff.cs:1430-1437`).
case selfConnection
/// Close the socket now. Always the last event of a session.
case close
}
/// Everything a session needs to know about the machine it runs on.
public struct SessionConfig: Sendable {
/// This machine's name, sent in every handshake.
public var localName: String
/// This machine's id (`MachineID` setting).
public var localID: UInt32
/// The magic number derived from the security key (`MagicHash`).
public var magic: UInt32
/// `BlockScreenSaverOnOtherMachines`, which sets the heartbeat cadence.
public var blockScreenSaver: Bool
/// The peer's name from DNS, if the caller resolved one; the `HandshakeAck`
/// name overrides it (`SocketStuff.cs:1412-1419`).
public var peerNameHint: String?
/// A session configuration.
public init(
localName: String, localID: UInt32, magic: UInt32, blockScreenSaver: Bool = true,
peerNameHint: String? = nil
) {
self.localName = localName
self.localID = localID
self.magic = magic
self.blockScreenSaver = blockScreenSaver
self.peerNameHint = peerNameHint
}
}
/// One connection's protocol logic, with no socket, timer or thread of its own.
///
/// The owner feeds it decrypted bytes, drains framed bytes to write back,
/// collects events and calls `tick` from its own timer. Not `Sendable`: one
/// connection owns one session, on one queue, alongside its `CipherWriter` and
/// `CipherReader`.
public final class Session {
/// Heartbeat every 60 s when the screen saver is being blocked
/// (`frmScreen.cs:565-570`: `count % 600` at 100 ms per tick).
public static let fastHeartbeat: TimeInterval = 60
/// Heartbeat every 300 s otherwise (`count % 3000`, `frmScreen.cs:568`).
public static let slowHeartbeat: TimeInterval = 300
/// Untrusted packets tolerated before the key is declared wrong
/// (`SocketStuff.cs:1390`).
public static let untrustedPacketLimit = 10
private let config: SessionConfig
private let sequencer: PacketSequencer
private let replay: ReplayFilter
private let isClient: Bool
private var inbox = Data()
private var outbox: [Data] = []
private var pending: [SessionEvent] = []
/// -1 once the peer is trusted, as `packageCount` is on Windows
/// (`SocketStuff.cs:1441`).
private var untrustedCount = 0
private var expectedNonce: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)
private var receiveErrors = 0
private var nextHeartbeat: TimeInterval = .greatestFiniteMagnitude
private var finished = false
/// The connection's status.
public private(set) var status: SocketStatus = .na
/// The peer's name, known once the handshake completes.
public private(set) var peerName: String?
/// The peer's machine id, taken from the `HandshakeAck`'s `Src`.
public private(set) var peerID: UInt32?
/// A session for one connection. `isClient` is whether we dialled out; it
/// changes nothing here but is what the network layer needs to decide which
/// of a pair's two connections to keep (`SocketStuff.cs:1980-2004`).
public init(
config: SessionConfig, sequencer: PacketSequencer, replay: ReplayFilter, isClient: Bool
) {
self.config = config
self.sequencer = sequencer
self.replay = replay
self.isClient = isClient
peerName = config.peerNameHint
}
/// Whether we dialled this connection out.
public var isOutbound: Bool { isClient }
// MARK: - Driving the session
/// Queues the opening handshake: ten identical `Handshake` packets, then
/// remembers the complement of their nonce as the ack we expect
/// (`SocketStuff.cs:1269-1299`).
///
/// The whole 64-byte packet starts as cryptographic randomness, so `Id`,
/// `Src` and `Des` are random too — only the type and the machine name are
/// set (`:1269-1289`).
public func start(now: TimeInterval) {
var handshake = Session.randomPacket()
try? handshake.setMachineName(config.localName)
handshake.type = .handshake
for _ in 0..<10 { sendDirect(handshake) }
let n = handshake.nonce
expectedNonce = (~n.0, ~n.1, ~n.2, ~n.3) // SocketStuff.cs:1296-1299
nextHeartbeat = now + heartbeatInterval
report(.handshaking)
}
/// Feeds decrypted socket bytes in. Handles the 32-then-32 rule itself: a
/// packet whose framing failed still occupies 64 bytes when its type byte
/// has the `Matrix` bit, which `.invalid` does (docs/protocol.md §10.1).
public func feed(_ plaintext: Data) {
inbox.append(plaintext)
while !finished {
guard inbox.count >= packageSize else { return }
let head = Framing.open(inbox.prefix(packageSize), magic: config.magic)
let size = head.type.packetSize
guard inbox.count >= size else { return }
// Re-open the whole 64 bytes for a big packet: the checksum covers
// bytes 2..31 either way, so this is what Windows does when it sets
// `package.Bytes = buf` (SocketStuff.cs:585-598).
let packet = size == packageSize ? head : Framing.open(inbox.prefix(size), magic: config.magic)
inbox.removeFirst(size)
receiveErrors = 0 // SocketStuff.cs:1364
handle(packet)
}
}
/// A read that returned nothing or a short packet — `PackageType.Error` on
/// Windows. Six in a row close the connection (`SocketStuff.cs:1326-1361`).
public func noteReceiveError() {
receiveErrors += 1
guard receiveErrors > 5 else { return }
report(.error)
close()
}
/// Reports a status the network layer knows and the session cannot see, such
/// as `.resolving` or `.sendError`.
public func report(_ new: SocketStatus) {
guard status != new else { return }
status = new
pending.append(.status(new))
}
/// Heartbeats. `userActive` is whether real input happened since the last
/// tick, which is what turns a `Heartbeat` into an `Awake`
/// (`Common.cs:545-552`).
public func tick(now: TimeInterval, userActive: Bool) {
guard status == .connected, !finished, now >= nextHeartbeat else { return }
nextHeartbeat = now + heartbeatInterval
let type: PackageType = config.blockScreenSaver && userActive ? .awake : .heartbeat
send(broadcast(type))
}
/// Queues a packet, stamping `Id` and `Src` as `SkSend` does
/// (`Common.cs:916`, `SocketStuff.cs:666-669`). Use this for anything the
/// app originates.
public func send(_ packet: Packet) {
var p = packet
p.id = sequencer.next()
sendDirect(p)
}
/// Queues a packet that already carries its `Id`, for a broadcast the app
/// sequenced once and is sending to several connections — which is what
/// `SkSend` does with one `Id` and many sockets (`Common.cs:912-930`), and
/// what keeps the receiver's replay ring collapsing a peer pair's two
/// copies into one. `Src` is still filled in if it is `NONE`.
public func forward(_ packet: Packet) {
sendDirect(packet)
}
/// The liveness probe Windows writes before trusting a socket's "connected"
/// state (`Hi`, `TestSend`, `Common.cs:822-847`). Not sequenced, like every
/// `TcpSend`-only packet.
public func probe() {
guard let id = peerID else { return }
var p = Packet(type: .hi)
p.des = id
try? p.setMachineName(config.localName)
sendDirect(p)
}
/// Queues `ByeBye (4)` on the way out (`Common.cs:612-616`).
public func sayGoodbye() {
send(broadcast(.byeBye))
}
/// Framed bytes to write through `CipherWriter`, in order. Drains the queue.
public func drain() -> [Data] {
defer { outbox.removeAll() }
return outbox
}
/// Everything that happened since the last call. Drains the queue.
public func events() -> [SessionEvent] {
defer { pending.removeAll() }
return pending
}
// MARK: - Receiving
private func handle(_ packet: Packet) {
// A Handshake is answered whatever the trust state, and never counts
// against the untrusted budget (SocketStuff.cs:1367-1384).
if packet.type == .handshake {
var ack = packet
ack.type = .handshakeAck
ack.src = MachineID.none // refilled with our id by sendDirect
try? ack.setMachineName(config.localName)
let n = packet.nonce
ack.nonce = (~n.0, ~n.1, ~n.2, ~n.3)
sendDirect(ack)
return
}
guard untrustedCount >= 0 else {
// Trusted. Duplicate acks from the peer's ten handshakes are
// ignored rather than processed (SocketStuff.cs:1524-1527).
if packet.type != .handshakeAck { deliver(packet) }
return
}
countUntrusted(packet)
}
/// The untrusted branch of `MainTCPRoutine` (`SocketStuff.cs:1386-1500`).
private func countUntrusted(_ packet: Packet) {
untrustedCount += 1
if untrustedCount >= Session.untrustedPacketLimit {
var reject = packet
reject.type = .invalid
for _ in 0..<10 { sendDirect(reject) } // SocketStuff.cs:1394-1397
report(.invalidKey)
pending.append(.invalidKey(.tooManyUntrustedPackets))
close()
return
}
switch packet.type {
case .handshakeAck:
acceptAck(packet)
case .mouse, .heartbeat, .heartbeatEx:
// Traffic from a peer mid-handshake is expected; give the budget
// back rather than spending it (SocketStuff.cs:1502-1515).
if untrustedCount > 5 { untrustedCount -= 1 }
default:
if untrustedCount > 5 { report(.invalidKey) } // SocketStuff.cs:1519-1521
}
}
/// The nonce check that makes a peer trusted (`SocketStuff.cs:1407-1480`).
private func acceptAck(_ packet: Packet) {
guard packet.nonce == expectedNonce else {
report(.invalidKey)
pending.append(.invalidKey(.handshakeAckMismatch))
close()
return
}
let claimed = packet.machineName ?? ""
let name = claimed.isEmpty ? (peerName ?? "") : claimed
if name.caseInsensitiveCompare(config.localName) == .orderedSame {
report(.na) // SocketStuff.cs:1433
pending.append(.selfConnection)
close()
return
}
untrustedCount = -1 // Trusted (SocketStuff.cs:1441)
peerName = name
peerID = packet.src
report(.connected)
pending.append(.connected(peerName: name, peerID: packet.src))
send(broadcast(.heartbeat)) // SendHeartBeat(initial: true), SocketStuff.cs:1451
}
/// `Receiver.PreProcess` (`Receiver.cs:40-82`): drop what framing rejected,
/// drop the type byte Windows treats as unknown, drop replays.
private func deliver(_ packet: Packet) {
if packet.type == .invalid { return }
if packet.type.rawValue == 0 { return }
if replay.isDuplicate(packet) { return }
pending.append(.packet(packet))
}
// MARK: - Sending
/// Writes a packet without touching `Id`, which is what `TcpSend` does:
/// only `SkSend` sequences (`SocketStuff.cs:663-678`).
private func sendDirect(_ packet: Packet) {
guard !finished else { return }
var p = packet
if p.src == MachineID.none { p.src = config.localID } // SocketStuff.cs:666-669
outbox.append(Framing.seal(p, magic: config.magic))
}
/// A broadcast packet carrying our machine name (`SendPackage`,
/// `Common.cs:499-507`).
private func broadcast(_ type: PackageType) -> Packet {
var p = Packet(type: type)
p.des = MachineID.all
try? p.setMachineName(config.localName)
return p
}
private var heartbeatInterval: TimeInterval {
config.blockScreenSaver ? Session.fastHeartbeat : Session.slowHeartbeat
}
private func close() {
guard !finished else { return }
finished = true
pending.append(.close)
}
/// 64 cryptographically random bytes as a packet (`SocketStuff.cs:1269-1270`).
private static func randomPacket() -> Packet {
var rng = SystemRandomNumberGenerator()
let bytes = (0..<packageSizeEx).map { _ in UInt8.random(in: .min ... .max, using: &rng) }
return Packet(bytes: Data(bytes)) ?? Packet(type: .handshake)
}
}