QA finding 1. `Resolver.addresses` applied one same-subnet check to the union of the Name2IP mappings and the DNS results. `StartNewTcpClient` checks each group on its own: the mapped group's failure is a `return` that skips `Dns.GetHostEntry` entirely (SocketStuff.cs:934-937, 950), so nothing is dialled for that name that round; the DNS group's failure (:1037-1040) drops only the DNS addresses, because the mapped ones have already been dialled (:941). Port that control flow, and document it in the feature README's Assumptions and docs/protocol.md §10.3 note 6. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
501 lines
28 KiB
Markdown
501 lines
28 KiB
Markdown
# 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 `SessionEvent`s 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 except `getaddrinfo`
|
||
inside `Resolver` for the `Name2IP`-free path, because
|
||
`NWConnection(host:port:)` already resolves names — prefer it and use
|
||
`getaddrinfo` only for the reverse-lookup validation option.
|
||
*(Shipped differently: `Resolver` does every lookup with `getaddrinfo`
|
||
and hands `NWConnection` a numeric address. See the work log — Windows
|
||
resolves the name itself, filters the address list and dials each
|
||
surviving address in parallel, and neither filter nor the parallel dial
|
||
can be expressed if the connection resolves the name for us.)*
|
||
- **Two listeners are the protocol's shape** (`SocketStuff.cs:475-495`):
|
||
this lane opens the control listener on `port + 1` only; the
|
||
clipboard listener on `port` is the clipboard lane's.
|
||
- **Per connection**: one `PeerConnection` owning `NWConnection`,
|
||
`Session`, `CipherWriter`, `CipherReader`, one serial `DispatchQueue`,
|
||
a bounded outbound queue (512 framed packets) and a 500 ms send
|
||
timeout (`SocketStuff.cs:1286`). The first bytes written are
|
||
`CipherWriter.header` (48 bytes); the first bytes read go into
|
||
`CipherReader`, whose output feeds `Session.feed`. A read that returns
|
||
fewer than 32 bytes at EOF or errors calls
|
||
`Session.noteReceiveError(bytesReceived:)` with the real count
|
||
(contracts, session-matrix Review). **The read is sized to make that
|
||
exact**: 48 bytes once for the peer's preamble, then exactly 32 bytes
|
||
per read, which after the preamble is exactly one Windows
|
||
`ReadEx(buf, 0, PACKAGE_SIZE)` (`docs/protocol.md` §10.3 note 8).
|
||
- **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 `.timeout` and wait for the next reconnect trigger. Socket
|
||
options mirror Windows: `NoDelay`, 320 000-byte buffers where
|
||
Network.framework exposes them (`SocketStuff.cs:1283-1286`) — it
|
||
exposes none, so only `NoDelay` is set and the bounded outbox is what
|
||
limits queued bytes.
|
||
- **Name resolution filters each address group on its own**
|
||
(`SocketStuff.cs:928-944, 950, 989-1044`): `Resolver.addresses` runs the
|
||
same control flow `StartNewTcpClient` does, not a filter over the union.
|
||
The `Name2IP` mappings are checked against the same-subnet rule alone, and
|
||
when that check fails Windows returns from `StartNewTcpClient` **before**
|
||
`Dns.GetHostEntry` is called (`:934-937, 950`) — so the name is not dialled
|
||
at all that round and we return `[]`. The DNS group is filtered by the
|
||
reverse lookup and then gets its own same-subnet check (`:1037-1040`);
|
||
failing it drops the DNS addresses only, leaving the mapped ones, which
|
||
Windows has already handed to `StartNewTcpClientThread` by then. Reverse-
|
||
lookup validation never applies to a user-supplied mapping
|
||
(`docs/protocol.md` §10.3 note 6).
|
||
- **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 `.idCollision` to the
|
||
sink; the app regenerates and calls `reopenAll()`. Windows force-closes
|
||
*every* socket in that branch, not just the offending one
|
||
(`docs/protocol.md` §10.3 note 3), and so do we.
|
||
- **Failure budget per endpoint** (`SocketStuff.cs:1482-1499`): more
|
||
than 10 `.invalidKey` outcomes from the same remote address ⇒ report
|
||
`.peerRejected(address)` and stop dialling it until `reopenAll()`.
|
||
Keyed by address only, and counting both invalid-key reasons — Windows
|
||
keys by address *and port* and counts only the mismatched ack, which
|
||
makes its counter almost unreachable (`docs/protocol.md` §10.3 note 5).
|
||
- **Reconnect triggers** (§3.3): `NWPathMonitor` status change, an
|
||
explicit `reopenAll()` (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 calls `reconfigure(_:)`). A key, port, local
|
||
name or local id change reopens everything; a matrix change clears the
|
||
dial state and grants a fresh 30 s budget, so a slot edited after the
|
||
budget expired is actually dialled.
|
||
- **Ticks**: the channel runs one 100 ms `DispatchSourceTimer` that
|
||
calls `Session.tick(now:userActive:)` on every connection (the app
|
||
reports `userActive` via `noteUserActivity()`), drains outboxes and
|
||
events, and detects the C2 "30 s silence while we are sending input"
|
||
stall: if the connection the sink marked as `controlled` receives
|
||
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, `Name2IP` text,
|
||
`sameSubnetOnly`, `validateRemoteIP`, `blockScreenSaver`.
|
||
- **Threading**: all mutation of channel state happens on one private
|
||
serial queue; `EngineSink` calls are made from that queue and the
|
||
sink is expected to hop to its actor. `PeerConnection` is not
|
||
`Sendable`; it never escapes the channel's queue. *(Shipped as
|
||
`@unchecked Sendable` on both `ControlChannel` and `PeerConnection`,
|
||
because Network.framework's handlers are `@Sendable` closures. The
|
||
confinement is real and unchanged: each `PeerConnection` has its own
|
||
serial queue created with `target: channelQueue`, so every callback in
|
||
the channel is serialised on the one channel queue. See the work log.)*
|
||
- **Time is monotonic.** Every interval here is measured with
|
||
`DispatchTime.now().uptimeNanoseconds`, which is what `Common.GetTick()`
|
||
is on Windows; nothing reads the wall clock, so a clock correction
|
||
cannot make a heartbeat or the stall rule fire.
|
||
|
||
## Handshakes
|
||
|
||
### Consumed
|
||
|
||
- `wire-core`: `CipherWriter`, `CipherReader`, `MagicHash`, `Packet`,
|
||
`Framing` (via `Session`), `packageSize`.
|
||
- `session-matrix`: `Session`, `SessionConfig`, `SessionEvent`,
|
||
`SocketStatus`, `InvalidKeyReason`, `PacketSequencer`, `ReplayFilter`.
|
||
|
||
Nothing in `MWBCore` was changed by this lane.
|
||
|
||
### Promised (to app-shell, clipboard)
|
||
|
||
As shipped 2026-09-16. Later lanes code against this, not against the
|
||
sketch this section used to hold.
|
||
|
||
```swift
|
||
// ChannelConfig.swift — the vocabulary
|
||
public struct ChannelConfig: Sendable, Equatable {
|
||
public var localName: String, localID: UInt32, port: UInt16 // port + 1 is the control port
|
||
public var securityKey: String, matrixNames: [String], name2IP: String
|
||
public var sameSubnetOnly: Bool, validateRemoteIP: Bool, blockScreenSaver: Bool
|
||
public var controlPort: UInt16 { get }
|
||
public init(localName:localID:port:securityKey:matrixNames:name2IP:
|
||
sameSubnetOnly:validateRemoteIP:blockScreenSaver:) // all but the first two defaulted
|
||
}
|
||
public enum Destination: Sendable, Equatable { case all, peer(UInt32) }
|
||
public enum DisconnectReason: Sendable, Equatable {
|
||
case closed, readError, sendError, invalidKey(InvalidKeyReason), peerRejected,
|
||
stall, duplicateClient, selfConnection, idCollision, timeout, forceClosed
|
||
}
|
||
public struct PeerStatus: Sendable, Equatable {
|
||
public var name: String; public var status: SocketStatus; public var isOutbound: Bool
|
||
public var peerID: UInt32?; public var address: String?
|
||
public init(name:status:isOutbound:peerID:address:)
|
||
}
|
||
public protocol EngineSink: AnyObject, Sendable {
|
||
func channel(_ channel: ControlChannel, connectionStatus: SocketStatus,
|
||
peerName: String?, isOutbound: Bool)
|
||
func channel(_ channel: ControlChannel, connected peerName: String, peerID: UInt32)
|
||
func channel(_ channel: ControlChannel, received packet: Packet, from peerID: UInt32)
|
||
func channel(_ channel: ControlChannel, disconnected peerID: UInt32?,
|
||
peerName: String?, reason: DisconnectReason)
|
||
func channelDetectedIDCollision(_ channel: ControlChannel)
|
||
}
|
||
|
||
// ControlChannel.swift — the sockets
|
||
public final class ControlChannel: @unchecked Sendable {
|
||
public static let connectTimeout: TimeInterval = 30 // SocketStuff.cs:158, 276
|
||
public static let retryInterval: TimeInterval = 1 // :1186
|
||
public static let tickInterval: TimeInterval = 0.1 // frmScreen.cs:285-288
|
||
public static let endpointFailureLimit = 10 // :1487-1497
|
||
public init(config: ChannelConfig, sequencer: PacketSequencer,
|
||
replay: ReplayFilter, sink: EngineSink)
|
||
public func start(); public func stop(); public func sayGoodbye()
|
||
public func reconfigure(_ new: ChannelConfig) // reopens what changed
|
||
public func reopenAll()
|
||
public func forward(_ packet: Packet, to: Destination) // already sequenced (C1)
|
||
public func noteUserActivity()
|
||
public func markControlled(peerID: UInt32?) // arms the 30 s stall rule
|
||
public var statuses: [PeerStatus] { get } // any thread
|
||
}
|
||
|
||
// Resolver.swift — name → addresses, no discovery
|
||
public enum Resolver {
|
||
public static func addresses(for name: String, config: ChannelConfig) -> [String]
|
||
public static func mappedAddresses(for name: String, in name2IP: String) -> [String]
|
||
public static func lookup(_ name: String) -> [String]
|
||
public static func reverseName(for address: String) -> String?
|
||
public static func shortName(for address: String) -> String
|
||
}
|
||
```
|
||
|
||
Rules the consuming lanes must honour:
|
||
|
||
- **Every `EngineSink` call arrives on the channel's serial queue.** Do
|
||
the least possible work in it and hop to the Engine actor; a sink that
|
||
blocks stalls every connection, the heartbeats and the stall rule. The
|
||
channel is handed to the sink as a parameter, so the sink never needs
|
||
to capture it.
|
||
- **`forward(_:to:)` takes an already-sequenced packet** (contracts C1).
|
||
The channel stamps nothing; it fans the identical bytes out, which is
|
||
what makes the receiver's replay ring collapse a peer pair's two
|
||
deliveries. `.all` is filtered by the matrix, exactly as `SkSend` does.
|
||
- **`reopenAll()` is the only way back from a give-up.** After the 30 s
|
||
connect budget expires, or after an address spends its failure budget,
|
||
the channel stops dialling on its own. The app is what turns that
|
||
around, on the reconnect hotkey, on wake, on a display change, and on
|
||
the "no socket established" countdown Windows runs from its 100 ms
|
||
timer (`frmScreen.cs:427-450`). The channel reopens itself only on an
|
||
`NWPathMonitor` status change.
|
||
- **`disconnected` carries optionals.** A connection that dies before the
|
||
handshake has no peer id and possibly no name; `peerID` is `nil` there.
|
||
Do not key recovery on the id alone.
|
||
- **The app owns the machine id.** On `channelDetectedIDCollision` the
|
||
channel has already closed every connection; the app draws a new
|
||
`MachineID`, hands it over in `reconfigure(_:)` and calls `reopenAll()`.
|
||
- **`stop()` does not say goodbye.** Call `sayGoodbye()` first on a clean
|
||
exit (`Common.SendByeBye`, `InitAndCleanup.cs:192`).
|
||
|
||
### Requested of other lanes (open)
|
||
|
||
1. **app-shell**: the reopen countdown is the app's. The channel gives up
|
||
dialling 30 s after `start()`/`reopenAll()` because Windows does
|
||
(`docs/protocol.md` §10.3 notes 1–2); something must call `reopenAll()`
|
||
again while no connection is established, or a machine that boots late
|
||
is never reached. Windows's rule — reopen when no socket is
|
||
established, checked every 30 s — is the one to port
|
||
(`frmScreen.cs:427-450`).
|
||
2. **app-shell**: `markControlled(peerID:)` must be called on every
|
||
switch, including back to local (`nil`). It is what arms the C2 30 s
|
||
stall rule, and nothing else in the channel knows which peer is
|
||
receiving input.
|
||
|
||
### Answered from session-matrix
|
||
|
||
- The duplicate-client-socket policy (`SocketStuff.cs:1980-2004`) and the
|
||
per-endpoint failure budget (`:1482-1499`) are implemented here, keyed
|
||
by peer name and remote address respectively. `Session` still counts
|
||
nothing across connections.
|
||
|
||
## Status / TODO
|
||
|
||
- [x] `Sources/MWBNet/ChannelConfig.swift`: config, `EngineSink`,
|
||
`DisconnectReason`, `PeerStatus`, `Destination`.
|
||
- [x] `Sources/MWBNet/PeerConnection.swift`: one connection — cipher
|
||
header exchange, read loop with 32/64 framing left to `Session`,
|
||
bounded outbox, 500 ms send timeout, stall detection, close
|
||
(`SocketStuff.cs:1261-1565` I/O side, `:1283-1286`).
|
||
- [x] `Sources/MWBNet/Resolver.swift`: `Name2IP` parsing
|
||
(`SocketStuff.cs:904-946, 1258-1259`), same-/16 check
|
||
(`:1065-1107`), reverse validation (`:991-1032`).
|
||
- [x] `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.
|
||
- [x] Delete `Sources/MWBNet/Placeholder.swift`.
|
||
- [x] `docs/protocol.md`: append §10.3 with anything learned, cited.
|
||
|
||
Not done, deliberately:
|
||
|
||
- **The `Name2IpPolicyList` half of the mapping list**
|
||
(`SocketStuff.cs:906`): it is a Windows GPO-delivered setting, and GPO
|
||
is out of scope (README D6). `Name2IP` alone is parsed, with the same
|
||
grammar.
|
||
- **The bad-IP cache** (`SocketStuff.cs:840-882`): it only memoises the
|
||
reverse-lookup result so a failing address is not looked up again.
|
||
Behaviour is identical without it — a rejected address is simply
|
||
re-checked on the next dial — and the option is off by default.
|
||
- **Socket send/receive buffer sizes** (`:1283-1284`): Network.framework
|
||
exposes neither. The bounded outbox (512 framed packets) is the
|
||
equivalent limit and is what contracts C3 asks for anyway.
|
||
- **Reverse DNS for an inbound peer's display name**
|
||
(`GetMachineNameFromSocket`, `:733-762`): the lookup blocks, and the
|
||
channel queue must not. An inbound connection is labelled by its
|
||
address until the `HandshakeAck` supplies the real name, which is
|
||
within ten packets. `Resolver.shortName(for:)` exists for a lane that
|
||
wants it off the queue.
|
||
- **Windows quitting the app on the eleventh failure from one endpoint**
|
||
(`:1493-1496`): a Mac that silently exits because one peer has a wrong
|
||
key is a worse outcome than one dead peer. We block the address and
|
||
keep running.
|
||
|
||
## Work log
|
||
|
||
### 2026-09-16 — dev (Opus)
|
||
|
||
Four files in `MWBNet`, `Placeholder.swift` deleted, `tools/gates.sh`
|
||
green. What each file is responsible for, in one sentence apiece:
|
||
|
||
- `ChannelConfig.swift` (189 lines) — the vocabulary the channel and the
|
||
app share, and nothing else: config, `Destination`, `DisconnectReason`,
|
||
`PeerStatus`, `EngineSink`.
|
||
- `Resolver.swift` (229 lines) — a machine name to the list of addresses
|
||
worth dialling, including both optional filters. The only file that
|
||
touches `getaddrinfo`/`getifaddrs`, and the only one that blocks.
|
||
- `PeerConnection.swift` (356 lines) — one connection's I/O: the cipher
|
||
preamble, the sized reads, the bounded outbox with its 500 ms timeout,
|
||
and the translation of `SessionEvent` into channel events.
|
||
- `ControlChannel.swift` (505 lines) — everything keyed by endpoint
|
||
rather than by connection: the listener, the dial loop, the
|
||
one-client-per-peer and id-collision rules, the failure budget, the
|
||
reconnect triggers and the 100 ms tick.
|
||
|
||
Decisions and deviations, each with why:
|
||
|
||
1. **Reads are sized, not streamed.** The obvious `receive(min: 1,
|
||
max: 65536)` loop would have made "a read that returned fewer than 32
|
||
bytes" unrepresentable, and that byte count is exactly what
|
||
`Session.noteReceiveError(bytesReceived:)` needs to distinguish
|
||
Windows's `Error` (0 bytes) from `Invalid` (short) package
|
||
(`SocketStuff.cs:574-578`). Instead the reader takes the peer's
|
||
48-byte preamble in one read and then exactly 32 bytes per read. That
|
||
is sound because the stream is packet-aligned after the preamble:
|
||
every write is a whole 32- or 64-byte packet through a no-padding CBC
|
||
stream, so 32 bytes of ciphertext in are always 32 bytes of plaintext
|
||
out (protocol §10.3 note 8). Verified off-line with a no-socket
|
||
harness that runs two `Session`s through real `CipherWriter`/
|
||
`CipherReader` pairs at exactly this chunking: the preamble yields 0
|
||
plaintext bytes, every 32-byte read yields 32, the handshake reaches
|
||
`.connected` on both sides with the right peer name and id, and both
|
||
streams drain to zero leftover.
|
||
2. **One serial queue, per-connection queues that target it.** The brief
|
||
asks for all channel state on one private serial queue; contracts C3
|
||
describes a queue per connection. Both are satisfied by
|
||
`DispatchQueue(label: "mwb.peer.N", target: channelQueue)`: each
|
||
connection has its own FIFO, and the target chain serialises every one
|
||
of them on the channel queue, so there is no lock anywhere in `MWBNet`
|
||
except the one publishing `statuses`.
|
||
3. **`@unchecked Sendable` on `ControlChannel` and `PeerConnection`.**
|
||
Network.framework's state, receive and send handlers are `@Sendable`
|
||
closures, so a non-`Sendable` class cannot be captured by them at all
|
||
under Swift 6. The confinement the README promised is unchanged and is
|
||
the justification: every stored property of both types is touched only
|
||
from the channel queue. `statuses` is the one exception, and it is an
|
||
`OSAllocatedUnfairLock` holding a value copy.
|
||
4. **`Resolver` resolves; `NWConnection` does not.** `NWConnection(host:
|
||
.name(…))` would have been less code, but Windows resolves the name
|
||
itself and then *filters* the address list (same-subnet, reverse
|
||
lookup) and dials every survivor in parallel (`SocketStuff.cs:989-1044`).
|
||
Neither the filter nor the parallel dial survives handing the name to
|
||
Network.framework, so `Resolver` returns numeric addresses and the
|
||
channel dials each one.
|
||
5. **`.waiting` counts as a failed attempt.** Network.framework would
|
||
happily sit in `.waiting` retrying a refused connection on its own
|
||
schedule. Windows retries every second against a 30 s deadline, so the
|
||
connection is cancelled on `.waiting` and the channel's own cadence
|
||
governs (`:1179-1193`).
|
||
6. **The dial loop is polled, Windows's is triggered.** `UpdateTCPClients`
|
||
runs only when something calls it (protocol §10.3 note 2), which works
|
||
there because the 100 ms UI timer also runs a reopen countdown. Ours is
|
||
re-evaluated on the same 100 ms tick, still bounded by the 1 s retry
|
||
interval and the 30 s budget, so the observable cadence is Windows's
|
||
without depending on an app-level countdown that does not exist yet —
|
||
the countdown is still requested of app-shell (Handshakes) because it
|
||
is what recovers after the budget expires.
|
||
7. **The failure budget is keyed by address, not by address:port, and
|
||
counts both invalid-key reasons.** Windows's key includes the remote
|
||
ephemeral port, which is new on every connection, so its counter
|
||
effectively never fires (protocol §10.3 note 5). Keying by address
|
||
makes the guard do what its code plainly intends. And we block that
|
||
address instead of quitting the app (invariant 3: the Mac stays usable).
|
||
8. **`DisconnectReason` has no `.byeBye` case.** The sketch listed one,
|
||
but the channel interprets no packet and therefore cannot know a
|
||
`ByeBye` arrived — `Session` delivers it to the app like any other
|
||
trusted packet, and the app's `Switcher.handleByeBye` already owns the
|
||
behaviour. Windows does not close the socket on `ByeBye` either.
|
||
9. **`disconnected` gained `peerName` and made `peerID` optional.** A
|
||
connection that dies during the handshake has neither an id nor,
|
||
usually, a confirmed name; the promised signature could not describe
|
||
it. The sink needs the name to clear a matrix slot's status.
|
||
10. **`sayGoodbye()` was added.** `Common.SendByeBye` is a broadcast on
|
||
Windows, but session-matrix deliberately made `ByeBye` a
|
||
per-connection originate, so the channel needs an entry point that is
|
||
not `forward(_:to:)`. It is the app's last call before `stop()`.
|
||
|
||
Nothing outside the lane's file list was edited: four new files in
|
||
`Sources/MWBNet`, one deletion, this README, `TODO.md` §3 and
|
||
`docs/protocol.md` §10.3. No `MWBCore` file was touched and no handshake
|
||
request against another lane's files was needed.
|
||
|
||
Verification (no real listening socket was opened at any point, and no
|
||
input event or pasteboard was touched):
|
||
|
||
- `tools/gates.sh` green on the final commit.
|
||
- The no-socket chunking harness described in decision 1.
|
||
- A `Resolver` harness over the public API: `Name2IP` parsing
|
||
(case-insensitive name match, several mappings for one name, malformed
|
||
and non-numeric lines dropped), `lookup` of a name that resolves and
|
||
one that does not, `shortName` of `127.0.0.1`, and `addresses(...)`
|
||
with `sameSubnetOnly` and `validateRemoteIP` on. All as specified.
|
||
|
||
## QA log
|
||
|
||
### 2026-09-16 — QA (Sonnet)
|
||
|
||
Checked, in order: `tools/gates.sh`; every Status/TODO tick against
|
||
`App/Class/SocketStuff.cs` (listeners, `UpdateTCPClients`, `Name2IP`, DNS,
|
||
subnet, connect, options, `MainTCPRoutine` I/O, failure budget,
|
||
dedup/collision), `TcpServer.cs`, `InitAndCleanup.cs:28-31`,
|
||
`frmScreen.cs:427-461`; all four changed files top to bottom for CLAUDE.md
|
||
compliance (size, layering, naming, force-unwraps, retain cycles); that
|
||
`MWBNet` logs nothing and interprets no packet.
|
||
|
||
- `tools/gates.sh`: green (`swift-format lint --strict`, MWBCore layering,
|
||
`swift build -Xswiftc -warnings-as-errors`). No `Tests/` target exists in
|
||
this repo (the user's rule, `TODO.md`/`docs/topo.md` history) so no
|
||
`swift test` gate applies; the work log's harnesses are not committed,
|
||
consistent with that rule.
|
||
- File-by-file read: no force-unwraps, `try!`, `fatalError` or
|
||
`precondition` in any of the four files; no `print`/`Logger`/`os_log`
|
||
calls anywhere in `MWBNet` (invariant 2 — nothing to leak key material or
|
||
packet contents even inadvertently); every closure captured across an
|
||
escaping boundary (`NWConnection`/`NWListener`/`NWPathMonitor`/
|
||
`DispatchSourceTimer`/`DispatchWorkItem` handlers in both
|
||
`PeerConnection` and `ControlChannel`) uses `[weak self]`, so no retain
|
||
cycle. File sizes (189/512/356/229) and every function body are inside
|
||
CLAUDE.md's targets. Confirmed `Session.forward` → `sendDirect` only
|
||
fills `Src` when unset and never touches `Id`
|
||
(`Sources/MWBCore/Session.swift:390-395`), so `forward(_:to:)` truly
|
||
never re-stamps a packet (C1). Confirmed the 48-byte `writer.header` is
|
||
enqueued before `session.start(now:)` in `becameReady()`
|
||
(`PeerConnection.swift:158-159`), and `receiveExactly` passes the real
|
||
`received.count` to `noteReceiveError(bytesReceived:)`
|
||
(`PeerConnection.swift:207-208`). Confirmed `@unchecked Sendable` on both
|
||
types: every stored property is touched only from `queue`/`peerQueue`
|
||
(which targets `queue`), except `statusStore`, which is its own
|
||
`OSAllocatedUnfairLock` — no handler found that touches state off the
|
||
channel queue.
|
||
- Two undocumented behavioural deviations from the Windows source turned
|
||
up from the line-by-line comparison; neither is mentioned in
|
||
`docs/protocol.md` §10.3, the README, or the work log's list of
|
||
deliberate deviations. Filed below.
|
||
- Verified deliberate, documented deviations are in fact what's shipped:
|
||
`Name2IpPolicyList` and the bad-IP cache are absent (`grep` clean), the
|
||
failure budget is keyed by address only and counts every `.invalidKey`
|
||
reason (`ControlChannel.swift:400-406`), Windows's app-quit-on-eleventh
|
||
is replaced with per-address blocking — all as the work log states.
|
||
|
||
Verdict: REWORK
|
||
|
||
Findings:
|
||
|
||
1. **`Resolver.addresses` merges the `Name2IP` and DNS address groups
|
||
before the same-subnet check, instead of checking each group
|
||
separately, and has no equivalent of Windows's early return when the
|
||
`Name2IP` group itself fails that check.**
|
||
`Sources/MWBNet/Resolver.swift:24-41` builds one `found` array from
|
||
`mappedAddresses` then `lookup`, and applies `isSameSubnet` once to the
|
||
union. Windows (`SocketStuff.cs:930-944`) runs `CheckForSameSubNet` on
|
||
the `Name2IP`-mapped addresses alone and, if it fails, `return`s from
|
||
`StartNewTcpClient` **before `Dns.GetHostEntry` is ever called** —
|
||
skipping DNS resolution for that round entirely — then separately runs
|
||
`CheckForSameSubNet` again on the DNS-resolved group
|
||
(`:1035-1044`). Net effect with `sameSubnetOnly` on and a `Name2IP`
|
||
mapping configured: (a) a `Name2IP` address outside the local subnet
|
||
but a DNS address inside it — Windows dials nothing for that name this
|
||
round (the early return skips DNS too); the port dials the DNS
|
||
address. (b) A `Name2IP` address inside the subnet but a DNS address
|
||
outside it — Windows dials only the `Name2IP` address; the port's
|
||
single union check passes (because *some* address in the union
|
||
matches) and dials both, including the out-of-subnet DNS address.
|
||
`docs/protocol.md` §10.3 note 6 documents the reverse-lookup-filter
|
||
half of this same code region but not the subnet-check-per-group
|
||
split or the early return. Both `sameSubnetOnly` and `Name2IP` are
|
||
off/empty by default, so this needs a live peer with both configured
|
||
to reach.
|
||
|
||
2. **Machine-id collision is detected on inbound (server) connections
|
||
too; Windows only detects it on outbound (client) sockets.**
|
||
`Sources/MWBNet/ControlChannel.swift:367-372` (`accept(_:name:id:)`)
|
||
runs `if id == config.localID { sink.channelDetectedIDCollision(...);
|
||
closeAll(.idCollision); return }` for every connection that completes
|
||
its handshake, regardless of `peer.isOutbound`. On Windows,
|
||
`UpdateTcpSockets`'s entire collision-and-dedup block is gated by
|
||
`status == SocketStatus.Connected && tcp.IsClient`
|
||
(`SocketStuff.cs:1981`) — the id check at `:1985` never runs for a
|
||
server-accepted socket. The port gets the *dedup* half of that same
|
||
guard right two lines below (`peer.isOutbound` on the
|
||
`duplicateClient` check, `ControlChannel.swift:375`) but drops the
|
||
guard for the collision half. `docs/protocol.md` §10.3 note 3
|
||
describes the force-close-everything behaviour but not the
|
||
client-only gate, so this reads as faithfully ported when it isn't.
|
||
Practical effect: a Mac can force-close every connection and
|
||
regenerate its machine id reacting to a collision reported over an
|
||
*inbound* connection, a case real Windows silently tolerates — not
|
||
unsafe (invariant 3 is still satisfied, this only affects other
|
||
machines), but an undocumented behavioural difference invariant 1
|
||
requires be either matched or explicitly justified.
|
||
|
||
3. **(Minor, doc-only) The `userActive` heuristic in
|
||
`ControlChannel.tick` is a time-window proxy, not what
|
||
`SendAwakeBeat` actually checks, and the approximation isn't cited
|
||
anywhere.** `ControlChannel.swift:441-442` computes `userActive =
|
||
lastUserActivity > 0 && now - lastUserActivity <= interval` (the
|
||
heartbeat interval itself, 60 s/300 s). Windows's `SendAwakeBeat`
|
||
(`Common.cs:545-558`) instead sends `Awake` when
|
||
`lastRealInputEventCount != Event.RealInputEventCount` — i.e. any new
|
||
real input since the *previous* heartbeat tick, not "within the last N
|
||
seconds of `now`" — plus `IsMyDesktopActive()` and
|
||
not-logon/not-screensaver-desktop checks this lane correctly leaves to
|
||
another lane. The two proxies agree in the steady state (continuous
|
||
activity or continuous idleness) and only diverge at the edges, so
|
||
this is low-impact, but note that `docs/protocol.md` §3.3's own
|
||
citation for this rule (`Common.cs:499-513, 662-676`) is stale — those
|
||
lines are `SendHeartBeat`/screen-capture code, not `SendAwakeBeat` —
|
||
which predates this lane and was inherited rather than checked against
|
||
source. Worth a one-line fix to protocol.md §3.3's citation and a note
|
||
on the approximation next time §3.3 or this file is touched; not
|
||
blocking on its own.
|
||
|
||
## Review
|