Files
lucio ee835508f4 wire-core: port DATA/PackageType, framing, magic hash and the CBC stream
Packet.swift, Framing.swift, MagicHash.swift, CipherStream.swift in
MWBCore, each constant cited to the Windows source.
2026-09-16 00:09:37 -07:00

405 lines
16 KiB
Swift

// The `DATA` packet of the Mouse Without Borders wire protocol: its type
// numbering, its size rule and the overlapping field views over one
// little-endian byte buffer. See docs/protocol.md §1.1-§1.2.
//
// Ported from App/Core/DATA.cs, App/Core/Package.cs, App/Core/PackageType.cs,
// App/Core/MOUSEDATA.cs, App/Core/KEYBDDATA.cs, App/Core/ID.cs.
import Foundation
/// Size in bytes of a small packet (`Package.PACKAGE_SIZE`, `Package.cs:17`).
public let packageSize = 32
/// Size in bytes of a big packet (`Package.PACKAGE_SIZE_EX`, `Package.cs:18`).
public let packageSizeEx = 64
/// What a packet is for; one byte on the wire (`PackageType.cs:15-57`).
///
/// Values the Windows build does not define decode as `.unknown` rather than
/// failing, so a newer peer cannot desynchronise our framing: the size rule
/// below is enough to keep the stream aligned.
public enum PackageType: RawRepresentable, Sendable, Hashable {
case hi // 2, PackageType.cs:22
case hello // 3, PackageType.cs:23
case byeBye // 4, PackageType.cs:24
case heartbeat // 20, PackageType.cs:26
case awake // 21, PackageType.cs:27
case hideMouse // 50, PackageType.cs:28
case heartbeatEx // 51, PackageType.cs:29
case heartbeatExL2 // 52, PackageType.cs:30
case heartbeatExL3 // 53, PackageType.cs:31
case clipboard // 69, PackageType.cs:33
case clipboardDragDrop // 70, PackageType.cs:34
case clipboardDragDropEnd // 71, PackageType.cs:35
case explorerDragDrop // 72, PackageType.cs:36
case clipboardCapture // 73, PackageType.cs:37
case captureScreenCommand // 74, PackageType.cs:38
case clipboardDragDropOperation // 75, PackageType.cs:39
case clipboardDataEnd // 76, PackageType.cs:40
case machineSwitched // 77, PackageType.cs:41
case clipboardAsk // 78, PackageType.cs:42
case clipboardPush // 79, PackageType.cs:43
case nextMachine // 121, PackageType.cs:45
case keyboard // 122, PackageType.cs:46
case mouse // 123, PackageType.cs:47
case clipboardText // 124, PackageType.cs:48
case clipboardImage // 125, PackageType.cs:49
case handshake // 126, PackageType.cs:51
case handshakeAck // 127, PackageType.cs:52
case matrix // 128 = 0x80, PackageType.cs:54; the flags below are OR'd in
case error // 0xFE, PackageType.cs:20 — never on the wire, a 0-byte read
case invalid // 0xFF, PackageType.cs:18 — never on the wire, bad framing
/// Any other byte value, kept verbatim so it can be re-encoded and sized.
case unknown(UInt8)
/// Bit 0x80: set on every `Matrix` packet (`DATA.cs:131`).
public static let matrixBit: UInt8 = 128
/// OR'd into a `Matrix` type when the two machines are swapping slots
/// (`MatrixSwapFlag = 2`, `PackageType.cs:55`).
public static let matrixSwapFlag: UInt8 = 2
/// OR'd into a `Matrix` type when the matrix is two rows
/// (`MatrixTwoRowFlag = 4`, `PackageType.cs:56`).
public static let matrixTwoRowFlag: UInt8 = 4
/// The byte that goes at offset 0 (`DATA.cs:27-28`).
public var rawValue: UInt8 {
switch self {
case .hi: return 2
case .hello: return 3
case .byeBye: return 4
case .heartbeat: return 20
case .awake: return 21
case .hideMouse: return 50
case .heartbeatEx: return 51
case .heartbeatExL2: return 52
case .heartbeatExL3: return 53
case .clipboard: return 69
case .clipboardDragDrop: return 70
case .clipboardDragDropEnd: return 71
case .explorerDragDrop: return 72
case .clipboardCapture: return 73
case .captureScreenCommand: return 74
case .clipboardDragDropOperation: return 75
case .clipboardDataEnd: return 76
case .machineSwitched: return 77
case .clipboardAsk: return 78
case .clipboardPush: return 79
case .nextMachine: return 121
case .keyboard: return 122
case .mouse: return 123
case .clipboardText: return 124
case .clipboardImage: return 125
case .handshake: return 126
case .handshakeAck: return 127
case .matrix: return PackageType.matrixBit
case .error: return 0xFE
case .invalid: return 0xFF
case .unknown(let raw): return raw
}
}
/// Never fails: an unrecognised byte becomes `.unknown`.
public init(rawValue: UInt8) {
switch rawValue {
case 2: self = .hi
case 3: self = .hello
case 4: self = .byeBye
case 20: self = .heartbeat
case 21: self = .awake
case 50: self = .hideMouse
case 51: self = .heartbeatEx
case 52: self = .heartbeatExL2
case 53: self = .heartbeatExL3
case 69: self = .clipboard
case 70: self = .clipboardDragDrop
case 71: self = .clipboardDragDropEnd
case 72: self = .explorerDragDrop
case 73: self = .clipboardCapture
case 74: self = .captureScreenCommand
case 75: self = .clipboardDragDropOperation
case 76: self = .clipboardDataEnd
case 77: self = .machineSwitched
case 78: self = .clipboardAsk
case 79: self = .clipboardPush
case 121: self = .nextMachine
case 122: self = .keyboard
case 123: self = .mouse
case 124: self = .clipboardText
case 125: self = .clipboardImage
case 126: self = .handshake
case 127: self = .handshakeAck
case PackageType.matrixBit: self = .matrix
case 0xFE: self = .error
case 0xFF: self = .invalid
default: self = .unknown(rawValue)
}
}
/// True when the packet is 64 bytes and therefore carries a machine name.
///
/// `DATA.cs:124-133`: a fixed list of types, **or** any type with the
/// `Matrix` bit set. Note the consequence the Windows receive loop relies
/// on (`SocketStuff.cs:558-610`): `Error` (0xFE) and `Invalid` (0xFF) also
/// have that bit, so a packet rejected by framing still consumes 64 bytes.
public var isBig: Bool {
switch self {
case .hello, .awake, .heartbeat, .heartbeatEx, .handshake, .handshakeAck,
.clipboardPush, .clipboard, .clipboardAsk, .clipboardImage, .clipboardText,
.clipboardDataEnd:
return true
default:
return (rawValue & PackageType.matrixBit) != 0
}
}
/// True for a `Matrix` packet, with or without the swap/two-row flags
/// (`DATA.cs:131`).
public var isMatrix: Bool { (rawValue & PackageType.matrixBit) != 0 }
/// Size on the wire in bytes.
public var packetSize: Int { isBig ? packageSizeEx : packageSize }
}
/// A machine id (`ID`, `ID.cs:15-19`); `Src` and `Des` on the wire.
public enum MachineID {
/// No machine (`ID.NONE`, `ID.cs:17`).
public static let none: UInt32 = 0
/// Broadcast to every machine (`ID.ALL`, `ID.cs:18`).
public static let all: UInt32 = 255
}
/// The mouse view of bytes 16..31 (`MOUSEDATA`, `MOUSEDATA.cs:18-26`).
public struct MouseData: Sendable, Hashable {
/// X coordinate, normalised per docs/protocol.md §4.4.
public var x: Int32
/// Y coordinate, normalised per docs/protocol.md §4.4.
public var y: Int32
/// Wheel delta in Windows units (120 per notch); also carries an id in
/// `NextMachine` packets.
public var wheelDelta: Int32
/// `MOUSEEVENTF_*` flags.
public var flags: Int32
/// A mouse view with the given fields.
public init(x: Int32 = 0, y: Int32 = 0, wheelDelta: Int32 = 0, flags: Int32 = 0) {
self.x = x
self.y = y
self.wheelDelta = wheelDelta
self.flags = flags
}
}
/// The keyboard view of bytes 16..31: `DateTime` then `KEYBDDATA`
/// (`DATA.cs:39-43`, `KEYBDDATA.cs:18-25`).
public struct KeyboardData: Sendable, Hashable {
/// Send timestamp, set only for `Keyboard` packets (`Event.cs:266`) and
/// ignored on receive.
public var dateTime: Int64
/// Windows virtual-key code (`wVk`).
public var virtualKey: Int32
/// `KEYEVENTF_*` / `LLKHF_*` flags (`dwFlags`).
public var flags: Int32
/// A keyboard view with the given fields.
public init(dateTime: Int64 = 0, virtualKey: Int32 = 0, flags: Int32 = 0) {
self.dateTime = dateTime
self.virtualKey = virtualKey
self.flags = flags
}
}
/// Why a machine name could not be put into a packet.
public enum PacketError: Error, Sendable, Hashable {
/// The name contains a character outside 7-bit ASCII, which cannot survive
/// the Windows `ASCIIEncoding` round trip (`Common.cs:397-405`).
case machineNameNotASCII
/// The name is longer than the 32-byte field (`DATA.cs:86-93`).
case machineNameTooLong
}
/// One protocol packet: a 64-byte little-endian buffer with overlapping field
/// views, of which the first 32 or all 64 bytes go on the wire.
///
/// Mirrors `DATA` (`DATA.cs:24-149`), which is an explicit-layout struct
/// marshalled with `Marshal.StructureToPtr` — little-endian, natural
/// alignment, no padding. Storage is always 64 bytes, as `DATA` always is;
/// `bytes` truncates to 32 for a small packet exactly as `DATA.Bytes` does
/// (`DATA.cs:105-113`).
public struct Packet: Sendable, Hashable {
private var buffer: [UInt8]
/// A zeroed packet of the given type.
public init(type: PackageType) {
buffer = [UInt8](repeating: 0, count: packageSizeEx)
self.type = type
}
/// A packet over received bytes, without any framing check; `nil` unless
/// there are exactly 32 or 64 of them.
///
/// A 32-byte buffer is zero-extended to 64, as `DATA.Bytes` does
/// (`DATA.cs:115-121`).
public init?(bytes: Data) {
guard bytes.count == packageSize || bytes.count == packageSizeEx else { return nil }
var buf = [UInt8](repeating: 0, count: packageSizeEx)
buf.replaceSubrange(0..<bytes.count, with: bytes)
buffer = buf
}
/// The wire bytes: 32 for a small packet, 64 for a big one
/// (`DATA.cs:105-113`).
public var bytes: Data { Data(buffer[0..<type.packetSize]) }
/// Package type, byte 0 (`DATA.cs:27-28`). Only byte 0 survives the wire:
/// bytes 1..3 are the checksum and magic (`Framing`).
public var type: PackageType {
get { PackageType(rawValue: buffer[0]) }
set { buffer[0] = newValue.rawValue }
}
/// Packet sequence number, offset 4 (`DATA.cs:30-31`).
public var id: Int32 {
get { loadInt32(4) }
set { store(UInt32(bitPattern: newValue), at: 4) }
}
/// Source machine id, offset 8 (`DATA.cs:33-34`). In `Matrix` packets this
/// is a 1-based slot index instead (docs/protocol.md §4.2).
public var src: UInt32 {
get { loadUInt32(8) }
set { store(newValue, at: 8) }
}
/// Destination machine id, offset 12 (`DATA.cs:36-37`); `MachineID.all`
/// broadcasts.
public var des: UInt32 {
get { loadUInt32(12) }
set { store(newValue, at: 12) }
}
/// The mouse view of bytes 16..31 (`DATA.cs:45-46`).
public var mouse: MouseData {
get {
MouseData(
x: loadInt32(16), y: loadInt32(20), wheelDelta: loadInt32(24),
flags: loadInt32(28))
}
set {
store(UInt32(bitPattern: newValue.x), at: 16)
store(UInt32(bitPattern: newValue.y), at: 20)
store(UInt32(bitPattern: newValue.wheelDelta), at: 24)
store(UInt32(bitPattern: newValue.flags), at: 28)
}
}
/// The keyboard view of bytes 16..31 (`DATA.cs:39-43`).
public var keyboard: KeyboardData {
get {
KeyboardData(
dateTime: Int64(bitPattern: loadUInt64(16)), virtualKey: loadInt32(24),
flags: loadInt32(28))
}
set {
store(UInt64(bitPattern: newValue.dateTime), at: 16)
store(UInt32(bitPattern: newValue.virtualKey), at: 24)
store(UInt32(bitPattern: newValue.flags), at: 28)
}
}
/// The handshake nonce view of bytes 16..31: `Machine1..4`
/// (`DATA.cs:48-58`).
public var nonce: (UInt32, UInt32, UInt32, UInt32) {
get { (loadUInt32(16), loadUInt32(20), loadUInt32(24), loadUInt32(28)) }
set {
store(newValue.0, at: 16)
store(newValue.1, at: 20)
store(newValue.2, at: 24)
store(newValue.3, at: 28)
}
}
/// The clipboard post-action view of bytes 16..19 (`DATA.cs:60-61`;
/// `ClipboardPostAction.cs:20-25`: Other 0, Desktop 1, Mspaint 2).
public var postAction: UInt32 {
get { loadUInt32(16) }
set { store(newValue, at: 16) }
}
/// Bytes 16..63, the 48-byte clipboard chunk of a big packet
/// (`Clipboard.cs:46, 274`: `dataStart = PACKAGE_SIZE_EX - DATA_SIZE`).
/// Writing fewer than 48 bytes zero-fills the rest, as the Windows sender
/// does for the last chunk (`Clipboard.cs:281`).
public var payload48: Data {
get { Data(buffer[16..<packageSizeEx]) }
set {
var chunk = [UInt8](repeating: 0, count: Packet.clipboardChunkSize)
let n = min(newValue.count, Packet.clipboardChunkSize)
chunk.replaceSubrange(0..<n, with: newValue.prefix(n))
buffer.replaceSubrange(16..<packageSizeEx, with: chunk)
}
}
/// Bytes of the clipboard chunk carried by one big packet
/// (`DATA_SIZE = 48`, `Clipboard.cs:46`).
public static let clipboardChunkSize = 48
/// The sender's machine name from bytes 32..63, or `nil` on a small packet
/// that has no such field (`DATA.cs:63-94`).
///
/// Decoded as ASCII like `Common.GetString` (`Common.cs:402-405`), which
/// substitutes `?` for any byte above 0x7F, then trimmed as `DATA.cs:83`
/// does. NULs are trimmed too, which `String.Trim()` does not do, so that a
/// zero-filled field reads as empty rather than as 32 NULs.
public var machineName: String? {
guard type.isBig else { return nil }
let ascii = buffer[32..<packageSizeEx].map { $0 < 0x80 ? Character(UnicodeScalar($0)) : "?" }
return String(ascii).trimmingCharacters(in: machineNameTrimSet)
}
/// Writes bytes 32..63 with `name`, right-padded with spaces to 32 bytes
/// (`DATA.cs:86-93`).
///
/// Not a property setter because a non-ASCII name is rejected rather than
/// silently turned into `?`: Windows would encode it lossily
/// (`Common.cs:397-400`) and the peer could never resolve the machine.
public mutating func setMachineName(_ name: String) throws {
guard name.allSatisfy({ $0.isASCII }) else { throw PacketError.machineNameNotASCII }
guard name.utf8.count <= 32 else { throw PacketError.machineNameTooLong }
var field = [UInt8](repeating: 0x20, count: 32) // PadRight(32, ' '), DATA.cs:88
field.replaceSubrange(0..<name.utf8.count, with: Array(name.utf8))
buffer.replaceSubrange(32..<packageSizeEx, with: field)
}
// MARK: - Little-endian access
private func loadUInt32(_ offset: Int) -> UInt32 {
UInt32(buffer[offset]) | (UInt32(buffer[offset + 1]) << 8)
| (UInt32(buffer[offset + 2]) << 16) | (UInt32(buffer[offset + 3]) << 24)
}
private func loadInt32(_ offset: Int) -> Int32 { Int32(bitPattern: loadUInt32(offset)) }
private func loadUInt64(_ offset: Int) -> UInt64 {
UInt64(loadUInt32(offset)) | (UInt64(loadUInt32(offset + 4)) << 32)
}
private mutating func store(_ value: UInt32, at offset: Int) {
buffer[offset] = UInt8(truncatingIfNeeded: value)
buffer[offset + 1] = UInt8(truncatingIfNeeded: value >> 8)
buffer[offset + 2] = UInt8(truncatingIfNeeded: value >> 16)
buffer[offset + 3] = UInt8(truncatingIfNeeded: value >> 24)
}
private mutating func store(_ value: UInt64, at offset: Int) {
store(UInt32(truncatingIfNeeded: value), at: offset)
store(UInt32(truncatingIfNeeded: value >> 32), at: offset + 4)
}
}
/// Characters stripped from both ends of a decoded machine name: the space
/// Windows pads with (`DATA.cs:88`) plus NUL from a zero-filled field.
private let machineNameTrimSet = CharacterSet.whitespacesAndNewlines.union(
CharacterSet(charactersIn: "\0"))