// The three framing bytes Mouse Without Borders writes over the top of the // package type: a one-byte checksum and the top 16 bits of the magic number. // See docs/protocol.md ยง1.3. // // Ported from App/Class/SocketStuff.cs TcpSendData (497-529) and // ProcessReceivedDataEx (531-556). import Foundation /// Sealing and opening the bytes 1..3 that carry the checksum and magic. /// /// There is no MAC anywhere in this protocol: framing plus the shared-key /// cipher stream is all that distinguishes a real packet from noise, which is /// why every caller must treat an `.invalid` packet as hostile. public enum Framing { /// The packet's wire bytes with byte 1 set to the checksum and bytes 2..3 /// to the magic number's top 16 bits (`SocketStuff.cs:509-519`). /// /// The checksum is a plain 8-bit sum of bytes 2..31 **only**, even for a /// 64-byte packet (`SocketStuff.cs:512-516`): the machine-name half is /// covered by the cipher, not by the checksum. public static func seal(_ packet: Packet, magic: UInt32) -> Data { var bytes = [UInt8](packet.bytes) // always 32 or 64, Packet.bytes bytes[3] = UInt8(truncatingIfNeeded: (magic >> 24) & 0xFF) // SocketStuff.cs:509 bytes[2] = UInt8(truncatingIfNeeded: (magic >> 16) & 0xFF) // SocketStuff.cs:510 bytes[1] = 0 // SocketStuff.cs:511 bytes[1] = checksum(of: bytes) return Data(bytes) } /// The packet carried by `bytes`, or a packet of type `.invalid` if the /// magic or the checksum does not match (`SocketStuff.cs:531-556`). /// /// Bytes 1..3 are zeroed before the packet is built, exactly as /// `ProcessReceivedDataEx` does (`SocketStuff.cs:553`), which is what makes /// the package type effectively one byte wide. Validation reads bytes /// 2..31 only, so it is the same whether the caller passes the first 32 /// bytes or all 64. A receiver therefore does what Windows does /// (`SocketStuff.cs:578-600`): open the first 32 bytes, and if /// `type.isBig`, read 32 more and open the concatenation. public static func open(_ bytes: Data, magic: UInt32) -> Packet { guard bytes.count == packageSize || bytes.count == packageSizeEx else { return Packet(type: .invalid) } var buf = [UInt8](bytes) // Only the top 16 bits of the magic number are ever transmitted // (SocketStuff.cs:537, 539). let received = (UInt32(buf[3]) << 24) | (UInt32(buf[2]) << 16) var valid = received == (magic & 0xFFFF_0000) if buf[1] != checksum(of: buf) { // SocketStuff.cs:545-551 valid = false } buf[1] = 0 buf[2] = 0 buf[3] = 0 // SocketStuff.cs:553 if !valid { buf[0] = PackageType.invalid.rawValue // SocketStuff.cs:542, 550 } return Packet(bytes: Data(buf)) ?? Packet(type: .invalid) } /// 8-bit wrapping sum of bytes 2..31 (`SocketStuff.cs:512-516`). private static func checksum(of bytes: [UInt8]) -> UInt8 { var sum: UInt8 = 0 for i in 2..